Merge branch 'main' into worktree-agent-a3f604d3c8055fe6e

This commit is contained in:
Ludovic Marie
2026-10-10 08:15:00 +02:00
80 changed files with 13221 additions and 82 deletions
Generated
+1
View File
@@ -672,6 +672,7 @@ name = "horizon-assets"
version = "0.1.0"
dependencies = [
"horizon-core",
"png",
"serde",
"serde_json",
]
+3
View File
@@ -13,3 +13,6 @@ serde_json = { version = "1.0.151", features = ["raw_value"] }
[lints]
workspace = true
[dev-dependencies]
png = "0.18"
@@ -0,0 +1,356 @@
//! Resolve item stacks into render layers for the differential harness
//! `tools/test_item_model_parity.py`.
use horizon_assets::{
animation::AnimationMetadata,
item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model},
item_model::*,
math::Mat4,
model::{CuboidModel, Direction},
resolve::{MISSING_MODEL, ModelLibrary},
};
use serde_json::{Value, json};
use std::{
cell::RefCell,
collections::BTreeMap,
fs::{self, File},
io::{BufRead, BufReader, BufWriter, Write},
path::{Path, PathBuf},
};
fn bits(v: f32) -> u32 {
if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }
}
struct Sprites {
root: PathBuf,
cache: RefCell<BTreeMap<String, Option<SpriteMask>>>,
}
impl SpriteLookup for Sprites {
fn mask(&self, sprite: &str) -> Option<SpriteMask> {
if let Some(hit) = self.cache.borrow().get(sprite) {
return hit.clone();
}
let mask = self.load(sprite);
self.cache
.borrow_mut()
.insert(sprite.to_owned(), mask.clone());
mask
}
}
impl Sprites {
fn load(&self, sprite: &str) -> Option<SpriteMask> {
let (namespace, path) = sprite.split_once(':')?;
let png = self
.root
.join(format!("assets/{namespace}/textures/{path}.png"));
let mut decoder = png::Decoder::new(BufReader::new(File::open(&png).ok()?));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
let mut bytes = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut bytes).ok()?;
let channels = info.color_type.samples();
let alpha = |pixel: &[u8]| match info.color_type {
png::ColorType::Rgba => pixel[3],
png::ColorType::GrayscaleAlpha => pixel[1],
_ => 255,
};
let (iw, ih) = (info.width as usize, info.height as usize);
let pixels: Vec<u8> = bytes[..info.buffer_size()]
.chunks_exact(channels)
.map(alpha)
.collect();
let meta = fs::read_to_string(png.with_extension("png.mcmeta")).ok();
let animation = meta
.and_then(|m| serde_json::from_str::<Value>(&m).ok())
.and_then(|m| m.get("animation").map(|a| a.to_string()))
.and_then(|a| AnimationMetadata::from_json(&a).ok());
let (w, h) = match &animation {
Some(a) => {
let [w, h] = a.frame_size(iw as i32, ih as i32);
(w as usize, h as usize)
}
None => (iw, ih),
};
let columns = iw / w;
let total = columns * (ih / h);
let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten());
let frame_indices: Vec<usize> = match clip {
Some(clip) => {
let mut unique = Vec::new();
for (index, _) in clip.sequence() {
if !unique.contains(&(*index as usize)) {
unique.push(*index as usize);
}
}
unique
}
None => vec![0],
};
let frames = frame_indices
.into_iter()
.map(|f| {
let (fx, fy) = (f % columns * w, f / columns * h);
(0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.map(|(x, y)| pixels[(fy + y) * iw + fx + x] == 0)
.collect()
})
.collect();
Some(SpriteMask {
width: w,
height: h,
frames,
})
}
}
struct Env {
grass: Vec<i32>,
local_time: String,
bundle_weight: bool,
prototypes: BTreeMap<String, Components>,
}
impl ItemEnv for Env {
fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
let rain = downfall * temperature;
let x = ((1.0 - temperature) * 255.0) as i64;
let y = ((1.0 - rain) * 255.0) as i64;
let index = (y << 8 | x) as usize;
self.grass.get(index).copied().unwrap_or(-65281)
}
fn local_time(&self, _: &str, _: &str, _: Option<&str>) -> String {
self.local_time.clone()
}
fn bundle_fullness(&self, stack: &StackView, components: &Components) -> f32 {
// Sum of count / max stack size over the contents, as a double fraction.
let Some(items) = components
.get("minecraft:bundle_contents")
.and_then(Value::as_array)
else {
return 0.0;
};
let _ = (stack, self.bundle_weight);
let mut total = 0.0f64;
for item in items {
let id = item["id"].as_str().unwrap_or("");
let count = item["count"].as_i64().unwrap_or(1) as f64;
let max = self
.prototypes
.get(id)
.and_then(|c| c.get("minecraft:max_stack_size"))
.and_then(Value::as_i64)
.unwrap_or(1) as f64;
total += count / max;
}
total as f32
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let root = PathBuf::from(&args[1]);
let prototypes_path = &args[2];
let mut output = BufWriter::new(File::create(&args[4])?);
let raw: BTreeMap<String, Components> = serde_json::from_slice(&fs::read(prototypes_path)?)?;
let mut models = ItemModels {
prototypes: raw,
..Default::default()
};
writeln!(
output,
"{}",
json!({"row":"components","names":DATA_COMPONENT_TYPES.to_vec()})
)?;
let items_dir = root.join("assets/minecraft/items");
let mut files: Vec<_> = fs::read_dir(&items_dir)?.collect::<Result<_, _>>()?;
files.sort_by_key(|f| f.file_name());
for file in files {
let name = file.file_name().to_string_lossy().into_owned();
let id = format!("minecraft:{}", name.trim_end_matches(".json"));
let ok = match ClientItem::from_json(&fs::read_to_string(file.path())?) {
Ok(item) => {
models.definitions.insert(id, item);
true
}
Err(_) => false,
};
writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?;
}
for line in BufReader::new(File::open(format!("{}.definitions", args[3]))?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let name = row["name"].as_str().unwrap();
let ok = match ClientItem::from_json(row["json"].as_str().unwrap()) {
Ok(item) => {
models
.definitions
.insert(horizon_assets::item_model::identifier(name)?, item);
true
}
Err(_) => false,
};
writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?;
}
let mut cuboids = BTreeMap::new();
let models_dir = root.join("assets/minecraft/models");
let mut stack = vec![models_dir.clone()];
while let Some(dir) = stack.pop() {
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
if path.is_dir() {
stack.push(path);
} else if path.extension().is_some_and(|e| e == "json") {
let relative = path.strip_prefix(&models_dir)?.with_extension("");
let id = format!(
"minecraft:{}",
relative.to_string_lossy().replace('\\', "/")
);
if let Ok(model) = CuboidModel::from_json(&fs::read_to_string(&path)?) {
cuboids.insert(id, model);
}
}
}
}
let library = ModelLibrary::with_item_generator(cuboids)?;
let sprites = Sprites {
root: root.clone(),
cache: RefCell::default(),
};
let grass = {
let mut decoder = png::Decoder::new(BufReader::new(File::open(
root.join("assets/minecraft/textures/colormap/grass.png"),
)?));
decoder.set_transformations(png::Transformations::EXPAND);
let mut reader = decoder.read_info()?;
let mut bytes = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut bytes)?;
let channels = info.color_type.samples();
bytes[..info.buffer_size()]
.chunks_exact(channels)
.map(|p| {
let a = if channels == 4 { p[3] } else { 255 };
i32::from_be_bytes([a, p[0], p[1], p[2]])
})
.collect()
};
let mut env = Env {
grass,
local_time: String::new(),
bundle_weight: true,
prototypes: models.prototypes.clone(),
};
let mut baked_cache: BTreeMap<String, BakedItemModel> = BTreeMap::new();
let mut bake = |name: &str| -> BakedItemModel {
baked_cache
.entry(name.to_owned())
.or_insert_with(|| {
bake_item_model(&library, &sprites, name)
.or_else(|_| bake_item_model(&library, &sprites, MISSING_MODEL))
.expect("missing model bakes")
})
.clone()
};
for line in BufReader::new(File::open(&args[3])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let id = row["id"].as_str().unwrap();
let mut stack = StackView::new(
row["item"].as_str().unwrap(),
row["count"].as_i64().unwrap() as i32,
);
if let Some(components) = row["components"].as_object() {
for (key, value) in components {
match key.strip_prefix('!') {
Some(removed) => stack.patch.insert(removed.to_owned(), None),
None => stack.patch.insert(key.clone(), Some(value.clone())),
};
}
}
stack.bundle_selected = row["bundle_selected"].as_i64().unwrap_or(-1) as i32;
env.local_time = row["local_time"].as_str().unwrap_or("").to_owned();
let context = DisplayContext::by_name(row["context"].as_str().unwrap()).unwrap();
let owner = row["owner"].as_object().map(|o| {
let derived = &row["derived"];
OwnerState {
entity_type: o["entity_type"].as_str().unwrap().to_owned(),
main_arm_left: o["main_arm"] == "left",
using_this_item: o["using"].as_bool().unwrap(),
use_item_remaining_ticks: o["remaining"].as_i64().unwrap() as i32,
use_duration: derived["use_duration"].as_i64().unwrap_or(0) as i32,
crossbow_charge_duration: derived["charge_duration"].as_i64().unwrap_or(0) as i32,
..Default::default()
}
});
let level = row["dimension"].as_str().map(|d| LevelState {
dimension: d.to_owned(),
..Default::default()
});
let ctx = Context {
display: context,
owner: owner.as_ref(),
level: level.as_ref(),
seed: row["seed"].as_i64().unwrap_or(0) as i32,
};
let resolved = models.resolve(&stack, &ctx, &env);
let mut layers = Vec::new();
for layer in &resolved.layers {
let (kind, baked, extra) = match &layer.content {
LayerContent::Model { model } => ("model", bake(model), json!({})),
LayerContent::Missing => ("model", bake(MISSING_MODEL), json!({})),
LayerContent::Special {
base,
model,
argument,
} => (
"special",
bake(base),
json!({"special":model.to_json(),"argument":argument}),
),
};
let matrix: Mat4 = baked.layer_matrix(context, &layer.transform);
let mut value = json!({
"kind":kind,
"tints":layer.tints,
"foil":match layer.foil { FoilType::None=>"none", FoilType::Standard=>"standard", FoilType::Special=>"special" },
"matrix":matrix.rows().iter().flatten().map(|v| bits(*v)).collect::<Vec<_>>(),
"uses_block_light":baked.uses_block_light,
"particle":baked.particle.sprite,
"has_transform":baked.transform(context).is_some(),
});
if kind == "model" {
value["quads"] = Value::Array(
baked
.quads
.iter()
.map(|q| {
json!({
"positions":q.positions.map(|v| v.map(bits)),
"uv":q.uv.map(|v| v.map(bits)),
"facing":q.facing.name(),
"tint":q.tint_index,
"sprite":q.material.sprite,
"shade":q.shade_direction_override.map(Direction::name),
"light":q.light_emission,
})
})
.collect(),
);
}
if let (Some(target), Some(source)) = (value.as_object_mut(), extra.as_object()) {
for (k, v) in source {
target.insert(k.clone(), v.clone());
}
}
layers.push(value);
}
writeln!(
output,
"{}",
json!({"row":"case","id":id,"layers":layers,"oversized":resolved.oversized_in_gui,
"swap":{"play":models.hand_animation_on_swap(&stack),"scale":bits(models.swap_animation_scale(&stack))}})
)?;
}
let _ = Path::new("");
Ok(())
}
+34
View File
@@ -213,6 +213,40 @@ fn bake_elements(
}
Ok(output)
}
/// `FaceBakery.bakeQuad` for a quad with explicit corners and unit-atlas UVs
/// (`uv` in 0..16 texels), as `ItemModelGenerator` builds its layers.
pub fn bake_flat_face(
from: [f32; 3],
to: [f32; 3],
uv: [f32; 4],
direction: Direction,
material: Material,
tint_index: i32,
) -> Result<ModelQuad> {
let element = Element {
from,
to,
faces: Default::default(),
rotation: None,
shade_direction_override: None,
light_emission: 0,
};
let face = Face {
cull: None,
tint_index,
texture: String::new(),
uv: Some(uv),
rotation: 0,
};
bake_face(
&element,
&face,
direction,
None,
material,
BlockModelTransform::new([0; 3], false),
)
}
fn bake_face(
element: &Element,
face: &Face,
+300
View File
@@ -0,0 +1,300 @@
//! Baking of item models: a cuboid model's quads, or the layer extrusion of
//! `builtin/generated` (`ItemModelGenerator`), with the display transforms
//! and render properties a `CuboidItemModelWrapper` keeps.
use crate::{
bake::{ModelQuad, bake_block_model, bake_flat_face},
item_model::DisplayContext,
json::Result,
math::{Mat4, quaternion_xyz},
model::{Direction, DisplayTransform, GuiLight, ItemTransform, Material},
resolve::ModelLibrary,
};
use std::{collections::BTreeSet, f32::consts::PI};
pub const MISSING_SPRITE: &str = "minecraft:missingno";
/// The alpha of every unique animation frame of a sprite.
#[derive(Clone, Debug, PartialEq)]
pub struct SpriteMask {
pub width: usize,
pub height: usize,
/// `frames[f][y * width + x]` is true for alpha 0.
pub frames: Vec<Vec<bool>>,
}
impl SpriteMask {
pub fn opaque(width: usize, height: usize) -> Self {
Self {
width,
height,
frames: vec![vec![false; width * height]],
}
}
fn transparent(&self, frame: usize, x: i64, y: i64) -> bool {
if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
return true;
}
self.frames[frame][y as usize * self.width + x as usize]
}
}
/// The sprites of the item and block atlases.
pub trait SpriteLookup {
/// `None` when the sprite is in neither atlas (the missing sprite stands in).
fn mask(&self, sprite: &str) -> Option<SpriteMask>;
}
#[derive(Clone, Debug)]
pub struct BakedItemModel {
/// `QuadCollection.getAll`: unculled quads, then north, south, east,
/// west, up and down.
pub quads: Vec<ModelQuad>,
/// `gui_light: side`.
pub uses_block_light: bool,
pub particle: Material,
/// By [`crate::model::DISPLAY_CONTEXTS`]; `None` is `NO_TRANSFORM`.
pub transforms: [Option<ItemTransform>; 9],
}
fn context_index(context: DisplayContext) -> Option<usize> {
Some(match context {
DisplayContext::None => return None,
DisplayContext::ThirdPersonLeftHand => 0,
DisplayContext::ThirdPersonRightHand => 1,
DisplayContext::FirstPersonLeftHand => 2,
DisplayContext::FirstPersonRightHand => 3,
DisplayContext::Head => 4,
DisplayContext::Gui => 5,
DisplayContext::Ground => 6,
DisplayContext::Fixed => 7,
DisplayContext::OnShelf => 8,
})
}
impl BakedItemModel {
/// `ItemTransforms.getTransform`.
pub fn transform(&self, context: DisplayContext) -> Option<&ItemTransform> {
context_index(context).and_then(|i| self.transforms[i].as_ref())
}
/// `LayerRenderState.applyTransform`: the display transform followed by
/// the item model's own local transformation.
pub fn layer_matrix(&self, context: DisplayContext, local: &Mat4) -> Mat4 {
item_transform_matrix(self.transform(context), context.left_hand()).mul(local)
}
}
/// `ItemTransform.apply` on an identity pose.
pub fn item_transform_matrix(transform: Option<&ItemTransform>, left_hand: bool) -> Mat4 {
let Some(t) = transform else {
return Mat4::IDENTITY.translate([-0.5, -0.5, -0.5]);
};
let (tx, ry, rz) = if left_hand {
(-t.translation[0], -t.rotation[1], -t.rotation[2])
} else {
(t.translation[0], t.rotation[1], t.rotation[2])
};
let radians = PI / 180.0;
Mat4::IDENTITY
.translate([tx, t.translation[1], t.translation[2]])
.rotate(quaternion_xyz(
t.rotation[0] * radians,
ry * radians,
rz * radians,
))
.scale(t.scale)
.translate([-0.5, -0.5, -0.5])
}
/// Bake the top geometry of `name` the way `CuboidItemModelWrapper` does.
pub fn bake_item_model(
library: &ModelLibrary,
sprites: &dyn SpriteLookup,
name: &str,
) -> Result<BakedItemModel> {
let model = library
.resolve(name)
.or_else(|_| library.resolve(crate::resolve::MISSING_MODEL))?;
let known = |sprite: &str| sprite == MISSING_SPRITE || sprites.mask(sprite).is_some();
let material = |m: &Material| {
if known(&m.sprite) {
m.clone()
} else {
Material {
sprite: MISSING_SPRITE.to_owned(),
force_translucent: m.force_translucent,
}
}
};
let quads = if model.uses_item_generator() {
let mut quads = Vec::new();
for (layer, slot) in ["layer0", "layer1", "layer2", "layer3", "layer4"]
.into_iter()
.enumerate()
{
let Some(m) = model.material(slot)? else {
break;
};
let m = material(m);
let mask = if m.sprite == MISSING_SPRITE {
SpriteMask::opaque(16, 16)
} else {
sprites
.mask(&m.sprite)
.unwrap_or_else(|| SpriteMask::opaque(16, 16))
};
quads.extend(extrude_layer(&mask, &m, layer as i32)?);
}
quads
} else {
let mut quads =
bake_block_model(&model, crate::bake::BlockModelTransform::new([0; 3], false))?;
for q in &mut quads {
q.material = material(&q.material);
}
// `QuadCollection.Builder.build`: unculled, then each culled direction.
let mut ordered: Vec<ModelQuad> =
quads.iter().filter(|q| q.cull.is_none()).cloned().collect();
for side in [
Direction::North,
Direction::South,
Direction::East,
Direction::West,
Direction::Up,
Direction::Down,
] {
ordered.extend(quads.iter().filter(|q| q.cull == Some(side)).cloned());
}
ordered
};
// `resolveParticleMaterial`: a missing `particle` slot is the missing sprite.
let particle = model.material("particle")?.map_or_else(
|| Material {
sprite: MISSING_SPRITE.to_owned(),
force_translucent: false,
},
material,
);
let transforms = std::array::from_fn(|i| match &model.display.contexts[i] {
DisplayTransform::Explicit(Some(t)) => Some(t.clone()),
_ => None,
});
Ok(BakedItemModel {
quads,
uses_block_light: model.gui_light == GuiLight::Side,
particle,
transforms,
})
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Side {
Up,
Down,
Left,
Right,
}
impl Side {
fn step(self) -> (i64, i64) {
match self {
Self::Up => (0, 1),
Self::Down => (0, -1),
Self::Left => (1, 0),
Self::Right => (-1, 0),
}
}
fn direction(self) -> Direction {
match self {
Self::Up => Direction::Up,
Self::Down => Direction::Down,
Self::Left => Direction::East,
Self::Right => Direction::West,
}
}
}
/// `ItemModelGenerator.bakeExtrudedSprite` for one layer: the front and back
/// faces and one thin face per opaque/transparent pixel edge. The native
/// client collects the sides in a hash set, so their order is unspecified;
/// they are emitted sorted by pixel here.
fn extrude_layer(mask: &SpriteMask, material: &Material, layer: i32) -> Result<Vec<ModelQuad>> {
let from = [0.0, 0.0, 7.5];
let to = [16.0, 16.0, 8.5];
let mut quads = vec![
bake_flat_face(
from,
to,
[0.0, 0.0, 16.0, 16.0],
Direction::South,
material.clone(),
layer,
)?,
bake_flat_face(
from,
to,
[16.0, 0.0, 0.0, 16.0],
Direction::North,
material.clone(),
layer,
)?,
];
let (width, height) = (mask.width as i64, mask.height as i64);
let mut faces = BTreeSet::new();
for frame in 0..mask.frames.len() {
for y in 0..height {
for x in 0..width {
if mask.transparent(frame, x, y) {
continue;
}
for side in [Side::Up, Side::Down, Side::Left, Side::Right] {
let (sx, sy) = side.step();
if mask.transparent(frame, x - sx, y - sy) {
faces.insert((y, x, side));
}
}
}
}
}
let x_scale = 16.0 / mask.width as f32;
let y_scale = 16.0 / mask.height as f32;
for (y, x, side) in faces {
let (x, y) = (x as f32, y as f32);
let u0 = x + 0.1;
let u1 = x + 1.0 - 0.1;
let (v0, v1) = if matches!(side, Side::Up | Side::Down) {
(y + 0.1, y + 1.0 - 0.1)
} else {
(y + 1.0 - 0.1, y + 0.1)
};
let (mut start_x, mut start_y, mut end_x, mut end_y) = (x, y, x, y);
match side {
Side::Up => end_x += 1.0,
Side::Down => {
end_x += 1.0;
start_y += 1.0;
end_y += 1.0;
}
Side::Left => end_y += 1.0,
Side::Right => {
start_x += 1.0;
end_x += 1.0;
end_y += 1.0;
}
}
start_x *= x_scale;
end_x *= x_scale;
start_y *= y_scale;
end_y *= y_scale;
start_y = 16.0 - start_y;
end_y = 16.0 - end_y;
let (from, to) = match side {
Side::Up => ([start_x, start_y, 7.5], [end_x, start_y, 8.5]),
Side::Down => ([start_x, end_y, 7.5], [end_x, end_y, 8.5]),
Side::Left => ([start_x, start_y, 7.5], [start_x, end_y, 8.5]),
Side::Right => ([end_x, start_y, 7.5], [end_x, end_y, 8.5]),
};
quads.push(bake_flat_face(
from,
to,
[u0 * x_scale, v0 * y_scale, u1 * x_scale, v1 * y_scale],
side.direction(),
material.clone(),
layer,
)?);
}
Ok(quads)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,254 @@
//! `special` item models: the block-entity style renderers an item can ask
//! for (`SpecialModelRenderers`), their codec fields and what each reads from
//! the stack (`extractArgument`).
use super::{Result, float, get, ident, object, required, string};
use crate::json::error as err;
use serde_json::{Map, Value, json};
#[derive(Clone, Debug, PartialEq)]
pub enum SpecialKind {
Bell,
Banner {
color: String,
wall: bool,
},
Book {
open_angle: f32,
page1: f32,
page2: f32,
},
Conduit,
Chest {
texture: String,
openness: f32,
chest_type: String,
},
CopperGolemStatue {
texture: String,
pose: String,
},
DecoratedPot,
EndCube {
effect: String,
},
Head {
kind: String,
texture: Option<String>,
animation: f32,
},
PlayerHead,
ShulkerBox {
texture: String,
openness: f32,
},
Shield,
Trident,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpecialModel {
pub kind: SpecialKind,
}
const DYES: [&str; 16] = [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black",
];
fn one_of(v: &Value, names: &[&str]) -> Result<String> {
let s = string(v)?;
if names.contains(&s.as_str()) {
Ok(s)
} else {
Err(err("invalid enum name"))
}
}
impl SpecialModel {
pub fn decode(v: &Value) -> Result<Self> {
let m = object(v)?;
let float_or = |key: &str, default: f32| get(m, key).map_or(Ok(default), float);
let kind = match ident(required(m, "type")?)?.as_str() {
"minecraft:bell" => SpecialKind::Bell,
"minecraft:banner" => SpecialKind::Banner {
color: one_of(required(m, "color")?, &DYES)?,
wall: match get(m, "attachment") {
None => false,
Some(a) => one_of(a, &["wall", "ground"])? == "wall",
},
},
"minecraft:book" => SpecialKind::Book {
open_angle: float(required(m, "open_angle")?)?,
page1: float(required(m, "page1")?)?,
page2: float(required(m, "page2")?)?,
},
"minecraft:conduit" => SpecialKind::Conduit,
"minecraft:chest" => SpecialKind::Chest {
texture: ident(required(m, "texture")?)?,
openness: float_or("openness", 0.0)?,
chest_type: match get(m, "chest_type") {
None => "single".to_owned(),
Some(t) => one_of(t, &["single", "left", "right"])?,
},
},
"minecraft:copper_golem_statue" => SpecialKind::CopperGolemStatue {
texture: ident(required(m, "texture")?)?,
pose: one_of(
required(m, "pose")?,
&["standing", "sitting", "running", "star"],
)?,
},
"minecraft:decorated_pot" => SpecialKind::DecoratedPot,
"minecraft:end_cube" => SpecialKind::EndCube {
effect: one_of(required(m, "effect")?, &["portal", "gateway"])?,
},
"minecraft:head" => SpecialKind::Head {
kind: one_of(
required(m, "kind")?,
&[
"skeleton",
"wither_skeleton",
"player",
"zombie",
"creeper",
"piglin",
"dragon",
],
)?,
texture: get(m, "texture").map(ident).transpose()?,
animation: float_or("animation", 0.0)?,
},
"minecraft:player_head" => SpecialKind::PlayerHead,
"minecraft:shulker_box" => SpecialKind::ShulkerBox {
texture: ident(required(m, "texture")?)?,
openness: float_or("openness", 0.0)?,
},
"minecraft:shield" => SpecialKind::Shield,
"minecraft:trident" => SpecialKind::Trident,
_ => return Err(err("unknown special model type")),
};
Ok(Self { kind })
}
/// The codec's encoding: optional fields equal to their default are omitted.
pub fn to_json(&self) -> Value {
let mut m = Map::new();
let mut put = |k: &str, v: Value| {
m.insert(k.to_owned(), v);
};
let ty = match &self.kind {
SpecialKind::Bell => "bell",
SpecialKind::Banner { color, wall } => {
put("color", json!(color));
if *wall {
put("attachment", json!("wall"));
}
"banner"
}
SpecialKind::Book {
open_angle,
page1,
page2,
} => {
put("open_angle", json!(open_angle));
put("page1", json!(page1));
put("page2", json!(page2));
"book"
}
SpecialKind::Conduit => "conduit",
SpecialKind::Chest {
texture,
openness,
chest_type,
} => {
put("texture", json!(texture));
if *openness != 0.0 {
put("openness", json!(openness));
}
if chest_type != "single" {
put("chest_type", json!(chest_type));
}
"chest"
}
SpecialKind::CopperGolemStatue { texture, pose } => {
put("texture", json!(texture));
put("pose", json!(pose));
"copper_golem_statue"
}
SpecialKind::DecoratedPot => "decorated_pot",
SpecialKind::EndCube { effect } => {
put("effect", json!(effect));
"end_cube"
}
SpecialKind::Head {
kind,
texture,
animation,
} => {
put("kind", json!(kind));
if let Some(t) = texture {
put("texture", json!(t));
}
if *animation != 0.0 {
put("animation", json!(animation));
}
"head"
}
SpecialKind::PlayerHead => "player_head",
SpecialKind::ShulkerBox { texture, openness } => {
if texture != "minecraft:shulker" {
put("texture", json!(texture));
}
if *openness != 0.0 {
put("openness", json!(openness));
}
"shulker_box"
}
SpecialKind::Shield => "shield",
SpecialKind::Trident => "trident",
};
m.insert("type".to_owned(), json!(format!("minecraft:{ty}")));
Value::Object(m)
}
pub fn type_name(&self) -> String {
self.to_json()["type"]
.as_str()
.unwrap_or_default()
.to_owned()
}
/// What `extractArgument` reads: banners their pattern layers, shields
/// their base colour and layers, decorated pots their sherds and player
/// heads their profile. Absent components give `null`.
pub fn argument(&self, component: &dyn Fn(&str) -> Option<Value>) -> Value {
match &self.kind {
SpecialKind::Banner { .. } => {
component("minecraft:banner_patterns").unwrap_or(Value::Null)
}
SpecialKind::DecoratedPot => {
component("minecraft:pot_decorations").unwrap_or(Value::Null)
}
SpecialKind::PlayerHead => component("minecraft:profile").unwrap_or(Value::Null),
SpecialKind::Shield => {
let mut m = Map::new();
for key in ["minecraft:banner_patterns", "minecraft:base_color"] {
if let Some(v) = component(key) {
m.insert(key.to_owned(), v);
}
}
Value::Object(m)
}
_ => Value::Null,
}
}
}
@@ -0,0 +1,20 @@
use super::*;
#[test]
fn identifier_adds_default_namespace() {
assert_eq!(identifier("stone").unwrap(), "minecraft:stone");
assert_eq!(identifier("a:b").unwrap(), "a:b");
}
#[test]
fn positive_modulo_wraps_negatives() {
assert!((positive_modulo(-0.25, 1.0) - 0.75).abs() < 1e-6);
assert!((positive_modulo(1.5, 1.0) - 0.5).abs() < 1e-6);
}
#[test]
fn display_context_names_round_trip() {
for name in ["gui", "ground", "fixed", "head"] {
assert_eq!(DisplayContext::by_name(name).unwrap().name(), name);
}
}
+3
View File
@@ -4,7 +4,10 @@
pub mod animation;
pub mod bake;
pub mod blockstate;
pub mod item_bake;
pub mod item_model;
mod json;
pub mod math;
pub mod model;
pub mod resolve;
+140
View File
@@ -0,0 +1,140 @@
//! Column-major `Matrix4f` arithmetic with the operand order of JOML's
//! default (non-FMA) code paths, for composing item-model transformations.
/// A JOML `Matrix4f`: `m[column][row]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mat4(pub [[f32; 4]; 4]);
impl Mat4 {
pub const IDENTITY: Self = Self([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]);
/// `Matrix4f.translation(x, y, z)`.
pub fn translation(t: [f32; 3]) -> Self {
let mut m = Self::IDENTITY;
m.0[3][..3].copy_from_slice(&t);
m
}
/// `ExtraCodecs.MATRIX4F`: sixteen values in row-major order.
pub fn from_row_major(values: [f32; 16]) -> Self {
let mut m = Self([[0.0; 4]; 4]);
for (i, v) in values.into_iter().enumerate() {
m.0[i & 3][i >> 2] = v;
}
m
}
/// The matrix as `[row][column]` entries, the order `getRowColumn` reads.
pub fn rows(&self) -> [[f32; 4]; 4] {
std::array::from_fn(|r| std::array::from_fn(|c| self.0[c][r]))
}
/// `this * right` (`Matrix4f.mul`).
pub fn mul(&self, right: &Self) -> Self {
let (m, r) = (&self.0, &right.0);
let mut out = [[0.0; 4]; 4];
for c in 0..4 {
for row in 0..4 {
out[c][row] = m[0][row] * r[c][0]
+ m[1][row] * r[c][1]
+ m[2][row] * r[c][2]
+ m[3][row] * r[c][3];
}
}
Self(out)
}
/// `Matrix4f.translate(x, y, z)` (`translateGeneric`).
pub fn translate(&self, t: [f32; 3]) -> Self {
let mut out = *self;
for row in 0..4 {
out.0[3][row] = self.0[0][row] * t[0]
+ (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row]));
}
out
}
/// `Matrix4f.scale(x, y, z)`: the first three columns are scaled.
pub fn scale(&self, s: [f32; 3]) -> Self {
let mut out = *self;
for c in 0..3 {
for row in 0..4 {
out.0[c][row] = self.0[c][row] * s[c];
}
}
out
}
/// `Matrix4f.rotate(Quaternionfc)` (`rotateGeneric`).
pub fn rotate(&self, q: [f32; 4]) -> Self {
let [x, y, z, w] = q;
let (w2, x2, y2, z2) = (w * w, x * x, y * y, z * z);
let (zw, xy, xz, yw, yz, xw) = (z * w, x * y, x * z, y * w, y * z, x * w);
let (dzw, dxy, dxz, dyw, dyz, dxw) = (zw + zw, xy + xy, xz + xz, yw + yw, yz + yz, xw + xw);
let r = [
[w2 + x2 - z2 - y2, dxy + dzw, dxz - dyw],
[dxy - dzw, y2 - z2 + w2 - x2, dyz + dxw],
[dyw + dxz, dyz - dxw, z2 - y2 - x2 + w2],
];
let m = &self.0;
let mut out = *self;
for c in 0..3 {
for row in 0..4 {
out.0[c][row] = m[0][row] * r[c][0] + m[1][row] * r[c][1] + m[2][row] * r[c][2];
}
}
out
}
pub fn is_finite(&self) -> bool {
self.0.iter().flatten().all(|v| v.is_finite())
}
}
/// `Quaternionf.normalize` as the codec applies it to four components.
pub fn normalize_quaternion(q: [f32; 4]) -> [f32; 4] {
let [x, y, z, w] = q;
let inv = 1.0 / (x * x + (y * y + (z * z + w * w))).sqrt();
[x * inv, y * inv, z * inv, w * inv]
}
/// `Quaternionf.rotationXYZ` from angles in radians.
pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] {
let half = |a: f32| -> (f32, f32) {
let h = a * 0.5;
((f64::from(h).sin()) as f32, (f64::from(h).cos()) as f32)
};
let ((sx, cx), (sy, cy), (sz, cz)) = (half(x), half(y), half(z));
let (cx_cy, sx_cy, cx_sy, sx_sy) = (cx * cy, sx * cy, cx * sy, sx * sy);
[
sx_cy * cz + cx_sy * sz,
cx_sy * cz - sx_cy * sz,
cx_cy * sz + sx_sy * cz,
cx_cy * cz - sx_sy * sz,
]
}
/// `new Quaternionf(new AxisAngle4f(angle, axis))`.
pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] {
let half = angle * 0.5;
let (sin, cos) = (half.sin(), half.cos());
let norm = 1.0 / (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
let s = sin * norm;
[axis[0] * s, axis[1] * s, axis[2] * s, cos]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn composes_in_joml_order() {
let t = Mat4::translation([1.0, 2.0, 3.0]);
let s = Mat4::IDENTITY.scale([2.0, -1.0, 1.0]);
let m = t.mul(&s);
assert_eq!(m.0[0][0], 2.0);
assert_eq!(m.0[1][1], -1.0);
assert_eq!(m.0[3][..3], [1.0, 2.0, 3.0]);
assert_eq!(s.mul(&t).0[3][..3], [2.0, -2.0, 3.0]);
}
#[test]
fn quarter_turn_about_z_rotates_x_into_y() {
let q = quaternion_from_axis_angle(std::f32::consts::FRAC_PI_2, [0.0, 0.0, 1.0]);
let m = Mat4::IDENTITY.rotate(q);
assert!((m.0[0][1] - 1.0).abs() < 1e-6 && m.0[0][0].abs() < 1e-6);
}
}
+35
View File
@@ -6,6 +6,8 @@ use std::{
};
pub const MISSING_MODEL: &str = "minecraft:builtin/missing";
/// `ItemModelGenerator.GENERATED_ITEM_MODEL_ID`.
pub const GENERATED_MODEL: &str = "minecraft:builtin/generated";
/// Decoded models are immutable and their inherited geometry is shared.
pub struct ModelLibrary {
@@ -21,8 +23,14 @@ pub struct ResolvedCuboidModel {
/// Cyclic and dangling aliases are absent from `textures`.
pub unresolved_textures: BTreeSet<String>,
geometry: Option<Arc<CuboidModel>>,
generated: bool,
}
impl ResolvedCuboidModel {
/// Whether the top geometry is `builtin/generated`'s layer extrusion
/// (no model closer to the leaf has elements of its own).
pub fn uses_item_generator(&self) -> bool {
self.generated
}
pub fn elements(&self) -> &[Option<Element>] {
self.geometry
.as_ref()
@@ -39,6 +47,25 @@ impl ResolvedCuboidModel {
}
}
impl ModelLibrary {
/// A library that also knows `builtin/generated`, the parent of every
/// flat item model; the native client registers it as a special model.
pub fn with_item_generator(mut models: BTreeMap<String, CuboidModel>) -> Result<Self> {
models.insert(
GENERATED_MODEL.to_owned(),
CuboidModel {
parent: None,
ambient_occlusion: None,
gui_light: Some(GuiLight::Front),
textures: BTreeMap::from([(
"particle".to_owned(),
TextureSlot::Reference("layer0".to_owned()),
)]),
elements: None,
display: None,
},
);
Self::new(models)
}
pub fn new(models: BTreeMap<String, CuboidModel>) -> Result<Self> {
let mut decoded = BTreeMap::new();
for (name, model) in models {
@@ -64,12 +91,14 @@ impl ModelLibrary {
let mut name = identifier(name)?;
let mut visited = BTreeSet::new();
let mut chain = Vec::new();
let mut names = Vec::new();
loop {
if !visited.insert(name.clone()) {
return Err(error("cyclic model parent"));
}
let model = self.models.get(&name).unwrap_or(&self.missing);
chain.push(model);
names.push(name.clone());
match &model.parent {
Some(parent) => name = parent.clone(),
None => break,
@@ -87,6 +116,11 @@ impl ModelLibrary {
.iter()
.find(|m| m.elements.is_some())
.map(|m| Arc::clone(m));
let generated = chain
.iter()
.zip(&names)
.find(|(m, name)| m.elements.is_some() || *name == GENERATED_MODEL)
.is_some_and(|(_, name)| name == GENERATED_MODEL);
let display = ItemTransforms {
contexts: std::array::from_fn(|index| {
chain
@@ -146,6 +180,7 @@ impl ModelLibrary {
textures,
unresolved_textures,
geometry,
generated,
})
}
}
@@ -0,0 +1,197 @@
//! Command parsing for differential tests against vanilla's Brigadier tree
//! (tools/test_command_parse_parity.py): reads one command per line and prints
//! the parse result, the error (rendered text and UTF-16 cursor), the parsed
//! node names and the completion suggestions at the end of the input, in the
//! same JSON-lines shape as VanillaCommandParseOracle.
//!
//! usage: command_parse_fixture RESOURCES REGISTRIES.json CORPUS PERMISSION OUTPUT
use horizon_client::{
command::{ArgType, Dispatcher, NodeKind, Registries, vanilla},
lang,
};
use serde_json::{Value, json};
use std::{fs, path::Path};
fn strings(v: &Value) -> Vec<String> {
v.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
fn utf16(input: &str, byte: usize) -> usize {
let mut end = byte.min(input.len());
while !input.is_char_boundary(end) {
end -= 1;
}
input[..end].encode_utf16().count()
}
fn parser_id(ty: &ArgType) -> String {
match ty {
ArgType::Bool => "brigadier:bool".into(),
ArgType::Integer { .. } => "brigadier:integer".into(),
ArgType::Float { .. } => "brigadier:float".into(),
ArgType::Double { .. } => "brigadier:double".into(),
ArgType::Word | ArgType::Str | ArgType::Greedy => "brigadier:string".into(),
ArgType::Entity { .. } => "minecraft:entity".into(),
ArgType::BlockPos => "minecraft:block_pos".into(),
ArgType::Vec3 { .. } => "minecraft:vec3".into(),
ArgType::Rotation => "minecraft:rotation".into(),
ArgType::Angle => "minecraft:angle".into(),
ArgType::Item => "minecraft:item_stack".into(),
ArgType::ItemPredicate => "minecraft:item_predicate".into(),
ArgType::BlockState => "minecraft:block_state".into(),
ArgType::BlockPredicate => "minecraft:block_predicate".into(),
ArgType::Resource(r) => format!("resource:{r:?}"),
ArgType::Id(n) | ArgType::Name(n) => format!("id:{n}"),
ArgType::Time { .. } => "minecraft:time".into(),
ArgType::GameMode => "minecraft:gamemode".into(),
ArgType::Message => "minecraft:message".into(),
ArgType::Dimension => "minecraft:dimension".into(),
ArgType::Anchor => "minecraft:entity_anchor".into(),
ArgType::Swizzle => "minecraft:swizzle".into(),
ArgType::Component => "minecraft:component".into(),
ArgType::Nbt => "minecraft:nbt_compound_tag".into(),
ArgType::ScoreHolder { .. } => "minecraft:score_holder".into(),
ArgType::Objective => "minecraft:objective".into(),
ArgType::Team => "minecraft:team".into(),
ArgType::Criteria => "minecraft:objective_criteria".into(),
ArgType::ScoreboardSlot => "minecraft:scoreboard_slot".into(),
ArgType::Operation => "minecraft:operation".into(),
ArgType::TeamColor => "minecraft:team_color".into(),
ArgType::IntRange => "minecraft:int_range".into(),
ArgType::FloatRange => "minecraft:float_range".into(),
ArgType::NbtPath => "minecraft:nbt_path".into(),
ArgType::NbtTag => "minecraft:nbt_tag".into(),
ArgType::Vec2 => "minecraft:vec2".into(),
ArgType::ColumnPos => "minecraft:column_pos".into(),
ArgType::Particle => "minecraft:particle".into(),
ArgType::Enum(words) => format!("enum:{}", words.join("|")),
ArgType::Function => "minecraft:function".into(),
ArgType::Slots => "minecraft:slots".into(),
ArgType::Slot => "minecraft:item_slot".into(),
}
}
fn tree(d: &Dispatcher, node: usize) -> Value {
let n = &d.nodes[node];
let mut children = serde_json::Map::new();
for &c in &n.children {
let child = &d.nodes[c];
let mut v = tree(d, c);
match &child.kind {
NodeKind::Literal(_) => v["type"] = json!("literal"),
NodeKind::Argument { ty, .. } => {
v["type"] = json!("argument");
v["parser"] = json!(parser_id(ty));
}
NodeKind::Root => {}
}
children.insert(child.name().to_owned(), v);
}
let mut v = json!({"children": children});
if n.command.is_some() {
v["executable"] = json!(true);
}
if n.redirect.is_some() {
v["redirect"] = json!(true);
}
v
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.get(1).map(String::as_str) == Some("tree") {
let d = vanilla::dispatcher();
let mut v = tree(d, 0);
v["type"] = json!("root");
fs::write(&args[2], v.to_string())?;
return Ok(());
}
if args.len() != 6 {
return Err(
"usage: command_parse_fixture RESOURCES REGISTRIES CORPUS PERMISSION OUTPUT".into(),
);
}
let root = Path::new(&args[1]).to_path_buf();
lang::set(lang::Language::load(&[&root], lang::DEFAULT));
let r: Value = serde_json::from_slice(&fs::read(&args[2])?)?;
let mut reg = Registries {
permission: args[4].parse()?,
..Registries::default()
};
reg.items = strings(&r["items"]);
reg.item_tags = strings(&r["item_tags"]);
reg.block_tags = strings(&r["block_tags"]);
for (id, props) in r["blocks"].as_object().into_iter().flatten() {
let props = props
.as_array()
.into_iter()
.flatten()
.map(|p| (p[0].as_str().unwrap_or("").to_owned(), strings(&p[1])))
.collect();
reg.blocks.insert(id.clone(), props);
}
reg.summonable = strings(&r["summonable"]);
reg.entity_types = strings(&r["entity_types"]);
reg.effects = strings(&r["effects"]);
reg.attributes = strings(&r["attributes"]);
reg.sounds = strings(&r["sounds"]);
reg.enchantments = strings(&r["enchantments"]);
reg.structures = strings(&r["structures"]);
reg.biomes = strings(&r["biomes"]);
reg.damage_types = strings(&r["damage_types"]);
reg.clocks = strings(&r["clocks"]);
reg.timelines = strings(&r["timelines"]);
reg.dimensions = strings(&r["dimensions"]);
reg.players = strings(&r["players"]);
reg.teams = strings(&r["teams"]);
reg.objectives = strings(&r["objectives"]);
reg.tracked = strings(&r["tracked"]);
let dispatcher = vanilla::dispatcher();
let mut out = String::new();
for input in fs::read_to_string(&args[3])?.lines() {
let parse = dispatcher.parse(input, &reg);
let result = match parse.executable() {
Ok(_) => {
let mut nodes = Vec::new();
let mut c = Some(&parse.context);
while let Some(ctx) = c {
nodes.extend(
ctx.nodes
.iter()
.map(|(n, _)| dispatcher.nodes[*n].name().to_owned()),
);
c = ctx.child.as_deref();
}
json!({"ok": true, "nodes": nodes})
}
Err(e) => json!({
"ok": false,
"error": e.message.plain(),
"cursor": utf16(input, if e.input.is_some() { e.cursor } else { parse.cursor }),
}),
};
let (range, list) = dispatcher.suggestions(&parse, input.len(), &reg);
let list: Vec<String> = list
.into_iter()
.map(|s| match s.tooltip {
Some(t) => format!("{}\t{t}", s.text),
None => s.text,
})
.collect();
let row = json!({
"in": input,
"parse": result,
"sugg": {"start": utf16(input, range.0), "end": utf16(input, range.1), "list": list},
});
out.push_str(&row.to_string());
out.push('\n');
}
fs::write(&args[5], out)?;
Ok(())
}
+8 -2
View File
@@ -41,6 +41,7 @@ pub struct Registries {
pub bossbars: Vec<String>,
pub predicates: Vec<String>,
pub schedules: Vec<String>,
pub stopwatches: Vec<String>,
pub recipes: Vec<String>,
pub sounds: Vec<String>,
pub damage_types: Vec<String>,
@@ -156,6 +157,7 @@ pub enum ArgType {
TeamColor,
/// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`).
IntRange,
FloatRange,
/// NbtPathArgument (kept as text).
NbtPath,
/// NbtTagArgument: any SNBT value (kept as text).
@@ -426,6 +428,7 @@ pub enum Arg {
Anchor(bool),
ScoreHolder(ScoreHolderArg),
IntRange(IntRange),
DoubleRange(DoubleRange),
}
fn is_id_char(c: char) -> bool {
@@ -1487,8 +1490,9 @@ impl ArgType {
}
ArgType::Entity { single, players } => {
let s = parse_selector(reader, reg)?;
// Vanilla rewinds to the very start of the input for these.
if s.limit > 1 && *single {
reader.cursor = start;
reader.cursor = 0;
let key = if *players {
"argument.player.toomany"
} else {
@@ -1497,7 +1501,7 @@ impl ArgType {
return Err(CommandError::tr_at(key, &[], reader));
}
if s.include_entities && *players && !s.is_self() {
reader.cursor = start;
reader.cursor = 0;
return Err(CommandError::tr_at("argument.player.entities", &[], reader));
}
Arg::Entity(s)
@@ -1749,6 +1753,7 @@ impl ArgType {
Arg::Str(name.to_owned())
}
ArgType::IntRange => Arg::IntRange(range_int(reader)?),
ArgType::FloatRange => Arg::DoubleRange(range_double(reader)?),
ArgType::Name(_) => Arg::Str(reader.read_string()?),
ArgType::Vec2 | ArgType::ColumnPos => {
let block = matches!(self, ArgType::ColumnPos);
@@ -1922,6 +1927,7 @@ impl ArgType {
"storages" => reg.storages.clone(),
"bossbars" => reg.bossbars.clone(),
"schedules" => reg.schedules.clone(),
"stopwatches" => reg.stopwatches.clone(),
"recipes" => reg.recipes.clone(),
"sounds" => reg.sounds.clone(),
"damage_types" => reg.damage_types.clone(),
@@ -180,6 +180,11 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
let p = d.argument(predicate, "predicate", ArgType::Id("predicates"));
conditional(d, p, ex);
let stopwatch = d.literal(m, "stopwatch");
let id = d.argument(stopwatch, "id", ArgType::Id("stopwatches"));
let range = d.argument(id, "range", ArgType::FloatRange);
conditional(d, range, ex);
let function = d.literal(m, "function");
let name = d.argument(function, "name", ArgType::Function);
conditional(d, name, ex);
@@ -21,6 +21,7 @@ pub fn register(d: &mut Dispatcher, root: usize) {
item(d, root);
bossbar(d, root);
function(d, root);
stopwatch(d, root);
// return <value> | fail | run <command>
let ret = d.literal(root, "return");
@@ -255,3 +256,32 @@ fn function(d: &mut Dispatcher, root: usize) {
d.executes(path, "function");
}
}
/// stopwatch create <id> | query <id> [<scale>] | restart <id> | remove <id>
fn stopwatch(d: &mut Dispatcher, root: usize) {
let sw = d.literal(root, "stopwatch");
d.requires(sw, GAMEMASTERS);
let create = d.literal(sw, "create");
let id = d.argument(create, "id", ArgType::Id("none"));
d.executes(id, "stopwatch.create");
let query = d.literal(sw, "query");
let id = d.argument(query, "id", ArgType::Id("stopwatches"));
d.executes(id, "stopwatch.query");
let scale = d.argument(
id,
"scale",
ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
);
d.executes(scale, "stopwatch.query");
for (name, command) in [
("restart", "stopwatch.restart"),
("remove", "stopwatch.remove"),
] {
let l = d.literal(sw, name);
let id = d.argument(l, "id", ArgType::Id("stopwatches"));
d.executes(id, command);
}
}
+31 -5
View File
@@ -213,7 +213,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
| "minecraft:donkey"
| "minecraft:mule"
| "minecraft:skeleton_horse"
| "minecraft:zombie_horse" => {
| "minecraft:zombie_horse"
| "minecraft:llama"
| "minecraft:trader_llama" => {
map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame)));
map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3)));
if let Some(owner) = m.extra.owner {
@@ -223,8 +225,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let v = i32::from(m.extra.variant) | i32::from(m.extra.variant2) << 8;
map.insert("Variant".into(), Tag::Int(v));
}
// Only donkeys and mules carry chests.
if matches!(id, "minecraft:donkey" | "minecraft:mule") {
let llama = crate::mobs::llama::is_llama(m.species());
if llama {
crate::mobs::llama::to_nbt(m, map);
}
// Only llamas, donkeys and mules carry chests.
if llama || matches!(id, "minecraft:donkey" | "minecraft:mule") {
map.insert("ChestedHorse".into(), Tag::Byte(i8::from(m.extra.chested)));
}
if m.extra.chested && !m.extra.items.is_empty() {
@@ -341,6 +347,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Tag::Long(if sitting { -1 } else { 0 }),
);
}
"minecraft:sniffer" => crate::mobs::sniffer::to_nbt(m, map),
"minecraft:wither" => {
map.insert("Invul".into(), Tag::Int(m.extra.counter));
}
@@ -410,7 +417,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (index, (slot, item)) in [
("mainhand", &m.extra.main_hand),
("offhand", &m.extra.off_hand),
("head", &m.extra.head),
(
// A happy ghast wears its harness in the body slot.
if m.species() == crate::mobs::Species::HappyGhast {
"body"
} else {
"head"
},
&m.extra.head,
),
("chest", &m.extra.chest),
("legs", &m.extra.legs),
("feet", &m.extra.feet),
@@ -508,7 +523,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
.map(Into::into);
if !crate::mobs::equine::is_equine(m.species()) {
let slot = |key| eq.get(key).and_then(|i| text(i.get("id"))).map(Into::into);
m.extra.head = slot("head");
m.extra.head = slot(if m.species() == crate::mobs::Species::HappyGhast {
"body"
} else {
"head"
});
m.extra.chest = slot("chest");
m.extra.legs = slot("legs");
m.extra.feet = slot("feet");
@@ -563,6 +582,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
let v = number(tag.get("Variant")).unwrap_or(0) as i32;
m.extra.variant = (v & 0xFF).clamp(0, 6) as u8;
m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8;
if crate::mobs::llama::is_llama(m.species()) {
crate::mobs::llama::from_nbt(&mut m, tag);
}
m.extra.chested = flag(tag, "ChestedHorse");
if m.extra.chested {
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
@@ -667,6 +689,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
if m.species() == crate::mobs::Species::Sniffer {
crate::mobs::sniffer::from_nbt(&mut m, tag);
}
m.extra.leash_pending = crate::mobs::leash::pending_from_nbt(tag.get("leash"));
if m.species() == crate::mobs::Species::Warden {
// The brain starts afresh: a minute before it digs back down.
crate::mobs::warden::finalize(&mut m, false, &mut Vec::new());
+21
View File
@@ -10,6 +10,7 @@ mod blockctl;
mod boats;
mod books;
mod bossbars;
mod breezes;
mod cartography;
mod chat;
mod combat;
@@ -30,13 +31,16 @@ mod fov;
mod frames;
mod functions;
mod game_mode;
mod ghasts;
mod golems;
mod growth;
mod jukebox;
mod lan;
mod lan_actions;
mod lan_screen;
mod leads;
mod lightning;
mod llamas;
mod loom;
mod machines;
mod maps;
@@ -66,6 +70,7 @@ mod screens;
mod sculk;
mod shield;
mod sign_edit;
mod sniffers;
mod station_control;
mod stations;
mod stats;
@@ -79,6 +84,8 @@ mod totem;
mod trading;
mod trident;
mod villagers;
mod wandering_trader;
mod wind;
mod wither;
mod zombie_villagers;
use horizon_client::{
@@ -1441,6 +1448,16 @@ impl Game<'_> {
let _ = self.spawn_mob("minecraft:tadpole", spawn, true);
}
}
LevelEvent::BlockEvent {
pos,
kind: "hatch_sniffer",
..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]),
LevelEvent::BlockEvent {
pos,
state,
kind: "spawn_ghastling",
} => self.spawn_ghastling([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent {
pos,
state,
@@ -1750,6 +1767,7 @@ impl Game<'_> {
|| self.interact_boat()
|| self.interact_cart()
|| self.interact_mob()?
|| self.interact_knot()
{
return Ok(());
}
@@ -4155,6 +4173,7 @@ impl Game<'_> {
self.cart_geometry(camera, alpha, &mut out);
self.beacon_geometry(camera, alpha, &mut out);
self.fishing_geometry(camera, alpha, &mut out);
self.leash_geometry(camera, alpha, &mut out);
self.trident_geometry(camera, alpha, &mut out);
self.rocket_geometry(camera, alpha, &mut out);
// Particles (ParticleEngine.extract): camera-facing quads.
@@ -4846,6 +4865,7 @@ impl Game<'_> {
self.spawn = None;
self.spawn_search = 0;
self.mobs.clear();
self.creatures.reset_trader();
self.arrows.clear();
self.dropped.clear();
self.particles.clear();
@@ -6759,6 +6779,7 @@ impl Game<'_> {
self.save_maps();
self.save_raids();
self.save_fight();
self.save_wandering_trader();
self.save_stats();
self.save_advancements();
self.save_scoreboard();
+65
View File
@@ -0,0 +1,65 @@
//! Breeze particles (`Breeze.tick`): block dust at its feet while it stands,
//! a burst of twenty while it slides and a short trail along a long jump.
use super::Game;
use horizon_client::{
mobs::{Species, breeze},
particles::Particle,
};
impl Game<'_> {
pub(super) fn tick_breeze_effects(&mut self) {
let Some(camera) = self.player.as_ref().map(|p| p.position) else {
return;
};
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Breeze
|| !m.alive()
|| m.position.distance_squared(camera) > 32.0 * 32.0
{
continue;
}
let pose = breeze::pose(m);
let (amount, jump_trail) = match pose {
breeze::SLIDING => (20, false),
breeze::LONG_JUMPING => (3, true),
_ => (1, false),
};
if jump_trail {
self.mobs[i].extra.scratch[1] += 1;
if self.mobs[i].extra.scratch[1] > 5 {
continue;
}
} else {
self.mobs[i].extra.scratch[1] = 0;
}
let m = &self.mobs[i];
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let mut state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
state = self.world.block(x, (m.position.y - 0.2).floor() as i32, z);
}
let Some((sprite, tint)) = self.particle_sprite(state) else {
continue;
};
let at = if jump_trail {
[
m.position.x + m.velocity.x,
m.position.y + m.velocity.y + f64::from(0.1_f32),
m.position.z + m.velocity.z,
]
} else {
[m.position.x, m.position.y, m.position.z]
};
for _ in 0..amount {
let particle =
Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint);
self.particles.push(particle);
}
}
}
}
@@ -552,6 +552,7 @@ impl Game<'_> {
id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx),
id if id.starts_with("loot.") => self.cmd_loot(id, ctx),
"teammsg" => self.cmd_teammsg(ctx),
id if id.starts_with("stopwatch.") => self.cmd_stopwatch(id, ctx),
id if id.starts_with("tick.") => self.cmd_tick(id, ctx),
id if id.starts_with("random.") => self.cmd_random(id, ctx),
"function" => self.cmd_function(ctx),
@@ -777,6 +777,9 @@ impl Game<'_> {
if c.has("blocks") {
return self.condition_blocks(c);
}
if c.has("range") && c.has("id") {
return self.condition_stopwatch(c).map(flag);
}
if c.has("predicate") {
let Some(Arg::Resource(id)) = c.get("predicate").cloned() else {
return Ok((false, 0));
@@ -785,6 +788,18 @@ impl Game<'_> {
}
Ok((false, 0))
}
fn condition_stopwatch(&mut self, c: &Context) -> R<bool> {
let Some(Arg::Resource(id)) = c.get("id").cloned() else {
return Ok(false);
};
let Some(Arg::DoubleRange((lo, hi))) = c.get("range").cloned() else {
return Ok(false);
};
let Some(t) = self.score.stopwatches.elapsed_seconds(&id) else {
return Err(err("commands.stopwatch.does_not_exist", &[&id]));
};
Ok(lo.is_none_or(|l| t >= l) && hi.is_none_or(|h| t <= h))
}
fn condition_score(&mut self, c: &Context) -> R<bool> {
let target = self.score_holder_names(c, "target", false)?;
let Some(Arg::Str(to)) = c.get("targetObjective").cloned() else {
@@ -9,6 +9,59 @@ fn millis(nanos: u64) -> String {
}
impl Game<'_> {
/// `/stopwatch` (StopwatchCommand).
pub(super) fn cmd_stopwatch(&mut self, id: &str, ctx: &Context) -> R<i32> {
let Some(Arg::Resource(name)) = ctx.get("id").cloned() else {
return Ok(0);
};
let arg = || Text::literal(name.clone());
let missing = || err("commands.stopwatch.does_not_exist", &[&name]);
let sw = &mut self.score.stopwatches;
match id {
"stopwatch.create" => {
if !sw.create(&name) {
return Err(err("commands.stopwatch.already_exists", &[&name]));
}
self.feedback(Text::translate(
"commands.stopwatch.create.success",
&[arg()],
));
Ok(1)
}
"stopwatch.query" => {
let scale = match ctx.get("scale") {
Some(Arg::Double(v)) => *v,
_ => 1.0,
};
let t = sw.elapsed_seconds(&name).ok_or_else(missing)?;
self.feedback(Text::translate(
"commands.stopwatch.query",
&[arg(), Text::literal(format!("{t:?}"))],
));
Ok((t * scale) as i32)
}
"stopwatch.restart" => {
if !sw.restart(&name) {
return Err(missing());
}
self.feedback(Text::translate(
"commands.stopwatch.restart.success",
&[arg()],
));
Ok(1)
}
_ => {
if !sw.remove(&name) {
return Err(missing());
}
self.feedback(Text::translate(
"commands.stopwatch.remove.success",
&[arg()],
));
Ok(1)
}
}
}
/// `/tick` (TickCommand) over the game clock.
pub(super) fn cmd_tick(&mut self, id: &str, ctx: &Context) -> R<i32> {
let t = |key: &str, args: &[Text]| Text::translate(key, args);
@@ -0,0 +1,739 @@
//! Copper golems on the game side: `TransportItemsBetweenContainers` (carry
//! items from copper chests to ordinary chests), weathering and turning into
//! statues, and the hand-over, waxing, scraping and shearing interactions.
use super::Game;
use horizon_client::{
containers::BlockEntity,
items::ItemStack,
mobs::{Mob, Species, copper_golem as cg, goals::should_panic},
};
use horizon_core::random::RandomSource;
use horizon_world::chunk::BlockState;
type Key = (i32, i32, i32);
/// `TransportItemState`.
const TRAVELLING: i32 = 0;
const QUEUING: i32 = 1;
const INTERACTING: i32 = 2;
/// `ContainerInteractionState` (0 = none).
const PICKUP_ITEM: i32 = 1;
const PICKUP_NO_ITEM: i32 = 2;
const PLACE_ITEM: i32 = 3;
const PLACE_NO_ITEM: i32 = 4;
/// Positions that were unreachable are kept in `positions` with this offset.
const UNREACHABLE: i32 = 1 << 20;
/// `TransportItemsBetweenContainers.VISITED_POSITIONS_MEMORY_TIME`.
const MEMORY_TICKS: i32 = 6000;
/// Whether a block is a copper chest (the pick-up sources).
pub(super) fn is_copper_chest(name: &str) -> bool {
name.ends_with("copper_chest")
}
/// The held stack (`getMainHandItem`).
pub(super) fn held(m: &Mob) -> Option<&ItemStack> {
m.extra.items.first().and_then(Option::as_ref)
}
/// `setItemInHand(MAIN_HAND, ..)`, keeping the rendered copy in step.
pub(super) fn set_held(m: &mut Mob, stack: Option<ItemStack>) {
let stack = stack.filter(|s| s.count > 0);
m.extra.main_hand = stack.as_ref().map(|s| s.item.clone());
m.extra.ints[1] = stack.as_ref().map_or(0, |s| s.count as i32);
if m.extra.items.is_empty() {
m.extra.items.push(None);
}
m.extra.items[0] = stack;
}
fn visited(m: &Mob) -> Vec<[i32; 3]> {
m.extra
.positions
.iter()
.filter(|p| p[1] < UNREACHABLE)
.copied()
.collect()
}
fn blocked_list(m: &Mob) -> impl Iterator<Item = [i32; 3]> + '_ {
m.extra.positions.iter().map(|p| {
if p[1] >= UNREACHABLE {
[p[0], p[1] - UNREACHABLE, p[2]]
} else {
*p
}
})
}
fn chest_center(h: [i32; 3]) -> [f64; 3] {
[
f64::from(h[0]) + 0.5,
f64::from(h[1]) + 0.5,
f64::from(h[2]) + 0.5,
]
}
/// The copper golem state the model, sounds and animations follow.
fn set_state(m: &mut Mob, state: u8) {
m.extra.variant3 = state;
}
impl Game<'_> {
pub(super) fn tick_copper_golems(&mut self) {
let ids: Vec<u32> = self
.mobs
.iter()
.filter(|m| m.species() == Species::CopperGolem && m.alive() && !m.removed)
.map(|m| m.id)
.collect();
for id in ids {
let Some(i) = self.mobs.iter().position(|m| m.id == id) else {
continue;
};
let mut m = self.mobs[i].clone();
self.copper_golem_step(&mut m);
if let Some(i) = self.mobs.iter().position(|x| x.id == id) {
self.mobs[i] = m;
}
}
let alive: std::collections::HashSet<u32> = self.mobs.iter().map(|m| m.id).collect();
self.golem_openers.retain(|id, _| alive.contains(id));
}
fn copper_golem_step(&mut self, m: &mut Mob) {
if self.golem_weathering(m) {
return;
}
// CountDownCooldownTicks(TRANSPORT_ITEMS_COOLDOWN_TICKS).
if m.extra.scratch[3] > 0 {
m.extra.scratch[3] -= 1;
}
// The visited positions fade after 6000 ticks.
if m.extra.ints[2] > 0 && m.age >= m.extra.ints[2] {
m.extra.positions.clear();
m.extra.ints[2] = 0;
}
let running = m.extra.scratch[3] <= 0 && !should_panic(m) && m.extra.leash.is_none();
if !running {
if m.extra.home.is_some() || m.extra.scratch[0] != TRAVELLING {
self.golem_on_start_travelling(m);
m.extra.point = None;
m.ai.nav.stop();
}
return;
}
let invalid = self.golem_update_invalid_target(m);
if m.extra.home.is_none() {
self.golem_on_start_travelling(m);
return;
}
if invalid {
return;
}
if m.extra.scratch[0] == QUEUING {
self.golem_on_queuing(m);
}
if m.extra.scratch[0] == TRAVELLING {
self.golem_on_travel(m);
}
if m.extra.scratch[0] == INTERACTING {
self.golem_on_reached(m);
}
}
// ---- weathering -------------------------------------------------------
/// `CopperGolem.updateWeathering`; true when it turned into a statue.
fn golem_weathering(&mut self, m: &mut Mob) -> bool {
let now = self.world.game_time;
let next = m.extra.vector[0] as i64;
if next == -2 {
return false;
}
let interval = |m: &mut Mob| 504_000 + i64::from(m.random.next_int_bound(48_001).unwrap_or(0));
if next == -1 {
m.extra.vector[0] = (now + interval(m)) as f64;
return false;
}
let fully = m.extra.variant >= 3;
if now >= next && !fully {
let new = cg::weather_next(m.extra.variant);
m.extra.variant = new;
m.extra.vector[0] = if new >= 3 {
0.0
} else {
(next + interval(m)) as f64
};
}
if fully && self.golem_can_turn_to_statue(m) {
self.golem_turn_to_statue(m);
return true;
}
false
}
fn golem_can_turn_to_statue(&mut self, m: &mut Mob) -> bool {
let p = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let at = self.world.block(p[0], p[1], p[2]);
self.res.facts.is_air(at) && self.world.random.next_float() <= 0.0058
}
fn golem_turn_to_statue(&mut self, m: &mut Mob) {
let pos = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let pose = ["standing", "sitting", "running", "star"]
[self.world.random.next_int_bound(4).unwrap_or(0) as usize];
// Direction.fromYRot.
let facing = ["south", "west", "north", "east"]
[((f64::from(m.yaw) / 90.0 + 0.5).floor() as i32 & 3) as usize];
let state = BlockState {
name: "minecraft:oxidized_copper_golem_statue".into(),
properties: [
("facing".to_string(), facing.to_string()),
("pose".to_string(), pose.to_string()),
("waterlogged".to_string(), "false".to_string()),
]
.into(),
};
let registry = self.res.assets.registry;
let Some(id) = registry.id(&state) else {
return;
};
if self.level_set(pos, id).is_err() {
return;
}
self.golem_drop_equipment(m);
self.golem_release(m);
if m.extra.leash.is_some() {
self.break_leash(m.id, true, false);
m.extra.leash = None;
}
m.removed = true;
self.audio.play(
"minecraft:entity.copper_golem_become_statue",
Some([m.position.x, m.position.y, m.position.z]),
1.0,
1.0,
);
}
/// `dropPreservedEquipment`: the carried stack and the antenna.
pub(super) fn golem_drop_equipment(&mut self, m: &mut Mob) {
let at = [m.position.x, m.position.y + 0.5, m.position.z];
if let Some(stack) = held(m).cloned() {
set_held(m, None);
self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10);
}
if let Some(antenna) = m.extra.legs.take() {
self.spawn_item(ItemStack::new(&antenna, 1), at, [0.0, 0.2, 0.0], 10);
}
}
// ---- containers -------------------------------------------------------
/// The block entities of the container at a chest, in slot order.
fn golem_container(&self, key: Key) -> Vec<Key> {
let Some(other) = self.chest_other_half(key) else {
return vec![key];
};
let right = self
.res
.assets
.registry
.state(self.world.block(key.0, key.1, key.2))
.and_then(|s| s.properties.get("type"))
.is_some_and(|t| t == "right");
if right {
vec![key, other]
} else {
vec![other, key]
}
}
fn golem_block_name(&self, key: Key) -> std::sync::Arc<str> {
self.res
.facts
.get(self.world.block(key.0, key.1, key.2))
.name
.clone()
}
fn golem_chest_blocked(&self, keys: &[Key]) -> bool {
keys.iter().any(|k| {
let above = self.world.block(k.0, k.1 + 1, k.2);
self.behaviours.facts(above).flags & horizon_world::level::data::state_flags::CONDUCTOR
!= 0
})
}
fn golem_slots(&self, keys: &[Key]) -> Vec<Option<ItemStack>> {
keys.iter()
.filter_map(|k| self.world.block_entities.get(k))
.flat_map(|e| e.slots().to_vec())
.collect()
}
fn golem_slot_mut(&mut self, keys: &[Key], mut n: usize) -> Option<&mut Option<ItemStack>> {
for k in keys {
let len = self.world.block_entities.get(k)?.slots().len();
if n < len {
return self.world.block_entities.get_mut(k)?.slots_mut().get_mut(n);
}
n -= len;
}
None
}
fn golem_max_stack(&self, stack: &ItemStack) -> u32 {
self.res.items.get(&stack.item).map_or(64, |i| i.max_stack).max(1)
}
/// `pickupItemFromContainer`: up to 16 of the first non-empty slot.
fn golem_pick_up(&mut self, keys: &[Key]) -> Option<ItemStack> {
let slots = self.golem_slots(keys);
let (n, stack) = slots
.iter()
.enumerate()
.find_map(|(n, s)| s.as_ref().map(|s| (n, s.clone())))?;
let take = stack.count.min(16);
let slot = self.golem_slot_mut(keys, n)?;
let mut out = stack;
out.count = take;
match slot {
Some(s) if s.count > take => s.count -= take,
_ => *slot = None,
}
Some(out)
}
/// `addItemsToContainer`: the part that did not fit.
fn golem_put_down(&mut self, keys: &[Key], mut stack: ItemStack) -> Option<ItemStack> {
let max = self.golem_max_stack(&stack);
let slots = self.golem_slots(keys);
for (n, existing) in slots.iter().enumerate() {
match existing {
None => {
if let Some(slot) = self.golem_slot_mut(keys, n) {
*slot = Some(stack);
}
return None;
}
Some(e)
if e.item == stack.item
&& e.damage == stack.damage
&& e.extra == stack.extra
&& e.count < max =>
{
let room = max - e.count;
let add = room.min(stack.count);
if let Some(Some(s)) = self.golem_slot_mut(keys, n) {
s.count += add;
}
// Vanilla subtracts the whole room, which empties the stack
// when it fitted.
stack.count = stack.count.saturating_sub(room);
if stack.count == 0 {
return None;
}
}
_ => {}
}
}
Some(stack)
}
/// Whether any other golem or a player has the chest open.
fn golem_chest_busy(&self, m: &Mob, keys: &[Key]) -> bool {
self.golem_openers
.iter()
.any(|(id, k)| *id != m.id && keys.contains(k))
|| self.container.is_some_and(|c| keys.contains(&c))
}
// ---- the behaviour ----------------------------------------------------
fn golem_wanted_block(&self, m: &Mob, key: Key) -> bool {
let name = self.golem_block_name(key);
if held(m).is_none() {
is_copper_chest(&name)
} else {
matches!(&*name, "minecraft:chest" | "minecraft:trapped_chest")
}
}
fn golem_update_invalid_target(&mut self, m: &mut Mob) -> bool {
if self.golem_has_valid_target(m) {
return false;
}
self.golem_stop_targeting(m);
match self.golem_find_target(m) {
Some(t) => {
m.extra.home = Some([t.0, t.1, t.2]);
self.golem_on_start_travelling(m);
self.golem_set_visited(m, [t.0, t.1, t.2]);
}
None => self.golem_enter_cooldown(m),
}
true
}
fn golem_has_valid_target(&mut self, m: &mut Mob) -> bool {
let Some(h) = m.extra.home else { return false };
let key = (h[0], h[1], h[2]);
let valid = self.golem_wanted_block(m, key)
&& matches!(self.world.block_entities.get(&key), Some(BlockEntity::Chest(_)))
&& !self.golem_chest_blocked(&self.golem_container(key));
if !valid {
return false;
}
if m.extra.scratch[0] != TRAVELLING {
return true;
}
if self.golem_valid_travelling_path(m, h) {
return true;
}
self.golem_mark_unreachable(m, h);
false
}
/// `hasValidTravellingPath`, without the line-of-sight clip.
fn golem_valid_travelling_path(&mut self, m: &mut Mob, h: [i32; 3]) -> bool {
let w = self.mob_world_base(&[]);
let path = match &m.ai.nav.path {
Some(p) => Some(p.clone()),
None => m.create_path_to(&w, h, 0),
};
let from = match path.as_ref().and_then(|p| p.end()) {
Some(n) => [
f64::from(n.x) + 0.5,
f64::from(n.y) + m.kind.height / 2.0,
f64::from(n.z) + 0.5,
],
None => [m.position.x, m.position.y + m.kind.height / 2.0, m.position.z],
};
let reach = golem_within(m, self.golem_range(m), from, h);
(path.is_none() && !reach) || reach
}
fn golem_range(&self, m: &Mob) -> f64 {
if m.ai.nav.path.as_ref().is_some_and(|p| p.is_done()) {
1.0
} else {
0.5
}
}
fn golem_find_target(&self, m: &Mob) -> Option<Key> {
let bx = m.position.x.floor() as i32;
let by = m.position.y.floor() as i32;
let bz = m.position.z.floor() as i32;
let skip: Vec<[i32; 3]> = blocked_list(m).collect();
let mut best: Option<(f64, Key)> = None;
for (key, entity) in &self.world.block_entities {
if !matches!(entity, BlockEntity::Chest(_)) {
continue;
}
if (key.0 - bx).abs() > 32 || (key.1 - by).abs() > 8 || (key.2 - bz).abs() > 32 {
continue;
}
let center = chest_center([key.0, key.1, key.2]);
let d = (center[0] - m.position.x).powi(2)
+ (center[1] - m.position.y).powi(2)
+ (center[2] - m.position.z).powi(2);
if best.is_some_and(|(b, _)| d >= b) {
continue;
}
if !self.golem_wanted_block(m, *key) {
continue;
}
let keys = self.golem_container(*key);
if keys.iter().any(|k| skip.contains(&[k.0, k.1, k.2])) {
continue;
}
if self.golem_chest_blocked(&keys) {
continue;
}
best = Some((d, *key));
}
best.map(|b| b.1)
}
fn golem_set_visited(&mut self, m: &mut Mob, h: [i32; 3]) {
let mut list = visited(m);
if !list.contains(&h) {
list.push(h);
}
if list.len() > 10 {
self.golem_enter_cooldown(m);
return;
}
m.extra.positions.retain(|p| p[1] >= UNREACHABLE);
m.extra.positions.extend(list);
m.extra.ints[2] = m.age + MEMORY_TICKS;
}
fn golem_mark_unreachable(&mut self, m: &mut Mob, h: [i32; 3]) {
m.extra.positions.retain(|p| *p != h);
let marked = [h[0], h[1] + UNREACHABLE, h[2]];
if !m.extra.positions.contains(&marked) {
m.extra.positions.push(marked);
}
let count = m.extra.positions.iter().filter(|p| p[1] >= UNREACHABLE).count();
if count > 50 {
self.golem_enter_cooldown(m);
} else {
m.extra.ints[2] = m.age + MEMORY_TICKS;
}
}
fn golem_stop_targeting(&mut self, m: &mut Mob) {
m.extra.scratch[1] = 0;
m.extra.home = None;
m.extra.point = None;
m.ai.nav.stop();
}
fn golem_clear_memories(&mut self, m: &mut Mob) {
self.golem_stop_targeting(m);
m.extra.positions.clear();
}
fn golem_enter_cooldown(&mut self, m: &mut Mob) {
self.golem_stop_targeting(m);
m.extra.scratch[3] = 140;
m.extra.positions.clear();
}
/// `onStartTravelling` and the golem's own consumer.
fn golem_on_start_travelling(&mut self, m: &mut Mob) {
self.golem_release(m);
set_state(m, cg::IDLE);
m.extra.scratch[0] = TRAVELLING;
m.extra.scratch[2] = 0;
m.extra.scratch[1] = 0;
}
/// `clearOpenedChestPos` (and so `stopOpen` at the next recheck).
fn golem_release(&mut self, m: &Mob) {
if let Some(key) = self.golem_openers.remove(&m.id) {
let keys = self.golem_container(key);
if !self.golem_chest_busy(m, &keys) {
self.golem_chest_sound(key, false);
}
}
}
fn golem_chest_sound(&mut self, key: Key, open: bool) {
let name = self.golem_block_name(key);
let base = name.trim_start_matches("minecraft:").trim_start_matches("waxed_");
let kind = if base.starts_with("weathered") {
"copper_chest_weathered"
} else if base.starts_with("oxidized") {
"copper_chest_oxidized"
} else if base.ends_with("copper_chest") {
"copper_chest"
} else {
"chest"
};
let side = if open { "open" } else { "close" };
let at = chest_center([key.0, key.1, key.2]);
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.audio
.play(&format!("minecraft:block.{kind}.{side}"), Some(at), 0.5, pitch);
}
fn golem_on_queuing(&mut self, m: &mut Mob) {
let Some(h) = m.extra.home else { return };
let keys = self.golem_container((h[0], h[1], h[2]));
if !self.golem_chest_busy(m, &keys) {
m.extra.scratch[0] = TRAVELLING;
m.extra.point = Some(chest_center(h));
}
}
fn golem_on_travel(&mut self, m: &mut Mob) {
let Some(h) = m.extra.home else { return };
let key = (h[0], h[1], h[2]);
let keys = self.golem_container(key);
let center = [
m.position.x,
m.position.y + m.kind.height / 2.0,
m.position.z,
];
if golem_within(m, 3.0, center, h) && self.golem_chest_busy(m, &keys) {
// startQueuing.
m.extra.point = None;
m.ai.nav.stop();
m.extra.scratch[0] = QUEUING;
} else if golem_within(m, self.golem_range(m), center, h) {
// startOnReachedTargetInteraction.
let slots = self.golem_slots(&keys);
let state = if held(m).is_none() {
if slots.iter().any(Option::is_some) {
PICKUP_ITEM
} else {
PICKUP_NO_ITEM
}
} else if slots.iter().all(Option::is_none)
|| slots
.iter()
.flatten()
.any(|s| held(m).is_some_and(|h| h.item == s.item))
{
PLACE_ITEM
} else {
PLACE_NO_ITEM
};
m.extra.scratch[2] = state;
m.extra.scratch[0] = INTERACTING;
} else {
m.extra.point = Some(chest_center(h));
}
}
fn golem_on_reached(&mut self, m: &mut Mob) {
let Some(h) = m.extra.home else { return };
let key = (h[0], h[1], h[2]);
let center = [
m.position.x,
m.position.y + m.kind.height / 2.0,
m.position.z,
];
if !golem_within(m, 2.0, center, h) {
self.golem_on_start_travelling(m);
return;
}
m.extra.scratch[1] += 1;
let ticks = m.extra.scratch[1];
// onTargetInteraction: stand still, and the reached interaction.
m.extra.point = None;
m.ai.nav.stop();
let (state, sound) = match m.extra.scratch[2] {
PICKUP_ITEM => (cg::GETTING_ITEM, Some("entity.copper_golem.no_item_get")),
PICKUP_NO_ITEM => (
cg::GETTING_NO_ITEM,
Some("entity.copper_golem.no_item_no_get"),
),
PLACE_ITEM => (cg::DROPPING_ITEM, Some("entity.copper_golem.item_drop")),
PLACE_NO_ITEM => (
cg::DROPPING_NO_ITEM,
Some("entity.copper_golem.item_no_drop"),
),
_ => (cg::IDLE, None),
};
if m.extra.scratch[2] != 0 {
if ticks == 1 {
let keys = self.golem_container(key);
if !self.golem_chest_busy(m, &keys) {
self.golem_chest_sound(key, true);
}
self.golem_openers.insert(m.id, key);
set_state(m, state);
}
if ticks == 9
&& let Some(sound) = sound
{
let at = [m.position.x, m.position.y, m.position.z];
self.audio.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
}
if ticks == 60 {
self.golem_release(m);
}
}
if ticks >= 60 {
let keys = self.golem_container(key);
if held(m).is_none() {
if self.golem_slots(&keys).iter().any(Option::is_some) {
// pickUpItems.
let stack = self.golem_pick_up(&keys);
set_held(m, stack);
self.golem_clear_memories(m);
} else {
self.golem_stop_targeting(m);
}
} else if self.golem_slots(&keys).iter().all(Option::is_none)
|| self
.golem_slots(&keys)
.iter()
.flatten()
.any(|s| held(m).is_some_and(|h| h.item == s.item))
{
// putDownItem.
let stack = held(m).cloned().unwrap_or_else(|| ItemStack::new("minecraft:air", 0));
let left = self.golem_put_down(&keys, stack);
let emptied = left.is_none();
set_held(m, left);
if emptied {
self.golem_clear_memories(m);
} else {
self.golem_stop_targeting(m);
}
} else {
self.golem_stop_targeting(m);
}
self.golem_on_start_travelling(m);
}
}
// ---- interactions -----------------------------------------------------
/// `CopperGolem.mobInteract`; true when handled.
pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool {
if self.mobs[index].species() != Species::CopperGolem || !self.mobs[index].alive() {
return false;
}
let at = {
let m = &self.mobs[index];
[m.position.x, m.position.y, m.position.z]
};
if item.is_empty() {
// Empty hand: the golem throws what it carries back.
let Some(h) = held(&self.mobs[index]).cloned() else {
return false;
};
set_held(&mut self.mobs[index], None);
let p = self.player.as_ref().map(|p| p.position);
let from = [at[0], at[1] + 0.9, at[2]];
let v = p.map_or([0.0; 3], |p| {
let d = [p.x - from[0], p.y + 1.0 - from[1], p.z - from[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
[d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]
});
self.spawn_item(h, from, v, 40);
return true;
}
let name = item;
let is_axe = name.ends_with("_axe");
let waxed = self.mobs[index].extra.vector[0] as i64 == -2;
if name == "minecraft:shears" && self.golem_shearable(index) {
let antenna = self.mobs[index].extra.legs.take();
self.audio
.play("minecraft:entity.copper_golem.shear", Some(at), 1.0, 1.0);
if let Some(a) = antenna {
self.spawn_item(ItemStack::new(&a, 1), [at[0], at[1] + 1.5, at[2]], [0.0, 0.2, 0.0], 10);
}
self.damage_held_tool();
return true;
}
if name == "minecraft:honeycomb" && !waxed {
self.mobs[index].extra.vector[0] = -2.0;
self.audio
.play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0);
self.consume_held();
return true;
}
if is_axe && waxed {
self.mobs[index].extra.vector[0] = -1.0;
self.audio
.play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0);
self.damage_held_tool();
return true;
}
if is_axe && self.mobs[index].extra.variant > 0 {
let m = &mut self.mobs[index];
m.extra.vector[0] = -1.0;
m.extra.variant = cg::weather_previous(m.extra.variant);
self.audio
.play("minecraft:item.axe.scrape", Some(at), 1.0, 1.0);
self.damage_held_tool();
return true;
}
false
}
fn golem_shearable(&self, index: usize) -> bool {
self.mobs[index].extra.legs.as_deref().is_some_and(|a| {
self.res
.items
.item_tags
.get("minecraft:shearable_from_copper_golem")
.is_some_and(|t| t.contains(a))
})
}
}
/// `isWithinTargetDistance`: the golem's box centred on `from` against the
/// chest's collision box inflated by `distance` (and half a block vertically).
fn golem_within(m: &Mob, distance: f64, from: [f64; 3], h: [i32; 3]) -> bool {
let hw = m.kind.width / 2.0;
let hh = m.kind.height / 2.0;
let lo = [
f64::from(h[0]) + 0.0625 - distance,
f64::from(h[1]) - 0.5,
f64::from(h[2]) + 0.0625 - distance,
];
let hi = [
f64::from(h[0]) + 0.9375 + distance,
f64::from(h[1]) + 0.875 + 0.5,
f64::from(h[2]) + 0.9375 + distance,
];
from[0] + hw > lo[0]
&& from[0] - hw < hi[0]
&& from[1] + hh > lo[1]
&& from[1] - hh < hi[1]
&& from[2] + hw > lo[2]
&& from[2] - hw < hi[2]
}
+115 -4
View File
@@ -30,8 +30,12 @@ pub(super) struct Creatures {
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
pub player_fire: i32,
pub pearl_cooldown: u32,
/// The wind charge's use cooldown (ticks).
pub wind_cooldown: u32,
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
pub elder_apparition: i32,
/// The wandering trader spawner's clock.
pub trader: super::wandering_trader::Spawner,
}
/// MobCategory caps (maxInstancesPerChunk with the 17x17 spawnable chunk area).
const CATEGORIES: [(&str, usize); 7] = [
@@ -121,6 +125,12 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
bed: (m.species() == Species::Villager)
.then_some(m.extra.bed)
.flatten(),
yaw: m.yaw,
velocity: m.velocity,
leash: m.extra.leash,
caravan: horizon_client::mobs::caravan::head_of(m),
delay: m.extra.ints[5],
hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)),
active_raid: horizon_client::mobs::raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => {
@@ -163,6 +173,8 @@ impl Game<'_> {
gold_armor: self.wearing_gold(),
hurt_by: self.player_hurt_by(),
last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)),
velocity: p.velocity,
yaw: self.yaw,
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
})
@@ -268,7 +280,11 @@ impl Game<'_> {
.spawn_mob(kind, at, true)
.ok_or_else(|| format!("unknown or unsupported mob {kind}"))?;
if baby && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.extra.age = -24000;
m.extra.age = if m.species() == Species::Sniffer {
horizon_client::mobs::sniffer::BABY_START_AGE
} else {
-24000
};
}
self.spawn_jockeys(id, false);
Ok(id)
@@ -301,6 +317,11 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"leash": m.extra.leash.map(|h| format!("{h:?}")),
"tame": m.extra.tame,
"temper": m.extra.variant3,
"chested": m.extra.chested,
"head": m.extra.head.as_deref(),
"warden": horizon_client::mobs::warden::describe(m),
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
"food_level": e.food_level,
@@ -659,6 +680,8 @@ impl Game<'_> {
self.spawn_generation_creatures(key.0, key.1);
}
self.tick_inhabited();
self.tick_leads();
self.tick_wandering_trader();
self.spawn_natural();
self.tick_patrol_spawner();
self.tick_raids();
@@ -699,6 +722,8 @@ impl Game<'_> {
self.tick_projectiles()?;
self.tick_fangs();
self.tick_allays();
self.tick_breeze_effects();
self.tick_sniffer_effects();
self.tick_player_effects();
self.piglin_pickups();
Ok(())
@@ -759,6 +784,11 @@ impl Game<'_> {
if m.species() == Species::Wither {
gear.push("minecraft:nether_star");
}
if species_drops_harness(m)
&& let Some(h) = m.extra.head.as_deref()
{
gear.push(h);
}
if m.extra.chested && horizon_client::mobs::equine::is_equine(m.species()) {
gear.push("minecraft:chest");
}
@@ -1072,6 +1102,7 @@ impl Game<'_> {
}
},
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound),
MobEvent::Vibration { from, to, ticks } => {
self.mob_vibration_particle(from, to, ticks)
}
@@ -1190,6 +1221,11 @@ impl Game<'_> {
q.extra.in_love = 0;
}
let q = self.mobs.iter().find(|m| m.id == partner).cloned();
// Sniffer.spawnChildFromBreeding: an egg instead of a baby.
if p.species() == Species::Sniffer {
self.lay_sniffer_egg(&p);
return;
}
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule.
@@ -1207,6 +1243,9 @@ impl Game<'_> {
let other = q.clone().unwrap_or_else(|| p.clone());
let mut r = self.world.random.clone();
horizon_client::mobs::equine::inherit(child, &p, &other, &mut r);
if horizon_client::mobs::llama::is_llama(p.species()) {
horizon_client::mobs::llama::offspring(child, &p, &other, &mut r);
}
// Horse.getBreedOffspring: coat from either parent or new.
if p.species() == Species::Horse && other.species() == Species::Horse {
let c = r.next_int_bound(9).unwrap_or(0);
@@ -1408,6 +1447,7 @@ impl Game<'_> {
self.creatures.player_fire -= 1;
}
}
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
if self.creatures.pearl_cooldown > 0 {
self.creatures.pearl_cooldown -= 1;
}
@@ -1425,6 +1465,7 @@ impl Game<'_> {
fn tick_projectiles(&mut self) -> Result<()> {
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
let mut hits = Vec::new();
let mut deflections: Vec<[f64; 3]> = Vec::new();
{
let mut targets: Vec<(Who, Aabb)> = self
.mobs
@@ -1443,16 +1484,55 @@ impl Game<'_> {
.into_iter()
.map(|(id, b)| (Who::Mob(id), b)),
);
let breezes: Vec<u32> = self
.mobs
.iter()
.filter(|m| m.alive() && m.species() == Species::Breeze)
.map(|m| m.id)
.collect();
let jitter = self.world.random.next_float();
let w = self.mob_world_base(&[]);
let pw = ProjWorld { w: &w, targets };
projectiles.retain_mut(|p| {
let (keep, hit) = p.tick(&pw);
let wind = matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
);
// Entity.deflection: a breeze turns every projectile but wind charges away.
if let Hit::Entity {
who: Who::Mob(id),
at,
} = hit
&& !wind
&& breezes.contains(&id)
{
super::wind::reverse(p, jitter);
deflections.push([at.x, at.y, at.z]);
return true;
}
// AbstractWindCharge.tick: out of the world's top it bursts.
if wind && keep && p.position.y > 350.0 {
hits.push((
p.clone(),
Hit::Block {
pos: [0; 3],
at: p.position,
face: [0; 3],
},
));
return false;
}
if hit != Hit::None {
hits.push((p.clone(), hit));
}
keep
});
}
for at in deflections {
self.audio
.play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0);
}
self.creatures.projectiles.append(&mut projectiles);
for (p, hit) in hits {
self.projectile_hit(&p, hit)?;
@@ -1468,6 +1548,12 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
if matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
) {
return self.wind_charge_hit(p, hit);
}
if let Hit::Entity {
who: Who::Mob(id), ..
} = hit
@@ -1832,6 +1918,13 @@ impl Game<'_> {
if self.name_mob(index) {
return Ok(true);
}
{
let item = self.held().map(|h| h.item.to_string()).unwrap_or_default();
if self.interact_leash(index, &item) {
self.swing_arm();
return Ok(true);
}
}
let held = self.held().cloned();
let item = held
.as_ref()
@@ -2107,7 +2200,11 @@ impl Game<'_> {
sound = Some("item.flintandsteel.use");
self.damage_held_tool();
}
_ if is_food && m.kind.flags.animal => {
// HappyGhast.canFallInLove: never, so only a ghastling takes food.
_ if is_food
&& m.kind.flags.animal
&& (species != Species::HappyGhast || m.is_baby()) =>
{
// Animal.mobInteract: breed adults, speed up babies.
if m.extra.age == 0 && m.extra.in_love <= 0 {
m.extra.in_love = 600;
@@ -2181,7 +2278,7 @@ impl Game<'_> {
}
Ok(true)
}
fn damage_held_tool(&mut self) {
pub(super) fn damage_held_tool(&mut self) {
if self.creative {
return;
}
@@ -2208,6 +2305,7 @@ impl Game<'_> {
self.creatures.pearl_cooldown = 20;
ProjectileKind::EnderPearl
}
"minecraft:wind_charge" => return self.throw_wind_charge(),
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
_ => return Ok(false),
};
@@ -2426,6 +2524,14 @@ impl Game<'_> {
}
continue;
}
// WindChargeRenderer.
if matches!(
a.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
) {
self.wind_charge_geometry(a, c, packed, out);
continue;
}
// WitherSkullRenderer: the skull model facing its flight.
if let Some(dangerous) = super::wither::skull_kind(a) {
static SKULL: std::sync::OnceLock<Option<horizon_client::mobs::Part>> =
@@ -2483,11 +2589,16 @@ impl Game<'_> {
}
}
}
fn species_drops_harness(m: &Mob) -> bool {
m.species() == Species::HappyGhast
}
fn eat_sound(s: Species) -> &'static str {
match s {
Species::Pig => "entity.pig.eat",
Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat",
Species::Llama | Species::TraderLlama => "entity.llama.eat",
Species::Goat => "entity.goat.eat",
Species::Sniffer => "entity.sniffer.eat",
Species::Fox => "entity.fox.eat",
Species::Cat => "entity.cat.eat",
Species::Panda => "entity.panda.eat",
@@ -2498,7 +2609,7 @@ fn eat_sound(s: Species) -> &'static str {
fn experience_reward(m: &Mob, random: &mut impl RandomSource) -> u32 {
use Species as S;
match m.species() {
S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute => 10,
S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute | S::Breeze => 10,
S::Slime | S::MagmaCube => m.extra.size.max(1) as u32,
S::Endermite => 3,
S::Bat
+1 -1
View File
@@ -78,7 +78,7 @@ impl Game<'_> {
true
}
/// `ServerExplosion.getSeenPercent` for an entity box.
fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
let ys = 1.0 / ((max[1] - min[1]) * 2.0 + 1.0);
let zs = 1.0 / ((max[2] - min[2]) * 2.0 + 1.0);
+111
View File
@@ -0,0 +1,111 @@
//! Happy ghasts on the game side: putting a harness on (and shearing it
//! off), riding, getting off on top, and the ghastling a dried ghast block
//! hatches.
use super::Game;
use horizon_client::{
items::ItemStack,
mobs::{MobEvent, happy_ghast},
};
use horizon_core::geometry::Vec3;
use horizon_world::registry::BlockStateId;
impl Game<'_> {
/// `HappyGhast.mobInteract`. Returns whether the click was used.
pub(super) fn interact_happy_ghast(&mut self, index: usize, item: &str) -> bool {
let m = &self.mobs[index];
if !m.alive() || Some(m.id) == self.riding {
return false;
}
if m.is_baby() {
// Animal.mobInteract: food grows it up.
return false;
}
let at = m.center();
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
let harnessed = m.extra.head.is_some();
// Equippable.equipOnInteract: a harness goes on a bare adult.
if item.ends_with("_harness") && item.starts_with("minecraft:") && !harnessed {
self.mobs[index].extra.head = Some(item.into());
self.audio
.play("minecraft:entity.happy_ghast.equip", Some(at), 1.0, 1.0);
self.consume_held();
return true;
}
// Equippable.canBeSheared: shears take the harness off again.
if item == "minecraft:shears"
&& harnessed
&& !sneaking
&& let Some(harness) = self.mobs[index].extra.head.take()
{
self.audio
.play("minecraft:entity.happy_ghast.unequip", Some(at), 1.0, 1.0);
self.spawn_item(ItemStack::new(&harness, 1), at, [0.0, 0.2, 0.0], 10);
self.damage_held_tool();
return true;
}
if harnessed && !sneaking {
// doPlayerRide.
let id = self.mobs[index].id;
self.break_leash(id, true, false);
let was_empty = self.mobs[index].rider.is_none();
self.yaw = self.mobs[index].yaw;
self.riding = Some(id);
self.mount.reset_jump();
if was_empty {
let down = happy_ghast::goggles(true, &self.mobs[index]);
let _ = self.handle_mob_events(vec![down]);
}
self.trigger_player("minecraft:started_riding");
return true;
}
false
}
/// Getting off lands on top of it.
pub(super) fn dismount_happy_ghast(&mut self, id: u32) {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return;
};
let top = Vec3::new(
m.position.x,
m.position.y + f64::from(m.height()),
m.position.z,
);
let up: MobEvent = happy_ghast::goggles(false, m);
if let Some(p) = self.player.as_mut() {
p.position = top;
p.velocity = Vec3::ZERO;
}
let _ = self.handle_mob_events(vec![up]);
}
/// `DriedGhastBlock.spawnGhastling`: a ghastling facing the way the block did.
pub(super) fn spawn_ghastling(&mut self, pos: [i32; 3], state: BlockStateId) {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
let facing = self
.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing").cloned());
let yaw = match facing.as_deref() {
Some("north") => 180.0,
Some("east") => 270.0,
Some("west") => 90.0,
_ => 0.0,
};
if let Some(id) = self.spawn_mob("minecraft:happy_ghast", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = -24000;
m.yaw = yaw;
m.body_yaw = yaw;
m.head_yaw = yaw;
let at = m.center();
self.audio
.play("minecraft:entity.ghastling.spawn", Some(at), 1.0, 1.0);
}
}
}
+55 -1
View File
@@ -4,6 +4,7 @@
//! golem. Players placing the pumpkin and dispensers share it.
use super::Game;
use horizon_client::Result;
use horizon_world::chunk::BlockState;
impl Game<'_> {
fn golem_block(&self, p: [i32; 3]) -> &str {
@@ -55,7 +56,7 @@ impl Game<'_> {
return Ok(());
}
let Some((kind, blocks, base)) = self.find_golem(head) else {
return Ok(());
return self.try_spawn_copper_golem(head);
};
for p in blocks {
let state = self.world.block(p[0], p[1], p[2]);
@@ -79,4 +80,57 @@ impl Game<'_> {
}
Ok(())
}
/// A pumpkin on a copper block: the block turns into the matching copper
/// chest (facing the pumpkin's way) and a copper golem appears where the
/// pumpkin was (`CarvedPumpkinBlock.spawnGolemInWorld` with
/// `CopperChestBlock.getFromCopperBlock`).
fn try_spawn_copper_golem(&mut self, head: [i32; 3]) -> Result<()> {
let below = [head[0], head[1] - 1, head[2]];
let registry = self.res.assets.registry;
let name = self.golem_block(below).to_string();
let Some(base) = name.strip_prefix("minecraft:") else {
return Ok(());
};
let waxed = base.strip_prefix("waxed_").unwrap_or(base);
if !matches!(
waxed,
"copper_block" | "exposed_copper" | "weathered_copper" | "oxidized_copper"
) {
return Ok(());
}
let chest = format!(
"minecraft:{}_chest",
base.strip_suffix("_block").unwrap_or(base)
);
let pumpkin = self.world.block(head[0], head[1], head[2]);
let facing = registry
.state(pumpkin)
.and_then(|s| s.properties.get("facing").cloned())
.unwrap_or_else(|| "north".into());
let chest_state = BlockState {
name: chest.clone(),
properties: [
("facing".to_string(), facing),
("type".to_string(), "single".to_string()),
("waterlogged".to_string(), "false".to_string()),
]
.into(),
};
let Some(chest_id) = registry
.id(&chest_state)
.or_else(|| registry.default_state(&chest))
else {
return Ok(());
};
self.destroy_particles(head, pumpkin);
self.level_set(head, self.world.air)?;
self.level_set(below, chest_id)?;
let at = [
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.05,
f64::from(head[2]) + 0.5,
];
let _ = self.spawn_mob("minecraft:copper_golem", at, false);
Ok(())
}
}
+450
View File
@@ -0,0 +1,450 @@
//! Leads on the game side: putting them on and taking them off mobs
//! (`Entity.interact`'s leash part), fence knots (`LeadItem.useOn` and
//! `LeashFenceKnotEntity.interact`), loading and saving who holds what,
//! breaking, and drawing the rope (`LeashFeatureRenderer`) and the knot.
use super::Game;
use horizon_client::{
items::ItemStack,
mesher::Vertex,
mobs::leash::{self, Holder, Pending},
};
use horizon_core::random::RandomSource;
use horizon_world::nbt::Tag;
/// `Vec3.yRot(angle)`.
fn rot_y(v: glam::DVec3, angle: f64) -> glam::DVec3 {
let (s, c) = (angle.sin(), angle.cos());
glam::DVec3::new(v.x * c + v.z * s, v.y, v.z * c - v.x * s)
}
fn pack_light(light: u8) -> u32 {
(u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8)
}
fn abgr(r: f32, g: f32, b: f32) -> u32 {
let c = |v: f32| (v * 255.0) as u32 & 255;
0xFF00_0000 | c(b) << 16 | c(g) << 8 | c(r)
}
impl Game<'_> {
fn lead_sound(&mut self, sound: &str, at: [f64; 3]) {
self.audio
.play(&format!("minecraft:item.lead.{sound}"), Some(at), 1.0, 1.0);
}
/// `Leashable.canHaveALeashAttachedTo` for the mob at `index` and a
/// holder whose box centre is `center`: within snapping range and
/// leashable.
fn can_attach_lead(&self, index: usize, center: glam::DVec3) -> bool {
let m = &self.mobs[index];
if !leash::can_be_leashed(m) || !m.alive() {
return false;
}
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
let mine = glam::DVec3::new(
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
);
mine.distance(center) <= leash::SNAP
}
fn player_center(&self) -> glam::DVec3 {
self.player.as_ref().map_or(glam::DVec3::ZERO, |p| {
glam::DVec3::new(
p.position.x,
p.position.y + f64::from(p.dimensions.height) / 2.0,
p.position.z,
)
})
}
/// The mobs on the player's lead within 32 blocks of a point.
fn player_leashed(&self, around: glam::DVec3) -> Vec<usize> {
(0..self.mobs.len())
.filter(|&i| {
let m = &self.mobs[i];
m.extra.leash == Some(Holder::Player)
&& (m.position.x - around.x).abs() <= 16.0
&& (m.position.y - around.y).abs() <= 16.0
&& (m.position.z - around.z).abs() <= 16.0
})
.collect()
}
fn drop_lead_item(&mut self, at: [f64; 3]) {
let r = &mut self.world.random;
let v = [
f64::from(r.next_float()) * 0.2 - 0.1,
0.2,
f64::from(r.next_float()) * 0.2 - 0.1,
];
self.spawn_item(ItemStack::new("minecraft:lead", 1), at, v, 10);
}
/// `Leashable.dropLeash` / `removeLeash`: the lead falls as an item.
pub(super) fn break_leash(&mut self, id: u32, drop: bool, sound: bool) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
};
if m.extra.leash.take().is_none() {
return;
}
let at = [m.position.x, m.position.y, m.position.z];
if sound {
self.lead_sound("break", at);
}
if drop {
self.drop_lead_item(at);
}
}
/// Holders read from a save become real once the entity is found; a
/// holder that never shows up drops the lead after 100 ticks.
pub(super) fn tick_leads(&mut self) {
let player_uuid = self.level.player_uuid.unwrap_or([0, 0, 0, 1]);
for i in 0..self.mobs.len() {
let Some(pending) = self.mobs[i].extra.leash_pending else {
continue;
};
let holder = match pending {
Pending::Knot(p) => Some(Holder::Knot(p)),
Pending::Uuid(u) if u == player_uuid => Some(Holder::Player),
Pending::Uuid(u) => self.mob_by_uuid(u).map(Holder::Mob),
};
let m = &mut self.mobs[i];
if let Some(h) = holder {
m.extra.leash = Some(h);
m.extra.leash_pending = None;
} else if m.age > 100 {
m.extra.leash_pending = None;
let at = [m.position.x, m.position.y, m.position.z];
self.drop_lead_item(at);
}
}
}
/// The `leash` tag of a mob about to be saved.
pub(super) fn write_leash(&mut self, tag: &mut Tag, index: usize) {
let Tag::Compound(map) = tag else { return };
map.remove(&"leash".into());
let m = &self.mobs[index];
let holder = m.extra.leash;
let pending = m.extra.leash_pending;
let uuid = match (holder, pending) {
(Some(Holder::Player), _) => Some(self.level.player_uuid.unwrap_or([0, 0, 0, 1])),
(Some(Holder::Mob(id)), _) => Some(self.mob_uuid(id)),
(_, Some(Pending::Uuid(u))) => Some(u),
_ => None,
};
let value = match (holder, pending) {
(Some(h), _) => leash::to_nbt(h, uuid),
(None, Some(Pending::Knot(p))) => leash::to_nbt(Holder::Knot(p), None),
(None, Some(Pending::Uuid(u))) => leash::to_nbt(Holder::Player, Some(u)),
_ => None,
};
if let Some(v) = value {
map.insert("leash".into(), v);
}
}
/// `Entity.interact`'s leash part for a mob. Returns whether it was used.
pub(super) fn interact_leash(&mut self, index: usize, item: &str) -> bool {
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
let id = self.mobs[index].id;
let at = self.mobs[index].center();
if !self.mobs[index].alive() {
return false;
}
// Sneaking with mobs in hand: tie them to this one.
if sneaking && leash::can_be_leashed(&self.mobs[index]) && !self.mobs[index].is_baby() {
let b = self.mobs[index].bounds();
let (lo, hi) = (b.min_position(), b.max_position());
let center = glam::DVec3::new(
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
);
let held = self.player_leashed(center);
let mut any = false;
for j in held {
if j != index && self.can_attach_lead(j, center) {
self.mobs[j].extra.leash = Some(Holder::Mob(id));
any = true;
}
}
if any {
self.lead_sound("tied", at);
return true;
}
}
if item == "minecraft:shears" {
let mut dropped = false;
if self.mobs[index].extra.leash.is_some() {
self.break_leash(id, true, false);
dropped = true;
}
let others: Vec<u32> = self
.mobs
.iter()
.filter(|m| m.extra.leash == Some(Holder::Mob(id)))
.map(|m| m.id)
.collect();
for o in others {
self.break_leash(o, true, false);
dropped = true;
}
if dropped {
self.audio
.play("minecraft:item.shears.snip", Some(at), 1.0, 1.0);
self.damage_held_tool();
return true;
}
}
if self.mobs[index].extra.leash == Some(Holder::Player) {
let creative = self.creative;
self.break_leash(id, !creative, false);
self.lead_sound("untied", at);
return true;
}
if item == "minecraft:lead" {
let center = self.player_center();
if self.can_attach_lead(index, center) {
if self.mobs[index].extra.leash.is_some() {
self.break_leash(id, true, false);
}
self.mobs[index].extra.leash = Some(Holder::Player);
self.lead_sound("tied", at);
// The lead is always used up.
if let Some(stack) = self.inventory[self.selected].as_mut() {
stack.count -= 1;
if stack.count == 0 {
self.inventory[self.selected] = None;
}
}
return true;
}
}
false
}
/// `LeadItem.useOn` and `LeashFenceKnotEntity.interact` on a fence.
pub(super) fn interact_knot(&mut self) -> bool {
let Some(hit) = self.pick() else {
return false;
};
let name = self
.res
.facts
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
if !self
.res
.items
.block_tags
.get("minecraft:fences")
.is_some_and(|s| s.contains(&*name.name))
{
return false;
}
let knot_pos = hit.pos;
let knot = leash::knot_state(knot_pos).center;
let center = glam::DVec3::new(knot.x, knot.y, knot.z);
let at = [center.x, center.y, center.z];
let existing: Vec<usize> = (0..self.mobs.len())
.filter(|&i| self.mobs[i].extra.leash == Some(Holder::Knot(knot_pos)))
.collect();
let held_item = self.held().map(|s| s.item.to_string());
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
// Shears snip every lead on the knot.
if held_item.as_deref() == Some("minecraft:shears") && !existing.is_empty() {
for i in existing {
let id = self.mobs[i].id;
self.break_leash(id, true, false);
}
self.audio
.play("minecraft:item.shears.snip", Some(at), 1.0, 1.0);
self.damage_held_tool();
return true;
}
let in_hand = self.player_leashed(center);
// The knot is only made for the lead item, or when mobs already hang on it.
if held_item.as_deref() != Some("minecraft:lead")
&& existing.is_empty()
&& in_hand.is_empty()
{
return false;
}
let mut attached = false;
for j in in_hand {
if self.can_attach_lead(j, center) {
self.mobs[j].extra.leash = Some(Holder::Knot(knot_pos));
attached = true;
}
}
if !attached && !sneaking {
let player = self.player_center();
for i in existing {
if self.can_attach_lead(i, player) {
self.mobs[i].extra.leash = Some(Holder::Player);
attached = true;
}
}
}
if attached {
self.lead_sound("tied", at);
self.swing_arm();
}
attached
}
/// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots.
pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.res.atlas;
let white = atlas.font.white();
let uv = [
[white.u0, white.v1],
[white.u1, white.v1],
[white.u1, white.v0],
[white.u0, white.v0],
];
let lerp3 = |a: horizon_core::geometry::Vec3, b: horizon_core::geometry::Vec3| {
glam::DVec3::new(
a.x + (b.x - a.x) * alpha,
a.y + (b.y - a.y) * alpha,
a.z + (b.z - a.z) * alpha,
)
};
let mut knots: Vec<[i32; 3]> = Vec::new();
for m in &self.mobs {
let Some(holder) = m.extra.leash else {
continue;
};
let body = f64::from(
m.previous_body_yaw
+ horizon_client::mobs::living::wrap(m.body_yaw - m.previous_body_yaw)
* alpha as f32,
)
.to_radians();
let offset = leash::leash_offset(m);
let offset = rot_y(glam::DVec3::from_array(offset), -body);
let start = lerp3(m.previous, m.position) + offset;
let end = match holder {
Holder::Knot(p) => {
if !knots.contains(&p) {
knots.push(p);
}
glam::DVec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.375 + 0.2,
f64::from(p[2]) + 0.5,
)
}
Holder::Mob(id) => {
let Some(o) = self.mobs.iter().find(|o| o.id == id) else {
continue;
};
lerp3(o.previous, o.position) + glam::DVec3::new(0.0, o.eye_height() * 0.7, 0.0)
}
Holder::Player => {
let Some(p) = self.player.as_ref() else {
continue;
};
self.player_rope_hold(p, alpha)
}
};
let light = |p: glam::DVec3| {
self.world
.light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32)
};
// Block and sky light averaged between the two ends.
let (a, b) = (light(start), light(end));
let packed = pack_light((((a >> 4) + (b >> 4)) / 2) << 4 | (((a & 15) + (b & 15)) / 2));
let d = end - start;
let k = 1.0 / (d.x * d.x + d.z * d.z).sqrt().max(1e-6) * 0.05 / 2.0;
let (dx_off, dz_off) = (d.z * k, d.x * k);
let point = |step: i32, fudge: f64| {
let progress = f64::from(step) / 24.0;
let y = if d.y > 0.0 {
d.y * progress * progress
} else {
d.y - d.y * (1.0 - progress) * (1.0 - progress)
};
let base = start + glam::DVec3::new(d.x * progress, y, d.z * progress);
(
base + glam::DVec3::new(-dx_off, fudge, dz_off),
base + glam::DVec3::new(dx_off, 0.05 - fudge, -dz_off),
)
};
for (fudge, backwards) in [(0.05, false), (0.0, true)] {
for step in 0..24 {
let shade = |s: i32| {
let dark = s % 2 == i32::from(backwards);
let f = if dark { 0.7 } else { 1.0 };
abgr(0.5 * f, 0.4 * f, 0.3 * f)
};
let (a0, b0) = point(step, fudge);
let (a1, b1) = point(step + 1, fudge);
let color = shade(step);
// Both faces: the leash is not culled.
for quad in [[a0, b0, b1, a1], [a1, b1, b0, a0]] {
for (v, uv) in quad.iter().zip(uv) {
out.push(Vertex {
pos: (*v - camera).as_vec3().to_array(),
uv,
layer: 0,
color,
light: packed,
});
}
}
}
}
}
// The knots: a 6 by 8 by 6 pixel block on the fence post.
static KNOT: std::sync::OnceLock<Option<horizon_client::mobs::Part>> =
std::sync::OnceLock::new();
let model = KNOT.get_or_init(|| {
horizon_client::mobs::load_model(&self.options.resources, "minecraft:leash_knot#main")
});
let Some(model) = model else { return };
let Some(r) = atlas.sprites.get("entity/lead_knot/lead_knot").copied() else {
return;
};
for p in knots {
let state = leash::knot_state(p);
let at =
glam::DVec3::new(state.position.x, state.position.y, state.position.z) - camera;
let base = glam::Mat4::from_translation(at.as_vec3())
* glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
let poses = horizon_client::mobs::anim::Poses::new(model);
let light = pack_light(self.world.light(p[0], p[1], p[2]));
horizon_client::mobs::render::draw(
model,
base,
&poses,
[r.u0, r.v0, r.u1, r.v1],
0xFFFF_FFFF,
light,
0,
out,
);
}
}
/// `Player.getRopeHoldPosition` (and `LocalPlayer`'s in first person).
fn player_rope_hold(
&self,
p: &horizon_client::motion::PlayerMotion,
alpha: f64,
) -> glam::DVec3 {
let pos = glam::DVec3::new(p.position.x, p.position.y, p.position.z);
let _ = alpha;
if self.camera_type.first_person() {
let (yaw, pitch) = (
f64::from(self.yaw.to_radians()),
f64::from(self.pitch.to_radians()),
);
let v = glam::DVec3::new(-0.39, -0.6, 0.3);
// Vec3.xRot(-pitch) then yRot(-yaw).
let (s, c) = ((-pitch).sin(), (-pitch).cos());
let v = glam::DVec3::new(v.x, v.y * c + v.z * s, v.z * c - v.y * s);
let eye = pos + glam::DVec3::new(0.0, f64::from(p.dimensions.eye_height), 0.0);
return rot_y(v, -yaw) + eye;
}
let yaw = f64::from(self.yaw.to_radians());
let crouching = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
let v = glam::DVec3::new(
-0.22,
f64::from(p.dimensions.height) - 1.0,
if crouching { -0.2 } else { 0.07 },
);
pos + rot_y(v, -yaw)
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Llamas on the game side: `AbstractChestedHorse.mobInteract` and
//! `Llama.handleEating` (wheat and hay), chests, carpets, shearing a carpet
//! off and riding.
use super::Game;
use horizon_client::{
items::ItemStack,
mobs::{MobEvent, equine, llama},
};
use horizon_core::random::RandomSource;
impl Game<'_> {
fn llama_sound(&mut self, index: usize, sound: &str, volume: f32) {
let at = self.mobs[index].center();
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0;
self.audio
.play(&format!("minecraft:{sound}"), Some(at), volume, pitch);
}
/// `Llama.handleEating`: wheat and hay bales heal, age up a baby, raise
/// the temper and, from a hay bale, put a tame adult in love.
fn feed_llama(&mut self, index: usize, item: &str) -> bool {
let (age_up, temper, heal) = match item {
"minecraft:wheat" => (10, 3, 2.0),
"minecraft:hay_block" => (90, 6, 10.0),
_ => return false,
};
let m = &mut self.mobs[index];
let mut used = false;
if item == "minecraft:hay_block" && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0
{
m.extra.in_love = 600;
m.extra.love_player = true;
used = true;
}
if m.health < m.attrs.max_health {
m.health = (m.health + heal).min(m.attrs.max_health);
used = true;
}
let mut happy = false;
if m.is_baby() && !m.extra.age_locked {
m.extra.age = (m.extra.age + age_up * 20).min(0);
used = true;
happy = true;
}
if (used || !m.extra.tame) && i32::from(m.extra.variant3) < llama::MAX_TEMPER {
m.extra.variant3 = (i32::from(m.extra.variant3) + temper).min(llama::MAX_TEMPER) as u8;
used = true;
}
let at = m.center();
if happy {
let _ = self.handle_mob_events(vec![MobEvent::Particles {
kind: "happy_villager",
at,
count: 1,
}]);
}
if !used {
return false;
}
self.llama_sound(index, "entity.llama.eat", 1.0);
self.consume_held();
true
}
/// `AbstractChestedHorse.mobInteract` and `AbstractHorse.mobInteract` for
/// llamas and trader llamas. Returns whether the click was used.
pub(super) fn interact_llama(&mut self, index: usize, item: &str) -> bool {
let m = &self.mobs[index];
if !m.alive() || Some(m.id) == self.riding {
return false;
}
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
let (baby, tamed, vehicle) = (m.is_baby(), m.extra.tame, m.rider.is_some());
let open_inventory = !baby && tamed && sneaking;
if !vehicle && !open_inventory && !item.is_empty() {
if self.mobs[index].kind.food.iter().any(|f| f == item) {
return self.feed_llama(index, item);
}
if !tamed {
let mut events = Vec::new();
equine::make_mad(&mut self.mobs[index], &mut events);
let _ = self.handle_mob_events(events);
return true;
}
if !self.mobs[index].extra.chested && item == "minecraft:chest" {
self.mobs[index].extra.chested = true;
self.llama_sound(index, "entity.llama.chest", 1.0);
self.consume_held();
return true;
}
}
// AbstractHorse.mobInteract.
if vehicle || baby {
return false;
}
if tamed && sneaking {
// The horse inventory screen is not available yet.
return true;
}
let m = &self.mobs[index];
let carpet = |i: &str| i.ends_with("_carpet") && i.starts_with("minecraft:");
if !item.is_empty() {
if item == "minecraft:shears" && m.extra.head.as_deref().is_some_and(carpet) {
// Equippable.canBeSheared: the carpet comes off.
let at = m.center();
let carpet = self.mobs[index].extra.head.take().unwrap_or_default();
self.audio
.play("minecraft:item.llama_carpet.unequip", Some(at), 1.0, 1.0);
self.spawn_item(ItemStack::new(&carpet, 1), at, [0.0, 0.2, 0.0], 10);
self.damage_held_tool();
return true;
}
if carpet(item) && m.extra.head.is_none() {
self.mobs[index].extra.head = Some(item.into());
self.llama_sound(index, "entity.llama.swag", 1.0);
self.consume_held();
return true;
}
}
// TraderLlama.doPlayerRide: not while a wandering trader leads it.
if self.is_led_by_trader(index) {
return true;
}
// doPlayerRide; mounting drops a lead.
let id = self.mobs[index].id;
self.break_leash(id, true, false);
let m = &mut self.mobs[index];
m.extra.flag = false;
m.extra.counter = 0;
self.yaw = m.yaw;
self.riding = Some(m.id);
self.mount.reset_jump();
self.trigger_player("minecraft:started_riding");
true
}
fn is_led_by_trader(&self, index: usize) -> bool {
let m = &self.mobs[index];
m.species() == horizon_client::mobs::Species::TraderLlama
&& matches!(
m.extra.leash,
Some(horizon_client::mobs::leash::Holder::Mob(id))
if self.mobs.iter().any(|o| o.id == id
&& o.species() == horizon_client::mobs::Species::WanderingTrader)
)
}
}
+42
View File
@@ -17,6 +17,7 @@ fn seat(s: Species) -> f64 {
Species::Pig => 0.86875,
Species::Strider => 1.7,
Species::Horse => 1.44375,
Species::Llama | Species::TraderLlama => 1.37,
Species::Donkey => 1.1125,
Species::Mule => 1.2125,
_ => 1.31875,
@@ -31,6 +32,12 @@ pub(super) struct MountState {
pub(super) jump_scale: f32,
was_jumping: bool,
}
impl MountState {
pub(super) fn reset_jump(&mut self) {
self.jump_ticks = 0;
self.jump_scale = 0.0;
}
}
impl Game<'_> {
fn mount_index(&self) -> Option<usize> {
let id = self.riding?;
@@ -96,6 +103,12 @@ impl Game<'_> {
if matches!(species, Species::Pig | Species::Strider) {
return self.interact_steerable(index, item);
}
if horizon_client::mobs::llama::is_llama(species) {
return self.interact_llama(index, item);
}
if species == Species::HappyGhast {
return self.interact_happy_ghast(index, item);
}
if !equine::is_equine(species) || !m.alive() || Some(m.id) == self.riding {
return false;
}
@@ -289,6 +302,7 @@ impl Game<'_> {
jump: if jump > 0.0 { jump } else { pending },
steer,
sprint: self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
jumping: keys.jump,
});
true
}
@@ -315,6 +329,29 @@ impl Game<'_> {
m.position.z + f64::from(0.5 * scale * yaw.cos()),
);
}
if m.species() == Species::HappyGhast {
// The first passenger attachment (0, 4, 1.7) of the harnessed back.
let yaw = f64::from(m.yaw.to_radians());
at = Vec3::new(
m.position.x - 1.7 * yaw.sin(),
m.position.y + 4.0 - 0.6,
m.position.z + 1.7 * yaw.cos(),
);
}
if horizon_client::mobs::llama::is_llama(m.species()) {
// The passenger attachment (0, 1.37, -0.3), half of it for a baby.
let (y, z) = if m.is_baby() {
(0.81, -0.15)
} else {
(1.37, -0.3)
};
let yaw = f64::from(m.yaw.to_radians());
at = Vec3::new(
m.position.x - z * yaw.sin(),
m.position.y + y - 0.6,
m.position.z + z * yaw.cos(),
);
}
if let Some(p) = self.player.as_mut() {
self.previous_position = p.position;
p.position = at;
@@ -331,6 +368,11 @@ impl Game<'_> {
return;
};
m.rider = None;
if m.species() == Species::HappyGhast {
let id = m.id;
self.dismount_happy_ghast(id);
return;
}
let yaw = m.yaw.to_radians();
let side = Vec3::new(f64::from(yaw.cos()), 0.0, f64::from(yaw.sin()));
let w = f64::from(m.width()) / 2.0 + 0.4;
+13
View File
@@ -352,6 +352,7 @@ impl Game<'_> {
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));
self.write_leash(&mut tag, i);
let riders: Vec<usize> = (0..self.mobs.len())
.filter(|&j| self.mobs[j].extra.mount == Some(id) && self.mobs[j].alive())
.collect();
@@ -376,6 +377,18 @@ impl Game<'_> {
}
self.persist.raw.insert(id, tag);
}
/// The mob that was loaded or saved with a UUID.
pub(super) fn mob_by_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
self.persist
.uuids
.iter()
.find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id))
.map(|(id, _)| *id)
}
/// A mob's UUID, made up for new ones.
pub(super) fn mob_uuid(&mut self, id: u32) -> [i32; 4] {
self.uuid_for(id)
}
pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] {
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
}
@@ -32,6 +32,7 @@ pub(super) struct ScoreState {
pub board: Scoreboard,
/// `/data ... storage`.
pub storage: horizon_client::command_storage::CommandStorage,
pub stopwatches: horizon_client::stopwatches::Stopwatches,
loaded: bool,
recorded: Recorded,
}
@@ -62,6 +63,7 @@ impl Game<'_> {
{
self.border = horizon_client::worldborder::WorldBorder::unpack(data);
}
self.score.stopwatches = horizon_client::stopwatches::Stopwatches::load(&self.world_root);
self.sync_score_registries();
}
pub(super) fn save_scoreboard(&mut self) {
@@ -69,6 +71,7 @@ impl Game<'_> {
return;
}
self.score.storage.save(&self.world_root);
self.score.stopwatches.save(&self.world_root);
if self.border != horizon_client::worldborder::WorldBorder::default() {
let _ = save::write_dat(
&self.world_root.join("data/minecraft/world_border.dat"),
@@ -99,6 +102,7 @@ impl Game<'_> {
reg.teams = board.teams.iter().map(|t| t.name.clone()).collect();
reg.tracked = board.tracked();
reg.storages = self.score.storage.keys();
reg.stopwatches = self.score.stopwatches.ids();
}
// ---- score holders ---------------------------------------------------
@@ -0,0 +1,87 @@
//! Sniffers on the game side: the egg a bred pair lays
//! (`Sniffer.spawnChildFromBreeding`), the snifflet that hatches from an
//! egg block (`SnifferEggBlock.tick`) and the dust and sound of digging.
use super::Game;
use horizon_client::{
items::ItemStack,
mobs::{Mob, Species, sniffer},
particles::Particle,
};
use horizon_core::random::RandomSource;
impl Game<'_> {
/// An egg item at the parent, a plop and some experience.
pub(super) fn lay_sniffer_egg(&mut self, parent: &Mob) {
let at = [parent.position.x, parent.position.y, parent.position.z];
self.spawn_item(
ItemStack::new("minecraft:sniffer_egg", 1),
at,
[0.0, 0.2, 0.0],
10,
);
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 0.5;
self.audio
.play("minecraft:block.sniffer_egg.plop", Some(at), 1.0, pitch);
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
self.spawn_orbs(at, xp);
}
/// A snifflet where the egg was.
pub(super) fn hatch_sniffer(&mut self, pos: [i32; 3]) {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
if let Some(id) = self.spawn_mob("minecraft:sniffer", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = sniffer::BABY_START_AGE;
let yaw = self.world.random.next_float() * 360.0 - 180.0;
m.yaw = yaw;
m.body_yaw = yaw;
m.head_yaw = yaw;
}
}
/// `Sniffer.emitDiggingParticles`: block dust and the digging sound
/// between the 1.7th and the 6th second of the digging animation.
pub(super) fn tick_sniffer_effects(&mut self) {
let Some(camera) = self.player.as_ref().map(|p| p.position) else {
return;
};
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Sniffer
|| !m.alive()
|| !sniffer::digging(m)
|| m.position.distance_squared(camera) > 32.0 * 32.0
{
continue;
}
let Some(ms) = m.anim.states[3].millis(m.age as f32) else {
continue;
};
if ms <= 1700 || ms >= 6000 {
continue;
}
let head = sniffer::head_block(m);
let below = self.world.block(head[0], head[1] - 1, head[2]);
let Some((sprite, tint)) = self.particle_sprite(below) else {
continue;
};
let at = [
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5 - f64::from(0.65_f32),
f64::from(head[2]) + 0.5,
];
for _ in 0..30 {
let particle =
Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint);
self.particles.push(particle);
}
if self.mobs[i].age.is_multiple_of(10) {
self.audio
.play("minecraft:entity.sniffer.digging", Some(at), 0.5, 0.5);
}
}
}
}
@@ -184,6 +184,8 @@ impl Game<'_> {
mob: Some(m.id),
name: m.custom_name.clone(),
};
// setTradingPlayer: a wandering trader stands still while trading.
self.mobs[index].extra.flag2 = species == Species::WanderingTrader;
self.open_merchant_state(state);
Ok(true)
}
@@ -197,6 +199,7 @@ impl Game<'_> {
if state.progress() {
m.extra.variant3 = state.level.clamp(1, 5) as u8;
}
m.extra.flag2 = false;
let trade = m.extra.trade.get_or_insert_default();
trade.xp = state.xp;
trade.offers = state.offers.clone();
@@ -0,0 +1,245 @@
//! `WanderingTraderSpawner`: every 1200 ticks the spawn delay counts down;
//! when it runs out a trader may appear near the player (or the nearest
//! bell), bringing two llamas on leads, and wanders off after two days.
use super::{Dim, Game, creatures::Creatures};
use horizon_client::{
mobs::{Species, leash::Holder, spawning, trader},
save::{read_dat, write_dat},
};
use horizon_core::random::RandomSource;
use horizon_world::nbt::Tag;
const TICK_DELAY: i32 = 1200;
const SPAWN_DELAY: i32 = 24000;
const MIN_CHANCE: i32 = 25;
const MAX_CHANCE: i32 = 75;
const ATTEMPTS: i32 = 10;
/// The spawner's clock and the `WanderingTraderData` saved with the world.
pub(super) struct Spawner {
tick_delay: i32,
spawn_delay: i32,
chance: i32,
loaded: bool,
dirty: bool,
}
impl Default for Spawner {
fn default() -> Self {
Self {
tick_delay: TICK_DELAY,
spawn_delay: SPAWN_DELAY,
chance: MIN_CHANCE,
loaded: false,
dirty: false,
}
}
}
impl Creatures {
/// A fresh spawner for a newly opened world.
pub(super) fn reset_trader(&mut self) {
self.trader = Spawner::default();
}
}
impl Game<'_> {
fn trader_path(&self) -> std::path::PathBuf {
self.world_root
.join("data")
.join("minecraft")
.join("wandering_trader.dat")
}
fn load_trader_data(&mut self) {
if self.creatures.trader.loaded {
return;
}
let tag = read_dat(&self.trader_path());
let data = tag.as_ref().and_then(|t| t.get("data"));
let get = |k: &str, d: i32| match data.and_then(|d| d.get(k)) {
Some(Tag::Int(v)) => *v,
_ => d,
};
let t = &mut self.creatures.trader;
t.spawn_delay = get("spawn_delay", SPAWN_DELAY);
t.chance = get("spawn_chance", MIN_CHANCE);
t.loaded = true;
}
pub(super) fn save_wandering_trader(&mut self) {
if !self.creatures.trader.loaded || !self.creatures.trader.dirty {
return;
}
let t = &self.creatures.trader;
let tag = Tag::compound([
(
"data",
Tag::compound([
("spawn_delay", Tag::Int(t.spawn_delay)),
("spawn_chance", Tag::Int(t.chance)),
]),
),
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
]);
if write_dat(&self.trader_path(), tag).is_ok() {
self.creatures.trader.dirty = false;
}
}
/// `WanderingTraderSpawner.tick`.
pub(super) fn tick_wandering_trader(&mut self) {
if self.dim != Dim::Overworld
|| self.player.is_none()
|| !self.ui.rules.bool("spawn_wandering_traders")
{
return;
}
self.load_trader_data();
self.creatures.trader.tick_delay -= 1;
if self.creatures.trader.tick_delay > 0 {
return;
}
self.creatures.trader.tick_delay = TICK_DELAY;
let t = &mut self.creatures.trader;
t.spawn_delay -= TICK_DELAY;
t.dirty = true;
if t.spawn_delay > 0 {
return;
}
t.spawn_delay = SPAWN_DELAY;
let chance = t.chance;
t.chance = (chance + 25).clamp(MIN_CHANCE, MAX_CHANCE);
if self.world.random.next_int_bound(100).unwrap_or(100) <= chance && self.spawn_trader() {
self.creatures.trader.chance = MIN_CHANCE;
}
}
/// `WanderingTraderSpawner.spawn`.
fn spawn_trader(&mut self) -> bool {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
return true;
};
if self.world.random.next_int_bound(10).unwrap_or(1) != 0 {
return false;
}
let player_pos = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
let reference = self.nearest_bell(player_pos, 48).unwrap_or(player_pos);
let Some(pos) = self.find_trader_spawn_near(reference, 48) else {
return false;
};
if !self.trader_has_space(pos) {
return false;
}
let biome = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)).map(|c| {
self.res
.biomes
.get(c.biome(pos[0], pos[1], pos[2]))
.name
.clone()
});
if biome.is_some_and(|b| {
self.res
.mob_data
.biome_has("minecraft:without_wandering_trader_spawns", &b)
}) {
return false;
}
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
let Some(id) = self.spawn_mob("minecraft:wandering_trader", at, true) else {
return false;
};
for _ in 0..2 {
self.spawn_trader_llama(id, 4);
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.extra.ints[5] = trader::DESPAWN_DELAY;
m.extra.point = Some([
f64::from(reference[0]),
f64::from(reference[1]),
f64::from(reference[2]),
]);
m.extra.home = Some(reference);
m.extra.ints[4] = 16;
}
true
}
/// `tryToSpawnLlamaFor`: a trader llama near the trader, on its lead.
fn spawn_trader_llama(&mut self, trader: u32, radius: i32) {
let Some(at) = self.mobs.iter().find(|m| m.id == trader).map(|m| {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}) else {
return;
};
let Some(pos) = self.find_trader_spawn_near(at, radius) else {
return;
};
let spot = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
if let Some(id) = self.spawn_mob("minecraft:trader_llama", spot, false)
&& let Some(l) = self.mobs.iter_mut().find(|m| m.id == id)
{
// EntitySpawnReason.EVENT: grown up.
l.extra.age = 0;
l.extra.leash = Some(Holder::Mob(trader));
}
}
/// `findSpawnPositionNear`: ten tries at a column near the reference
/// where the trader could stand.
fn find_trader_spawn_near(&mut self, reference: [i32; 3], radius: i32) -> Option<[i32; 3]> {
for _ in 0..ATTEMPTS {
let x =
reference[0] + self.world.random.next_int_bound(radius * 2).unwrap_or(0) - radius;
let z =
reference[2] + self.world.random.next_int_bound(radius * 2).unwrap_or(0) - radius;
if !self.world.loaded(x, z) {
continue;
}
let y = self.motion_top(x, z);
let w = self.mob_world_base(&[]);
if spawning::placement_ok(Species::WanderingTrader, &w, x, y, z) {
return Some([x, y, z]);
}
}
None
}
/// `hasEnoughSpace`: no collision in the 2 by 3 by 2 box.
fn trader_has_space(&self, pos: [i32; 3]) -> bool {
(0..=1).all(|dx| {
(0..=2).all(|dy| {
(0..=1).all(|dz| {
!self
.res
.facts
.get(self.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz))
.full_collision
})
})
})
}
/// The closest bell (`PoiTypes.MEETING`) within `range` blocks.
fn nearest_bell(&self, from: [i32; 3], range: i32) -> Option<[i32; 3]> {
let mut best: Option<([i32; 3], i32)> = None;
for x in from[0] - range..=from[0] + range {
for z in from[2] - range..=from[2] + range {
if !self.world.loaded(x, z) {
continue;
}
for y in (from[1] - range).max(horizon_client::chunk::MIN_Y)..=from[1] + range {
if &*self.res.facts.get(self.world.block(x, y, z)).name != "minecraft:bell" {
continue;
}
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if best.is_none_or(|b| d < b.1) {
best = Some(([x, y, z], d));
}
}
}
}
best.map(|b| b.0)
}
}
+503
View File
@@ -0,0 +1,503 @@
//! Wind charges: the item a player throws (`WindChargeItem`), the charges
//! breezes shoot, and the burst they make (`ServerExplosion` with
//! `TRIGGER_BLOCK`: no damage, only knockback and the blocks that react).
use super::Game;
use horizon_client::{
Result,
mobs::{Damage, DamageKind, Species, Who},
particles::{ParticleOptions, ParticleType},
projectiles::{Hit, Projectile, ProjectileKind},
};
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::level::PlayerContext;
use std::collections::BTreeSet;
/// `WindCharge.RADIUS` and the knockback multiplier of its damage calculator.
const PLAYER_RADIUS: f32 = 1.2;
const PLAYER_KNOCKBACK: f32 = 1.22;
/// `BreezeWindCharge.RADIUS`.
const BREEZE_RADIUS: f32 = 3.0;
/// `Projectile.deflect` with `ProjectileDeflection.REVERSE`.
pub(super) fn reverse(p: &mut Projectile, jitter: f32) {
p.velocity = Vec3::new(
p.velocity.x * -0.5,
p.velocity.y * -0.5,
p.velocity.z * -0.5,
);
p.yaw += 170.0 + jitter * 20.0;
}
/// Whether a block reacts to a wind charge's burst by being used.
fn triggers(name: &str) -> bool {
let n = name.trim_start_matches("minecraft:");
// Doors and trapdoors open unless iron; gates, buttons, levers and bells react.
(n.ends_with("_door") || n.ends_with("_trapdoor")) && !n.starts_with("iron_")
|| n.ends_with("_fence_gate")
|| n.ends_with("_button")
|| n == "lever"
|| n == "bell"
}
impl Game<'_> {
/// `WindChargeItem.use`.
pub(super) fn throw_wind_charge(&mut self) -> Result<bool> {
if self.creatures.wind_cooldown > 0 {
return Ok(true);
}
self.creatures.wind_cooldown = 10;
let (Some(eye), Some(p)) = (self.eye_position(), self.player.as_ref()) else {
return Ok(false);
};
let (velocity, on_ground, pos) = (p.velocity, p.ground.on_ground, p.position);
let start = Vec3::new(pos.x, eye[1], pos.z);
let mut proj = Projectile::new(ProjectileKind::WindCharge, start, Some(Who::Player));
proj.shoot_from_rotation(
&mut self.world.random,
self.pitch,
self.yaw,
0.0,
1.5,
1.0,
velocity,
on_ground,
);
self.creatures.projectiles.push(proj);
let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8);
self.audio
.play("minecraft:entity.wind_charge.throw", Some(eye), 0.5, pitch);
self.stats.add("used", "minecraft:wind_charge", 1);
self.swing_arm();
if !self.creative
&& let Some(s) = self.inventory[self.selected].as_mut()
{
s.count -= 1;
if s.count == 0 {
self.inventory[self.selected] = None;
}
}
Ok(true)
}
/// A wind charge meeting an entity or a block (or flying too high).
pub(super) fn wind_charge_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
let breeze = p.kind == ProjectileKind::BreezeWindCharge;
let (radius, knockback) = if breeze {
(BREEZE_RADIUS, 1.0)
} else {
(PLAYER_RADIUS, PLAYER_KNOCKBACK)
};
let center = match hit {
Hit::Entity { who, at } => {
self.wind_charge_damage(p, who);
[at.x, at.y, at.z]
}
// onHitBlock: a quarter of a block out along the face.
Hit::Block { at, face, .. } => [
at.x + f64::from(face[0]) * 0.25,
at.y + f64::from(face[1]) * 0.25,
at.z + f64::from(face[2]) * 0.25,
],
Hit::None => return Ok(()),
};
self.wind_burst(
center,
radius,
knockback,
breeze,
p.owner == Some(Who::Player),
)
}
/// `AbstractWindCharge.onHitEntity`: one point of damage.
fn wind_charge_damage(&mut self, p: &Projectile, who: Who) {
let owner_breeze = matches!(p.owner, Some(Who::Mob(id))
if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Breeze));
match who {
Who::Player => {
if !self.creative {
self.mob_hits_player_kind(
1.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:wind_charge",
);
}
}
Who::Mob(id) => {
let source = Damage {
kind: DamageKind::Thrown,
attacker: p.owner,
from: Some([p.previous.x, p.previous.y, p.previous.z]),
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
// Breeze.isInvulnerableTo: its own kind's charges.
if owner_breeze && m.species() == Species::Breeze {
return;
}
m.damage(1.0, source);
}
if p.owner == Some(Who::Player) {
self.last_hurt_by_player.insert(id);
}
}
}
}
/// The exploded positions: rays through everything but the blocks that
/// stop wind (`blocks_wind_charge_explosions`).
fn wind_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> {
let stops = self
.res
.items
.block_tags
.get("minecraft:blocks_wind_charge_explosions")
.cloned()
.unwrap_or_default();
let (min_y, max_y) = (horizon_client::chunk::MIN_Y, 320);
let mut set: BTreeSet<[i32; 3]> = BTreeSet::new();
for xx in 0..16 {
for yy in 0..16 {
for zz in 0..16 {
if !(xx == 0 || xx == 15 || yy == 0 || yy == 15 || zz == 0 || zz == 15) {
continue;
}
let mut d = [
f64::from(xx as f32 / 15.0 * 2.0 - 1.0),
f64::from(yy as f32 / 15.0 * 2.0 - 1.0),
f64::from(zz as f32 / 15.0 * 2.0 - 1.0),
];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
for c in &mut d {
*c /= len;
}
let mut power = radius * (0.7 + self.world.random.next_float() * 0.6);
let mut at = center;
while power > 0.0 {
let pos = [
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
];
if pos[1] < min_y || pos[1] >= max_y {
break;
}
let name = &self
.res
.facts
.get(self.world.block(pos[0], pos[1], pos[2]))
.name;
if stops.contains(&**name) {
power -= (3_600_000.0_f32 + 0.3) * 0.3;
}
if power > 0.0 {
set.insert(pos);
}
for i in 0..3 {
at[i] += d[i] * f64::from(0.3_f32);
}
power -= 0.225_000_01;
}
}
}
}
set.into_iter().collect()
}
/// `ServerExplosion.hurtEntities` for a calculator that damages nothing:
/// knockback scaled by distance, exposure and the multiplier.
fn wind_knockback(
&mut self,
center: [f64; 3],
radius: f32,
multiplier: f32,
player_charge: bool,
) {
let diameter = f64::from(radius * 2.0);
let distance = |p: [f64; 3]| {
((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2))
.sqrt()
};
let direction = |origin: [f64; 3]| {
let d = [
origin[0] - center[0],
origin[1] - center[1],
origin[2] - center[2],
];
let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if l < 1.0e-5 {
[0.0; 3]
} else {
[d[0] / l, d[1] / l, d[2] / l]
}
};
let multiplier = f64::from(multiplier);
// The player (not a spectator; a flying creative player takes none).
if let Some(p) = self.player.as_ref()
&& !self.spectator()
{
let feet = [p.position.x, p.position.y, p.position.z];
let dist = distance(feet) / diameter;
let flying = self.creative && p.flying;
if dist <= 1.0 && !flying {
let w = f64::from(p.dimensions.width) / 2.0;
let h = f64::from(p.dimensions.height);
let eye = [
feet[0],
feet[1] + f64::from(p.dimensions.eye_height),
feet[2],
];
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let power = (1.0 - dist) * f64::from(exposure) * multiplier;
let dir = direction(eye);
if let Some(p) = self.player.as_mut() {
p.velocity = Vec3::new(
p.velocity.x + dir[0] * power,
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
// ServerPlayer.onExplosionHit: a player's own charge cancels the fall.
if player_charge {
let at = p.position;
p.impulse.set_ignore_fall_damage(true, Some(at));
}
}
}
}
let mut mobs = std::mem::take(&mut self.mobs);
for m in mobs.iter_mut().filter(|m| m.alive()) {
let feet = [m.position.x, m.position.y, m.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
continue;
}
let (w, h) = (m.kind.width / 2.0, f64::from(m.height()));
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let eye = [feet[0], m.eye_y(), feet[2]];
let power = (1.0 - dist) * f64::from(exposure) * multiplier;
let dir = direction(eye);
m.velocity = Vec3::new(
m.velocity.x + dir[0] * power,
m.velocity.y + dir[1] * power,
m.velocity.z + dir[2] * power,
);
}
self.mobs = mobs;
// Arrows and other projectiles (the charges themselves ignore it).
let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| {
let feet = [position.x, position.y, position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
return;
}
let exposure = game.seen_percent(
center,
[feet[0] - 0.125, feet[1], feet[2] - 0.125],
[feet[0] + 0.125, feet[1] + 0.25, feet[2] + 0.125],
);
let power = (1.0 - dist) * f64::from(exposure) * multiplier;
let dir = direction(feet);
*velocity = Vec3::new(
velocity.x + dir[0] * power,
velocity.y + dir[1] * power,
velocity.z + dir[2] * power,
);
};
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
for p in projectiles.iter_mut().filter(|p| {
!p.stuck
&& !matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
)
}) {
push(p.position, &mut p.velocity, self);
}
self.creatures.projectiles = projectiles;
let mut arrows = std::mem::take(&mut self.arrows);
for a in arrows.iter_mut().filter(|a| !a.stuck) {
push(a.position, &mut a.velocity, self);
}
self.arrows = arrows;
let mut tnts = std::mem::take(&mut self.tnts);
for t in &mut tnts {
push(t.position, &mut t.velocity, self);
}
self.tnts = tnts;
}
/// The burst: knockback, the blocks that react, the gust and the sound.
fn wind_burst(
&mut self,
center: [f64; 3],
radius: f32,
multiplier: f32,
breeze: bool,
player_charge: bool,
) -> Result<()> {
let mut targets = self.wind_positions(center, radius);
self.wind_knockback(center, radius, multiplier, player_charge);
// Explosion.canTriggerBlocks: a breeze's charge needs mob griefing.
if !breeze || self.ui.rules.bool("mob_griefing") {
// Util.shuffle(list, level.random)
for i in (2..=targets.len()).rev() {
let swap = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
targets.swap(i - 1, swap);
}
for pos in targets {
self.wind_trigger_block(pos)?;
}
}
let sound = if breeze {
"minecraft:entity.breeze.wind_burst"
} else {
"minecraft:entity.wind_charge.wind_burst"
};
let pitch = (1.0
+ (super::explosion::client_float() - super::explosion::client_float()) * 0.2)
* 0.7;
self.audio.play(sound, Some(center), 4.0, pitch);
// Explosion.isSmall: below a radius of 2.
let ty = if radius < 2.0 {
ParticleType::GustEmitterSmall
} else {
ParticleType::GustEmitterLarge
};
self.particles
.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` for `TRIGGER_BLOCK`: doors, gates,
/// buttons, levers and bells react as if used; candles go out.
fn wind_trigger_block(&mut self, pos: [i32; 3]) -> Result<()> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let name = self.res.facts.get(state).name.clone();
let prop = |game: &Self, key: &str| {
game.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get(key).cloned())
};
if name.ends_with("candle") || name.ends_with("candle_cake") {
if prop(self, "lit").as_deref() == Some("true") {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio.play(
"minecraft:entity.generic.extinguish_fire",
Some(at),
1.0,
1.0,
);
self.set_state_named(pos, &name, &["candles", "waterlogged"])?;
}
return Ok(());
}
if !triggers(&name) {
return Ok(());
}
// Doors react in their lower half only; powered ones and pressed
// buttons stay as they are.
if name.ends_with("_door") && prop(self, "half").as_deref() != Some("lower") {
return Ok(());
}
if prop(self, "powered").as_deref() == Some("true") && &*name != "minecraft:lever" {
return Ok(());
}
let at = Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
);
let player = PlayerContext {
yaw: self.yaw,
pitch: self.pitch,
may_build: true,
can_eat: false,
game_master: false,
};
self.with_level(|b, level, ticks| {
b.use_without_item(
level,
ticks,
BlockPos::new(pos[0], pos[1], pos[2]),
Direction::Up,
at,
player,
)
});
self.process_level_events()?;
Ok(())
}
/// `WindChargeRenderer`: the spinning charge and its wind.
pub(super) fn wind_charge_geometry(
&self,
p: &Projectile,
at: glam::Vec3,
light: u32,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
static MODEL: std::sync::OnceLock<Option<horizon_client::mobs::Part>> =
std::sync::OnceLock::new();
let model = MODEL.get_or_init(|| {
horizon_client::mobs::load_model(&self.options.resources, "minecraft:wind_charge#main")
});
let Some(model) = model else { return };
let Some(r) = self
.res
.atlas
.sprites
.get("entity/projectiles/wind_charge")
.copied()
else {
return;
};
let age = p.age as f32;
let mut poses = horizon_client::mobs::anim::Poses::new(model);
poses.yrot("wind_charge", -age * 16.0_f32.to_radians());
poses.yrot("wind", age * 16.0_f32.to_radians());
let base = glam::Mat4::from_translation(at)
* glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
horizon_client::mobs::render::draw(
model,
base,
&poses,
[r.u0, r.v0, r.u1, r.v1],
0xFFFF_FFFF,
light,
0,
out,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_burst_opens_wooden_doors_but_not_iron_ones() {
assert!(triggers("minecraft:oak_door"));
assert!(triggers("minecraft:copper_trapdoor"));
assert!(!triggers("minecraft:iron_door"));
assert!(!triggers("minecraft:iron_trapdoor"));
assert!(triggers("minecraft:lever"));
assert!(triggers("minecraft:stone_button"));
assert!(triggers("minecraft:bell"));
assert!(!triggers("minecraft:stone"));
}
#[test]
fn a_deflected_projectile_turns_around_at_half_speed() {
let mut p = Projectile::new(ProjectileKind::Snowball, Vec3::ZERO, None);
p.velocity = Vec3::new(2.0, -1.0, 0.0);
reverse(&mut p, 0.5);
assert!((p.velocity.x + 1.0).abs() < 1e-9 && (p.velocity.y - 0.5).abs() < 1e-9);
assert!((p.yaw - 180.0).abs() < 1e-4);
}
}
+10 -1
View File
@@ -509,7 +509,16 @@ impl Items {
return vec![];
};
let name = block.name.trim_start_matches("minecraft:");
let Some(table) = self.loot.get(&format!("minecraft:blocks/{name}")) else {
// `Blocks.wallVariant`: wall signs, banners, heads, fans and torches
// reuse the standing block's loot table.
let standing = name.replacen("_wall_", "_", 1);
let standing = standing.strip_prefix("wall_").unwrap_or(&standing);
let standing = standing.replacen("wall_", "", 1);
let table = self
.loot
.get(&format!("minecraft:blocks/{name}"))
.or_else(|| self.loot.get(&format!("minecraft:blocks/{standing}")));
let Some(table) = table else {
return vec![];
};
let ctx = LootContext {
+1
View File
@@ -77,6 +77,7 @@ pub mod snbt;
pub mod sprint;
pub mod sprites;
pub mod stations;
pub mod stopwatches;
pub mod streaming;
pub mod structure_blocks;
pub mod subtitles;
+35
View File
@@ -9,7 +9,10 @@ pub mod ai;
pub mod allay;
pub mod anim;
pub mod aquatic;
pub mod brain;
pub mod breeze;
pub mod camel;
pub mod caravan;
pub mod control;
pub mod creaking;
pub mod cube;
@@ -21,10 +24,13 @@ pub mod gear;
pub mod goals;
pub mod golem;
pub mod guardian;
pub mod happy_ghast;
pub mod hostile;
pub mod illager;
pub mod keyframes;
pub mod leash;
pub mod living;
pub mod llama;
pub mod nav;
pub mod nether;
pub mod path;
@@ -35,9 +41,11 @@ pub mod ravager;
pub mod render;
pub mod riders;
pub mod shulker;
pub mod sniffer;
pub mod spawning;
pub mod species;
pub mod tame;
pub mod trader;
pub mod undead;
pub mod vex;
pub mod villager;
@@ -485,6 +493,15 @@ pub struct Extra {
pub meeting: Option<[i32; 3]>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
/// Who holds this mob's lead, a holder not yet found after loading, and
/// the spin the rope's torque gives it.
pub leash: Option<leash::Holder>,
pub leash_pending: Option<leash::Pending>,
pub leash_spin: f64,
/// More species scratch values.
pub scratch: [i32; 4],
/// Block positions a species remembers (a sniffer's explored ground).
pub positions: Vec<[i32; 3]>,
/// A warden's brain, anger and vibrations.
pub warden: Option<Box<warden::Warden>>,
/// A raider's patrol and raid state.
@@ -734,6 +751,12 @@ pub enum MobEvent {
table: &'static str,
at: [f64; 3],
},
/// A lead snaps or loses its holder: the lead item drops when asked.
LeashBreak {
mob: u32,
drop: bool,
sound: bool,
},
/// A zombie villager's cure is complete: the game turns it back into a villager.
CureZombieVillager {
mob: u32,
@@ -803,6 +826,16 @@ pub struct Seen {
/// A villager's claimed job site and bed.
pub job: Option<[i32; 3]>,
pub bed: Option<[i32; 3]>,
pub yaw: f32,
pub velocity: Vec3,
/// Who holds this mob's lead.
pub leash: Option<leash::Holder>,
/// A llama's caravan head (its id plus one, 0 when not in a caravan).
pub caravan: u32,
/// A wandering trader's despawn delay.
pub delay: i32,
/// `getLastHurtByMob` and its timestamp.
pub hurt_by: Option<(Who, i32)>,
/// A raider in an active raid.
pub active_raid: bool,
/// A villager's reputation of the player (`getPlayerReputation`).
@@ -829,6 +862,8 @@ pub struct PlayerView {
pub hurt_by: Option<(Who, i64)>,
/// `getLastHurtMob` and when.
pub last_hurt: Option<(Who, i64)>,
pub velocity: Vec3,
pub yaw: f32,
/// The Hero of the Village effect.
pub hero: bool,
/// The player's UUID (villagers' gossip is keyed by it).
+61 -5
View File
@@ -87,6 +87,10 @@ pub enum Family {
Wither,
Allay,
Villager,
Trader,
Breeze,
Sniffer,
HappyGhast,
Warden,
Creaking,
}
@@ -125,10 +129,19 @@ pub fn family(s: Species) -> Family {
S::Allay => Family::Allay,
S::Creaking => Family::Creaking,
S::Villager => Family::Villager,
S::WanderingTrader => Family::Trader,
S::Breeze => Family::Breeze,
S::Sniffer => Family::Sniffer,
S::HappyGhast => Family::HappyGhast,
S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin,
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => {
Family::Equine
}
S::Horse
| S::Donkey
| S::Mule
| S::SkeletonHorse
| S::ZombieHorse
| S::Camel
| S::Llama
| S::TraderLlama => Family::Equine,
S::Phantom => Family::Phantom,
S::Enderman => Family::Enderman,
S::Slime | S::MagmaCube => Family::Cube,
@@ -173,6 +186,10 @@ pub fn register(m: &mut Mob) {
Family::Wither => super::wither::register(m),
Family::Allay => super::allay::register(m),
Family::Villager => super::villager::register(m),
Family::Trader => super::trader::register(m),
Family::Breeze => super::breeze::register(m),
Family::Sniffer => super::sniffer::register(m),
Family::HappyGhast => super::happy_ghast::register(m),
Family::Warden => super::warden::register(m),
Family::Creaking => super::creaking::register(m),
}
@@ -198,6 +215,9 @@ pub fn custom_move_control(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>
if m.species() == Species::Ghast {
return super::nether::ghast_move_control(m, w);
}
if m.species() == Species::HappyGhast {
return super::happy_ghast::move_control(m, w);
}
if m.species() == Species::Phantom {
return super::phantom::move_control(m);
}
@@ -355,6 +375,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
} else if m.air < 300 {
m.air = (m.air + 4).min(300);
}
if m.kind.flags.water_sensitive
&& (m.fluids.in_water || w.raining && w.can_see_sky(ex, ey, ez))
{
@@ -381,6 +402,8 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
play_ambient(m, w, events);
}
}
// Entity.baseTick ends with Leashable.tickLeash.
super::leash::tick(m, w, events);
}
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let sound = match m.species() {
@@ -409,6 +432,27 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air",
Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return,
Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item",
// HappyGhast: its own voice, never pitched up.
Species::HappyGhast => {
let sound = super::happy_ghast::sounds(m)[0];
events.push(MobEvent::Sound(
sound,
m.center(),
super::happy_ghast::volume(m),
1.0,
));
return;
}
// Sniffer.getAmbientSound.
Species::Sniffer => match super::sniffer::ambient(m) {
Some(s) => s,
None => return,
},
// Breeze.playAmbientSound.
Species::Breeze => match super::breeze::ambient(m) {
Some(s) => s,
None => return,
},
// Creaking.getAmbientSound: silent while awake.
Species::Creaking if m.extra.flag => return,
// Shulker.playAmbientSound: silent while closed.
@@ -594,7 +638,14 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Ravager => super::ravager::ai_step(m, w, events),
Species::Wither => super::wither::ai_step(m, w, events),
Species::Allay => super::allay::ai_step(m),
Species::Villager | Species::WanderingTrader => super::villager::ai_step(m, w),
Species::Breeze => super::breeze::ai_step(m, events),
Species::Sniffer => super::sniffer::ai_step(m, events),
Species::HappyGhast => super::happy_ghast::ai_step(m, w),
Species::Villager => super::villager::ai_step(m, w),
Species::WanderingTrader => {
super::villager::ai_step(m, w);
super::trader::ai_step(m, w);
}
Species::Shulker => {
super::shulker::tick(m, w, events);
super::shulker::ai_step(m, w, events);
@@ -666,6 +717,7 @@ pub fn speed_bonus(m: &Mob) -> f64 {
pub fn sound_volume(m: &Mob) -> f32 {
match m.species() {
Species::Ghast => 5.0,
Species::HappyGhast => super::happy_ghast::volume(m),
Species::Warden => 4.0,
Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32,
Species::Cod
@@ -674,7 +726,11 @@ pub fn sound_volume(m: &Mob) -> f32 {
| Species::Pufferfish
| Species::Bat => 0.1,
Species::Squid | Species::GlowSquid => 0.4,
Species::Horse | Species::Donkey | Species::Mule => 0.8,
Species::Horse
| Species::Donkey
| Species::Mule
| Species::Llama
| Species::TraderLlama => 0.8,
_ => 1.0,
}
}
+8 -1
View File
@@ -8,6 +8,9 @@ use std::f32::consts::PI;
/// The setupAnim implementation a model uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Anim {
HappyGhast,
Sniffer,
Breeze,
Warden,
Allay,
Creaking,
@@ -192,7 +195,7 @@ fn head(p: &mut Poses, s: &State) {
p.yrot("head", s.y_rot.to_radians());
}
/// QuadrupedModel.setupAnim
fn quadruped(p: &mut Poses, s: &State) {
pub(super) fn quadruped(p: &mut Poses, s: &State) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp);
@@ -347,6 +350,10 @@ pub fn setup(
) {
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Breeze => super::breeze::anim(m, s, p, w_anims),
Anim::Sniffer => super::sniffer::anim(m, s, p, w_anims),
Anim::HappyGhast => super::happy_ghast::anim(m, s, p),
Anim::Llama => super::llama::anim(m, s, p),
Anim::Warden => super::warden::anim(m, s, p, w_anims),
Anim::Allay => super::allay::anim(m, s, p),
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
+136
View File
@@ -0,0 +1,136 @@
//! Pieces of vanilla's `Brain` that species implemented as brains share:
//! memories that expire, behaviour durations, walk targets and
//! `MoveToTargetSink`.
use super::{Mob, goals::Cx};
use horizon_core::random::RandomSource;
/// A memory with an expiry (`Brain.setMemoryWithExpiry`): present for the
/// tick it was set and `ttl` more ticks. `Ttl::default()` is absent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Ttl(i32);
impl Ttl {
pub fn set(&mut self, ttl: i32) {
self.0 = ttl + 1;
}
pub fn erase(&mut self) {
self.0 = 0;
}
pub fn present(self) -> bool {
self.0 > 0
}
/// `Brain.forgetOutdatedMemories`, once at the start of each tick.
pub fn tick(&mut self) {
if self.0 > 0 {
self.0 -= 1;
}
}
}
/// A random duration in `min..=max` (`Behavior`'s end time).
pub fn duration(m: &mut Mob, min: i32, max: i32) -> i32 {
if max <= min {
return min;
}
min + m.random.next_int_bound(max - min + 1).unwrap_or(0)
}
/// `WalkTarget`: where to go, how fast and how close counts as there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WalkTarget {
pub pos: [i32; 3],
pub speed: f64,
pub close: i32,
}
impl WalkTarget {
pub fn new(pos: [i32; 3], speed: f64, close: i32) -> Self {
Self { pos, speed, close }
}
/// `MoveToTargetSink.reachedTarget`: Manhattan distance of blocks.
pub fn reached(&self, m: &Mob) -> bool {
let here = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let d = (self.pos[0] - here[0]).abs()
+ (self.pos[1] - here[1]).abs()
+ (self.pos[2] - here[2]).abs();
d <= self.close
}
}
/// `MoveToTargetSink(min, max)`: walks to the walk target and gives up on it
/// after a random time.
#[derive(Clone, Debug)]
pub struct Sink {
min: i32,
max: i32,
until: Option<i32>,
}
impl Sink {
pub fn new(min: i32, max: i32) -> Self {
Self {
min,
max,
until: None,
}
}
pub fn running(&self) -> bool {
self.until.is_some()
}
/// `stop`: forget the walk target and the path.
pub fn stop(&mut self, m: &mut Mob, walk: &mut Option<WalkTarget>) {
if self.until.take().is_some() {
m.nav_stop();
}
*walk = None;
}
/// One tick of `checkExtraStartConditions`, `canStillUse`, `tick` and
/// `stop` for the walk target.
pub fn tick(&mut self, m: &mut Mob, cx: &mut Cx, walk: &mut Option<WalkTarget>) {
let now = m.age as i32;
if let Some(until) = self.until {
let still = !m.ai.nav.is_done() && walk.is_some_and(|w| !w.reached(m));
if now > until || !still {
self.stop(m, walk);
}
return;
}
let Some(target) = *walk else { return };
if target.reached(m) {
*walk = None;
return;
}
let at = [
f64::from(target.pos[0]) + 0.5,
f64::from(target.pos[1]),
f64::from(target.pos[2]) + 0.5,
];
let mut moving = m.nav_move_to(cx.w, at, target.speed);
if !moving {
// A partial step toward it (`DefaultRandomPos.getPosTowards`).
moving = m
.default_random_pos_towards(cx.w, 10, 7, at, std::f64::consts::FRAC_PI_2)
.is_some_and(|p| m.nav_move_to(cx.w, p, target.speed));
}
if moving {
self.until = Some(now + duration(m, self.min, self.max));
} else {
*walk = None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_memory_lasts_its_expiry_and_the_tick_it_was_set() {
let mut t = Ttl::default();
assert!(!t.present());
t.set(2);
let mut ticks = 0;
while t.present() {
ticks += 1;
t.tick();
}
assert_eq!(ticks, 3);
}
}
+785
View File
@@ -0,0 +1,785 @@
//! Breezes (`Breeze`, `BreezeAi`): the brain's idle and fight activities as
//! one simulation (start attacking the nearest player or iron golem or whoever
//! hurt it, slide to a walk target, then shoot, long jump, shoot when stuck or
//! slide), memories with vanilla's expiry, the poses and their animations,
//! `BreezeModel`'s layers and the wind charges it shoots.
use super::{
Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{Cx, Float, Goal, goal_clone},
keyframes::Animation,
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
// Breeze state (see `brain`): `variant3` the pose, `variant` the pose the
// animations last saw, `ints[0..6]` the memories (shoot, shoot cooldown,
// shoot charging, shoot recovering, jump cooldown, jump inhaling) as the
// remaining ticks plus one, `point` the walk target with `vector[0]` its
// speed and `vector[1]` how close is close enough, `home` the jump target,
// `vector[2]` the whirl sound clock, `flag` the long jump behaviour with its
// end tick in `anim_ticks`, `flag2` the shoot behaviour with its end tick in
// `egg_time`, `counter` the end tick of the slide to the walk target (0 when
// not sliding), `counter2` the end tick of doing nothing, `anger` the
// cooldown before the next try to walk, `scratch[0]` the ticks it may still
// be unable to attack its target. AnimState states:
// idle, shoot, slide, slide back, inhale, long jump.
pub const STANDING: u8 = 0;
pub const SHOOTING: u8 = 1;
pub const INHALING: u8 = 2;
pub const LONG_JUMPING: u8 = 3;
pub const SLIDING: u8 = 4;
const SHOOT: usize = 0;
const SHOOT_COOLDOWN: usize = 1;
const SHOOT_CHARGING: usize = 2;
const SHOOT_RECOVERING: usize = 3;
const JUMP_COOLDOWN: usize = 4;
const JUMP_INHALING: usize = 5;
const SHOOT_INITIAL_DELAY: i32 = 15;
const SHOOT_RECOVER_DELAY: i32 = 4;
const SHOOT_COOLDOWN_TICKS: i32 = 10;
const INHALING_TICKS: i32 = 10;
const ALLOWED_ANGLES: [i32; 5] = [40, 55, 60, 75, 80];
pub fn register(m: &mut Mob) {
m.set_malus(super::path::PathType::OnTopOfTrapdoor, -1.0);
m.set_malus(super::path::PathType::Fire, -1.0);
// Swim(0.8) and the brain.
m.ai.goals.add(0, Float);
m.ai.goals.add(0, Brain);
}
pub fn pose(m: &Mob) -> u8 {
m.extra.variant3
}
fn set_pose(m: &mut Mob, pose: u8) {
m.extra.variant3 = pose;
}
fn has(m: &Mob, memory: usize) -> bool {
m.extra.ints[memory] > 0
}
/// `Brain.setMemoryWithExpiry`: present now and for `ttl` more ticks.
fn remember(m: &mut Mob, memory: usize, ttl: i32) {
m.extra.ints[memory] = ttl + 1;
}
fn forget(m: &mut Mob, memory: usize) {
m.extra.ints[memory] = 0;
}
fn walk_target(m: &Mob) -> bool {
m.extra.point.is_some()
}
fn now(m: &Mob) -> i32 {
m.age as i32
}
/// `Breeze.getFiringYPosition`.
pub fn firing_y(m: &Mob) -> f64 {
m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32)
}
/// `Breeze.withinInnerCircleRange`.
fn within_inner_circle(m: &Mob, target: Vec3) -> bool {
let me = Vec3::new(
m.position.x.floor() + 0.5,
m.position.y.floor() + 0.5,
m.position.z.floor() + 0.5,
);
(target.x - me.x).powi(2) + (target.z - me.z).powi(2) < 16.0 && (target.y - me.y).abs() < 10.0
}
/// `Entity.lookAt` with the eyes anchor: snap body and head to face a point.
fn snap_look(m: &mut Mob, at: [f64; 3]) {
let (dx, dy, dz) = (
at[0] - m.position.x,
at[1] - m.eye_y(),
at[2] - m.position.z,
);
let flat = (dx * dx + dz * dz).sqrt();
m.head_pitch = (-dy.atan2(flat).to_degrees()) as f32;
m.yaw = (dz.atan2(dx).to_degrees() - 90.0) as f32;
m.head_yaw = m.yaw;
m.previous_head_pitch = m.head_pitch;
m.previous_yaw = m.yaw;
m.previous_head_yaw = m.yaw;
}
/// `BreezeUtil.hasLineOfSight`.
fn line_of_sight(m: &Mob, w: &MobWorld, target: Vec3) -> bool {
let from = m.position;
let range = 50.0_f64.max(m.attrs.follow_range);
from.distance(target) <= range && w.clear_between(from, target, false)
}
/// `BreezeUtil.randomPointBehindTarget`: four to eight blocks behind the
/// target's facing, with a spread of 45 degrees.
fn point_behind(m: &mut Mob, target: Vec3, head_yaw: f32) -> Vec3 {
let view = head_yaw + 180.0 + m.random.next_gaussian() as f32 * 90.0 / 2.0;
let r = 4.0 + m.random.next_float() * 4.0;
let d = Vec3::direction_from_rotation(0.0, view).scale(f64::from(r));
target.add_vector(d)
}
/// The attack target's position, eye height, facing and whether it is a
/// player.
struct Quarry {
position: Vec3,
eye: f64,
yaw: f32,
height: f64,
}
fn quarry(m: &Mob, cx: &Cx, who: Who) -> Option<Quarry> {
let t = cx.w.target_info(who)?;
let yaw = match who {
Who::Player => {
cx.w.player
.as_ref()
.map_or(0.0, |p| (-p.look[0]).atan2(p.look[2]).to_degrees() as f32)
}
Who::Mob(id) => cx.w.seen(id).map_or(m.yaw, |s| s.yaw),
};
Some(Quarry {
position: t.position,
eye: t.eye_y,
yaw,
height: t.bounds.max_position().y - t.bounds.min_position().y,
})
}
/// `TargetingConditions.forCombat().range(follow)` plus `canAttack`: a
/// player (not in creative or spectator) or an iron golem it can see.
fn attackable(m: &mut Mob, cx: &Cx, who: Who) -> bool {
let follow = m.attrs.follow_range;
match who {
Who::Player => m.can_target_player(cx.w, follow, true),
Who::Mob(id) => {
let Some(s) = cx.w.seen(id) else {
return false;
};
s.alive
&& s.species == Species::IronGolem
&& m.distance_sqr(s.position) <= follow * follow
&& m.sees(cx.w, who)
}
}
}
/// `BreezeAttackEntitySensor` and `HurtBySensor`: candidates for
/// `StartAttacking`.
fn nearest_attackable(m: &mut Mob, cx: &Cx) -> Option<Who> {
let follow = m.attrs.follow_range;
let mut candidates: Vec<(f64, Who)> = Vec::new();
if let Some(p) = &cx.w.player
&& p.alive
&& !p.creative
&& !p.spectator
{
candidates.push((m.distance_sqr(p.position), Who::Player));
}
for s in
cx.w.nearby(m.position, follow, |s| s.species == Species::IronGolem)
{
candidates.push((m.distance_sqr(s.position), Who::Mob(s.id)));
}
candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
candidates
.into_iter()
.map(|c| c.1)
.find(|w| attackable(m, cx, *w))
}
fn hurt_by(m: &Mob, cx: &Cx) -> Option<Who> {
let (d, at) = m.last_damage?;
if i64::from(m.age) - at > 40 {
return None;
}
match d.attacker? {
Who::Player => Some(Who::Player),
Who::Mob(id) => {
cx.w.seen(id)
.filter(|s| s.alive && s.species == Species::IronGolem)
.map(|_| Who::Mob(id))
}
}
}
/// The goal that runs the brain every tick.
#[derive(Clone, Debug)]
struct Brain;
impl Goal for Brain {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
true
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
brain(m, cx);
}
}
/// `Brain.tick`: memories expire, sensors scan, behaviours start in
/// priority order for the active activity, then the running ones tick.
fn brain(m: &mut Mob, cx: &mut Cx) {
for i in 0..6 {
if m.extra.ints[i] > 0 {
m.extra.ints[i] -= 1;
}
}
if m.extra.anger > 0 {
m.extra.anger -= 1;
}
let fight = m.ai.target.is_some() && !walk_target(m);
if fight {
stop_if_target_invalid(m, cx);
start_shoot(m, cx);
start_long_jump(m, cx);
start_shoot_when_stuck(m);
start_slide(m, cx);
} else {
// StartAttacking on the nearest attackable, then on whoever hurt it.
if m.ai.target.is_none() {
let scan = (m.age + m.id).is_multiple_of(20);
let found = if scan {
nearest_attackable(m, cx)
} else {
None
};
let found = found.or_else(|| hurt_by(m, cx));
if let Some(who) = found {
m.ai.target = Some(who);
m.extra.anger = 0;
m.extra.counter2 = 0;
}
}
start_walking(m, cx);
idle_stroll(m, cx);
}
tick_shoot(m, cx);
tick_long_jump(m, cx);
tick_walking(m, cx);
}
/// `StopAttackingIfTargetInvalid` with `wasEntityAttackableLastNTicks(100)`:
/// the target is dropped once it has not been attackable for 100 ticks.
fn stop_if_target_invalid(m: &mut Mob, cx: &mut Cx) {
let Some(who) = m.ai.target else { return };
let alive = cx.w.target_info(who).is_some_and(|t| t.alive);
if alive && attackable(m, cx, who) {
m.extra.scratch[0] = 100;
return;
}
m.extra.scratch[0] -= 1;
if !alive || m.extra.scratch[0] < 0 {
m.ai.target = None;
m.extra.scratch[0] = 0;
}
}
/// `Shoot.checkExtraStartConditions` and `start`.
fn start_shoot(m: &mut Mob, cx: &mut Cx) {
if m.extra.flag2
|| !has(m, SHOOT)
|| has(m, SHOOT_COOLDOWN)
|| has(m, SHOOT_CHARGING)
|| has(m, SHOOT_RECOVERING)
|| walk_target(m)
|| m.extra.home.is_some()
|| pose(m) != STANDING
{
return;
}
let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else {
return;
};
if m.position.distance_squared(q.position) >= 256.0 {
forget(m, SHOOT);
return;
}
m.extra.flag2 = true;
m.extra.egg_time = now(m) + SHOOT_INITIAL_DELAY + 1 + SHOOT_RECOVER_DELAY;
set_pose(m, SHOOTING);
remember(m, SHOOT_CHARGING, SHOOT_INITIAL_DELAY);
let at = m.center();
cx.events
.push(MobEvent::Sound("entity.breeze.inhale", at, 1.0, 1.0));
}
fn tick_shoot(m: &mut Mob, cx: &mut Cx) {
if !m.extra.flag2 {
return;
}
let target = m.ai.target;
if now(m) > m.extra.egg_time || target.is_none() || !has(m, SHOOT) {
// Shoot.stop.
m.extra.flag2 = false;
if pose(m) == SHOOTING {
set_pose(m, STANDING);
}
remember(m, SHOOT_COOLDOWN, SHOOT_COOLDOWN_TICKS);
forget(m, SHOOT);
return;
}
let Some(q) = target.and_then(|w| quarry(m, cx, w)) else {
return;
};
snap_look(m, [q.position.x, q.eye, q.position.z]);
if !has(m, SHOOT_CHARGING) && !has(m, SHOOT_RECOVERING) {
remember(m, SHOOT_RECOVERING, SHOOT_RECOVER_DELAY);
let start = Vec3::new(m.position.x, firing_y(m), m.position.z);
let passenger_offset = 0.3;
let (xd, yd, zd) = (
q.position.x - m.position.x,
q.position.y + q.height * passenger_offset - start.y,
q.position.z - m.position.z,
);
let mut p = Projectile::new(
ProjectileKind::BreezeWindCharge,
start,
Some(Who::Mob(m.id)),
);
// 5 - 4 * difficulty at normal.
p.shoot(&mut m.random, [xd, yd, zd], 0.7, -3.0);
cx.events.push(MobEvent::Projectile(p));
cx.events
.push(MobEvent::Sound("entity.breeze.shoot", m.center(), 1.5, 1.0));
}
}
/// `ShootWhenStuck`.
fn start_shoot_when_stuck(m: &mut Mob) {
if has(m, SHOOT) || has(m, JUMP_INHALING) || m.extra.home.is_some() || walk_target(m) {
return;
}
if m.rider.is_some() || m.fluids.in_water || m.extra.levitation_effect() {
remember(m, SHOOT, 60);
}
}
impl super::Extra {
fn levitation_effect(&self) -> bool {
self.effects.iter().any(|e| e.0 == "minecraft:levitation")
}
}
/// `Slide.start`: pick a point to slide to.
fn start_slide(m: &mut Mob, cx: &mut Cx) {
if has(m, SHOOT)
|| has(m, JUMP_COOLDOWN)
|| walk_target(m)
|| !m.on_ground
|| m.fluids.in_water
|| pose(m) != STANDING
{
return;
}
let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else {
return;
};
let mut position: Option<Vec3> = None;
if within_inner_circle(m, q.position)
&& let Some(away) =
m.default_random_pos_away(cx.w, 5, 5, [q.position.x, q.position.y, q.position.z])
{
let away = Vec3::new(away[0], away[1], away[2]);
if line_of_sight(m, cx.w, away)
&& q.position.distance_squared(away) > q.position.distance_squared(m.position)
{
position = Some(away);
}
}
let position = position.unwrap_or_else(|| {
if m.random.next_boolean() {
point_behind(m, q.position, q.yaw)
} else {
// randomPointInMiddleCircle: stop four to eight blocks short.
let d = q.position.subtract(m.position);
let distance = d.length() - (8.0 + (4.0 - 8.0) * m.random.next_double());
m.position.add_vector(d.normalize().scale(distance))
}
});
m.extra.point = Some([position.x.floor(), position.y.floor(), position.z.floor()]);
m.extra.vector[0] = 0.6;
m.extra.vector[1] = 1.0;
}
/// `SlideToTargetSink` (`MoveToTargetSink`): walk to the walk target.
fn start_walking(m: &mut Mob, cx: &mut Cx) {
if m.extra.counter != 0 {
return;
}
let Some(target) = m.extra.point else {
return;
};
if m.extra.anger > 0 {
return;
}
let close = m.extra.vector[1] as i32;
let here = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let reached = (target[0] as i32 - here[0]).abs()
+ (target[1] as i32 - here[1]).abs()
+ (target[2] as i32 - here[2]).abs()
<= close;
let speed = m.extra.vector[0];
if !reached && m.nav_move_to(cx.w, [target[0] + 0.5, target[1], target[2] + 0.5], speed) {
m.extra.counter = now(m) + 20 + m.random.next_int_bound(21).unwrap_or(0);
cx.events
.push(MobEvent::Sound("entity.breeze.slide", m.center(), 1.0, 1.0));
set_pose(m, SLIDING);
} else {
m.extra.point = None;
}
}
fn tick_walking(m: &mut Mob, _cx: &mut Cx) {
if m.extra.counter == 0 {
return;
}
let reached = m.extra.point.is_none_or(|target| {
let here = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
(target[0] as i32 - here[0]).abs()
+ (target[1] as i32 - here[1]).abs()
+ (target[2] as i32 - here[2]).abs()
<= m.extra.vector[1] as i32
});
if now(m) > m.extra.counter || m.ai.nav.is_done() || reached {
// SlideToTargetSink.stop.
m.extra.counter = 0;
m.extra.point = None;
m.nav_stop();
set_pose(m, STANDING);
if m.ai.target.is_some() {
remember(m, SHOOT, 60);
}
}
}
/// `RunOne` of `DoNothing(20, 100)` and `RandomStroll.stroll(0.6)`.
fn idle_stroll(m: &mut Mob, cx: &mut Cx) {
if m.extra.counter != 0 || walk_target(m) || m.ai.target.is_some() {
return;
}
if now(m) < m.extra.counter2 {
return;
}
if m.random.next_int_bound(3).unwrap_or(0) == 0 {
m.extra.counter2 = now(m) + 20 + m.random.next_int_bound(81).unwrap_or(0);
} else if let Some(p) = m.land_random_pos(cx.w, 10, 7) {
m.extra.point = Some([p[0].floor(), p[1].floor(), p[2].floor()]);
m.extra.vector[0] = 0.6;
m.extra.vector[1] = 0.0;
}
}
fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool {
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
if w.block_name(x, y, z) == "minecraft:honey_block" {
return false;
}
(1..=4).all(|i| {
w.facts.is_air(w.world.block(x, y + i, z))
|| w.fluid(x, y + i, z) == crate::blocks::Fluid::Water
})
}
/// `LongJump.snapToSurface`: the block above the surface below the point,
/// else above the ceiling over it.
fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> {
let (x, z) = (p.x.floor() as i32, p.z.floor() as i32);
let y0 = p.y.floor() as i32;
for y in (y0 - 10..=y0).rev() {
let top = f64::from(w.data.state(w.world.block(x, y, z)).top);
if top > 0.0 {
let hit = (f64::from(y) + top).min(p.y);
return Some([x, hit.floor() as i32 + 1, z]);
}
}
for y in y0..=y0 + 10 {
if w.data.state(w.world.block(x, y, z)).top > 0.0 {
return Some([x, y + 1, z]);
}
}
None
}
fn dangerous_block(name: &str) -> bool {
matches!(
name,
"minecraft:fire"
| "minecraft:soul_fire"
| "minecraft:lava"
| "minecraft:magma_block"
| "minecraft:campfire"
| "minecraft:soul_campfire"
| "minecraft:wither_rose"
| "minecraft:sweet_berry_bush"
| "minecraft:cactus"
| "minecraft:powder_snow"
)
}
/// `LongJump.canRun` and `start`.
fn start_long_jump(m: &mut Mob, cx: &mut Cx) {
if m.extra.flag
|| has(m, SHOOT)
|| has(m, JUMP_COOLDOWN)
|| walk_target(m)
|| !can_run_long_jump(m, cx)
{
return;
}
m.extra.flag = true;
m.extra.anim_ticks = now(m) + 200;
if !has(m, JUMP_INHALING) {
remember(m, JUMP_INHALING, INHALING_TICKS);
}
set_pose(m, INHALING);
let at = m.center();
cx.events
.push(MobEvent::Sound("entity.breeze.charge", at, 1.0, 1.0));
if let Some(t) = m.extra.home {
snap_look(
m,
[
f64::from(t[0]) + 0.5,
f64::from(t[1]) + 0.5,
f64::from(t[2]) + 0.5,
],
);
}
}
fn can_run_long_jump(m: &mut Mob, cx: &mut Cx) -> bool {
if !m.on_ground && !m.fluids.in_water {
return false;
}
if m.fluids.water > m.eye_height() || m.fluids.in_lava {
return false;
}
if m.extra.home.is_some() {
return true;
}
let Some(who) = m.ai.target else {
return false;
};
let Some(q) = quarry(m, cx, who) else {
return false;
};
let follow = m.attrs.follow_range;
let distance = m.position.distance(q.position);
if distance >= follow {
m.ai.target = None;
return false;
}
if distance - 4.0 <= 0.0 || !can_jump_from_here(m, cx.w) {
return false;
}
let behind = point_behind(m, q.position, q.yaw);
let Some(target) = snap_to_surface(cx.w, behind) else {
return false;
};
if dangerous_block(cx.w.block_name(target[0], target[1] - 1, target[2])) {
return false;
}
let centre = Vec3::new(
f64::from(target[0]) + 0.5,
f64::from(target[1]) + 0.5,
f64::from(target[2]) + 0.5,
);
if !line_of_sight(m, cx.w, centre)
&& !line_of_sight(m, cx.w, centre.add_vector(Vec3::new(0.0, 4.0, 0.0)))
{
return false;
}
m.extra.home = Some(target);
true
}
/// `LongJumpUtil.calculateJumpVectorForAngle` without the collision check.
fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option<Vec3> {
let pos = m.position;
let plane = Vec3::new(target.x - pos.x, 0.0, target.z - pos.z)
.normalize()
.scale(0.5);
let aim = target.subtract(plane);
let d = aim.subtract(pos);
let angrad = f64::from(angle as f32 * std::f32::consts::PI / 180.0);
let xz = d.z.atan2(d.x);
let r2 = d.x * d.x + d.z * d.z;
let r = r2.sqrt();
let g = m.kind.gravity;
let sin2 = f64::from((2.0 * angrad as f32).sin());
let cos_sq = angrad.cos().powi(2);
let v0sq = r2 * g / (r * sin2 - 2.0 * d.y * cos_sq);
if v0sq < 0.0 {
return None;
}
let v0 = v0sq.sqrt();
if v0 > f64::from(max_velocity) {
return None;
}
let v0r = v0 * angrad.cos();
let v0y = v0 * angrad.sin();
Some(Vec3::new(v0r * xz.cos(), v0y, v0r * xz.sin()).scale(f64::from(0.95_f32)))
}
fn tick_long_jump(m: &mut Mob, cx: &mut Cx) {
if !m.extra.flag {
return;
}
let ongoing = pose(m) != STANDING && !has(m, JUMP_COOLDOWN);
if now(m) > m.extra.anim_ticks || !ongoing {
// LongJump.stop.
m.extra.flag = false;
if matches!(pose(m), LONG_JUMPING | INHALING) {
set_pose(m, STANDING);
}
m.extra.home = None;
forget(m, JUMP_INHALING);
m.extra.variant2 = 0;
return;
}
let in_water = m.fluids.in_water;
if !in_water && m.extra.variant2 != 0 {
m.extra.variant2 = 0;
}
let finished_inhaling = !has(m, JUMP_INHALING) && pose(m) == INHALING;
if finished_inhaling {
let target = m.extra.home.map(|t| {
Vec3::new(
f64::from(t[0]) + 0.5,
f64::from(t[1]),
f64::from(t[2]) + 0.5,
)
});
let mut angles = ALLOWED_ANGLES;
for i in (1..angles.len()).rev() {
let j = m.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
angles.swap(i, j);
}
let max = 0.058_333_334_f32 * m.attrs.follow_range as f32;
let v = target.and_then(|t| angles.iter().find_map(|&a| jump_vector(m, t, max, a)));
let Some(v) = v else {
set_pose(m, STANDING);
return;
};
if in_water {
m.extra.variant2 = 1;
}
let at = m.center();
cx.events
.push(MobEvent::Sound("entity.breeze.jump", at, 1.0, 1.0));
set_pose(m, LONG_JUMPING);
m.yaw = m.body_yaw;
m.velocity = v;
m.on_ground = false;
return;
}
let landed_in_water = in_water && m.extra.variant2 == 0;
if pose(m) == LONG_JUMPING && (m.on_ground || landed_in_water) {
let at = m.center();
cx.events
.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0));
set_pose(m, STANDING);
let hurt = m
.last_damage
.is_some_and(|(_, t)| i64::from(m.age) - t <= 40);
remember(m, JUMP_COOLDOWN, if hurt { 2 } else { 10 });
remember(m, SHOOT, 100);
}
}
/// Whether `Breeze.shouldDiscardFriction` applies (a long jump in the air).
pub fn discards_friction(m: &Mob) -> bool {
m.species() == Species::Breeze && pose(m) == LONG_JUMPING
}
/// `Breeze.tick` and the client's pose-driven animation states.
pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
let age = m.age as f32;
let current = pose(m);
if current != m.extra.variant {
// resetAnimations, then the pose's own animation.
let st = &mut m.anim.states;
st[1].stop();
st[0].stop();
st[4].stop();
st[5].stop();
match current {
SHOOTING => st[1].start_if_stopped(age),
INHALING => st[4].start_if_stopped(age),
SLIDING => st[2].start_if_stopped(age),
_ => {}
}
m.extra.variant = current;
}
if current == LONG_JUMPING {
m.anim.states[5].start_if_stopped(age);
}
m.anim.states[0].start_if_stopped(age);
if current != SLIDING && m.anim.states[2].started.is_some() {
m.anim.states[3].start(age);
m.anim.states[2].stop();
}
// The whirl sound.
if m.extra.vector[2] <= 0.0 {
m.extra.vector[2] = f64::from(1 + m.random.next_int_bound(80).unwrap_or(0));
} else {
m.extra.vector[2] -= 1.0;
if m.extra.vector[2] <= 0.0 {
let pitch = 0.7 + 0.4 * m.random.next_float();
let volume = 0.8 + 0.2 * m.random.next_float();
events.push(MobEvent::Sound(
"entity.breeze.whirl",
[m.position.x, m.position.y, m.position.z],
volume,
pitch,
));
}
}
}
/// `Breeze.playAmbientSound` and its sound selection.
pub fn ambient(m: &Mob) -> Option<&'static str> {
if m.ai.target.is_some() && m.on_ground {
return None;
}
Some(if m.on_ground {
"entity.breeze.idle_ground"
} else {
"entity.breeze.idle_air"
})
}
/// `BreezeModel.setupAnim`: the six keyframe animations.
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
let age = s.age;
for (state, name) in [
(&m.anim.states[0], "IDLE"),
(&m.anim.states[1], "SHOOT"),
(&m.anim.states[2], "SLIDE"),
(&m.anim.states[3], "SLIDE_BACK"),
(&m.anim.states[4], "INHALE"),
(&m.anim.states[5], "JUMP"),
] {
if let (Some(ms), Some(a)) = (
state.millis(age),
animations.get(&format!("BreezeAnimation.{name}")),
) {
a.apply(ms, 1.0, p);
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_memory_is_present_for_its_ttl_plus_the_tick_it_was_set() {
// setMemoryWithExpiry(15) at tick T: present T through T + 15.
let mut v = 16;
let mut present = 1;
for _ in 0..30 {
if v > 0 {
v -= 1;
}
if v > 0 {
present += 1;
}
}
assert_eq!(present, 16);
}
#[test]
fn the_highest_arc_reaches_a_target_within_range() {
// Angle 80 degrees: v0^2 = r^2 g / (r sin 2a - 2 y cos^2 a).
let g = 0.08;
let (r, y): (f64, f64) = (10.0, 0.0);
let a = 60.0_f64.to_radians();
let v0sq = r * r * g / (r * (2.0 * a).sin() - 2.0 * y * a.cos().powi(2));
assert!(v0sq.sqrt() < 1.4);
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Llama caravans and the trader's llamas: `LlamaFollowCaravanGoal` (a
//! llama joins the nearest line of llamas that starts at a leashed one and
//! follows the llama ahead), `TraderLlamaDefendWanderingTraderGoal` and the
//! trader llama's despawn.
use super::{
Mob, MobWorld, Seen, Species, Who,
goals::{Cx, Goal, TARGET, TargetState, goal_clone, reduced, target_continue},
llama::is_llama,
};
use horizon_core::geometry::Vec3;
const CARAVAN_LIMIT: i32 = 8;
/// The id plus one of the llama this one follows, 0 when not in a caravan
/// (`Llama.caravanHead`, kept in `ints[1]`).
pub fn head_of(m: &Mob) -> u32 {
if is_llama(m.species()) {
m.extra.ints[1].max(0) as u32
} else {
0
}
}
fn in_caravan(m: &Mob) -> bool {
head_of(m) != 0
}
fn is_leashed_seen(s: &Seen) -> bool {
s.leash.is_some()
}
/// Whether another llama follows `s` (`hasCaravanTail`).
fn has_tail(cx: &Cx, s: &Seen) -> bool {
cx.w.others
.iter()
.any(|o| is_llama(o.species) && o.alive && o.caravan == s.id + 1)
}
/// `firstIsLeashed`: the line leads back to a leashed llama in at most
/// eight links.
fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool {
if counter > CARAVAN_LIMIT {
return false;
}
let _ = leashed;
if caravan == 0 {
return false;
}
let Some(head) = cx.w.seen(caravan - 1) else {
return false;
};
if is_leashed_seen(head) {
true
} else {
first_is_leashed(cx, head.caravan, false, counter + 1)
}
}
/// `LlamaFollowCaravanGoal`.
#[derive(Clone, Debug)]
pub struct FollowCaravan {
speed: f64,
base_speed: f64,
dist_check: i32,
}
impl FollowCaravan {
pub fn new(speed: f64) -> Self {
Self {
speed,
base_speed: speed,
dist_check: 0,
}
}
}
impl Goal for FollowCaravan {
goal_clone!();
fn flags(&self) -> u8 {
super::goals::MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.extra.leash.is_some() || in_caravan(m) {
return false;
}
let area = m.bounds().inflate(Vec3::new(9.0, 4.0, 9.0));
let mine = m.position;
let id = m.id;
let candidates: Vec<&Seen> = cx
.w
.others
.iter()
.filter(|s| s.id != id && is_llama(s.species) && s.alive && s.bounds.intersects(area))
.collect();
let mut closest: Option<&Seen> = None;
let mut best = f64::MAX;
for c in &candidates {
if c.caravan != 0 && !has_tail(cx, c) {
let d = mine.distance_squared(c.position);
if d <= best {
best = d;
closest = Some(c);
}
}
}
if closest.is_none() {
for c in &candidates {
if is_leashed_seen(c) && !has_tail(cx, c) {
let d = mine.distance_squared(c.position);
if d <= best {
best = d;
closest = Some(c);
}
}
}
}
let Some(head) = closest else {
return false;
};
if best < 4.0 {
return false;
}
if !is_leashed_seen(head) && !first_is_leashed(cx, head.caravan, false, 1) {
return false;
}
m.extra.ints[1] = head.id as i32 + 1;
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let caravan = head_of(m);
if caravan == 0 {
return false;
}
let Some(head) = cx.w.seen(caravan - 1).filter(|h| h.alive) else {
return false;
};
if !first_is_leashed(cx, caravan, false, 0) {
return false;
}
// Two llamas that joined the same one in the same tick: the one with
// the higher id leaves and looks for another place.
if cx
.w
.others
.iter()
.any(|o| o.id < m.id && is_llama(o.species) && o.alive && o.caravan == caravan)
{
return false;
}
let dist_sqr = m.position.distance_squared(head.position);
if dist_sqr > 676.0 {
if self.speed <= 3.0 {
self.speed *= 1.2;
self.dist_check = reduced(40);
return true;
}
if self.dist_check == 0 {
return false;
}
}
if self.dist_check > 0 {
self.dist_check -= 1;
}
true
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.extra.ints[1] = 0;
self.speed = self.base_speed;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let caravan = head_of(m);
if caravan == 0 {
return;
}
// A llama leashed to a fence knot does not walk to the one ahead.
if matches!(m.extra.leash, Some(super::leash::Holder::Knot(_))) {
return;
}
let Some(head) = cx.w.seen(caravan - 1) else {
return;
};
let to = Vec3::new(
head.position.x - m.position.x,
head.position.y - m.position.y,
head.position.z - m.position.z,
);
let distance = to.length();
let delta = to.normalize().scale((distance - 2.0).max(0.0));
m.nav_move_to(
cx.w,
[
m.position.x + delta.x,
m.position.y + delta.y,
m.position.z + delta.z,
],
self.speed,
);
}
}
/// `TraderLlamaDefendWanderingTraderGoal`: attack whoever last hurt the
/// wandering trader holding this llama's lead.
#[derive(Clone, Debug, Default)]
pub struct DefendTrader {
attacker: Option<Who>,
timestamp: i32,
st: TargetState,
}
impl Goal for DefendTrader {
goal_clone!();
fn flags(&self) -> u8 {
TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(super::leash::Holder::Mob(id)) = m.extra.leash else {
return false;
};
let Some(owner) =
cx.w.seen(id)
.filter(|s| s.species == Species::WanderingTrader)
else {
return false;
};
let Some((by, stamp)) = owner.hurt_by else {
return false;
};
if stamp == self.timestamp {
return false;
}
let Some(t) = cx.w.target_info(by) else {
return false;
};
if !t.alive || t.is_player && t.creative {
return false;
}
let follow = m.attrs.follow_range;
if m.distance_sqr(t.position) > follow * follow || !m.sees(cx.w, by) {
return false;
}
self.attacker = Some(by);
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
target_continue(&mut self.st, false, m, cx)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.target = self.attacker;
if let Some(super::leash::Holder::Mob(id)) = m.extra.leash
&& let Some(owner) = cx.w.seen(id)
&& let Some((_, stamp)) = owner.hurt_by
{
self.timestamp = stamp;
}
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.ai.target = None;
}
}
/// `TraderLlama.maybeDespawn`: counts down its own delay, or follows the
/// trader's when led by one, unless tamed, led by something else, ridden,
/// age-locked or kept.
pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) {
let trader = match m.extra.leash {
Some(super::leash::Holder::Mob(id)) => w
.seen(id)
.filter(|s| s.species == Species::WanderingTrader)
.map(|s| s.delay),
_ => None,
};
let leashed_other = m.extra.leash.is_some() && trader.is_none();
if m.extra.tame || leashed_other || m.rider.is_some() || m.extra.age_locked || m.persistent {
return;
}
m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1;
if m.extra.ints[0] <= 0 {
m.extra.leash = None;
m.removed = true;
}
}
@@ -0,0 +1,253 @@
//! Copper golems (`CopperGolem`, `CopperGolemAi`): they carry items from
//! copper chests to chests (see `game::copper_golems` for the container side
//! of `TransportItemsBetweenContainers`), play the chest interaction
//! animations, spin their heads when idle, oxidise over time and finally turn
//! into statues.
use super::{
Mob, MobEvent, MobWorld,
anim::{Poses, State},
goals::{Cx, Goal, JUMP, LOOK, MOVE, Panic, goal_clone},
keyframes::Animation,
};
use horizon_core::random::RandomSource;
use std::collections::HashMap;
// Copper golem state: `variant` the weathering (0 unaffected .. 3 oxidized),
// `variant3` the `CopperGolemState`, `main_hand` with `ints[1]` the carried
// stack, `legs` the antenna block, `egg_time` the next weathering tick (-1
// unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest
// being served with `positions` the visited chests, `point` where it walks,
// `scratch` = [transport phase, ticks since reaching the target, interaction
// state, transport cooldown ticks]. AnimationState slots: idle (0), getting an
// item (1), getting nothing (2), dropping an item (3), dropping nothing (4).
pub const IDLE: u8 = 0;
pub const GETTING_ITEM: u8 = 1;
pub const GETTING_NO_ITEM: u8 = 2;
pub const DROPPING_ITEM: u8 = 3;
pub const DROPPING_NO_ITEM: u8 = 4;
/// `WeatheringCopper.WeatherState` names.
pub const WEATHER: [&str; 4] = ["unaffected", "exposed", "weathered", "oxidized"];
pub fn register(m: &mut Mob) {
m.ai.nav.required_path_length = 48.0;
m.ai.nav.can_open_doors = true;
m.persistent = true;
m.extra.egg_time = -1;
m.extra.scratch[3] = 60 + m.random.next_int_bound(40).unwrap_or(0);
let g = &mut m.ai.goals;
g.add(0, Panic::new(1.5));
g.add(1, Serve);
g.add(2, super::goals::LookAtPlayer::new(6.0).probability(0.02));
g.add(3, Idle::default());
}
/// `CopperGolemOxidationLevels`: the body and eye textures.
pub fn texture(m: &Mob) -> String {
match m.extra.variant {
0 => "entity/copper_golem/copper_golem".into(),
n => format!("entity/copper_golem/copper_golem_{}", WEATHER[n.min(3) as usize]),
}
}
pub fn eye_texture(m: &Mob) -> String {
match m.extra.variant {
0 => "entity/copper_golem/copper_golem_eyes".into(),
n => format!(
"entity/copper_golem/copper_golem_eyes_{}",
WEATHER[n.min(3) as usize]
),
}
}
/// The sound of the oxidation level: `spin`, `hurt`, `death` or `step`.
pub fn sound(m: &Mob, what: &str) -> &'static str {
match (m.extra.variant, what) {
(2, "spin") => "entity.copper_golem_weathered.spin",
(2, "hurt") => "entity.copper_golem_weathered.hurt",
(2, "death") => "entity.copper_golem_weathered.death",
(2, _) => "entity.copper_golem_weathered.step",
(3, "spin") => "entity.copper_golem_oxidized.spin",
(3, "hurt") => "entity.copper_golem_oxidized.hurt",
(3, "death") => "entity.copper_golem_oxidized.death",
(3, _) => "entity.copper_golem_oxidized.step",
(_, "spin") => "entity.copper_golem.spin",
(_, "hurt") => "entity.copper_golem.hurt",
(_, "death") => "entity.copper_golem.death",
_ => "entity.copper_golem.step",
}
}
/// `CopperGolemAi`'s transport behaviour is running a target.
fn serving(m: &Mob) -> bool {
m.extra.home.is_some()
}
/// `TransportItemsBetweenContainers` walking and looking at its chest, and
/// standing still while interacting with it.
#[derive(Clone, Debug)]
struct Serve;
impl Goal for Serve {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
serving(m) && !m.ai.panicking
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(h) = m.extra.home else { return };
m.look_at([
f64::from(h[0]) + 0.5,
f64::from(h[1]) + 0.5,
f64::from(h[2]) + 0.5,
]);
match m.extra.point {
Some(p) => {
if m.ai.nav.is_done() || m.age % 10 == 0 {
let block = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
let path = m.create_path_to(cx.w, block, 0);
m.nav_move_to_path(path, 1.0);
}
}
None => {
// stopInPlace.
m.ai.nav.stop();
m.velocity.x = 0.0;
m.velocity.z = 0.0;
}
}
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.ai.nav.stop();
}
}
/// The idle `RunOne`: `RandomStroll.stroll(1.0, 2, 2)` or `DoNothing(30, 60)`,
/// only while the transport cooldown runs.
#[derive(Clone, Debug, Default)]
struct Idle {
wait: i32,
stroll: bool,
}
impl Goal for Idle {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if serving(m) || m.extra.scratch[3] <= 0 || !m.ai.nav.is_done() {
return false;
}
if m.random.next_int_bound(2).unwrap_or(0) == 0 {
let Some(p) = m.land_random_pos(cx.w, 2, 2) else {
return false;
};
self.stroll = true;
m.nav_move_to(cx.w, p, 1.0);
} else {
self.stroll = false;
self.wait = 30 + m.random.next_int_bound(30).unwrap_or(0);
}
true
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
if serving(m) {
return false;
}
if self.stroll {
!m.ai.nav.is_done()
} else {
self.wait > 0
}
}
fn tick(&mut self, _: &mut Mob, _: &mut Cx) {
self.wait -= 1;
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.ai.nav.stop();
}
}
/// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin.
pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
let age = m.age as f32;
let state = m.extra.variant3;
let st = &mut m.anim.states;
let interaction = |st: &mut [super::keyframes::AnimationState; 6], keep: usize| {
for (i, s) in st.iter_mut().enumerate().take(5).skip(1) {
if i != keep {
s.stop();
}
}
};
match state {
IDLE => {
interaction(st, 0);
if m.extra.ints[0] == m.age {
st[0].start(age);
} else if m.extra.ints[0] == 0 {
m.extra.ints[0] = m.age + 200 + m.random.next_int_bound(40).unwrap_or(0);
}
if m.age == m.extra.ints[0] + 10 {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound(sound(m, "spin"), at, 1.0, 1.0));
m.extra.ints[0] = 0;
}
}
s @ GETTING_ITEM..=DROPPING_NO_ITEM => {
st[0].stop();
m.extra.ints[0] = 0;
interaction(st, s as usize);
st[s as usize].start_if_stopped(age);
}
_ => {}
}
}
/// `CopperGolemModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
let get = |n: &str| animations.get(&format!("CopperGolemAnimation.COPPER_GOLEM_{n}"));
let holding = m.extra.main_hand.is_some() || m.extra.off_hand.is_some();
if holding {
if let Some(a) = get("WALK_ITEM") {
a.apply_walk(s.pos, s.speed, 2.0, 2.5, p);
}
// poseHeldItemArmsIfStill.
let right = p.get("right_arm");
right[3] = right[3].min(-0.872_664_6);
right[4] = right[4].min(-0.113_446_4);
right[5] = right[5].min(-0.064_577_185);
let left = p.get("left_arm");
left[3] = left[3].min(-0.872_664_6);
left[4] = left[4].max(0.113_446_4);
left[5] = left[5].max(0.064_577_185);
} else if let Some(a) = get("WALK") {
a.apply_walk(s.pos, s.speed, 2.0, 2.5, p);
}
for (state, name) in [
(&m.anim.states[0], "IDLE"),
(&m.anim.states[1], "CHEST_INTERACTION_NOITEM_GET"),
(&m.anim.states[2], "CHEST_INTERACTION_NOITEM_NOGET"),
(&m.anim.states[3], "CHEST_INTERACTION_ITEM_DROP"),
(&m.anim.states[4], "CHEST_INTERACTION_ITEM_NODROP"),
] {
if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) {
a.apply(ms, 1.0, p);
}
}
}
/// `WeatheringCopper.WeatherState.next`/`previous` on the variant.
pub fn weather_next(v: u8) -> u8 {
(v + 1).min(3)
}
pub fn weather_previous(v: u8) -> u8 {
v.saturating_sub(1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn weathering_stops_at_both_ends() {
assert_eq!(weather_next(3), 3);
assert_eq!(weather_previous(0), 0);
assert_eq!(weather_next(1), 2);
assert_eq!(weather_previous(2), 1);
}
}
+27 -3
View File
@@ -41,6 +41,8 @@ pub struct Rider {
pub steer: bool,
/// Sprinting (camels run faster).
pub sprint: bool,
/// Holding the jump key (a happy ghast rises).
pub jumping: bool,
}
pub fn is_equine(s: Species) -> bool {
@@ -52,8 +54,18 @@ pub fn is_equine(s: Species) -> bool {
| Species::SkeletonHorse
| Species::ZombieHorse
| Species::Camel
| Species::Llama
| Species::TraderLlama
)
}
/// `AbstractHorse.getMaxTemper`: 100, 30 for llamas.
pub fn max_temper(s: Species) -> i32 {
if super::llama::is_llama(s) {
super::llama::MAX_TEMPER
} else {
100
}
}
/// `canPerformRearing`: not donkeys or mules.
fn can_rear(s: Species) -> bool {
matches!(
@@ -65,6 +77,9 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Camel {
return super::camel::register(m);
}
if super::llama::is_llama(m.species()) {
return super::llama::register(m);
}
let tempt = m.kind.tempt.clone();
let rears = can_rear(m.species());
let g = &mut m.ai.goals;
@@ -142,6 +157,7 @@ pub fn controlled(m: &Mob) -> bool {
match m.species() {
// Pig/Strider.getControllingPassenger: saddled, the rider holding the stick.
Species::Pig | Species::Strider => m.extra.saddled && r.steer,
Species::HappyGhast => super::happy_ghast::controlled(m),
_ => m.extra.saddled || m.species() == Species::SkeletonHorse && m.extra.tame,
}
}
@@ -190,7 +206,7 @@ impl Goal for MountPanic {
/// `RunAroundLikeCrazyGoal`: an untamed horse with a rider bolts about until
/// it is tamed (temper) or throws the rider off.
#[derive(Clone, Debug)]
struct RunAroundLikeCrazy;
pub(super) struct RunAroundLikeCrazy;
impl Goal for RunAroundLikeCrazy {
goal_clone!();
fn flags(&self) -> u8 {
@@ -224,13 +240,14 @@ impl Goal for RunAroundLikeCrazy {
return;
}
let temper = i32::from(m.extra.variant3);
if m.random.next_int_bound(100).unwrap_or(0) < temper {
let max = max_temper(m.species());
if m.random.next_int_bound(max).unwrap_or(0) < temper {
// tameWithName
m.extra.tame = true;
cx.events.push(MobEvent::Tamed { mob: m.id });
return;
}
m.extra.variant3 = (temper + 5).min(100) as u8;
m.extra.variant3 = (temper + 5).min(max) as u8;
cx.events.push(MobEvent::Buck { mob: m.id });
make_mad(m, cx.events);
}
@@ -247,6 +264,7 @@ pub fn make_mad(m: &mut Mob, events: &mut Vec<MobEvent>) {
let sound = match m.species() {
Species::Donkey => "entity.donkey.angry",
Species::Mule => "entity.mule.angry",
Species::Llama | Species::TraderLlama => "entity.llama.angry",
_ => "entity.horse.angry",
};
events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
@@ -291,6 +309,9 @@ pub fn ridden_step(m: &mut Mob) {
m.body_yaw = r.yaw;
m.head_yaw = r.yaw;
m.ai.nav.stop();
if m.species() == Species::HappyGhast {
return super::happy_ghast::ridden(m);
}
if matches!(m.species(), Species::Pig | Species::Strider) {
// Pig/Strider: always forward along the rider's look, at a fraction
// of the movement speed, boosted by the stick.
@@ -375,6 +396,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.species() == Species::Camel {
return super::camel::ai_step(m, events);
}
if super::llama::is_llama(m.species()) {
return super::llama::ai_step(m, w);
}
if m.alive() && m.random.next_int_bound(900).unwrap_or(1) == 0 && m.death_time == 0 {
m.health = (m.health + 1.0).min(m.attrs.max_health);
}
+36 -5
View File
@@ -922,12 +922,25 @@ pub struct NearestTarget {
found: Option<Who>,
target_goal: TargetState,
}
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug)]
pub struct TargetState {
unseen: i32,
pub unseen_memory: i32,
reach_cache: i32,
reach_time: i32,
/// `TargetGoal.getFollowDistance` as a fraction of the follow range.
pub follow_scale: f64,
}
impl Default for TargetState {
fn default() -> Self {
Self {
unseen: 0,
unseen_memory: 0,
reach_cache: 0,
reach_time: 0,
follow_scale: 1.0,
}
}
}
impl NearestTarget {
pub fn new(prey: Prey, must_see: bool) -> Self {
@@ -954,6 +967,11 @@ impl NearestTarget {
self.interval = reduced(i);
self
}
/// Scale the follow distance (llamas hunt wolves within a quarter of it).
pub fn follow_scale(mut self, scale: f64) -> Self {
self.target_goal.follow_scale = scale;
self
}
pub fn reach(mut self) -> Self {
self.must_reach = true;
self
@@ -972,7 +990,8 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m
if !t.alive || t.is_player && t.creative {
return false;
}
if m.distance_sqr(t.position) > m.attrs.follow_range * m.attrs.follow_range {
let follow = m.attrs.follow_range * st.follow_scale;
if m.distance_sqr(t.position) > follow * follow {
return false;
}
if must_see {
@@ -1018,7 +1037,7 @@ impl Goal for NearestTarget {
{
return false;
}
let range = m.attrs.follow_range;
let range = m.attrs.follow_range * self.target_goal.follow_scale;
self.found = None;
match &self.prey {
Prey::Player => {
@@ -1429,20 +1448,32 @@ impl Goal for Breed {
}
let id = m.id;
// Horses and donkeys breed together (AbstractHorse.canParent: tame).
let equine = matches!(species, Species::Horse | Species::Donkey);
// Sniffer.canMate: calm states only.
let sniffer = species == Species::Sniffer;
if sniffer && !super::sniffer::can_mate_state(m.extra.variant) {
return false;
}
let llama = super::llama::is_llama(species);
let equine = matches!(species, Species::Horse | Species::Donkey) || llama;
if equine && !m.extra.tame {
return false;
}
// Llama.canParent: not ridden, and at full health.
if llama && (m.rider.is_some() || m.health < m.attrs.max_health) {
return false;
}
self.partner =
cx.w.nearby(m.position, 8.0, move |s| {
let same = s.species == species
|| equine && matches!(s.species, Species::Horse | Species::Donkey);
|| llama && super::llama::is_llama(s.species)
|| !llama && equine && matches!(s.species, Species::Horse | Species::Donkey);
s.id != id
&& same
&& s.in_love
&& !s.baby
&& (!tamable || s.tame)
&& (!equine || s.tame)
&& (!sniffer || super::sniffer::can_mate_state(s.variant))
})
.map(|s| s.id)
.next();
@@ -0,0 +1,470 @@
//! Happy ghasts and ghastlings (`HappyGhast`, `HappyGhastAi`): the adult
//! floats about following torchlight of snowballs and harnesses, the
//! ghastling follows players and adults, a harnessed adult can be ridden and
//! flown, healing is slow (fast in the rain) and `HappyGhastModel`.
use super::{
Mob, MobEvent, MobWorld, Species,
anim::{Poses, State},
control::{MoveKind, Operation},
goals::{Cx, Float, Goal, LOOK, MOVE, Panic, Stroll, Tempt, goal_clone},
nav::NavKind,
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
};
// Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a
// baby and 2 as an adult, `home` and `ints[4]` the restriction, `counter`
// the end tick of the follow-an-adult range pick.
pub const BABY_SCALE: f64 = 0.2375;
/// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`).
pub const FLYING_SPEED: f64 = 0.05;
pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0;
pub fn register(m: &mut Mob) {
setup(m, m.is_baby());
}
/// `adultGhastSetup` and `babyGhastSetup`.
fn setup(m: &mut Mob, baby: bool) {
m.extra.scratch[0] = if baby { 1 } else { 2 };
m.ai.goals.clear();
m.ai.nav.stop();
m.ai.mov.operation = Operation::Wait;
if baby {
m.ai.mov.kind = MoveKind::Flying {
max_turn: 180.0,
hovers: true,
};
m.ai.nav.kind = NavKind::Flying;
m.ai.nav.can_float = true;
m.ai.nav.required_path_length = 48.0;
let tempt = m.kind.food.clone();
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(0, Panic::new(2.0));
let mut t = Tempt::new(1.25, tempt, false);
t.stop_distance = 3.0;
g.add(1, t);
g.add(2, FollowAdult::default());
g.add(4, Stroll::flying(1.0));
return;
}
m.ai.mov.kind = MoveKind::Custom;
m.ai.nav.kind = NavKind::Ground;
let g = &mut m.ai.goals;
g.add(3, Float);
g.add(4, GhastTempt::default());
g.add(5, FloatAround { blocks: 16 });
}
fn wearing_harness(m: &Mob) -> bool {
m.extra.head.is_some()
}
/// `getControllingPassenger`: a player on a harnessed adult.
pub fn controlled(m: &Mob) -> bool {
m.rider.is_some() && wearing_harness(m) && !m.is_baby()
}
/// `getHappyGhastRestrictionRadius`.
fn restriction_radius(m: &Mob) -> i32 {
if !m.is_baby() && m.extra.head.is_none() {
64
} else {
32
}
}
/// `Mob.isWithinHome` for the ghast's restriction.
fn within_home(m: &Mob, p: Vec3) -> bool {
let Some(h) = m.extra.home else { return true };
let r = f64::from(m.extra.ints[4]);
let (dx, dy, dz) = (
f64::from(h[0]) + 0.5 - p.x,
f64::from(h[1]) + 0.5 - p.y,
f64::from(h[2]) + 0.5 - p.z,
);
dx * dx + dy * dy + dz * dz < r * r
}
/// `Ghast.GhastMoveControl` with the careful block checks: a push toward
/// the wanted point every few ticks while the way is clear.
pub fn move_control(m: &mut Mob, w: &MobWorld) {
if m.ai.mov.operation != Operation::MoveTo {
return;
}
m.extra.counter2 -= 1;
if m.extra.counter2 > 0 {
return;
}
m.extra.counter2 += m.random.next_int_bound(5).unwrap_or(0) + 2;
let [wx, wy, wz] = m.ai.mov.wanted;
let travel = Vec3::new(wx - m.position.x, wy - m.position.y, wz - m.position.z);
let len = travel.length();
if len < 1.0e-6 {
return;
}
let b = m.bounds();
let steps = len.ceil() as i32;
let clear = (1..=steps).all(|i| {
let f = f64::from(i) / f64::from(steps);
let d = Vec3::new(travel.x * f, travel.y * f, travel.z * f);
let at = Aabb::new(
b.min_position().add_vector(d),
b.max_position().add_vector(d),
);
w.no_collision(at) && !touches_fluid(w, at)
});
if clear {
let speed = AIR_SPEED;
m.velocity = m.velocity.add_vector(Vec3::new(
travel.x / len * f64::from(speed),
travel.y / len * f64::from(speed),
travel.z / len * f64::from(speed),
));
} else {
m.ai.mov.operation = Operation::Wait;
}
}
/// A careful ghast does not float into water or lava.
fn touches_fluid(w: &MobWorld, b: Aabb) -> bool {
let (lo, hi) = (b.min_position(), b.max_position());
for x in lo.x.floor() as i32..=hi.x.floor() as i32 {
for y in lo.y.floor() as i32..=hi.y.floor() as i32 {
for z in lo.z.floor() as i32..=hi.z.floor() as i32 {
if w.fluid(x, y, z) != crate::blocks::Fluid::None {
return true;
}
}
}
}
false
}
/// `TemptGoal.ForNonPathfinders`: drift toward a player holding food, or
/// food and harnesses for a bare adult.
#[derive(Clone, Debug, Default)]
struct GhastTempt {
calm_down: i32,
}
impl GhastTempt {
fn wants(m: &Mob, item: &Option<std::sync::Arc<str>>) -> bool {
let Some(i) = item else { return false };
let harness = !wearing_harness(m) && !m.is_baby() && i.ends_with("_harness");
harness || m.kind.food.iter().any(|f| f.as_str() == &**i)
}
}
impl Goal for GhastTempt {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if self.calm_down > 0 {
self.calm_down -= 1;
return false;
}
let Some(p) = &cx.w.player else { return false };
// Attributes.TEMPT_RANGE 16.
p.alive
&& !p.creative
&& (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand))
&& m.distance_sqr(p.position) <= 256.0
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.ai.mov.operation = Operation::Wait;
self.calm_down = 50;
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = cx.w.player.clone() else { return };
m.look_at(p.eye);
if m.distance_sqr(p.position) < 49.0 {
m.ai.mov.operation = Operation::Wait;
} else {
let f = m.random.next_double();
let at = [
(p.eye[0] - m.position.x) * f + m.position.x,
(p.eye[1] - m.position.y) * f + m.position.y,
(p.eye[2] - m.position.z) * f + m.position.z,
];
m.ai.mov.set_wanted(at[0], at[1], at[2], 1.0);
}
}
}
/// `Ghast.RandomFloatAroundGoal` with a restriction and a wish for open
/// air next to something solid.
#[derive(Clone, Debug)]
struct FloatAround {
blocks: i32,
}
impl FloatAround {
fn good(&self, w: &MobWorld, p: Vec3) -> bool {
if self.blocks <= 0 {
return true;
}
let at = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
if !w.facts.is_air(w.world.block(at[0], at[1], at[2])) {
return false;
}
for d in [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
] {
for i in 1..self.blocks {
if !w.facts.is_air(w.world.block(
at[0] + d[0] * i,
at[1] + d[1] * i,
at[2] + d[2] * i,
)) {
return true;
}
}
}
false
}
}
impl Goal for FloatAround {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
if !m.ai.mov.has_wanted() {
return true;
}
let [x, y, z] = m.ai.mov.wanted;
let d =
(x - m.position.x).powi(2) + (y - m.position.y).powi(2) + (z - m.position.z).powi(2);
!(1.0..=3600.0).contains(&d)
}
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
false
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
let c = m.position;
let mut result: Option<Vec3> = None;
for _ in 0..64 {
let r = &mut m.random;
let t = Vec3::new(
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
);
result = Some(t);
if within_home(m, t) && self.good(cx.w, t) {
break;
}
result = None;
}
let mut t = result.unwrap_or_else(|| {
let r = &mut m.random;
Vec3::new(
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
)
});
let top =
cx.w.motion_blocking_height(t.x.floor() as i32, t.z.floor() as i32);
if top < t.y.floor() as i32 && top > crate::chunk::MIN_Y {
t.y = c.y - (c.y - t.y).abs();
}
m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0);
}
}
/// `BabyFollowAdult`: a ghastling drifts toward the nearest player or adult
/// until it is a few blocks away.
#[derive(Clone, Debug, Default)]
struct FollowAdult {
close: f64,
}
impl FollowAdult {
fn target(m: &Mob, cx: &Cx) -> Option<Vec3> {
let player =
cx.w.player
.as_ref()
.filter(|p| p.alive && !p.spectator && m.distance_sqr(p.position) <= 32.0 * 32.0)
.map(|p| p.position);
player.or_else(|| {
cx.w.nearby(m.position, 32.0, |s| {
s.species == Species::HappyGhast && !s.baby
})
.next()
.map(|s| s.position)
})
}
}
impl Goal for FollowAdult {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.is_baby()
&& Self::target(m, cx).is_some_and(|t| {
let close = if self.close > 0.0 { self.close } else { 16.0 };
m.position.distance_squared(t) > close * close
})
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
Self::target(m, cx).is_some_and(|t| m.position.distance_squared(t) > 9.0)
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
// UniformInt.of(3, 16).
self.close = f64::from(3 + m.random.next_int_bound(14).unwrap_or(0));
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(t) = Self::target(m, cx) {
m.nav_move_to(cx.w, [t.x, t.y, t.z], 1.1);
}
}
}
/// What a rider asks (`getRiddenInput`, `tickRidden`).
pub fn ridden(m: &mut Mob) {
let Some(r) = m.rider else { return };
// tickRidden: turn 8% of the way toward the rider's yaw; pitch half of theirs.
let diff = super::living::wrap(r.yaw - m.yaw);
m.yaw += diff * 0.08;
m.head_pitch = r.pitch * 0.5;
m.body_yaw = m.yaw;
m.head_yaw = m.yaw;
m.ai.nav.stop();
let (mut forward, mut up) = (0.0, 0.0);
if r.forward != 0.0 {
let mut f = r.pitch.to_radians().cos();
let mut u = -r.pitch.to_radians().sin();
if r.forward < 0.0 {
f *= -0.5;
u *= -0.5;
}
forward = f;
up = u;
}
if r.jumping {
up += 0.5;
}
let scale = 3.9 * FLYING_SPEED as f32;
m.ai.xxa = r.strafe * scale;
m.ai.yya = up * scale;
m.ai.zza = forward * scale;
m.ai.mov.operation = Operation::Wait;
}
/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby
/// setup at the age boundary, the home, face-the-motion and slow healing.
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
let baby = m.is_baby();
if m.extra.scratch[0] != if baby { 1 } else { 2 } {
setup(m, baby);
}
// checkRestriction.
if m.extra.leash.is_none() && m.rider.is_none() {
let radius = restriction_radius(m);
let here = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let stale = match m.extra.home {
Some(h) => {
(h[0] - here[0]).pow(2) + (h[1] - here[1]).pow(2) + (h[2] - here[2]).pow(2)
>= (radius + 16).pow(2)
|| radius != m.extra.ints[4]
}
None => true,
};
if stale {
m.extra.home = Some(here);
m.extra.ints[4] = radius;
}
}
// LookControl: face where it is going.
if !baby && m.rider.is_none() {
let v = m.velocity;
if m.ai.target.is_none() && v.x * v.x + v.z * v.z > 1.0e-6 {
m.yaw = -(v.x.atan2(v.z) as f32).to_degrees();
m.body_yaw = m.yaw;
m.head_yaw = m.yaw;
}
}
// continuousHeal: a point every 30 seconds, every second in rain.
if m.alive() && m.death_time == 0 && m.health < m.attrs.max_health {
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let wet = w.raining && w.can_see_sky(x, y, z);
let interval = if wet { 20 } else { 600 };
if m.age.is_multiple_of(interval) {
m.health = (m.health + 1.0).min(m.attrs.max_health);
}
}
}
/// Sounds: the ghastling has its own.
pub fn sounds(m: &Mob) -> [&'static str; 3] {
if m.is_baby() {
[
"entity.ghastling.ambient",
"entity.ghastling.hurt",
"entity.ghastling.death",
]
} else {
[
"entity.happy_ghast.ambient",
"entity.happy_ghast.hurt",
"entity.happy_ghast.death",
]
}
}
/// `getSoundVolume`: 4 for adults, 1 for ghastlings.
pub fn volume(m: &Mob) -> f32 {
if m.is_baby() { 1.0 } else { 4.0 }
}
/// `HappyGhastModel.setupAnim`: the tentacles, and the body squeezed under a harness.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
if wearing_harness(m) {
let b = p.get("body");
b[6] = 0.9375;
b[7] = 0.9375;
b[8] = 0.9375;
}
super::nether::ghast_anim(s, p);
}
/// Texture of the harness layer for the worn item.
pub fn harness_texture(item: &str) -> Option<String> {
let name = item.strip_prefix("minecraft:")?;
name.ends_with("_harness")
.then(|| format!("entity/equipment/happy_ghast_body/{name}"))
}
/// Events for the player getting on or off.
pub fn goggles(down: bool, m: &Mob) -> MobEvent {
MobEvent::Sound(
if down {
"entity.happy_ghast.harness_goggles_down"
} else {
"entity.happy_ghast.harness_goggles_up"
},
m.center(),
1.0,
1.0,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_harness_names_its_texture() {
assert_eq!(
harness_texture("minecraft:red_harness").as_deref(),
Some("entity/equipment/happy_ghast_body/red_harness")
);
assert_eq!(harness_texture("minecraft:saddle"), None);
}
#[test]
fn travel_speed_is_five_thirds_of_the_flying_speed() {
assert!((f64::from(AIR_SPEED) - FLYING_SPEED * 5.0 / 3.0).abs() < 1e-7);
}
}
+400
View File
@@ -0,0 +1,400 @@
//! Leads (`Leashable`): who holds a mob's lead and the elastic physics of
//! `Leashable.tickLeash` (a pull once the rope stretches past six blocks,
//! the lead snapping past twelve, `PathfinderMob`'s walk toward the holder
//! while the rope is slack).
use super::{Mob, MobEvent, MobWorld, Species, Who};
use horizon_core::geometry::Vec3;
use horizon_world::nbt::Tag;
/// `Leashable.LEASH_ELASTIC_DIST`.
pub const ELASTIC: f64 = 6.0;
/// `Leashable.LEASH_TOO_FAR_DIST`.
pub const SNAP: f64 = 12.0;
/// What holds the other end of a lead.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Holder {
Player,
Mob(u32),
/// A `LeashFenceKnotEntity` on the fence at this block.
Knot([i32; 3]),
}
impl Holder {
pub fn who(self) -> Option<Who> {
match self {
Holder::Player => Some(Who::Player),
Holder::Mob(id) => Some(Who::Mob(id)),
Holder::Knot(_) => None,
}
}
}
/// A holder read from a save that is not in the world yet (the entity may
/// load later): the holder's UUID, or the fence knot's block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pending {
Uuid([i32; 4]),
Knot([i32; 3]),
}
/// `Leashable.LeashData.CODEC`: `{UUID: [I;..]}` for an entity holder or the
/// fence's block position as an int array.
pub fn pending_from_nbt(tag: Option<&Tag>) -> Option<Pending> {
match tag? {
Tag::IntArray(p) if p.len() == 3 => Some(Pending::Knot([p[0], p[1], p[2]])),
t @ Tag::Compound(_) => crate::save::uuid_from_tag(t.get("UUID")).map(Pending::Uuid),
_ => None,
}
}
/// The `leash` tag for a holder: the holder entity's UUID, or the knot's block.
pub fn to_nbt(holder: Holder, uuid: Option<[i32; 4]>) -> Option<Tag> {
match holder {
Holder::Knot(p) => Some(Tag::IntArray(p.to_vec())),
_ => uuid.map(|u| Tag::compound([("UUID", Tag::IntArray(u.to_vec()))])),
}
}
/// Where the other end of the lead is this tick.
#[derive(Clone, Copy, Debug)]
pub struct HolderState {
pub position: Vec3,
pub center: Vec3,
pub width: f64,
pub height: f64,
pub yaw: f32,
pub velocity: Vec3,
}
/// `LeashFenceKnotEntity`: 0.375 wide, 0.5 tall, centred a block's 0.375 up.
pub fn knot_state(pos: [i32; 3]) -> HolderState {
let position = Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.375,
f64::from(pos[2]) + 0.5,
);
HolderState {
position,
center: Vec3::new(position.x, position.y + 0.25, position.z),
width: 0.375,
height: 0.5,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
/// The holder's state, or `None` when it is gone.
pub fn holder_state(w: &MobWorld, holder: Holder) -> Option<HolderState> {
match holder {
Holder::Player => {
let p = w.player.as_ref()?;
let size = p.bounds.max_position().subtract(p.bounds.min_position());
Some(HolderState {
position: p.position,
center: Vec3::new(p.position.x, p.position.y + size.y / 2.0, p.position.z),
width: size.x,
height: size.y,
yaw: p.yaw,
velocity: p.velocity,
})
}
Holder::Mob(id) => {
let s = w.seen(id).filter(|s| s.alive)?;
let lo = s.bounds.min_position();
let hi = s.bounds.max_position();
Some(HolderState {
position: s.position,
center: Vec3::new(
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
),
width: hi.x - lo.x,
height: hi.y - lo.y,
yaw: s.yaw,
velocity: s.velocity,
})
}
Holder::Knot(pos) => {
let fence = w.has_tag("minecraft:fences", w.block_name(pos[0], pos[1], pos[2]));
fence.then(|| knot_state(pos))
}
}
}
/// `Entity.yRot(angle)` on a vector (rotation about the Y axis).
fn rot_y(v: [f64; 3], angle: f64) -> [f64; 3] {
let (s, c) = (angle.sin(), angle.cos());
[v[0] * c + v[2] * s, v[1], v[2] * c - v[0] * s]
}
/// `Leashable.computeDampenedSpringInteraction` for the single attachment
/// of a mob (0, 0.5, 0.5 of its box) and its holder (0, 0.5, 0): the force
/// toward the holder and the torque on the mob, or `None` while slack.
pub fn spring(
position: Vec3,
yaw: f32,
size: (f64, f64),
holder: &HolderState,
own_motion: Vec3,
) -> Option<([f64; 3], f64)> {
let (w, h) = size;
let lever = rot_y([0.0, 0.5 * h, 0.5 * w], -f64::from(yaw.to_radians()));
let object = [
position.x + lever[0],
position.y + lever[1],
position.z + lever[2],
];
let arm = rot_y(
[0.0, 0.5 * holder.height, 0.0],
-f64::from(holder.yaw.to_radians()),
);
let pivot = [
holder.position.x + arm[0],
holder.position.y + arm[1],
holder.position.z + arm[2],
];
let d = [
pivot[0] - object[0],
pivot[1] - object[1],
pivot[2] - object[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if distance < ELASTIC {
return None;
}
let scale = (distance - ELASTIC) / distance;
let mut force = [d[0] * scale, d[1] * scale, d[2] * scale];
let torque = lever[2] * force[0] - lever[0] * force[2];
let same_direction =
own_motion.x * force[0] + own_motion.y * force[1] + own_motion.z * force[2] >= 0.0;
if same_direction {
for f in &mut force {
*f *= f64::from(0.3_f32);
}
}
Some((force, torque))
}
/// `Entity.checkFallDistanceAccumulation`.
fn check_fall_distance(m: &mut Mob) {
if m.velocity.y > -0.5 && m.fall_distance > 1.0 {
m.fall_distance = 1.0;
}
}
/// Whether a mob can be put on a lead (`Mob.canBeLeashed` and overrides).
pub fn can_be_leashed(m: &Mob) -> bool {
use Species as S;
match m.species() {
S::Hoglin | S::Zoglin => true,
S::Villager
| S::WanderingTrader
| S::Turtle
| S::Panda
| S::Bat
| S::Cod
| S::Salmon
| S::TropicalFish
| S::Pufferfish
| S::Tadpole => false,
S::Wolf => !super::tame::angry(m),
_ => !m.hostile() && !m.removed,
}
}
/// `Leashable.tickLeash` at the end of `Entity.baseTick`.
pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let Some(holder) = m.extra.leash else {
m.extra.leash_spin = 0.0;
return;
};
let Some(state) = holder_state(w, holder) else {
// The holder is gone: the lead drops.
if !matches!(holder, Holder::Player) {
events.push(MobEvent::LeashBreak {
mob: m.id,
drop: true,
sound: false,
});
}
return;
};
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
let center = Vec3::new(
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
);
let distance = ((state.center.x - center.x).powi(2)
+ (state.center.y - center.y).powi(2)
+ (state.center.z - center.z).powi(2))
.sqrt();
if distance > SNAP {
events.push(MobEvent::LeashBreak {
mob: m.id,
drop: true,
sound: true,
});
return;
}
let stretched = distance > ELASTIC - state.width - f64::from(m.width());
let pulled = stretched
&& spring(
m.position,
m.yaw,
(f64::from(m.width()), f64::from(m.height())),
&state,
m.velocity,
)
.is_some_and(|(force, torque)| {
m.extra.leash_spin += 10.0 * torque;
let rel = Vec3::new(
state.velocity.x - m.velocity.x,
state.velocity.y - m.velocity.y,
state.velocity.z - m.velocity.z,
);
m.velocity = Vec3::new(
m.velocity.x + force[0] * 0.8 + rel.x * 0.11,
m.velocity.y + force[1] * 0.2 + rel.y * 0.11,
m.velocity.z + force[2] * 0.8 + rel.z * 0.11,
);
check_fall_distance(m);
true
});
if !pulled {
close_range(m, w, &state);
}
m.yaw -= m.extra.leash_spin as f32;
let friction = if m.on_ground {
0.6 * 0.91
} else if m.is_in_liquid() {
0.8
} else {
0.91
};
m.extra.leash_spin *= friction;
}
/// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of
/// the holder unless panicking.
fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) {
if m.ai.panicking {
return;
}
let d = Vec3::new(
holder.position.x - m.position.x,
holder.position.y - m.position.y,
holder.position.z - m.position.z,
);
let dist = d.length();
let len = d.length();
let scale = if len > 0.0 {
(dist - 2.0).max(0.0) / len
} else {
0.0
};
let target = [
m.position.x + d.x * scale,
m.position.y + d.y * scale,
m.position.z + d.z * scale,
];
let speed = follow_speed(m);
m.nav_move_to(w, target, speed);
}
/// `followLeashSpeed`: 1.0, 2.0 for llamas.
pub fn follow_speed(m: &Mob) -> f64 {
if super::llama::is_llama(m.species()) {
2.0
} else {
1.0
}
}
/// `Mob.leashable` position of the rope on a mob (`getLeashOffset`).
pub fn leash_offset(m: &Mob) -> [f64; 3] {
if super::llama::is_llama(m.species()) {
// Llama.getLeashOffset.
[0.0, 0.75 * m.eye_height(), f64::from(m.width()) * 0.5]
} else {
[0.0, m.eye_height(), f64::from(m.width() * 0.4)]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rotating_about_y_matches_vanilla() {
let v = rot_y([0.0, 1.0, 1.0], std::f64::consts::FRAC_PI_2);
assert!((v[0] - 1.0).abs() < 1e-9 && v[2].abs() < 1e-9);
}
fn holder(x: f64) -> HolderState {
let position = Vec3::new(x, 64.0, 0.0);
HolderState {
position,
center: Vec3::new(x, 64.9, 0.0),
width: 0.6,
height: 1.8,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
#[test]
fn a_slack_rope_does_not_pull() {
let pulled = spring(
Vec3::new(0.0, 64.0, 0.0),
0.0,
(0.9, 1.87),
&holder(3.0),
Vec3::ZERO,
);
assert!(pulled.is_none());
}
#[test]
fn a_stretched_rope_pulls_toward_the_holder() {
let (force, _) = spring(
Vec3::new(0.0, 64.0, 0.0),
0.0,
(0.9, 1.87),
&holder(10.0),
Vec3::ZERO,
)
.expect("past the slack");
// Moving away from nothing: the same-direction damping applies.
assert!(force[0] > 0.0);
assert!(force[0] < 10.0 - ELASTIC);
}
#[test]
fn moving_with_the_pull_damps_it() {
let at = Vec3::new(0.0, 64.0, 0.0);
let still = spring(
at,
0.0,
(0.9, 1.87),
&holder(10.0),
Vec3::new(-0.1, 0.0, 0.0),
)
.expect("pull")
.0;
let following = spring(
at,
0.0,
(0.9, 1.87),
&holder(10.0),
Vec3::new(0.1, 0.0, 0.0),
)
.expect("pull")
.0;
assert!((following[0] - still[0] * 0.3_f32 as f64).abs() < 1e-9);
}
#[test]
fn leash_tags_round_trip() {
let knot = to_nbt(Holder::Knot([1, 2, 3]), None).expect("knot tag");
assert_eq!(
pending_from_nbt(Some(&knot)),
Some(Pending::Knot([1, 2, 3]))
);
let held = to_nbt(Holder::Player, Some([4, 5, 6, 7])).expect("uuid tag");
assert_eq!(
pending_from_nbt(Some(&held)),
Some(Pending::Uuid([4, 5, 6, 7]))
);
assert_eq!(to_nbt(Holder::Mob(1), None), None);
}
#[test]
fn a_knot_sits_on_the_fence_post() {
let k = knot_state([10, 64, -3]);
assert_eq!(k.position.x, 10.5);
assert_eq!(k.position.y, 64.375);
assert_eq!(k.center.y, 64.625);
}
}
+13
View File
@@ -90,6 +90,10 @@ impl Mob {
pub fn dims(&self) -> (f64, f64, f64) {
let k = &self.kind;
let (mut w, mut h, mut e) = (k.width, k.height, k.eye_height);
// Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81.
if k.species == super::Species::Sniffer && super::sniffer::digging(self) {
(h, e) = (h - f64::from(0.4_f32), f64::from(0.81_f32));
}
if self.is_baby() {
match super::species::def(k.species).baby {
super::species::Baby::Abs(bw, bh, be) => (w, h, e) = (bw, bh, be),
@@ -126,6 +130,10 @@ impl Mob {
self.extra.age < 0
}
pub fn fluid_jump_threshold(&self) -> f64 {
// Breeze.getFluidJumpThreshold: its eye height.
if self.species() == super::Species::Breeze {
return self.eye_height();
}
if self.eye_height() < 0.4 { 0.0 } else { 0.4 }
}
pub fn is_in_liquid(&self) -> bool {
@@ -311,6 +319,11 @@ impl Mob {
} else {
y -= self.gravity();
}
// LivingEntity.shouldDiscardFriction (a breeze's long jump).
if super::breeze::discards_friction(self) {
self.velocity = Vec3::new(movement.x, y, movement.z);
return;
}
let drag = 0.91f32;
let f = friction * drag;
let vertical = if self.kind.flags.omnidirectional {
+286
View File
@@ -0,0 +1,286 @@
//! Llamas and trader llamas (`Llama`, `TraderLlama`): coat variants and
//! strength, chests and carpets, taming by riding (maximum temper 30), the
//! spit ranged attack, hunting wolves (and, for traders, zombies and
//! illagers) and `LlamaModel`.
use super::{
Mob, MobEvent, MobWorld, Seen, Species, Who,
anim::{Poses, State},
equine,
goals::{
Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic,
Prey, RandomLookAround, Stroll, Tempt, goal_clone,
},
witch::RangedAttack,
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"];
/// `Llama.getMaxTemper`.
pub const MAX_TEMPER: i32 = 30;
// Llama state: `variant` the coat, `variant2` the strength (1 to 5),
// `variant3` the temper, `chested` the chest, `head` the carpet, `flag2`
// `didSpit`, `ints[0]` a trader llama's despawn delay.
pub fn is_llama(s: Species) -> bool {
matches!(s, Species::Llama | Species::TraderLlama)
}
pub fn is_trader(m: &Mob) -> bool {
m.species() == Species::TraderLlama
}
/// `Llama.getStrength`.
pub fn strength(m: &Mob) -> i32 {
i32::from(m.extra.variant2).clamp(1, 5)
}
/// `getInventoryColumns`: a chest holds three rows of `strength` columns.
pub fn inventory_columns(m: &Mob) -> i32 {
if m.extra.chested { strength(m) } else { 0 }
}
/// The mob is a zombie of any kind (`Zombie.class`).
fn is_zombie(s: &Seen) -> bool {
matches!(
s.species,
Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager
)
}
/// The mob is an illager (`AbstractIllager.class`).
pub fn is_illager(s: &Seen) -> bool {
matches!(
s.species,
Species::Pillager | Species::Vindicator | Species::Evoker
)
}
pub fn register(m: &mut Mob) {
m.ai.nav.required_path_length = 40.0;
let tempt = m.kind.tempt.clone();
let trader = is_trader(m);
if trader {
m.extra.ints[0] = DEFAULT_DESPAWN_DELAY;
}
let g = &mut m.ai.goals;
g.add(0, Float);
if trader {
g.add(1, Panic::new(2.0));
}
g.add(1, equine::RunAroundLikeCrazy);
g.add(2, super::caravan::FollowCaravan::new(2.1));
g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit));
g.add(3, Panic::new(1.2));
g.add(4, Breed::new(1.0));
g.add(5, Tempt::new(1.25, tempt, false));
g.add(6, FollowParent::new(1.0));
g.add(7, Stroll::avoiding_water(0.7));
g.add(8, LookAtPlayer::new(6.0));
g.add(9, RandomLookAround::default());
m.ai.targets.add(1, LlamaHurtBy(HurtByTarget::new()));
if trader {
m.ai.targets.add(1, super::caravan::DefendTrader::default());
}
m.ai.targets.add(
2,
NearestTarget::new(
Prey::Filter(|s| s.species == Species::Wolf && !s.tame),
false,
)
.interval(16)
.reach()
.follow_scale(0.25),
);
if trader {
m.ai.targets
.add(2, NearestTarget::new(Prey::Filter(is_zombie), true));
m.ai.targets
.add(2, NearestTarget::new(Prey::Filter(is_illager), true));
}
}
/// `TraderLlama.DEFAULT_DESPAWN_DELAY`.
pub const DEFAULT_DESPAWN_DELAY: i32 = 47999;
/// `Llama.finalizeSpawn` and `AbstractChestedHorse.randomizeAttributes`:
/// health 15 to 30, a coat and the strength.
pub fn finalize(m: &mut Mob) {
let r = &mut m.random;
let health =
15.0 + r.next_int_bound(8).unwrap_or(0) as f32 + r.next_int_bound(9).unwrap_or(0) as f32;
let max = if r.next_float() < 0.04 { 5 } else { 3 };
let strength = 1 + r.next_int_bound(max).unwrap_or(0);
let variant = r.next_int_bound(4).unwrap_or(0);
m.attrs.max_health = health;
m.health = health;
m.extra.variant2 = strength as u8;
m.extra.variant = variant as u8;
m.extra.vector[0] = m.kind.jump_strength;
}
/// `Llama.getBreedOffspring` after `setOffspringAttributes`: the strength
/// (rarely one more) and either parent's coat.
pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) {
let top = strength(a).max(strength(b));
let mut s = r.next_int_bound(top).unwrap_or(0) + 1;
if r.next_float() < 0.03 {
s += 1;
}
child.extra.variant2 = s.clamp(1, 5) as u8;
child.extra.variant = if r.next_boolean() {
a.extra.variant
} else {
b.extra.variant
};
if is_trader(child) {
child.persistent = true;
}
}
/// `LlamaHurtByTargetGoal`: stops hunting right after a spit.
#[derive(Clone, Debug)]
struct LlamaHurtBy(HurtByTarget);
impl Goal for LlamaHurtBy {
goal_clone!();
fn flags(&self) -> u8 {
self.0.flags()
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_use(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.extra.flag2 {
m.extra.flag2 = false;
return false;
}
self.0.can_continue(m, cx)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.start(m, cx)
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.stop(m, cx)
}
}
/// `Llama.performRangedAttack` / `spit`: a llama spit toward the target's
/// lower third, 1.5 fast, with 10 degrees of spread.
fn spit(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
let Some(t) = cx.w.target_info(who) else {
return;
};
let body = m.body_yaw.to_radians();
let reach = (f64::from(m.width()) + 1.0) * 0.5;
let start = Vec3::new(
m.position.x - reach * f64::from(body.sin()),
m.eye_y() - f64::from(0.1_f32),
m.position.z + reach * f64::from(body.cos()),
);
let top = t.bounds.max_position();
let low = t.bounds.min_position();
let xd = t.position.x - m.position.x;
let yd = low.y + (top.y - low.y) * 0.333_333_333_333_333_3 - start.y;
let zd = t.position.z - m.position.z;
let yo = (xd * xd + zd * zd).sqrt() * f64::from(0.2_f32);
let mut p = Projectile::new(ProjectileKind::LlamaSpit, start, Some(Who::Mob(m.id)));
p.shoot(&mut m.random, [xd, yd + yo, zd], 1.5, 10.0);
cx.events.push(MobEvent::Projectile(p));
let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2;
cx.events.push(MobEvent::Sound(
"entity.llama.spit",
[m.position.x, m.position.y, m.position.z],
1.0,
pitch,
));
m.extra.flag2 = true;
}
/// `AbstractHorse.aiStep` for llamas, which never graze: the slow healing.
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
if m.alive() && m.random.next_int_bound(900).unwrap_or(1) == 0 && m.death_time == 0 {
m.health = (m.health + 1.0).min(m.attrs.max_health);
}
if is_trader(m) {
super::caravan::trader_llama_tick(m, w);
}
}
/// The llama's own save fields, over the horse ones: `Variant` (the coat id),
/// `Strength` and a trader llama's `DespawnDelay`.
pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
use horizon_world::nbt::Tag;
map.insert("Variant".into(), Tag::Int(i32::from(m.extra.variant)));
map.insert("Strength".into(), Tag::Int(strength(m)));
if is_trader(m) {
map.insert("DespawnDelay".into(), Tag::Int(m.extra.ints[0]));
}
}
pub fn from_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
use crate::save::number;
m.extra.variant = number(tag.get("Variant")).unwrap_or(0).clamp(0, 3) as u8;
m.extra.variant2 = number(tag.get("Strength")).unwrap_or(1).clamp(1, 5) as u8;
m.extra.variant3 = i32::from(m.extra.variant3).min(MAX_TEMPER) as u8;
if is_trader(m) {
m.extra.ints[0] =
number(tag.get("DespawnDelay")).map_or(DEFAULT_DESPAWN_DELAY, |v| v as i32);
}
}
/// The coat texture (`LlamaRenderer`).
pub fn texture(m: &Mob) -> String {
let baby = if m.is_baby() { "_baby" } else { "" };
let coat = VARIANTS[(m.extra.variant as usize).min(3)];
format!("entity/llama/llama_{coat}{baby}")
}
/// The carpet colour on the llama, if it wears one.
fn carpet(m: &Mob) -> Option<&str> {
m.extra
.head
.as_deref()
.and_then(|i| i.strip_prefix("minecraft:"))
.and_then(|i| i.strip_suffix("_carpet"))
}
/// `LlamaDecorLayer`: the carpet of an adult, else the trader's blanket.
pub fn decor(m: &Mob) -> Option<(String, String)> {
let baby = m.is_baby();
let model = if baby {
"llama_baby#decor"
} else {
"llama#decor"
};
if let Some(color) = carpet(m)
&& !baby
{
return Some((model.into(), format!("entity/equipment/llama_body/{color}")));
}
is_trader(m).then(|| {
let name = if baby {
"trader_llama_baby"
} else {
"trader_llama"
};
(model.into(), format!("entity/equipment/llama_body/{name}"))
})
}
/// `LlamaModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
super::anim::quadruped(p, s);
let chest = m.extra.chested && !s.baby;
for part in ["right_chest", "left_chest"] {
if !chest {
p.visible(part, false);
}
}
let _ = PI;
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::random::LegacyRandom;
#[test]
fn strength_stays_in_range_and_rarely_reaches_five() {
let mut r = LegacyRandom::new(7);
let mut fives = 0;
for _ in 0..4000 {
let max = if r.next_float() < 0.04 { 5 } else { 3 };
let s = 1 + r.next_int_bound(max).unwrap();
assert!((1..=5).contains(&s));
fives += i32::from(s > 3);
}
assert!(fives > 0 && fives < 200);
}
#[test]
fn a_chest_holds_strength_columns() {
assert_eq!(DEFAULT_DESPAWN_DELAY, 47999);
assert_eq!(MAX_TEMPER, 30);
}
}
+66
View File
@@ -106,6 +106,17 @@ pub fn body(m: &Mob) -> (String, String) {
return ("main".into(), m.kind.texture.to_string());
}
match m.species() {
S::Llama | S::TraderLlama => {
let name = if m.species() == S::Llama {
"llama"
} else {
"trader_llama"
};
(
baby_or(m, &format!("{name}#main"), &format!("{name}_baby#main")),
super::llama::texture(m),
)
}
s if super::equine::is_equine(s) => {
let name = super::equine::model_name(s);
(
@@ -117,6 +128,22 @@ pub fn body(m: &Mob) -> (String, String) {
baby_or(m, "wolf#main", "wolf_baby#main"),
super::tame::texture(m),
),
S::HappyGhast => (
baby_or(m, "happy_ghast#main", "happy_ghast_baby#main"),
if baby {
"entity/ghast/happy_ghast_baby".into()
} else {
"entity/ghast/happy_ghast".into()
},
),
S::Sniffer => (
baby_or(m, "sniffer#main", "sniffer_baby#main"),
if baby {
"entity/sniffer/snifflet".into()
} else {
"entity/sniffer/sniffer".into()
},
),
S::Shulker => ("shulker#main".into(), super::shulker::texture(m)),
S::Vex => ("vex#main".into(), super::vex::texture(m).into()),
S::Wither => ("wither#main".into(), super::wither::texture(m).into()),
@@ -302,6 +329,41 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
false,
);
}
// SimpleEquipmentLayer: the harness over the body.
S::HappyGhast if !m.is_baby() => {
if let Some(texture) = m
.extra
.head
.as_deref()
.and_then(super::happy_ghast::harness_texture)
{
push(&mut v, "happy_ghast_harness#main", &texture, white, false);
}
}
// BreezeWindLayer (the scroll is not reproduced: atlas sprites do
// not wrap) and BreezeEyesLayer.
S::Breeze => {
push(
&mut v,
"breeze#wind",
"entity/breeze/breeze_wind",
white,
false,
);
push(
&mut v,
"breeze#eyes",
"entity/breeze/breeze_eyes",
white,
true,
);
}
// LlamaDecorLayer: the carpet, or the trader's blanket.
S::Llama | S::TraderLlama => {
if let Some((model, texture)) = super::llama::decor(m) {
push(&mut v, &model, &texture, white, false);
}
}
// HorseMarkingLayer, the saddle and the horse armour.
s if super::equine::is_equine(s) => {
let name = super::equine::model_name(s);
@@ -760,6 +822,10 @@ pub fn render_with(
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
// The invisibility effect hides the model (a drinking wandering trader).
if super::trader::is_invisible(m) {
return;
}
let base = base_transform(m, alpha, camera);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
+651
View File
@@ -0,0 +1,651 @@
//! Sniffers (`Sniffer`, `SnifferAi`): the brain's core, idle, sniff and dig
//! activities, scenting and sniffing for diggable ground, walking there,
//! digging up a seed, the explored positions, laying eggs when bred, and
//! `SnifferModel`'s keyframe animations.
use super::{
Mob, MobEvent, MobWorld,
anim::{Poses, State},
brain::{Sink, Ttl, WalkTarget, duration},
goals::{Breed, Cx, Float, Goal, Panic, Tempt, goal_clone},
keyframes::Animation,
};
use horizon_core::random::RandomSource;
use std::collections::HashMap;
// Sniffer state: `variant` the state (below), `scratch[0]` the state the
// animations last saw, `positions` the explored positions (newest first),
// `ints[3]` the tick the dug seed drops. AnimState states: feeling happy,
// scenting, sniffing, digging, rising.
pub const IDLING: u8 = 0;
pub const FEELING_HAPPY: u8 = 1;
pub const SCENTING: u8 = 2;
pub const SNIFFING: u8 = 3;
pub const SEARCHING: u8 = 4;
pub const DIGGING: u8 = 5;
pub const RISING: u8 = 6;
const SNIFF_COOLDOWN: i32 = 9600;
/// `Sniffer.getBabyStartAge`.
pub const BABY_START_AGE: i32 = -48000;
pub fn state(m: &Mob) -> u8 {
m.extra.variant
}
fn set_state(m: &mut Mob, s: u8) {
m.extra.variant = s;
}
/// `Sniffer.getDefaultDimensions`: lower while digging.
pub fn digging(m: &Mob) -> bool {
state(m) == DIGGING
}
pub fn register(m: &mut Mob) {
use super::path::PathType;
m.ai.nav.can_float = true;
m.set_malus(PathType::Water, -1.0);
m.set_malus(PathType::OnTopOfPowderSnow, -1.0);
m.set_malus(PathType::DamageCautious, -1.0);
let tempt = m.kind.tempt.clone();
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(0, SnifferPanic(Panic::new(2.0)));
g.add(
0,
Brain {
walk: None,
sink: Sink::new(500, 700),
look: None,
look_until: 0,
digging: false,
happy: false,
cooldown: Ttl::default(),
sniff_target: None,
run: Run::None,
until: 0,
breed: Breed::new(1.0),
tempt: Tempt::new(1.25, tempt, false),
love_on: false,
tempt_on: false,
},
);
}
/// The core's `AnimalPanic`, forgetting any sniffing when it starts.
#[derive(Clone, Debug)]
struct SnifferPanic(Panic);
impl Goal for SnifferPanic {
goal_clone!();
fn flags(&self) -> u8 {
self.0.flags()
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_use(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(m, cx)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
set_state(m, IDLING);
self.0.start(m, cx)
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.stop(m, cx)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Run {
None,
Digging,
FinishedDigging,
Searching,
Happy,
Scenting,
Sniffing,
DoNothing,
}
#[derive(Clone, Debug)]
struct Brain {
walk: Option<WalkTarget>,
sink: Sink,
/// `LOOK_TARGET` and the end of `LookAtTargetSink`'s run (0 when not running).
look: Option<[f64; 3]>,
look_until: i32,
/// `SNIFFER_DIGGING`, `SNIFFER_HAPPY`, `SNIFF_COOLDOWN`, `SNIFFER_SNIFFING_TARGET`.
digging: bool,
happy: bool,
cooldown: Ttl,
sniff_target: Option<[i32; 3]>,
/// The timed behaviour running and when it times out.
run: Run,
until: i32,
breed: Breed,
tempt: Tempt,
love_on: bool,
tempt_on: bool,
}
impl Goal for Brain {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
true
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.brain(m, cx);
}
}
fn now(m: &Mob) -> i32 {
m.age as i32
}
fn sound(m: &Mob, cx: &mut Cx, name: &'static str, pitch: f32) {
cx.events
.push(MobEvent::Sound(name, m.center(), 1.0, pitch));
}
/// `Sniffer.getOnPos`: the block under its feet.
fn on_pos(m: &Mob) -> [i32; 3] {
[
m.position.x.floor() as i32,
(m.position.y - 0.2).floor() as i32,
m.position.z.floor() as i32,
]
}
/// `Sniffer.getHeadBlock`: 2.25 blocks ahead of it, a little above its feet.
pub fn head_block(m: &Mob) -> [i32; 3] {
let (yaw, pitch) = (m.yaw.to_radians(), m.head_pitch.to_radians());
let forward = [
f64::from(-yaw.sin() * pitch.cos()),
f64::from(-pitch.sin()),
f64::from(yaw.cos() * pitch.cos()),
];
[
(m.position.x + forward[0] * 2.25).floor() as i32,
(m.position.y + f64::from(0.2_f32)).floor() as i32,
(m.position.z + forward[2] * 2.25).floor() as i32,
]
}
impl Brain {
fn tempted(&self) -> bool {
self.tempt_on
}
/// `Sniffer.canSniff`.
fn can_sniff(&self, m: &Mob) -> bool {
!self.tempted()
&& !m.ai.panicking
&& !m.fluids.in_water
&& m.extra.in_love <= 0
&& m.on_ground
&& m.rider.is_none()
&& m.extra.leash.is_none()
}
/// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable.
fn can_dig_at(&self, m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool {
w.has_tag(
"minecraft:sniffer_diggable_block",
w.block_name(p[0], p[1], p[2]),
) && !m.extra.positions.contains(&p)
&& m.create_path_to(w, p, 1).is_some_and(|path| path.reached)
}
/// `Sniffer.canDig`.
fn can_dig(&self, m: &mut Mob, w: &MobWorld) -> bool {
if m.ai.panicking
|| self.tempted()
|| m.is_baby()
|| m.fluids.in_water
|| !m.on_ground
|| m.rider.is_some()
{
return false;
}
let head = head_block(m);
self.can_dig_at(m, w, [head[0], head[1] - 1, head[2]])
}
/// `Sniffer.calculateDigPosition`.
fn dig_position(&self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> {
for idx in 0..5 {
let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else {
continue;
};
let below = [
p[0].floor() as i32,
p[1].floor() as i32 - 1,
p[2].floor() as i32,
];
if self.can_dig_at(m, w, below) {
return Some(below);
}
}
None
}
fn transition(&mut self, m: &mut Mob, cx: &mut Cx, to: u8) {
match to {
FEELING_HAPPY => sound(m, cx, "entity.sniffer.happy", 1.0),
SCENTING => {
let pitch = if m.is_baby() { 1.3 } else { 1.0 };
sound(m, cx, "entity.sniffer.scenting", pitch)
}
SNIFFING => sound(m, cx, "entity.sniffer.sniffing", 1.0),
DIGGING => m.extra.ints[3] = now(m) + 120,
RISING => sound(m, cx, "entity.sniffer.digging_stop", 1.0),
_ => {}
}
set_state(m, to);
}
/// `SnifferAi.resetSniffing`.
fn reset_sniffing(&mut self, m: &mut Mob, cx: &mut Cx) {
self.digging = false;
self.sniff_target = None;
self.transition(m, cx, IDLING);
}
fn brain(&mut self, m: &mut Mob, cx: &mut Cx) {
self.cooldown.tick();
// Tempted: the tempting player memory while the goal runs.
if m.ai.panicking {
self.walk = None;
self.sink.stop(m, &mut self.walk);
self.love_on = false;
self.tempt_on = false;
} else {
self.start_behaviours(m, cx);
}
self.sink.tick(m, cx, &mut self.walk);
self.tick_running(m, cx);
}
/// `Brain.startEachNonRunningBehavior` for the first valid activity.
fn start_behaviours(&mut self, m: &mut Mob, cx: &mut Cx) {
let n = now(m);
// DIG, SNIFF, IDLE.
let dig = self.digging && self.walk.is_none();
let sniff = self.sniff_target.is_some() && self.walk.is_some();
if dig {
if self.run == Run::None && !self.cooldown.present() && self.can_sniff(m) {
self.run = Run::Digging;
self.until = n + duration(m, 160, 180);
self.transition(m, cx, DIGGING);
}
if self.run == Run::None && self.cooldown.present() {
self.run = Run::FinishedDigging;
self.until = n + 40;
self.transition(m, cx, RISING);
}
return;
}
if sniff {
if self.run == Run::None && self.can_sniff(m) {
self.run = Run::Searching;
self.until = n + 600;
self.transition(m, cx, SEARCHING);
}
return;
}
if self.digging {
return;
}
// IDLE: love, tempt, look at the target, feeling happy, one of the rest.
if !self.love_on && !self.tempt_on && self.breed.can_use(m, cx) {
self.reset_sniffing(m, cx);
self.breed.start(m, cx);
self.love_on = true;
}
if !self.love_on && !self.tempt_on && self.tempt.can_use(m, cx) {
self.reset_sniffing(m, cx);
self.tempt.start(m, cx);
self.tempt_on = true;
}
if self.look.is_some() && self.look_until == 0 {
self.look_until = n + duration(m, 45, 90);
}
if self.run == Run::None && self.happy {
self.run = Run::Happy;
self.until = n + duration(m, 40, 100);
self.transition(m, cx, FEELING_HAPPY);
}
if self.run == Run::None {
self.run_one(m, cx);
}
}
/// The idle `RunOne`: a weighted random pick among what can start.
fn run_one(&mut self, m: &mut Mob, cx: &mut Cx) {
let n = now(m);
// (weight, option)
let mut options: Vec<(i32, u8)> = Vec::new();
if self.look.is_some() && self.walk.is_none() {
options.push((2, 0));
}
if !self.happy && !self.love_on && !self.tempted() && self.sniff_target.is_none() {
options.push((1, 1));
}
if self.walk.is_none()
&& self.sniff_target.is_none()
&& !self.cooldown.present()
&& !m.is_baby()
&& self.can_sniff(m)
{
options.push((1, 2));
}
if cx.w.player.as_ref().is_some_and(|p| {
p.alive && !p.creative && m.distance_sqr(p.position) <= 36.0 && !p.spectator
}) {
options.push((1, 3));
}
if self.walk.is_none() {
options.push((1, 4));
}
options.push((2, 5));
let total: i32 = options.iter().map(|o| o.0).sum();
// A weighted pick from the high bits (`WeightedList.getRandom`).
let mut roll = ((m.random.next_float() * total as f32) as i32).min(total - 1);
let mut pick = options[0].1;
for (w, o) in &options {
if roll < *w {
pick = *o;
break;
}
roll -= w;
}
match pick {
// SetWalkTargetFromLookTarget(1.0, 3).
0 => {
if let Some(l) = self.look {
self.walk = Some(WalkTarget::new(
[
l[0].floor() as i32,
l[1].floor() as i32,
l[2].floor() as i32,
],
1.0,
3,
));
}
}
1 => {
self.run = Run::Scenting;
self.until = n + duration(m, 40, 80);
self.transition(m, cx, SCENTING);
}
2 => {
self.run = Run::Sniffing;
self.until = n + duration(m, 40, 80);
self.transition(m, cx, SNIFFING);
}
// SetEntityLookTarget(PLAYER, 6).
3 => {
if let Some(p) = &cx.w.player {
self.look = Some(p.eye);
self.look_until = 0;
}
}
// RandomStroll.stroll(1.0).
4 => {
if let Some(p) = m.land_random_pos(cx.w, 10, 7) {
self.walk = Some(WalkTarget::new(
[
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
],
1.0,
0,
));
}
}
_ => {
self.run = Run::DoNothing;
self.until = n + duration(m, 5, 20);
}
}
}
/// `Brain.tickRunningBehaviors`.
fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx) {
let n = now(m);
let timed_out = n > self.until;
// The delegated idle behaviours.
if self.love_on {
if self.breed.can_continue(m, cx) {
self.breed.tick(m, cx);
} else {
self.breed.stop(m, cx);
self.love_on = false;
}
}
if self.tempt_on {
self.tempt.stop_distance = if m.is_baby() { 2.5 } else { 3.5 };
if self.tempt.can_continue(m, cx) {
self.tempt.tick(m, cx);
} else {
self.tempt.stop(m, cx);
self.tempt_on = false;
}
}
// LookAtTargetSink.
if self.look_until != 0 {
if let Some(l) = self.look
&& n <= self.look_until
{
m.look_at(l);
} else {
self.look = None;
self.look_until = 0;
}
}
match self.run {
Run::None => {}
Run::Digging => {
let ok = self.digging && self.can_dig(m, cx.w) && m.extra.in_love <= 0;
if timed_out || !ok {
if timed_out {
self.cooldown.set(SNIFF_COOLDOWN);
} else {
self.reset_sniffing(m, cx);
}
self.run = Run::None;
}
}
Run::FinishedDigging => {
if timed_out || !self.digging {
self.transition(m, cx, IDLING);
// onDiggingComplete: remember the spot when it finished.
if timed_out {
let p = on_pos(m);
m.extra.positions.insert(0, p);
m.extra.positions.truncate(21);
}
self.digging = false;
self.happy = true;
self.run = Run::None;
}
}
Run::Searching => {
let still = if !self.can_sniff(m) {
self.transition(m, cx, IDLING);
false
} else {
match (self.walk, self.sniff_target) {
(Some(w), Some(t)) => w.pos == t,
_ => false,
}
};
if timed_out || !still {
if self.can_dig(m, cx.w) && self.can_sniff(m) {
self.digging = true;
}
self.sink.stop(m, &mut self.walk);
self.sniff_target = None;
self.run = Run::None;
}
}
Run::Happy => {
if timed_out {
self.transition(m, cx, IDLING);
self.happy = false;
self.run = Run::None;
}
}
Run::Scenting => {
if timed_out {
self.transition(m, cx, IDLING);
self.run = Run::None;
}
}
Run::Sniffing => {
if timed_out || !self.can_sniff(m) {
self.transition(m, cx, IDLING);
if timed_out && let Some(p) = self.dig_position(m, cx.w) {
self.sniff_target = Some(p);
self.walk = Some(WalkTarget::new(p, 1.25, 0));
}
self.run = Run::None;
}
}
Run::DoNothing => {
if timed_out {
self.run = Run::None;
}
}
}
}
}
/// `Sniffer.tick` and `Sniffer.aiStep` additions: the animation states,
/// the dropped seed and the water malus.
pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
use super::path::PathType;
let age = m.age as f32;
let current = state(m);
if current != m.extra.scratch[0] as u8 {
// resetAnimations, then the state's own.
for s in &mut m.anim.states[..5] {
s.stop();
}
match current {
FEELING_HAPPY => m.anim.states[0].start_if_stopped(age),
SCENTING => m.anim.states[1].start_if_stopped(age),
SNIFFING => m.anim.states[2].start_if_stopped(age),
DIGGING => m.anim.states[3].start_if_stopped(age),
RISING => m.anim.states[4].start_if_stopped(age),
_ => {}
}
m.extra.scratch[0] = i32::from(current);
}
if current == DIGGING && now(m) == m.extra.ints[3] {
let h = head_block(m);
events.push(MobEvent::GiftLoot {
table: "minecraft:gameplay/sniffer_digging",
at: [f64::from(h[0]), f64::from(h[1]), f64::from(h[2])],
});
events.push(MobEvent::Sound(
"entity.sniffer.drop_seed",
m.center(),
1.0,
1.0,
));
}
if current == SEARCHING && m.age.is_multiple_of(20) {
events.push(MobEvent::Sound(
"entity.sniffer.searching",
m.center(),
1.0,
1.0,
));
}
// onPathfindingStart / Done: water only blocks the way while it is dry.
let wet = m.fluids.in_water || m.fire_ticks > 0;
m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 });
}
/// The brain memory holding the explored positions
/// (`SNIFFER_EXPLORED_POSITIONS`).
pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
use horizon_world::nbt::Tag;
let list: Vec<Tag> = m
.extra
.positions
.iter()
.map(|p| {
Tag::compound([
("dimension", Tag::String("minecraft:overworld".into())),
("pos", Tag::IntArray(p.to_vec())),
])
})
.collect();
let mut memories = horizon_world::nbt::Compound::new();
if !list.is_empty() {
memories.insert(
"minecraft:sniffer_explored_positions".into(),
Tag::compound([("value", Tag::List(list))]),
);
}
map.insert(
"Brain".into(),
Tag::compound([("memories", Tag::Compound(memories))]),
);
}
pub fn from_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
use horizon_world::nbt::Tag;
let Some(Tag::List(list)) = tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get("minecraft:sniffer_explored_positions"))
.and_then(|b| b.get("value"))
else {
return;
};
m.extra.positions = list
.iter()
.filter_map(|e| match e.get("pos") {
Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]),
_ => None,
})
.collect();
}
/// `Sniffer.canMate`'s state test.
pub fn can_mate_state(s: u8) -> bool {
matches!(s, IDLING | SCENTING | FEELING_HAPPY)
}
/// Ambient sound: none while digging or searching.
pub fn ambient(m: &Mob) -> Option<&'static str> {
(!matches!(state(m), DIGGING | SEARCHING)).then_some("entity.sniffer.idle")
}
/// `SnifferModel.setupAnim` (and `SniffletModel`'s baby transform).
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
let get = |n: &str| animations.get(&format!("SnifferAnimation.{n}"));
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
let walk = if state(m) == SEARCHING {
"SNIFFER_SNIFF_SEARCH"
} else {
"SNIFFER_WALK"
};
if let Some(a) = get(walk) {
a.apply_walk(s.pos, s.speed, 9.0, 100.0, p);
}
let age = s.age;
for (st, name) in [
(&m.anim.states[3], "SNIFFER_DIG"),
(&m.anim.states[2], "SNIFFER_LONGSNIFF"),
(&m.anim.states[4], "SNIFFER_STAND_UP"),
(&m.anim.states[0], "SNIFFER_HAPPY"),
(&m.anim.states[1], "SNIFFER_SNIFFSNIFF"),
] {
if let (Some(ms), Some(a)) = (st.millis(age), get(name)) {
a.apply(ms, 1.0, p);
}
}
if m.is_baby()
&& let Some(a) = get("BABY_TRANSFORM")
{
a.apply(0, 1.0, p);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_calm_states_can_mate() {
assert!(can_mate_state(IDLING));
assert!(can_mate_state(SCENTING));
assert!(can_mate_state(FEELING_HAPPY));
assert!(!can_mate_state(SNIFFING));
assert!(!can_mate_state(DIGGING));
}
}
@@ -103,6 +103,7 @@ pub fn spawn_rules_ok(
| S::Horse
| S::Donkey
| S::Llama
| S::Camel
| S::Wolf
| S::Cat
| S::Fox
@@ -116,6 +117,7 @@ pub fn spawn_rules_ok(
| S::Bee => {
let tag = match species {
S::Mooshroom => "minecraft:mooshrooms_spawnable_on",
S::Camel => "minecraft:camels_spawnable_on",
S::Wolf => "minecraft:wolves_spawnable_on",
S::Fox => "minecraft:foxes_spawnable_on",
S::Rabbit => "minecraft:rabbits_spawnable_on",
@@ -363,6 +365,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => {
super::equine::finalize(m)
}
S::Llama | S::TraderLlama => super::llama::finalize(m),
// Camel.finalizeSpawn: standing, with fixed attributes.
S::Camel => super::camel::stand_up_instantly(m),
// Piglin.createSpawnWeapon: half crossbows, half golden swords, and
+60 -2
View File
@@ -83,6 +83,9 @@ pub enum Species {
Wither,
Camel,
Allay,
Breeze,
Sniffer,
HappyGhast,
Warden,
Creaking,
}
@@ -944,6 +947,48 @@ pub const ALL: &[Def] = &[
Some("entity.camel.step"),
Baby::Abs(0.95, 1.4, 1.38)
),
def!(
HappyGhast,
"happy_ghast",
"happy_ghast#main",
"entity/ghast/happy_ghast",
A::HappyGhast,
[
"entity.happy_ghast.ambient",
"entity.happy_ghast.hurt",
"entity.happy_ghast.death"
],
None,
Baby::Scale(0.2375, Some(0.46875))
),
def!(
Sniffer,
"sniffer",
"sniffer#main",
"entity/sniffer/sniffer",
A::Sniffer,
[
"entity.sniffer.idle",
"entity.sniffer.hurt",
"entity.sniffer.death"
],
Some("entity.sniffer.step"),
Baby::Scale(0.5, None)
),
def!(
Breeze,
"breeze",
"breeze#main",
"entity/breeze/breeze",
A::Breeze,
[
"entity.breeze.idle_ground",
"entity.breeze.hurt",
"entity.breeze.death"
],
None,
Baby::None
),
def!(
Wither,
"wither",
@@ -1204,12 +1249,18 @@ impl Def {
Species::Donkey => &["donkey_baby"],
Species::Mule => &["mule_baby"],
Species::Llama => &["llama_baby"],
Species::TraderLlama => &["trader_llama_baby", "llama"],
Species::TraderLlama => &["trader_llama_baby", "llama", "llama_baby"],
Species::Goat => &["goat_baby"],
Species::Panda => &["panda_baby"],
Species::PolarBear => &["polar_bear_baby"],
Species::Fox => &["fox_baby"],
Species::Wolf => &["wolf_baby"],
Species::Sniffer => &["sniffer_baby"],
Species::HappyGhast => &[
"happy_ghast_baby",
"happy_ghast_harness",
"happy_ghast_ropes",
],
Species::Cat => &["cat_baby"],
Species::Ocelot => &["ocelot_baby"],
Species::Bee => &["bee_baby"],
@@ -1282,6 +1333,7 @@ impl Def {
| S::Parrot
| S::Bee
| S::Ghast
| S::HappyGhast
| S::Blaze
| S::Phantom
| S::IronGolem
@@ -1293,7 +1345,7 @@ impl Def {
| S::Wither
| S::Allay
),
flying: matches!(s, S::Ghast | S::Phantom),
flying: matches!(s, S::Ghast | S::Phantom | S::HappyGhast),
climber: matches!(s, S::Spider | S::CaveSpider),
lava_walker: s == S::Strider,
omnidirectional: matches!(s, S::Bat | S::Bee | S::Parrot),
@@ -1401,6 +1453,8 @@ impl Def {
S::Horse | S::Donkey | S::Mule => "horse_food",
S::Llama | S::TraderLlama => "llama_food",
S::Goat => "goat_food",
S::Sniffer => "sniffer_food",
S::HappyGhast => "happy_ghast_food",
S::Panda => "panda_food",
S::Fox => "fox_food",
S::Wolf => "wolf_food",
@@ -1435,6 +1489,7 @@ impl Def {
pub fn air_speed(&self) -> f32 {
match self.species {
Species::Phantom => 0.2,
Species::HappyGhast => super::happy_ghast::AIR_SPEED,
_ => 0.02,
}
}
@@ -1447,6 +1502,7 @@ impl Def {
pub fn head_rot_speed(&self) -> f32 {
match self.species {
Species::Frog => 35.0,
Species::Breeze => 25.0,
_ => 10.0,
}
}
@@ -1461,6 +1517,8 @@ impl Def {
match self.species {
Species::Dolphin | Species::Axolotl => 1.0,
Species::Frog => 5.0,
Species::Breeze => 30.0,
Species::Sniffer => 50.0,
Species::Goat => 15.0,
Species::Armadillo => 32.0,
_ => 75.0,
+314
View File
@@ -0,0 +1,314 @@
//! The wandering trader (`WanderingTrader`): drinking invisibility at night
//! and milk by day, fleeing monsters, walking to the place it came to
//! visit, staying within its home, trading and leaving after its despawn
//! delay.
use super::{
Mob, MobEvent, MobWorld, Species,
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, JUMP, LOOK, LookAtPlayer, MOVE, Panic, Stroll,
goal_clone,
},
};
use horizon_core::random::RandomSource;
// Trader state: `point` the wander target, `home` the place it is tied to
// with `ints[4]` the radius, `ints[5]` the despawn delay, `flag2` whether
// a player is trading with it and `using_item` how long it has been
// drinking.
/// `WanderingTraderSpawner`: how long a spawned trader stays.
pub const DESPAWN_DELAY: i32 = 48000;
const DRINK_TICKS: i32 = 32;
const INVISIBILITY: &str = "minecraft:invisibility";
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(
0,
DrinkItem {
item: "minecraft:potion",
finish_sound: "entity.wandering_trader.disappeared",
dark: true,
},
);
g.add(
0,
DrinkItem {
item: "minecraft:milk_bucket",
finish_sound: "entity.wandering_trader.reappeared",
dark: false,
},
);
g.add(1, TradeWithPlayer);
for (species, distance) in [
(Species::Zombie, 8.0),
(Species::Evoker, 12.0),
(Species::Vindicator, 8.0),
(Species::Vex, 8.0),
(Species::Pillager, 15.0),
(Species::Zoglin, 10.0),
] {
// `Zombie.class` covers the zombie family.
let list = if species == Species::Zombie {
vec![
Species::Zombie,
Species::Husk,
Species::Drowned,
Species::ZombieVillager,
Species::ZombifiedPiglin,
]
} else {
vec![species]
};
g.add(
1,
AvoidEntity::new(Avoid::Species(list), distance, 0.5, 0.5),
);
}
g.add(1, Panic::new(0.5));
g.add(1, LookAtTradingPlayer);
g.add(
2,
WanderToPosition {
stop: 2.0,
speed: 0.35,
},
);
g.add(4, MoveTowardsRestriction::new(0.35));
g.add(8, Stroll::avoiding_water(0.35));
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
g.add(10, LookAtPlayer::new(8.0));
}
fn invisible(m: &Mob) -> bool {
m.extra.effects.iter().any(|e| e.0 == INVISIBILITY)
}
pub fn is_invisible(m: &Mob) -> bool {
invisible(m)
}
/// `UseItemGoal`: drink a potion of invisibility once it is dark outside,
/// or milk to clear it by day.
#[derive(Clone, Debug)]
struct DrinkItem {
item: &'static str,
finish_sound: &'static str,
dark: bool,
}
impl Goal for DrinkItem {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if cx.w.nether {
return false;
}
if self.dark {
!cx.w.daylight && !invisible(m)
} else {
cx.w.daylight && invisible(m)
}
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.using_item > 0
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
m.extra.main_hand = Some(self.item.into());
m.extra.using_item = 1;
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
m.extra.main_hand = None;
m.extra.using_item = 0;
let pitch = m.random.next_float() * 0.2 + 0.9;
cx.events
.push(MobEvent::Sound(self.finish_sound, m.center(), 1.0, pitch));
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if m.extra.using_item == 0 {
return;
}
m.extra.using_item += 1;
if m.extra.using_item > DRINK_TICKS {
// LivingEntity.completeUsingItem: the potion or the milk takes effect.
if self.dark {
m.extra.effects.retain(|e| e.0 != INVISIBILITY);
m.extra.effects.push((INVISIBILITY, 3600, 0));
cx.events.push(MobEvent::Sound(
"entity.wandering_trader.drink_potion",
m.center(),
1.0,
1.0,
));
} else {
m.extra.effects.clear();
cx.events.push(MobEvent::Sound(
"entity.wandering_trader.drink_milk",
m.center(),
1.0,
1.0,
));
}
m.extra.using_item = 0;
}
}
}
/// `TradeWithPlayerGoal`: stand still while trading.
#[derive(Clone, Debug)]
struct TradeWithPlayer;
impl Goal for TradeWithPlayer {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.flag2 && m.alive() && !m.fluids.in_water && m.on_ground
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
m.nav_stop();
}
}
/// `LookAtTradingPlayerGoal`.
#[derive(Clone, Debug)]
struct LookAtTradingPlayer;
impl Goal for LookAtTradingPlayer {
goal_clone!();
fn flags(&self) -> u8 {
LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.extra.flag2 && cx.w.player.is_some()
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(p) = &cx.w.player {
m.look_at([p.position.x, p.eye[1], p.position.z]);
}
}
}
/// `WanderingTrader.WanderToPositionGoal`: head for the wander target, in
/// hops of ten blocks while it is far.
#[derive(Clone, Debug)]
struct WanderToPosition {
stop: f64,
speed: f64,
}
fn too_far(m: &Mob, p: [f64; 3], distance: f64) -> bool {
// BlockPos.closerToCenterThan.
let (x, y, z) = (p[0].floor() + 0.5, p[1].floor() + 0.5, p[2].floor() + 0.5);
let d = (x - m.position.x).powi(2) + (y - m.position.y).powi(2) + (z - m.position.z).powi(2);
d >= distance * distance
}
impl Goal for WanderToPosition {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.point.is_some_and(|p| too_far(m, p, self.stop))
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.extra.point = None;
m.nav_stop();
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = m.extra.point else { return };
if !m.ai.nav.is_done() {
return;
}
if too_far(m, p, 10.0) {
let d = [
p[0].floor() - m.position.x,
p[1].floor() - m.position.y,
p[2].floor() - m.position.z,
];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-9);
let at = [
d[0] / len * 10.0 + m.position.x,
d[1] / len * 10.0 + m.position.y,
d[2] / len * 10.0 + m.position.z,
];
m.nav_move_to(cx.w, at, self.speed);
} else {
m.nav_move_to(cx.w, [p[0].floor(), p[1].floor(), p[2].floor()], self.speed);
}
}
}
/// `Mob.isWithinHome`.
pub fn within_home(m: &Mob) -> bool {
let Some(h) = m.extra.home else { return true };
let r = m.extra.ints[4];
if r <= 0 {
return true;
}
let d = (h[0] - m.position.x.floor() as i32).pow(2)
+ (h[1] - m.position.y.floor() as i32).pow(2)
+ (h[2] - m.position.z.floor() as i32).pow(2);
d < r * r
}
/// `MoveTowardsRestrictionGoal`.
#[derive(Clone, Debug)]
struct MoveTowardsRestriction {
speed: f64,
wanted: [f64; 3],
}
impl MoveTowardsRestriction {
fn new(speed: f64) -> Self {
Self {
speed,
wanted: [0.0; 3],
}
}
}
impl Goal for MoveTowardsRestriction {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if within_home(m) {
return false;
}
let Some(h) = m.extra.home else { return false };
let to = [
f64::from(h[0]) + 0.5,
f64::from(h[1]),
f64::from(h[2]) + 0.5,
];
match m.default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::FRAC_PI_2) {
Some(p) => {
self.wanted = p;
true
}
None => false,
}
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.nav_move_to(cx.w, self.wanted, self.speed);
}
}
/// `WanderingTrader.maybeDespawn` in `aiStep`.
pub fn ai_step(m: &mut Mob, _w: &MobWorld) {
if m.extra.ints[5] > 0 && !m.extra.flag2 {
m.extra.ints[5] -= 1;
if m.extra.ints[5] == 0 {
m.removed = true;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn despawn_delay_is_two_days() {
assert_eq!(DESPAWN_DELAY, 2 * 24000);
}
}
+1 -1
View File
@@ -447,7 +447,7 @@ fn work(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
}
pub fn sleeping(m: &Mob) -> bool {
m.extra.ints[1] != 0
matches!(m.species(), Species::Villager | Species::WanderingTrader) && m.extra.ints[1] != 0
}
/// `LivingEntity.startSleeping`: lie in the bed (`setPosToBed`).
fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
+185 -26
View File
@@ -3,7 +3,9 @@
//! and High Contrast packs, `pack.mcmeta` metadata and format compatibility,
//! and an overlay resource root that layers the enabled packs over the
//! vanilla resources (later packs win), so every loader sees one tree.
mod pattern;
use crate::{text::Text, zip::Zip};
use pattern::Pattern;
use std::{
collections::{BTreeMap, BTreeSet},
fs, io,
@@ -26,6 +28,30 @@ pub struct Pack {
pub title: Text,
pub description: Text,
pub compatible: bool,
/// Overlay directories active for this game version, in `pack.mcmeta` order.
pub overlays: Vec<String>,
/// `filter.block` entries (namespace and path patterns) hiding resources
/// of the packs below this one.
pub filter: Vec<Filter>,
}
#[derive(Clone, Debug, Default)]
pub struct Filter {
namespace: Option<Pattern>,
path: Option<Pattern>,
}
impl Filter {
fn blocks(&self, file: &str) -> bool {
let Some(rest) = file.strip_prefix("assets/") else {
return false;
};
let Some((namespace, path)) = rest.split_once('/') else {
return false;
};
self.namespace
.as_ref()
.is_none_or(|p| p.is_match(namespace))
&& self.path.as_ref().is_none_or(|p| p.is_match(path))
}
}
/// A minimal text component from JSON (strings, `text`, `translate`, arrays).
pub fn component(v: &serde_json::Value) -> Text {
@@ -102,6 +128,58 @@ pub fn compatible(meta: &serde_json::Value) -> bool {
}
format_of(&pack["pack_format"]).is_some_and(|f| f.0 == current.0)
}
/// Whether an `overlays.entries[]` item applies to the current format
/// (OverlayMetadataSection: `formats` as an int, `[min, max]` or
/// `{min_inclusive, max_inclusive}`, or `min_format`/`max_format`).
fn overlay_applies(entry: &serde_json::Value) -> bool {
let current = RESOURCE_FORMAT;
if let (Some(min), Some(max)) = (
format_of(&entry["min_format"]),
format_of(&entry["max_format"]),
) {
return min <= current && current <= (max.0, if max.1 == 0 { i64::MAX } else { max.1 });
}
let formats = &entry["formats"];
if let Some(n) = formats.as_i64() {
return n == current.0;
}
if let Some(a) = formats.as_array() {
return match (
a.first().and_then(|v| v.as_i64()),
a.get(1).and_then(|v| v.as_i64()),
) {
(Some(lo), Some(hi)) => lo <= current.0 && current.0 <= hi,
_ => false,
};
}
match (
formats["min_inclusive"].as_i64(),
formats["max_inclusive"].as_i64(),
) {
(Some(lo), Some(hi)) => lo <= current.0 && current.0 <= hi,
_ => false,
}
}
fn overlays_of(meta: &serde_json::Value) -> Vec<String> {
meta["overlays"]["entries"]
.as_array()
.into_iter()
.flatten()
.filter(|e| overlay_applies(e))
.filter_map(|e| e["directory"].as_str().map(str::to_owned))
.collect()
}
fn filter_of(meta: &serde_json::Value) -> Vec<Filter> {
meta["filter"]["block"]
.as_array()
.into_iter()
.flatten()
.map(|b| Filter {
namespace: b["namespace"].as_str().and_then(Pattern::new),
path: b["path"].as_str().and_then(Pattern::new),
})
.collect()
}
fn read_meta(source: &Source) -> Option<serde_json::Value> {
let bytes = match source {
Source::Dir(d) => fs::read(d.join("pack.mcmeta")).ok()?,
@@ -116,6 +194,8 @@ fn pack(id: String, title: Text, source: Source) -> Option<Pack> {
title,
description: component(&meta["pack"]["description"]),
compatible: compatible(&meta),
overlays: overlays_of(&meta),
filter: filter_of(&meta),
source,
})
}
@@ -155,30 +235,44 @@ pub fn discover(resources: &Path, packs_dir: &Path) -> Vec<Pack> {
out.extend(user);
out
}
/// Files a pack provides under `assets/`.
fn pack_files(source: &Source) -> io::Result<BTreeMap<String, Option<PathBuf>>> {
/// A file a pack provides: its path (folder packs) and its name inside the pack.
type Provided = (Option<PathBuf>, String);
/// Files a pack provides under `assets/`, keyed by their resource name; active
/// overlay directories are applied after the base, in order, later wins.
fn pack_files(pack: &Pack) -> io::Result<BTreeMap<String, Provided>> {
let mut out = BTreeMap::new();
match source {
let roots = std::iter::once(String::new())
.chain(pack.overlays.iter().map(|d| format!("{d}/")))
.collect::<Vec<_>>();
match &pack.source {
Source::Dir(d) => {
let mut stack = vec![d.join("assets")];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
stack.push(p);
} else if let Ok(rel) = p.strip_prefix(d) {
out.insert(rel.to_string_lossy().replace('\\', "/"), Some(p.clone()));
for root in &roots {
let base = d.join(root.trim_end_matches('/'));
let mut stack = vec![base.join("assets")];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
stack.push(p);
} else if let Ok(rel) = p.strip_prefix(&base) {
let rel = rel.to_string_lossy().replace('\\', "/");
out.insert(rel.clone(), (Some(p.clone()), format!("{root}{rel}")));
}
}
}
}
}
Source::Zip(z) => {
for name in Zip::open(z)?.names() {
if name.starts_with("assets/") {
out.insert(name.to_owned(), None);
let zip = Zip::open(z)?;
for root in &roots {
let prefix = format!("{root}assets/");
for name in zip.names() {
if let Some(rest) = name.strip_prefix(&prefix) {
out.insert(format!("assets/{rest}"), (None, name.to_owned()));
}
}
}
}
@@ -205,12 +299,16 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
}
fs::create_dir_all(out)?;
// Final owner of every overridden file.
let mut files: BTreeMap<String, (usize, Option<PathBuf>)> = BTreeMap::new();
let mut files: BTreeMap<String, (usize, Provided)> = BTreeMap::new();
for (i, p) in packs.iter().enumerate() {
for (name, path) in pack_files(&p.source)? {
files.insert(name, (i, path));
// A pack's filter hides what the packs below it provide.
files.retain(|name, _| !p.filter.iter().any(|f| f.blocks(name)));
for (name, provided) in pack_files(p)? {
files.insert(name, (i, provided));
}
}
// Vanilla sits below every pack, so filters hide its files too.
let filters: Vec<&Filter> = packs.iter().flat_map(|p| &p.filter).collect();
let touched_dirs: BTreeSet<String> = files
.keys()
.flat_map(|f| {
@@ -233,7 +331,8 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
vanilla: &Path,
out: &Path,
touched: &BTreeSet<String>,
files: &BTreeMap<String, (usize, Option<PathBuf>)>,
files: &BTreeMap<String, (usize, Provided)>,
filters: &[&Filter],
zips: &[Option<Zip>],
) -> io::Result<()> {
let src = if rel.is_empty() {
@@ -265,25 +364,29 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
}
for name in names {
let child = format!("{prefix}{name}");
if let Some((owner, path)) = files.get(&child) {
if let Some((owner, (path, inner))) = files.get(&child) {
let target = out.join(&child);
match path {
Some(p) => link(p, &target)?,
None => {
if let Some(Some(z)) = zips.get(*owner) {
fs::write(&target, z.read(&child)?)?;
fs::write(&target, z.read(inner)?)?;
}
}
}
} else if touched.contains(&child) {
mirror(&child, vanilla, out, touched, files, zips)?;
} else if touched.contains(&child)
|| (vanilla.join(&child).is_dir() && !filters.is_empty())
{
mirror(&child, vanilla, out, touched, files, filters, zips)?;
} else if filters.iter().any(|f| f.blocks(&child)) {
// Hidden by a pack's filter.
} else {
link(&vanilla.join(&child), &out.join(&child))?;
}
}
Ok(())
}
mirror("", vanilla, out, &touched_dirs, &files, &zips)
mirror("", vanilla, out, &touched_dirs, &files, &filters, &zips)
}
/// The packs to apply for an options.txt `resourcePacks` list (bottom first).
pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
@@ -388,4 +491,60 @@ mod tests {
assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]");
let _ = fs::remove_dir_all(base);
}
#[test]
fn overlays_and_filters() {
let v = |s: &str| serde_json::from_str::<serde_json::Value>(s).unwrap();
let meta = v(r#"{"overlays":{"entries":[
{"formats":[90,96],"directory":"old"},
{"formats":{"min_inclusive":97,"max_inclusive":97},"directory":"new"},
{"min_format":97,"max_format":[97,5],"directory":"also"},
{"formats":50,"directory":"no"}]}}"#);
assert_eq!(overlays_of(&meta), ["new", "also"]);
let base = std::env::temp_dir().join(format!("horizon-packs-ov-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let vanilla = base.join("vanilla");
fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap();
fs::write(
vanilla.join("assets/minecraft/textures/block/stone.png"),
b"v",
)
.unwrap();
fs::write(
vanilla.join("assets/minecraft/textures/block/dirt.png"),
b"v",
)
.unwrap();
let dir = base.join("packs/P");
fs::create_dir_all(dir.join("new/assets/minecraft/textures/block")).unwrap();
fs::create_dir_all(dir.join("old/assets/minecraft/textures/block")).unwrap();
fs::write(
dir.join("pack.mcmeta"),
br#"{"pack":{"description":"p","pack_format":97},
"overlays":{"entries":[{"formats":97,"directory":"new"},{"formats":1,"directory":"old"}]},
"filter":{"block":[{"path":"textures/block/dirt\\.png"}]}}"#,
)
.unwrap();
fs::write(
dir.join("new/assets/minecraft/textures/block/stone.png"),
b"overlay",
)
.unwrap();
fs::write(
dir.join("old/assets/minecraft/textures/block/stone.png"),
b"old",
)
.unwrap();
let packs = discover(&vanilla, &base.join("packs"));
let out = base.join("overlay");
build_overlay(&vanilla, &packs, &out).unwrap();
assert_eq!(
fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(),
b"overlay"
);
assert!(
!out.join("assets/minecraft/textures/block/dirt.png")
.exists()
);
let _ = fs::remove_dir_all(base);
}
}
+142
View File
@@ -0,0 +1,142 @@
//! A small regular-expression subset for `pack.mcmeta` filter blocks (Java
//! `Pattern.asPredicate()` semantics: an unanchored search). Supports
//! literals, `.`, classes `[a-z_]`/`[^..]`, escapes, `* + ?` quantifiers,
//! `^`/`$` and top-level alternation with `|`.
#[derive(Clone, Debug)]
enum Atom {
Any,
Lit(char),
Class(Vec<(char, char)>, bool),
Start,
End,
}
#[derive(Clone, Debug)]
struct Item {
atom: Atom,
min: usize,
max: usize,
}
#[derive(Clone, Debug)]
pub struct Pattern(Vec<Vec<Item>>);
impl Pattern {
pub fn new(src: &str) -> Option<Pattern> {
let mut alternatives = vec![Vec::new()];
let chars: Vec<char> = src.chars().collect();
let mut i = 0;
while i < chars.len() {
let atom = match chars[i] {
'|' => {
alternatives.push(Vec::new());
i += 1;
continue;
}
'.' => Atom::Any,
'^' => Atom::Start,
'$' => Atom::End,
'\\' => {
i += 1;
match *chars.get(i)? {
'd' => Atom::Class(vec![('0', '9')], false),
'w' => {
Atom::Class(vec![('a', 'z'), ('A', 'Z'), ('0', '9'), ('_', '_')], false)
}
c => Atom::Lit(c),
}
}
'[' => {
i += 1;
let negate = chars.get(i) == Some(&'^');
if negate {
i += 1;
}
let mut ranges = Vec::new();
loop {
let mut c = *chars.get(i)?;
if c == ']' && !ranges.is_empty() {
break;
}
if c == '\\' {
i += 1;
c = *chars.get(i)?;
}
if chars.get(i + 1) == Some(&'-')
&& chars.get(i + 2).is_some_and(|e| *e != ']')
{
ranges.push((c, chars[i + 2]));
i += 3;
} else {
ranges.push((c, c));
i += 1;
}
}
Atom::Class(ranges, negate)
}
'(' | ')' | '{' | '}' => return None,
c => Atom::Lit(c),
};
i += 1;
let (min, max) = match chars.get(i) {
Some('*') => (0, usize::MAX),
Some('+') => (1, usize::MAX),
Some('?') => (0, 1),
_ => (1, 1),
};
if (min, max) != (1, 1) {
i += 1;
}
alternatives.last_mut()?.push(Item { atom, min, max });
}
Some(Pattern(alternatives))
}
pub fn is_match(&self, text: &str) -> bool {
let text: Vec<char> = text.chars().collect();
self.0
.iter()
.any(|alt| (0..=text.len()).any(|start| run(alt, &text, start)))
}
}
fn one(atom: &Atom, c: char) -> bool {
match atom {
Atom::Any => c != '\n',
Atom::Lit(l) => *l == c,
Atom::Class(r, negate) => r.iter().any(|(lo, hi)| *lo <= c && c <= *hi) != *negate,
Atom::Start | Atom::End => false,
}
}
fn run(items: &[Item], text: &[char], at: usize) -> bool {
let Some((item, rest)) = items.split_first() else {
return true;
};
match item.atom {
Atom::Start => return at == 0 && run(rest, text, at),
Atom::End => return at == text.len() && run(rest, text, at),
_ => {}
}
let mut count = 0;
while count < item.max && at + count < text.len() && one(&item.atom, text[at + count]) {
count += 1;
}
(item.min..=count).rev().any(|n| run(rest, text, at + n))
}
#[cfg(test)]
mod tests {
use super::Pattern;
fn m(p: &str, t: &str) -> bool {
Pattern::new(p).unwrap().is_match(t)
}
#[test]
fn java_find_semantics() {
assert!(m("stone", "minecraft/stone_bricks"));
assert!(!m("^stone$", "stone_bricks"));
assert!(m("^textures/.*\\.png$", "textures/block/a.png"));
assert!(!m("^textures/.*\\.png$", "textures/block/a_png"));
assert!(m("[a-c]+z", "xxabcz"));
assert!(!m("^[^a]+$", "bab"));
assert!(m("dirt|grass", "grass_block"));
assert!(m(".*", ""));
assert!(Pattern::new("(a)").is_none());
}
}
+66 -1
View File
@@ -120,6 +120,10 @@ particle_types! {
Soul = "soul",
SculkSoul = "sculk_soul",
DragonBreath = "dragon_breath",
Gust = "gust",
SmallGust = "small_gust",
GustEmitterLarge = "gust_emitter_large",
GustEmitterSmall = "gust_emitter_small",
DustColorTransition = "dust_color_transition",
SculkCharge = "sculk_charge",
SculkChargePop = "sculk_charge_pop",
@@ -132,7 +136,12 @@ impl ParticleType {
pub fn override_limiter(self) -> bool {
matches!(
self,
Self::DamageIndicator | Self::ExplosionEmitter | Self::Explosion | Self::Poof
Self::DamageIndicator
| Self::ExplosionEmitter
| Self::Explosion
| Self::Poof
| Self::GustEmitterLarge
| Self::GustEmitterSmall
)
}
}
@@ -294,6 +303,11 @@ enum Behaviour {
Crit,
HugeExplosion,
ExplosionSeed,
/// `GustSeedParticle`: three gusts around it every `delay + 1` ticks.
GustSeed {
scale: f64,
delay: i32,
},
Campfire,
SimpleAnimated {
fade: Option<[f32; 3]>,
@@ -1540,6 +1554,34 @@ impl ParticleEngine {
q.behaviour = Behaviour::ExplosionSeed;
q
}
// GustParticle: a still, bright, opaque quad that animates over
// its 12 to 15 ticks; the small one is scaled to 15%.
T::Gust | T::SmallGust => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
q.velocity = [0.0; 3];
q.lifetime = 12 + r.next_int_bound(4).unwrap_or(0);
q.size = 1.0;
q.set_size(1.0, 1.0);
if ty == T::SmallGust {
q.scale(0.15);
}
q.light = Light::FullBright;
q.behaviour = Behaviour::HugeExplosion;
q.set = set;
q
}
T::GustEmitterLarge | T::GustEmitterSmall => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
let (scale, lifetime, delay) = if ty == T::GustEmitterLarge {
(3.0, 7, 0)
} else {
(1.0, 3, 2)
};
q.lifetime = lifetime;
q.no_render = true;
q.behaviour = Behaviour::GustSeed { scale, delay };
q
}
T::CampfireCosySmoke | T::CampfireSignalSmoke => {
let mut q = Particle::at(r, ty, p);
q.scale(3.0);
@@ -2404,6 +2446,29 @@ impl ParticleEngine {
}
self.sprite_from_age(p);
}
Behaviour::GustSeed { scale, delay } => {
if p.age % (delay + 1) == 0 {
for _ in 0..3 {
let r = &mut self.random;
let at = [
p.position[0] + (r.next_double() - r.next_double()) * scale,
p.position[1] + (r.next_double() - r.next_double()) * scale,
p.position[2] + (r.next_double() - r.next_double()) * scale,
];
let f = f64::from(p.age as f32 / p.lifetime as f32);
self.add(
&ParticleOptions::simple(ParticleType::Gust),
at,
[f, 0.0, 0.0],
);
}
}
let age = p.age;
p.age += 1;
if age == p.lifetime {
p.removed = true;
}
}
Behaviour::ExplosionSeed => {
for _ in 0..6 {
let r = &mut self.random;
+50
View File
@@ -25,6 +25,10 @@ pub enum ProjectileKind {
power: i32,
},
LlamaSpit,
/// A player's `WindCharge` and a breeze's `BreezeWindCharge`: straight
/// flight that bursts on whatever it meets.
WindCharge,
BreezeWindCharge,
/// `ShulkerBullet`: homing on `target` in axis-aligned steps.
ShulkerBullet {
target: Who,
@@ -487,6 +491,13 @@ impl Projectile {
);
}
ProjectileKind::Arrow { .. } => {}
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {}
// LlamaSpit.tick: gone in water; drag and gravity follow the move.
ProjectileKind::LlamaSpit => {
if water {
return (false, Hit::None);
}
}
_ => {
// ThrowableProjectile: gravity, then inertia.
self.velocity.y -= self.gravity();
@@ -551,6 +562,32 @@ impl Projectile {
}
return (false, Hit::Block { pos, at, face });
}
if self.kind == ProjectileKind::LlamaSpit {
// The 0.25 box touching anything but air discards the spit.
let h = 0.125;
let touches = [-h, h].iter().any(|dx| {
[-h, h].iter().any(|dy| {
[-h, h].iter().any(|dz| {
!w.empty([
(from.x + dx).floor() as i32,
(from.y + dy + h).floor() as i32,
(from.z + dz).floor() as i32,
])
})
})
});
if touches {
return (false, Hit::None);
}
self.position = to;
self.velocity = Vec3::new(
self.velocity.x * 0.99,
self.velocity.y * 0.99 - self.gravity(),
self.velocity.z * 0.99,
);
self.update_rotation();
return (self.position.y > -128.0 && self.age < 6000, Hit::None);
}
self.position = to;
if self.is_arrow() {
// AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity.
@@ -599,6 +636,8 @@ impl Projectile {
ProjectileKind::Potion { .. } => "item/splash_potion",
ProjectileKind::LlamaSpit => "entity/llama/llama_spit",
ProjectileKind::ShulkerBullet { .. } => "entity/shulker/spark",
// Drawn as `WindChargeModel` by the game.
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None,
ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither",
ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable",
ProjectileKind::Arrow { .. } => return None,
@@ -641,6 +680,17 @@ mod tests {
assert!((p.position.x - 0.99).abs() < 1e-9);
}
#[test]
fn llama_spit_moves_first_then_drags_and_falls() {
let mut p = Projectile::new(ProjectileKind::LlamaSpit, Vec3::new(0.0, 100.0, 0.0), None);
p.velocity = Vec3::new(1.0, 0.0, 0.0);
let w = Empty(vec![]);
let (keep, _) = p.tick(&w);
assert!(keep);
assert!((p.position.x - 1.0).abs() < 1e-9);
assert!((p.velocity.x - 0.99).abs() < 1e-9);
assert!((p.velocity.y + 0.06).abs() < 1e-9);
}
#[test]
fn arrow_applies_drag_then_gravity_after_moving() {
let mut p = Projectile::new(
ProjectileKind::Arrow {
+119
View File
@@ -0,0 +1,119 @@
//! `Stopwatches`: the named wall-clock timers of `/stopwatch`, saved in
//! `data/minecraft/stopwatches.dat` as the elapsed milliseconds of each.
use crate::save;
use horizon_world::nbt::{Compound, JavaString, Tag};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::OnceLock,
time::Instant,
};
/// `Util.getMillis`, measured from the first call.
pub fn current_time() -> i64 {
static START: OnceLock<Instant> = OnceLock::new();
START.get_or_init(Instant::now).elapsed().as_millis() as i64
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Stopwatch {
creation_time: i64,
accumulated: i64,
}
impl Stopwatch {
fn elapsed_ms(self, now: i64) -> i64 {
self.accumulated + (now - self.creation_time)
}
}
#[derive(Clone, Debug, Default)]
pub struct Stopwatches {
watches: BTreeMap<String, Stopwatch>,
dirty: bool,
}
fn file(root: &Path) -> PathBuf {
root.join("data/minecraft/stopwatches.dat")
}
impl Stopwatches {
pub fn load(root: &Path) -> Self {
let mut s = Self::default();
let now = current_time();
if let Some(Tag::Compound(data)) =
save::read_dat(&file(root)).and_then(|t| t.get("data").cloned())
&& let Some(Tag::Compound(map)) = data.get(&JavaString::from("stopwatches"))
{
for (k, v) in map.iter() {
if let Tag::Long(ms) = v {
s.watches.insert(
k.to_string_lossy(),
Stopwatch {
creation_time: now,
accumulated: *ms,
},
);
}
}
}
s
}
pub fn save(&mut self, root: &Path) {
if !self.dirty && self.watches.is_empty() {
return;
}
self.dirty = false;
let now = current_time();
let map: Compound = self
.watches
.iter()
.map(|(k, w)| (k.as_str().into(), Tag::Long(w.elapsed_ms(now))))
.collect();
let _ = save::write_dat(
&file(root),
Tag::compound([
("data", Tag::compound([("stopwatches", Tag::Compound(map))])),
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
]),
);
}
pub fn ids(&self) -> Vec<String> {
self.watches.keys().cloned().collect()
}
/// `add`: false when the id exists.
pub fn create(&mut self, id: &str) -> bool {
if self.watches.contains_key(id) {
return false;
}
self.watches.insert(
id.to_owned(),
Stopwatch {
creation_time: current_time(),
accumulated: 0,
},
);
self.dirty = true;
true
}
/// `update` with a fresh stopwatch.
pub fn restart(&mut self, id: &str) -> bool {
let Some(w) = self.watches.get_mut(id) else {
return false;
};
*w = Stopwatch {
creation_time: current_time(),
accumulated: 0,
};
self.dirty = true;
true
}
pub fn remove(&mut self, id: &str) -> bool {
let removed = self.watches.remove(id).is_some();
self.dirty |= removed;
removed
}
/// `Stopwatch.elapsedSeconds`.
pub fn elapsed_seconds(&self, id: &str) -> Option<f64> {
self.watches
.get(id)
.map(|w| w.elapsed_ms(current_time()) as f64 / 1000.0)
}
}
@@ -0,0 +1,321 @@
//! Rust side of the block update, random tick and redstone parity harnesses
//! (`tools/test_block_update_parity.py`, `test_random_tick_parity.py`,
//! `test_redstone_parity.py`): replays `VanillaBlockUpdateOracle` cases against
//! `Behaviours` over a map-backed level and prints the same result text.
use horizon_core::{
geometry::{Aabb, Direction},
position::{BlockPos, ChunkPos},
random::{LegacyRandom, RandomSource},
};
use horizon_world::{
level::{
Behaviours, Dimension, EntityQuery, GameRules, LevelAccess, LevelEvent, Ticks,
data::load_registry,
},
registry::BlockStateId,
};
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
fmt::Write as _,
io::{BufRead, Write},
path::Path,
};
struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
time: i64,
sky: i32,
block: i32,
raining: bool,
thundering: bool,
events: Vec<LevelEvent>,
}
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 random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
self.time
}
fn block_light(&self, _pos: BlockPos) -> i32 {
self.block
}
fn sky_light(&self, _pos: BlockPos) -> i32 {
self.sky
}
fn is_raining(&self) -> bool {
self.raining
}
fn is_thundering(&self) -> bool {
self.thundering
}
fn is_raining_at(&self, _pos: BlockPos) -> bool {
self.raining
}
fn dimension(&self) -> Dimension {
Dimension::Overworld
}
fn game_rules(&self) -> GameRules {
GameRules::default()
}
fn count_entities(&self, _area: Aabb, _query: EntityQuery) -> usize {
0
}
fn emit(&mut self, event: LevelEvent) {
self.events.push(event);
}
}
fn pos_of(value: &Value) -> BlockPos {
let c: Vec<i32> = value
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
BlockPos::new(c[0], c[1], c[2])
}
fn p(pos: BlockPos) -> String {
format!("{},{},{}", pos.x, pos.y, pos.z)
}
fn summary(level: &Cells, before: &HashMap<BlockPos, BlockStateId>, out: &mut String) {
let mut all: BTreeMap<(i32, i32, i32), ()> = BTreeMap::new();
for pos in before.keys().chain(level.cells.keys()) {
all.insert((pos.x, pos.y, pos.z), ());
}
for (x, y, z) in all.keys() {
let pos = BlockPos::new(*x, *y, *z);
let a = before.get(&pos).copied().unwrap_or(level.air);
let b = level.block_state(pos);
if a != b {
let _ = writeln!(out, "set {} {}", p(pos), b.0);
}
}
}
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 cells = HashMap::new();
for cell in case["cells"].as_array().unwrap() {
let c = cell.as_array().unwrap();
let state = BlockStateId(c[3].as_i64().unwrap() as u32);
if state != air {
cells.insert(
BlockPos::new(
c[0].as_i64().unwrap() as i32,
c[1].as_i64().unwrap() as i32,
c[2].as_i64().unwrap() as i32,
),
state,
);
}
}
let before = cells.clone();
let light = case.get("light").and_then(|v| v.as_array());
let mut level = Cells {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
time: case.get("time").and_then(|v| v.as_i64()).unwrap_or(0),
sky: light.map_or(15, |l| l[0].as_i64().unwrap() as i32),
block: light.map_or(0, |l| l[1].as_i64().unwrap() as i32),
raining: case
.get("raining")
.and_then(|v| v.as_bool())
.unwrap_or(false),
thundering: case
.get("thundering")
.and_then(|v| v.as_bool())
.unwrap_or(false),
events: Vec::new(),
};
let mut ticks = Ticks::new(0);
for x in -3..=3 {
for z in -3..=3 {
ticks.add_empty_chunk(ChunkPos::new(x, z))?;
}
}
let mut result = format!("case {index}\n");
let origin = pos_of(&case["pos"]);
match case["mode"].as_str().unwrap() {
"shape" => {
let dir = Direction::ALL[case["dir"].as_u64().unwrap() as usize];
let neighbour = BlockStateId(case["neighbor"].as_i64().unwrap() as u32);
let state = level.block_state(origin);
let s = behaviours.update_shape(
&mut level,
&mut ticks,
state,
origin,
dir,
{
let [x, y, z] = dir.normal();
origin.offset(x, y, z)
},
neighbour,
);
let _ = writeln!(result, "shape {}", s.0);
}
"random" => behaviours.random_tick(&mut level, &mut ticks, origin),
"tick" => behaviours.scheduled_block_tick(&mut level, &mut ticks, origin),
"ftick" => behaviours.scheduled_fluid_tick(&mut level, &mut ticks, origin),
"neighbor" => {
let from = pos_of(&case["from"]);
let changed = behaviours.block(level.block_state(from));
behaviours.handle_neighbor_changed(&mut level, &mut ticks, origin, changed);
}
"run" => {
for op in case["ops"].as_array().unwrap() {
match op["op"].as_str().unwrap() {
"set" => {
behaviours.set_block(
&mut level,
&mut ticks,
pos_of(&op["pos"]),
BlockStateId(op["state"].as_i64().unwrap() as u32),
op["flags"].as_i64().unwrap() as i32,
);
}
"ticks" => {
let snap = op.get("snap").and_then(|v| v.as_bool()).unwrap_or(false);
for _ in 0..op["n"].as_i64().unwrap() {
level.time += 1;
behaviours.tick_scheduled(&mut level, &mut ticks);
if snap {
let _ = writeln!(result, "tick {}", level.time);
summary(&level, &before, &mut result);
}
}
}
other => panic!("unknown op {other}"),
}
}
}
other => panic!("unknown mode {other}"),
}
summary(&level, &before, &mut result);
// Pending scheduled ticks, sorted as the oracle sorts its rows.
let mut rows: Vec<String> = Vec::new();
for x in -3..=3 {
for z in -3..=3 {
let chunk = ChunkPos::new(x, z);
if let Some(c) = ticks.blocks.chunk(chunk) {
for t in c.queued() {
let block = horizon_world::level::BlockId(t.kind.0 as u16);
rows.push(format!(
"bt {} {} {} {}",
p(t.pos),
behaviours.table.info(block).name,
t.trigger_tick - level.time,
t.priority as i32
));
}
}
if let Some(c) = ticks.fluids.chunk(chunk) {
for t in c.queued() {
let name = ["empty", "flowing_water", "water", "flowing_lava", "lava"]
[t.kind.0 as usize];
rows.push(format!(
"ft {} minecraft:{} {} {}",
p(t.pos),
name,
t.trigger_tick - level.time,
t.priority as i32
));
}
}
}
}
rows.sort();
for r in rows {
result.push_str(&r);
result.push('\n');
}
for event in &level.events {
match event {
LevelEvent::LevelEvent { id, pos, data } => {
let _ = writeln!(result, "L {} {} {}", id, p(*pos), data);
}
LevelEvent::Sound { pos, sound, .. } => {
let _ = writeln!(result, "S {} {}", p(*pos), sound);
}
LevelEvent::DropResources { state, .. } => {
let name = behaviours.table.name(*state);
let short = name.strip_prefix("minecraft:").unwrap_or(name);
// `Blocks.wallVariant` reuses the standing block's loot table.
let short = short.replacen("_wall_", "_", 1);
let short = short.strip_prefix("wall_").unwrap_or(&short);
let short = short.replacen("wall_", "", 1);
let _ = writeln!(result, "D minecraft:blocks/{short}");
}
LevelEvent::FallingBlock { .. } => {
let _ = writeln!(result, "E minecraft:falling_block");
}
LevelEvent::PrimeTnt { .. } => {
let _ = writeln!(result, "E minecraft:tnt");
}
LevelEvent::GameEvent { pos, event, .. } => {
let _ = writeln!(result, "G {} {}", p(*pos), event);
}
LevelEvent::BlockEvent { kind, .. } => {
let _ = writeln!(result, "X {kind}");
}
LevelEvent::GrowTree { .. } => {
let _ = writeln!(result, "X grow_tree");
}
LevelEvent::PlaceFeature { feature, .. } => {
let _ = writeln!(result, "X feature {feature}");
}
LevelEvent::Player { .. } => {
let _ = writeln!(result, "X player");
}
}
}
for e in &ticks.block_events {
let _ = writeln!(
result,
"B {} {} {} {}",
p(e.pos),
behaviours.table.info(e.block).name,
e.param_a,
e.param_b
);
}
let _ = writeln!(result, "rng {}", level.random.next_long());
out.write_all(result.as_bytes())?;
}
Ok(())
}
@@ -414,3 +414,36 @@ fn turtle_eggs_crack_at_dawn_on_sand() {
f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.name(pos), "minecraft:air", "hatched");
}
#[test]
fn sniffer_eggs_crack_twice_then_hatch_a_snifflet() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 5);
w.floor("moss_block", 1);
let egg = w.id("sniffer_egg", &[]);
let pos = BlockPos::new(0, 64, 0);
f.behaviours
.set_block(&mut w.level, &mut w.ticks, pos, egg, flags::UPDATE_ALL);
let block = f.behaviours.block(egg);
assert!(
w.ticks.has_block_tick(pos, block),
"placing schedules the first stage"
);
for stage in 1..=2 {
f.behaviours
.scheduled_block_tick(&mut w.level, &mut w.ticks, pos);
assert_eq!(
w.level.block_state(pos),
w.id("sniffer_egg", &[("hatch", &stage.to_string())])
);
}
f.behaviours
.scheduled_block_tick(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.name(pos), "minecraft:air", "hatched");
assert!(w.level.events.iter().any(|e| matches!(
e,
LevelEvent::BlockEvent {
kind: "hatch_sniffer",
..
}
)));
}
+9
View File
@@ -171,6 +171,15 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::Scaffolding => {
self.schedule_tick(pos, block, 1);
}
Class::SnifferEgg => {
let boosted = b.is_block(self.below_state(pos), b.named.moss_block);
if boosted {
self.level_event(3009, pos, 0);
}
let delay = if boosted { 12000 } else { 24000 } / 3;
let jitter = self.random().next_int_bound(300).unwrap_or(0);
self.schedule_tick(pos, block, delay + jitter);
}
Class::SculkSensor => {
if !same
&& b.table.int(state, b.props.power) > 0
+13
View File
@@ -568,6 +568,19 @@ impl Behaviours {
) {
self.sim(level, ticks).update_neighbors_at(pos, block);
}
/// `BlockState.handleNeighborChanged(level, pos, changedBlock, orientation, movedByPiston)`
/// for the state currently at `pos`.
pub fn handle_neighbor_changed<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
changed: BlockId,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
sim.neighbor_changed(state, pos, changed, false);
}
/// Entity collision with a block (`entityInside`) for the entity-sensing
/// blocks: pressure plates, tripwires and buttons hit by arrows are
/// re-evaluated through [`LevelAccess::count_entities`].
@@ -111,6 +111,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
let data = self.b.data(state);
if data.is(super::classes::Class::PistonBase) {
self.piston_trigger_event(pos, state, a, b)
} else if data.is(super::classes::Class::Note) {
self.note_trigger_event(pos, state);
true
} else {
false
}
+32 -22
View File
@@ -1067,35 +1067,45 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.set_block(pos, b.table.set_bool(next, p.powered, signal), 3);
}
}
/// `NoteBlock.playNote` (block event; instrument pitch from `note`).
/// `NoteBlock.playNote`: queues the block event and emits the game event.
pub(crate) fn note_play(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let instrument = b.table.text(state, b.props.instrument);
let mob_head = super::data::INSTRUMENTS
.iter()
.position(|n| *n == instrument)
.is_some_and(|i| super::data::instrument_works_above(i as u8));
if mob_head || b.is_air(self.above_state(pos)) {
self.block_event(pos, b.block(state), 0, 0);
self.game_event(pos, "minecraft:note_block_play");
}
}
/// `NoteBlock.triggerEvent`: the note's sound.
pub(crate) fn note_trigger_event(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let instrument = b.table.text(state, b.props.instrument).to_owned();
let mob_head = super::data::INSTRUMENTS
.iter()
.position(|n| *n == instrument)
.is_some_and(|i| super::data::instrument_works_above(i as u8));
if mob_head || b.is_air(self.above_state(pos)) {
let note = b.table.int(state, b.props.note);
let pitch = if mob_head {
1.0
} else {
2f64.powf(f64::from(note - 12) / 12.0) as f32
};
let sound = match instrument.as_str() {
"custom_head" => "minecraft:ui.button.click".to_owned(),
"dragon" => "minecraft:block.note_block.imitate.ender_dragon".to_owned(),
name if mob_head => format!("minecraft:block.note_block.imitate.{name}"),
name => format!("minecraft:block.note_block.{name}"),
};
self.emit(LevelEvent::Sound {
pos,
sound: sound.into(),
volume: 3.0,
pitch,
});
self.game_event(pos, "minecraft:note_block_play");
}
let note = b.table.int(state, b.props.note);
let pitch = if mob_head {
1.0
} else {
2f64.powf(f64::from(note - 12) / 12.0) as f32
};
let sound = match instrument.as_str() {
"custom_head" => "minecraft:ui.button.click".to_owned(),
"dragon" => "minecraft:block.note_block.imitate.ender_dragon".to_owned(),
name if mob_head => format!("minecraft:block.note_block.imitate.{name}"),
name => format!("minecraft:block.note_block.{name}"),
};
self.emit(LevelEvent::Sound {
pos,
sound: sound.into(),
volume: 3.0,
pitch,
});
}
pub(crate) fn note_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
+1
View File
@@ -148,6 +148,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::Eyeblossom => self.eyeblossom_tick(state, pos, false),
Class::CreakingHeart => self.heart_tick(state, pos),
Class::DriedGhast => self.dried_ghast_tick(state, pos),
Class::SnifferEgg => self.sniffer_egg_tick(state, pos),
Class::RedstoneLamp => self.lamp_tick(pos, state),
Class::RedstoneTorch => self.torch_tick(pos, state),
Class::Scaffolding => self.scaffolding_tick(pos, state),
@@ -173,6 +173,25 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
});
}
}
/// `SnifferEggBlock.tick`: crack twice, then hatch a snifflet.
pub(crate) fn sniffer_egg_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let b = self.b;
let hatch = b.table.int(state, b.props.hatch);
let pitch = 0.9 + self.random().next_float() * 0.2;
if hatch < 2 {
self.play(pos, "minecraft:block.sniffer_egg.crack", 0.7, pitch);
self.set_block(pos, b.table.set_int(state, b.props.hatch, hatch + 1), 2);
} else {
self.play(pos, "minecraft:block.sniffer_egg.hatch", 0.7, pitch);
self.destroy_block(pos, false, 512);
// The snifflet is an entity the caller spawns.
self.emit(LevelEvent::BlockEvent {
pos,
state,
kind: "hatch_sniffer",
});
}
}
/// `DriedGhastBlock.tick`: hydrate while waterlogged, dry out otherwise.
pub(crate) fn dried_ghast_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let b = self.b;
+8 -2
View File
@@ -1,6 +1,6 @@
//! `Level.setBlock`, `LevelChunk.setBlockState` and the
//! `CollectingNeighborUpdater` that orders neighbour and shape updates.
use super::{LevelAccess, LevelEvent, Sim, flags, states::BlockId};
use super::{LevelAccess, LevelEvent, Sim, classes::Class, flags, states::BlockId};
use crate::{fluid::FluidState, registry::BlockStateId};
use horizon_core::{
geometry::Direction,
@@ -338,7 +338,13 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if self.b.is_air(state) {
return false;
}
self.level_event(2001, pos, state.0 as i32);
let is_fire = {
let data = self.b.data(state);
data.is(Class::BaseFire) || data.is(Class::Fire) || data.is(Class::SoulFire)
};
if !is_fire {
self.level_event(2001, pos, state.0 as i32);
}
if drop {
self.drop_resources(state, pos);
}
@@ -0,0 +1,377 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.ticks.LevelTicks;
/**
* Drives vanilla block behaviour (updateShape, randomTick, tick, neighbour
* updates, setBlock cascades and multi-tick runs) over a map-backed headless
* ServerLevel. Shared by tools/test_block_update_parity.py,
* test_random_tick_parity.py and test_redstone_parity.py. Block entities do not
* exist here; entities never exist; every side effect is appended to an event
* log compared against the Rust port.
*/
public final class VanillaBlockUpdateOracle {
static Object unsafe;
static Method allocate;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) {
try {
return (T) allocate.invoke(unsafe, type);
} catch (Exception e) {
throw new AssertionError(e);
}
}
static void set(Class<?> owner, Object target, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
f.set(target, value);
}
static BlockState AIR;
static String pos(BlockPos p) {
return p.getX() + "," + p.getY() + "," + p.getZ();
}
static final class Chunk extends LevelChunk {
World world;
Chunk() {
super(null, null);
}
@Override
public BlockState setBlockState(BlockPos pos, BlockState state, int flags) {
BlockState old = world.cells.getOrDefault(pos.immutable(), AIR);
if (old == state) {
return null;
}
if (state.isAir()) {
world.cells.remove(pos);
} else {
world.cells.put(pos.immutable(), state);
}
Block newBlock = state.getBlock();
boolean blockChanged = !old.is(newBlock);
boolean movedByPiston = (flags & 64) != 0;
if ((blockChanged || newBlock instanceof net.minecraft.world.level.block.BaseRailBlock) && ((flags & 1) != 0 || movedByPiston)) {
old.affectNeighborsAfterRemoval(world, pos, movedByPiston);
}
if (!world.getBlockState(pos).is(newBlock)) {
return null;
}
if ((flags & 512) == 0) {
state.onPlace(world, pos, old, movedByPiston);
}
return old;
}
@Override
public net.minecraft.world.level.chunk.status.ChunkStatus getPersistedStatus() {
return net.minecraft.world.level.chunk.status.ChunkStatus.FULL;
}
@Override
public net.minecraft.server.level.FullChunkStatus getFullStatus() {
return net.minecraft.server.level.FullChunkStatus.ENTITY_TICKING;
}
}
static final class World extends net.minecraft.server.level.ServerLevel {
Map<BlockPos, BlockState> cells = new HashMap<>();
RandomSource rng;
long time;
long subTick;
Chunk chunk;
LevelTicks<Block> blockTicks;
LevelTicks<Fluid> fluidTicks;
StringBuilder log = new StringBuilder();
int skyLight = 15;
int blockLight = 0;
GameRules rules;
Server server;
boolean raining, thundering;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
void emit(String line) {
log.append(line).append('\n');
}
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, AIR); }
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
@Override public BlockEntity getBlockEntity(BlockPos p) { return null; }
@Override public LevelChunk getChunkAt(BlockPos p) { return chunk; }
@Override public LevelChunk getChunk(int x, int z) { return chunk; }
@Override public boolean isLoaded(BlockPos p) { return true; }
@Override public boolean hasChunkAt(BlockPos p) { return true; }
@Override public boolean hasChunksAt(int x0, int z0, int x1, int z1) { return true; }
@Override public boolean hasChunksAt(int x0, int y0, int z0, int x1, int y1, int z1) { return true; }
@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; }
@Override public long getGameTime() { return time; }
@Override public long nextSubTickCount() { return subTick++; }
@Override public LevelTicks<Block> getBlockTicks() { return blockTicks; }
@Override public LevelTicks<Fluid> getFluidTicks() { return fluidTicks; }
@Override public void sendBlockUpdated(BlockPos p, BlockState a, BlockState b, int f) { }
@Override public void setBlocksDirty(BlockPos p, BlockState a, BlockState b) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
@Override public GameRules getGameRules() { return rules; }
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return 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); }
@Override public int getSkyDarken() { return 0; }
@Override public boolean isRaining() { return raining; }
@Override public boolean isThundering() { return thundering; }
@Override public boolean isRainingAt(BlockPos p) { return raining; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, net.minecraft.world.phys.shapes.CollisionContext c) { return true; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public List<Entity> getEntities(Entity except, AABB box, java.util.function.Predicate<? super Entity> filter) { return List.of(); }
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB box, java.util.function.Predicate<? super T> filter) { return List.of(); }
@Override public List<net.minecraft.server.level.ServerPlayer> players() { return List.of(); }
@Override public net.minecraft.world.entity.player.Player getNearestPlayer(double x, double y, double z, double d, boolean b) { return null; }
@Override public boolean addFreshEntity(Entity entity) {
emit("E " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()));
return true;
}
@Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
@Override public void playSeededSound(Entity except, double x, double y, double z, net.minecraft.core.Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {
emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
}
@Override public void playSeededSound(Entity except, Entity src, net.minecraft.core.Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {
emit("S entity " + sound.value().location());
}
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) {
emit("G " + pos(BlockPos.containing(p)) + " " + e.getRegisteredName());
}
@Override public <T extends net.minecraft.core.particles.ParticleOptions> int sendParticles(T p, double x, double y, double z, int n, double a, double b, double c, double s) { return 0; }
@Override public void blockEvent(BlockPos p, Block block, int a, int b) { emit("B " + pos(p) + " " + BuiltInRegistries.BLOCK.getKey(block) + " " + a + " " + b); }
@Override public void updatePOIOnBlockStateChange(BlockPos p, BlockState a, BlockState b) { }
@Override public boolean isPositionEntityTicking(BlockPos p) { return true; }
@Override public boolean shouldTickBlocksAt(BlockPos p) { return true; }
@Override public boolean shouldTickBlocksAt(long p) { return true; }
}
static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder {
World world;
Loot() {
super(null);
}
@Override
public net.minecraft.world.level.storage.loot.LootTable getLootTable(net.minecraft.resources.ResourceKey<net.minecraft.world.level.storage.loot.LootTable> id) {
world.emit("D " + id.identifier());
return net.minecraft.world.level.storage.loot.LootTable.EMPTY;
}
}
static final class Server extends net.minecraft.server.MinecraftServer {
Loot loot;
Server() {
super(null, null, null, null, null, null, null, null, null, false, null);
}
@Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return loot; }
@Override protected boolean initServer() { return false; }
@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; }
@Override public boolean shouldRconBroadcast() { return false; }
@Override protected net.minecraft.util.debugchart.SampleLogger getTickTimeLogger() { return null; }
@Override public boolean isTickTimeLoggingEnabled() { return false; }
@Override public net.minecraft.SystemReport fillServerSystemReport(net.minecraft.SystemReport r) { return r; }
@Override public boolean isDedicatedServer() { return true; }
@Override public int getRateLimitPacketsPerSecond() { return 0; }
@Override public int getCommandSpamThresholdSeconds() { return 0; }
@Override public int getChatSpamThresholdSeconds() { return 0; }
@Override public boolean useNativeTransport() { return false; }
@Override public boolean isPublished() { return false; }
@Override public boolean shouldInformAdmins() { return false; }
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
}
static List<String> summary(World w, Map<BlockPos, BlockState> before) {
List<String> out = new ArrayList<>();
Set<BlockPos> all = new HashSet<>(before.keySet());
all.addAll(w.cells.keySet());
List<BlockPos> sorted = new ArrayList<>(all);
sorted.sort(Comparator.<BlockPos>comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ()));
for (BlockPos p : sorted) {
BlockState a = before.getOrDefault(p, AIR), b = w.cells.getOrDefault(p, AIR);
if (a != b) {
out.add("set " + pos(p) + " " + Block.getId(b));
}
}
return out;
}
@SuppressWarnings("unchecked")
static void pending(World w, StringBuilder out) throws Exception {
for (var pair : List.of(new Object[]{"bt", w.blockTicks}, new Object[]{"ft", w.fluidTicks})) {
Field f = LevelTicks.class.getDeclaredField("allContainers");
f.setAccessible(true);
var map = (it.unimi.dsi.fastutil.longs.Long2ObjectMap<net.minecraft.world.ticks.LevelChunkTicks<Object>>) f.get(pair[1]);
List<String> rows = new ArrayList<>();
for (var container : map.values()) {
container.getAll().forEach(t -> {
String type = t.type() instanceof Block b ? BuiltInRegistries.BLOCK.getKey(b).toString() : BuiltInRegistries.FLUID.getKey((Fluid) t.type()).toString();
rows.add(pair[0] + " " + pos(t.pos()) + " " + type + " " + (t.triggerTick() - w.time) + " " + t.priority().getValue());
});
}
Collections.sort(rows);
for (String r : rows) out.append(r).append('\n');
}
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
AIR = Blocks.AIR.defaultBlockState();
Path resources = Path.of(args[0]);
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject());
VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid"));
var allocator = Class.forName("sun.misc.Unsafe");
var field = allocator.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
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();
StringBuilder result = new StringBuilder("case " + index++ + "\n");
try {
run(f, result);
} catch (Throwable e) {
Throwable c = e;
while (c.getCause() != null) c = c.getCause();
StackTraceElement[] st = c.getStackTrace();
result.append("error ").append(c.getClass().getSimpleName()).append(' ').append(st.length > 0 ? st[0].toString() : "").append('\n');
}
out.print(result);
}
}
}
static BlockPos readPos(JsonArray a) {
return new BlockPos(a.get(0).getAsInt(), a.get(1).getAsInt(), a.get(2).getAsInt());
}
static World build(JsonObject f) throws Exception {
World w = make(World.class);
w.cells = new HashMap<>();
w.log = new StringBuilder();
for (var cell : f.getAsJsonArray("cells")) {
var c = cell.getAsJsonArray();
BlockState s = Block.stateById(c.get(3).getAsInt());
if (!s.isAir()) w.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), s);
}
w.rng = new LegacyRandomSource(f.get("seed").getAsLong());
w.time = f.has("time") ? f.get("time").getAsLong() : 0;
w.rules = new GameRules(FeatureFlags.DEFAULT_FLAGS);
if (f.has("light")) {
w.skyLight = f.getAsJsonArray("light").get(0).getAsInt();
w.blockLight = f.getAsJsonArray("light").get(1).getAsInt();
}
w.raining = f.has("raining") && f.get("raining").getAsBoolean();
w.thundering = f.has("thundering") && f.get("thundering").getAsBoolean();
set(Level.class, w, "random", w.rng);
set(Level.class, w, "neighborUpdater", new net.minecraft.world.level.redstone.CollectingNeighborUpdater(w, 512));
w.server = make(Server.class);
w.server.loot = make(Loot.class);
w.server.loot.world = w;
w.chunk = make(Chunk.class);
w.chunk.world = w;
w.blockTicks = new LevelTicks<>(l -> true);
w.fluidTicks = new LevelTicks<>(l -> true);
for (int x = -3; x <= 3; x++) {
for (int z = -3; z <= 3; z++) {
w.blockTicks.addContainer(new net.minecraft.world.level.ChunkPos(x, z), new net.minecraft.world.ticks.LevelChunkTicks<>());
w.fluidTicks.addContainer(new net.minecraft.world.level.ChunkPos(x, z), new net.minecraft.world.ticks.LevelChunkTicks<>());
}
}
return w;
}
static void run(JsonObject f, StringBuilder result) throws Exception {
World w = build(f);
Map<BlockPos, BlockState> before = new HashMap<>(w.cells);
String mode = f.get("mode").getAsString();
BlockPos p = readPos(f.getAsJsonArray("pos"));
BlockState state = w.getBlockState(p);
switch (mode) {
case "shape" -> {
Direction d = Direction.from3DDataValue(f.get("dir").getAsInt());
BlockPos np = p.relative(d);
BlockState n = Block.stateById(f.get("neighbor").getAsInt());
BlockState s = state.updateShape(w, w, p, d, np, n, w.rng);
result.append("shape ").append(Block.getId(s)).append('\n');
}
case "random" -> {
if (state.isRandomlyTicking()) state.randomTick(w, p, w.rng);
FluidState fs = state.getFluidState();
if (fs.isRandomlyTicking()) fs.randomTick(w, p, w.rng);
}
case "tick" -> state.tick(w, p, w.rng);
case "ftick" -> state.getFluidState().tick(w, p, state);
case "neighbor" -> {
BlockPos from = readPos(f.getAsJsonArray("from"));
w.getBlockState(from);
state.handleNeighborChanged(w, p, w.getBlockState(from).getBlock(), null, false);
}
case "run" -> {
for (var op : f.getAsJsonArray("ops")) {
var o = op.getAsJsonObject();
switch (o.get("op").getAsString()) {
case "set" -> w.setBlock(readPos(o.getAsJsonArray("pos")), Block.stateById(o.get("state").getAsInt()), o.get("flags").getAsInt());
case "ticks" -> {
for (int i = 0; i < o.get("n").getAsInt(); i++) {
w.time++;
w.blockTicks.tick(w.time, 65536, (bp, b) -> { if (w.getBlockState(bp).is(b)) w.getBlockState(bp).tick(w, bp, w.rng); });
w.fluidTicks.tick(w.time, 65536, (bp, fl) -> {
if (w.getFluidState(bp).getType() == fl) w.getFluidState(bp).tick(w, bp, w.getBlockState(bp));
});
if (o.has("snap") && o.get("snap").getAsBoolean()) {
result.append("tick ").append(w.time).append('\n');
for (String s : summary(w, before)) result.append(s).append('\n');
}
}
}
default -> throw new IllegalStateException(o.toString());
}
}
}
default -> throw new IllegalStateException(mode);
}
for (String s : summary(w, before)) result.append(s).append('\n');
pending(w, result);
result.append(w.log);
result.append("rng ").append(w.rng.nextLong()).append('\n');
}
}
@@ -0,0 +1,320 @@
package dev.horizonlab.parity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.context.ContextChain;
import com.mojang.brigadier.suggestion.Suggestion;
import com.mojang.brigadier.suggestion.Suggestions;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import net.minecraft.SharedConstants;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.ServerScoreboard;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import net.minecraft.server.permissions.PermissionLevel;
import net.minecraft.server.permissions.PermissionSet;
import net.minecraft.server.players.PlayerList;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
/**
* Runs a corpus of command strings through vanilla's real Brigadier command
* tree and prints, per input, whether it parses, the error (message and
* cursor), the parsed nodes and the completion suggestions at the end of the
* input. Also exports the registry contents the Rust side needs.
*
* usage: registries|run OUT_DIR [CORPUS PERMISSION_LEVEL]
*/
public final class VanillaCommandParseOracle {
static sun.misc.Unsafe unsafe;
static final String[] PLAYERS = {"Player", "Steve", "Alex"};
static final String[] TEAMS = {"red", "blue"};
static final String[] OBJECTIVES = {"kills", "health", "obj"};
static final String[] TRACKED = {"#total", "Steve", "fake"};
static final class Src extends CommandSourceStack {
final RegistryAccess access;
final HolderLookup.Provider lookup;
Src(MinecraftServer server, PermissionSet perms, RegistryAccess access, HolderLookup.Provider lookup) {
super(CommandSource.NULL, Vec3.ZERO, Vec2.ZERO, null, perms, Component.literal("Player"), server);
this.access = access;
this.lookup = lookup;
}
@Override public Collection<String> getOnlinePlayerNames() { return new ArrayList<>(List.of(PLAYERS)); }
@Override public Collection<String> getAllTeams() { return new ArrayList<>(List.of(TEAMS)); }
@Override public RegistryAccess registryAccess() { return access; }
@Override public Set<ResourceKey<Level>> levels() { return Set.of(Level.OVERWORLD, Level.NETHER, Level.END); }
@Override public FeatureFlagSet enabledFeatures() { return FeatureFlags.VANILLA_SET; }
@Override public <E> java.util.concurrent.CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<E>> key, SharedSuggestionProvider.ElementSuggestionType elements, com.mojang.brigadier.suggestion.SuggestionsBuilder builder, com.mojang.brigadier.context.CommandContext<?> context, java.util.function.Predicate<E> filter) {
java.util.Optional<? extends HolderLookup<E>> registry = access.lookup(key);
if (registry.isEmpty()) registry = lookup.lookup(key);
if (registry.isEmpty()) return Suggestions.empty();
this.suggestRegistryElements(registry.get(), elements, builder, filter);
return builder.buildFuture();
}
}
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
long offset = unsafe.objectFieldOffset(f);
unsafe.putObject(target, offset, value);
}
static String message(CommandSyntaxException e) {
com.mojang.brigadier.Message m = e.getRawMessage();
return m.getString();
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = (sun.misc.Unsafe) unsafeField.get(null);
Path out = Path.of(args[1]);
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);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var dims = RegistryDataLoader.load(resources, java.util.stream.Stream.concat(context.stream(), world.listRegistries()).toList(), RegistryDataLoader.DIMENSION_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world, dims);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
RegistryAccess access = loaded.layers().compositeAccess();
if (args[0].equals("registries")) {
exportRegistries(out, access, lookup);
return;
}
FeatureFlagSet features = FeatureFlags.VANILLA_SET;
CommandBuildContext buildContext = CommandBuildContext.simple(lookup, features);
Commands commands = new Commands(Commands.CommandSelection.INTEGRATED, buildContext);
CommandDispatcher<CommandSourceStack> dispatcher = commands.getDispatcher();
if (args[0].equals("tree")) {
Files.writeString(out.resolve("tree.json"), net.minecraft.commands.synchronization.ArgumentUtils.serializeNodeToJson(dispatcher, dispatcher.getRoot()).toString());
return;
}
MinecraftServer server = (MinecraftServer) unsafe.allocateInstance(DedicatedServer.class);
PlayerList playerList = (PlayerList) unsafe.allocateInstance(net.minecraft.server.dedicated.DedicatedPlayerList.class);
put(playerList, PlayerList.class, "players", new ArrayList<>());
put(server, MinecraftServer.class, "playerList", playerList);
ServerScoreboard scoreboard = new ServerScoreboard(server);
put(server, MinecraftServer.class, "scoreboard", scoreboard);
for (String team : TEAMS) scoreboard.addPlayerTeam(team);
for (String objective : OBJECTIVES)
scoreboard.addObjective(objective, net.minecraft.world.scores.criteria.ObjectiveCriteria.DUMMY, Component.literal(objective),
net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType.INTEGER, true, null);
Object holder = null;
for (String tracked : TRACKED)
scoreboard.getOrCreatePlayerScore(net.minecraft.world.scores.ScoreHolder.forNameOnly(tracked), scoreboard.getObjective("kills"));
PermissionSet perms = LevelBasedPermissionSet.forLevel(PermissionLevel.byId(Integer.parseInt(args[3])));
Src source = new Src(server, perms, access, lookup);
List<String> lines = Files.readAllLines(Path.of(args[2]), StandardCharsets.UTF_8);
java.io.BufferedWriter sb = Files.newBufferedWriter(out.resolve("vanilla.jsonl"));
for (String raw : lines) {
String input = raw;
JsonObject row = new JsonObject();
row.addProperty("in", input);
try {
ParseResults<CommandSourceStack> parse = dispatcher.parse(new StringReader(input), source);
JsonObject result = new JsonObject();
String error = null;
int cursor = 0;
if (parse.getReader().canRead()) {
if (parse.getExceptions().size() == 1) {
CommandSyntaxException e = parse.getExceptions().values().iterator().next();
error = message(e);
cursor = e.getCursor();
} else if (parse.getContext().getRange().isEmpty()) {
error = Component.translatable("command.unknown.command").getString();
cursor = parse.getReader().getCursor();
} else {
error = Component.translatable("command.unknown.argument").getString();
cursor = parse.getReader().getCursor();
}
} else {
var ctx = parse.getContext().build(input);
if (ContextChain.tryFlatten(ctx).isEmpty()) {
error = Component.translatable("command.unknown.command").getString();
cursor = parse.getReader().getCursor();
}
}
if (error == null) {
result.addProperty("ok", true);
JsonArray nodes = new JsonArray();
CommandContextBuilder<CommandSourceStack> b = parse.getContext();
while (b != null) {
for (ParsedCommandNode<CommandSourceStack> n : b.getNodes()) nodes.add(n.getNode().getName());
b = b.getChild();
}
result.add("nodes", nodes);
} else {
result.addProperty("ok", false);
result.addProperty("error", error);
result.addProperty("cursor", cursor);
}
row.add("parse", result);
Suggestions suggestions = dispatcher.getCompletionSuggestions(parse, input.length()).get();
JsonObject sg = new JsonObject();
sg.addProperty("start", suggestions.getRange().getStart());
sg.addProperty("end", suggestions.getRange().getEnd());
JsonArray list = new JsonArray();
for (Suggestion s : suggestions.getList()) {
String text = s.getText();
if (s.getTooltip() != null) text += "\t" + s.getTooltip().getString();
list.add(text);
}
sg.add("list", list);
row.add("sugg", sg);
} catch (Throwable t) {
Throwable root = t;
while (root.getCause() != null) root = root.getCause();
StackTraceElement[] st = root.getStackTrace();
row.addProperty("crash", root + (st.length > 0 ? " @ " + st[0] : ""));
}
sb.write(row.toString());
sb.write("\n");
}
sb.close();
}
static void exportRegistries(Path out, RegistryAccess access, HolderLookup.Provider lookup) throws Exception {
JsonObject o = new JsonObject();
JsonArray items = new JsonArray();
for (var item : BuiltInRegistries.ITEM) {
if (FeatureFlags.VANILLA_SET.isSubsetOf(item.requiredFeatures()))
items.add(BuiltInRegistries.ITEM.getKey(item).toString());
}
o.add("items", items);
JsonObject blocks = new JsonObject();
for (Block block : BuiltInRegistries.BLOCK) {
if (!FeatureFlags.VANILLA_SET.isSubsetOf(block.requiredFeatures())) continue;
JsonArray props = new JsonArray();
for (Property<?> p : block.getStateDefinition().getProperties()) {
JsonArray values = new JsonArray();
for (Object v : p.getPossibleValues()) values.add(((Property) p).getName((Comparable) v));
JsonArray pair = new JsonArray();
pair.add(p.getName());
pair.add(values);
props.add(pair);
}
blocks.add(BuiltInRegistries.BLOCK.getKey(block).toString(), props);
}
o.add("blocks", blocks);
o.add("item_tags", tags(lookup, Registries.ITEM));
o.add("block_tags", tags(lookup, Registries.BLOCK));
JsonArray summonable = new JsonArray();
JsonArray types = new JsonArray();
for (var type : BuiltInRegistries.ENTITY_TYPE) {
if (!FeatureFlags.VANILLA_SET.isSubsetOf(type.requiredFeatures())) continue;
String id = BuiltInRegistries.ENTITY_TYPE.getKey(type).toString();
types.add(id);
if (type.canSummon()) summonable.add(id);
}
o.add("entity_types", types);
o.add("summonable", summonable);
o.add("effects", ids(BuiltInRegistries.MOB_EFFECT));
o.add("attributes", ids(BuiltInRegistries.ATTRIBUTE));
o.add("sounds", ids(BuiltInRegistries.SOUND_EVENT));
o.add("enchantments", dynamic(access, Registries.ENCHANTMENT));
o.add("structures", dynamic(access, Registries.STRUCTURE));
o.add("biomes", dynamic(access, Registries.BIOME));
o.add("damage_types", dynamic(access, Registries.DAMAGE_TYPE));
o.add("clocks", dynamic(access, Registries.WORLD_CLOCK));
o.add("timelines", dynamic(access, Registries.TIMELINE));
o.add("dimensions", arr("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end"));
o.add("players", arr(PLAYERS));
o.add("teams", arr(TEAMS));
o.add("objectives", arr(OBJECTIVES));
o.add("tracked", arr(TRACKED));
JsonObject by = new JsonObject();
lookup.listRegistryKeys().sorted(java.util.Comparator.comparing(k -> k.identifier().toString())).forEach(key -> {
var reg = lookup.lookupOrThrow(key);
JsonObject entry = new JsonObject();
java.util.List<String> ids = reg.listElementIds().map(k -> k.identifier().toString()).sorted().toList();
JsonArray idArr = new JsonArray();
ids.forEach(idArr::add);
entry.add("ids", idArr);
JsonArray tagArr = new JsonArray();
reg.listTagIds().map(t -> t.location().toString()).sorted().forEach(tagArr::add);
entry.add("tags", tagArr);
by.add(key.identifier().toString(), entry);
});
o.add("by_registry", by);
Files.writeString(out.resolve("registries.json"), o.toString());
}
static JsonArray arr(String... values) {
JsonArray a = new JsonArray();
for (String v : values) a.add(v);
return a;
}
static <T> JsonArray ids(Registry<T> registry) {
Set<String> sorted = new TreeSet<>();
for (var key : registry.keySet()) sorted.add(key.toString());
JsonArray a = new JsonArray();
sorted.forEach(a::add);
return a;
}
static <T> JsonArray dynamic(RegistryAccess access, ResourceKey<? extends Registry<T>> key) {
return ids(access.lookupOrThrow(key));
}
static <T> JsonArray tags(HolderLookup.Provider lookup, ResourceKey<? extends Registry<T>> key) {
Set<String> sorted = new TreeSet<>();
lookup.lookupOrThrow(key).listTagIds().forEach(t -> sorted.add(t.location().toString()));
JsonArray a = new JsonArray();
sorted.forEach(a::add);
return a;
}
}
@@ -0,0 +1,407 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.MapCodec;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.*;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.renderer.item.*;
import net.minecraft.client.renderer.item.properties.select.SelectItemModelProperty;
import net.minecraft.client.renderer.special.SpecialModelRenderer;
import net.minecraft.client.renderer.special.SpecialModelRenderers;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection;
import net.minecraft.client.resources.model.*;
import net.minecraft.client.resources.model.cuboid.*;
import net.minecraft.client.resources.model.geometry.BakedQuad;
import net.minecraft.client.resources.model.sprite.SpriteGetter;
import net.minecraft.client.resources.model.sprite.SpriteId;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.registries.VanillaRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryOps;
import net.minecraft.util.StrictJsonParser;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.ItemOwner;
import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.item.*;
import net.minecraft.world.item.component.BundleContents;
import net.minecraft.world.level.GrassColor;
import net.minecraft.world.level.Level;
import org.joml.Matrix4f;
import org.joml.Vector3fc;
/**
* Drives the pinned client's own item pipeline headlessly: the ClientItem codec,
* ModelDiscovery, ModelBakery with real baked item models, ItemModelResolver
* semantics and ItemStackRenderState layers. Sprites are real PNGs in a unit
* atlas; the player skin cache and GPU are never touched.
*/
public final class VanillaItemModelOracle {
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
private static long bits(float value) { return Integer.toUnsignedLong(Float.floatToIntBits(value)); }
static Map<String, Object> map(Object... values) {
var result = new TreeMap<String, Object>();
for (int i = 0; i < values.length; i += 2) result.put((String) values[i], values[i + 1]);
return result;
}
static Path root;
static HolderLookup.Provider registries;
static RegistryOps<JsonElement> ops;
static String frozenTime = "";
static final Identifier BLOCKS = TextureAtlas.LOCATION_BLOCKS, ITEMS = TextureAtlas.LOCATION_ITEMS;
static final class Sprite extends TextureAtlasSprite {
Sprite(Identifier atlas, SpriteContents contents) { super(atlas, contents, contents.width(), contents.height(), 0, 0, 0); }
}
/** Sprites loaded on demand from the extracted jar. */
static final class Regions extends HashMap<Identifier, TextureAtlasSprite> {
final boolean items;
Regions(boolean items) { this.items = items; }
@Override public TextureAtlasSprite get(Object key) {
var id = (Identifier) key;
boolean itemAtlas = id.getPath().startsWith("item/") || id.getPath().startsWith("trims/");
if (itemAtlas != items) return null;
return computeIfAbsent(id, k -> load(k, items ? ITEMS : BLOCKS));
}
}
static TextureAtlasSprite load(Identifier id, Identifier atlas) {
try {
var png = root.resolve("assets").resolve(id.getNamespace()).resolve("textures").resolve(id.getPath() + ".png");
if (!Files.isRegularFile(png)) return null;
NativeImage image;
try (var in = Files.newInputStream(png)) { image = NativeImage.read(in); }
var mcmeta = png.resolveSibling(png.getFileName() + ".mcmeta");
Optional<AnimationMetadataSection> animation = Optional.empty();
if (Files.isRegularFile(mcmeta)) {
var json = JsonParser.parseString(Files.readString(mcmeta)).getAsJsonObject();
if (json.has("animation"))
animation = Optional.of(AnimationMetadataSection.CODEC.parse(JsonOps.INSTANCE, json.get("animation")).getOrThrow());
}
var size = animation.map(a -> a.calculateFrameSize(image.getWidth(), image.getHeight()))
.orElse(new net.minecraft.client.resources.metadata.animation.FrameSize(image.getWidth(), image.getHeight()));
return new Sprite(atlas, new SpriteContents(id, size, image, animation, List.of(), Optional.empty()));
} catch (IOException e) { throw new UncheckedIOException(e); }
}
// --- Tagging of special renderers so the layer carries its codec form. ---
static final class Tagged implements SpecialModelRenderer.Unbaked<Object> {
final SpecialModelRenderer.Unbaked<?> delegate;
Tagged(SpecialModelRenderer.Unbaked<?> delegate) { this.delegate = delegate; }
@SuppressWarnings({"unchecked", "rawtypes"})
public MapCodec<? extends SpecialModelRenderer.Unbaked<Object>> type() { return (MapCodec) delegate.type(); }
public SpecialModelRenderer<Object> bake(SpecialModelRenderer.BakingContext context) {
var baked = delegate.bake(context);
if (baked == null) return null;
@SuppressWarnings({"unchecked", "rawtypes"}) JsonElement config = SpecialModelRenderers.CODEC.encodeStart(JsonOps.INSTANCE, (SpecialModelRenderer.Unbaked) delegate).getOrThrow();
return new TaggedRenderer(baked, config);
}
}
static final class TaggedRenderer implements SpecialModelRenderer<Object> {
final SpecialModelRenderer<?> delegate; final JsonElement config;
TaggedRenderer(SpecialModelRenderer<?> delegate, JsonElement config) { this.delegate = delegate; this.config = config; }
public void submit(Object argument, com.mojang.blaze3d.vertex.PoseStack poseStack, net.minecraft.client.renderer.SubmitNodeCollector collector, int light, int overlay, boolean foil, int outline) {}
public void getExtents(java.util.function.Consumer<Vector3fc> output) { delegate.getExtents(output); }
public Object extractArgument(ItemStack stack) { return new Argument(argument(config.getAsJsonObject().get("type").getAsString(), stack)); }
}
record Argument(JsonElement json) {}
static JsonElement encode(DataComponentType<?> type, ItemStack stack) {
var value = stack.get((DataComponentType) type);
if (value == null) return JsonNull.INSTANCE;
@SuppressWarnings({"unchecked", "rawtypes"}) var result = ((Codec) type.codecOrThrow()).encodeStart(ops, value).getOrThrow();
return (JsonElement) result;
}
static JsonElement argument(String type, ItemStack stack) {
return switch (type) {
case "minecraft:banner" -> encode(DataComponents.BANNER_PATTERNS, stack);
case "minecraft:decorated_pot" -> encode(DataComponents.POT_DECORATIONS, stack);
case "minecraft:player_head" -> encode(DataComponents.PROFILE, stack);
case "minecraft:shield" -> {
var o = new JsonObject();
var patterns = encode(DataComponents.BANNER_PATTERNS, stack);
if (!patterns.isJsonNull()) o.add("minecraft:banner_patterns", patterns);
var color = encode(DataComponents.BASE_COLOR, stack);
if (!color.isJsonNull()) o.add("minecraft:base_color", color);
yield o;
}
default -> JsonNull.INSTANCE;
};
}
/** Stands in for LocalTime so a case can script the formatted time. */
record FrozenTime(Codec<String> valueCodec) implements SelectItemModelProperty<String> {
public String get(ItemStack s, ClientLevel l, net.minecraft.world.entity.LivingEntity o, int seed, ItemDisplayContext d) { return frozenTime; }
@SuppressWarnings({"unchecked", "rawtypes"})
public SelectItemModelProperty.Type type() { return net.minecraft.client.renderer.item.properties.select.LocalTime.TYPE; }
}
@SuppressWarnings({"unchecked", "rawtypes"})
static ItemModel.Unbaked tag(ItemModel.Unbaked u) {
if (u instanceof SpecialModelWrapper.Unbaked s)
return new SpecialModelWrapper.Unbaked(s.base(), s.transformation(), new Tagged(s.specialModel()));
if (u instanceof CompositeModel.Unbaked c)
return new CompositeModel.Unbaked(c.models().stream().map(VanillaItemModelOracle::tag).collect(Collectors.toList()), c.transformation());
if (u instanceof ConditionalItemModel.Unbaked c)
return new ConditionalItemModel.Unbaked(c.transformation(), c.property(), tag(c.onTrue()), tag(c.onFalse()));
if (u instanceof SelectItemModel.Unbaked s) {
var sw = (SelectItemModel.UnbakedSwitch) s.unbakedSwitch();
var cases = new ArrayList<SelectItemModel.SwitchCase>();
for (var c : (List<SelectItemModel.SwitchCase>) sw.cases()) cases.add(new SelectItemModel.SwitchCase(c.values(), tag(c.model())));
Object property = sw.property();
if (property instanceof net.minecraft.client.renderer.item.properties.select.LocalTime) property = new FrozenTime(Codec.STRING);
return new SelectItemModel.Unbaked(s.transformation(), new SelectItemModel.UnbakedSwitch((SelectItemModelProperty) property, cases), s.fallback().map(VanillaItemModelOracle::tag));
}
if (u instanceof RangeSelectItemModel.Unbaked r) {
var entries = new ArrayList<RangeSelectItemModel.Entry>();
for (var e : r.entries()) entries.add(new RangeSelectItemModel.Entry(e.threshold(), tag(e.model())));
return new RangeSelectItemModel.Unbaked(r.transformation(), r.property(), r.scale(), entries, r.fallback().map(VanillaItemModelOracle::tag));
}
return u;
}
// --- Scripted owner ---
static final class Actor extends ArmorStand {
boolean using; int remaining; ItemStack stack = ItemStack.EMPTY; HumanoidArm arm = HumanoidArm.RIGHT; EntityType<?> kind = EntityTypes.PLAYER;
Actor() { super(null, null); }
@Override public boolean isUsingItem() { return using; }
@Override public ItemStack getUseItem() { return using ? stack : ItemStack.EMPTY; }
@Override public int getUseItemRemainingTicks() { return remaining; }
@Override public HumanoidArm getMainArm() { return arm; }
@Override public net.minecraft.core.Holder.Reference<EntityType<?>> typeHolder() { return kind.builtInRegistryHolder(); }
}
static Object unsafe; static Method allocate;
@SuppressWarnings("unchecked") static <T> T make(Class<T> type) throws Exception { return (T) allocate.invoke(unsafe, type); }
static final class Resolver extends ItemModelResolver {
Map<Identifier, ItemModel> models; Map<Identifier, ClientItem.Properties> properties; ItemModel missing;
Resolver() { super(null); }
@Override public void appendItemLayers(ItemStackRenderState output, ItemStack item, ItemDisplayContext context, Level level, ItemOwner owner, int seed) {
Identifier id = item.get(DataComponents.ITEM_MODEL);
if (id != null) {
output.setOversizedInGui(properties.getOrDefault(id, ClientItem.Properties.DEFAULT).oversizedInGui());
models.getOrDefault(id, missing).update(output, item, this, context, level instanceof ClientLevel c ? c : null, owner, seed);
}
}
}
static Object field(Object target, Class<?> type, String name) throws Exception {
var f = type.getDeclaredField(name); f.setAccessible(true); return f.get(target);
}
static Object quad(BakedQuad q) {
var positions = new long[4][3]; var uvs = new long[4][2];
for (int i = 0; i < 4; i++) {
var p = q.position(i); positions[i] = new long[]{bits(p.x()), bits(p.y()), bits(p.z())};
long packed = q.packedUV(i); uvs[i] = new long[]{packed >>> 32, packed & 0xffffffffL};
}
var info = q.materialInfo();
return map("positions", positions, "uv", uvs, "facing", q.direction().getName(), "tint", info.tintIndex(),
"sprite", info.sprite().contents().name().toString(),
"shade", info.shadeDirectionOverride() == null ? null : info.shadeDirectionOverride().getName(), "light", info.lightEmission());
}
static Object matrix(Matrix4f m) {
var rows = new long[16];
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) rows[r * 4 + c] = bits(m.getRowColumn(r, c));
return rows;
}
static Object layer(ItemStackRenderState state, Object layer, ItemDisplayContext context) throws Exception {
var type = layer.getClass();
var out = new TreeMap<String, Object>();
var special = (SpecialModelRenderer<?>) field(layer, type, "specialRenderer");
var tints = (it.unimi.dsi.fastutil.ints.IntList) field(layer, type, "tintLayers");
out.put("tints", tints == null ? new int[0] : tints.toIntArray());
out.put("foil", ((ItemStackRenderState.FoilType) field(layer, type, "foilType")).name().toLowerCase(Locale.ROOT));
var pose = new com.mojang.blaze3d.vertex.PoseStack.Pose();
var apply = type.getDeclaredMethod("applyTransform", com.mojang.blaze3d.vertex.PoseStack.Pose.class);
apply.setAccessible(true); apply.invoke(layer, pose);
out.put("matrix", matrix(pose.pose()));
out.put("uses_block_light", field(layer, type, "usesBlockLight"));
var particle = (net.minecraft.client.resources.model.sprite.Material.Baked) field(layer, type, "particleMaterial");
out.put("particle", particle == null ? null : particle.sprite().contents().name().toString());
var transform = (net.minecraft.client.resources.model.cuboid.ItemTransform) field(layer, type, "itemTransform");
out.put("has_transform", transform != net.minecraft.client.resources.model.cuboid.ItemTransform.NO_TRANSFORM);
if (special instanceof TaggedRenderer tagged) {
out.put("kind", "special");
out.put("special", tagged.config);
var argument = field(layer, type, "argumentForSpecialRendering");
out.put("argument", argument instanceof Argument a ? a.json() : JsonNull.INSTANCE);
} else {
var quads = (net.minecraft.client.resources.model.geometry.ItemQuads) field(layer, type, "quads");
out.put("quads", quads.all().stream().map(VanillaItemModelOracle::quad).toList());
out.put("kind", "model");
}
return out;
}
static Map<String, JsonObject> prototypes = new HashMap<>();
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
ItemModels.bootstrap();
SpecialModelRenderers.bootstrap();
net.minecraft.client.color.item.ItemTintSources.bootstrap();
net.minecraft.client.renderer.item.properties.select.SelectItemModelProperties.bootstrap();
net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperties.bootstrap();
net.minecraft.client.renderer.item.properties.numeric.RangeSelectItemModelProperties.bootstrap();
var u = Class.forName("sun.misc.Unsafe");
var uf = u.getDeclaredField("theUnsafe"); uf.setAccessible(true); unsafe = uf.get(null);
allocate = u.getMethod("allocateInstance", Class.class);
root = Path.of(args[0]);
registries = VanillaRegistries.createWorldLookup();
ops = RegistryOps.create(JsonOps.INSTANCE, registries);
// Default components come from the prepared export of the vanilla reports.
var defaults = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject();
for (var item : BuiltInRegistries.ITEM) {
var json = defaults.get(BuiltInRegistries.ITEM.getKey(item).toString());
var map = json == null ? net.minecraft.core.component.DataComponentMap.EMPTY
: net.minecraft.core.component.DataComponentMap.CODEC.parse(ops, json).getOrThrow();
item.builtInRegistryHolder().bindComponents(map);
}
// Grass colour map for the grass tint.
try (var in = Files.newInputStream(root.resolve("assets/minecraft/textures/colormap/grass.png")); var image = NativeImage.read(in)) {
GrassColor.init(image.getPixels());
}
// Every model file.
var models = new HashMap<Identifier, UnbakedModel>();
try (Stream<Path> files = Files.walk(root.resolve("assets/minecraft/models"))) {
for (var file : (Iterable<Path>) files.filter(p -> p.toString().endsWith(".json"))::iterator) {
var relative = root.resolve("assets/minecraft/models").relativize(file).toString().replace('\\', '/');
try (var reader = Files.newBufferedReader(file)) {
models.put(Identifier.withDefaultNamespace(relative.substring(0, relative.length() - 5)), CuboidModel.fromStream(reader));
} catch (RuntimeException ignored) {}
}
}
// Every item definition.
var output = Files.newBufferedWriter(Path.of(args[2]));
output.write(JSON.toJson(map("row", "components", "names",
BuiltInRegistries.DATA_COMPONENT_TYPE.keySet().stream().map(Identifier::toString).sorted().toList()))); output.newLine();
var items = new TreeMap<Identifier, ClientItem>();
try (Stream<Path> files = Files.list(root.resolve("assets/minecraft/items"))) {
for (var file : (Iterable<Path>) files.sorted()::iterator) {
var name = file.getFileName().toString();
var id = Identifier.withDefaultNamespace(name.substring(0, name.length() - 5));
String text = Files.readString(file);
boolean ok = decode(id, text, items);
output.write(JSON.toJson(map("row", "decode", "name", name, "ok", ok))); output.newLine();
}
}
// Synthetic definitions from the harness.
try (var lines = Files.lines(Path.of(args[1] + ".definitions"))) {
for (var line : (Iterable<String>) lines::iterator) {
var row = JsonParser.parseString(line).getAsJsonObject();
var id = Identifier.parse(row.get("name").getAsString());
boolean ok = decode(id, row.get("json").getAsString(), items);
output.write(JSON.toJson(map("row", "decode", "name", row.get("name").getAsString(), "ok", ok))); output.newLine();
}
}
var missingModel = MissingCuboidModel.missingModel();
var discovery = new ModelDiscovery(models, missingModel);
discovery.addSpecialModel(ItemModelGenerator.GENERATED_ITEM_MODEL_ID, new ItemModelGenerator());
items.values().forEach(info -> discovery.addRoot(info.model()));
var resolved = discovery.resolve();
var missingSprite = new Sprite(BLOCKS, MissingTextureAtlasSprite.create());
var blockAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(false), CompletableFuture.completedFuture(null));
var itemAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(true), CompletableFuture.completedFuture(null));
var materials = new net.minecraft.client.resources.model.sprite.MaterialBaker(blockAtlas, itemAtlas);
var dummy = new Sprite(ITEMS, new SpriteContents(Identifier.parse("minecraft:dummy"), new net.minecraft.client.resources.metadata.animation.FrameSize(16, 16), new NativeImage(16, 16, true)));
SpriteGetter sprites = id -> dummy;
var bakery = new ModelBakery(EntityModelSet.vanilla(), sprites, null, Map.of(), tagged(items), resolved, discovery.missingModel());
var baked = bakery.bakeModels(materials, Runnable::run).join();
var resolver = new Resolver();
resolver.models = baked.itemStackModels(); resolver.properties = baked.itemProperties(); resolver.missing = baked.missingModels().item();
for (var id : items.keySet()) if (!resolver.models.containsKey(id)) {
output.write(JSON.toJson(map("row", "unbaked", "name", id.toString()))); output.newLine();
}
var state = new ItemStackRenderState();
try (var lines = Files.lines(Path.of(args[1]))) {
for (var line : (Iterable<String>) lines::iterator) {
var row = JsonParser.parseString(line).getAsJsonObject();
var result = new TreeMap<String, Object>();
result.put("row", "case"); result.put("id", row.get("id").getAsString());
try {
var stackJson = new JsonObject();
stackJson.addProperty("id", row.get("item").getAsString());
stackJson.addProperty("count", row.get("count").getAsInt());
if (row.has("components")) stackJson.add("components", row.get("components"));
var stack = ItemStack.CODEC.parse(ops, stackJson).getOrThrow();
if (row.has("bundle_selected") && row.get("bundle_selected").getAsInt() >= 0) {
var contents = stack.get(DataComponents.BUNDLE_CONTENTS);
var mutable = contents.asMutable();
mutable.toggleSelectedItem(row.get("bundle_selected").getAsInt());
stack.set(DataComponents.BUNDLE_CONTENTS, mutable.toImmutable());
}
var context = ItemDisplayContext.CODEC.parse(JsonOps.INSTANCE, row.get("context")).getOrThrow();
frozenTime = row.has("local_time") ? row.get("local_time").getAsString() : "";
Actor actor = null;
if (row.has("owner") && !row.get("owner").isJsonNull()) {
var o = row.getAsJsonObject("owner");
actor = make(Actor.class);
actor.using = o.get("using").getAsBoolean();
actor.remaining = o.get("remaining").getAsInt();
actor.stack = stack;
actor.arm = o.get("main_arm").getAsString().equals("left") ? HumanoidArm.LEFT : HumanoidArm.RIGHT;
actor.kind = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(o.get("entity_type").getAsString()));
var derived = new TreeMap<String, Object>();
derived.put("use_duration", stack.getUseDuration(actor));
try { derived.put("charge_duration", CrossbowItem.getChargeDuration(stack, actor)); } catch (RuntimeException e) { derived.put("charge_duration", 0); }
result.put("derived", derived);
}
Level level = null;
if (row.has("dimension") && !row.get("dimension").isJsonNull()) {
var dim = net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DIMENSION, Identifier.parse(row.get("dimension").getAsString()));
var clientLevel = make(ClientLevel.class);
var f = Level.class.getDeclaredField("dimension"); f.setAccessible(true);
var offset = (long) u.getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
u.getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, clientLevel, offset, dim);
level = clientLevel;
}
resolver.updateForTopItem(state, stack, context, level, actor, row.has("seed") ? row.get("seed").getAsInt() : 0);
var layersField = ItemStackRenderState.class.getDeclaredField("layers"); layersField.setAccessible(true);
var countField = ItemStackRenderState.class.getDeclaredField("activeLayerCount"); countField.setAccessible(true);
var layers = (Object[]) layersField.get(state); int count = countField.getInt(state);
var list = new ArrayList<Object>();
for (int i = 0; i < count; i++) list.add(layer(state, layers[i], context));
result.put("layers", list);
result.put("oversized", state.isOversizedInGui());
result.put("swap", map("play", resolver.shouldPlaySwapAnimation(stack), "scale", bits(resolver.swapAnimationScale(stack))));
} catch (Throwable e) {
Throwable cause = e; while (cause.getCause() != null) cause = cause.getCause();
result.put("error", cause.toString());
}
output.write(JSON.toJson(result)); output.newLine();
}
}
output.close();
}
static Map<Identifier, ClientItem> tagged(Map<Identifier, ClientItem> items) {
var out = new TreeMap<Identifier, ClientItem>();
items.forEach((id, item) -> out.put(id, new ClientItem(tag(item.model()), item.properties(), item.registrySwapper())));
return out;
}
static boolean decode(Identifier id, String text, Map<Identifier, ClientItem> items) {
try {
var parsed = ClientItem.CODEC.parse(ops, StrictJsonParser.parse(new StringReader(text))).result();
parsed.ifPresent(item -> items.put(id, item));
return parsed.isPresent();
} catch (Exception e) { return false; }
}
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Shared driver of the block update / random tick / redstone differential harnesses.
Cases are JSON lines understood by `VanillaBlockUpdateOracle` (vanilla block code
over a map-backed headless ServerLevel) and `block_update_fixture` (the Rust
`Behaviours` over the same kind of level). Both print one result block per case
(state changes, pending scheduled ticks, side-effect log, RNG fingerprint); this
module generates cases, runs both sides and reports differing cases grouped by
the block under test.
"""
import argparse
import json
import os
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
NEIGHBOUR_PALETTE = [
'stone', 'dirt', 'grass_block', 'water', 'lava', 'sand', 'oak_log', 'oak_planks', 'farmland', 'snow', 'snow_block',
'ice', 'packed_ice', 'soul_sand', 'netherrack', 'mycelium', 'podzol', 'gravel', 'glass', 'oak_leaves', 'fire',
'redstone_block', 'redstone_wire', 'redstone_torch', 'torch', 'lever', 'iron_block', 'magma_block', 'bedrock',
'cobblestone', 'obsidian', 'tnt', 'oak_slab', 'oak_stairs', 'hopper', 'bamboo', 'cactus', 'sugar_cane', 'kelp',
'seagrass', 'vine', 'moss_block', 'dripstone_block', 'amethyst_block', 'calcite', 'clay', 'coarse_dirt', 'rooted_dirt',
]
DIRS = [(0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)]
class Facts:
def __init__(self, resources):
facts = json.loads((resources / 'facts.json').read_text())
self.states = facts['states']
self.defaults = facts['defaults']
self.by_block = {}
for index, state in enumerate(self.states):
self.by_block.setdefault(state[0], []).append(index)
self.palette = [name for name in ('minecraft:' + n for n in NEIGHBOUR_PALETTE) if name in self.by_block]
self.names = list(self.by_block)
def describe(self, index):
return self.states[index][3].replace('Block{', '').replace('}', '', 1)
def neighbour(self, rng, own):
roll = rng.random()
if roll < 0.30:
return rng.choice(self.by_block[rng.choice(self.palette)])
if roll < 0.45:
return rng.choice(self.by_block[self.states[own][0]])
if roll < 0.60:
return rng.choice(self.by_block[rng.choice(self.names)])
return None
def cells(self, rng, origin_state, density=0.55, face_density=0.8, extent=2):
cells = [[0, 0, 0, origin_state]]
for x in range(-extent, extent + 1):
for y in range(-extent, extent + 1):
for z in range(-extent, extent + 1):
if (x, y, z) == (0, 0, 0):
continue
face = abs(x) + abs(y) + abs(z) == 1
if rng.random() > (face_density if face else density):
continue
state = self.neighbour(rng, origin_state)
if state is not None:
cells.append([x, y, z, state])
return cells
def environment(rng):
case = {'seed': rng.randrange(1 << 40), 'time': rng.randrange(0, 100000)}
roll = rng.random()
if roll < 0.5:
case['light'] = [15, 0]
elif roll < 0.7:
case['light'] = [0, 0]
elif roll < 0.85:
case['light'] = [rng.randrange(16), rng.randrange(16)]
else:
case['light'] = [15, 15]
if rng.random() < 0.1:
case['raining'] = True
case['thundering'] = rng.random() < 0.3
return case
def put(cells, pos, state):
for cell in cells:
if cell[:3] == list(pos):
cell[3] = state
return
cells.append([*pos, state])
def argument_parser(description):
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--count', type=int, default=40000, help='cases to generate')
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--only', help='substring of the block name under test')
parser.add_argument('--show', type=int, default=1, help='examples printed per block')
parser.add_argument('--events', action='store_true', help='compare side-effect logs too (default: states, ticks, rng and events)')
parser.add_argument('--ignore', default='', help='comma separated line prefixes to ignore when comparing (e.g. S,G)')
return parser
def blocks_of(facts):
return facts.names
def run(command, **kwargs):
done = subprocess.run(command, capture_output=True, text=True, **kwargs)
if done.returncode:
print((done.stdout + done.stderr)[-3000:])
raise SystemExit(f'{command[0]} failed')
return done
def execute(name, cases, args, facts, origin_of=None):
"""Run `cases` on both sides; print a report and return the number of differing cases."""
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / name
work.mkdir(parents=True, exist_ok=True)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
java_root = lab.ROOT / 'mods/horizon/src/test/java'
run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaBlockUpdateOracle.java')])
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockUpdateOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'block_update_fixture', '--',
str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'})
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix)
native = split_cases((work / 'native.txt').read_text(), ignore)
rust = split_cases((work / 'rust.txt').read_text(), ignore)
assert len(native) == len(rust) == len(cases), (len(native), len(rust), len(cases))
groups = {}
errors = {}
for case, a, b in zip(cases, native, rust):
if a and a[0].startswith('error'):
errors.setdefault(a[0], []).append(case)
continue
if a != b:
groups.setdefault(origin_name(case, facts), []).append((case, a, b))
total = sum(len(v) for v in groups.values())
for kind, entries in sorted(errors.items(), key=lambda entry: -len(entry[1])):
print(f'oracle error x{len(entries)}: {kind} (e.g. {facts.describe(entries[0]["cells"][0][3])})')
for block, entries in sorted(groups.items(), key=lambda entry: -len(entry[1])):
print(f'{block}: {len(entries)} differing')
for case, a, b in entries[:args.show]:
print(' case ' + describe_case(case, facts))
print(' native ' + ' | '.join(a))
print(' rust ' + ' | '.join(b))
skipped = sum(len(v) for v in errors.values())
print(f'{len(cases) - total - skipped}/{len(cases) - skipped} cases match ({skipped} oracle errors)')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in groups.items()}))
return total
def split_cases(text, ignore):
out = []
for block in text.split('case ')[1:]:
lines = block.splitlines()[1:]
out.append([line for line in lines if not line.startswith(ignore)] if ignore else lines)
return out
def origin_name(case, facts):
pos = case.get('pos', [0, 0, 0])
for cell in case['cells']:
if cell[:3] == pos:
return facts.states[cell[3]][0]
return 'minecraft:air'
def describe_case(case, facts):
pos = case.get('pos', [0, 0, 0])
parts = [case['mode'], facts.describe(next(c[3] for c in case['cells'] if c[:3] == pos))]
if case['mode'] == 'shape':
parts.append(f'dir={case["dir"]} neighbor={facts.describe(case["neighbor"])}')
if case['mode'] == 'neighbor':
parts.append(f'from={case["from"]}')
if case.get('light') not in (None, [15, 0]):
parts.append(f'light={case["light"]}')
if case.get('raining'):
parts.append('raining')
near = []
for dx, dy, dz in DIRS:
at = [pos[0] + dx, pos[1] + dy, pos[2] + dz]
state = next((c[3] for c in case['cells'] if c[:3] == at), None)
near.append('air' if state is None else facts.describe(state))
parts.append('faces=' + ';'.join(near))
return ' '.join(parts) + f' seed={case["seed"]} time={case.get("time")}'
def load_facts():
lock, _, _ = base.verify_artifacts()
return Facts(lab.LOCAL / 'horizon-client' / lock['minecraft']['version'])
def state_pool(facts, only):
return [i for i, s in enumerate(facts.states) if not only or only in s[0]]
def finish(differing):
raise SystemExit(1 if differing else 0)
+545
View File
@@ -0,0 +1,545 @@
"""Command corpus for tools/test_command_parse_parity.py.
The corpus walks vanilla's exported command tree. For every executable path it
emits the valid command (sample values per argument type), every token-boundary
prefix (completion suggestions), mutations that replace one argument by a bad
sample of its type (error message and cursor), a truncated last argument and a
trailing-garbage variant. Hand-written extra commands cover selectors, NBT
paths, coordinates, ranges and the other parsers in more depth.
"""
import hashlib
SELECTORS = [
'@s', '@a', '@e', '@p', '@r', '@n', 'Player', 'Steve', 'some_name', '00000000-0000-0000-0000-000000000001',
'@a[distance=..5]', '@e[distance=1..5]', '@e[distance=2]', '@e[type=minecraft:pig,limit=1,sort=nearest]', '@e[type=!zombie]',
'@e[type=#minecraft:skeletons]', '@e[tag=a,tag=!b]', '@e[tag=]', '@e[tag=!]', '@e[team=red]', '@e[team=!red]', '@e[team=]',
'@e[scores={kills=1..}]', '@e[scores={kills=1,health=..5}]', '@e[nbt={Invulnerable:1b}]', '@e[nbt=!{Invulnerable:1b}]',
'@e[x=1,y=2,z=3,dx=4,dy=5,dz=6]', '@e[x=1.5]', '@e[level=5..10]', '@e[level=3]', '@a[gamemode=survival]', '@a[gamemode=!creative]',
'@e[name="Bob"]', '@e[name=Bob]', '@e[name=!Bob]', '@e[advancements={minecraft:story/root=true}]',
'@e[advancements={minecraft:story/root={a=true}}]', '@e[predicate=minecraft:foo]', '@e[predicate=!minecraft:foo]',
'@e[x_rotation=..0]', '@e[y_rotation=90..180]', '@e[x_rotation=0]', '@e[limit=0]', '@e[limit=3]', '@e[sort=random]',
'@e[sort=furthest]', '@e[sort=arbitrary]', '@e[type=player]', '@a[type=player]', '@e[distance=..5,limit=1]', '@e[ ]',
'@e[ type = pig ]', '@e[type=pig , limit=2]', '@e[type=pig,]', '@e[,]', '@a[ name = "x" ]',
'@a[scores={}]', '@a[advancements={}]', '@e[nbt={}]', '@e[nbt={a:1,b:[1,2]}]',
'@e[x=1,x=2]', '@e[limit=1,limit=2]', '@s[type=pig]', '@e[type=pig,type=cow]', '@e[type=!pig,type=!cow]',
'@e[distance=..5,distance=1..]', '@e[sort=nearest,sort=random]', '@e[gamemode=survival,gamemode=creative]',
]
BAD_SELECTORS = [
'@x', '@', '@E', '@e[', '@e[]', '@e[distance=-1]', '@e[distance=..-1]', '@e[unknown=1]', '@e[limit=a]', '@e[limit=-1]',
'@e[type=pig', '@e[type=minecraft:nope]', '@e[type=nope]', '@e[type=#nope]', '@e[sort=bad]', '@e[gamemode=bad]',
'@e[nbt={]', '@e[nbt=]', '@e[scores={a=}]', '@e[scores={a=x}]', '@e[scores={a}]', '@e[scores={a=1', '@e[scores=1]',
'@e[advancements={a=}]', '@e[advancements={nope=true}]', '@e[advancements={minecraft:story/root=maybe}]',
'@e[level=a]', '@e[level=-1..]', '@e[x=]', '@e[x=a]', '@e[dx=a]', '@e[x_rotation=a]', '@e[name=]', '@e[name="x]',
'@e[team]', '@e[tag]', '@e[limit]', '@e[=1]', '@e[a=1]', '@e[type=pig,]x', '@e[type=pig]x', '@e [type=pig]',
'@e[predicate=]', '@e[predicate=minecraft:]', '@e[predicate=Bad]', '@e[type=Bad]', '@e[gamemode=]', '@e[sort=]',
'@e[distance=..]', '@e[distance=1..a]', '@e[level=..]', '@e[nbt={a:}]', '@e[nbt=1]', '@a[limit=0]',
'@e[nbt={a:1}', '@e[type=pig,type=!pig]', '@e[type=!pig,type=pig]', '@p[type=zombie]', '@a[type=zombie]', '@r[type=!player]',
'@e[scores={kills=1..}', '@e[tag=a b]', '"Bob', '@e[type="pig"]', '@e[type=\'pig\']', '@s[', '@s]', '@e{}',
'Bad Name', 'x'.ljust(17, 'y'), '\u00e9', '00000000-0000-0000-0000-00000000000g', '00000000-0000-0000-0000-00000000000',
]
COMPONENTS = [
'"text"', '{"text":"hi"}', '[{"text":"a"},"b"]', '{"translate":"chat.type.text","with":["a","b"]}',
'{"text":"x","color":"red","bold":true}', 'true', '12', '1.5', '{"selector":"@a"}', '{"selector":"@a","separator":", "}',
'{"score":{"name":"@s","objective":"kills"}}', '{"nbt":"foo","entity":"@s"}', '{"nbt":"foo","block":"0 0 0"}',
'{"nbt":"foo","storage":"a:b","interpret":true}', '{"keybind":"key.jump"}', "'single'", '{text:"snbt"}', '{text:"a",extra:["b",{text:"c"}]}',
'{"text":"x","hover_event":{"action":"show_text","value":"y"}}', '{"text":"x","click_event":{"action":"open_url","url":"https://a.b"}}',
'{"text":"x","click_event":{"action":"run_command","command":"/help"}}', '{"text":"x","font":"minecraft:uniform"}',
'{"text":"x","color":"#ff00ff"}', '{"text":"x","shadow_color":-1}', '{"text":"x","insertion":"y"}', '[]', '[1,2]', '""', '{}',
'{"type":"text","text":"x"}', '{"type":"translatable","translate":"x"}', '{"translate":"x","fallback":"y"}',
'{"object":"atlas","sprite":"item/porkchop"}', '{"object":"player","player":{"name":"Notch"}}',
'{text:"x",color:red}', '"a\\nb"', '{"text":"a","italic":false,"underlined":true,"strikethrough":false,"obfuscated":false}',
]
BAD_COMPONENTS = [
'{"text":', '{"text":"x",}', '{"color":"nope","text":"x"}', '{"translate":}', '[', '{"text":"x","extra":5}', '{"unknown":1}',
'{"text":"x"} y', '"unterminated', "{'a':1}", '{"text":1,"color":}', '{"selector":"@x"}', '{"nbt":"a"}',
'{"score":{"name":"@s"}}', '{"keybind":5}', '{"text":"x","click_event":{"action":"nope"}}', '{"text":"x","bold":"maybe"}',
'{"translate":"x","with":5}', '{"text":"x","color":"#gggggg"}', '{"text":"x","hover_event":{"action":"show_text"}}', 'nope',
'{"text":"x","font":"Bad Font"}', '{"nbt":"a","entity":"@x"}', '{"type":"nope"}', '[{"text":"a"},', '{"text":"a"', '}',
]
NBT_COMPOUNDS = [
'{}', '{a:1}', '{a:1b,b:"x",c:[1,2,3]}', '{a:{b:{c:1}}}', '{"quoted key":1}', "{'single':1}", '{a:[I;1,2,3]}', '{a:[B;1b,2b]}',
'{a:[L;1L,2L]}', '{a:1.5f,b:2d,c:3L,d:4s}', '{a:1,}', '{ a : 1 }', '{a:true,b:false}', '{a:1.5e3}', '{a:0x10}', '{a:0b101}',
'{a:-1b}', '{a:+1}', '{a:"\\n"}', '{a:[]}', '{a:[{}]}', '{a:[[1],[2]]}', '{a:1_000}', '{a:bare}', '{a:.5}', '{a:5.}',
'{a:1,a:2}', '{a:[I;]}', '{a:[B;]}', '{a:1f}', '{a:1F}', '{a:1D}', '{a:NaN}', '{a:Infinity}', '{a:"\\u00e9"}',
]
BAD_NBT_COMPOUNDS = [
'{', '{a:}', '{a:1', '{a 1}', '{a:[I;1b]}', '{a:[1,"x"]}', '{a:1,,}', '{,}', '{:1}', '{a:[B;1]}', '[]', '1', '"x"',
'{a:"unterminated}', '{a:[}', '{a:1b2}', '{a:300b}', '{a:99999999999}', '{a:[I;1.5]}', '{a:1 b:2}', '{a:{}', '{a:1}x',
'{"":1}', '{a:\\}', '{a:"\\x"}', '{a:0x}', '{a:1.2.3}', '{a:--1}',
]
NBT_TAGS = ['1', '1b', '"str"', '[1,2]', '{a:1}', 'true', '1.5', '[B;1b]', '1s', '1L', '1.5f', '2d', "'x'", 'bare', '[]', '[I;1]', '0', '-1']
BAD_NBT_TAGS = ['', '[', '{', '"x', '[1,"a"]', '1b2', '[B;1', '1.5.5', '[I;1b]', '1,', '{a}', ']']
NBT_PATHS = [
'foo', 'foo.bar', 'foo[0]', 'foo[]', 'foo[{a:1}]', '{a:1}', 'foo{a:1}', '"quoted key".x', 'a.b[2].c', '[0]', 'foo[-1]', 'a[0][1]',
'a[0].b', 'a{b:1}.c', '"a b"', "'a b'", 'a.b.c.d', '{}', 'a[{}]', 'a[ 0 ]', 'a.', 'Items[{Slot:0b}].id', 'a[{b:{c:1}}]',
'_x', 'A1', '1a', 'a-b', 'a:b', 'a/b', 'a+b', '\u00e9',
]
BAD_NBT_PATHS = ['.', 'foo.', 'foo[', 'foo[a]', 'foo..bar', '{a:', 'foo[{a:1}', '[]foo', 'foo[0', 'foo]', 'foo[1.5]', 'foo[-]', '"foo', 'foo."bar', 'a{', '{a:1}{b:2}', 'a.{b:1}', '[{a:1}]x']
BLOCK_POS = ['0 64 0', '~ ~ ~', '~1 ~-2 ~3', '^ ^ ^1', '1 2 3', '~.5 ~ ~', '-1 -2 -3', '1.5 2 3', '~1.5 ~ ~', '^1.5 ^ ^', '0 0 0', '+1 +2 +3', '.5 1 1', '1e2 2 3']
BAD_BLOCK_POS = ['0 64', '~ ~', '^ ^ 1', '~1 ^2 3', 'a b c', '1 2', '~ a ~', '^ ~ ^', '1 2 ^', '99999999999 0 0', '~a ~ ~', '~ ~ ~x', '^1 ^2', '~-', '- 0 0']
VEC3 = ['0 64 0', '~ ~ ~', '1.5 2.5 -3.5', '^1 ^ ^-2', '.5 .5 .5', '1 2 3', '~0.5 ~ ~', '-0 0 0', '1e3 0 0', '+1 0 0', '1.5e-3 0 0']
BAD_VEC3 = ['1 2', '^ ~ ~', '~a ~ ~', '1.5 2', 'a b c', '~ ~', 'NaN 0 0', '1 2 ^', '0 0 0x', '1.2.3 0 0', '~- 0 0']
VEC2 = ['0 0', '~ ~', '1.5 -2', '~1 ~-1', '1 2']
BAD_VEC2 = ['1', '~ a', '^ ^', '1 ^', 'a b', '~ ~ ~']
COLUMN_POS = ['0 0', '~ ~', '~3 ~-4', '1 2', '-5 7']
BAD_COLUMN_POS = ['0', '~ ^', 'a b', '1.5 2', '^ ^', '0 0 0']
ROTATION = ['0 0', '~ ~', '90 -45', '~10 ~-5', '1.5 2.5', '-180 180', '^ ^']
BAD_ROTATION = ['^ ^', 'a b', '0', '~ a', '1 2 3']
INT_RANGES = ['1', '1..5', '..5', '1..', '0..0', '-5..-1', '-5..5', '5..5', '+1', '1..+5', '0']
BAD_INT_RANGES = ['..', '1...5', 'a', '5..1', '1..a', '1.5', '1..5..6', '-', '..-', ' ', '99999999999', '1..99999999999']
FLOAT_RANGES = ['1', '1.5', '1..5', '..5.5', '0.1..', '-1.5..2.5', '.5', '5.', '1..1', '1.5..1.5', '..0', '0..']
BAD_FLOAT_RANGES = ['..', 'a', '1.5.5', '5..1', '1..a', '1...2', '1e5', '-', '..-', '2..1.5']
TIMES = ['1', '1d', '1s', '1t', '0.5d', '2.5s', '100', '1.5t', '0', '0d', '3600', '24000', '1e2']
BAD_TIMES = ['1x', 'abc', '-1', '1.5.5s', '1 s', 'd', '99999999999', '1e', '.d', '-1t', '0.5t', '2147483648']
RESOURCE_LOCATIONS = ['minecraft:stone', 'stone', 'foo:bar', 'a/b', 'foo:bar/baz', 'foo.bar:a-b_c', 'a_b', '.', 'minecraft:']
BAD_RESOURCE_LOCATIONS = ['Stone', 'foo:Bar', 'a b', ':x', 'minecraft::x', 'a:b:c', 'foo:bar$', '\u00e9', '@a', '#a']
ITEM_STACKS = [
'minecraft:stone', 'stone', 'minecraft:diamond_sword[damage=5]', 'minecraft:stone[]', 'minecraft:stone[minecraft:custom_name="x"]',
'minecraft:stone[!damage]', 'minecraft:diamond_sword[damage=5,max_damage=10]', 'minecraft:stone[count=1]', 'minecraft:stone[ ]',
'minecraft:stone[custom_name={"text":"x"}]', 'minecraft:stone[lore=["a","b"]]', 'minecraft:stone[enchantments={"minecraft:sharpness":1}]',
'minecraft:stone[custom_data={a:1}]', 'minecraft:stone[unbreakable={}]', 'minecraft:stone[max_stack_size=1]', 'minecraft:stone[rarity=epic]',
'minecraft:stone[!damage,!max_damage]', 'minecraft:stone[damage=5,!max_damage]', 'minecraft:player_head[profile="Notch"]', 'minecraft:stone[ damage = 5 ]',
'minecraft:stone[repair_cost=0]', 'minecraft:stone[item_name="x"]', 'minecraft:stone[tooltip_display={hide_tooltip:true}]',
]
BAD_ITEM_STACKS = [
'minecraft:nope', 'nope', 'minecraft:stone[', 'minecraft:stone[damage]', 'minecraft:stone[damage=x]', 'minecraft:stone[nope=1]',
'minecraft:stone[damage=5,damage=6]', 'minecraft:stone{a:1}', 'minecraft:stone[!nope]', 'minecraft:stone[damage=5', 'minecraft:stone[damage=5,]',
'minecraft:stone[=5]', 'minecraft:stone[!]', 'minecraft:stone[!damage=5]', 'minecraft:stone]', 'Minecraft:stone', 'minecraft:stone[damage=-5]',
'minecraft:stone[damage=5,!damage]', 'minecraft:stone[max_stack_size=0]', 'minecraft:stone[max_stack_size=100]', 'minecraft:stone[rarity=nope]',
'minecraft:stone[custom_name={"text":}]', 'minecraft:stone[enchantments=1]', '#minecraft:logs', '*', 'minecraft:stone[unknown:thing=1]',
]
ITEM_PREDICATES = [
'minecraft:stone', 'stone', '*', '#minecraft:planks', '#planks', 'minecraft:stone[damage=5]', 'minecraft:stone[!damage]', 'stone[count=1]',
'stone[count~1]', 'stone[damage|max_damage=5]', 'stone[damage~5]', 'stone[count={min:1}]', 'stone[custom_data~{a:1}]', '*[damage=5]',
'#minecraft:planks[damage=5]', 'stone[enchantments~[{enchantments:"minecraft:sharpness"}]]', 'stone[enchantments~[{levels:{min:1}}]]',
'stone[damage|count=1]', 'stone[count=1|damage=2]', 'stone[(count=1|damage=2),!max_damage]', 'stone[damage={durability:5}]',
]
BAD_ITEM_PREDICATES = [
'minecraft:nope', '#nope', '#', 'stone[', 'stone[damage=x]', 'stone[nope=1]', 'stone[nope~1]', 'stone[count~]', 'stone[!nope]', 'stone[damage|]',
'stone[|damage]', 'stone[damage||count]', '*[', '*x', 'stone[damage=5,damage=6]', 'stone[damage=1 count=2]', 'stone[count=1,]', 'stone[ ]x',
'stone[count~a]', 'stone[(damage=1]', 'stone[damage=1)]',
]
BLOCK_STATES = [
'minecraft:stone', 'stone', 'oak_stairs[facing=north]', 'oak_stairs[facing=north,half=top]', 'minecraft:chest{Items:[]}', 'stone{}', 'oak_stairs[]',
'oak_stairs[ ]', 'oak_stairs[ facing = north ]', 'minecraft:chest[facing=west]{Items:[]}', 'oak_stairs[waterlogged=true,shape=straight]',
'minecraft:oak_stairs[half=bottom,facing=south,shape=inner_left,waterlogged=false]', 'redstone_wire[north=side]', 'sculk_sensor[power=15]', 'cake[bites=0]',
]
BAD_BLOCK_STATES = [
'minecraft:nope', 'oak_stairs[', 'oak_stairs[facing=up]', 'oak_stairs[nope=1]', 'oak_stairs[facing]', 'oak_stairs[facing=north,facing=south]', 'oak_stairs[facing=]',
'oak_stairs[=north]', 'oak_stairs[facing=north', 'oak_stairs[facing=north,]', 'oak_stairs[facing=north]x', 'oak_stairs{', 'stone[a=b]', 'oak_stairs[facing=north]{}x',
'oak_stairs]', '#minecraft:logs', 'oak_stairs[facing=North]', 'cake[bites=99]', 'minecraft:chest{', 'Minecraft:stone', 'stone{a:}',
]
BLOCK_PREDICATES = BLOCK_STATES + ['#minecraft:logs', '#minecraft:logs[axis=y]', '#logs', '#minecraft:logs{}', '#minecraft:logs[nope=1]']
BAD_BLOCK_PREDICATES = BAD_BLOCK_STATES[:-1] + ['#nope', '#', '#minecraft:logs[', '#minecraft:logs[axis=]', '#minecraft:logs[axis]', '#minecraft:logs[axis=y,axis=x]', '#minecraft:logs[axis=q]']
PARTICLES = [
'flame', 'minecraft:flame', 'minecraft:dust{color:[1.0,0.0,0.0],scale:1.0}', 'minecraft:dust{color:16711680,scale:1.0}', 'minecraft:block{block_state:"minecraft:stone"}',
'minecraft:block{block_state:{Name:"minecraft:stone"}}', 'minecraft:entity_effect{color:[1.0,0.0,0.0,1.0]}', 'minecraft:item{item:"minecraft:stick"}',
'minecraft:item{item:{id:"minecraft:stick",count:1}}', 'minecraft:sculk_charge{roll:0.5}', 'minecraft:shriek{delay:5}', 'minecraft:dragon_breath{power:1.0}',
'minecraft:trail{target:[0.0,0.0,0.0],color:16777215,duration:5}', 'minecraft:vibration{destination:{type:"block",pos:[0,0,0]},arrival_in_ticks:5}',
'minecraft:dust_color_transition{from_color:[1.0,0.0,0.0],to_color:[0.0,0.0,1.0],scale:1.0}', 'minecraft:flame{}',
]
BAD_PARTICLES = ['nope', 'minecraft:dust', 'minecraft:dust{', 'minecraft:flame{a:1}x', 'minecraft:block', 'minecraft:block{}', 'minecraft:dust{color:1}', 'Flame', 'minecraft:']
ITEM_SLOTS = [
'container.0', 'weapon.mainhand', 'weapon.offhand', 'armor.head', 'armor.chest', 'armor.legs', 'armor.feet', 'hotbar.3', 'enderchest.26', 'villager.0',
'horse.chest.4', 'player.cursor', 'contents', 'inventory.5', 'saddle', 'horse.armor', 'player.crafting.0', 'container.53', 'hotbar.8', 'weapon', 'armor.body',
]
BAD_ITEM_SLOTS = ['container.54', 'nope', 'container.a', 'armor.', 'hotbar.9', 'container.-1', 'container', 'container.0.0', '', 'weapon.', 'armor.nope', 'enderchest.27']
HEX_COLORS = ['ff0000', '#ff0000', '00ff00', 'FFFFFF', '000000', '#abc']
BAD_HEX_COLORS = ['ff00', 'gggggg', '##ff0000', '1234567', '#', '-1']
MESSAGES = ['hello', '@a hello @p', 'hi @e[type=pig] there', 'two spaces', '@s', 'a @r b @n c', 'x @e[', '@a[x=1]', '@a[limit=0] hi', 'hello world @', '@x hello', '@e[type=nope]']
BAD_MESSAGES = ['@e[', 'hello @x', '@e[type=nope] x']
OBJECTIVE_CRITERIA = ['dummy', 'trigger', 'health', 'minecraft.killed:minecraft.pig', 'minecraft.custom:minecraft.jump', 'teamkill.red', 'killedByTeam.blue',
'level', 'food', 'air', 'armor', 'xp', 'deathCount', 'playerKillCount', 'totalKillCount', 'minecraft.mined:minecraft.stone',
'minecraft.broken:minecraft.stone', 'minecraft.crafted:minecraft.stone', 'minecraft.used:minecraft.stone',
'minecraft.picked_up:minecraft.stone', 'minecraft.dropped:minecraft.stone', 'minecraft.killed_by:minecraft.pig', 'teamkill.', 'killedByTeam.blue']
BAD_OBJECTIVE_CRITERIA = ['bad', 'minecraft.killed:', 'minecraft.killed:minecraft.nope', 'minecraft.custom:nope', 'teamkill.nocolor', 'minecraft.nope:minecraft.pig', '', 'DUMMY', 'minecraft.killed']
OPERATIONS = ['=', '+=', '-=', '*=', '/=', '%=', '<', '>', '><']
BAD_OPERATIONS = ['==', '=+', 'x', '=-', '<>', '+', '<=']
SCOREBOARD_SLOTS = ['sidebar', 'list', 'below_name', 'sidebar.team.red', 'sidebar.team.light_purple', 'sidebar.team.blue']
BAD_SCOREBOARD_SLOTS = ['foo', 'sidebar.team', 'sidebar.team.nocolor', 'sidebar.', 'Sidebar', 'sidebar.team.']
SCORE_HOLDERS = ['Player', '@s', '@e[type=pig]', '*', '#total', '@a[tag=x]', 'fake', 'Steve', '@p', '@e[limit=1]', 'a b']
BAD_SCORE_HOLDERS = ['@x', '@e[', '@e[type=nope]', '@a[limit=-1]']
UUIDS = ['00000000-0000-0000-0000-000000000001', '123e4567-e89b-12d3-a456-426614174000', '1-2-3-4-5', 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF']
BAD_UUIDS = ['nope', '1234', '00000000-0000-0000-0000', 'g-2-3-4-5', '-', '00000000-0000-0000-0000-0000000000000000000']
SWIZZLES = ['x', 'xy', 'xyz', 'zx', 'yz', 'zyx']
BAD_SWIZZLES = ['xx', 'a', 'xyzx', 'xa', 'X', '']
STYLES = ['{"color":"red"}', '{"bold":true,"italic":false}', '{}', '{color:red}', '{"color":"#ff0000"}', '{"font":"minecraft:uniform"}', '{"underlined":true,"strikethrough":true,"obfuscated":true}']
BAD_STYLES = ['{"color":"x"}', 'red', '{', '"x"', '{"bold":"x"}', '{"color":}', '[]', '{"text":"x"}']
CONTEXT_INTS = ['1', '5', '0', '-1', '{type:"minecraft:uniform",min_inclusive:1,max_inclusive:5}', '{type:"minecraft:constant",value:3}', '{"type":"minecraft:uniform","min":1,"max":5}',
'{type:"minecraft:binomial",n:5,p:0.5}', '{min:1,max:5}', '[1,2]', '"x"']
BAD_CONTEXT_INTS = ['{', 'x', '{type:"minecraft:nope"}', '{type:"minecraft:uniform"}', '1.5', '{min:5}', '[1', '']
CONTEXT_FLOATS = ['1', '1.5', '0', '-1.5', '{type:"minecraft:uniform",min_inclusive:1,max_inclusive:5}', '{type:"minecraft:constant",value:3}', '{min:1,max:5}']
BAD_CONTEXT_FLOATS = ['{', 'x', '{type:"minecraft:nope"}', '{min:5}', '']
SLOT_SOURCES = ['container.0', 'weapon.mainhand', '{type:"minecraft:slot_range",slots:"container.*"}', '{source:"minecraft:this"}', 'armor.*', 'hotbar.*', 'container.*']
BAD_SLOT_SOURCES = ['{', 'nope', '{type:"minecraft:nope"}', 'container.', '']
ENTITY_ANCHORS = ['feet', 'eyes']
BAD_ENTITY_ANCHORS = ['head', 'Eyes', '']
HEIGHTMAPS = ['world_surface', 'motion_blocking', 'motion_blocking_no_leaves', 'ocean_floor']
BAD_HEIGHTMAPS = ['x', 'surface', 'WORLD_SURFACE']
GAMEMODES = ['survival', 'creative', 'adventure', 'spectator']
BAD_GAMEMODES = ['x', 'Survival', '0', 's', 'survival ']
MIRRORS = ['none', 'left_right', 'front_back']
BAD_MIRRORS = ['x', 'both', 'LEFT_RIGHT']
ROTATIONS = ['none', 'clockwise_90', '180', 'counterclockwise_90']
BAD_ROTATIONS = ['90', 'x', 'clockwise']
SWINGS = ['mainhand', 'offhand']
BAD_SWINGS = ['x', 'main_hand', '']
TEAM_COLORS = ['red', 'blue', 'reset', 'white', 'light_purple', 'dark_aqua', 'black']
BAD_TEAM_COLORS = ['nope', 'Red', 'bold', 'italic']
DIMENSIONS = ['minecraft:overworld', 'overworld', 'the_nether', 'minecraft:the_end']
BAD_DIMENSIONS = ['minecraft:nope', 'nope', 'Bad']
FUNCTIONS = ['foo:bar', '#foo:bar', 'minecraft:x/y', 'foo']
BAD_FUNCTIONS = ['#', 'Foo:bar', '#Foo:bar', 'foo:']
GAME_PROFILES = ['Player', '@a', '@p', 'Steve', '00000000-0000-0000-0000-000000000001', '@s', 'Alex', 'unknown_name']
BAD_GAME_PROFILES = ['@x', '@e[', '@a[limit=-1]']
DIALOGS = ['{type:"minecraft:notice",title:"x"}', 'minecraft:server_links', 'foo:bar']
BAD_DIALOGS = ['{', '{type:"minecraft:nope"}', 'Bad']
BOOLS = ['true', 'false']
BAD_BOOLS = ['maybe', 'TRUE', '1', 'tru', 'True', 'truee']
def sha(text):
return int(hashlib.sha1(text.encode()).hexdigest()[:8], 16)
def int_samples(props):
lo = props.get('min', -2147483648) if props else -2147483648
hi = props.get('max', 2147483647) if props else 2147483647
cands = [v for v in (0, 1, 5, 10, 100, 1000, -1, -10) if lo <= v <= hi]
if not cands:
cands = [lo]
bad = ['abc', '1.5', '99999999999', '-99999999999', '1e3', '-', '+', '--1', '0x10', '1 ', '2147483648', '-2147483649']
if lo > -2147483648:
bad.append(str(lo - 1))
if hi < 2147483647:
bad.append(str(hi + 1))
return [str(c) for c in cands], bad
def double_samples(props, long_like=False):
lo = props.get('min', -1e308) if props else -1e308
hi = props.get('max', 1e308) if props else 1e308
cands = [v for v in ('0', '1', '1.5', '-2.25', '10', '0.5', '100', '.5', '5.') if lo <= float(v) <= hi]
if not cands:
cands = [str(lo)]
bad = ['abc', '1.2.3', 'NaN', '1e', '-', '--1', '1,5', '+', '.', 'infinity']
if lo > -1e308:
bad.append(repr(lo - 1))
if hi < 1e308:
bad.append(repr(hi + 1))
return cands, bad
def registry_samples(registries, registry, allow_tag, allow_inline=False):
entry = registries.get('by_registry', {}).get(registry, {'ids': [], 'tags': []})
ids = entry['ids']
valid = []
if ids:
valid += [ids[0], ids[len(ids) // 2], ids[-1].split(':', 1)[-1] if ids[-1].startswith('minecraft:') else ids[-1]]
else:
valid += ['minecraft:thing']
if allow_tag and entry['tags']:
valid.append('#' + entry['tags'][0])
bad = ['minecraft:nonexistent_thing', 'Bad Id', 'minecraft:']
if allow_tag:
bad += ['#minecraft:nonexistent_tag', '#']
return valid, bad
def pools(parser, props, registries):
"""(valid samples, bad samples) for one argument node."""
props = props or {}
if parser == 'brigadier:bool':
return BOOLS, BAD_BOOLS
if parser == 'brigadier:integer' or parser == 'brigadier:long':
return int_samples(props)
if parser in ('brigadier:double', 'brigadier:float'):
return double_samples(props)
if parser == 'brigadier:string':
kind = props.get('type', 'word')
if kind == 'greedy':
return ['hello world', 'a', '@a x', '"q" r', ''], []
if kind == 'phrase':
return ['word', '"quoted phrase"', '"esc\\"aped"', '"a\\\\b"', "'single'"], ['"unterminated', '"bad\\escape"', '"x\\']
return ['word', 'a.b-c_d+e', 'a1'], []
if parser == 'minecraft:block_pos':
return BLOCK_POS, BAD_BLOCK_POS
if parser == 'minecraft:vec3':
return VEC3, BAD_VEC3
if parser == 'minecraft:vec2':
return VEC2, BAD_VEC2
if parser == 'minecraft:column_pos':
return COLUMN_POS, BAD_COLUMN_POS
if parser == 'minecraft:rotation':
return ROTATION, BAD_ROTATION
if parser == 'minecraft:entity':
return SELECTORS, BAD_SELECTORS
if parser == 'minecraft:score_holder':
return SCORE_HOLDERS, BAD_SCORE_HOLDERS
if parser == 'minecraft:game_profile':
return GAME_PROFILES, BAD_GAME_PROFILES
if parser == 'minecraft:uuid':
return UUIDS, BAD_UUIDS
if parser == 'minecraft:message':
return MESSAGES, BAD_MESSAGES
if parser == 'minecraft:component':
return COMPONENTS, BAD_COMPONENTS
if parser == 'minecraft:style':
return STYLES, BAD_STYLES
if parser == 'minecraft:nbt_compound_tag':
return NBT_COMPOUNDS, BAD_NBT_COMPOUNDS
if parser == 'minecraft:nbt_tag':
return NBT_TAGS, BAD_NBT_TAGS
if parser == 'minecraft:nbt_path':
return NBT_PATHS, BAD_NBT_PATHS
if parser == 'minecraft:objective':
return ['kills', 'obj', 'health', 'x'], []
if parser == 'minecraft:objective_criteria':
return OBJECTIVE_CRITERIA, BAD_OBJECTIVE_CRITERIA
if parser == 'minecraft:operation':
return OPERATIONS, BAD_OPERATIONS
if parser == 'minecraft:scoreboard_slot':
return SCOREBOARD_SLOTS, BAD_SCOREBOARD_SLOTS
if parser == 'minecraft:team':
return ['red', 'blue', 'x'], []
if parser == 'minecraft:team_color':
return TEAM_COLORS, BAD_TEAM_COLORS
if parser == 'minecraft:hex_color':
return HEX_COLORS, BAD_HEX_COLORS
if parser == 'minecraft:int_range':
return INT_RANGES, BAD_INT_RANGES
if parser == 'minecraft:float_range':
return FLOAT_RANGES, BAD_FLOAT_RANGES
if parser == 'minecraft:time':
return TIMES, BAD_TIMES
if parser == 'minecraft:resource_location':
return RESOURCE_LOCATIONS, BAD_RESOURCE_LOCATIONS
if parser in ('minecraft:resource', 'minecraft:resource_key'):
return registry_samples(registries, props.get('registry', ''), False)
if parser in ('minecraft:resource_or_tag', 'minecraft:resource_or_tag_key'):
return registry_samples(registries, props.get('registry', ''), True)
if parser == 'minecraft:resource_selector':
valid, bad = registry_samples(registries, props.get('registry', ''), True)
return valid + ['*', 'minecraft:*', '#minecraft:*'], bad
if parser == 'minecraft:dimension':
return DIMENSIONS, BAD_DIMENSIONS
if parser == 'minecraft:function':
return FUNCTIONS, BAD_FUNCTIONS
if parser == 'minecraft:item_stack':
return ITEM_STACKS, BAD_ITEM_STACKS
if parser == 'minecraft:item_predicate':
return ITEM_PREDICATES, BAD_ITEM_PREDICATES
if parser == 'minecraft:block_state':
return BLOCK_STATES, BAD_BLOCK_STATES
if parser == 'minecraft:block_predicate':
return BLOCK_PREDICATES, BAD_BLOCK_PREDICATES
if parser == 'minecraft:particle':
return PARTICLES, BAD_PARTICLES
if parser == 'minecraft:item_slot':
return ITEM_SLOTS, BAD_ITEM_SLOTS
if parser == 'minecraft:slot_source':
return SLOT_SOURCES, BAD_SLOT_SOURCES
if parser == 'minecraft:swizzle':
return SWIZZLES, BAD_SWIZZLES
if parser == 'minecraft:entity_anchor':
return ENTITY_ANCHORS, BAD_ENTITY_ANCHORS
if parser == 'minecraft:heightmap':
return HEIGHTMAPS, BAD_HEIGHTMAPS
if parser == 'minecraft:gamemode':
return GAMEMODES, BAD_GAMEMODES
if parser == 'minecraft:template_mirror':
return MIRRORS, BAD_MIRRORS
if parser == 'minecraft:template_rotation':
return ROTATIONS, BAD_ROTATIONS
if parser == 'minecraft:swing_animation':
return SWINGS, BAD_SWINGS
if parser == 'minecraft:context_int_provider':
return CONTEXT_INTS, BAD_CONTEXT_INTS
if parser == 'minecraft:context_float_provider':
return CONTEXT_FLOATS, BAD_CONTEXT_FLOATS
if parser == 'minecraft:dialog':
return DIALOGS, BAD_DIALOGS
if parser in ('minecraft:loot_table', 'minecraft:loot_modifier', 'minecraft:loot_predicate'):
registry = {'minecraft:loot_table': 'minecraft:loot_table', 'minecraft:loot_modifier': 'minecraft:item_modifier', 'minecraft:loot_predicate': 'minecraft:predicate'}[parser]
valid, bad = registry_samples(registries, registry, False)
return valid + ['{}', '{type:"minecraft:chest",pools:[]}', '{"function":"minecraft:set_count","count":1}'], bad + ['{', '{"function":"nope"}']
if parser == 'minecraft:feature':
return registry_samples(registries, 'minecraft:worldgen/configured_feature', False)
return ['0'], ['@@bad@@']
def resolve(tree, path):
node = tree
for name in path:
node = node['children'][name]
return node
SKIP_ROOTS = {'test', 'jfr', 'perf', 'debug'}
def walk(tree, registries, limit_per_root=0):
"""Yield command token lists: (tokens, kinds) where kinds[i] is None for literals or (valid, bad) pools."""
out = []
def rec(node, tokens, kinds, redirects, counter):
if node.get('executable') and tokens:
out.append((list(tokens), list(kinds)))
children = node.get('children', {})
redirect = node.get('redirect')
if redirect is not None and redirects < 1:
target = resolve(tree, redirect)
rec(target, tokens, kinds, redirects + 1, counter)
for name, child in children.items():
if len(tokens) == 0 and name in SKIP_ROOTS:
continue
if child['type'] == 'literal':
tokens.append(name)
kinds.append(None)
else:
valid, bad = pools(child['parser'], child.get('properties'), registries)
pick = valid[0]
tokens.append(pick)
kinds.append((valid, bad, child['parser'], name))
rec(child, tokens, kinds, redirects, counter)
tokens.pop()
kinds.pop()
rec(tree, [], [], 0, [0])
return out
def corpus(tree, registries):
seen = {}
def add(line):
if line not in seen:
seen[line] = True
paths = walk(tree, registries)
budget = {}
def spend(key, limit=2):
used = budget.get(key, 0)
if used >= limit:
return False
budget[key] = used + 1
return True
for tokens, kinds in paths:
add(' '.join(tokens))
for tokens, kinds in paths:
n = len(tokens)
for i in range(1, n + 1):
add(' '.join(tokens[:i]))
add(' '.join(tokens[:i]) + ' ')
for i, kind in enumerate(kinds):
if kind is None:
continue
valid, bad, parser, name = kind
head = ' '.join(tokens[:i])
head = head + ' ' if head else head
for v in valid:
if spend((parser, v, 'v')):
add(head + v)
add(head + v + ' ')
for b in bad:
if spend((parser, b, 'b')):
add(head + b)
add(head + b + ' x')
value = tokens[i]
if spend((parser, value, 'cut')):
for cut in range(1, min(len(value), 6)):
add(head + value[:cut])
if spend((tokens[0], 'extra'), 3):
add(' '.join(tokens) + ' extra')
add(' '.join(tokens) + ' ')
for line in EXTRA:
add(line)
for line in [l for l in seen]:
pass
return list(seen)
EXTRA = [
'', ' ', 'nope', 'Help', '/help', 'help ', 'he', 'h', 'g', 'give', 'give ', 'give @s', 'give @s minecraft:stone 0', 'give @s minecraft:stone 100000',
'tp 1 2 3', 'tp @s 1 2 3', 'tp @s @a', 'tp @e[type=pig] ~ ~ ~', 'tp @s 1 2 3 90 0', 'tp @s ~ ~ ~ facing 0 0 0', 'tp @s ~ ~ ~ facing entity @a eyes',
'teleport @s ~ ~ ~ facing entity @p feet', 'execute as @a at @s run say hi', 'execute if entity @s run say x', 'execute store result score @s kills run say x',
'execute positioned ~ ~ ~ rotated ~ ~ run say x', 'execute run', 'execute', 'execute as', 'execute as @a', 'execute foo',
'execute if score @s kills matches 1..5 run say x', 'execute if block ~ ~ ~ minecraft:stone run say x', 'execute unless dimension minecraft:overworld run say',
'execute if data entity @s {a:1} run say x', 'execute if predicate minecraft:foo run say x', 'execute summon minecraft:pig run say x',
'execute on vehicle run say x', 'execute on passengers run say x', 'execute on origin run say x', 'execute on nope run say x',
'execute align xyz run say x', 'execute align xx run say x', 'execute align q run say x', 'execute anchored eyes run say x',
'execute in minecraft:the_nether run say x', 'execute in nope run say x', 'execute facing 1 2 3 run say x', 'execute rotated as @s run say x',
'execute positioned over world_surface run say x', 'execute positioned as @s run say x', 'execute store success storage a:b c int 1.0 run say x',
'execute store result bossbar a:b value run say x', 'execute store result entity @s Health float 1 run say x',
'execute store result block 0 0 0 a byte 2 run say x', 'execute if biome ~ ~ ~ minecraft:plains run say x', 'execute if loaded ~ ~ ~ run say x',
'execute if items entity @s weapon.mainhand minecraft:stone run say x', 'execute if function foo:bar run say x', 'execute if stopwatch foo:bar 1.. run say x',
'execute if blocks 0 0 0 1 1 1 2 2 2 all run say x', 'execute if blocks 0 0 0 1 1 1 2 2 2 masked run say x', 'execute if blocks 0 0 0 1 1 1 2 2 2 nope run say x',
'scoreboard objectives add a dummy', 'scoreboard objectives add a dummy "Disp"', 'scoreboard objectives add a dummy {"text":"x"}', 'scoreboard objectives add bad!name dummy',
'scoreboard objectives add a nope', 'scoreboard players set @s kills 1', 'scoreboard players set @s kills a', 'scoreboard players add Player kills -5',
'scoreboard players operation @s kills += @a health', 'scoreboard players operation @s kills >< @a health', 'scoreboard objectives setdisplay sidebar kills',
'scoreboard objectives modify kills numberformat fixed {"text":"x"}', 'scoreboard objectives modify kills numberformat styled {"color":"red"}',
'scoreboard objectives modify kills numberformat blank', 'scoreboard objectives modify kills rendertype hearts', 'scoreboard objectives modify kills displayautoupdate true',
'scoreboard players display name @s kills "x"', 'scoreboard players display numberformat @s kills fixed {"text":"x"}', 'scoreboard players enable @s kills',
'scoreboard players get @s kills', 'scoreboard players list', 'scoreboard players list @s', 'scoreboard players reset *', 'scoreboard players reset @s kills',
'team add red', 'team add red "Display"', 'team modify red color red', 'team modify red friendlyFire true', 'team modify red prefix {"text":"p"}',
'team modify red nametagVisibility never', 'team modify red collisionRule pushOtherTeams', 'team modify red deathMessageVisibility hideForOtherTeams',
'team modify red seeFriendlyInvisibles false', 'team join red @a', 'team join red', 'team leave @a', 'team empty red', 'team remove red', 'team list', 'team list red',
'data get entity @s', 'data get entity @s Health', 'data get entity @s Health 2', 'data get block 0 0 0 Items[0]', 'data get storage a:b x', 'data merge entity @s {a:1}',
'data merge block 0 0 0 {a:1}', 'data merge storage a:b {a:1}', 'data modify entity @s a set value 1', 'data modify storage a:b x append value 1',
'data modify storage a:b x prepend from entity @s Pos', 'data modify storage a:b x insert 0 value 1', 'data modify storage a:b x merge value {a:1}',
'data modify storage a:b x set string entity @s CustomName 1 2', 'data modify storage a:b x set string entity @s CustomName', 'data modify storage a:b x set from storage a:c y',
'data remove entity @s a', 'data remove storage a:b x.y[0]', 'data get entity @s a 1.5', 'data modify storage a:b x nope value 1',
'fill 0 0 0 1 1 1 minecraft:stone', 'fill 0 0 0 1 1 1 stone replace dirt', 'fill 0 0 0 1 1 1 stone outline', 'fill 0 0 0 1 1 1 stone hollow', 'fill 0 0 0 1 1 1 stone destroy',
'fill 0 0 0 1 1 1 stone keep', 'fill 0 0 0 1 1 1 stone replace', 'fill 0 0 0 1 1 1 stone replace #logs[axis=y]', 'fill 0 0 0 1 1 1 stone nope',
'fillbiome 0 0 0 1 1 1 minecraft:plains', 'fillbiome 0 0 0 1 1 1 minecraft:plains replace #minecraft:is_ocean', 'clone 0 0 0 1 1 1 2 2 2', 'clone 0 0 0 1 1 1 2 2 2 replace move',
'clone 0 0 0 1 1 1 2 2 2 masked force', 'clone 0 0 0 1 1 1 2 2 2 filtered stone normal', 'clone from minecraft:overworld 0 0 0 1 1 1 to minecraft:the_nether 2 2 2',
'setblock 0 0 0 stone', 'setblock 0 0 0 stone destroy', 'setblock 0 0 0 stone keep', 'setblock 0 0 0 stone replace', 'setblock 0 0 0 stone strict', 'setblock ~ ~ ~ oak_stairs[facing=north]{a:1}',
'summon pig', 'summon pig ~ ~ ~', 'summon pig ~ ~ ~ {NoAI:1b}', 'summon minecraft:nope', 'summon pig ~ ~ ~ {', 'summon minecraft:player', 'summon item ~ ~ ~ {Item:{id:"minecraft:stone",count:1}}',
'kill', 'kill @e[type=pig]', 'kill Player', 'kill @', 'effect give @s minecraft:speed', 'effect give @s speed 10 1 true', 'effect give @s speed infinite', 'effect give @s speed 0', 'effect give @s speed 1000000 255',
'effect give @s speed 1000000 256', 'effect give @s nope', 'effect clear @s', 'effect clear @s speed', 'enchant @s sharpness', 'enchant @s minecraft:sharpness 2', 'enchant @s nope',
'experience add @s 5', 'experience add @s 5 levels', 'experience add @s 5 points', 'experience set @s 5 levels', 'experience query @s levels', 'experience query @s nope', 'xp add @s 1',
'gamemode creative', 'gamemode creative @s', 'gamemode nope', 'gamemode 1', 'defaultgamemode survival', 'difficulty hard', 'difficulty nope', 'difficulty 1',
'time set day', 'time set noon', 'time set 1000', 'time set 1d', 'time set 1s', 'time set nope', 'time add 1', 'time add 1d', 'time query daytime', 'time query gametime', 'time query day',
'time set minecraft:day', 'time of minecraft:overworld set 5', 'time query nope', 'weather clear', 'weather rain 10', 'weather thunder 5t', 'weather clear 1d', 'weather nope',
'say hello', 'say', 'say @a', 'say @e[', 'me waves', 'msg @a hello', 'tell @a hello', 'w @a hello', 'teammsg hello', 'tm hello', 'tellraw @a {"text":"x"}', 'tellraw @a "x"', 'tellraw @a',
'title @a title {"text":"x"}', 'title @a subtitle "x"', 'title @a actionbar "x"', 'title @a times 1 2 3', 'title @a times 1s 2s 3s', 'title @a clear', 'title @a reset', 'title @a title', 'title @a nope',
'list', 'list uuids', 'list nope', 'seed', 'locate structure minecraft:village_plains', 'locate structure #minecraft:village', 'locate biome minecraft:plains', 'locate biome #minecraft:is_ocean',
'locate poi minecraft:home', 'locate structure nope', 'spawnpoint', 'spawnpoint @s', 'spawnpoint @s 0 0 0', 'spawnpoint @s 0 0 0 90', 'spawnpoint @s ~ ~ ~ ~ ~', 'setworldspawn', 'setworldspawn 0 0 0',
'setworldspawn 0 0 0 90', 'setworldspawn 0 0 0 90 0', 'clear', 'clear @s', 'clear @s minecraft:stone', 'clear @s stone 0', 'clear @s stone 5', 'clear @s *', 'clear @s #logs', 'clear @s stone[damage=5] 0',
'gamerule', 'gamerule keepInventory', 'gamerule keep_inventory', 'gamerule keep_inventory true', 'gamerule minecraft:keep_inventory true', 'gamerule max_command_sequence_length 5', 'gamerule nope', 'gamerule keep_inventory 5',
'worldborder get', 'worldborder set 100', 'worldborder set 100 10', 'worldborder set 100 10s', 'worldborder add 10 5', 'worldborder center 0 0', 'worldborder damage amount 1', 'worldborder damage buffer 1',
'worldborder warning distance 5', 'worldborder warning time 5', 'worldborder set -1', 'worldborder set 1e10', 'worldborder nope',
'bossbar add a:b "x"', 'bossbar set a:b color red', 'bossbar set a:b style notched_6', 'bossbar set a:b value 5', 'bossbar set a:b max 5', 'bossbar set a:b visible true', 'bossbar set a:b players @a',
'bossbar set a:b name "x"', 'bossbar get a:b value', 'bossbar list', 'bossbar remove a:b', 'bossbar set a:b color nope',
'tag @s add x', 'tag @s remove x', 'tag @s list', 'tag @s add', 'tag @s add "quoted tag"', 'ride @s mount @e[limit=1]', 'ride @s dismount', 'ride @s mount', 'ride @s evict', 'ride @s nope',
'item replace entity @s weapon.mainhand with stone', 'item replace entity @s weapon.mainhand with stone 5', 'item replace block 0 0 0 container.0 with stone', 'item replace entity @s container.0 from entity @a weapon.mainhand',
'item replace entity @s container.0 from block 0 0 0 container.1 minecraft:foo', 'item modify entity @s weapon.mainhand minecraft:foo', 'item modify block 0 0 0 container.0 minecraft:foo',
'loot give @s loot minecraft:chests/simple_dungeon', 'loot give @s kill @e[limit=1]', 'loot give @s mine 0 0 0', 'loot give @s mine 0 0 0 mainhand', 'loot give @s fish minecraft:gameplay/fishing 0 0 0',
'loot give @s fish minecraft:gameplay/fishing 0 0 0 mainhand', 'loot spawn 0 0 0 loot minecraft:chests/simple_dungeon', 'loot insert 0 0 0 loot minecraft:chests/simple_dungeon', 'loot replace entity @s weapon.mainhand loot minecraft:chests/simple_dungeon',
'loot replace entity @s weapon.mainhand 2 loot minecraft:chests/simple_dungeon', 'loot replace block 0 0 0 container.0 loot minecraft:chests/simple_dungeon', 'loot give @s nope',
'particle flame', 'particle flame ~ ~ ~', 'particle flame ~ ~ ~ 1 1 1 0 10', 'particle flame ~ ~ ~ 1 1 1 0 10 force', 'particle flame ~ ~ ~ 1 1 1 0 10 normal @a', 'particle flame ~ ~ ~ 1 1 1 0 0 nope',
'playsound minecraft:entity.pig.ambient master @s', 'playsound minecraft:entity.pig.ambient master @s ~ ~ ~ 1 1 0', 'playsound entity.pig.ambient nope @s', 'stopsound @s', 'stopsound @s master', 'stopsound @s master minecraft:entity.pig.ambient',
'stopsound @s * minecraft:entity.pig.ambient', 'attribute @s minecraft:max_health get', 'attribute @s max_health base set 20', 'attribute @s max_health modifier add a:b 1 add_value', 'attribute @s max_health modifier add a:b 1 nope',
'attribute @s max_health modifier remove a:b', 'attribute @s max_health modifier value get a:b 2', 'attribute @s max_health base get 2', 'attribute @s nope get',
'damage @s 5', 'damage @s 5 minecraft:generic', 'damage @s 5 minecraft:generic by @a', 'damage @s 5 minecraft:generic by @a from @p', 'damage @s 5 minecraft:generic at 0 0 0', 'damage @s -5', 'damage @s 5 nope',
'rotate @s 0 0', 'rotate @s ~ ~', 'rotate @s facing 0 0 0', 'rotate @s facing entity @a', 'rotate @s facing entity @a eyes', 'swing @s', 'swing @s mainhand', 'swing @s offhand', 'swing @s nope',
'spreadplayers 0 0 5 10 false @a', 'spreadplayers 0 0 5 10 under 100 false @a', 'spreadplayers 0 0 5 10 true @a', 'spreadplayers 0 0 0 10 false @a', 'spreadplayers 0 0 5 5 false @a',
'forceload add 0 0', 'forceload add 0 0 16 16', 'forceload remove all', 'forceload remove 0 0', 'forceload query', 'forceload query 0 0', 'forceload nope', 'recipe give @s *', 'recipe give @s minecraft:stick', 'recipe take @s *',
'advancement grant @s everything', 'advancement grant @s only minecraft:story/root', 'advancement grant @s only minecraft:story/root criterion', 'advancement grant @s from minecraft:story/root', 'advancement grant @s through minecraft:story/root',
'advancement grant @s until minecraft:story/root', 'advancement revoke @s everything', 'advancement nope', 'function foo:bar', 'function #foo:bar', 'function foo:bar {a:1}', 'function foo:bar with entity @s a',
'function foo:bar with storage a:b c', 'function foo:bar with block 0 0 0 a', 'schedule function foo:bar 1t', 'schedule function foo:bar 1d append', 'schedule function foo:bar 1s replace', 'schedule clear foo:bar',
'schedule function #foo:bar 1t', 'schedule function foo:bar 0t', 'trigger kills', 'trigger kills add 5', 'trigger kills set 5', 'trigger kills nope', 'return 5', 'return fail', 'return run say x', 'return run return 1',
'random value 1..5', 'random value 1', 'random value 5..1', 'random value ..5', 'random roll 1..5', 'random roll 1..5 foo:bar', 'random reset *', 'random reset foo:bar 5', 'random reset foo:bar 5 true', 'random reset foo:bar 5 true true',
'random reset * 5 true true 7', 'tick query', 'tick rate 20', 'tick rate 20.5', 'tick rate 0.1', 'tick rate 10000', 'tick rate 1000000', 'tick freeze', 'tick unfreeze', 'tick step', 'tick step 5', 'tick step 5s', 'tick sprint 100', 'tick sprint stop', 'tick nope',
'reload', 'datapack list', 'datapack list enabled', 'datapack list available', 'datapack enable "vanilla"', 'datapack disable "vanilla"', 'datapack enable "x" first', 'datapack enable "x" last', 'datapack enable "x" before "y"', 'datapack enable "x" after "y"',
'place feature minecraft:oak', 'place feature minecraft:oak ~ ~ ~', 'place jigsaw minecraft:bastion/starts minecraft:bastion/bridge/start 5', 'place jigsaw a:b c:d 5 ~ ~ ~', 'place structure minecraft:village_plains', 'place structure minecraft:village_plains ~ ~ ~',
'place template minecraft:igloo/top', 'place template minecraft:igloo/top ~ ~ ~ clockwise_90 front_back 0.5 5', 'place template minecraft:igloo/top ~ ~ ~ nope', 'raid start 5', 'compute',
'stopwatch create foo:bar', 'stopwatch query foo:bar', 'stopwatch query foo:bar 1.5', 'stopwatch restart foo:bar', 'stopwatch remove foo:bar', 'spectate', 'spectate @e[limit=1]', 'spectate @e[limit=1] @s', 'spectate @e[limit=1] nope',
'waypoint list', 'waypoint modify @s color red', 'waypoint modify @s color hex ff0000', 'waypoint modify @s style default', 'waypoint modify @s style reset', 'waypoint modify @s color reset', 'waypoint modify @s style nope',
'dialog show @s foo:bar', 'dialog clear @s', 'dialog show @s {type:"minecraft:notice",title:"x"}', 'publish', 'publish true', 'publish true survival 25565', 'publish false creative', 'publish nope', 'unpublish',
'version', 'help execute', 'help execute run', 'help nope', 'help give', 'help tp', 'kick @s', 'kick @s "reason"', 'fetchprofile name Notch', 'fetchprofile id 00000000-0000-0000-0000-000000000001',
'posteffect @s minecraft:x', 'posteffect', 'ban Player', 'op Player', 'whitelist add Player', 'stop', 'save-all', 'debug start', 'debug stop', 'debug report', 'debug function foo:bar',
'time set 1', 'time set 1', ' time set 1', 'time\tset 1', 'say \u00e9\u00e9', 'say \U0001f600', 'tp \u00e9 1 2 3', 'give \U0001f600 stone', 'execute as @e[name="\u00e9"] run say \u00e9',
]
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Group the mismatches of tools/test_command_parse_parity.py by cause.
usage: command_parse_summary.py MISMATCHES.jsonl [ROOT]
"""
import collections
import json
import sys
from pathlib import Path
def describe(side, kind):
if kind == 'parse':
if side.get('ok'):
return 'OK'
return f"ERR {side.get('error')!r}@{'c' if side.get('cursor') else '0'}"
return f"SUGG[{len(side['list'])}]"
path = Path(sys.argv[1])
only = sys.argv[2] if len(sys.argv) > 2 else None
groups = collections.Counter()
examples = {}
for line in path.open(encoding='utf-8'):
m = json.loads(line)
root = m['in'].split(' ')[0]
if only and root != only:
continue
key = (m['kind'], describe(m['vanilla'], m['kind']), describe(m['rust'], m['kind']))
if m['kind'] == 'parse':
key = key[:1] + (key[1][:90], key[2][:90])
groups[key] += 1
examples.setdefault(key, m)
for key, count in sorted(groups.items(), key=lambda kv: -kv[1])[:int(sys.argv[3]) if len(sys.argv) > 3 else 40]:
ex = examples[key]
print(f'{count:6} {key[0]} vanilla={key[1]} rust={key[2]}\n e.g. {ex["in"]!r}')
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Structural diff between vanilla's exported command tree and Horizon's.
usage: command_tree_diff.py VANILLA_TREE.json RUST_TREE.json [ROOT]
Reports, for every shared node, the children Horizon lacks or adds, differing
argument parsers and executable/redirect flags. Missing subtrees are reported
once at their root.
"""
import json
import sys
LOOSE = {
# Horizon's coarse argument kinds that stand in for several vanilla parsers.
'brigadier:string': {'brigadier:string', 'minecraft:message', 'minecraft:component'},
}
def same_parser(vanilla, rust):
if vanilla == rust:
return True
return False
def keyed(children):
"""Literals by name; arguments by position (their names are internal)."""
out = {}
index = 0
for name, child in children.items():
if child['type'] == 'literal':
out[('l', name)] = (name, child)
else:
out[('a', index)] = (name, child)
index += 1
return out
def diff(path, v, r, out):
vc, rc = keyed(v.get('children', {})), keyed(r.get('children', {}))
for key, (name, node) in vc.items():
if key not in rc:
out.append(('missing', path + [name], node.get('parser') or 'literal', count(node)))
for key, (name, node) in rc.items():
if key not in vc:
out.append(('extra', path + [name], node.get('parser') or 'literal', count(node)))
for key, (name, a) in vc.items():
if key not in rc:
continue
_, b = rc[key]
if a['type'] == 'argument' and not same_parser(a['parser'], b['parser']):
out.append(('parser', path + [name], f"{a['parser']} vs {b['parser']}", 0))
if bool(a.get('executable')) != bool(b.get('executable')):
out.append(('executable', path + [name], f"vanilla={bool(a.get('executable'))}", 0))
if bool(a.get('redirect')) != bool(b.get('redirect')):
out.append(('redirect', path + [name], f"vanilla={bool(a.get('redirect'))}", 0))
diff(path + [name], a, b, out)
def count(node):
return 1 + sum(count(c) for c in node.get('children', {}).values())
def main():
vanilla = json.load(open(sys.argv[1]))
rust = json.load(open(sys.argv[2]))
only = sys.argv[3] if len(sys.argv) > 3 else None
if only:
vanilla = {'children': {only: vanilla['children'][only]}, 'type': 'root'}
rust = {'children': {only: rust['children'].get(only, {'children': {}, 'type': 'literal'})}, 'type': 'root'}
out = []
diff([], vanilla, rust, out)
for kind, path, detail, size in out:
print(f'{kind:10} {" ".join(path)} [{detail}]' + (f' ({size} nodes)' if size else ''))
missing = sum(size for kind, _, _, size in out if kind == 'missing')
print(f'-- {len(out)} differences, {missing} vanilla nodes missing in Horizon')
if __name__ == '__main__':
main()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Compare vanilla updateShape and neighborChanged with horizon-world, state by state.
Every block state is put at the origin of a random neighbourhood; `shape` cases
call `BlockState.updateShape` for one direction with a (consistent) neighbour
state and compare the resulting state, requested scheduled ticks, side effects and
RNG use; `neighbor` cases call `handleNeighborChanged` from one direction.
"""
import random
try:
from . import block_update_harness as h
except ImportError:
import block_update_harness as h
def cases(facts, count, seed, only):
rng = random.Random(seed)
pool = h.state_pool(facts, only)
air = facts.defaults['minecraft:air']
for n in range(count):
state = pool[n % len(pool)]
direction = rng.randrange(6)
cells = facts.cells(rng, state)
case = {**h.environment(rng), 'pos': [0, 0, 0], 'dir': direction}
dx, dy, dz = h.DIRS[direction]
if n % 3 == 2:
case['mode'] = 'neighbor'
case['from'] = [dx, dy, dz]
else:
case['mode'] = 'shape'
neighbour = facts.neighbour(rng, state)
neighbour = air if neighbour is None else neighbour
h.put(cells, (dx, dy, dz), neighbour)
case['neighbor'] = neighbour
case['cells'] = cells
yield case
def main():
args = h.argument_parser(__doc__).parse_args()
facts = h.load_facts()
differing = h.execute('block-update-parity', list(cases(facts, args.count, args.seed, args.only)), args, facts)
h.finish(differing)
if __name__ == '__main__':
main()
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Compare Horizon's command parser with vanilla's real Brigadier command tree.
Java (VanillaCommandParseOracle) builds vanilla's `Commands` dispatcher with
the real registries and data-pack loaded tags, exports the whole tree, and
parses a corpus of command strings. The corpus is generated by walking that
tree (every command and subcommand with valid and invalid sample values per
argument type) plus hand-written edge cases for selectors, NBT paths,
coordinates, ranges, resource locations and block/item predicates. For every
input the parse success, the exact error text and cursor, the parsed node
names and the completion suggestions at the end of the input must match.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
try:
from . import lab, test_rust_parity as base
from . import command_parse_corpus as corpus_module
except ImportError:
import lab
import test_rust_parity as base
import command_parse_corpus as corpus_module
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
parser.add_argument('--permission', type=int, nargs='*', default=[4, 2, 0])
parser.add_argument('--limit', type=int, default=0, help='print at most this many mismatches per class')
parser.add_argument('--allow-gaps', action='store_true', help='report mismatches without failing')
args = parser.parse_args()
build = lab.LOCAL / 'command-parse-parity'
build.mkdir(parents=True, exist_ok=True)
report_path = build / 'report.json'
report_path.unlink(missing_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandParseOracle.java'
classes = build / 'classes'
classes.mkdir(exist_ok=True)
dependency_path = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
tail = (build / (name + '.log')).read_text(errors='replace')[-2500:]
sys.exit(f'{name} failed ({result.returncode}):\n{tail}')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + dependency_path, '-d', classes, oracle], 'compile-java')
def java(*arguments):
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]), 'dev.horizonlab.parity.VanillaCommandParseOracle', *arguments], 'java-' + arguments[0])
java('registries', str(build))
java('tree', str(build))
tree = json.loads((build / 'tree.json').read_text())
registries = json.loads((build / 'registries.json').read_text())
corpus = corpus_module.corpus(tree, registries)
(build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'command_parse_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('command_parse_fixture.exe' if os.name == 'nt' else 'command_parse_fixture')
resources = lab.LOCAL / 'horizon-client/26.3'
total_failures = 0
summary = []
for permission in args.permission:
level_dir = build / f'perm{permission}'
level_dir.mkdir(exist_ok=True)
(level_dir / 'registries.json').write_bytes((build / 'registries.json').read_bytes())
stamp = level_dir / 'vanilla.stamp'
digest = lab.digest(build / 'corpus.txt', 'sha256') + lab.digest(oracle, 'sha256')
if not (stamp.exists() and stamp.read_text() == digest and (level_dir / 'vanilla.jsonl').exists()):
java('run', str(level_dir), str(build / 'corpus.txt'), str(permission))
stamp.write_text(digest)
run([binary, resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}')
failures = compare(level_dir / 'vanilla.jsonl', level_dir / 'rust.jsonl', args.limit)
count = sum(1 for _ in (level_dir / 'vanilla.jsonl').open())
print(f'permission {permission}: {count - failures}/{count} commands match', flush=True)
summary.append({'permission': permission, 'commands': count, 'mismatches': failures})
total_failures += failures
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'results': summary,
'scope': 'Parse success, error text and cursor, parsed node names and end-of-input suggestions for a tree-walked corpus.'}
lab.write_json(report_path, report)
if total_failures and not args.allow_gaps:
sys.exit(f'{total_failures} command parse mismatches; see {build}')
print(f'Command parse parity report: {report_path}')
def compare(vanilla_path, rust_path, limit):
vanilla = [json.loads(line) for line in vanilla_path.open(encoding='utf-8')]
rust = [json.loads(line) for line in rust_path.open(encoding='utf-8')]
if len(vanilla) != len(rust):
raise SystemExit(f'line count differs: vanilla {len(vanilla)} rust {len(rust)}')
shown = {}
failures = 0
mismatches = []
for v, r in zip(vanilla, rust):
assert v['in'] == r['in'], (v['in'], r['in'])
kind = None
if 'crash' in v:
continue # oracle could not evaluate (missing server state)
# Node names are internal to each implementation; only success matters.
vp = {k: val for k, val in v['parse'].items() if k != 'nodes'}
rp = {k: val for k, val in r['parse'].items() if k != 'nodes'}
if vp != rp:
kind = 'parse'
elif v['sugg'] != r['sugg']:
kind = 'suggestions'
if kind:
failures += 1
mismatches.append({'kind': kind, 'in': v['in'], 'vanilla': v['parse'] if kind == 'parse' else v['sugg'], 'rust': r['parse'] if kind == 'parse' else r['sugg']})
out = vanilla_path.with_name('mismatches.jsonl')
out.write_text(''.join(json.dumps(m, ensure_ascii=False) + '\n' for m in mismatches), encoding='utf-8')
for m in mismatches:
n = shown.get(m['kind'], 0)
if limit and n >= limit:
continue
shown[m['kind']] = n + 1
print(m['kind'], repr(m['in']), '\n vanilla', json.dumps(m['vanilla'], ensure_ascii=False)[:300], '\n rust ', json.dumps(m['rust'], ensure_ascii=False)[:300])
return failures
if __name__ == '__main__':
main()
+380
View File
@@ -0,0 +1,380 @@
#!/usr/bin/env python3
"""Compare item model resolution with the pinned client's own item pipeline.
The vanilla side (VanillaItemModelOracle) decodes every `items/*.json` with the
client codec, discovers and bakes all models with `ModelBakery` against real
PNG sprites, and resolves stacks through `ItemStackRenderState` layers. The
Rust side (`item_model_fixture`) must pick the same layers, tints, foil,
transformations, special-renderer configurations and baked quads."""
import json
import os
import platform
import random
import subprocess
import zipfile
from pathlib import Path
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
CONTEXTS = ['gui', 'ground', 'fixed', 'head', 'thirdperson_righthand', 'thirdperson_lefthand',
'firstperson_righthand', 'firstperson_lefthand', 'on_shelf', 'none']
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan',
'purple', 'blue', 'brown', 'green', 'red', 'black']
TRIM_MATERIALS = ['quartz', 'iron', 'netherite', 'redstone', 'copper', 'gold', 'emerald', 'diamond', 'lapis',
'amethyst', 'resin']
NEEDED = ('assets/minecraft/items/', 'assets/minecraft/models/', 'assets/minecraft/textures/item/',
'assets/minecraft/textures/block/', 'assets/minecraft/textures/trims/',
'assets/minecraft/textures/colormap/')
def extract(jar, destination):
marker = destination / '.jar-sha256'
digest = lab.digest(jar, 'sha256')
if marker.exists() and marker.read_text() == digest:
return
destination.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(jar) as archive:
for name in archive.namelist():
if name.startswith(NEEDED) and not name.endswith('/'):
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.read(name))
marker.write_text(digest)
def owner(using, remaining, arm='right', entity='minecraft:player'):
return {'using': using, 'remaining': remaining, 'main_arm': arm, 'entity_type': entity}
def corpus(prototypes):
"""Representative stacks for every registered item."""
rng = random.Random(0x4954454d)
cases = []
def add(item, context='gui', count=1, components=None, **extra):
case = {'id': str(len(cases)), 'item': item, 'count': count, 'context': context}
if components: case['components'] = components
case.update(extra)
cases.append(case)
for item, components in prototypes.items():
stack = components.get('minecraft:max_stack_size', 64)
for context in CONTEXTS: add(item, context)
max_damage = components.get('minecraft:max_damage', 0)
if max_damage:
for damage in sorted({0, 1, max_damage // 2, max_damage - 2, max_damage - 1, max_damage}):
add(item, 'gui', components={'minecraft:damage': damage})
add(item, 'gui', components={'minecraft:damage': max_damage - 1, 'minecraft:unbreakable': {}})
add(item, 'gui', components={'!minecraft:max_damage': {}})
for count in sorted({2, stack // 2, stack}):
if 1 <= count <= stack: add(item, 'gui', count=count)
for color in (0xFF0000, 0x123456, 0xFFFFFF, 0):
add(item, 'gui', components={'minecraft:dyed_color': color})
for material in TRIM_MATERIALS:
add(item, 'gui', components={'minecraft:trim': {'material': 'minecraft:' + material, 'pattern': 'minecraft:coast'}})
add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [0.0, 0.5, 1.0, 2.5, 7.0],
'flags': [True, False, True], 'strings': ['a', 'b', 'c'], 'colors': [0xFF0000, 0x00FF00]}})
add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [3.0]}})
for context in ('gui', 'ground', 'head'):
add(item, context, components={'minecraft:enchantments': {'minecraft:sharpness': 1}})
add(item, 'gui', components={'minecraft:enchantment_glint_override': True})
add(item, 'gui', components={'minecraft:enchantment_glint_override': False,
'minecraft:enchantments': {'minecraft:sharpness': 1}})
add(item, 'gui', components={'minecraft:potion_contents': {'custom_color': 0x00FF7F}})
add(item, 'gui', components={'minecraft:potion_contents': {'potion': 'minecraft:water'}})
add(item, 'gui', components={'minecraft:potion_contents': {}})
for colors in ([], [0xFF0000], [0xFF0000, 0x0000FF], [0x112233, 0x445566, 0x778899]):
add(item, 'gui', components={'minecraft:firework_explosion': {'shape': 'small_ball', 'colors': colors}})
add(item, 'gui', components={'minecraft:item_model': 'minecraft:diamond'})
add(item, 'gui', components={'minecraft:item_model': 'minecraft:horizon_unknown'})
add(item, 'gui', components={'!minecraft:item_model': {}})
add(item, 'gui', components={'minecraft:item_model': 'minecraft:bundle'}, bundle_selected=0)
for state in ({'honey_level': '0'}, {'honey_level': '5'}, {'light_level': '7'}, {'level': '1'},
{'age': '3'}, {'powered': 'true'}, {'unknown': 'x'}):
add(item, 'gui', components={'minecraft:block_state': state})
for projectile in ('minecraft:arrow', 'minecraft:firework_rocket'):
add(item, 'gui', components={'minecraft:charged_projectiles': [{'id': projectile, 'count': 1}]})
add(item, 'gui', components={'minecraft:charged_projectiles': []})
add(item, 'gui', components={'minecraft:lodestone_tracker': {}})
add(item, 'gui', components={'minecraft:lodestone_tracker': {'tracked': True,
'target': {'dimension': 'minecraft:overworld', 'pos': [1, 2, 3]}}})
add(item, 'gui', components={'minecraft:banner_patterns': [{'pattern': 'minecraft:circle', 'color': 'red'},
{'pattern': 'minecraft:border', 'color': 'blue'}]})
add(item, 'gui', components={'minecraft:base_color': 'green',
'minecraft:banner_patterns': [{'pattern': 'minecraft:globe', 'color': 'yellow'}]})
add(item, 'gui', components={'minecraft:pot_decorations': {'back': {'id': 'minecraft:brick'},
'left': {'id': 'minecraft:angler_pottery_sherd'}, 'front': {'id': 'minecraft:blade_pottery_sherd'}}})
add(item, 'gui', components={'minecraft:profile': {'name': 'Notch'}})
add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3},
{'id': 'minecraft:diamond_sword', 'count': 1},
{'id': 'minecraft:dirt', 'count': 20}]}, bundle_selected=1)
add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3}]}, bundle_selected=-1)
for time in ('12-24', '12-25', '12-26', '10-09', ''):
add(item, 'gui', local_time=time)
for dimension in ('minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end', 'horizon:other'):
add(item, 'gui', dimension=dimension)
for arm in ('left', 'right'):
for entity in ('minecraft:player', 'minecraft:zombie'):
add(item, 'firstperson_righthand', owner=owner(False, 0, arm, entity))
for remaining in (0, 1, 3, 7, 13, 20, 71000, 71990, 72000):
for context in ('firstperson_righthand', 'thirdperson_righthand'):
add(item, context, owner=owner(True, remaining))
add(item, 'firstperson_righthand', owner=owner(False, 5))
# Item definitions with every shape the codec accepts and rejects.
return cases
def definitions():
"""Synthetic client item definitions: valid and invalid shapes."""
model = {'type': 'minecraft:model', 'model': 'minecraft:item/stick'}
other = {'type': 'minecraft:model', 'model': 'minecraft:item/diamond'}
rows = {}
def put(name, definition):
rows['horizon:' + name] = definition if isinstance(definition, str) else json.dumps(definition)
put('plain', {'model': model})
put('props', {'model': model, 'hand_animation_on_swap': False, 'oversized_in_gui': True, 'swap_animation_scale': 2.5})
put('no_model', {})
put('unknown_type', {'model': {'type': 'minecraft:horizon'}})
put('empty', {'model': {'type': 'minecraft:empty'}})
put('composite', {'model': {'type': 'minecraft:composite', 'models': [model, other, {'type': 'minecraft:empty'}]}})
put('composite_empty', {'model': {'type': 'minecraft:composite', 'models': []}})
put('composite_one', {'model': {'type': 'minecraft:composite', 'models': [model],
'transformation': [1, 0, 0, 0.5, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]}})
put('matrix', {'model': dict(model, transformation=[0.5, 0, 0, 1, 0, 0.5, 0, 2, 0, 0, 0.5, 3, 0, 0, 0, 1])})
put('matrix_short', {'model': dict(model, transformation=[1, 0, 0])})
quarter = [0.0, 0.0, 0.70710677, 0.70710677]
put('decomposed', {'model': dict(model, transformation={'translation': [1, 2, 3], 'left_rotation': quarter,
'scale': [1, 2, 3], 'right_rotation': [0, 0.38268343, 0, 0.9238795]})})
put('axis_angle', {'model': dict(model, transformation={'translation': [0, 0, 0],
'left_rotation': {'angle': 1.5707964, 'axis': [0, 0, 1]}, 'scale': [1, 1, 1], 'right_rotation': [0, 0, 0, 1]})})
put('decomposed_partial', {'model': dict(model, transformation={'translation': [0, 0, 0], 'scale': [1, 1, 1]})})
put('nested_transform', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged',
'transformation': [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1], 'on_true': dict(model, transformation=[1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), 'on_false': other}})
put('tints', {'model': dict(model, tints=[{'type': 'minecraft:constant', 'value': 0x123456},
{'type': 'minecraft:constant', 'value': [0.5, 0.25, 1.0]},
{'type': 'minecraft:dye', 'default': -6265536}, {'type': 'minecraft:grass', 'temperature': 0.5, 'downfall': 1.0},
{'type': 'minecraft:grass', 'temperature': 0.0, 'downfall': 0.0}, {'type': 'minecraft:grass', 'temperature': 1.0, 'downfall': 0.3},
{'type': 'minecraft:firework', 'default': 7}, {'type': 'minecraft:potion', 'default': 9},
{'type': 'minecraft:team', 'default': 11},
{'type': 'minecraft:custom_model_data', 'index': 1, 'default': 0x0000FF}])})
put('bad_tint', {'model': dict(model, tints=[{'type': 'minecraft:horizon'}])})
put('bad_grass', {'model': dict(model, tints=[{'type': 'minecraft:grass', 'temperature': 2.0, 'downfall': 0.0}])})
put('condition_missing_branch', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged', 'on_true': model}})
for prop in ('broken', 'damaged', 'using_item', 'selected', 'carried', 'view_entity', 'extended_view',
'fishing_rod/cast', 'bundle/has_selected_item'):
put('cond_' + prop.replace('/', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:' + prop, 'on_true': model, 'on_false': other}})
for index in (0, 1, 3, -1):
put(f'cond_cmd_{index}', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': index, 'on_true': model, 'on_false': other}})
for ignore in (True, False):
for component in ('minecraft:damage', 'minecraft:enchantments', 'minecraft:max_damage', 'minecraft:custom_name', 'minecraft:horizon'):
put(f'cond_has_{ignore}_{component}'.lower().replace(':', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:has_component',
'component': component, 'ignore_default': ignore, 'on_true': model, 'on_false': other}})
select = lambda prop, cases, **extra: {'model': dict({'type': 'minecraft:select', 'property': 'minecraft:' + prop,
'cases': [{'when': w, 'model': m} for w, m in cases]}, **extra)}
put('select_ctx', select('display_context', [(['gui', 'ground'], model), ('head', other)], fallback={'type': 'minecraft:empty'}))
put('select_ctx_nofallback', select('display_context', [('gui', model)]))
put('select_ctx_bad', select('display_context', [('guii', model)]))
put('select_dup', select('display_context', [('gui', model), (['gui', 'head'], other)]))
put('select_empty_cases', select('display_context', []))
put('select_empty_when', select('display_context', [([], model)]))
put('select_arm', select('main_hand', [('left', model), ('right', other)]))
put('select_arm_fallback', select('main_hand', [('left', model)], fallback=other))
put('select_charge', select('charge_type', [('none', model), ('arrow', other), ('rocket', {'type': 'minecraft:empty'})]))
put('select_trim', select('trim_material', [(['minecraft:quartz', 'iron'], model), ('minecraft:gold', other)], fallback={'type': 'minecraft:empty'}))
put('select_state', select('block_state', [('3', model), ('5', other)], block_state_property='honey_level', fallback=model))
put('select_state_missing_prop', select('block_state', [('3', model)]))
put('select_entity', select('context_entity_type', [('minecraft:player', model), ('zombie', other)], fallback={'type': 'minecraft:empty'}))
put('select_dimension', select('context_dimension', [('minecraft:overworld', model), ('the_nether', other)], fallback={'type': 'minecraft:empty'}))
put('select_cmd', select('custom_model_data', [('a', model), ('c', other)], index=2, fallback={'type': 'minecraft:empty'}))
put('select_time', select('local_time', [('12-25', model)], pattern='MM-dd', fallback=other))
put('select_time_bad', select('local_time', [('12-25', model)], pattern='Q{', fallback=other))
put('select_component', select('component', [('minecraft:diamond_sword', model)], component='minecraft:item_model', fallback=other))
put('select_unknown_prop', select('horizon', [('a', model)]))
ranges = lambda prop, entries, **extra: {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:' + prop,
'entries': [{'threshold': t, 'model': m} for t, m in entries]}, **extra)}
put('range_damage', ranges('damage', [(0.0, model), (0.5, other), (0.99, {'type': 'minecraft:empty'})], fallback={'type': 'minecraft:empty'}))
put('range_damage_raw', ranges('damage', [(0, model), (10, other)], normalize=False))
put('range_count', ranges('count', [(0.0, model), (0.5, other), (1.0, {'type': 'minecraft:empty'})]))
put('range_count_raw', ranges('count', [(1, model), (32, other)], normalize=False))
put('range_scale', ranges('damage', [(0, model), (50, other)], scale=100))
put('range_nofallback', ranges('damage', [(0.4, model)]))
put('range_unsorted', ranges('count', [(0.9, other), (0.1, model), (0.5, {'type': 'minecraft:empty'}), (0.1, other)]))
put('range_many', ranges('count', [(i / 20, model if i % 2 else other) for i in range(20)]))
put('range_cmd', ranges('custom_model_data', [(0, model), (1, other), (2.5, {'type': 'minecraft:empty'})], index=0))
put('range_cooldown', ranges('cooldown', [(0, model), (0.5, other)]))
put('range_use_duration', ranges('use_duration', [(0, model), (10, other)]))
put('range_use_remaining', ranges('use_duration', [(0, model), (10, other)], remaining=True))
put('range_cycle', ranges('use_cycle', [(0, model), (2, other)], period=4))
put('range_cycle_bad', ranges('use_cycle', [(0, model)], period=0))
put('range_crossbow', ranges('crossbow/pull', [(0, model), (0.5, other)]))
put('range_fullness', ranges('bundle/fullness', [(0, model), (0.5, other)]))
put('range_time', ranges('time', [(0, model)], source='daytime'))
put('range_compass', ranges('compass', [(0, model)], target='spawn'))
put('range_compass_bad', ranges('compass', [(0, model)], target='moon'))
put('range_nan_threshold', ranges('damage', [(float('nan'), model)]))
put('range_no_entries', {'model': {'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage'}})
for kind, config in [('banner', {'color': 'red'}), ('banner', {'color': 'blue', 'attachment': 'wall'}),
('banner', {'color': 'pink', 'attachment': 'ground'}), ('banner', {'color': 'nope'}), ('banner', {}),
('bell', {}), ('book', {'open_angle': 1.0, 'page1': 0.25, 'page2': 0.75}), ('book', {'open_angle': 1.0}),
('chest', {'texture': 'minecraft:normal'}), ('chest', {'texture': 'christmas', 'openness': 0.5, 'chest_type': 'left'}),
('chest', {'texture': 'minecraft:normal', 'chest_type': 'triple'}), ('chest', {}),
('conduit', {}), ('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'star'}),
('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'dancing'}),
('decorated_pot', {}), ('end_cube', {'effect': 'portal'}), ('end_cube', {'effect': 'void'}),
('head', {'kind': 'dragon'}), ('head', {'kind': 'player', 'texture': 'horizon:custom', 'animation': 1.5}),
('head', {'kind': 'ghast'}), ('player_head', {}),
('shulker_box', {}), ('shulker_box', {'texture': 'minecraft:shulker_red', 'openness': 0.25}),
('shield', {}), ('trident', {}), ('horizon', {})]:
put(f'special_{kind}_{len(rows)}', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/shield' if kind == 'shield' else 'minecraft:item/template_banner',
'model': dict(config, type='minecraft:' + kind)}})
put('special_transformed', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/trident_in_hand', 'model': {'type': 'minecraft:trident'},
'transformation': {'left_rotation': [0, 0, 0, 1], 'right_rotation': [0, 0, 0, 1], 'scale': [1, -1, -1], 'translation': [0, 0, 0]}}})
put('bundle_selected', {'model': {'type': 'minecraft:composite', 'models': [model, {'type': 'minecraft:bundle/selected_item'}, other]}})
for pack in ('', '_x'):
put('trailing' + pack, json.dumps({'model': model}) + pack)
put('not_object', '[]')
put('null_model', {'model': None})
put('number_scale', {'model': model, 'swap_animation_scale': 'x'})
put('bool_flag_number', {'model': model, 'oversized_in_gui': 1})
put('bool_flag_string', {'model': model, 'oversized_in_gui': 'true'})
put('bool_flag_float', {'model': model, 'oversized_in_gui': 0.5})
put('swap_bool', {'model': model, 'swap_animation_scale': True})
put('int_float_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': 1.5, 'on_true': model, 'on_false': other}})
put('int_bool_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': True, 'on_true': model, 'on_false': other}})
put('bool_as_number', {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage', 'entries': [{'threshold': True, 'model': model}]})})
return rows
def definition_cases(rows):
cases = []
stacks = [('minecraft:diamond_sword', {'minecraft:damage': 100}, 1), ('minecraft:diamond_sword', {'minecraft:damage': 1560}, 1),
('minecraft:diamond_sword', {}, 1), ('minecraft:stone', {}, 64), ('minecraft:stone', {}, 17), ('minecraft:stone', {}, 1),
('minecraft:bow', {}, 1), ('minecraft:leather_helmet', {'minecraft:trim': {'material': 'minecraft:gold', 'pattern': 'minecraft:coast'}}, 1),
('minecraft:beehive', {'minecraft:block_state': {'honey_level': '3'}}, 1),
('minecraft:beehive', {'minecraft:block_state': {'honey_level': '5'}}, 1), ('minecraft:crossbow', {}, 1),
('minecraft:crossbow', {'minecraft:charged_projectiles': [{'id': 'minecraft:arrow', 'count': 1}]}, 1),
('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [0.0, 1.0, 3.0], 'flags': [True], 'strings': ['a', 'b', 'c']}}, 1),
('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [2.5], 'flags': [False, True], 'strings': ['x']}}, 1),
('minecraft:bundle', {'minecraft:bundle_contents': [{'id': 'minecraft:diamond_sword', 'count': 1}, {'id': 'minecraft:stone', 'count': 3}]}, 1),
('minecraft:bundle', {'minecraft:bundle_contents': []}, 1),
('minecraft:stone', {'minecraft:enchantments': {'minecraft:sharpness': 1}}, 1),
('minecraft:stone', {'minecraft:custom_name': '"x"'}, 1)]
for name in rows:
for stack_index, (item, components, count) in enumerate(stacks):
for context in ('gui', 'head', 'firstperson_lefthand', 'ground'):
for owner_state in (None, owner(True, 9), owner(False, 0, 'left', 'minecraft:zombie')):
for dimension in (None, 'minecraft:overworld', 'minecraft:the_nether'):
if dimension and context != 'gui': continue
case = {'id': f'd{len(cases)}', 'item': item, 'count': count, 'context': context,
'components': dict(components, **{'minecraft:item_model': name})}
if owner_state: case['owner'] = owner_state
if dimension: case['dimension'] = dimension
if 'bundle_contents' in str(components) and count == 1 and 'diamond_sword' in str(components):
case['bundle_selected'] = stack_index % 2
case['local_time'] = '12-25' if stack_index % 2 else '01-01'
cases.append(case)
return cases
import struct
def float_bits(value):
return struct.unpack('<I', struct.pack('<f', value))[0]
THIN = (float_bits(7.5 / 16), float_bits(8.5 / 16))
def canonical_quads(quads):
"""The extruded sides of generated layers come out of a hash set in vanilla: no order to keep."""
if quads and all(THIN[0] <= p[2] <= THIN[1] for q in quads for p in q['positions']):
return sorted(quads, key=lambda q: json.dumps(q, sort_keys=True))
return quads
def matrix(bits):
return [0 if b == 0x80000000 else b for b in bits]
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / 'item-model-parity'; build.mkdir(parents=True, exist_ok=True)
report_path = build / 'report.json'; report_path.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java'
crate = lab.ROOT / 'crates/horizon-assets'
sources = [oracle, Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.toml',
lab.ROOT / 'Cargo.lock', crate / 'Cargo.toml', *sorted(crate.rglob('*.rs'))]
tested = base.source_hashes(sources)
resources = build / 'resources'
extract(jars['client'], resources)
_, directory = lab.config()
prototypes_path = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] / 'items.json'
prototypes = json.loads(prototypes_path.read_text())
cases = corpus(prototypes)
rows = definitions()
cases += definition_cases(rows)
inputs = build / 'cases.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in cases))
(build / 'cases.jsonl.definitions').write_text(''.join(json.dumps({'name': n, 'json': j}) + '\n' for n, j in rows.items()))
classes = build / 'classes'; classes.mkdir(exist_ok=True)
def run(command, name):
with (build / (name + '.log')).open('w') as log:
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
run(['cargo', 'build', '--locked', '-p', 'horizon-assets', '--example', 'item_model_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory']) / 'debug/examples' / ('item_model_fixture.exe' if os.name == 'nt' else 'item_model_fixture')
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaItemModelOracle',
resources, inputs, build / 'client.jsonl', prototypes_path], 'client')
# The host inputs vanilla derives from the stack (use duration, charge time).
client = [json.loads(line) for line in (build / 'client.jsonl').read_text().splitlines()]
derived = {r['id']: r['derived'] for r in client if r.get('row') == 'case' and 'derived' in r}
rust_cases = []
for case in cases:
case = dict(case)
if case['id'] in derived: case['derived'] = derived[case['id']]
rust_cases.append(case)
rust_inputs = build / 'rust-cases.jsonl'
rust_inputs.write_text(''.join(json.dumps(c) + '\n' for c in rust_cases))
(build / 'rust-cases.jsonl.definitions').write_text((build / 'cases.jsonl.definitions').read_text())
run([binary, resources, prototypes_path, rust_inputs, build / 'rust.jsonl'], 'rust')
rust = [json.loads(line) for line in (build / 'rust.jsonl').read_text().splitlines()]
mismatches, compared, skipped, decoded = [], 0, 0, 0
vanilla_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in client if r['row'] in ('case', 'decode', 'components')}
rust_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in rust}
assert vanilla_by_key.keys() == rust_by_key.keys(), 'The two sides produced different rows'
assert vanilla_by_key[('components', None)]['names'] == rust_by_key[('components', None)]['names'], 'Data component registry differs'
unbaked = [r['name'] for r in client if r['row'] == 'unbaked']
for key, left in vanilla_by_key.items():
right = rust_by_key[key]
if key[0] == 'components': continue
if key[0] == 'decode':
decoded += 1
if left['ok'] != right['ok']: mismatches.append(('decode', key[1], left, right))
continue
if 'error' in left:
skipped += 1
continue
compared += 1
for side in (left, right):
for layer in side['layers']:
layer['matrix'] = matrix(layer['matrix'])
layer.pop('has_transform', None)
if layer.get('quads') is not None: layer['quads'] = canonical_quads(layer['quads'])
if left != right:
mismatches.append(('case', key[1], left, right))
if mismatches:
for kind, name, left, right in mismatches[:5]:
print(kind, name, '\nvanilla:', json.dumps(left)[:1500], '\nrust: ', json.dumps(right)[:1500])
raise AssertionError(f'{len(mismatches)} item model mismatches')
base.ensure_sources_unchanged(sources, tested)
assert compared > 1000, 'Too few cases compared'
assert skipped * 20 < len(cases), f'Too many cases rejected by vanilla: {skipped}'
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'manifest_sha1': lock['minecraft']['manifest_sha1'],
'platform': platform.platform(), 'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(),
'cases': len(cases), 'compared': compared, 'rejected_by_vanilla': skipped, 'definitions_decoded': decoded,
'definitions_unbaked': unbaked, 'sources_sha256': tested,
'scope': 'Actual ClientItem codec, ModelDiscovery, ModelBakery item baking and ItemModelResolver semantics against real sprites in a unit atlas. Every bundled items/*.json and synthetic definitions; every item prototype in every display context with representative components. Layer content, tints, foil, composed transformation matrices (numeric equality), special-renderer codec forms and arguments, baked quads by float bits, render properties. Not covered: GPU rendering, atlas packing, level-dependent needles (see the needle tests), player/keybind/team-based properties that need a live client.'}
lab.write_json(report_path, report)
print(f'Item models: {compared:,} resolved stacks match ({skipped:,} rejected by vanilla, {decoded:,} definitions); {report_path}', flush=True)
if __name__ == '__main__': main()