Merge main into the scoreboard and command work

# Conflicts:
#	crates/horizon-client/src/game.rs
#	crates/horizon-client/src/game/commands.rs
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/lib.rs
This commit is contained in:
Ludovic Marie
2026-10-09 13:57:10 +02:00
73 changed files with 13562 additions and 575 deletions
+313
View File
@@ -0,0 +1,313 @@
//! Banner patterns: the `banner_pattern` registry and its tags, the
//! `banner_patterns` layers carried by banner items, shields and placed
//! banners, and the loom rules of `LoomMenu` (selectable patterns, the
//! six-layer limit and the result stack).
use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items};
use horizon_world::nbt::Tag;
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path, sync::Arc};
/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BannerLayer {
pub pattern: Arc<str>,
pub color: Arc<str>,
}
impl BannerLayer {
pub fn new(pattern: &str, color: &str) -> Self {
Self {
pattern: Arc::from(pattern),
color: Arc::from(color),
}
}
}
/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`).
pub const MAX_LAYERS: usize = 6;
/// One `banner_pattern` registry entry.
#[derive(Clone, Debug)]
pub struct Pattern {
pub id: Arc<str>,
/// `asset_id` path, the texture under `entity/banner` and `entity/shield`.
pub asset: String,
pub translation_key: String,
}
/// The pattern registry, its tags and the item components the loom reads.
#[derive(Default)]
pub struct Banners {
patterns: Vec<Pattern>,
/// `#minecraft:no_item_required`, in tag order.
no_item_required: Vec<Arc<str>>,
/// Item -> `dye` component.
dyes: HashMap<Arc<str>, Arc<str>>,
/// Item -> `provides_banner_patterns`, in tag order.
provided: HashMap<Arc<str>, Vec<Arc<str>>>,
}
fn read_tag(root: &Path, name: &str, depth: u32) -> Vec<Arc<str>> {
if depth > 8 {
return Vec::new();
}
let path = root.join(format!(
"data/minecraft/tags/banner_pattern/{}.json",
name.trim_start_matches("minecraft:")
));
let Some(v) = fs::read(path)
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
else {
return Vec::new();
};
let mut out = Vec::new();
for value in v["values"].as_array().into_iter().flatten() {
let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else {
continue;
};
match s.strip_prefix('#') {
Some(tag) => out.extend(read_tag(root, tag, depth + 1)),
None => out.push(Arc::from(s)),
}
}
out
}
impl Banners {
pub fn load(root: &Path) -> Self {
let mut banners = Self::default();
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
files.sort();
for path in files {
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let Some(v) = fs::read(&path)
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
else {
continue;
};
let asset = v["asset_id"]
.as_str()
.unwrap_or(stem)
.trim_start_matches("minecraft:")
.to_owned();
banners.patterns.push(Pattern {
id: Arc::from(format!("minecraft:{stem}").as_str()),
asset,
translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(),
});
}
banners.no_item_required = read_tag(root, "no_item_required", 0);
if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| {
serde_json::from_slice::<std::collections::BTreeMap<String, Value>>(&b).ok()
}) {
for (item, c) in raw {
let id: Arc<str> = Arc::from(item.as_str());
if let Some(dye) = c["minecraft:dye"].as_str() {
banners.dyes.insert(id.clone(), Arc::from(dye));
}
match &c["minecraft:provides_banner_patterns"] {
Value::String(tag) if tag.starts_with('#') => {
banners.provided.insert(id, read_tag(root, &tag[1..], 0));
}
Value::String(single) => {
banners
.provided
.insert(id, vec![Arc::from(single.as_str())]);
}
_ => {}
}
}
}
banners
}
pub fn pattern(&self, id: &str) -> Option<&Pattern> {
self.patterns.iter().find(|p| &*p.id == id)
}
/// `Sheets.getBannerSprite` texture name of a pattern.
pub fn banner_texture(&self, id: &str) -> String {
match self.pattern(id) {
Some(p) => format!("entity/banner/{}", p.asset),
None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")),
}
}
/// `Sheets.getShieldSprite` texture name of a pattern.
pub fn shield_texture(&self, id: &str) -> String {
match self.pattern(id) {
Some(p) => format!("entity/shield/{}", p.asset),
None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")),
}
}
/// `BannerPatternLayers.Layer.description` translation key.
pub fn layer_key(&self, layer: &BannerLayer) -> String {
let base = self.pattern(&layer.pattern).map_or_else(
|| {
format!(
"block.minecraft.banner.{}",
layer.pattern.trim_start_matches("minecraft:")
)
},
|p| p.translation_key.clone(),
);
format!("{base}.{}", layer.color)
}
/// `LoomMenu.isDyeItem`: the dye colour of a loom dye.
pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option<Arc<str>> {
let tagged = items
.item_tags
.get("minecraft:loom_dyes")
.is_some_and(|t| t.contains(&*stack.item));
tagged
.then(|| self.dyes.get(&stack.item).cloned())
.flatten()
}
/// `LoomMenu.isPatternItem`.
pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool {
items
.item_tags
.get("minecraft:loom_patterns")
.is_some_and(|t| t.contains(&*stack.item))
&& self.provided.contains_key(&stack.item)
}
/// `LoomMenu.getSelectablePatterns`.
pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec<Arc<str>> {
match pattern_item {
None => self.no_item_required.clone(),
Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(),
}
}
}
/// `BannerItem`: a banner's dye colour from its item id.
pub fn banner_color(item: &str) -> Option<&'static str> {
let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?;
DYES.iter().map(|d| d.0).find(|d| *d == name)
}
/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name.
pub fn dye_rgb(name: &str) -> u32 {
DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1)
}
/// The layers of a banner or shield stack.
pub fn layers(stack: &ItemStack) -> &[BannerLayer] {
stack.data().map_or(&[], |d| &d.banner_patterns)
}
/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour.
pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack {
let mut result = ItemStack {
count: 1,
..banner.clone()
};
result
.data_mut()
.banner_patterns
.push(BannerLayer::new(pattern, dye));
result
}
/// Whether the banner already carries the loom's limit.
pub fn has_max_layers(banner: &ItemStack) -> bool {
layers(banner).len() >= MAX_LAYERS
}
/// The `banner_patterns` NBT list of layers.
pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag {
Tag::List(
layers
.iter()
.map(|l| {
Tag::compound([
("pattern", Tag::String((&*l.pattern).into())),
("color", Tag::String((&*l.color).into())),
])
})
.collect(),
)
}
pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec<BannerLayer> {
let Some(Tag::List(list)) = tag else {
return Vec::new();
};
list.iter()
.filter_map(|e| {
let text = |k: &str| match e.get(k) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
let pattern = text("pattern")?;
let color = text("color")?;
Some(BannerLayer::new(
&if pattern.contains(':') {
pattern
} else {
format!("minecraft:{pattern}")
},
&color,
))
})
.collect()
}
/// Keeps `item_data` linked: the `StackData` fields the banner code reads.
pub fn set_layers(stack: &mut ItemStack, layers: Vec<BannerLayer>) {
let data: &mut item_data::StackData = stack.data_mut();
data.banner_patterns = layers;
stack.tidy();
}
#[cfg(test)]
mod tests {
use super::*;
fn banners() -> Banners {
let mut b = Banners {
no_item_required: vec![Arc::from("minecraft:stripe_top")],
..Default::default()
};
b.provided.insert(
Arc::from("minecraft:flower_banner_pattern"),
vec![Arc::from("minecraft:flower")],
);
b
}
#[test]
fn selectable_follow_the_pattern_item() {
let b = banners();
assert_eq!(b.selectable(None).len(), 1);
let item = ItemStack::new("minecraft:flower_banner_pattern", 1);
assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower");
}
#[test]
fn banner_colour_comes_from_the_item() {
assert_eq!(
banner_color("minecraft:light_gray_banner"),
Some("light_gray")
);
assert_eq!(banner_color("minecraft:white_banner"), Some("white"));
assert_eq!(banner_color("minecraft:white_wool"), None);
}
#[test]
fn loom_adds_a_layer_up_to_the_limit() {
let mut banner = ItemStack::new("minecraft:white_banner", 3);
for i in 0..MAX_LAYERS {
assert!(!has_max_layers(&banner));
banner = loom_result(&banner, "red", "minecraft:cross");
assert_eq!(banner.count, 1);
assert_eq!(layers(&banner).len(), i + 1);
}
assert!(has_max_layers(&banner));
}
#[test]
fn layers_round_trip_through_nbt() {
let l = vec![
BannerLayer::new("minecraft:flower", "red"),
BannerLayer::new("minecraft:border", "black"),
];
assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l);
}
}
@@ -700,6 +700,8 @@ pub struct Scene<'a> {
pub lid: &'a dyn Fn([i32; 3]) -> f32,
/// Sign block-entity data at a position.
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
/// Font glyph cell and advance.
pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>,
}
@@ -773,6 +775,13 @@ impl BlockEntityRenderer {
random: LegacyRandom::new(0x5EED_B00C),
}
}
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> {
Some((
self.models.get("standing_banner")?,
self.models.get("standing_banner_flag")?,
))
}
fn kind(&self, state: u32) -> &Kind {
self.kinds.get(state as usize).unwrap_or(&Kind::None)
}
@@ -993,10 +1002,16 @@ impl BlockEntityRenderer {
draw_part(main, "root", m, &none, paint, out);
draw_part(flag, "root", m, &wave, paint, out);
}
// BannerRenderer.submitPatterns: the base pattern layer in the dye colour.
// BannerRenderer.submitPatterns: the base pattern layer in the dye colour,
// then up to 16 pattern layers in order.
if let Some(paint) = paint("entity/banner/base", *color, packed) {
draw_part(flag, "root", m, &wave, paint, out);
}
for (texture, tint) in (scene.banner)(pos).iter().take(16) {
if let Some(paint) = paint(texture, *tint, packed) {
draw_part(flag, "root", m, &wave, paint, out);
}
}
}
Kind::Skull {
kind,
+3
View File
@@ -94,6 +94,8 @@ pub struct Chunk {
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
pub lit: bool,
/// Light read from a save with `isLightOn`: no light job is needed.
pub light_loaded: bool,
/// Newly generated (not loaded from a save): eligible for generation-time spawns.
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
@@ -120,6 +122,7 @@ impl Chunk {
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
heights: Arc::new([MIN_Y as i16; 256]),
lit: false,
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
structure_refs: Vec::new(),
@@ -111,6 +111,28 @@ pub fn build() -> Dispatcher {
d.executes(dur, "weather");
}
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
let raid = d.literal(root, "raid");
d.requires(raid, 3);
let start = d.literal(raid, "start");
let level = d.argument(start, "omenlvl", integer(0));
d.executes(level, "raid.start");
for (name, id) in [
("stop", "raid.stop"),
("check", "raid.check"),
("spawnleader", "raid.spawnleader"),
("glow", "raid.glow"),
] {
let n = d.literal(raid, name);
d.executes(n, id);
}
let sound = d.literal(raid, "sound");
let kind = d.argument(sound, "type", ArgType::Greedy);
d.executes(kind, "raid.sound");
let setomen = d.literal(raid, "setomen");
let level = d.argument(setomen, "level", integer(0));
d.executes(level, "raid.setomen");
// kill [<targets>]
let kill = d.literal(root, "kill");
d.requires(kill, GAMEMASTERS);
+101 -3
View File
@@ -58,6 +58,77 @@ pub enum BlockEntity {
Beacon(Box<Beacon>),
/// `LecternBlockEntity`: the book and the open page.
Lectern(Lectern),
/// `CreakingHeartBlockEntity`: its protector and the hurt emitter.
CreakingHeart(Box<CreakingHeart>),
/// `BannerBlockEntity`: the pattern layers.
Banner(Banner),
/// `CrafterBlockEntity`.
Crafter(Crafter),
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
#[derive(Clone, Debug, Default)]
pub struct Crafter {
pub items: [Option<ItemStack>; 9],
pub disabled: [bool; 9],
pub triggered: bool,
pub crafting_ticks: i32,
}
impl Crafter {
/// `slotCanBeDisabled`: only empty slots.
pub fn slot_can_be_disabled(&self, slot: usize) -> bool {
slot < 9 && self.items[slot].is_none()
}
/// `setSlotState`.
pub fn set_slot_state(&mut self, slot: usize, enabled: bool) {
if self.slot_can_be_disabled(slot) {
self.disabled[slot] = !enabled;
}
}
/// `getRedstoneSignal`: filled or disabled slots.
pub fn redstone_signal(&self) -> i32 {
(0..9)
.filter(|&i| self.items[i].is_some() || self.disabled[i])
.count() as i32
}
/// `canPlaceItem`: a hopper fills the smallest stacks first.
pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool {
if slot >= 9 || self.disabled[slot] {
return false;
}
let Some(current) = &self.items[slot] else {
return true;
};
if current.count >= max_stack {
return false;
}
!(slot + 1..9).any(|i| {
!self.disabled[i]
&& match &self.items[i] {
None => true,
Some(other) => {
other.count < current.count && other.same_item_same_components(stack)
}
}
})
}
}
#[derive(Clone, Debug, Default)]
pub struct Banner {
pub layers: Vec<crate::banner::BannerLayer>,
pub name: Option<String>,
}
/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`).
#[derive(Clone, Debug, Default)]
pub struct CreakingHeart {
/// The protector: its entity id once resolved, and its UUID (the saved form).
pub creaking: Option<(Option<u32>, [i32; 4])>,
pub ticks_existed: i64,
pub ticker: i32,
/// Ticks left of the hurt effect (`emitter`) and where it heads.
pub emitter: i32,
pub emitter_target: Option<[f64; 3]>,
pub output_signal: i32,
}
#[derive(Clone, Debug, Default)]
pub struct Lectern {
@@ -101,9 +172,18 @@ impl BlockEntity {
speed: 1.0,
}));
}
if name == "minecraft:creaking_heart" {
return Some(Self::CreakingHeart(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
if name == "minecraft:crafter" {
return Some(Self::Crafter(Crafter::default()));
}
if name.ends_with("_banner") {
return Some(Self::Banner(Banner::default()));
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -135,6 +215,7 @@ impl BlockEntity {
"minecraft:blast_furnace" => "minecraft:blast_furnace",
"minecraft:smoker" => "minecraft:smoker",
n if n.ends_with("shulker_box") => "minecraft:shulker_box",
"minecraft:crafter" => "minecraft:crafter",
_ => return None,
})
}
@@ -155,6 +236,9 @@ impl BlockEntity {
Self::Jukebox(_) => "minecraft:jukebox",
Self::Beacon(_) => "minecraft:beacon",
Self::Lectern(_) => "minecraft:lectern",
Self::Banner(_) => "minecraft:banner",
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -164,8 +248,10 @@ impl BlockEntity {
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
Self::Sign(_) => Vec::new(),
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) => Vec::new(),
Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -173,7 +259,13 @@ impl BlockEntity {
Self::Chest(items) => items,
Self::Furnace(f) => &f.items,
Self::Brewing(b) => &b.items,
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[],
Self::Sign(_)
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -181,7 +273,13 @@ impl BlockEntity {
Self::Chest(items) => items,
Self::Furnace(f) => &mut f.items,
Self::Brewing(b) => &mut b.items,
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [],
Self::Sign(_)
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) => &mut [],
}
}
}
+222 -4
View File
@@ -53,9 +53,104 @@ pub enum Recipe {
ingredients: Vec<Ingredient>,
result: ItemStack,
},
/// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`.
Special(Special),
}
/// The banner-copying custom recipes.
#[derive(Clone, Debug)]
pub enum Special {
/// A patterned banner and a blank one of the same colour copy the patterns.
BannerDuplicate { banner: Ingredient, result: String },
/// A banner decorates an undecorated shield.
ShieldDecoration {
banner: Ingredient,
target: Ingredient,
result: String,
},
}
impl Special {
/// `matches` + `assemble` over the non-empty stacks of the grid.
fn assemble(&self, stacks: &[&ItemStack]) -> Option<ItemStack> {
use crate::banner;
if stacks.len() != 2 {
return None;
}
match self {
Self::BannerDuplicate {
banner: ing,
result,
} => {
let color = banner::banner_color(&stacks[0].item)?;
let mut source = None;
let mut target = false;
for s in stacks {
if !ing.test(s) || banner::banner_color(&s.item)? != color {
return None;
}
let layers = banner::layers(s).len();
if layers > banner::MAX_LAYERS {
return None;
}
if layers > 0 {
if source.is_some() {
return None;
}
source = Some(*s);
} else {
if target {
return None;
}
target = true;
}
}
let source = source.filter(|_| target)?;
// TransmuteRecipe.createWithOriginalComponents: the source's components.
Some(ItemStack {
item: Arc::from(result.as_str()),
count: 1,
..(*source).clone()
})
}
Self::ShieldDecoration {
banner: ing,
target: tgt,
result,
} => {
let (mut patterned, mut clear) = (None, None);
for s in stacks {
if ing.test(s) && banner::banner_color(&s.item).is_some() {
if patterned.is_some() {
return None;
}
patterned = Some(*s);
} else {
if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() {
return None;
}
clear = Some(*s);
}
}
let (banner_stack, shield) = (patterned?, clear?);
let mut out = ItemStack {
item: Arc::from(result.as_str()),
count: 1,
..shield.clone()
};
let data = out.data_mut();
data.banner_patterns = banner::layers(banner_stack).to_vec();
data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from);
Some(out)
}
}
}
}
#[derive(Clone, Debug)]
pub struct Cooking {
/// The recipe's file name (its id without namespace).
pub id: String,
/// `category` (`food`, `blocks`, `misc`) and `group` of the recipe book.
pub category: String,
pub group: String,
pub kind: String,
pub ingredient: Ingredient,
pub result: ItemStack,
@@ -65,6 +160,8 @@ pub struct Cooking {
pub struct Recipes {
pub crafting: Vec<(String, Recipe)>,
pub cooking: Vec<Cooking>,
/// `category` and `group` of each crafting recipe, by file name.
pub meta: std::collections::HashMap<String, (String, String)>,
}
fn result(v: &Value) -> Option<ItemStack> {
Some(ItemStack {
@@ -78,6 +175,7 @@ impl Recipes {
pub fn load(root: &Path, items: &Items) -> Result<Self> {
let mut crafting = Vec::new();
let mut cooking = Vec::new();
let mut meta = std::collections::HashMap::new();
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))?
.flatten()
.map(|e| e.path())
@@ -91,6 +189,8 @@ impl Recipes {
.unwrap_or("")
.to_owned();
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
let text = |k: &str| v[k].as_str().unwrap_or("").to_owned();
meta.insert(name.clone(), (text("category"), text("group")));
match v["type"].as_str().unwrap_or("") {
"minecraft:crafting_shaped" => {
let pattern: Vec<Vec<char>> = v["pattern"]
@@ -145,6 +245,36 @@ impl Recipes {
));
}
}
"minecraft:crafting_special_bannerduplicate" => {
if let (Some(banner), Some(id)) = (
Ingredient::parse(&v["banner"], items),
v["result"]["id"].as_str(),
) {
crafting.push((
name,
Recipe::Special(Special::BannerDuplicate {
banner,
result: id.to_owned(),
}),
));
}
}
"minecraft:crafting_special_shielddecoration" => {
if let (Some(banner), Some(target), Some(id)) = (
Ingredient::parse(&v["banner"], items),
Ingredient::parse(&v["target"], items),
v["result"]["id"].as_str(),
) {
crafting.push((
name,
Recipe::Special(Special::ShieldDecoration {
banner,
target,
result: id.to_owned(),
}),
));
}
}
kind @ ("minecraft:smelting"
| "minecraft:blasting"
| "minecraft:smoking"
@@ -154,6 +284,9 @@ impl Recipes {
result(&v["result"]),
) {
cooking.push(Cooking {
id: name,
category: text("category"),
group: text("group"),
kind: kind.to_owned(),
ingredient,
result,
@@ -165,10 +298,18 @@ impl Recipes {
_ => {}
}
}
Ok(Self { crafting, cooking })
Ok(Self {
crafting,
cooking,
meta,
})
}
/// Match a `size`x`size` grid (row-major) against the crafting recipes.
pub fn craft(&self, grid: &[Option<ItemStack>], size: usize) -> Option<ItemStack> {
self.find(grid, size).map(|(_, result)| result)
}
/// `craft` with the matched recipe's id (the file name without namespace).
pub fn find(&self, grid: &[Option<ItemStack>], size: usize) -> Option<(&str, ItemStack)> {
// Trim to the occupied bounding box.
let occupied: Vec<(usize, usize)> = (0..size * size)
.filter(|&i| grid[i].is_some())
@@ -187,8 +328,14 @@ impl Recipes {
);
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref();
for (_, recipe) in &self.crafting {
for (name, recipe) in &self.crafting {
match recipe {
Recipe::Special(special) => {
let stacks: Vec<&ItemStack> = grid.iter().flatten().collect();
if let Some(result) = special.assemble(&stacks) {
return Some((name, result));
}
}
Recipe::Shaped {
width,
height,
@@ -211,7 +358,7 @@ impl Recipes {
})
};
if matches(false) || matches(true) {
return Some(result.clone());
return Some((name, result.clone()));
}
}
Recipe::Shapeless {
@@ -235,16 +382,87 @@ impl Recipes {
}
});
if ok {
return Some(result.clone());
return Some((name, result.clone()));
}
}
}
}
None
}
/// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder
/// (buckets, bottles), and the patterned banner a duplicate keeps.
pub fn remainders(
&self,
items: &Items,
grid: &[Option<ItemStack>],
result: &ItemStack,
) -> Vec<Option<ItemStack>> {
grid.iter()
.map(|cell| {
let s = cell.as_ref()?;
if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) {
return Some(ItemStack::new(rem, 1));
}
(result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then(
|| ItemStack {
count: 1,
..s.clone()
},
)
})
.collect()
}
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
self.cooking
.iter()
.find(|c| c.kind == kind && c.ingredient.test(input))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::banner::BannerLayer;
fn ingredient(items: &[&str]) -> Ingredient {
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
}
fn patterned(item: &str) -> ItemStack {
let mut s = ItemStack::new(item, 1);
s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")];
s
}
#[test]
fn banner_duplicate_copies_the_patterns_of_the_same_colour() {
let recipe = Special::BannerDuplicate {
banner: ingredient(&["minecraft:white_banner"]),
result: "minecraft:white_banner".into(),
};
let source = patterned("minecraft:white_banner");
let blank = ItemStack::new("minecraft:white_banner", 1);
let out = recipe.assemble(&[&source, &blank]).expect("copy");
assert_eq!(out.data().unwrap().banner_patterns.len(), 1);
// Two blanks, or two patterned banners, do not match.
assert!(recipe.assemble(&[&blank, &blank]).is_none());
assert!(recipe.assemble(&[&source, &source]).is_none());
// Another colour is not in the recipe's ingredient.
let other = ItemStack::new("minecraft:red_banner", 1);
assert!(recipe.assemble(&[&source, &other]).is_none());
}
#[test]
fn shield_decoration_needs_a_bare_shield() {
let recipe = Special::ShieldDecoration {
banner: ingredient(&["minecraft:red_banner"]),
target: ingredient(&["minecraft:shield"]),
result: "minecraft:shield".into(),
};
let banner = patterned("minecraft:red_banner");
let shield = ItemStack::new("minecraft:shield", 1);
let out = recipe.assemble(&[&banner, &shield]).expect("decorated");
let data = out.data().unwrap();
assert_eq!(data.base_color.as_deref(), Some("red"));
assert_eq!(data.banner_patterns.len(), 1);
// A shield that already has patterns cannot be decorated again.
assert!(recipe.assemble(&[&banner, &out]).is_none());
}
}
+5 -1
View File
@@ -194,7 +194,11 @@ impl Enchantments {
|| k.starts_with("potion.")
|| k.starts_with("container.")
|| k.starts_with("merchant.")
|| k.starts_with("entity.minecraft.villager")
|| k.starts_with("entity.minecraft.")
|| k.starts_with("gui.recipebook.")
|| k.starts_with("gui.togglable_slot")
|| k.starts_with("block.minecraft.banner.")
|| k.starts_with("recipe.toast.")
})
.collect();
let mut list = Vec::new();
+48 -3
View File
@@ -135,7 +135,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
("LeftHanded", Tag::Byte(0)),
(
"Brain",
@@ -216,6 +216,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.insert("Variant".into(), Tag::Int(v));
}
map.insert("ChestedHorse".into(), Tag::Byte(i8::from(m.extra.chested)));
if m.extra.chested && !m.extra.items.is_empty() {
map.insert("Items".into(), crate::save::encode_items(&m.extra.items));
} else {
map.remove(&"Items".into());
}
let mut equipment = Vec::new();
if m.extra.saddled {
equipment.push((
@@ -257,6 +262,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("equipment".into(), Tag::Compound(equipment));
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
} else {
map.remove(&"home_pos".into());
}
}
"minecraft:villager" => {
use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
let data = Tag::compound([
@@ -283,6 +296,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.insert("RestocksToday".into(), Tag::Int(t.restocks_today));
put_offers(map, m);
put_memories(map, m);
crate::mobs::villager::write_nbt(m, map);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:allay" => {
@@ -374,6 +388,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
_ => {}
}
crate::mobs::raider::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
if !crate::mobs::equine::is_equine(m.species()) {
let mut equipment = match map.get(&"equipment".into()) {
@@ -394,7 +409,22 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
equipment.get(&slot.into()).and_then(|e| e.get("id")),
Some(Tag::String(s)) if s.to_string_lossy() == **id
);
if !keep {
if slot == "head"
&& &**id == crate::mobs::raider::BANNER
&& crate::mobs::raider::is_raider(m.species())
{
// The captain's ominous banner keeps its patterns.
let has_patterns = equipment
.get(&slot.into())
.and_then(|e| e.get("components"))
.is_some();
if !has_patterns {
equipment.insert(
slot.into(),
crate::save::item_to_nbt(&crate::mobs::raider::ominous_banner()),
);
}
} else if !keep {
equipment.insert(
slot.into(),
Tag::compound([
@@ -457,6 +487,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
if m.kind.category == "creature" {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
@@ -494,6 +525,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.variant = (v & 0xFF).clamp(0, 6) as u8;
m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8;
m.extra.chested = flag(tag, "ChestedHorse");
if m.extra.chested {
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
}
let eq = tag.get("equipment");
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
m.extra.head = eq
@@ -577,6 +611,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.egg_time = -1 - 400;
}
}
if m.species() == crate::mobs::Species::Creaking
&& let Some(Tag::IntArray(home)) = tag.get("home_pos")
&& home.len() == 3
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
@@ -616,6 +656,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.health = health;
m.extra.flag2 = flag(tag, "wasOnGround");
}
crate::mobs::raider::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
if m.health <= 0.0 && m.death_time == 0 {
return None;
@@ -1029,7 +1070,7 @@ fn put_offers(map: &mut Compound, m: &Mob) {
}
/// The villager brain's `job_site`, `home` and `meeting_point` memories.
fn put_memories(map: &mut Compound, m: &Mob) {
let memories: Vec<(&str, Tag)> = [
let mut memories: Vec<(&str, Tag)> = [
("minecraft:job_site", m.extra.home),
("minecraft:home", m.extra.bed),
("minecraft:meeting_point", m.extra.meeting),
@@ -1043,6 +1084,7 @@ fn put_memories(map: &mut Compound, m: &Mob) {
Some((key, Tag::compound([("value", pos)])))
})
.collect();
crate::mobs::villager::write_memories(m, &mut memories);
map.insert(
"Brain".into(),
Tag::compound([("memories", Tag::compound(memories))]),
@@ -1076,6 +1118,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
m.extra.home = memory("minecraft:job_site");
m.extra.bed = memory("minecraft:home");
m.extra.meeting = memory("minecraft:meeting_point");
if m.species() == crate::mobs::Species::Villager {
crate::mobs::villager::read_nbt(m, tag);
}
let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
return;
};
+151 -70
View File
@@ -4,6 +4,7 @@ mod advancements;
mod advancements_screen;
mod allays;
mod armor_stands;
mod banners;
mod beacon;
mod blockctl;
mod boats;
@@ -14,8 +15,10 @@ mod chat;
mod combat;
mod commands;
mod control;
mod creaking;
mod creatures;
mod crossbow;
mod dispenser;
mod dragon;
mod enchant_effects;
mod end;
@@ -27,12 +30,15 @@ mod fov;
mod frames;
mod functions;
mod game_mode;
mod golems;
mod growth;
mod jukebox;
mod lightning;
mod loom;
mod machines;
mod maps;
mod minecarts;
mod mount_menu;
mod mounts;
mod music;
mod names;
@@ -44,6 +50,8 @@ mod perspective;
mod piglins;
mod postprocess;
mod potions;
mod raids;
mod recipe_book;
mod remote;
mod render_control;
mod render_tick;
@@ -63,6 +71,7 @@ mod tnt;
mod totem;
mod trading;
mod trident;
mod villagers;
mod wither;
use horizon_client::{
Result,
@@ -309,6 +318,17 @@ impl LevelAccess for GameLevel<'_> {
if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) {
return comparator;
}
if let Some(signal) = creaking::heart_signal(self.world, pos) {
return if self.registry.state(_state).is_some_and(|s| {
s.properties
.get("creaking_heart_state")
.is_some_and(|v| v == "uprooted")
}) {
0
} else {
signal
};
}
if let Some(signal) = books::lectern_signal(self.world, pos) {
return signal;
}
@@ -521,6 +541,7 @@ struct Game<'a> {
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
raiding: raids::Raiding,
attack_ticks: u32,
last_hurt_by_player: HashSet<u32>,
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
@@ -611,10 +632,17 @@ struct Game<'a> {
ender_open: Option<(i32, i32, i32)>,
/// Contents of broken shulker boxes waiting for their dropped item.
pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
/// Layers of broken banners waiting for their dropped item.
pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>,
/// The recipe book of the open screen (game/recipe_book.rs).
recipe_ui: recipe_book::RecipeUi,
/// The horse inventory (game/mount_menu.rs).
mount_menu: mount_menu::MountMenu,
/// The player's fishing hook.
hook: Option<fishing::Hook>,
tridents: Vec<trident::ThrownTrident>,
rockets: Vec<fireworks::Rocket>,
creaking: creaking::CreakingState,
trident_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
@@ -988,6 +1016,7 @@ impl Game<'_> {
/// Block.popResource
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
self.attach_shulker_contents(pos, &mut stack);
self.attach_banner_layers(pos, &mut stack);
let r = &mut self.world.random;
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
let p = [
@@ -1618,6 +1647,7 @@ impl Game<'_> {
None
}
.unwrap_or(self.world.air);
self.creaking_heart_broken(pos);
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
// Containers.dropContents (shulker boxes keep theirs).
let name = facts.name.clone();
@@ -1819,6 +1849,7 @@ impl Game<'_> {
.block_entities
.insert((target[0], target[1], target[2]), entity);
self.fill_placed_box(target, &stack);
self.fill_placed_banner(target, &stack);
if sign {
self.open_sign_editor((target[0], target[1], target[2]), true);
}
@@ -1841,6 +1872,7 @@ impl Game<'_> {
self.stats.add("used", &stack.item, 1);
self.trigger_block("minecraft:placed_block", target, &stack);
self.check_wither_spawn(target)?;
self.check_golem_spawn(target)?;
self.consume_held();
Ok(())
}
@@ -2441,6 +2473,7 @@ impl Game<'_> {
self.screen = Screen::Dead;
self.capture(false);
}
self.tick_omens();
self.tick_effects();
self.tick_burning();
self.tick_using();
@@ -2683,13 +2716,18 @@ impl Game<'_> {
.map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned()))
}
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
if &*stack.item == "minecraft:shield" {
shield::draw_shield_icon(batch, &self.res.atlas, x, y);
return;
}
let icon = self.icon(&stack.item);
// Special-model items: the shield and banners draw their own 3D icon.
let banner = if &*stack.item == "minecraft:shield" {
let passes = shield::shield_passes(&self.res.stations.banners, stack);
shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes);
true
} else {
self.draw_banner_icon(batch, stack, x, y)
};
let icon = if banner { None } else { self.icon(&stack.item) };
let atlas = &self.res.atlas;
match icon {
None if banner => {}
Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX),
Some(Icon::Cube {
top,
@@ -3050,7 +3088,7 @@ impl Game<'_> {
}
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
(
(batch.width - 176.0) / 2.0,
(batch.width - 176.0) / 2.0 + self.recipe_book_shift(batch.width),
(batch.height - self.screen_height()) / 2.0,
)
}
@@ -3061,19 +3099,22 @@ impl Game<'_> {
}
/// 300.. are the open container's slots.
fn slots(&self) -> Vec<usize> {
if let Some(v) = self.station_slots() {
if let Some(v) = self.station_slots().or_else(|| self.mount_slots()) {
return v;
}
let mut v: Vec<usize> = (0..36).collect();
match self.container_kind() {
Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)),
Some(BlockEntity::Chest(_)) => v.extend((0..self.container_size()).map(|i| 300 + i)),
Some(BlockEntity::Furnace(_)) => v.extend(300..303),
Some(BlockEntity::Brewing(_)) => v.extend(300..305),
Some(BlockEntity::Crafter(_)) => v.extend(300..310),
Some(
BlockEntity::Sign(_)
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_),
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -3090,15 +3131,18 @@ impl Game<'_> {
if let Some(p) = self
.station_slot_position(i)
.or_else(|| self.machine_slot_position(i))
.or_else(|| self.crafter_slot_position(i))
.or_else(|| self.mount_slot_position(i))
{
return p;
}
let table = self.craft_size == 3;
// ContainerScreen (3 rows) shifts the player inventory down by one pixel.
let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) {
1.0
} else {
0.0
// ChestMenu: the inventory sits `18 * (rows - 3) + 1` lower than the
// 3-row layout of the other menus.
let shift = match self.chest_rows() {
Some(rows) => 1.0 + (rows as f32 - 3.0) * 18.0,
None => 0.0,
};
match i {
0..9 => (8.0 + i as f32 * 18.0, 142.0 + shift),
@@ -3144,6 +3188,9 @@ impl Game<'_> {
})
}
fn slot_mut(&mut self, i: usize) -> &mut Option<ItemStack> {
if i >= mount_menu::SADDLE {
return self.mount_slot_mut(i);
}
if i >= stations::INPUT {
return self.station_slot_mut(i);
}
@@ -3154,14 +3201,7 @@ impl Game<'_> {
return &mut self.offhand;
}
if i >= 300 {
let key = self.container;
return match key.and_then(|k| self.world.block_entities.get_mut(&k)) {
Some(e) => e
.slots_mut()
.get_mut(i - 300)
.unwrap_or(&mut self.scratch_slot),
None => &mut self.scratch_slot,
};
return self.container_slot_mut(i - 300);
}
if (100..109).contains(&i) {
&mut self.craft_grid[i - 100]
@@ -3169,6 +3209,14 @@ impl Game<'_> {
&mut self.inventory[i]
}
}
/// What a slot shows: the crafting result slots are computed.
fn slot_view(&mut self, i: usize) -> Option<ItemStack> {
match i {
200 => self.craft_result(),
309 => self.crafter_result(),
_ => self.slot_mut(i).clone(),
}
}
fn craft_result(&self) -> Option<ItemStack> {
let n = self.craft_size;
let grid: Vec<Option<ItemStack>> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect();
@@ -3212,42 +3260,7 @@ impl Game<'_> {
.and_then(|k| self.world.block_entities.get(&k))
{
Some(BlockEntity::Chest(_)) if self.draw_machine_screen(batch, ox, oy) => {}
Some(BlockEntity::Chest(_)) => {
// ContainerScreen with 3 rows: top 71px, then the player inventory from v=126.
part(
batch,
"gui/container/generic_54",
0.0,
0.0,
176.0,
71.0,
ox,
oy,
);
part(
batch,
"gui/container/generic_54",
0.0,
126.0,
176.0,
96.0,
ox,
oy + 71.0,
);
let name = self
.container
.map(|k| self.world.block(k.0, k.1, k.2))
.map(|s| self.res.facts.get(s).name.clone());
let title = if self.open_cart_kind().is_some() {
"Minecart with Chest"
} else if name.as_deref() == Some("minecraft:barrel") {
"Barrel"
} else {
"Chest"
};
batch.text(atlas, title, ox + 8.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 73.0, grey, false);
}
Some(BlockEntity::Chest(_)) => self.draw_chest_screen(batch, ox, oy),
Some(BlockEntity::Furnace(f)) => {
let (tex, title) = match f.kind {
horizon_client::containers::FurnaceKind::Furnace => {
@@ -3294,12 +3307,16 @@ impl Game<'_> {
}
}
Some(BlockEntity::Brewing(_)) => {}
Some(BlockEntity::Crafter(_)) => self.draw_crafter_screen(batch, ox, oy),
Some(
BlockEntity::Sign(_)
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_),
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
let texture = if self.craft_size == 3 {
"gui/container/crafting_table"
@@ -3326,7 +3343,7 @@ impl Game<'_> {
}
}
}
if self.container.is_none() && self.craft_size != 3 {
if self.container.is_none() && self.craft_size != 3 && !self.mount_active() {
self.draw_inventory_player(batch, ox, oy);
}
for i in self.slots() {
@@ -3348,15 +3365,12 @@ impl Game<'_> {
oy + sy,
);
}
let stack = if i == 200 {
self.craft_result()
} else {
self.slot_mut(i).clone()
};
let stack = self.slot_view(i);
if let Some(stack) = stack {
self.draw_item(batch, &stack, ox + sx, oy + sy);
}
}
self.draw_recipe_book(batch);
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(
@@ -3375,6 +3389,8 @@ impl Game<'_> {
}
pub(super) fn close_container(&mut self) {
self.close_station();
self.mount_closed();
self.recipe_ui.reset_screen();
if self.remote.is_some() {
return self.remote_close_container();
}
@@ -3424,6 +3440,12 @@ impl Game<'_> {
self.close_cart_container();
}
fn click_inventory(&mut self, right: bool) {
if self.mount_click(right) {
return;
}
if self.recipe_book_click(right) {
return;
}
if self.station_click(right) {
return;
}
@@ -3441,6 +3463,17 @@ impl Game<'_> {
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return;
};
let held_shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
if self.crafter_click(slot, held_shift) {
return;
}
if held_shift && self.container.is_some() && self.container_quick_move(slot) {
if let Some(key) = self.container {
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
}
return;
}
if let Some(c) = &self.carried
&& self.refuses(slot, c)
{
@@ -3486,6 +3519,12 @@ impl Game<'_> {
let mut crafted = 0;
while let Some(result) = self.craft_result() {
let made = (result.item.clone(), result.count);
let cells = self.craft_size * self.craft_size;
let remainders = self.res.recipes.remainders(
&self.res.items,
&self.craft_grid[..cells],
&result,
);
if shift {
if self.give(result).is_some() {
break;
@@ -3510,6 +3549,14 @@ impl Game<'_> {
}
}
}
for (i, rest) in remainders.into_iter().enumerate() {
let Some(rest) = rest else { continue };
match &mut self.craft_grid[i] {
cell @ None => *cell = Some(rest),
Some(c) if c.same_item_same_components(&rest) => c.count += rest.count,
_ => self.give_or_drop(rest),
}
}
crafted += 1;
self.stats.add("crafted", &made.0, made.1 as i32);
if !shift || crafted >= 64 {
@@ -3900,6 +3947,7 @@ impl Game<'_> {
Some(BlockEntity::Sign(sign)) => Some(sign),
_ => None,
},
banner: &|p| self.banner_layers_at(p),
glyph: &|c| self.res.atlas.glyph(c),
};
self.res
@@ -4340,8 +4388,11 @@ impl Game<'_> {
}
fn tick_block_entities(&mut self) -> Result<()> {
self.tick_hoppers()?;
self.tick_crafters();
self.tick_mount_menu();
self.tick_jukeboxes();
self.tick_beacons();
self.tick_creaking_hearts()?;
// ChestLidController: 0.1 per tick towards open/closed.
if let Some(key) = self.container {
self.chest_open.entry(key).or_insert((0.0, 0.0));
@@ -5803,6 +5854,10 @@ impl Game<'_> {
}
first(&d["model"])
});
if item.ends_with("_banner") {
// The banner item model is a special renderer over this base model.
current = Some("minecraft:item/template_banner".to_owned());
}
for _ in 0..16 {
let Some(m) = current.take() else { break };
let path = m.trim_start_matches("minecraft:").to_owned();
@@ -5949,6 +6004,9 @@ impl Game<'_> {
* glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2])))
* glam::Mat4::from_scale(glam::Vec3::from(scale))
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
if self.held_banner_geometry(m, &stack, packed, &mut out) {
return out;
}
let atlas = &self.res.atlas;
let quad = |corners: [glam::Vec3; 4],
name: &str,
@@ -6589,6 +6647,7 @@ impl Game<'_> {
self.ender_items = items.clone();
}
level.ender_items = self.ender_items.clone();
level.recipe_book.recipes = self.adv.recipes.iter().cloned().collect();
level.active_effects = self
.potions
.effects
@@ -6619,6 +6678,7 @@ impl Game<'_> {
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
self.save_entities()?;
self.save_maps();
self.save_raids();
self.save_fight();
self.save_stats();
self.save_advancements();
@@ -6845,6 +6905,7 @@ impl Game<'_> {
Screen::Advancements => self.close_advancements(),
Screen::Chat => self.close_chat(),
},
KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(),
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
// key.advancements.
KeyCode::KeyL if self.screen == Screen::Playing => self.open_advancements(false),
@@ -6859,12 +6920,15 @@ impl Game<'_> {
KeyCode::KeyE => match self.screen {
Screen::Playing if self.spectator() => {}
Screen::Playing => {
self.screen = if self.creative {
Screen::Creative
} else {
Screen::Inventory
};
self.capture(false);
// key.inventory while riding a tamed mount opens its inventory.
if !self.open_ridden_mount_menu() {
self.screen = if self.creative {
Screen::Creative
} else {
Screen::Inventory
};
self.capture(false);
}
}
Screen::Creative => {
if let Some(c) = self.carried.take() {
@@ -7083,6 +7147,9 @@ impl ApplicationHandler for Game<'_> {
if self.screen == Screen::Advancements {
self.advancements_drag();
}
if self.screen == Screen::Inventory {
self.loom_drag();
}
if self.dragging && self.screen == Screen::Options {
let _ = b;
self.options_drag()?;
@@ -7214,6 +7281,7 @@ impl ApplicationHandler for Game<'_> {
self.container_changed(key);
}
}
Screen::Inventory => self.loom_release(),
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
Screen::Creative if pressed => {
self.click_creative(button == MouseButton::Right);
@@ -7275,6 +7343,14 @@ impl ApplicationHandler for Game<'_> {
}
self.creative_screen.scroll = 0.0;
}
WindowEvent::KeyboardInput { event, .. }
if self.recipe_search_focused()
&& event.state == ElementState::Pressed
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
{
// The recipe book's search box takes every key but Escape.
self.recipe_key(&event);
}
WindowEvent::KeyboardInput { event, .. }
if self.station_typing()
&& event.state == ElementState::Pressed
@@ -7649,6 +7725,7 @@ pub fn run() -> Result<()> {
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
raiding: Default::default(),
attack_ticks: 100,
last_hurt_by_player: HashSet::new(),
chest_open: HashMap::new(),
@@ -7717,9 +7794,13 @@ pub fn run() -> Result<()> {
ender_items: vec![None; 27],
ender_open: None,
pending_shulker: HashMap::new(),
pending_banner: HashMap::new(),
recipe_ui: Default::default(),
mount_menu: Default::default(),
hook: None,
tridents: Vec::new(),
rockets: Vec::new(),
creaking: Default::default(),
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
tnts: Vec::new(),
hoppers: HashMap::new(),
+51 -2
View File
@@ -20,6 +20,26 @@ pub(super) struct Toast {
frame: Frame,
title: Text,
shown: Option<Instant>,
/// A `RecipeToast`: the icon is a recipe result.
recipe: bool,
}
impl Toast {
pub(super) fn is_recipe(&self) -> bool {
self.recipe
}
pub(super) fn was_shown(&self) -> bool {
self.shown.is_some()
}
/// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result.
pub(super) fn recipe(icon: &str) -> Self {
Self {
icon: icon.to_owned(),
frame: Frame::Task,
title: Text::literal(""),
shown: None,
recipe: true,
}
}
}
#[derive(Default)]
pub(super) struct AdvState {
@@ -27,7 +47,7 @@ pub(super) struct AdvState {
pub(super) progress: Progress,
loaded: bool,
pub(super) recipes: BTreeSet<String>,
toasts: VecDeque<Toast>,
pub(super) toasts: VecDeque<Toast>,
/// Awards skip the toast (`/advancement grant ... everything`).
pub(super) quiet: bool,
/// The inventory last seen by `inventory_changed`.
@@ -297,12 +317,26 @@ impl Game<'_> {
}
}
pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView {
// mainhand, offhand, head, chest, legs, feet.
let slot = |i: &Option<std::sync::Arc<str>>| {
i.as_ref().map(|id| item_view(&ItemStack::new(id, 1)))
};
let mut equipment: [Option<ItemView>; 7] = Default::default();
if !horizon_client::mobs::equine::is_equine(m.species()) {
equipment[0] = slot(&m.extra.main_hand);
equipment[1] = slot(&m.extra.off_hand);
equipment[2] = slot(&m.extra.head);
equipment[3] = slot(&m.extra.chest);
equipment[4] = slot(&m.extra.legs);
equipment[5] = slot(&m.extra.feet);
}
EntityView {
kind: m.kind.id.clone(),
position: [m.position.x, m.position.y, m.position.z],
on_fire: m.fire_ticks > 0,
baby: m.is_baby(),
on_ground: m.on_ground,
equipment,
..Default::default()
}
}
@@ -375,6 +409,7 @@ impl Game<'_> {
frame: d.frame,
title: text_of(&d.title),
shown: None,
recipe: false,
});
}
if d.announce && self.ui.rules.bool("show_advancement_messages") {
@@ -390,6 +425,7 @@ impl Game<'_> {
));
}
}
self.recipe_toast(&unlocked);
for r in unlocked {
self.trigger("minecraft:recipe_unlocked", |c, _| {
c["recipes"].as_str() == Some(r.as_str())
@@ -612,7 +648,20 @@ impl Game<'_> {
} else {
1.0
};
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe);
if recipe {
// RecipeToast: black description under a purple title.
let atlas = &self.res.atlas;
let x = batch.width - 160.0 * slide;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.res.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
return;
}
if frame == Frame::Challenge && ms < 50.0 {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
+222
View File
@@ -0,0 +1,222 @@
//! Placed banners (`BannerBlockEntity`): the pattern layers move from the
//! banner item to the block when placed and back to the dropped item when
//! broken (`copy_components` in the banner loot tables).
use super::Game;
use glam::{EulerRot, Mat4, Quat, Vec3};
use horizon_client::{
banner::{self, BannerLayer},
block_entity_render::{Paint, draw_part},
containers::{Banner, BlockEntity},
hud::{HudBatch, rgba},
items::ItemStack,
mesher::Vertex,
};
impl Game<'_> {
/// The pattern textures and tints of the banner at `pos`, bottom first.
pub(super) fn banner_layers_at(&self, pos: [i32; 3]) -> Vec<(String, u32)> {
let Some(BlockEntity::Banner(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
else {
return Vec::new();
};
layer_textures(&self.res.stations.banners, &b.layers)
}
/// A placed banner takes the item's layers and name.
pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) {
self.pending_banner.remove(&pos);
if !stack.item.ends_with("_banner") {
return;
}
if let Some(BlockEntity::Banner(b)) =
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
{
b.layers = banner::layers(stack).to_vec();
b.name = stack.custom_name().map(str::to_owned);
}
}
/// A banner in a slot: `item/template_banner`'s `gui` transform on the
/// banner model (pole, bar and flag with every layer), flat-lit and
/// depth-sorted. False when the stack is not a banner.
pub(super) fn draw_banner_icon(
&self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
y: f32,
) -> bool {
let Some(base) = banner::banner_color(&stack.item) else {
return false;
};
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
return true;
};
let banners = &self.res.stations.banners;
let sprites = &self.res.atlas.sprites;
// display.gui, then the item's special transformation (a banner is
// modelled upside down and 2/3 size around the block centre).
let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0))
* Mat4::from_quat(Quat::from_euler(
EulerRot::XYZ,
30f32.to_radians(),
20f32.to_radians(),
0.0,
))
* Mat4::from_scale(Vec3::splat(0.5325))
* Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0))
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
let wave = |name: &str, p: &mut [f32; 9]| {
if name == "flag" {
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
}
};
let none = |_: &str, _: &mut [f32; 9]| {};
let mut passes: Vec<(&str, u32, bool, String)> = vec![
("entity/banner/banner_base", 0xFFFFFF, true, String::new()),
(
"entity/banner/base",
banner::dye_rgb(base),
false,
String::new(),
),
];
for layer in banner::layers(stack).iter().take(16) {
passes.push((
"",
banner::dye_rgb(&layer.color),
false,
banners.banner_texture(&layer.pattern),
));
}
// (depth, pass, screen corners, uv, colour)
let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() {
let name = if fixed.is_empty() {
dynamic.as_str()
} else {
fixed
};
let Some(sprite) = sprites.get(name).copied() else {
continue;
};
let paint = Paint {
sprite,
tint: 0xFFFFFF,
light: 0,
lights: (Vec3::ZERO, Vec3::ZERO),
};
let mut verts: Vec<Vertex> = Vec::new();
if *with_pole {
draw_part(main, "root", m, &none, paint, &mut verts);
}
draw_part(flag, "root", m, &wave, paint, &mut verts);
for quad in verts.as_chunks::<4>().0 {
let p = |i: usize| Vec3::from(quad[i].pos);
let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero();
// Faces turned away from the viewer are culled.
if normal.z <= 0.0 {
continue;
}
let depth = (0..4).map(|i| p(i).z).sum::<f32>() / 4.0;
let shade = (0.6 + 0.4 * normal.z).min(1.0);
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
faces.push((
depth,
index,
std::array::from_fn(|i| {
[
x + 8.0 + quad[i].pos[0] * 16.0,
y + 8.0 - quad[i].pos[1] * 16.0,
]
}),
std::array::from_fn(|i| quad[i].uv),
rgba(c(16), c(8), c(0), 255),
));
}
}
faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
for (_, _, corners, uv, color) in faces {
batch.quad(corners, uv, color);
}
true
}
/// A banner in the first-person hand: the standing banner model under the
/// item's `firstperson_righthand` transform (`m`) and its special
/// transformation. False when the stack is not a banner.
pub(super) fn held_banner_geometry(
&self,
m: Mat4,
stack: &ItemStack,
packed: u32,
out: &mut Vec<Vertex>,
) -> bool {
let Some(base) = banner::banner_color(&stack.item) else {
return false;
};
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
return true;
};
let m = m
* Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5))
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
let wave = |name: &str, p: &mut [f32; 9]| {
if name == "flag" {
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
}
};
let none = |_: &str, _: &mut [f32; 9]| {};
let lights = horizon_client::block_entity_render::diffuse_lights(false);
let sprites = &self.res.atlas.sprites;
let paint = |name: &str, tint: u32| {
sprites.get(name).map(|&sprite| Paint {
sprite,
tint,
light: packed,
lights,
})
};
if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) {
draw_part(main, "root", m, &none, p, out);
draw_part(flag, "root", m, &wave, p, out);
}
if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) {
draw_part(flag, "root", m, &wave, p, out);
}
for layer in banner::layers(stack).iter().take(16) {
let texture = self.res.stations.banners.banner_texture(&layer.pattern);
if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) {
draw_part(flag, "root", m, &wave, p, out);
}
}
true
}
/// The layers a banner dropped at `pos` carries.
pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if !stack.item.ends_with("_banner") {
return;
}
if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) {
let data = stack.data_mut();
data.banner_patterns = layers;
if name.is_some() {
data.custom_name = name;
}
stack.tidy();
}
}
}
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
pub(super) fn layer_textures(
banners: &banner::Banners,
layers: &[BannerLayer],
) -> Vec<(String, u32)> {
layers
.iter()
.map(|l| {
(
banners.banner_texture(&l.pattern),
banner::dye_rgb(&l.color),
)
})
.collect()
}
@@ -6,6 +6,7 @@ pub(super) mod execute;
mod items;
mod misc;
mod place;
mod raid;
mod terrain_cmds;
mod text_commands;
mod world_cmds;
@@ -496,6 +497,7 @@ impl Game<'_> {
| "teleport.targets.location"
| "teleport.targets.destination" => self.cmd_teleport(id, ctx),
id if id.starts_with("time.") => self.cmd_time(id, ctx),
id if id.starts_with("raid.") => self.cmd_raid(id, ctx),
"weather" => self.cmd_weather(ctx),
"kill" => self.cmd_kill(ctx),
"summon" => self.cmd_summon(ctx),
@@ -0,0 +1,108 @@
//! `RaidCommand`: `/raid start|stop|check|spawnleader|setomen|glow|sound`.
use super::{Game, R, Text, err};
use horizon_client::{command::Context, mobs::raider};
impl Game<'_> {
pub(in crate::game) fn cmd_raid(&mut self, id: &str, ctx: &Context) -> R<i32> {
let Some(player) = self.player.as_ref().map(|p| p.position) else {
return Ok(0);
};
let at = [
player.x.floor() as i32,
player.y.floor() as i32,
player.z.floor() as i32,
];
let fail = |game: &mut Self, message: &str| {
game.command_failure(Text::literal(message));
};
match id {
"raid.start" => {
if self.raiding_nearby(at).is_some() {
fail(self, "Raid already started close by");
return Ok(-1);
}
let level = Self::int(ctx, "omenlvl").unwrap_or(0);
match self.raid_command_create(at, level) {
true => self.feedback(Text::literal("Created a raid in your local village")),
false => fail(self, "Failed to create a raid in your local village"),
}
Ok(1)
}
"raid.stop" => match self.raiding_nearby(at) {
Some(raid) => {
self.raid_command_stop(raid);
self.feedback(Text::literal("Stopped raid"));
Ok(1)
}
None => {
fail(self, "No raid here");
Ok(-1)
}
},
"raid.check" => match self.raiding_nearby(at).filter(|id| self.raid_started(*id)) {
Some(raid) => {
self.feedback(Text::literal("Found a started raid!"));
let status = self.raid_status_text(raid);
self.feedback(Text::literal(&status));
Ok(1)
}
None => {
fail(self, "Found no started raids");
Ok(0)
}
},
"raid.spawnleader" => {
let kind = "minecraft:pillager";
match self.spawn_mob_for(kind, [player.x, player.y, player.z], true, true) {
Some(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
raider::set_patrol_leader(m, true);
raider::finalize(m, raider::Reason::Other);
}
self.feedback(Text::literal("Spawned a raid captain"));
Ok(1)
}
None => {
fail(self, "Pillager failed to spawn");
Ok(0)
}
}
}
"raid.setomen" => {
let level = Self::int(ctx, "level").unwrap_or(0);
let Some(raid) = self.raiding_nearby(at) else {
fail(self, "No raid found here");
return Ok(1);
};
if level > horizon_client::raid::MAX_OMEN_LEVEL {
fail(
self,
&format!(
"Sorry, the max raid omen level you can set is {}",
horizon_client::raid::MAX_OMEN_LEVEL
),
);
} else {
let before = self.raid_set_omen(raid, level);
self.feedback(Text::literal(format!(
"Changed village's raid omen level from {before} to {level}"
)));
}
Ok(1)
}
"raid.glow" => {
if let Some(raid) = self.raiding_nearby(at) {
self.raid_glow(raid);
}
Ok(1)
}
"raid.sound" => {
let at = [player.x + 5.0, player.y, player.z];
self.audio
.play("minecraft:event.raid.horn", Some(at), 1.0, 1.0);
Ok(1)
}
_ => Err(err("commands.help.failed", &[])),
}
}
}
@@ -293,6 +293,9 @@ impl Game<'_> {
match self.screen {
Screen::Chat => self.chat_type(text),
Screen::Options => self.ui.options.type_text(text),
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
_ => {
return Err(
"type needs the chat screen (key t tap) or the language search".into(),
+663
View File
@@ -0,0 +1,663 @@
//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an
//! awake heart in a pale oak trunk spawns a creaking that protects it,
//! hurting the creaking makes the heart emit trails and spread resin over
//! the logs, and breaking the heart tears the creaking down.
use super::Game;
use horizon_client::{
Result,
containers::{BlockEntity, CreakingHeart},
mobs::creaking,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource};
use horizon_world::registry::BlockStateId;
use std::collections::{HashSet, VecDeque};
type Pos = (i32, i32, i32);
/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`.
const ORANGE: u32 = 16_545_810;
const GRAY: u32 = 6_250_335;
/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`.
const TOO_FAR: f64 = 34.0;
/// `Direction.values()`: down, up, north, south, west, east.
const DIRECTIONS: [[i32; 3]; 6] = [
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
[-1, 0, 0],
[1, 0, 0],
];
const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
/// Comparator input of a heart (`getAnalogOutputSignal`).
pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option<i32> {
match world.block_entities.get(&(pos.x, pos.y, pos.z))? {
BlockEntity::CreakingHeart(h) => Some(h.output_signal),
_ => None,
}
}
impl Game<'_> {
fn heart_state_name(&self, state: BlockStateId) -> String {
self.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
.unwrap_or_default()
}
/// `Util.shuffledCopy(Direction.values(), random)`.
fn shuffled_directions(&mut self) -> [usize; 6] {
let mut order = [0, 1, 2, 3, 4, 5];
for i in (2..=6).rev() {
let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
order.swap(i - 1, j);
}
order
}
fn is_pale_oak_log(&self, p: Pos) -> bool {
let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name;
self.res
.items
.block_tags
.get("minecraft:pale_oak_logs")
.is_some_and(|s| s.contains(&**name))
}
fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> {
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
Some((m.center(), m.bounds()))
}
/// The protector's entity, resolving a UUID read from a save.
fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option<u32> {
let (id, uuid) = heart.creaking?;
if let Some(id) = id {
if self.mobs.iter().any(|m| m.id == id && !m.removed) {
return Some(id);
}
// The entity is gone: remember it by UUID until it reappears.
heart.creaking = Some((None, uuid));
}
if let Some(id) = self.mob_id_for_uuid(uuid) {
heart.creaking = Some((Some(id), uuid));
return Some(id);
}
if heart.ticks_existed >= 30 {
heart.creaking = None;
}
None
}
/// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart.
fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) {
let Some(id) = self.heart_protector(heart) else {
return;
};
if by_player {
// creakingDeathEffects: a twitching death.
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
creaking::set_tearing_down(m);
m.health = 0.0;
m.death_time = m.death_time.max(0);
let at = m.center();
self.audio
.play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0);
}
} else if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
let mut events = Vec::new();
creaking::tear_down(&mut self.mobs[i], &mut events);
let _ = self.handle_mob_events(events);
}
heart.creaking = None;
}
fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 {
self.mob_center(id).map_or(0.0, |_| {
let m = self.mobs.iter().find(|m| m.id == id).unwrap();
let at = (
f64::from(pos.0) + 0.5,
f64::from(pos.1),
f64::from(pos.2) + 0.5,
);
((m.position.x - at.0).powi(2)
+ (m.position.y - at.1).powi(2)
+ (m.position.z - at.2).powi(2))
.sqrt()
})
}
/// `emitParticles`: trails between the creaking and the heart.
fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) {
let Some(id) = self.heart_protector(heart) else {
return;
};
let Some((_, b)) = self.mob_center(id) else {
return;
};
let (lo, hi) = (b.min_position(), b.max_position());
for _ in 0..count {
let r = &mut self.world.random;
let mut source = [
lo.x + r.next_double() * (hi.x - lo.x),
lo.y + r.next_double() * (hi.y - lo.y),
lo.z + r.next_double() * (hi.z - lo.z),
];
let mut destination = [
f64::from(pos.0) + r.next_double(),
f64::from(pos.1) + r.next_double(),
f64::from(pos.2) + r.next_double(),
];
if towards {
std::mem::swap(&mut source, &mut destination);
}
let duration = r.next_int_bound(40).unwrap_or(0) + 10;
let color = if towards { ORANGE } else { GRAY };
self.particles.add(
&ParticleOptions::trail(destination, color, duration),
source,
[0.0; 3],
);
}
}
/// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log
/// face found within two steps of pale oak logs.
fn heart_spread_resin(&mut self, pos: Pos) -> Option<Pos> {
let mut visited: HashSet<Pos> = HashSet::new();
let mut queue: VecDeque<(Pos, i32)> = VecDeque::new();
queue.push_back((pos, 0));
let mut count = 0;
while let Some((current, depth)) = queue.pop_front() {
if !visited.insert(current) {
continue;
}
// The node processor.
if self.is_pale_oak_log(current) {
for d in self.shuffled_directions() {
let n = (
current.0 + DIRECTIONS[d][0],
current.1 + DIRECTIONS[d][1],
current.2 + DIRECTIONS[d][2],
);
let neighbour = self.world.block(n.0, n.1, n.2);
let opposite = d ^ 1;
let clump = self.resin_clump_for(neighbour);
let Some(clump) = clump else { continue };
if self.prop_is(clump, FACE_NAMES[opposite]) {
continue;
}
let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else {
continue;
};
let _ = self.level_set([n.0, n.1, n.2], placed);
return Some(n);
}
}
count += 1;
if count >= 64 {
return None;
}
if depth < 2 {
// The neighbour provider: adjacent pale oak logs.
for d in self.shuffled_directions() {
let n = (
current.0 + DIRECTIONS[d][0],
current.1 + DIRECTIONS[d][1],
current.2 + DIRECTIONS[d][2],
);
if self.is_pale_oak_log(n) {
queue.push_back((n, depth + 1));
}
}
}
}
None
}
/// The state a face of resin can be added to: air, a source of water, or
/// a clump already there.
fn resin_clump_for(&self, neighbour: BlockStateId) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let clump = registry.default_state("minecraft:resin_clump")?;
let facts = self.res.facts.get(neighbour);
if self.res.facts.is_air(neighbour) {
Some(clump)
} else if &*facts.name == "minecraft:water"
&& facts.fluid_level == 8
&& !facts.fluid_falling
{
let mut s = registry.state(clump)?.clone();
s.properties.insert("waterlogged".into(), "true".into());
registry.resolve(&s).ok()
} else if &*facts.name == "minecraft:resin_clump" {
Some(neighbour)
} else {
None
}
}
fn prop_is(&self, state: BlockStateId, key: &str) -> bool {
self.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get(key))
.is_some_and(|v| v == "true")
}
fn with_face(&self, state: BlockStateId, face: &str) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
s.properties.insert(face.to_owned(), "true".to_owned());
self.res.assets.registry.resolve(&s).ok()
}
/// A creaking bound to the heart at `home` was hurt (`creakingHurt`).
pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) {
if !by_player {
return;
}
let key = (home[0], home[1], home[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
else {
return;
};
if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 {
self.heart_emit(&mut heart, key, 20, false);
let state = self.world.block(key.0, key.1, key.2);
if self.heart_state_name(state) == "awake" {
let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0);
for _ in 0..clumps {
if let Some(at) = self.heart_spread_resin(key) {
self.audio.play(
"minecraft:block.resin.place",
Some([
f64::from(at.0) + 0.5,
f64::from(at.1) + 0.5,
f64::from(at.2) + 0.5,
]),
1.0,
1.0,
);
}
}
}
heart.emitter = 100;
heart.emitter_target = self.mob_center(id).map(|(c, _)| c);
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
/// `Creaking.tearDown`: the crumble particles.
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
let registry = self.res.assets.registry;
let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| {
let Some(mut state) = registry
.default_state(name)
.and_then(|s| registry.state(s).cloned())
else {
return;
};
for (k, v) in props {
state.properties.insert((*k).to_owned(), (*v).to_owned());
}
let Ok(id) = registry.resolve(&state) else {
return;
};
let Some((sprite, tint)) = this.particle_sprite(id) else {
return;
};
for _ in 0..count {
let r = &mut this.world.random;
let p = [
center[0] + r.next_gaussian() * spread[0],
center[1] + r.next_gaussian() * spread[1],
center[2] + r.next_gaussian() * spread[2],
];
this.particles.add(
&ParticleOptions::block(ParticleType::BlockCrumble, sprite.clone(), tint),
p,
[0.0; 3],
);
}
};
crumble(self, "minecraft:pale_oak_wood", &[], 100);
crumble(
self,
"minecraft:creaking_heart",
&[("creaking_heart_state", "awake")],
10,
);
}
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
/// death and a natural heart drops experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
let key = (pos[0], pos[1], pos[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
else {
return;
};
self.heart_remove_protector(&mut heart, true);
let state = self.world.block(key.0, key.1, key.2);
if self.prop_is(state, "natural") && !self.creative && !self.spectator() {
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
self.spawn_orbs(
[
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
],
xp,
);
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
/// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`.
fn spawn_protector(&mut self, pos: Pos) -> Option<u32> {
let t = self.res.mob_types.get("minecraft:creaking").cloned()?;
for _ in 0..5 {
let r = &mut self.world.random;
let dx = r.next_int_bound(33).unwrap_or(16) - 16;
let dz = r.next_int_bound(33).unwrap_or(16) - 16;
let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz);
if !self.world.loaded(at.0, at.2) {
continue;
}
// moveToPossibleSpawnPosition: scan down for a collider with room above.
let mut above = self.world.block(at.0, at.1, at.2);
let mut found = false;
for _ in 0..=16 {
at.1 -= 1;
let current = self.world.block(at.0, at.1, at.2);
let facts = self.res.facts.get(current);
let leaves = self
.res
.items
.block_tags
.get("minecraft:leaves")
.is_some_and(|s| s.contains(&*facts.name));
let clear_above = self
.res
.behaviours
.collision_shape(above)
.map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty());
if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 {
at.1 += 1;
found = true;
break;
}
above = current;
}
if !found {
continue;
}
// noCollision(spawn box) and no liquid.
let w = t.width / 2.0;
let bounds = Aabb::new(
horizon_core::geometry::Vec3::new(
f64::from(at.0) + 0.5 - w,
f64::from(at.1),
f64::from(at.2) + 0.5 - w,
),
horizon_core::geometry::Vec3::new(
f64::from(at.0) + 0.5 + w,
f64::from(at.1) + t.height,
f64::from(at.2) + 0.5 + w,
),
);
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
};
let free = scene.unobstructed(bounds).unwrap_or(false);
let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid
!= horizon_client::blocks::Fluid::None;
if !free || wet {
continue;
}
let id = self.spawn_mob(
"minecraft:creaking",
[
f64::from(at.0) + 0.5,
f64::from(at.1),
f64::from(at.2) + 0.5,
],
false,
)?;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
creaking::set_transient(m, [pos.0, pos.1, pos.2]);
}
return Some(id);
}
None
}
/// `CreakingHeartBlockEntity.computeAnalogOutputSignal`.
fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 {
if heart.creaking.is_none() {
return 0;
}
let Some(id) = self.heart_protector(heart) else {
return 0;
};
let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0;
15 - (distance * 15.0).floor() as i32
}
/// `CreakingHeartBlockEntity.serverTick` for every heart.
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_)))
.map(|(k, _)| *k)
.collect();
for key in keys {
let Some(BlockEntity::CreakingHeart(mut heart)) =
self.world.block_entities.remove(&key)
else {
continue;
};
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
// The block is gone: preRemoveSideEffects.
self.heart_remove_protector(&mut heart, false);
continue;
}
if self.heart_state_name(state) != "uprooted" {
self.heart_tick(&mut heart, key, state)?;
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
self.scan_for_hearts();
Ok(())
}
fn heart_tick(
&mut self,
heart: &mut CreakingHeart,
key: Pos,
state: BlockStateId,
) -> Result<()> {
heart.ticks_existed += 1;
let output = self.heart_output(heart, key);
if output != heart.output_signal {
heart.output_signal = output;
self.container_changed(key);
}
if heart.emitter > 0 {
if heart.emitter > 50 {
self.heart_emit(heart, key, 1, true);
self.heart_emit(heart, key, 1, false);
}
if heart.emitter % 10 == 0 && heart.emitter_target.is_some() {
if let Some(id) = self.heart_protector(heart)
&& let Some((c, _)) = self.mob_center(id)
{
heart.emitter_target = Some(c);
}
if let Some(target) = heart.emitter_target {
let center = [
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
f64::from(key.2) + 0.5,
];
let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0;
let at = [
(center[0] - target[0]) * progress + target[0],
(center[1] - target[1]) * progress + target[1],
(center[2] - target[2]) * progress + target[2],
];
let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5;
self.audio
.play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0);
}
}
heart.emitter -= 1;
}
let ticker = heart.ticker;
heart.ticker -= 1;
if ticker >= 0 {
return Ok(());
}
heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20;
// updateCreakingState: logs gone and no creaking means uprooted.
let active = self.creaking_active();
let has_logs = self.with_level(|b, level, ticks| {
b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state)
});
let wanted = if !has_logs && heart.creaking.is_none() {
"uprooted"
} else if active {
"awake"
} else {
"dormant"
};
let mut current = self.heart_state_name(state);
if wanted != current
&& let Some(next) = self.heart_with_state(state, wanted)
{
self.level_set([key.0, key.1, key.2], next)?;
current = wanted.to_owned();
if wanted == "uprooted" {
return Ok(());
}
}
if heart.creaking.is_none() {
if current == "awake" && self.spawning_monsters() {
let near = self.player.as_ref().is_some_and(|p| {
let (dx, dy, dz) = (
p.position.x - (f64::from(key.0) + 0.5),
p.position.y - (f64::from(key.1) + 0.5),
p.position.z - (f64::from(key.2) + 0.5),
);
dx * dx + dy * dy + dz * dz < 32.0 * 32.0
}) && !self.spectator();
if near && let Some(id) = self.spawn_protector(key) {
let uuid = self.uuid_for(id);
heart.creaking = Some((Some(id), uuid));
heart.ticks_existed = 0;
let at = self.mob_center(id).map(|(c, _)| c);
self.audio
.play("minecraft:entity.creaking.spawn", at, 1.0, 1.0);
self.audio.play(
"minecraft:block.creaking_heart.spawn",
Some([
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
f64::from(key.2) + 0.5,
]),
1.0,
1.0,
);
}
}
} else if let Some(id) = self.heart_protector(heart) {
let persistent = self
.mobs
.iter()
.find(|m| m.id == id)
.is_some_and(|m| m.persistent);
let eye = self.player_view().map(|v| v.eye);
let stuck = self
.mobs
.iter_mut()
.find(|m| m.id == id)
.is_some_and(|m| creaking::player_is_stuck(m, eye));
if (!active && !persistent)
|| self.heart_distance_to_creaking(id, key) > TOO_FAR
|| stuck
{
self.heart_remove_protector(heart, false);
}
}
Ok(())
}
fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
s.properties
.insert("creaking_heart_state".to_owned(), wanted.to_owned());
self.res.assets.registry.resolve(&s).ok()
}
/// `ServerLevel.isSpawningMonsters`.
fn spawning_monsters(&self) -> bool {
self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters")
}
/// `EnvironmentAttributes.CREAKING_ACTIVE`.
pub(super) fn creaking_active(&mut self) -> bool {
self.with_level(|b, level, ticks| b.creaking_active(level, ticks))
}
/// Hearts that came with generated or loaded chunks get their block
/// entity (`newBlockEntity`) the first time their chunk is seen.
fn scan_for_hearts(&mut self) {
let Some(heart) = self
.res
.assets
.registry
.default_state("minecraft:creaking_heart")
else {
return;
};
let keys: Vec<(i32, i32)> = self
.world
.chunks
.iter()
.filter(|(k, c)| c.lit && !self.creaking.scanned.contains(k))
.map(|(k, _)| *k)
.collect();
for key in keys {
self.creaking.scanned.insert(key);
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
continue;
};
let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name;
let _ = heart;
for (si, section) in chunk.sections.iter().enumerate() {
if section.is_uniform(0) {
continue;
}
for i in 0..4096 {
let id = section.get(i);
if name(id) != "minecraft:creaking_heart" {
continue;
}
let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32);
let pos = (
key.0 * 16 + lx,
horizon_client::chunk::MIN_Y + si as i32 * 16 + ly,
key.1 * 16 + lz,
);
self.world
.block_entities
.entry(pos)
.or_insert_with(|| BlockEntity::CreakingHeart(Box::default()));
}
}
}
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
self.creaking.scanned.retain(|k| loaded.contains(k));
}
}
/// What the creaking code remembers between ticks.
#[derive(Default)]
pub(super) struct CreakingState {
/// Chunks already scanned for heart blocks.
scanned: HashSet<(i32, i32)>,
}
+123 -4
View File
@@ -93,7 +93,8 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
.full_collision
}
}
fn seen(m: &Mob) -> Seen {
fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
let villager = m.species() == Species::Villager;
Seen {
id: m.id,
species: m.species(),
@@ -102,7 +103,12 @@ fn seen(m: &Mob) -> Seen {
eye_y: m.eye_y(),
alive: m.alive(),
baby: m.is_baby(),
in_love: m.extra.in_love > 0,
// A villager is "in love" when it is willing to breed (`canBreed`).
in_love: if villager {
horizon_client::mobs::villager::can_breed(m)
} else {
m.extra.in_love > 0
},
tame: m.extra.tame,
hostile: m.hostile(),
target: m.ai.target,
@@ -115,6 +121,13 @@ fn seen(m: &Mob) -> Seen {
bed: (m.species() == Species::Villager)
.then_some(m.extra.bed)
.flatten(),
active_raid: horizon_client::mobs::raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => {
horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid))
}
_ => 0,
},
}
}
impl Game<'_> {
@@ -150,6 +163,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)),
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
})
}
/// Biome facts at a position for finalizeSpawn and variant rules.
@@ -191,6 +206,17 @@ impl Game<'_> {
}
/// Create a mob of `kind` at a position, finalized like a natural spawn.
pub(super) fn spawn_mob(&mut self, kind: &str, at: [f64; 3], persistent: bool) -> Option<u32> {
self.spawn_mob_for(kind, at, persistent, false)
}
/// `spawn_mob` for a patrol or raid (`EntitySpawnReason.PATROL` / `EVENT`),
/// which never rolls a patrol leader.
pub(super) fn spawn_mob_for(
&mut self,
kind: &str,
at: [f64; 3],
persistent: bool,
scripted: bool,
) -> Option<u32> {
let kind = if kind.contains(':') {
kind.to_owned()
} else {
@@ -208,6 +234,14 @@ impl Game<'_> {
);
let difficulty = self.local_difficulty(at);
spawning::finalize(&mut mob, &facts, &difficulty);
if !scripted {
let reason = if persistent {
horizon_client::mobs::raider::Reason::Other
} else {
horizon_client::mobs::raider::Reason::Natural
};
horizon_client::mobs::raider::finalize(&mut mob, reason);
}
let id = mob.id;
self.mobs.push(mob);
Some(id)
@@ -259,13 +293,28 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
"food_level": e.food_level,
"inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::<Vec<_>>(),
"gossips": e.gossips.len(),
"last_slept": e.last_slept,
"raid": e.raid,
})),
"raider": horizon_client::mobs::raider::state(m).map(|s| serde_json::json!({
"raid": s.raid_id,
"wave": s.wave,
"leader": s.patrol_leader,
"patrolling": s.patrolling,
"patrol_target": s.patrol_target,
"vehicle": s.vehicle,
})),
})
})
.collect();
serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() })
}
/// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES).
fn motion_top(&self, x: i32, z: i32) -> i32 {
pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 {
let top = if self.dim == Dim::Nether { 127 } else { 319 };
for y in (horizon_client::chunk::MIN_Y..=top).rev() {
let f = self.res.facts.get(self.world.block(x, y, z));
@@ -602,7 +651,10 @@ impl Game<'_> {
}
self.tick_inhabited();
self.spawn_natural();
let snapshot: Vec<Seen> = self.mobs.iter().map(seen).collect();
self.tick_patrol_spawner();
self.tick_raids();
let uuid = self.level.player_uuid;
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
let mut mobs = std::mem::take(&mut self.mobs);
let mut dead = Vec::new();
@@ -625,6 +677,9 @@ impl Game<'_> {
push_apart(&mut mobs);
}
self.mobs.append(&mut mobs);
self.sync_riders();
self.villager_reputation_tick();
self.villager_pickups();
for m in dead {
self.mob_died(&m);
}
@@ -647,6 +702,8 @@ impl Game<'_> {
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
}
self.score_entity_removed(m.id);
self.raider_died(m, by_player);
self.villager_murdered(m, by_player);
let held = self.held().cloned();
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
if !m.is_baby() {
@@ -690,6 +747,11 @@ impl Game<'_> {
for item in gear {
self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10);
}
// AbstractChestedHorse.dropEquipment: the chest contents.
for stack in m.extra.items.clone().into_iter().flatten() {
self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10);
}
self.raider_death_loot(m, pos);
let worn = if horizon_client::mobs::equine::is_equine(m.species()) {
[None, None, None, None]
} else {
@@ -705,6 +767,7 @@ impl Game<'_> {
// Vexes never drop their sword.
if let Some(item) = &item
&& by_player
&& &**item != horizon_client::mobs::raider::BANNER
&& m.species() != Species::Vex
&& self.world.random.next_float() < 0.085
{
@@ -972,6 +1035,36 @@ impl Game<'_> {
}
},
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
MobEvent::CreakingHurt {
home,
by_player,
id,
} => self.creaking_hurt(home, id, by_player),
MobEvent::CreakingTearDown { center, spread } => {
self.creaking_tear_down(center, spread)
}
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
}
MobEvent::ThrowGift { table, from, to } => self.throw_gift(&table, from, to),
MobEvent::PatrolTarget { mob, target } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
horizon_client::mobs::raider::set_patrol_target(m, target);
}
}
MobEvent::RaiderTarget {
mob,
target,
aggressive,
} => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.ai.target = Some(target);
m.ai.aggressive |= aggressive;
}
}
MobEvent::GiftLoot { table, at } => {
let drops =
self.res
@@ -1549,6 +1642,32 @@ impl Game<'_> {
}
}
}
// A witch's healing potions reach the raiders around the splash.
if matches!(
*effect,
"minecraft:instant_health" | "minecraft:regeneration"
) {
let center = at;
for m in &mut self.mobs {
let d2 = m.position.distance_squared(center);
if !m.alive()
|| d2 >= 16.0
|| !horizon_client::mobs::raider::is_raider(m.species())
{
continue;
}
let scale = 1.0 - d2.sqrt() / 4.0;
if *effect == "minecraft:instant_health" {
let heal = (4 << *amplifier) as f64 * scale;
m.health = (m.health + heal as f32).min(m.attrs.max_health);
} else {
let t = (f64::from(*ticks) * scale + 0.5) as i32;
if t > 20 {
m.add_effect(effect, t, *amplifier);
}
}
}
}
self.audio.play(
"minecraft:entity.splash_potion.break",
Some(atp),
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1842,7 +1842,8 @@ impl Game<'_> {
/// The boss bar (`BossHealthOverlay`): name and the pink progress bar.
pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) {
let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End);
self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
self.draw_raid_bar(batch, y);
let Some(d) = dragon else {
return;
};
+28 -6
View File
@@ -24,6 +24,9 @@ pub(super) struct Rocket {
explosions: Vec<FireworkExplosion>,
/// Boosting the player (attachedToEntity).
attached: bool,
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
/// the first block it hits.
angled: bool,
icon: Option<String>,
}
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
@@ -34,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
.unwrap_or((1, Vec::new()))
}
impl Game<'_> {
fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
let (flight, explosions) = fireworks_of(stack);
let r = &mut self.world.random;
let tri = |r: &mut horizon_core::random::LegacyRandom| {
@@ -52,6 +55,7 @@ impl Game<'_> {
lifetime,
explosions,
attached,
angled: false,
icon: Some("item/firework_rocket".into()),
}
}
@@ -73,6 +77,13 @@ impl Game<'_> {
self.swing_arm();
true
}
/// `FireworkRocketItem.asProjectile` shot out of a dispenser.
pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
let mut rocket = self.new_rocket(at, stack, false);
rocket.velocity = velocity;
rocket.angled = true;
self.rockets.push(rocket);
}
/// `FireworkRocketItem.use` while gliding: a rocket attached to the player.
pub(super) fn boost_firework(&mut self, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:firework_rocket"
@@ -118,12 +129,23 @@ impl Game<'_> {
Vec3::new(r.position.x - h, r.position.y, r.position.z - h),
Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h),
);
let wanted = Vec3::new(
r.velocity.x * 1.15,
r.velocity.y + 0.04,
r.velocity.z * 1.15,
);
let wanted = if r.angled {
r.velocity
} else {
Vec3::new(
r.velocity.x * 1.15,
r.velocity.y + 0.04,
r.velocity.z * 1.15,
)
};
if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) {
let blocked = (moved.x - wanted.x).abs() > 1e-7
|| (moved.y - wanted.y).abs() > 1e-7
|| (moved.z - wanted.z).abs() > 1e-7;
if r.angled && blocked {
// hitTargetOrDeflectSelf: explode on the block.
r.life = r.lifetime;
}
let horizontal =
(moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7;
r.position = Vec3::new(
+82
View File
@@ -0,0 +1,82 @@
//! Building golems from blocks (`CarvedPumpkinBlock.trySpawnGolem`): a carved
//! pumpkin or jack o'lantern on two snow blocks makes a snow golem, and on a
//! T of four iron blocks (arms along X or Z, nothing beside the legs) an iron
//! golem. Players placing the pumpkin and dispensers share it.
use super::Game;
use horizon_client::Result;
impl Game<'_> {
fn golem_block(&self, p: [i32; 3]) -> &str {
let state = self.world.block(p[0], p[1], p[2]);
&self.res.facts.get(state).name
}
fn is_golem_head(&self, p: [i32; 3]) -> bool {
matches!(
self.golem_block(p),
"minecraft:carved_pumpkin" | "minecraft:jack_o_lantern"
)
}
/// The blocks of the golem whose head is at `head` and its spawn base
/// (`BlockPattern.find`), snow golems first.
fn find_golem(&self, head: [i32; 3]) -> Option<(&'static str, Vec<[i32; 3]>, [i32; 3])> {
let below = |n: i32| [head[0], head[1] - n, head[2]];
if self.golem_block(below(1)) == "minecraft:snow_block"
&& self.golem_block(below(2)) == "minecraft:snow_block"
{
return Some((
"minecraft:snow_golem",
vec![head, below(1), below(2)],
below(2),
));
}
for (ax, az) in [(1, 0), (0, 1)] {
let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s];
let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block");
let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2]));
if arms
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
{
let mut blocks = vec![head];
blocks.extend((-1..=1).map(|s| side(s, 1)));
blocks.push(side(0, 2));
return Some(("minecraft:iron_golem", blocks, side(0, 2)));
}
}
None
}
/// `CarvedPumpkinBlock.canSpawnGolem`.
pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool {
self.find_golem(head).is_some()
}
/// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed.
pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> {
if !self.is_golem_head(head) {
return Ok(());
}
let Some((kind, blocks, base)) = self.find_golem(head) else {
return Ok(());
};
for p in blocks {
let state = self.world.block(p[0], p[1], p[2]);
self.destroy_particles(p, state);
self.level_set(p, self.world.air)?;
}
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.05,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob(kind, at, false)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
m.previous_yaw = 0.0;
m.previous_body_yaw = 0.0;
m.previous_head_yaw = 0.0;
}
Ok(())
}
}
+415
View File
@@ -0,0 +1,415 @@
//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a
//! banner with a dye (and a pattern item for the special patterns), the
//! six-layer limit, the scrolling pattern list and the banner preview.
use super::{
Game,
stations::{INPUT, Station},
};
use horizon_client::{
banner::{self, BannerLayer},
hud::{HudBatch, Rect, rgba},
items::ItemStack,
};
use std::sync::Arc;
/// Per-menu loom state: `selectablePatterns`, the selected index and the
/// screen's scroller.
#[derive(Default)]
pub(super) struct LoomState {
pub(super) patterns: Vec<Arc<str>>,
pub(super) selected: Option<usize>,
/// `displayPatterns`: the pattern buttons are shown.
pub(super) display: bool,
pub(super) has_max: bool,
pub(super) scroll: f32,
pub(super) start_row: usize,
pub(super) scrolling: bool,
}
impl LoomState {
fn total_rows(&self) -> usize {
self.patterns.len().div_ceil(4)
}
fn offscreen_rows(&self) -> i32 {
self.total_rows() as i32 - 4
}
fn scroll_active(&self) -> bool {
self.display && self.patterns.len() > 16
}
/// `startRow` for a scroller position.
fn row_for(&self, offs: f32) -> usize {
((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize
}
}
const BUTTON: f32 = 14.0;
fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool {
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
}
/// A sub-rectangle of a sprite given in texels.
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
Rect {
u0: r.u0 + x * du,
v0: r.v0 + y * dv,
u1: r.u0 + (x + w) * du,
v1: r.v0 + (y + h) * dv,
w: w as u32,
h: h as u32,
}
}
/// A dye's tint as a HUD vertex colour.
pub(super) fn dye_color(name: &str) -> u32 {
let c = banner::dye_rgb(name);
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255)
}
impl Game<'_> {
/// `LoomMenu.slotsChanged` and the screen's `containerChanged`.
pub(super) fn loom_changed(&self, s: &mut Station) {
let banners = &self.res.stations.banners;
let items = &self.res.items;
let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref());
let l = &mut s.loom;
let mut result = None;
if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) {
let valid = l.selected.is_some_and(|i| i < l.patterns.len());
let previous = std::mem::take(&mut l.patterns);
l.patterns = banners.selectable(s.inputs[2].as_ref());
let shown = if l.patterns.len() == 1 {
l.selected = Some(0);
Some(l.patterns[0].clone())
} else if !valid {
l.selected = None;
None
} else {
let value = previous[l.selected.unwrap_or(0)].clone();
match l.patterns.iter().position(|p| *p == value) {
Some(i) => {
l.selected = Some(i);
Some(value)
}
None => {
l.selected = None;
None
}
}
};
l.has_max = banner::has_max_layers(banner_stack);
if let Some(pattern) = shown {
if l.has_max {
l.selected = None;
} else if let Some(dye) = banners.loom_dye(items, dye_stack) {
result = Some(banner::loom_result(banner_stack, &dye, &pattern));
}
}
l.display = !l.has_max && !l.patterns.is_empty();
} else {
l.patterns.clear();
l.selected = None;
l.has_max = banner_in.is_some_and(banner::has_max_layers);
l.display = false;
}
if l.start_row >= l.total_rows() {
l.start_row = 0;
l.scroll = 0.0;
}
s.result = result;
}
/// The loom slots' `mayPlace`.
pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) {
let banners = &self.res.stations.banners;
let ok = match input {
0 => stack.item.ends_with("_banner"),
1 => banners.loom_dye(&self.res.items, stack).is_some(),
_ => banners.is_pattern_item(&self.res.items, stack),
};
(ok, 64)
}
/// The result slot's `onTake`: one banner and one dye are used up.
pub(super) fn loom_taken(&mut self, s: &mut Station) {
for slot in &mut s.inputs[..2] {
if let Some(x) = slot.as_mut() {
x.count -= 1;
if x.count == 0 {
*slot = None;
}
}
}
if s.inputs[0].is_none() || s.inputs[1].is_none() {
s.loom.selected = None;
}
if s.last_sound != self.ticks {
s.last_sound = self.ticks;
let pos = s.pos;
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio
.play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0);
}
}
/// `LoomMenu.quickMoveStack` from an inventory slot.
pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool {
let banners = &self.res.stations.banners;
let items = &self.res.items;
let target = if stack.item.ends_with("_banner") {
Some(INPUT)
} else if banners.loom_dye(items, stack).is_some() {
Some(INPUT + 1)
} else if banners.is_pattern_item(items, stack) {
Some(INPUT + 2)
} else {
None
};
match target {
Some(t) => self.move_to(stack, &[t], false),
None if (9..36).contains(&slot) => {
let hotbar: Vec<usize> = (0..9).collect();
self.move_to(stack, &hotbar, false)
}
None if slot < 9 => {
let main: Vec<usize> = (9..36).collect();
self.move_to(stack, &main, false)
}
None => false,
}
}
/// A left click inside the loom's pattern grid or scroller.
pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool {
let Some(s) = self.station.as_ref() else {
return false;
};
let l = &s.loom;
if !l.display {
return false;
}
for row in 0..4 {
for column in 0..4 {
let index = (row + l.start_row) * 4 + column;
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) {
if let Some(s) = self.station.as_mut() {
s.loom.selected = Some(index);
}
self.audio
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
self.station_changed();
return true;
}
}
}
if inside(local, 119.0, 9.0, 12.0, 56.0)
&& let Some(s) = self.station.as_mut()
{
s.loom.scrolling = true;
return true;
}
false
}
/// `LoomScreen.mouseDragged` on the scroller.
pub(super) fn loom_drag(&mut self) {
let Some(size) = self
.renderer
.as_ref()
.map(|r| [r.config.width, r.config.height])
else {
return;
};
let (_, oy) = self.inventory_origin(&HudBatch::new(size));
let cursor_y = self.cursor.1;
let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else {
return;
};
if l.scrolling && l.display && l.offscreen_rows() > 0 {
let top = oy + 13.0;
l.scroll = ((cursor_y - top - 7.5) / (56.0 - 15.0)).clamp(0.0, 1.0);
l.start_row = l.row_for(l.scroll);
}
}
pub(super) fn loom_release(&mut self) {
if let Some(s) = self.station.as_mut() {
s.loom.scrolling = false;
}
}
/// `LoomScreen.mouseScrolled`.
pub(super) fn loom_scroll(&mut self, d: f32) {
let Some(l) = self.station.as_mut().map(|s| &mut s.loom) else {
return;
};
let offscreen = l.offscreen_rows();
if l.display && offscreen > 0 {
l.scroll = (l.scroll - d / offscreen as f32).clamp(0.0, 1.0);
l.start_row = l.row_for(l.scroll);
}
}
/// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1))
/// drawn flat: the cloth, the base colour and every layer.
pub(super) fn draw_flag(
&self,
batch: &mut HudBatch,
rect: [f32; 4],
base: &str,
layers: &[BannerLayer],
) {
let banners = &self.res.stations.banners;
let mut paint = |name: &str, color: u32| {
if let Some(r) = self.res.atlas.sprites.get(name).copied() {
let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]);
batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color);
}
};
paint("entity/banner/banner_base", u32::MAX);
paint("entity/banner/base", dye_color(base));
for layer in layers.iter().take(16) {
paint(
&banners.banner_texture(&layer.pattern),
dye_color(&layer.color),
);
}
}
/// `LoomScreen.extractBackground` after the background; returns the
/// pattern name tooltip of the hovered button.
pub(super) fn draw_loom(
&mut self,
batch: &mut HudBatch,
ox: f32,
oy: f32,
local: (f32, f32),
) -> Option<Vec<(String, u32)>> {
let s = self.station.as_ref()?;
let l = &s.loom;
let atlas = &self.res.atlas;
for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() {
if s.inputs[i].is_none() {
let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i];
batch.sprite(
atlas,
&format!("gui/sprites/container/slot/{icon}"),
ox + pos.0,
oy + pos.1,
);
}
}
let scroller = if l.scroll_active() {
"scroller"
} else {
"scroller_disabled"
};
batch.sprite(
atlas,
&format!("gui/sprites/container/loom/{scroller}"),
ox + 119.0,
oy + 13.0 + (41.0 * l.scroll).floor(),
);
let result = s.result.clone();
let (display, has_max, start_row, selected) =
(l.display, l.has_max, l.start_row, l.selected);
let patterns = l.patterns.clone();
let dye = s.inputs[1]
.as_ref()
.and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d))
.unwrap_or_else(|| Arc::from("white"));
if let Some(result) = result.filter(|_| !has_max)
&& let Some(base) = banner::banner_color(&result.item)
{
self.draw_flag(
batch,
[ox + 141.0, oy + 8.0, 20.0, 40.0],
base,
banner::layers(&result),
);
} else if has_max {
batch.sprite(
&self.res.atlas,
"gui/sprites/container/loom/error",
ox + 138.0,
oy + 52.0,
);
}
let mut tooltip = None;
if display {
let atlas = &self.res.atlas;
for row in 0..4 {
for column in 0..4 {
let index = (row + start_row) * 4 + column;
let Some(pattern) = patterns.get(index) else {
return tooltip;
};
let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON);
let hover = inside(local, x, y, BUTTON, BUTTON);
let sprite = if selected == Some(index) {
"pattern_selected"
} else if hover {
let key = self
.res
.stations
.banners
.layer_key(&BannerLayer::new(pattern, &dye));
tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]);
"pattern_highlighted"
} else {
"pattern"
};
batch.sprite(
atlas,
&format!("gui/sprites/container/loom/{sprite}"),
ox + x,
oy + y,
);
// extractBannerOnButton: a 5x10 grey cloth with the pattern.
batch.fill(
atlas,
ox + x + 4.0,
oy + y + 2.0,
5.0,
10.0,
dye_color("gray"),
);
let texture = self.res.stations.banners.banner_texture(pattern);
if let Some(r) = atlas.sprites.get(&texture).copied() {
let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]);
batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX);
}
}
}
}
tooltip
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scroller_rows_follow_the_offset() {
let l = LoomState {
patterns: (0..40)
.map(|i| Arc::from(format!("p{i}").as_str()))
.collect(),
display: true,
..Default::default()
};
// 40 patterns = 10 rows, 6 off screen.
assert_eq!(l.offscreen_rows(), 6);
assert!(l.scroll_active());
assert_eq!(l.row_for(0.0), 0);
assert_eq!(l.row_for(1.0), 6);
assert_eq!(l.row_for(0.5), 3);
}
#[test]
fn few_patterns_do_not_scroll() {
let l = LoomState {
patterns: (0..16)
.map(|i| Arc::from(format!("p{i}").as_str()))
.collect(),
display: true,
..Default::default()
};
assert!(!l.scroll_active());
assert_eq!(l.offscreen_rows(), 0);
}
}
+48 -385
View File
@@ -3,18 +3,15 @@
//! the vanilla dispense behaviours Horizon has entities for, and container
//! comparator signals (`AbstractContainerMenu.getRedstoneSignalFromContainer`).
use super::Game;
mod crafter;
use horizon_client::{
Result,
containers::BlockEntity,
entities::Arrow,
items::{ItemStack, Items},
world::World,
};
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
use horizon_world::{level::Behaviours, registry::BlockStateId};
type Pos = (i32, i32, i32);
@@ -40,6 +37,8 @@ enum Kind {
/// `AbstractFurnaceBlockEntity` (a `WorldlyContainer`).
Furnace,
Hopper,
/// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule.
Crafter,
}
/// A container: one block entity, or a double chest (`CompoundContainer`).
@@ -72,11 +71,6 @@ impl View {
}
}
thread_local! {
/// Entity-owned randomness (projectile spread), separate from the level random.
static ENTITY_RANDOM: std::cell::RefCell<LegacyRandom> = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45));
}
fn dir_from_name(name: &str) -> Option<Direction> {
Some(match name {
"down" => Direction::Down,
@@ -145,6 +139,7 @@ impl Containers<'_> {
let name = self.name(state);
let kind = match (entity, name) {
(BlockEntity::Furnace(_), _) => Kind::Furnace,
(BlockEntity::Crafter(_), _) => Kind::Crafter,
(_, "minecraft:hopper") => Kind::Hopper,
_ => Kind::Generic,
};
@@ -212,6 +207,12 @@ impl Containers<'_> {
}
/// `Container.canPlaceItem` (+ `canPlaceItemThroughFace` for furnaces).
fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool {
if view.kind == Kind::Crafter {
return match self.world.block_entities.get(&view.parts[0].0) {
Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)),
_ => false,
};
}
if view.kind != Kind::Furnace {
return true;
}
@@ -246,6 +247,13 @@ impl Containers<'_> {
}
/// `AbstractContainerMenu.getRedstoneSignalFromContainer`.
fn signal(&self, view: &View) -> i32 {
if view.kind == Kind::Crafter {
// CrafterBlockEntity.getRedstoneSignal: filled or disabled slots.
return match self.world.block_entities.get(&view.parts[0].0) {
Some(BlockEntity::Crafter(c)) => c.redstone_signal(),
_ => 0,
};
}
let mut total = 0.0f32;
for i in 0..view.len() {
if let Some(s) = self.get(view, i) {
@@ -304,10 +312,16 @@ impl Game<'_> {
if pos.1 == super::minecarts::CART_KEY_Y {
return;
}
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
self.with_level(|b, level, ticks| {
b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2))
});
// A double chest's other half changes with it.
let halves: Vec<Pos> = std::iter::once(pos)
.chain(self.chest_other_half(pos))
.collect();
for pos in halves {
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
self.with_level(|b, level, ticks| {
b.container_changed(level, ticks, BlockPos::new(pos.0, pos.1, pos.2))
});
}
}
/// `HopperBlockEntity.tryMoveInItem`.
fn try_move_in_item(
@@ -567,6 +581,9 @@ impl Game<'_> {
pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
let key = (pos.x, pos.y, pos.z);
let name = self.res.facts.get(state).name.clone();
if &*name == "minecraft:crafter" {
return self.crafter_dispense(pos, state);
}
let dropper = &*name == "minecraft:dropper";
if !dropper && &*name != "minecraft:dispenser" {
return Ok(());
@@ -585,14 +602,8 @@ impl Game<'_> {
odds += 1;
}
}
let center = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z) + 0.5,
];
let Some(slot) = slot else {
self.audio
.play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2);
self.dispenser_event(1001, key, 0);
return Ok(());
};
let Some(facing) = self
@@ -608,7 +619,7 @@ impl Game<'_> {
let target = offset(key, facing);
let remaining = if dropper {
match self.containers().view(target, false) {
None => self.default_dispense(key, facing, stack),
None => self.dispense_default(key, facing, stack),
Some(into) => {
let one = ItemStack {
count: 1,
@@ -630,7 +641,7 @@ impl Game<'_> {
}
}
} else {
self.dispense_behaviour(key, facing, stack)?
self.dispense_item(key, facing, stack)?
};
if let Some(entry) = self.slot_mut_at(&view, slot) {
*entry = remaining;
@@ -638,367 +649,6 @@ impl Game<'_> {
self.container_changed(key);
Ok(())
}
/// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke.
fn default_dispense(
&mut self,
pos: Pos,
facing: Direction,
mut stack: ItemStack,
) -> Option<ItemStack> {
let one = ItemStack {
count: 1,
..stack.clone()
};
stack.count -= 1;
self.spawn_dispensed(pos, facing, one, 6);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
(stack.count > 0).then_some(stack)
}
fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) {
let center = [
f64::from(pos.0) + 0.5,
f64::from(pos.1) + 0.5,
f64::from(pos.2) + 0.5,
];
self.audio.play(sound, Some(center), 1.0, pitch);
}
/// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`.
fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) {
let s = step(facing);
let mut at = [
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]),
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
];
at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 };
let r = &mut self.world.random;
// new ItemEntity(level, x, y, z, stack): its default motion draws first.
let _ = (r.next_double(), r.next_double());
let pow = r.next_double() * 0.1 + 0.2;
let spread = 0.017_227_5 * f64::from(accuracy);
let v = [
r.triangle(f64::from(s[0]) * pow, spread),
r.triangle(0.2, spread),
r.triangle(f64::from(s[2]) * pow, spread),
];
self.spawn_item(stack, at, v, 0);
}
/// `DefaultDispenseItemBehavior.consumeWithRemainder`.
fn consume_with_remainder(
&mut self,
pos: Pos,
facing: Direction,
mut stack: ItemStack,
remainder: ItemStack,
) -> Option<ItemStack> {
stack.count -= 1;
if stack.count == 0 {
return Some(remainder);
}
// DispenserBlockEntity.insertItem, then drop what does not fit.
let mut rest = remainder;
if let Some(view) = self.containers().view(pos, false) {
let max = self.containers().max_stack(&rest);
for i in 0..view.len() {
let Some(entry) = self.slot_mut_at(&view, i) else {
continue;
};
match entry {
None => {
let n = rest.count.min(max);
*entry = Some(ItemStack {
count: n,
..rest.clone()
});
rest.count -= n;
}
Some(e) if e.item == rest.item && e.damage == rest.damage => {
let n = rest.count.min(max.saturating_sub(e.count));
e.count += n;
rest.count -= n;
}
Some(_) => {}
}
if rest.count == 0 {
break;
}
}
}
if rest.count > 0 {
self.spawn_dispensed(pos, facing, rest, 6);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
}
Some(stack)
}
/// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`.
fn dispense_behaviour(
&mut self,
pos: Pos,
facing: Direction,
stack: ItemStack,
) -> Result<Option<ItemStack>> {
let target = offset(pos, facing);
let target_pos = BlockPos::new(target.0, target.1, target.2);
let item = stack.item.to_string();
let result = match item.as_str() {
"minecraft:bone_meal" => {
let grown = self.with_level(|b, level, ticks| {
b.grow_crop(level, ticks, target_pos)
|| b.grow_water_plant(level, ticks, target_pos, None)
});
self.process_level_events()?;
if grown {
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.audio.play(
"minecraft:item.bone_meal.use",
Some([
f64::from(target.0) + 0.5,
f64::from(target.1) + 0.5,
f64::from(target.2) + 0.5,
]),
1.0,
1.0,
);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
} else {
self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2);
Some(stack)
}
}
"minecraft:tnt" => {
self.spawn_primed_tnt(target_pos, false);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
}
"minecraft:flint_and_steel" => {
let target_state = self.world.block(target.0, target.1, target.2);
let target_name = self.res.facts.get(target_state).name.clone();
let fire = self.res.assets.registry.default_state("minecraft:fire");
let success = if self.res.facts.is_air(target_state)
&& let Some(fire) = fire
&& self
.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire))
{
self.level_set([target.0, target.1, target.2], fire)?;
true
} else if &*target_name == "minecraft:tnt" {
self.spawn_primed_tnt(target_pos, false);
self.with_level(|b, level, ticks| {
b.remove_block(level, ticks, target_pos, false)
});
self.process_level_events()?;
true
} else if self.containers().prop(target_state, "lit") == Some("false")
&& (target_name.contains("campfire") || target_name.contains("candle"))
&& self.containers().prop(target_state, "waterlogged") != Some("true")
{
let lit = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("lit".into(), "true".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(lit) = lit {
self.level_set([target.0, target.1, target.2], lit)?;
}
true
} else {
false
};
self.dispenser_sound(
pos,
if success {
"minecraft:block.dispenser.dispense"
} else {
"minecraft:block.dispenser.fail"
},
if success { 1.0 } else { 1.2 },
);
let mut stack = stack;
if success {
stack.damage += 1;
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
if max > 0 && stack.damage >= max {
return Ok(None);
}
}
Some(stack)
}
"minecraft:water_bucket" | "minecraft:lava_bucket" => {
let fluid = if item == "minecraft:water_bucket" {
"minecraft:water"
} else {
"minecraft:lava"
};
let target_state = self.world.block(target.0, target.1, target.2);
let f = self.res.facts.get(target_state).clone();
let waterloggable = item == "minecraft:water_bucket"
&& self.containers().prop(target_state, "waterlogged") == Some("false");
if waterloggable {
let wet = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("waterlogged".into(), "true".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(wet) = wet {
self.level_set([target.0, target.1, target.2], wet)?;
}
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: "minecraft:bucket".into(),
count: 1,
damage: 0,
extra: None,
},
)
} else if (self.res.facts.is_air(target_state) || f.replaceable)
&& !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid)
&& let Some(source) = self.res.assets.registry.default_state(fluid)
{
self.level_set([target.0, target.1, target.2], source)?;
let sound = if fluid == "minecraft:water" {
"minecraft:item.bucket.empty"
} else {
"minecraft:item.bucket.empty_lava"
};
self.audio.play(
sound,
Some([
f64::from(target.0) + 0.5,
f64::from(target.1) + 0.5,
f64::from(target.2) + 0.5,
]),
1.0,
1.0,
);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: "minecraft:bucket".into(),
count: 1,
damage: 0,
extra: None,
},
)
} else {
self.default_dispense(pos, facing, stack)
}
}
"minecraft:bucket" => {
let target_state = self.world.block(target.0, target.1, target.2);
let f = self.res.facts.get(target_state).clone();
let picked = if f.waterlogged
&& self.containers().prop(target_state, "waterlogged") == Some("true")
{
let dry = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("waterlogged".into(), "false".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(dry) = dry {
self.level_set([target.0, target.1, target.2], dry)?;
}
Some("minecraft:water_bucket")
} else if f.fluid_level == 8
&& !f.fluid_falling
&& matches!(&*f.name, "minecraft:water" | "minecraft:lava")
{
self.level_set([target.0, target.1, target.2], self.world.air)?;
Some(if &*f.name == "minecraft:water" {
"minecraft:water_bucket"
} else {
"minecraft:lava_bucket"
})
} else if &*f.name == "minecraft:powder_snow" {
self.level_set([target.0, target.1, target.2], self.world.air)?;
Some("minecraft:powder_snow_bucket")
} else {
None
};
match picked {
Some(filled) => {
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: filled.into(),
count: 1,
damage: 0,
extra: None,
},
)
}
None => self.default_dispense(pos, facing, stack),
}
}
"minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => {
// ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up.
let s = step(facing);
let at = Vec3::new(
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1,
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
);
let spread = 0.017_227_5 * 6.0;
let v = ENTITY_RANDOM.with(|r| {
let r = &mut *r.borrow_mut();
[
(f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1,
(f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1,
(f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1,
]
});
self.arrows.push(Arrow {
from_player: true,
critical: false,
position: at,
previous: at,
velocity: Vec3::new(v[0], v[1], v[2]),
stuck: false,
age: 0,
base_damage: 2.0,
});
self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
}
_ => self.default_dispense(pos, facing, stack),
};
Ok(result)
}
}
// ---- hopper, dispenser and dropper screens ----
@@ -1035,6 +685,13 @@ impl Game<'_> {
{
return super::beacon::HEIGHT;
}
if let Some(rows) = self.chest_rows() {
// ContainerScreen: 114 + 18 per row.
return 114.0 + rows as f32 * 18.0;
}
if self.container_block_is_shulker() {
return 167.0;
}
if self.machine_screen() == Some(Screen::Hopper) {
133.0
} else {
@@ -1070,7 +727,13 @@ impl Game<'_> {
return false;
};
let atlas = &self.res.atlas;
let key_is_cart = self
.container
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
let (texture, height, title) = match screen {
Screen::Hopper if key_is_cart => {
("gui/container/hopper", 133.0, "Minecart with Hopper")
}
Screen::Hopper => ("gui/container/hopper", 133.0, "Item Hopper"),
Screen::Dispenser => ("gui/container/dispenser", 166.0, "Dispenser"),
Screen::Dropper => ("gui/container/dispenser", 166.0, "Dropper"),
@@ -0,0 +1,432 @@
//! The crafter (`CrafterBlock`, `CrafterBlockEntity`, `CrafterMenu`,
//! `CrafterScreen`): redstone-triggered crafting of its 3x3 grid, ejecting
//! the result and remainders into the container in front or as items, the
//! crafting animation ticks, and the menu with its toggleable slots.
use super::*;
use horizon_client::{
advancements as adv,
containers::Crafter,
hud::{HudBatch, rgba},
particles::{ParticleOptions, ParticleType},
};
use serde_json::Value;
/// `CrafterBlock`'s crafting animation length.
const CRAFTING_TICKS: i32 = 6;
const RESULT_SLOT: usize = 309;
fn center(pos: Pos) -> [f64; 3] {
[
f64::from(pos.0) + 0.5,
f64::from(pos.1) + 0.5,
f64::from(pos.2) + 0.5,
]
}
/// Whether an advancement condition's `recipes` entry names the recipe.
fn recipe_matches(condition: &Value, id: &str) -> bool {
match condition {
Value::String(s) => s == id,
Value::Array(list) => list.iter().any(|v| v.as_str() == Some(id)),
_ => true,
}
}
impl Game<'_> {
/// `Level.setBlock` of one boolean property of the block at `pos`.
fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) {
let registry = self.res.assets.registry;
let old = self.world.block(pos.0, pos.1, pos.2);
let Some(mut state) = registry.state(old).cloned() else {
return;
};
if !state.properties.contains_key(key) {
return;
}
state.properties.insert(key.to_owned(), value.to_string());
let Ok(id) = registry.resolve(&state) else {
return;
};
self.with_level(|b, level, ticks| {
b.set_block(level, ticks, BlockPos::new(pos.0, pos.1, pos.2), id, flags)
});
let _ = self.process_level_events();
}
fn crafter_at(&self, pos: Pos) -> Option<&Crafter> {
match self.world.block_entities.get(&pos)? {
BlockEntity::Crafter(c) => Some(c),
_ => None,
}
}
/// `CrafterBlockEntity.serverTick` for every crafter, and the powered
/// flag following the block state.
pub(in crate::game) fn tick_crafters(&mut self) {
let positions: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
.map(|(p, _)| *p)
.collect();
for pos in positions {
let state = self.world.block(pos.0, pos.1, pos.2);
let triggered = self.containers().prop(state, "triggered") == Some("true");
let mut finished = false;
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
c.triggered = triggered;
let remaining = c.crafting_ticks - 1;
if remaining >= 0 {
c.crafting_ticks = remaining;
finished = remaining == 0;
}
}
if finished {
self.set_bool_prop(
pos,
"crafting",
false,
horizon_world::level::flags::UPDATE_ALL,
);
}
}
}
/// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse).
pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
let key = (pos.x, pos.y, pos.z);
let Some(crafter) = self.crafter_at(key) else {
return Ok(());
};
let grid: Vec<Option<ItemStack>> = crafter.items.to_vec();
let found = self
.res
.recipes
.find(&grid, 3)
.map(|(name, result)| (name.to_owned(), result))
.filter(|(_, result)| result.count > 0);
let Some((recipe, result)) = found else {
// LevelEvent 1050: CRAFTER_FAIL.
self.audio
.play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0);
return Ok(());
};
let Some(facing) = self
.containers()
.prop(state, "orientation")
.and_then(|o| o.split('_').next())
.and_then(dir_from_name)
else {
return Ok(());
};
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) {
c.crafting_ticks = CRAFTING_TICKS;
}
self.set_bool_prop(
key,
"crafting",
true,
horizon_world::level::flags::UPDATE_CLIENTS,
);
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
}
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&key) {
for slot in c.items.iter_mut() {
if let Some(s) = slot {
s.count -= 1;
if s.count == 0 {
*slot = None;
}
}
}
}
self.container_changed(key);
Ok(())
}
/// `CrafterBlock.dispenseItem`: into the container in front, else out as an item.
fn crafter_eject(&mut self, pos: Pos, facing: Direction, stack: ItemStack, recipe: &str) {
let target = offset(pos, facing);
let mut rest = stack;
if let Some(into) = self.containers().view(target, false) {
let one_by_one = self.crafter_at(target).is_some()
|| rest.count > self.containers().max_stack(&rest);
while rest.count > 0 {
let before = rest.count;
if one_by_one {
let one = ItemStack {
count: 1,
..rest.clone()
};
if self
.add_item(None, &into, one, Some(facing.opposite()))
.is_some()
{
break;
}
rest.count -= 1;
} else {
match self.add_item(None, &into, rest.clone(), Some(facing.opposite())) {
Some(left) => rest = left,
None => rest.count = 0,
}
if rest.count == before {
break;
}
}
}
}
if rest.count == 0 {
return;
}
self.spawn_dispensed(pos, facing, rest, 6);
// LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front).
self.audio
.play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0);
let s = step(facing);
for _ in 0..10 {
let r = &mut self.world.random;
let pow = r.next_double() * 0.2 + 0.01;
let at = [
f64::from(pos.0)
+ f64::from(s[0]) * 0.6
+ 0.5
+ f64::from(s[0]) * 0.01
+ (r.next_double() - 0.5) * f64::from(s[2]) * 0.5,
f64::from(pos.1)
+ f64::from(s[1]) * 0.6
+ 0.5
+ f64::from(s[1]) * 0.01
+ (r.next_double() - 0.5) * f64::from(s[1]) * 0.5,
f64::from(pos.2)
+ f64::from(s[2]) * 0.6
+ 0.5
+ f64::from(s[2]) * 0.01
+ (r.next_double() - 0.5) * f64::from(s[0]) * 0.5,
];
let v = [
f64::from(s[0]) * pow + r.next_gaussian() * 0.01,
f64::from(s[1]) * pow + r.next_gaussian() * 0.01,
f64::from(s[2]) * pow + r.next_gaussian() * 0.01,
];
self.particles
.add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v);
}
// CrafterRecipeCraftedTrigger for players within the 17-block box.
let near = self.eye_position().is_some_and(|e| {
let c = center(pos);
(0..3).all(|i| (e[i] - c[i]).abs() <= 8.5 + 1.0)
});
if near {
let id = format!("minecraft:{recipe}");
let me = self.player_entity();
self.trigger("minecraft:crafter_recipe_crafted", move |c, w| {
let ctx = adv::Entities {
this: Some(&me),
origin: me.position,
tool: None,
block_pos: None,
};
adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id)
});
}
}
// ---- the menu ----
/// The grid's current recipe result (`CrafterMenu.refreshRecipeResult`).
pub(in crate::game) fn crafter_result(&self) -> Option<ItemStack> {
let key = self.container?;
let c = self.crafter_at(key)?;
self.res.recipes.craft(&c.items, 3)
}
fn crafter_open(&self) -> bool {
matches!(self.container_kind(), Some(BlockEntity::Crafter(_)))
}
/// `CrafterMenu` slot layout: the grid at (26, 17), the result at (134, 35).
pub(in crate::game) fn crafter_slot_position(&self, i: usize) -> Option<(f32, f32)> {
if !self.crafter_open() {
return None;
}
match i {
300..309 => Some((
26.0 + ((i - 300) % 3) as f32 * 18.0,
17.0 + ((i - 300) / 3) as f32 * 18.0,
)),
RESULT_SLOT => Some((134.0, 35.0)),
_ => None,
}
}
/// `CrafterScreen`'s background, title, disabled slots and powered arrow.
pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else {
return;
};
let atlas = &self.res.atlas;
batch.sprite_region(
atlas,
"gui/container/crafter",
[ox, oy, 176.0, 166.0],
256.0,
256.0,
);
let grey = rgba(64, 64, 64, 255);
let title = self.translate("container.crafter", "Crafter");
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
&title,
ox + (176.0 - tw) / 2.0,
oy + 6.0,
grey,
false,
);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
for slot in 0..9 {
if c.disabled[slot] {
let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default();
batch.sprite(
atlas,
"gui/sprites/container/crafter/disabled_slot",
ox + x - 1.0,
oy + y - 1.0,
);
}
}
let powered = self
.container
.map(|k| self.world.block(k.0, k.1, k.2))
.is_some_and(|state| self.containers().prop(state, "triggered") == Some("true"));
let arrow = if powered {
"powered_redstone"
} else {
"unpowered_redstone"
};
batch.sprite(
atlas,
&format!("gui/sprites/container/crafter/{arrow}"),
ox + 97.0,
oy + 35.0,
);
}
/// `gui.togglable_slot` over an empty, enabled grid slot.
pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option<String> {
let c = self.container.and_then(|k| self.crafter_at(k))?;
let i = slot.checked_sub(300).filter(|i| *i < 9)?;
(self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator())
.then(|| self.translate("gui.togglable_slot", "Click to disable slot"))
}
/// A click in the crafter menu before the generic handling; true when
/// it was fully handled (the result, shift-clicks).
pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool {
if !self.crafter_open() {
return false;
}
if slot == RESULT_SLOT {
return true;
}
if (300..309).contains(&slot) {
// CrafterScreen.slotClicked: toggle an empty slot.
let i = slot - 300;
if !shift && !self.spectator() && self.slot_mut(slot).is_none() {
let carried_empty = self.carried.is_none();
let key = self.container;
let mut toggled = None;
if let Some(BlockEntity::Crafter(c)) =
key.and_then(|k| self.world.block_entities.get_mut(&k))
{
if c.disabled[i] {
c.set_slot_state(i, true);
toggled = Some(true);
} else if carried_empty {
c.set_slot_state(i, false);
toggled = Some(false);
}
}
if let Some(enabled) = toggled {
let pitch = if enabled { 1.0 } else { 0.75 };
self.audio
.play("minecraft:ui.button.click", None, 0.4, pitch);
}
}
}
if shift {
self.crafter_quick_move(slot);
return true;
}
false
}
/// `CrafterMenu.quickMoveStack`.
fn crafter_quick_move(&mut self, slot: usize) {
if slot >= 309 {
return;
}
let Some(mut stack) = self.slot_mut(slot).take() else {
return;
};
if slot >= 300 {
let player: Vec<usize> = (9..36).chain(0..9).collect();
self.move_to(&mut stack, &player, true);
} else {
let grid: Vec<usize> = (300..309).collect();
self.move_to(&mut stack, &grid, false);
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stack(item: &str, count: u32) -> Option<ItemStack> {
Some(ItemStack::new(item, count))
}
#[test]
fn signal_counts_filled_and_disabled_slots() {
let mut c = Crafter::default();
assert_eq!(c.redstone_signal(), 0);
c.items[0] = stack("minecraft:stick", 3);
c.set_slot_state(4, false);
assert_eq!(c.redstone_signal(), 2);
// A filled slot cannot be disabled.
c.set_slot_state(0, false);
assert!(!c.disabled[0]);
c.set_slot_state(4, true);
assert_eq!(c.redstone_signal(), 1);
}
#[test]
fn hoppers_fill_the_smaller_stacks_first() {
let mut c = Crafter::default();
let stick = ItemStack::new("minecraft:stick", 1);
c.items[0] = stack("minecraft:stick", 2);
c.items[1] = stack("minecraft:stick", 1);
// A later empty slot counts as smaller: stacks level out front to back.
assert!(!c.can_place(0, &stick, 64));
assert!(!c.can_place(1, &stick, 64));
assert!(c.can_place(2, &stick, 64));
c.disabled[5] = true;
assert!(!c.can_place(5, &stick, 64));
// With every later slot at least as big, a slot accepts again.
for i in 2..9 {
c.items[i] = stack("minecraft:stick", 2);
}
assert!(c.can_place(1, &stick, 64));
// A full stack accepts nothing.
c.items[2] = stack("minecraft:stick", 64);
assert!(!c.can_place(2, &stick, 64));
}
#[test]
fn recipes_condition_accepts_a_name_or_a_list() {
assert!(recipe_matches(
&serde_json::json!("minecraft:crafter"),
"minecraft:crafter"
));
assert!(!recipe_matches(
&serde_json::json!(["minecraft:stick"]),
"minecraft:crafter"
));
assert!(recipe_matches(&Value::Null, "minecraft:crafter"));
}
}
+6 -5
View File
@@ -90,7 +90,7 @@ const SEAT: f64 = 0.1875 - 0.6;
pub(super) const CART_KEY_Y: i32 = -100_000;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Shape {
pub(super) enum Shape {
NorthSouth,
EastWest,
AscendingEast,
@@ -117,7 +117,7 @@ impl Shape {
_ => Self::NorthSouth,
}
}
fn is_slope(self) -> bool {
pub(super) fn is_slope(self) -> bool {
matches!(
self,
Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth
@@ -141,9 +141,9 @@ impl Shape {
}
}
}
struct Rail {
pub(super) struct Rail {
name: Arc<str>,
shape: Shape,
pub(super) shape: Shape,
powered: bool,
}
impl Minecart {
@@ -203,7 +203,7 @@ impl CartModels {
}
}
impl Game<'_> {
fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
let state = self.world.block(x, y, z);
let name = self.res.facts.get(state).name.clone();
if !matches!(
@@ -1238,6 +1238,7 @@ impl Game<'_> {
nether: self.dim == super::Dim::Nether,
lid: &lid,
sign: &|_| None,
banner: &|_| Vec::new(),
glyph: &|c| self.res.atlas.glyph(c),
};
self.res
@@ -0,0 +1,455 @@
//! The horse inventory (`HorseInventoryMenu`, `HorseInventoryScreen`): the
//! saddle and body armour slots, the 3x5 chest of donkeys and mules and the
//! mount drawn following the cursor. It opens with E while riding a tamed
//! mount or with shift + use on a tamed one.
use super::{Game, Screen};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
mobs::{Mob, Species, equine},
};
/// Menu slot ids: the saddle, the body armour and the chest from 710.
pub(super) const SADDLE: usize = 700;
pub(super) const ARMOR: usize = 701;
pub(super) const CHEST: usize = 710;
/// `AbstractChestedHorse.INV_CHEST_COUNT` and `getInventoryColumns`.
const CHEST_SIZE: usize = 15;
const COLUMNS: usize = 5;
/// The open mount menu: copies of the mount's slots, written back on every change.
#[derive(Default)]
pub(super) struct MountMenu {
open: Option<Open>,
}
struct Open {
mob: u32,
species: Species,
columns: usize,
saddle: Option<ItemStack>,
armor: Option<ItemStack>,
items: Vec<Option<ItemStack>>,
/// `shouldRenderSaddleSlot` / `shouldRenderArmorSlot`.
show_saddle: bool,
show_armor: bool,
}
/// `EntityTypeTags.CAN_WEAR_HORSE_ARMOR`.
fn can_wear_horse_armor(species: Species) -> bool {
matches!(species, Species::Horse | Species::ZombieHorse)
}
/// Whether `item` fits the body slot of the species (`isEquippableInSlot`).
fn body_armor_fits(species: Species, item: &str) -> bool {
can_wear_horse_armor(species) && item.ends_with("_horse_armor")
}
impl Game<'_> {
/// Whether the mount menu is the open screen.
pub(super) fn mount_active(&self) -> bool {
self.screen == Screen::Inventory && self.mount_menu.open.is_some()
}
fn mount_mob_index(&self, id: u32) -> Option<usize> {
self.mobs.iter().position(|m| m.id == id)
}
/// `AbstractHorse.openCustomInventoryScreen` for a tamed adult mount.
pub(super) fn open_mount_menu(&mut self, index: usize) {
let m = &self.mobs[index];
let species = m.species();
if !equine::is_equine(species) {
return;
}
let chested = m.extra.chested && matches!(species, Species::Donkey | Species::Mule);
let columns = if chested { COLUMNS } else { 0 };
let mut items = m.extra.items.clone();
items.resize(CHEST_SIZE, None);
let show_armor = can_wear_horse_armor(species);
self.mount_menu.open = Some(Open {
mob: m.id,
species,
columns,
saddle: m
.extra
.saddled
.then(|| ItemStack::new("minecraft:saddle", 1)),
armor: m
.extra
.head
.as_deref()
.filter(|_| show_armor)
.map(|i| ItemStack::new(i, 1)),
items,
show_saddle: true,
show_armor,
});
self.carried = None;
self.station = None;
self.container = None;
self.craft_size = 2;
self.screen = Screen::Inventory;
self.capture(false);
}
/// E while riding a tamed mount opens its inventory instead of the player's.
pub(super) fn open_ridden_mount_menu(&mut self) -> bool {
let Some(id) = self.riding else {
return false;
};
let Some(index) = self.mount_mob_index(id) else {
return false;
};
let m = &self.mobs[index];
if !equine::is_equine(m.species()) || !m.extra.tame || !m.alive() {
return false;
}
self.open_mount_menu(index);
true
}
/// The menu ends when the mount dies or is more than 4 blocks away
/// (`AbstractMountInventoryMenu.stillValid`).
pub(super) fn tick_mount_menu(&mut self) {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let valid = self.mount_mob_index(open.mob).is_some_and(|i| {
let m = &self.mobs[i];
let c = m.center();
m.alive()
&& self.eye_position().is_some_and(|e| {
let d = (e[0] - c[0]).powi(2) + (e[1] - c[1]).powi(2) + (e[2] - c[2]).powi(2);
d <= 16.0 + 4.0
})
});
if !valid {
self.close_container();
self.screen = Screen::Playing;
self.capture(true);
}
}
/// Closing the screen keeps what is in the slots on the mount.
pub(super) fn mount_closed(&mut self) {
self.mount_sync();
self.mount_menu.open = None;
}
/// Writes the menu slots to the mount, with the equip sounds.
fn mount_sync(&mut self) {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let Some(index) = self.mount_mob_index(open.mob) else {
return;
};
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
let items = open.items.clone();
let m = &mut self.mobs[index];
let at = m.center();
let sound = if saddle && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
} else {
None
};
m.extra.saddled = saddle;
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
}
m.extra.items = items;
let (x, z) = (at[0].floor() as i32 >> 4, at[2].floor() as i32 >> 4);
self.world.modified.insert((x, z));
if let Some(sound) = sound {
self.audio.play(sound, Some(at), 0.5, 1.0);
}
}
pub(super) fn mount_slots(&self) -> Option<Vec<usize>> {
let open = self
.mount_menu
.open
.as_ref()
.filter(|_| self.mount_active())?;
let mut v: Vec<usize> = (0..36).collect();
if open.show_saddle {
v.push(SADDLE);
}
if open.show_armor {
v.push(ARMOR);
}
v.extend((0..open.columns * 3).map(|i| CHEST + i));
Some(v)
}
pub(super) fn mount_slot_position(&self, i: usize) -> Option<(f32, f32)> {
let open = self
.mount_menu
.open
.as_ref()
.filter(|_| self.mount_active())?;
match i {
SADDLE => Some((8.0, 18.0)),
ARMOR => Some((8.0, 36.0)),
_ if i >= CHEST => {
let n = i - CHEST;
(n < open.columns * 3).then(|| {
(
80.0 + (n % open.columns) as f32 * 18.0,
18.0 + (n / open.columns) as f32 * 18.0,
)
})
}
_ => None,
}
}
pub(super) fn mount_slot_mut(&mut self, i: usize) -> &mut Option<ItemStack> {
match self.mount_menu.open.as_mut() {
Some(open) if i == SADDLE => &mut open.saddle,
Some(open) if i == ARMOR => &mut open.armor,
Some(open) if i >= CHEST && i - CHEST < CHEST_SIZE => &mut open.items[i - CHEST],
_ => &mut self.scratch_slot,
}
}
/// `ArmorSlot.mayPlace` and the stack limits of the mount's slots.
pub(super) fn mount_slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
let Some(open) = self.mount_menu.open.as_ref() else {
return (false, 64);
};
match slot {
SADDLE => (&*stack.item == "minecraft:saddle", 1),
ARMOR => (body_armor_fits(open.species, &stack.item), 1),
_ => (true, 64),
}
}
/// A click in the mount menu before the generic handling.
pub(super) fn mount_click(&mut self, right: bool) -> bool {
if !self.mount_active() {
return false;
}
let Some(r) = self.renderer.as_ref() else {
return true;
};
let batch = HudBatch::new([r.config.width, r.config.height]);
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return true;
};
let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight);
if shift {
self.mount_quick_move(slot);
} else if slot >= SADDLE {
self.click_filtered(slot, right);
} else {
return false;
}
self.mount_sync();
true
}
/// The inventory slot ids in menu order.
fn mount_player_slots() -> Vec<usize> {
(9..36).chain(0..9).collect()
}
/// `AbstractMountInventoryMenu.quickMoveStack`.
fn mount_quick_move(&mut self, slot: usize) {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let (columns, show_saddle, show_armor) = (open.columns, open.show_saddle, open.show_armor);
let Some(mut stack) = self.slot_mut(slot).take() else {
return;
};
if slot >= SADDLE {
let player = Self::mount_player_slots();
self.move_to(&mut stack, &player, true);
} else {
let armor_free = self.mount_slot_mut(ARMOR).is_none();
let saddle_free = self.mount_slot_mut(SADDLE).is_none();
let armor_ok = show_armor && self.mount_slot_rules(ARMOR, &stack).0 && armor_free;
let saddle_ok = show_saddle && self.mount_slot_rules(SADDLE, &stack).0 && saddle_free;
if armor_ok {
self.move_to(&mut stack, &[ARMOR], false);
} else if saddle_ok {
self.move_to(&mut stack, &[SADDLE], false);
} else {
let chest: Vec<usize> = (0..columns * 3).map(|i| CHEST + i).collect();
let moved = columns > 0 && self.move_to(&mut stack, &chest, false);
if !moved {
// Between the hotbar and the main inventory.
let other: Vec<usize> = if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
};
self.move_to(&mut stack, &other, false);
}
}
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
}
/// `HorseInventoryScreen`'s background, slot frames and the mount.
pub(super) fn draw_mount_background(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let atlas = &self.res.atlas;
batch.sprite_region(
atlas,
"gui/container/horse",
[ox, oy, 176.0, 166.0],
256.0,
256.0,
);
if open.columns > 0 {
batch.sprite_region(
atlas,
"gui/sprites/container/horse/chest_slots",
[ox + 79.0, oy + 17.0, open.columns as f32 * 18.0, 54.0],
90.0,
54.0,
);
}
if open.show_saddle {
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 17.0);
if open.saddle.is_none() {
batch.sprite(
atlas,
"gui/sprites/container/slot/saddle",
ox + 8.0,
oy + 18.0,
);
}
}
if open.show_armor {
batch.sprite(atlas, "gui/sprites/container/slot", ox + 7.0, oy + 35.0);
if open.armor.is_none() {
batch.sprite(
atlas,
"gui/sprites/container/slot/horse_armor",
ox + 8.0,
oy + 36.0,
);
}
}
let grey = rgba(64, 64, 64, 255);
let title = match self.mobs.iter().find(|m| m.id == open.mob) {
Some(m) => m.custom_name.clone().unwrap_or_else(|| {
let key = format!(
"entity.minecraft.{}",
m.kind.id.trim_start_matches("minecraft:")
);
self.translate(&key, &key)
}),
None => String::new(),
};
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
if let Some(m) = self.mobs.iter().find(|m| m.id == open.mob) {
self.draw_mob_preview(
batch,
m,
ox + 26.0,
oy + 18.0,
ox + 78.0,
oy + 70.0,
17.0,
0.25,
);
}
}
/// `extractEntityInInventoryFollowsMouse` for a mob: depth-sorted,
/// back-face-culled quads turned toward the cursor.
#[allow(clippy::too_many_arguments)]
fn draw_mob_preview(
&self,
batch: &mut HudBatch,
mob: &Mob,
x0: f32,
y0: f32,
x1: f32,
y1: f32,
size: f32,
offset_y: f32,
) {
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
let x_angle = ((cx - self.cursor.0) / 40.0).atan();
let y_angle = ((cy - self.cursor.1) / 40.0).atan();
let mut m = mob.clone();
m.previous = m.position;
m.body_yaw = 180.0 + x_angle * 20.0;
m.previous_body_yaw = m.body_yaw;
m.head_yaw = m.body_yaw + x_angle * 20.0;
m.previous_head_yaw = m.head_yaw;
m.head_pitch = -y_angle * 20.0;
m.previous_head_pitch = m.head_pitch;
m.hurt_time = 0;
m.death_time = 0;
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
let atlas = &self.res.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let mut verts = Vec::new();
horizon_client::mobs::render::render_with(
&m,
1.0,
camera,
&lookup,
240 | 240 << 8,
&self.res.mob_data,
&[],
&mut verts,
);
let height = m.kind.height as f32;
let gui = glam::Mat4::from_translation(glam::Vec3::new(cx, cy, 0.0))
* glam::Mat4::from_scale(glam::Vec3::new(size, size, -size))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, height / 2.0 + offset_y, 0.0))
* glam::Mat4::from_rotation_z(std::f32::consts::PI)
* glam::Mat4::from_rotation_x((y_angle * 20.0).to_radians());
let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for q in verts.as_chunks::<4>().0 {
let p: [glam::Vec3; 4] =
std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos)));
let n = (p[1] - p[0]).cross(p[2] - p[0]);
if n.z >= 0.0 {
continue;
}
let n = n.normalize_or_zero();
let shade = (0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0);
let c = q[0].color;
let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s;
let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16);
let depth = p.iter().map(|v| v.z).sum::<f32>() / 4.0;
quads.push((
depth,
p.map(|v| [v.x, v.y]),
std::array::from_fn(|i| q[i].uv),
color,
));
}
quads.sort_by(|a, b| a.0.total_cmp(&b.0));
let start = batch.vertices.len();
for (_, p, uv, color) in quads {
batch.quad(p, uv, color);
}
batch.clip_since(start, x0, y0, x1, y1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_horses_wear_horse_armour() {
assert!(body_armor_fits(
Species::Horse,
"minecraft:iron_horse_armor"
));
assert!(body_armor_fits(
Species::ZombieHorse,
"minecraft:diamond_horse_armor"
));
assert!(!body_armor_fits(
Species::Donkey,
"minecraft:iron_horse_armor"
));
assert!(!body_armor_fits(
Species::Horse,
"minecraft:iron_chestplate"
));
}
}
+9
View File
@@ -99,6 +99,15 @@ impl Game<'_> {
if !equine::is_equine(species) || !m.alive() || Some(m.id) == self.riding {
return false;
}
// AbstractHorse.mobInteract: shift + use opens a tamed adult's inventory.
if !m.is_baby()
&& m.extra.tame
&& (self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight))
{
self.open_mount_menu(index);
return true;
}
if self.feed_mount(index, item) {
return true;
}
@@ -272,6 +272,14 @@ impl Game<'_> {
pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] {
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
}
/// The loaded mob with a saved UUID.
pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
self.persist
.uuids
.iter()
.find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed))
.map(|(id, _)| *id)
}
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
+77 -21
View File
@@ -19,6 +19,18 @@ pub(super) struct ThrownPotion {
velocity: Vec3,
age: u32,
}
impl Game<'_> {
/// A splash potion, lingering potion or experience bottle in flight (the
/// player's throws and dispensers both end up here).
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
self.potions.thrown.push(ThrownPotion {
stack,
position,
velocity,
age: 0,
});
}
}
/// Effects, thrown potions and the attribute modifiers last applied.
#[derive(Default)]
pub(super) struct PotionState {
@@ -40,21 +52,25 @@ impl Game<'_> {
/// Right-click with a potion, splash/lingering potion or glass bottle.
pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result<bool> {
match &*stack.item {
"minecraft:potion" => {
"minecraft:potion" | "minecraft:ominous_bottle" => {
if self.using.is_none() {
self.using = Some((self.selected, 0));
}
Ok(true)
}
"minecraft:splash_potion" | "minecraft:lingering_potion" => {
"minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:experience_bottle" => {
let Some(eye) = self.eye_position() else {
return Ok(true);
};
let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8);
let sound = if &*stack.item == "minecraft:splash_potion" {
"minecraft:entity.splash_potion.throw"
} else {
"minecraft:entity.lingering_potion.throw"
let (sound, power) = match &*stack.item {
"minecraft:splash_potion" => ("minecraft:entity.splash_potion.throw", 0.5),
"minecraft:experience_bottle" => {
("minecraft:entity.experience_bottle.throw", 0.7)
}
_ => ("minecraft:entity.lingering_potion.throw", 0.5),
};
self.audio.play(sound, Some(eye), 0.5, pitch);
// Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0).
@@ -74,9 +90,9 @@ impl Game<'_> {
let r = &mut self.world.random;
let mut jitter = || r.triangle(0.0, 0.0172275);
let v = Vec3::new(
(f64::from(dir[0]) / l + jitter()) * 0.5,
(f64::from(dir[1]) / l + jitter()) * 0.5,
(f64::from(dir[2]) / l + jitter()) * 0.5,
(f64::from(dir[0]) / l + jitter()) * power,
(f64::from(dir[1]) / l + jitter()) * power,
(f64::from(dir[2]) / l + jitter()) * power,
);
let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity);
let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground);
@@ -85,15 +101,14 @@ impl Game<'_> {
v.y + if on_ground { 0.0 } else { pv.y },
v.z + pv.z,
);
self.potions.thrown.push(ThrownPotion {
stack: ItemStack {
self.launch_thrown(
ItemStack {
count: 1,
..stack.clone()
},
position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
velocity: v,
age: 0,
});
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
v,
);
self.swing_arm();
self.consume_held();
Ok(true)
@@ -137,7 +152,8 @@ impl Game<'_> {
}
/// Drinking a potion while right-click is held; true when handled.
pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:potion" {
let ominous = &*stack.item == "minecraft:ominous_bottle";
if &*stack.item != "minecraft:potion" && !ominous {
return false;
}
let ticks = ticks + 1;
@@ -154,6 +170,10 @@ impl Game<'_> {
return true;
}
self.using = None;
if ominous {
self.drink_ominous_bottle(slot, stack);
return true;
}
let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0);
for e in lasting {
self.potions.effects.add(e);
@@ -326,19 +346,25 @@ impl Game<'_> {
}
t.position = next;
// ThrowableItemProjectile: drag 0.99 then gravity 0.05.
// ThrownExperienceBottle.getDefaultGravity is 0.07.
let gravity = if &*t.stack.item == "minecraft:experience_bottle" {
0.07
} else {
0.05
};
t.velocity = Vec3::new(
t.velocity.x * 0.99,
t.velocity.y * 0.99 - 0.05,
t.velocity.y * 0.99 - gravity,
t.velocity.z * 0.99,
);
t.age < 1200 && t.position.y > -128.0
});
// ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position.
for t in &thrown {
let sprite = if &*t.stack.item == "minecraft:lingering_potion" {
"item/lingering_potion"
} else {
"item/splash_potion"
let sprite = match &*t.stack.item {
"minecraft:lingering_potion" => "item/lingering_potion",
"minecraft:experience_bottle" => "item/experience_bottle",
_ => "item/splash_potion",
};
let mut fixed = horizon_core::random::LegacyRandom::new(0);
let mut p = horizon_client::particles::Particle::terrain(
@@ -362,6 +388,36 @@ impl Game<'_> {
}
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
if &*stack.item == "minecraft:experience_bottle" {
// ThrownExperienceBottle.onHit: the water-coloured splash (level
// event 2002) and 3 to 11 experience.
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.audio.play(
"minecraft:entity.splash_potion.break",
Some([at.x, at.y, at.z]),
1.0,
pitch,
);
for _ in 0..8 {
let v = [
f64::from(self.world.random.next_float() - 0.5) * 0.3,
0.2,
f64::from(self.world.random.next_float() - 0.5) * 0.3,
];
let p = horizon_client::particles::Particle::terrain(
&mut self.world.random,
[at.x, at.y, at.z],
v,
"item/splash_potion".into(),
0x38_5DC6,
);
self.particles.push(p);
}
let r = &mut self.world.random;
let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0);
self.spawn_orbs([at.x, at.y, at.z], value as u32);
return;
}
let lingering = &*stack.item == "minecraft:lingering_potion";
let event = if lingering {
"minecraft:entity.lingering_potion.break"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+56 -20
View File
@@ -252,14 +252,8 @@ pub(super) fn draw_shield_icon(
atlas: &horizon_client::hud::HudAtlas,
x: f32,
y: f32,
passes: &[(String, u32)],
) {
let Some(r) = atlas
.sprites
.get("entity/shield/shield_base_nopattern")
.copied()
else {
return;
};
// display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65.
let (sx, cx) = 15f32.to_radians().sin_cos();
let (sy, cy) = (-25f32).to_radians().sin_cos();
@@ -282,15 +276,9 @@ pub(super) fn draw_shield_icon(
qz,
]
};
let tex = |u: f32, v: f32| {
[
r.u0 + (r.u1 - r.u0) * u / 64.0,
r.v0 + (r.v1 - r.v0) * v / 64.0,
]
};
// ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and
// handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6).
let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new();
for (tu, tv, from, size) in [
(0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]),
(26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]),
@@ -324,16 +312,64 @@ pub(super) fn draw_shield_icon(
}
let p = verts.map(place);
let depth = p.iter().map(|q| q[2]).sum::<f32>() / 4.0;
let uv = [tex(c, b), tex(a, b), tex(a, e), tex(c, e)];
let texels = [[c, b], [a, b], [a, e], [c, e]];
// Flat item lighting: faces toward the viewer are brightest.
let shade = (0.6 + 0.4 * normal[2]).min(1.0);
let s = (shade * 255.0) as u8;
let color = horizon_client::hud::rgba(s, s, s, 255);
faces.push((depth, p.map(|q| [q[0], q[1]]), uv, color));
faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade));
}
}
faces.sort_by(|a, b| a.0.total_cmp(&b.0));
for (_, p, uv, color) in faces {
// Every pass redraws the same boxes; equal depths keep the pass order.
let mut quads = Vec::new();
for (index, (name, tint)) in passes.iter().enumerate() {
let Some(r) = atlas.sprites.get(name).copied() else {
continue;
};
for (depth, p, texels, shade) in &faces {
let uv = texels.map(|[u, v]| {
[
r.u0 + (r.u1 - r.u0) * u / 64.0,
r.v0 + (r.v1 - r.v0) * v / 64.0,
]
});
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
quads.push((
*depth,
index,
*p,
uv,
horizon_client::hud::rgba(c(16), c(8), c(0), 255),
));
}
}
quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
for (_, _, p, uv, color) in quads {
batch.quad(p, uv, color);
}
}
/// The textures a shield draws: the plain or patterned base, then the
/// banner layers (`ShieldSpecialRenderer.submit`).
pub(super) fn shield_passes(
banners: &horizon_client::banner::Banners,
stack: &ItemStack,
) -> Vec<(String, u32)> {
let data = stack.data();
let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]);
let base = data.and_then(|d| d.base_color.as_deref());
if layers.is_empty() && base.is_none() {
return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)];
}
let mut passes = vec![
("entity/shield/shield_base".into(), 0xFFFFFF),
(
"entity/shield/base".into(),
horizon_client::banner::dye_rgb(base.unwrap_or("white")),
),
];
for layer in layers.iter().take(16) {
passes.push((
banners.shield_texture(&layer.pattern),
horizon_client::banner::dye_rgb(&layer.color),
));
}
passes
}
@@ -17,6 +17,7 @@ pub(super) const HELP: &[&str] = &[
"effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)",
"effects list active status effects",
"trade PROFESSION [LEVEL] [TYPE] open a villager trading menu (offers from the world's trade sequences)",
"mount-menu [tame] [chest] open the inventory of the nearest horse, donkey or mule (tame, chest set those)",
"close close the open menu",
];
fn id(name: &str) -> String {
@@ -194,6 +195,29 @@ impl Game<'_> {
"effects" => Ok(Some(
json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }),
)),
"mount-menu" => {
let eye = self.eye_position().ok_or("no player")?;
let index = (0..self.mobs.len())
.filter(|&i| horizon_client::mobs::equine::is_equine(self.mobs[i].species()))
.min_by(|&a, &b| {
let d = |i: usize| {
let c = self.mobs[i].center();
(c[0] - eye[0]).powi(2)
+ (c[1] - eye[1]).powi(2)
+ (c[2] - eye[2]).powi(2)
};
d(a).total_cmp(&d(b))
})
.ok_or("no horse around")?;
if flag("tame") {
self.mobs[index].extra.tame = true;
}
if flag("chest") {
self.mobs[index].extra.chested = true;
}
self.open_mount_menu(index);
ok()
}
"close" => {
self.close_container();
self.screen = Screen::Playing;
+72 -15
View File
@@ -32,6 +32,8 @@ pub(super) enum Kind {
Beacon,
/// The cartography table (game/cartography.rs).
Cartography,
/// The loom (game/loom.rs).
Loom,
}
impl Kind {
fn from_block(name: &str) -> Option<Self> {
@@ -45,12 +47,13 @@ impl Kind {
"minecraft:stonecutter" => Self::Stonecutter,
"minecraft:beacon" => Self::Beacon,
"minecraft:cartography_table" => Self::Cartography,
"minecraft:loom" => Self::Loom,
_ => return None,
})
}
fn inputs(self) -> usize {
match self {
Self::Smithing => 3,
Self::Smithing | Self::Loom => 3,
Self::Stonecutter | Self::Beacon => 1,
_ => 2,
}
@@ -65,6 +68,7 @@ impl Kind {
Self::Merchant => "gui/container/villager",
Self::Beacon => "gui/container/beacon",
Self::Cartography => "gui/container/cartography_table",
Self::Loom => "gui/container/loom",
}
}
fn title_key(self) -> &'static str {
@@ -77,6 +81,7 @@ impl Kind {
Self::Merchant => "merchant.trades",
Self::Beacon => "container.beacon",
Self::Cartography => "container.cartography_table",
Self::Loom => "container.loom",
}
}
/// (titleLabelX, titleLabelY).
@@ -85,7 +90,7 @@ impl Kind {
Self::Anvil => (60.0, 6.0),
Self::Smithing => (44.0, 15.0),
Self::Stonecutter => (8.0, 5.0),
Self::Cartography => (8.0, 4.0),
Self::Cartography | Self::Loom => (8.0, 4.0),
_ => (8.0, 6.0),
}
}
@@ -99,6 +104,7 @@ impl Kind {
Self::Merchant => &[(86.0, 37.0), (112.0, 37.0)],
Self::Beacon => &[(109.0, 110.0)],
Self::Cartography => &[(15.0, 15.0), (15.0, 52.0)],
Self::Loom => &[(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)],
};
table[i.min(table.len() - 1)]
}
@@ -112,6 +118,7 @@ impl Kind {
Self::Merchant => Some((170.0, 37.0)),
Self::Beacon => None,
Self::Cartography => Some((145.0, 39.0)),
Self::Loom => Some((143.0, 57.0)),
}
}
}
@@ -133,11 +140,13 @@ pub(super) struct Station {
input_item: Option<Arc<str>>,
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
last_sound: u64,
pub(super) last_sound: u64,
/// Villager trading state.
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
/// Beacon menu: the selected primary and secondary power (EFFECTS index).
pub(super) beacon: [Option<usize>; 2],
/// The loom's patterns, selection and scroller (game/loom.rs).
pub(super) loom: super::loom::LoomState,
}
impl Station {
fn new(kind: Kind, pos: [i32; 3]) -> Self {
@@ -158,6 +167,7 @@ impl Station {
last_sound: 0,
merchant: None,
beacon: [None; 2],
loom: Default::default(),
}
}
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
@@ -437,6 +447,7 @@ impl Game<'_> {
Kind::Merchant => super::trading::update(&mut s, items),
Kind::Beacon => {}
Kind::Cartography => s.result = self.cartography_result(&s),
Kind::Loom => self.loom_changed(&mut s),
Kind::Stonecutter => {
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
if item != s.input_item {
@@ -472,7 +483,20 @@ impl Game<'_> {
/// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots.
fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
let data = self.data();
if (300..305).contains(&slot) {
if slot >= super::mount_menu::SADDLE {
return self.mount_slot_rules(slot, stack);
}
if let Some(BlockEntity::Crafter(c)) = self.container_kind()
&& (300..309).contains(&slot)
{
// CrafterSlot.mayPlace: not a disabled slot.
return (!c.disabled[slot - 300], 64);
}
if (300..400).contains(&slot) && !self.brewing_open() && self.refuses(slot, stack) {
// ShulkerBoxSlot.mayPlace.
return (false, 64);
}
if self.brewing_open() && (300..305).contains(&slot) {
return match slot - 300 {
0..=2 => (data.brewing.is_bottle(stack), 1),
3 => (data.brewing.is_reagent(stack), 64),
@@ -498,6 +522,7 @@ impl Game<'_> {
match s.kind {
Kind::Enchanting if i == 0 => (true, 1),
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
Kind::Loom => self.loom_slot_rules(i, stack),
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
Kind::Cartography => (
matches!(
@@ -513,7 +538,7 @@ impl Game<'_> {
}
}
/// `AbstractContainerMenu.doClick` PICKUP on a filtered slot.
fn click_filtered(&mut self, slot: usize, right: bool) {
pub(super) fn click_filtered(&mut self, slot: usize, right: bool) {
let carried = self.carried.take();
let current = self.slot_mut(slot).take();
let (new_slot, new_carried) = match (carried, current) {
@@ -565,7 +590,12 @@ impl Game<'_> {
self.carried = new_carried;
}
/// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots.
fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool {
pub(super) fn move_to(
&mut self,
stack: &mut ItemStack,
targets: &[usize],
reverse: bool,
) -> bool {
let order: Vec<usize> = if reverse {
targets.iter().rev().copied().collect()
} else {
@@ -614,8 +644,12 @@ impl Game<'_> {
return false;
};
let player = Self::player_slots();
let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom);
let moved = if (300..305).contains(&slot) || slot >= INPUT {
self.move_to(&mut stack, &player, true)
// LoomMenu moves into the inventory front to back, the others back to front.
self.move_to(&mut stack, &player, !loom)
} else if loom {
self.loom_quick_move(slot, &mut stack)
} else if self.brewing_open() {
// BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half.
let data = self.data();
@@ -673,7 +707,7 @@ impl Game<'_> {
moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
}
}
Some(Kind::Merchant) => {}
Some(Kind::Merchant | Kind::Loom) => {}
Some(Kind::Beacon) => {
// BeaconMenu.quickMoveStack: one payment item into the empty slot.
if super::beacon::is_payment(&stack.item) {
@@ -713,7 +747,7 @@ impl Game<'_> {
];
self.audio.play(sound, Some(at), volume, pitch);
}
fn give_or_drop(&mut self, stack: ItemStack) {
pub(super) fn give_or_drop(&mut self, stack: ItemStack) {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
@@ -860,6 +894,7 @@ impl Game<'_> {
self.cartography_taken(pos);
}
}
Kind::Loom => self.loom_taken(&mut s),
Kind::Enchanting => {}
}
self.station = Some(s);
@@ -991,6 +1026,9 @@ impl Game<'_> {
if kind == Kind::Merchant && !right && self.merchant_click(local) {
return true;
}
if kind == Kind::Loom && !right && self.loom_click(local) {
return true;
}
if kind == Kind::Beacon && !right && self.beacon_click(local) {
return true;
}
@@ -1065,6 +1103,7 @@ impl Game<'_> {
}
pub(super) fn station_scroll(&mut self, d: f32) {
self.merchant_scroll(d);
self.loom_scroll(d);
let Some(s) = self.station.as_mut() else {
return;
};
@@ -1084,6 +1123,11 @@ impl Game<'_> {
.is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some())
}
pub(super) fn station_text(&mut self, text: Option<&str>, backspace: bool) {
// The recipe book's search box takes scripted typing too.
if self.recipe_search_focused() {
self.recipe_text(text, backspace);
return;
}
let Some(s) = self.station.as_mut() else {
return;
};
@@ -1308,6 +1352,9 @@ impl Game<'_> {
if kind == Kind::Cartography {
self.draw_cartography(batch, ox, oy);
}
if kind == Kind::Loom {
tooltip = self.draw_loom(batch, ox, oy, local);
}
let atlas = &self.res.atlas;
let s = self.station.as_ref().expect("open station");
let has_input = s.inputs.iter().any(Option::is_some);
@@ -1598,7 +1645,7 @@ impl Game<'_> {
}
}
}
Kind::Merchant | Kind::Beacon | Kind::Cartography => {}
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
Kind::Stonecutter => {
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
let active = display && s.recipes.len() > 12;
@@ -1725,6 +1772,10 @@ impl Game<'_> {
let e: &Enchantments = &self.res.stations.enchantments;
let props = e.props(&stack.item);
let mut rarity = props.map_or("common", |p| p.rarity.as_str());
// The ominous banner's rarity component.
if stack.data().is_some_and(|d| d.ominous_banner) {
rarity = "uncommon";
}
if !stack.enchantments().is_empty() {
rarity = match rarity {
"common" | "uncommon" => "rare",
@@ -1740,6 +1791,9 @@ impl Game<'_> {
};
let name = if let Some(n) = stack.custom_name() {
n.to_owned()
} else if stack.data().is_some_and(|d| d.ominous_banner) {
e.translate("block.minecraft.ominous_banner")
.map_or_else(|| "Ominous Banner".to_owned(), str::to_owned)
} else if stack.data().and_then(|d| d.potion.as_ref()).is_some()
|| stack.item.ends_with("potion")
|| &*stack.item == "minecraft:tipped_arrow"
@@ -1799,6 +1853,11 @@ impl Game<'_> {
},
));
}
// BannerPatternLayers.addToTooltip: up to six layer names.
for layer in horizon_client::banner::layers(stack).iter().take(6) {
let key = self.res.stations.banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
}
if let Some(info) = self.res.items.get(&stack.item)
&& info.max_damage > 0
&& stack.damage > 0
@@ -1918,14 +1977,12 @@ impl Game<'_> {
let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) else {
return;
};
let stack = if slot == 200 {
self.craft_result()
} else {
self.slot_mut(slot).clone()
};
let stack = self.slot_view(slot);
if let Some(stack) = stack {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
} else if let Some(text) = self.crafter_tooltip(slot) {
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
}
}
/// Potion items: `layer0` tinted with the potion colour under the bottle
+311
View File
@@ -11,6 +11,10 @@ impl Game<'_> {
/// Block-entity contents on removal: shulker boxes keep theirs for the
/// dropped box (`copy_components`), other containers spill them.
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
if let BlockEntity::Banner(banner) = entity {
self.pending_banner.insert(pos, banner);
return;
}
if is_shulker_box(block) {
if let BlockEntity::Chest(items) = entity {
let kept = items
@@ -79,3 +83,310 @@ impl Game<'_> {
}
}
}
// ---- chest menus: double chests, titles and shift-click ----
/// `Direction.getClockWise` for horizontal facings.
fn clockwise(facing: &str) -> &'static str {
match facing {
"north" => "east",
"east" => "south",
"south" => "west",
_ => "north",
}
}
fn counter_clockwise(facing: &str) -> &'static str {
match clockwise(facing) {
"east" => "west",
"south" => "north",
"west" => "east",
_ => "south",
}
}
fn facing_step(facing: &str) -> (i32, i32) {
match facing {
"north" => (0, -1),
"south" => (0, 1),
"west" => (-1, 0),
_ => (1, 0),
}
}
impl Game<'_> {
/// The other half of the open double chest and whether the open one is
/// the right half (`ChestBlock.getConnectedDirection`).
fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
let registry = self.res.assets.registry;
let state = registry.state(self.world.block(key.0, key.1, key.2))?;
if !matches!(
state.name.as_str(),
"minecraft:chest" | "minecraft:trapped_chest"
) {
return None;
}
let kind = state.properties.get("type")?.as_str();
if kind == "single" {
return None;
}
let facing = state.properties.get("facing")?.as_str();
let dir = if kind == "left" {
clockwise(facing)
} else {
counter_clockwise(facing)
};
let (dx, dz) = facing_step(dir);
let other = (key.0 + dx, key.1, key.2 + dz);
let other_state = registry.state(self.world.block(other.0, other.1, other.2))?;
let other_kind = other_state.properties.get("type")?.as_str();
let paired = other_state.name == state.name
&& other_kind != "single"
&& other_kind != kind
&& matches!(
self.world.block_entities.get(&other),
Some(BlockEntity::Chest(items)) if items.len() == 27
);
paired.then_some((other, kind == "right"))
}
/// The other half of a double chest at `key`, for neighbour updates.
pub(super) fn chest_other_half(&self, key: (i32, i32, i32)) -> Option<(i32, i32, i32)> {
self.chest_partner(key).map(|p| p.0)
}
/// The block entities of the open container in menu order, with their
/// sizes: a double chest is its right half then its left half.
pub(super) fn container_parts(&self) -> Vec<((i32, i32, i32), usize)> {
let Some(key) = self.container else {
return Vec::new();
};
let Some(entity) = self.world.block_entities.get(&key) else {
return Vec::new();
};
let own = (key, entity.slots().len());
match self.chest_partner(key) {
Some((other, true)) => vec![own, (other, 27)],
Some((other, false)) => vec![(other, 27), own],
None => vec![own],
}
}
/// The number of slots of the open container.
pub(super) fn container_size(&self) -> usize {
self.container_parts().iter().map(|p| p.1).sum()
}
/// Container slot `n` (menu slot `300 + n`).
pub(super) fn container_slot_mut(&mut self, mut n: usize) -> &mut Option<ItemStack> {
let mut target = None;
for (pos, size) in self.container_parts() {
if n < size {
target = Some((pos, n));
break;
}
n -= size;
}
match target.and_then(|(pos, i)| {
self.world
.block_entities
.get_mut(&pos)
.and_then(|e| e.slots_mut().get_mut(i))
}) {
Some(slot) => slot,
None => &mut self.scratch_slot,
}
}
pub(super) fn container_block_is_shulker(&self) -> bool {
self.container_block()
.as_deref()
.is_some_and(is_shulker_box)
}
fn container_block(&self) -> Option<std::sync::Arc<str>> {
let k = self.container?;
Some(
self.res
.facts
.get(self.world.block(k.0, k.1, k.2))
.name
.clone(),
)
}
/// Rows of the open generic 9-wide container (`ChestMenu`), or None for
/// the other menus (hoppers, dispensers, shulker boxes, furnaces...).
pub(super) fn chest_rows(&self) -> Option<usize> {
if !matches!(self.container_kind()?, BlockEntity::Chest(_)) {
return None;
}
let generic = match self.container_block().as_deref() {
Some(
"minecraft:chest"
| "minecraft:trapped_chest"
| "minecraft:barrel"
| "minecraft:ender_chest",
) => true,
_ => self.open_cart_kind() == Some(super::minecarts::CartKind::Chest),
};
generic.then(|| self.container_size() / 9)
}
/// The title of the open chest-like menu.
fn chest_title(&self, rows: usize) -> String {
let (key, fallback) = match self.container_block().as_deref() {
Some("minecraft:barrel") => ("container.barrel", "Barrel"),
Some("minecraft:ender_chest") => ("container.enderchest", "Ender Chest"),
_ if self.open_cart_kind().is_some() => {
("entity.minecraft.chest_minecart", "Minecart with Chest")
}
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
_ => ("container.chest", "Chest"),
};
self.translate(key, fallback)
}
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
/// container rows, the title and the inventory label.
pub(super) fn draw_chest_screen(
&self,
batch: &mut horizon_client::hud::HudBatch,
ox: f32,
oy: f32,
) {
use horizon_client::hud::rgba;
let atlas = &self.res.atlas;
let grey = rgba(64, 64, 64, 255);
if self
.container_block()
.as_deref()
.is_some_and(is_shulker_box)
{
batch.sprite_region(
atlas,
"gui/container/shulker_box",
[ox, oy, 176.0, 167.0],
256.0,
256.0,
);
let title = self.translate("container.shulkerBox", "Shulker Box");
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 73.0, grey, false);
return;
}
let rows = self.chest_rows().unwrap_or(3);
let top = rows as f32 * 18.0 + 17.0;
batch.sprite_region(
atlas,
"gui/container/generic_54",
[ox, oy, 176.0, top],
256.0,
256.0,
);
// The player half of the texture starts at v = 126.
if let Some(mut r) = atlas.sprites.get("gui/container/generic_54").copied() {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
r.v0 += 126.0 * dv;
r.v1 = r.v0 + 96.0 * dv;
r.u1 = r.u0 + 176.0 * du;
batch.rect_uv(ox, oy + top, 176.0, 96.0, r, u32::MAX);
}
batch.text(
atlas,
&self.chest_title(rows),
ox + 8.0,
oy + 6.0,
grey,
false,
);
batch.text(
atlas,
"Inventory",
ox + 8.0,
oy + 114.0 + rows as f32 * 18.0 - 94.0,
grey,
false,
);
}
}
impl Game<'_> {
/// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace
/// menu for a shift-click on `slot`; false when the menu has none.
pub(super) fn container_quick_move(&mut self, slot: usize) -> bool {
let size = self.container_size();
let furnace = match self.container_kind() {
Some(BlockEntity::Chest(_)) => None,
Some(BlockEntity::Furnace(f)) => Some(f.kind),
_ => return false,
};
if slot >= 300 + size.max(3) {
return false;
}
let Some(mut stack) = self.slot_mut(slot).take() else {
return true;
};
let player: Vec<usize> = (9..36).chain(0..9).collect();
let hotbar_or_main = |slot: usize| -> Vec<usize> {
if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
}
};
match furnace {
None => {
if slot >= 300 {
self.move_to(&mut stack, &player, true);
} else {
let targets: Vec<usize> = (300..300 + size).collect();
self.move_to(&mut stack, &targets, false);
}
}
Some(kind) => {
// AbstractFurnaceMenu.quickMoveStack.
if slot >= 300 {
self.move_to(&mut stack, &player, slot == 302);
} else {
let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some();
let fuel = self
.res
.items
.get(&stack.item)
.is_some_and(|i| i.fuel.is_some());
let moved = if smeltable {
self.move_to(&mut stack, &[300], false)
} else if fuel {
self.move_to(&mut stack, &[301], false)
} else {
false
};
if !moved && !smeltable && !fuel {
let other = hotbar_or_main(slot);
self.move_to(&mut stack, &other, false);
}
if let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
}
}
}
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn double_chest_halves_connect_around_the_facing() {
// A left half facing north connects east, a right half west.
assert_eq!(facing_step(clockwise("north")), (1, 0));
assert_eq!(facing_step(counter_clockwise("north")), (-1, 0));
assert_eq!(facing_step(clockwise("south")), (-1, 0));
assert_eq!(facing_step(counter_clockwise("east")), (0, -1));
}
#[test]
fn shulker_boxes_are_recognised_by_name() {
assert!(is_shulker_box("minecraft:red_shulker_box"));
assert!(is_shulker_box("minecraft:shulker_box"));
assert!(!is_shulker_box("minecraft:chest"));
}
}
+29 -1
View File
@@ -148,7 +148,13 @@ impl Game<'_> {
}));
}
let m = &self.mobs[index];
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
// Villager.updateSpecialPrices: reputation and Hero of the Village.
if species == Species::Villager {
let reputation = self.villager_reputation(m.id);
merchant::update_special_prices(&mut trade.offers, reputation, self.hero_amplifier());
}
let m = &self.mobs[index];
if trade.offers.is_empty() {
let mut events = Vec::new();
villager::set_unhappy(&mut self.mobs[index], &mut events);
@@ -190,6 +196,10 @@ impl Game<'_> {
let trade = m.extra.trade.get_or_insert_default();
trade.xp = state.xp;
trade.offers = state.offers.clone();
// setTradingPlayer(null) resets the special prices.
for offer in &mut trade.offers {
offer.special_price_diff = 0;
}
}
/// Opens a merchant menu for a villager (or a generated one for tests).
pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) {
@@ -244,6 +254,16 @@ impl Game<'_> {
.map(|p| [p.position.x, p.position.y + 0.5, p.position.z]);
self.audio
.play("minecraft:entity.villager.yes", at, 1.0, 1.0);
// Villager.notifyTrade: the villager remembers the trade.
let villager = s
.merchant
.as_ref()
.filter(|m| m.progress())
.and_then(|m| m.mob);
if let Some(mob) = villager {
self.villager_traded(mob);
}
let Some(m) = s.merchant.as_mut() else { return };
if level_up {
let (profession, variant, level) =
(m.profession.clone(), m.variant.clone(), m.level + 1);
@@ -254,6 +274,14 @@ impl Game<'_> {
}
pop += 5;
}
// The prices follow the villager's new reputation.
if let Some(mob) = villager {
let reputation = self.villager_reputation(mob);
let hero = self.hero_amplifier();
if let Some(m) = s.merchant.as_mut() {
merchant::update_special_prices(&mut m.offers, reputation, hero);
}
}
if offer.reward_exp
&& let Some(at) = at
{
+467
View File
@@ -0,0 +1,467 @@
//! What villagers do with each other and with the player: gossip and
//! reputation, sharing food and wares, picking up dropped items, making
//! babies, calling iron golems and the prices they ask.
use super::Game;
use horizon_client::{
gossip::{self, GossipType},
items::ItemStack,
mobs::{Mob, Species, spawning, villager},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
}
/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on.
fn golem_floor_ok(name: &str) -> bool {
!matches!(
name,
"minecraft:cobweb"
| "minecraft:cactus"
| "minecraft:glass_pane"
| "minecraft:conduit"
| "minecraft:ice"
| "minecraft:tnt"
| "minecraft:glowstone"
| "minecraft:beacon"
| "minecraft:sea_lantern"
| "minecraft:frosted_ice"
| "minecraft:tinted_glass"
| "minecraft:glass"
) && !name.ends_with("_stained_glass_pane")
&& !name.ends_with("_stained_glass")
&& !name.ends_with("leaves")
}
impl Game<'_> {
fn villager_index(&self, id: u32) -> Option<usize> {
self.mobs
.iter()
.position(|m| m.id == id && m.species() == Species::Villager)
}
fn item_max_stack(&self, item: &str) -> u32 {
self.res.items.get(item).map_or(64, |i| i.max_stack)
}
/// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward
/// a point.
fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) {
let at = [from.x, eye - 0.3, from.z];
let d = Vec3::new(to.x - from.x, to.y - from.y, to.z - from.z).normalize();
self.spawn_item(stack, at, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10);
}
/// `TradeWithVillager.tick` for one pair: gossip (at most once in 1200
/// ticks for both), then surplus food and wanted wares tossed over.
pub(super) fn villager_meet(&mut self, a: u32, b: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(a), self.villager_index(b)) else {
return;
};
let now = self.world.game_time;
let items = &self.res.items;
let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack);
// Villager.gossip: both must be past their cool-down.
let ready = {
let ea = villager::ext(&self.mobs[ia]);
let eb = villager::ext(&self.mobs[ib]);
ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now))
};
let mut golem = false;
if ready {
let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default();
let me = &mut self.mobs[ia];
let mut random = me.random.clone();
let e = villager::ext_mut(me);
e.gossips.transfer_from(&source.gossips, &mut random, 10);
e.last_gossip_time = now;
me.random = random;
villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now;
golem = true;
}
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
let farmer = villager::is_farmer(&self.mobs[ia]);
let (from, eye, to) = (
self.mobs[ia].position,
self.mobs[ia].eye_y(),
self.mobs[ib].position,
);
let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food());
let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food());
let mut thrown = Vec::new();
if excess
&& (farmer || wants_more)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| villager::food_points(&s.item) > 0, max)
{
thrown.push(s);
}
// A farmer's wheat.
if farmer
&& villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
{
thrown.push(s);
}
// Wares the neighbour's profession asks for and ours does not.
let theirs = villager::requested_items(&self.mobs[ib]);
let mine = villager::requested_items(&self.mobs[ia]);
let wanted: Vec<&str> = theirs
.iter()
.copied()
.filter(|i| !mine.contains(i))
.collect();
if !wanted.is_empty()
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| wanted.contains(&&*s.item), max)
{
thrown.push(s);
}
for stack in thrown {
self.villager_throw(from, eye, to, stack);
}
if golem {
self.villager_golem_check(a, 5);
}
}
/// `Villager.spawnGolemIfNeeded`: when enough villagers nearby that
/// slept recently and saw no golem agree, an iron golem appears.
pub(super) fn villager_golem_check(&mut self, id: u32, needed: usize) {
let Some(i) = self.villager_index(id) else {
return;
};
let now = self.world.game_time;
if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) {
return;
}
let at = self.mobs[i].position;
let nearby: Vec<usize> = self
.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.species() == Species::Villager
&& m.alive()
&& (m.position.x - at.x).abs() <= 10.0
&& (m.position.y - at.y).abs() <= 10.0
&& (m.position.z - at.z).abs() <= 10.0
})
.map(|(j, _)| j)
.collect();
let wanting = nearby
.iter()
.filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now)))
.take(5)
.count();
if wanting < needed {
return;
}
if self.try_spawn_iron_golem(block_of(at)) {
for j in nearby {
villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599;
}
}
}
/// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up
/// and down, LEGACY_IRON_GOLEM)`.
fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool {
for _ in 0..10 {
let r = &mut self.world.random;
let dx = r.next_int_bound(17).unwrap_or(8) - 8;
let dz = r.next_int_bound(17).unwrap_or(8) - 8;
let (x, z) = (start[0] + dx, start[2] + dz);
let mut y = start[1] + 6;
let mut above = self.world.block(x, y, z);
let mut found = None;
for _ in 0..=12 {
y -= 1;
let here = self.world.block(x, y, z);
let f = self.res.facts.get(here);
let above_f = self.res.facts.get(above);
let air_or_liquid = self.res.facts.is_air(above)
|| above_f.fluid != horizon_client::blocks::Fluid::None;
let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID
!= 0
|| f.name.as_ref() == "minecraft:powder_snow";
if golem_floor_ok(&f.name) && air_or_liquid && solid {
found = Some(y + 1);
break;
}
above = here;
}
let Some(y) = found else { continue };
// IronGolem.checkSpawnRules: a floor and three free blocks.
let free = |g: &Self, yy: i32| {
g.res.mob_data.state(g.world.block(x, yy, z)).flags
& horizon_client::mobs::data::VALID_EMPTY_SPAWN
!= 0
};
if !(0..4).all(|k| free(self, y + k)) {
continue;
}
let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5];
if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
let sound = m.kind.sounds[0];
if !sound.is_empty() {
let at = m.center();
self.audio
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
}
return true;
}
}
false
}
/// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48
/// blocks is taken for the child, who is a baby villager of one of
/// three villager types.
pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner))
else {
return;
};
villager::ext_mut(&mut self.mobs[ia]).eat_and_digest();
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
let from = self.mobs[ia].position;
let angry = |g: &mut Self| {
for i in [ia, ib] {
let p = g.mobs[i].position;
g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
}
};
let Some(bed) = self.take_vacant_bed(block_of(from)) else {
angry(self);
return;
};
// Villager.getBreedOffspring: half the biome's type, a quarter each parent's.
let roll = self.mobs[ia].random.next_double();
let kind_of = |m: &Mob| m.extra.variant;
let facts = self.biome_facts(
from.x.floor() as i32,
from.y.floor() as i32,
from.z.floor() as i32,
);
let variant = if roll < 0.5 {
spawning::villager_type(&facts)
} else if roll < 0.75 {
kind_of(&self.mobs[ia])
} else {
kind_of(&self.mobs[ib])
};
let Some(id) =
self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true)
else {
return;
};
self.mobs[ia].extra.age = 6000;
self.mobs[ib].extra.age = 6000;
if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) {
child.extra.variant = variant;
child.extra.variant2 = villager::NONE;
child.extra.age = -24000;
child.extra.bed = Some(bed);
}
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head.
fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Villager)
.filter_map(|m| m.extra.bed)
.collect();
let mut known: HashMap<u32, bool> = HashMap::new();
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
continue;
}
let free_head = *known.entry(state.0).or_insert_with(|| {
self.res.facts.get(state).name.ends_with("_bed")
&& self.res.assets.registry.state(state).is_some_and(|s| {
s.properties.get("part").map(String::as_str) == Some("head")
&& s.properties.get("occupied").map(String::as_str)
!= Some("true")
})
});
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if free_head
&& d <= 48 * 48
&& !claimed.contains(&[x, y, z])
&& best.is_none_or(|(b, _)| d < b)
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
let options = horizon_client::particles::ParticleOptions::simple(ty);
self.particles.add(&options, at, [0.0; 3]);
}
}
/// `Mob.aiStep` item pickup for villagers (`InventoryCarrier`): food,
/// seeds and what their profession wants, from within a block.
pub(super) fn villager_pickups(&mut self) {
if self.dropped.is_empty() || !self.ui.rules.bool("mob_griefing") {
return;
}
let picks_up = self
.res
.items
.item_tags
.get("minecraft:villager_picks_up")
.cloned();
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Villager || !m.alive() {
continue;
}
let (pos, half) = (m.position, f64::from(m.width()) / 2.0 + 1.0);
let top = f64::from(m.height());
let requested = villager::requested_items(m);
let mut j = 0;
while j < self.dropped.len() {
let e = &self.dropped[j];
let near = (e.position.x - pos.x).abs() <= half
&& (e.position.z - pos.z).abs() <= half
&& e.position.y >= pos.y - 0.25
&& e.position.y <= pos.y + top;
let item = e.stack.item.clone();
let wants = villager::food_points(&item) > 0
|| picks_up.as_ref().is_some_and(|t| t.contains(&*item))
|| requested.contains(&&*item);
if !near || e.pickup_delay > 0 || !wants {
j += 1;
continue;
}
let max = self.item_max_stack(&item);
let stack = self.dropped[j].stack.clone();
if !villager::ext_mut(&mut self.mobs[i]).can_add(&stack, max) {
j += 1;
continue;
}
let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max);
match rest {
None => {
self.dropped.remove(j);
}
Some(rest) => {
self.dropped[j].stack.count = rest.count;
j += 1;
}
}
}
}
}
/// `Villager.setLastHurtByMob` and `ServerLevel.onReputationEvent`: a hit
/// from the player counts against it with the villager that was hit.
pub(super) fn villager_reputation_tick(&mut self) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let mut angry = Vec::new();
for m in &mut self.mobs {
if m.species() != Species::Villager
|| m.ai.last_hurt_by != Some(horizon_client::mobs::Who::Player)
{
continue;
}
let time = m.ai.last_hurt_by_time;
let alive = m.alive();
let at = m.position;
let e = villager::ext_mut(m);
if e.hurt_seen != time {
e.hurt_seen = time;
e.gossips.add(
uuid,
GossipType::MinorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
if alive {
angry.push(at);
}
}
}
for at in angry {
self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]);
}
}
/// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a
/// player kill one remember it as a major wrong.
pub(super) fn villager_murdered(&mut self, victim: &Mob, by_player: bool) {
if victim.species() != Species::Villager || !by_player {
return;
}
let Some(uuid) = self.level.player_uuid else {
return;
};
let eye = Vec3::new(victim.position.x, victim.eye_y(), victim.position.z);
let witnesses: Vec<usize> = {
let w = self.mob_world_base(&[]);
self.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.id != victim.id
&& m.species() == Species::Villager
&& m.alive()
&& (m.position.x - victim.position.x).abs() <= 16.0
&& (m.position.y - victim.position.y).abs() <= 16.0
&& (m.position.z - victim.position.z).abs() <= 16.0
&& w.line_of_sight(eye, Vec3::new(m.position.x, m.eye_y(), m.position.z))
})
.map(|(i, _)| i)
.collect()
};
for i in witnesses {
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::MajorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
}
}
/// `ReputationEventType.TRADE`: each trade earns a little trust.
pub(super) fn villager_traded(&mut self, id: u32) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let Some(i) = self.villager_index(id) else {
return;
};
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::Trading,
gossip::REPUTATION_CHANGE_PER_TRADE,
);
let p = self.mobs[i].position;
self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]);
}
/// `Villager.getPlayerReputation` of the local player.
pub(super) fn villager_reputation(&self, id: u32) -> i32 {
let Some(uuid) = self.level.player_uuid else {
return 0;
};
self.villager_index(id)
.and_then(|i| villager::ext(&self.mobs[i]))
.map_or(0, |e| e.gossips.reputation(uuid))
}
/// The Hero of the Village amplifier of the player, if any.
pub(super) fn hero_amplifier(&self) -> Option<i32> {
self.potions.effects.amplifier("hero_of_the_village")
}
}
+3 -2
View File
@@ -75,9 +75,9 @@ impl Game<'_> {
Ok(())
}
/// The wither boss bars (purple, below the dragon's), within range.
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) {
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 {
let Some(p) = self.player.as_ref() else {
return;
return y;
};
let atlas = &self.res.atlas;
for m in self
@@ -117,6 +117,7 @@ impl Game<'_> {
);
y += 19.0;
}
y
}
pub(super) fn wither_near(&self) -> bool {
self.player.as_ref().is_some_and(|p| {
+386
View File
@@ -0,0 +1,386 @@
//! Villager gossip (`GossipContainer` and `GossipType`): what a villager
//! remembers about each player, how it fades by the day, how it spreads from
//! villager to villager and the reputation it adds up to.
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::nbt::Tag;
use std::collections::BTreeMap;
/// `ReputationEventType` amounts.
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
const DISCARD_THRESHOLD: i32 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GossipType {
MajorNegative,
MinorNegative,
MinorPositive,
MajorPositive,
Trading,
}
impl GossipType {
pub const ALL: [Self; 5] = [
Self::MajorNegative,
Self::MinorNegative,
Self::MinorPositive,
Self::MajorPositive,
Self::Trading,
];
pub fn id(self) -> &'static str {
match self {
Self::MajorNegative => "major_negative",
Self::MinorNegative => "minor_negative",
Self::MinorPositive => "minor_positive",
Self::MajorPositive => "major_positive",
Self::Trading => "trading",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|t| t.id() == id)
}
fn index(self) -> usize {
self as usize
}
pub fn weight(self) -> i32 {
match self {
Self::MajorNegative => -5,
Self::MinorNegative => -1,
Self::MinorPositive => 1,
Self::MajorPositive => 5,
Self::Trading => 1,
}
}
pub fn max(self) -> i32 {
match self {
Self::MajorNegative => 100,
Self::MinorNegative => 200,
Self::MinorPositive | Self::Trading => 25,
Self::MajorPositive => 20,
}
}
pub fn decay_per_day(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 1,
Self::MajorPositive => 0,
Self::Trading => 2,
}
}
pub fn decay_per_transfer(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 5,
Self::MajorPositive | Self::Trading => 20,
}
}
}
/// A UUID as four ints.
pub type Target = [i32; 4];
/// One gossip entry (`GossipContainer.GossipEntry`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Entry {
target: Target,
kind: GossipType,
value: i32,
}
impl Entry {
fn weighted(self) -> i32 {
self.value * self.kind.weight()
}
}
/// `GossipContainer`: per target, the value of each gossip type (0: none).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gossips {
map: BTreeMap<Target, [i32; 5]>,
}
impl Gossips {
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn get(&self, target: Target, kind: GossipType) -> i32 {
self.map.get(&target).map_or(0, |e| e[kind.index()])
}
/// `getReputation`: the weighted sum of every type for a target.
pub fn reputation(&self, target: Target) -> i32 {
self.map.get(&target).map_or(0, |e| {
GossipType::ALL
.into_iter()
.map(|t| e[t.index()] * t.weight())
.sum()
})
}
/// How many targets have a gossip of `kind` whose weighted value passes `test`.
pub fn count_for_type(&self, kind: GossipType, test: impl Fn(f64) -> bool) -> usize {
self.map
.values()
.filter(|e| test(f64::from(e[kind.index()] * kind.weight())))
.count()
}
/// `add`: sums up to the type's maximum and forgets values below 2.
pub fn add(&mut self, target: Target, kind: GossipType, amount: i32) {
let entries = self.map.entry(target).or_insert([0; 5]);
let old = entries[kind.index()];
entries[kind.index()] = if old == 0 {
amount
} else {
let sum = old + amount;
if sum > kind.max() {
kind.max().max(old)
} else {
sum
}
};
let value = entries[kind.index()];
if value > kind.max() {
entries[kind.index()] = kind.max();
}
if value < DISCARD_THRESHOLD {
entries[kind.index()] = 0;
}
if entries.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
pub fn remove(&mut self, target: Target, kind: GossipType) {
if let Some(e) = self.map.get_mut(&target) {
e[kind.index()] = 0;
if e.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
}
/// `decay` (once per day): every type loses its daily amount.
pub fn decay(&mut self) {
self.map.retain(|_, e| {
for kind in GossipType::ALL {
let v = e[kind.index()];
if v == 0 {
continue;
}
let next = v - kind.decay_per_day();
e[kind.index()] = if next < DISCARD_THRESHOLD { 0 } else { next };
}
e.iter().any(|v| *v != 0)
});
}
fn unpack(&self) -> Vec<Entry> {
let mut out = Vec::new();
for (target, e) in &self.map {
for kind in GossipType::ALL {
if e[kind.index()] != 0 {
out.push(Entry {
target: *target,
kind,
value: e[kind.index()],
});
}
}
}
out
}
/// `selectGossipsForTransfer`: `max_count` picks weighted by magnitude,
/// duplicates counted once.
fn select_for_transfer(&self, random: &mut LegacyRandom, max_count: usize) -> Vec<Entry> {
let entries = self.unpack();
if entries.is_empty() {
return Vec::new();
}
let mut ends = Vec::with_capacity(entries.len());
let mut total = 0;
for e in &entries {
total += e.weighted().abs();
ends.push(total - 1);
}
let mut picked: Vec<usize> = Vec::new();
for _ in 0..max_count {
let choice = random.next_int_bound(total).unwrap_or(0);
// Arrays.binarySearch on the strictly increasing range ends.
let index = match ends.binary_search(&choice) {
Ok(i) | Err(i) => i,
};
if !picked.contains(&index) {
picked.push(index);
}
}
picked.into_iter().map(|i| entries[i]).collect()
}
/// `transferFrom`: gossip heard from another villager, weakened by the
/// retelling. Returns how many gossips were picked.
pub fn transfer_from(
&mut self,
source: &Gossips,
random: &mut LegacyRandom,
max_count: usize,
) -> usize {
let picked = source.select_for_transfer(random, max_count);
for g in &picked {
let decayed = g.value - g.kind.decay_per_transfer();
if decayed >= DISCARD_THRESHOLD {
let e = self.map.entry(g.target).or_insert([0; 5]);
let slot = &mut e[g.kind.index()];
*slot = (*slot).max(decayed);
}
}
picked.len()
}
pub fn to_nbt(&self) -> Tag {
Tag::List(
self.unpack()
.into_iter()
.map(|e| {
Tag::compound([
("Target", Tag::IntArray(e.target.to_vec())),
("Type", Tag::String(e.kind.id().into())),
("Value", Tag::Int(e.value)),
])
})
.collect(),
)
}
pub fn from_nbt(tag: &Tag) -> Self {
let mut out = Self::default();
let Tag::List(list) = tag else { return out };
for g in list {
let target = match g.get("Target") {
Some(Tag::IntArray(v)) if v.len() == 4 => [v[0], v[1], v[2], v[3]],
_ => continue,
};
let kind = match g.get("Type") {
Some(Tag::String(s)) => GossipType::from_id(&s.to_string_lossy()),
_ => None,
};
let value = match g.get("Value") {
Some(Tag::Int(v)) => *v,
_ => continue,
};
if let Some(kind) = kind
&& value > 0
{
out.map.entry(target).or_insert([0; 5])[kind.index()] = value;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const PLAYER: Target = [1, 2, 3, 4];
const OTHER: Target = [5, 6, 7, 8];
#[test]
fn reputation_adds_up_weighted() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MinorPositive, 25);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.add(PLAYER, GossipType::Trading, 2);
// 25 + 20 * 5 + 2
assert_eq!(g.reputation(PLAYER), 127);
g.add(PLAYER, GossipType::MajorNegative, 25);
assert_eq!(g.reputation(PLAYER), 127 - 125);
assert_eq!(g.reputation(OTHER), 0);
}
#[test]
fn values_stop_at_their_maximum() {
let mut g = Gossips::default();
for _ in 0..10 {
g.add(PLAYER, GossipType::MajorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 100);
// The minor negative cap is 200: eight hits of 25 fill it.
for _ in 0..12 {
g.add(PLAYER, GossipType::MinorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 200);
assert_eq!(g.reputation(PLAYER), -500 - 200);
}
#[test]
fn small_values_are_forgotten() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::Trading, 1);
assert!(g.is_empty());
g.add(PLAYER, GossipType::Trading, 2);
assert_eq!(g.get(PLAYER, GossipType::Trading), 2);
g.remove(PLAYER, GossipType::Trading);
assert!(g.is_empty());
}
#[test]
fn gossip_decays_by_the_day() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::MinorNegative, 25);
g.add(PLAYER, GossipType::MinorPositive, 3);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 15);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 2);
// Major positive gossip never fades.
assert_eq!(g.get(PLAYER, GossipType::MajorPositive), 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 0);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 0);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 0);
assert_eq!(g.len(), 1);
}
#[test]
fn retold_gossip_is_weaker() {
let mut source = Gossips::default();
source.add(PLAYER, GossipType::MajorNegative, 25);
source.add(OTHER, GossipType::Trading, 25);
let mut heard = Gossips::default();
let mut random = LegacyRandom::new(11);
let n = heard.transfer_from(&source, &mut random, 50);
assert!((1..=2).contains(&n));
// 25 - 10 per transfer for major negative, 25 - 20 for trading.
let major = heard.get(PLAYER, GossipType::MajorNegative);
let trading = heard.get(OTHER, GossipType::Trading);
assert!(major == 0 || major == 15);
assert!(trading == 0 || trading == 5);
assert!(major + trading > 0);
// A second hearing keeps the stronger value.
heard.transfer_from(&source, &mut random, 50);
assert!(heard.get(PLAYER, GossipType::MajorNegative) <= 15);
// Gossip too weak to survive retelling is dropped.
let mut faint = Gossips::default();
faint.add(PLAYER, GossipType::Trading, 5);
let mut heard = Gossips::default();
heard.transfer_from(&faint, &mut random, 10);
assert!(heard.is_empty());
}
#[test]
fn gossip_round_trips_through_nbt() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::Trading, 2);
g.add(OTHER, GossipType::MinorPositive, 25);
assert_eq!(Gossips::from_nbt(&g.to_nbt()), g);
}
#[test]
fn counts_by_type() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::Trading, 25);
assert_eq!(g.count_for_type(GossipType::MajorNegative, |v| v < 0.0), 2);
assert_eq!(g.count_for_type(GossipType::Trading, |v| v < 0.0), 0);
}
}
+104
View File
@@ -35,7 +35,27 @@ pub struct StackData {
pub writable_pages: Vec<String>,
/// `minecraft:written_book_content`.
pub written: Option<WrittenBook>,
/// `minecraft:banner_patterns` (banners and shields).
pub banner_patterns: Vec<crate::banner::BannerLayer>,
/// `minecraft:base_color` (a shield's dye).
pub base_color: Option<Arc<str>>,
/// The raid captain's banner: `minecraft:banner_patterns` with the
/// ominous layers, its item name, rarity and hidden tooltip.
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
("rhombus", "cyan"),
("stripe_bottom", "light_gray"),
("stripe_center", "gray"),
("border", "light_gray"),
("stripe_middle", "black"),
("half_horizontal", "light_gray"),
("circle", "light_gray"),
("border", "black"),
];
/// `WrittenBookContent` with the pages as plain text.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WrittenBook {
@@ -267,6 +287,15 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
if let Some(id) = d.map_id {
entries.push(("minecraft:map_id", Tag::Int(id)));
}
if !d.banner_patterns.is_empty() {
entries.push((
"minecraft:banner_patterns",
crate::banner::layers_to_nbt(&d.banner_patterns),
));
}
if let Some(color) = &d.base_color {
entries.push(("minecraft:base_color", Tag::String((&**color).into())));
}
// Filterable values are saved as {raw: ..}.
let raw = |t: Tag| Tag::compound([("raw", t)]);
if !d.writable_pages.is_empty() {
@@ -330,6 +359,39 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()),
));
}
if d.ominous_banner {
let layer = |pattern: &str, color: &str| {
Tag::compound([
(
"pattern",
Tag::String(format!("minecraft:{pattern}").as_str().into()),
),
("color", Tag::String(color.into())),
])
};
entries.push((
"minecraft:banner_patterns",
Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()),
));
entries.push((
"minecraft:tooltip_display",
Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]),
)]),
));
entries.push((
"minecraft:item_name",
Tag::compound([(
"translate",
Tag::String("block.minecraft.ominous_banner".into()),
)]),
));
entries.push(("minecraft:rarity", Tag::String("uncommon".into())));
}
if let Some(a) = d.ominous_amplifier {
entries.push(("minecraft:ominous_bottle_amplifier", Tag::Int(i32::from(a))));
}
if !d.container.is_empty() {
let slots = d
.container
@@ -371,6 +433,11 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
custom_name: c.get("minecraft:custom_name").and_then(read_text),
potion,
map_id: c.get("minecraft:map_id").and_then(int).map(|v| v as i32),
banner_patterns: crate::banner::layers_from_nbt(c.get("minecraft:banner_patterns")),
base_color: c
.get("minecraft:base_color")
.and_then(string)
.map(|s| Arc::from(s.as_str())),
writable_pages: match c
.get("minecraft:writable_book_content")
.and_then(|b| b.get("pages"))
@@ -435,6 +502,15 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
.map(|v| v.clamp(0, 4) as u8),
trim: c.get("minecraft:trim").and_then(|t| {
Some((
Arc::from(t.get("material").and_then(string)?.as_str()),
@@ -499,6 +575,34 @@ mod tests {
assert_eq!(back.custom_name(), Some("Blade"));
}
#[test]
fn banner_layers_and_shield_base_round_trip() {
let mut stack = ItemStack::new("minecraft:shield", 1);
stack.data_mut().base_color = Some(Arc::from("red"));
stack.data_mut().banner_patterns = vec![
crate::banner::BannerLayer::new("minecraft:flower", "black"),
crate::banner::BannerLayer::new("minecraft:border", "white"),
];
let tag = encode_components(&stack).expect("components");
let (_, extra) = decode_components(Some(&tag));
let extra = extra.expect("data");
assert_eq!(extra.base_color.as_deref(), Some("red"));
assert_eq!(extra.banner_patterns, stack.data().unwrap().banner_patterns);
}
#[test]
fn ominous_items_round_trip() {
let mut banner = ItemStack::new("minecraft:white_banner", 1);
banner.data_mut().ominous_banner = true;
let tag = encode_components(&banner).unwrap();
assert!(tag.get("minecraft:banner_patterns").is_some());
let (_, back) = decode_components(Some(&tag));
assert!(back.unwrap().ominous_banner);
let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1);
bottle.data_mut().ominous_amplifier = Some(3);
let (_, back) = decode_components(encode_components(&bottle).as_ref());
assert_eq!(back.unwrap().ominous_amplifier, Some(3));
}
#[test]
fn plain_stacks_have_no_components() {
let stack = ItemStack::new("minecraft:stone", 64);
+25
View File
@@ -53,6 +53,10 @@ pub struct ItemInfo {
pub glider: bool,
/// `equippable.swappable` and `equip_sound`.
pub swappable: bool,
/// `equippable.dispensable` (dispensers may put it on an entity).
pub equip_dispensable: bool,
/// `equippable.allowed_entities` resolved to entity type ids; None allows all.
pub equip_allowed: Option<HashSet<String>>,
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
@@ -251,6 +255,13 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
})
.collect())
}
/// An entity type id or `#tag` as the set of entity type ids it names.
fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<String> {
match spec.strip_prefix('#') {
Some(tag) => tags.get(tag).cloned().unwrap_or_default(),
None => HashSet::from([spec.to_owned()]),
}
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
@@ -264,6 +275,7 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
for (name, c) in &raw {
@@ -323,6 +335,19 @@ impl Items {
swappable: c["minecraft:equippable"]["swappable"]
.as_bool()
.unwrap_or(true),
equip_dispensable: c["minecraft:equippable"]["dispensable"]
.as_bool()
.unwrap_or(true),
equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] {
Value::String(spec) => Some(entity_spec(&entity_tags, spec)),
Value::Array(list) => Some(
list.iter()
.filter_map(Value::as_str)
.flat_map(|spec| entity_spec(&entity_tags, spec))
.collect(),
),
_ => None,
},
equip_sound: c["minecraft:equippable"]["equip_sound"]
.as_str()
.map(str::to_owned),
+4
View File
@@ -7,6 +7,7 @@ pub mod animate_tick;
pub mod assets;
pub mod attribute_updates;
pub mod audio;
pub mod banner;
pub mod biome;
pub mod block_entity_render;
pub mod blocks;
@@ -34,6 +35,7 @@ pub mod fog;
pub mod font;
pub mod gamerules;
pub mod gfx;
pub mod gossip;
pub mod health;
pub mod hud;
pub mod hunger;
@@ -58,7 +60,9 @@ pub mod packs;
pub mod particles;
pub mod pose;
pub mod projectiles;
pub mod raid;
pub mod random_sequences;
pub mod recipe_book;
pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
+43
View File
@@ -98,6 +98,23 @@ impl Trader {
}
}
/// `Villager.updateSpecialPrices`: the reputation and Hero of the Village
/// discounts of a player, from scratch.
pub fn update_special_prices(offers: &mut [MerchantOffer], reputation: i32, hero: Option<i32>) {
// 0.3F + 0.0625F * amplifier, widened from float.
let hero_modifier = hero.map_or(0.0, |a| f64::from(0.3f32 + 0.0625f32 * a as f32));
for offer in offers {
offer.special_price_diff = 0;
if reputation != 0 {
offer.special_price_diff -= (reputation as f32 * offer.price_multiplier).floor() as i32;
}
if hero_modifier > 0.0 {
let reduction =
(hero_modifier * f64::from(offer.base_cost_a.stack.count)).floor() as i32;
offer.special_price_diff -= reduction.max(1);
}
}
}
/// An `ItemCost`: item and count (component predicates are not used by the
/// 26.3 trade data except for one exact match, kept as the stack's data).
#[derive(Clone, Debug, PartialEq)]
@@ -708,6 +725,32 @@ mod tests {
assert!(!can_level_up(5));
}
#[test]
fn reputation_and_heroes_lower_prices() {
let items = items();
let mut offers = vec![offer(10, None), offer(1, None)];
// Reputation 50 with a 0.2 multiplier: 10 off, floored per offer.
update_special_prices(&mut offers, 50, None);
assert_eq!(offers[0].special_price_diff, -10);
assert_eq!(offers[0].cost_a_count(&items), 1);
assert_eq!(offers[1].special_price_diff, -10);
// Bad reputation raises the price (-30 * 0.2 = -6 floors to -6).
update_special_prices(&mut offers, -30, None);
assert_eq!(offers[0].special_price_diff, 6);
assert_eq!(offers[0].cost_a_count(&items), 16);
// Hero of the Village I: 0.3 * 10 = 3 off, at least 1.
update_special_prices(&mut offers, 0, Some(0));
assert_eq!(offers[0].special_price_diff, -3);
assert_eq!(offers[1].special_price_diff, -1);
// Level III: 0.3 + 0.125 = 0.425 -> 4 off a ten emerald price.
update_special_prices(&mut offers, 0, Some(2));
assert_eq!(offers[0].special_price_diff, -4);
// Both stack, from scratch each time.
update_special_prices(&mut offers, 25, Some(0));
assert_eq!(offers[0].special_price_diff, -5 - 3);
update_special_prices(&mut offers, 0, None);
assert_eq!(offers[0].special_price_diff, 0);
}
#[test]
fn offers_follow_the_trade_data() {
let items = items();
+67
View File
@@ -11,6 +11,7 @@ pub mod anim;
pub mod aquatic;
pub mod camel;
pub mod control;
pub mod creaking;
pub mod cube;
pub mod data;
pub mod enderman;
@@ -28,6 +29,7 @@ pub mod nether;
pub mod path;
pub mod phantom;
pub mod piglin;
pub mod raider;
pub mod ravager;
pub mod render;
pub mod shulker;
@@ -433,8 +435,12 @@ pub struct Extra {
/// Dye colour id (sheep wool, collars).
pub color: u8,
pub sheared: bool,
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
pub tame: bool,
pub sitting: bool,
/// The owner's UUID (tamed animals).
@@ -473,6 +479,10 @@ pub struct Extra {
pub meeting: Option<[i32; 3]>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
/// A raider's patrol and raid state.
pub raider: Option<Box<raider::State>>,
/// A villager's raid activity and gossip.
pub villager: Option<Box<villager::Ext>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -663,11 +673,60 @@ pub enum MobEvent {
kind: DamageKind,
amount: f32,
},
/// Two villagers are close: swap gossip and share food and wares.
VillagerMeet {
mob: u32,
other: u32,
},
/// Two villagers make a baby.
VillagerBirth {
parent: u32,
partner: u32,
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
mob: u32,
needed: usize,
},
/// A villager launches a firework rocket (celebrating a won raid).
Firework {
at: [f64; 3],
color: usize,
flight: u8,
},
/// A villager throws a hero's gift (a loot table) toward the player.
ThrowGift {
table: String,
from: [f64; 3],
to: [f64; 3],
},
/// A patrol leader hands its patrol target to a companion.
PatrolTarget {
mob: u32,
target: [i32; 3],
},
/// A raider is told to attack (`HoldGroundAttackGoal` shouting).
RaiderTarget {
mob: u32,
target: Who,
aggressive: bool,
},
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
GiftLoot {
table: &'static str,
at: [f64; 3],
},
/// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it).
CreakingHurt {
home: [i32; 3],
by_player: bool,
id: u32,
},
/// `Creaking.tearDown`: crumbling particles around the creaking.
CreakingTearDown {
center: [f64; 3],
spread: [f64; 3],
},
}
/// How a spawned-by-kind mob should be set up.
#[derive(Clone, Debug, Default)]
@@ -707,6 +766,10 @@ pub struct Seen {
/// A villager's claimed job site and bed.
pub job: Option<[i32; 3]>,
pub bed: Option<[i32; 3]>,
/// A raider in an active raid.
pub active_raid: bool,
/// A villager's reputation of the player (`getPlayerReputation`).
pub player_rep: i32,
}
/// The player as mobs see it.
#[derive(Clone, Debug)]
@@ -729,6 +792,10 @@ pub struct PlayerView {
pub hurt_by: Option<(Who, i64)>,
/// `getLastHurtMob` and when.
pub last_hurt: Option<(Who, i64)>,
/// The Hero of the Village effect.
pub hero: bool,
/// The player's UUID (villagers' gossip is keyed by it).
pub uuid: [i32; 4],
}
pub struct MobWorld<'a> {
pub world: &'a World,
+26 -1
View File
@@ -87,6 +87,7 @@ pub enum Family {
Wither,
Allay,
Villager,
Creaking,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -121,6 +122,7 @@ pub fn family(s: Species) -> Family {
S::Ravager => Family::Ravager,
S::Wither => Family::Wither,
S::Allay => Family::Allay,
S::Creaking => Family::Creaking,
S::Villager => Family::Villager,
S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin,
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => {
@@ -169,7 +171,9 @@ 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::Creaking => super::creaking::register(m),
}
super::raider::register(m);
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
@@ -251,7 +255,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
return false;
}
base_tick(m, w, events);
if m.death_time >= 20 {
if m.death_time >= super::creaking::death_limit(m) {
// Creaking.tickDeath: a heart's creaking crumbles away.
if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) {
super::creaking::tear_down(m, events);
}
return false;
}
if !m.no_ai {
@@ -393,6 +401,8 @@ 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",
// Creaking.getAmbientSound: silent while awake.
Species::Creaking if m.extra.flag => return,
// Shulker.playAmbientSound: silent while closed.
Species::Shulker if m.extra.counter == 0 => return,
Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry",
@@ -407,6 +417,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if super::creaking::is_creaking(m) {
super::creaking::update(m, w, events);
}
if m.ai.no_jump_delay > 0 {
m.ai.no_jump_delay -= 1;
}
@@ -488,6 +501,10 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
/// Mob.serverAiStep
fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.ai.no_action_time += 1;
// A creaking looked at stands still.
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
return;
}
// A saddled mount follows its rider instead of its goals.
if super::equine::controlled(m) {
super::equine::ridden_step(m);
@@ -589,6 +606,10 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
}
let Some(p) = &w.player else { return true };
let d = m.distance_sqr(p.position);
// Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`).
if super::raider::keeps_alive(m, d) {
return true;
}
let despawn = if m.kind.category == "water_ambient" {
64.0
} else {
@@ -666,6 +687,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
match m.species() {
// Allay.hurtServer: its liked player cannot hurt it.
Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false,
Species::Creaking => super::creaking::accepts_damage(m, source),
Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false),
Species::Shulker => super::shulker::accepts(m, source),
Species::Enderman => super::enderman::on_damage(m, source),
@@ -709,6 +731,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if m.species() == Species::Ravager {
super::ravager::on_attack(m, cx.events);
}
if super::creaking::is_creaking(m) {
super::creaking::on_attack(m, cx.events);
}
let mut amount = m.attrs.attack_damage;
let from = [m.position.x, m.position.y, m.position.z];
let source = Damage::mob(m.id, from);
+2
View File
@@ -9,6 +9,7 @@ use std::f32::consts::PI;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Anim {
Allay,
Creaking,
Camel,
Wither,
Vex,
@@ -346,6 +347,7 @@ pub fn setup(
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Allay => super::allay::anim(m, s, p),
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => {
super::aquatic::anim(m, s, p)
}
+365
View File
@@ -0,0 +1,365 @@
//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at
//! them, wake up when one looks from within 12 blocks, then hunt the nearest
//! visible player and hit every 40 ticks. One bound to a creaking heart takes
//! no damage (it only sways and hurts the heart's resin spreader), dies when
//! the heart no longer protects it and falls apart with the heart.
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone},
keyframes::Animation,
path::PathType,
};
use crate::containers::BlockEntity;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
/// `Extra.ints` slots.
const INVULNERABLE: usize = 0;
const ATTACKING: usize = 1;
const STUCK: usize = 2;
const TEARING_DOWN: usize = 3;
const EYES: usize = 4;
const NEXT_FLICKER: usize = 5;
/// `Extra.counter` bits: hurt while protected, and by a player.
const HURT: i32 = 1;
const HURT_BY_PLAYER: i32 = 2;
/// `Creaking.ACTIVATION_RANGE_SQ`.
const ACTIVATION_RANGE_SQ: f64 = 144.0;
/// `Creaking.INVULNERABILITY_ANIMATION_DURATION` and the attack animation.
const INVULNERABILITY_TICKS: i32 = 8;
const ATTACK_TICKS: i32 = 15;
/// `Creaking.TWITCH_DEATH_DURATION`.
const TWITCH_TICKS: i32 = 45;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(2, MeleeAttack::new(1.0, false).interval(40));
g.add(5, Stroll::avoiding_water(0.3));
g.add(6, LookAtPlayer::new(8.0));
m.ai.targets.add(1, HuntPlayer);
}
/// Bound to a heart (`getHomePos() != null`).
pub fn heart_bound(m: &Mob) -> bool {
is_creaking(m) && m.extra.home.is_some()
}
pub fn tearing_down(m: &Mob) -> bool {
is_creaking(m) && m.extra.ints[TEARING_DOWN] != 0
}
/// `Creaking.canMove`: false while a player looks at it.
pub fn can_move(m: &Mob) -> bool {
!m.extra.flag2
}
/// `Creaking.isActive`.
pub fn is_active(m: &Mob) -> bool {
m.extra.flag
}
/// `Creaking.setTransient`: bind to the heart at `pos` and avoid damage.
pub fn set_transient(m: &mut Mob, pos: [i32; 3]) {
m.extra.home = Some(pos);
m.set_malus(PathType::Damaging, 8.0);
m.set_malus(PathType::PowderSnow, 8.0);
m.set_malus(PathType::Lava, 8.0);
m.set_malus(PathType::Fire, 0.0);
m.set_malus(PathType::FireInNeighbor, 0.0);
}
/// `Creaking.setTearingDown`: the heart was broken by someone.
pub fn set_tearing_down(m: &mut Mob) {
m.extra.ints[TEARING_DOWN] = 1;
}
/// `Creaking.hasGlowingEyes` / `isActive`: the eyes layer shows.
pub fn eyes_glowing(m: &Mob) -> bool {
if tearing_down(m) {
m.extra.ints[EYES] != 0
} else {
is_active(m)
}
}
/// Ticks of death animation before the mob is removed (`tickDeath`).
pub fn death_limit(m: &Mob) -> i32 {
if heart_bound(m) && tearing_down(m) {
TWITCH_TICKS + 1
} else {
20
}
}
/// `Creaking.tearDown`: crumbles away.
pub fn tear_down(m: &mut Mob, events: &mut Vec<MobEvent>) {
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
events.push(MobEvent::CreakingTearDown {
center: [
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
],
spread: [
(hi.x - lo.x) * 0.3,
(hi.y - lo.y) * 0.3,
(hi.z - lo.z) * 0.3,
],
});
m.voice("entity.creaking.death", events);
m.removed = true;
}
/// `Creaking.hurtServer` for a heart-bound creaking: no damage, only the
/// invulnerability animation and the heart's reaction. Returns whether the
/// normal damage path should run.
pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
if !heart_bound(m) || source.kind == DamageKind::Generic {
return true;
}
if source.is_fire() || !m.alive() || m.extra.ints[INVULNERABLE] > 0 {
return false;
}
let by_player = source.attacker == Some(Who::Player);
// The direct entity must be living or a projectile (or a player must be to blame).
let direct = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
| DamageKind::Fireball
| DamageKind::Thorns
);
if !direct && !by_player {
return false;
}
m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS;
m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 };
false
}
/// `Creaking.doHurtTarget` extras: the attack animation and sound.
pub fn on_attack(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.extra.ints[ATTACKING] = ATTACK_TICKS;
m.voice("entity.creaking.attack", events);
}
/// The heart this creaking is bound to protects it (`isProtector`); a link
/// read from a save is trusted until the heart resolves it.
fn protected(m: &Mob, w: &MobWorld) -> bool {
let Some(home) = m.extra.home else {
return true;
};
match w.world.block_entities.get(&(home[0], home[1], home[2])) {
Some(BlockEntity::CreakingHeart(h)) => match h.creaking {
Some((Some(id), _)) => id == m.id,
Some((None, _)) => true,
None => false,
},
_ => false,
}
}
/// `Creaking.tick` and the start of `aiStep`: protection, timers, freezing.
pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
// Creaking.tick: without its heart's protection it dies.
if heart_bound(m) && m.alive() && !protected(m, w) {
m.health = 0.0;
}
for slot in [INVULNERABLE, ATTACKING] {
if m.extra.ints[slot] > 0 {
m.extra.ints[slot] -= 1;
}
}
let age = m.age as f32;
m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age);
m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age);
m.anim.states[2].animate_when(tearing_down(m), age);
if m.extra.counter & HURT != 0 {
// hurtServer: sway, and the heart reacts to a player's hit.
if protected(m, w) {
let by_player = m.extra.counter & HURT_BY_PLAYER != 0;
if let Some(home) = m.extra.home {
events.push(MobEvent::CreakingHurt {
home,
by_player,
id: m.id,
});
}
m.voice("entity.creaking.sway", events);
}
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
}
// checkEyeBlink: the eyes of a creaking falling apart flicker.
if m.death_time > m.extra.ints[NEXT_FLICKER] {
let glowing = m.extra.ints[EYES] != 0;
let (lo, hi) = if glowing {
(2, 8)
} else {
(m.death_time / 4, m.death_time / 2)
};
let span = (hi - lo + 1).max(1);
m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0);
m.extra.ints[EYES] = i32::from(!glowing);
}
if !m.alive() {
return;
}
let now = check_can_move(m, w, events);
if now != can_move(m) {
if now {
m.voice("entity.creaking.unfreeze", events);
} else {
stop_in_place(m);
m.voice("entity.creaking.freeze", events);
}
m.extra.flag2 = !now;
}
}
/// `Mob.stopInPlace`.
pub fn stop_in_place(m: &mut Mob) {
m.nav_stop();
m.ai.xxa = 0.0;
m.ai.yya = 0.0;
m.ai.zza = 0.0;
m.ai.speed = 0.0;
}
fn activate(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.ai.target = Some(Who::Player);
m.voice("entity.creaking.activate", events);
m.extra.flag = true;
}
fn deactivate(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.ai.target = None;
m.voice("entity.creaking.deactivate", events);
m.extra.flag = false;
}
/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`.
fn looked_at_by(m: &Mob, w: &MobWorld) -> bool {
let Some(p) = &w.player else { return false };
let look = p.look;
let eye = m.eye_y();
[eye, m.position.y + 0.5, (eye + m.position.y) / 2.0]
.into_iter()
.any(|y| {
let d = [
m.position.x - p.position.x,
y - p.eye[1],
m.position.z - p.position.z,
];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if len < 1.0e-6 {
return true;
}
let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len;
dot > 0.5
&& w.line_of_sight(
Vec3::new(p.eye[0], p.eye[1], p.eye[2]),
Vec3::new(m.position.x, y, m.position.z),
)
})
}
/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it.
fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
let active = is_active(m);
// NEAREST_PLAYERS: players within the follow range.
let near = w.player.as_ref().filter(|p| {
let d = Vec3::new(p.position.x, p.position.y, p.position.z);
m.distance_sqr(d) < 32.0 * 32.0
});
let Some(p) = near else {
if active {
deactivate(m, events);
}
return true;
};
// canAttack: alive and not creative or spectator.
let attackable = p.alive && !p.creative;
if attackable {
// GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake.
let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin");
if (!active || !disguised) && looked_at_by(m, w) {
if active {
return false;
}
if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ {
activate(m, events);
return false;
}
}
} else if active {
deactivate(m, events);
}
true
}
/// `Creaking.playerIsStuckInYou`: the player's eyes inside it for more than 4 ticks.
pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool {
let Some(eye) = eye else {
m.extra.ints[STUCK] = 0;
return false;
};
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
let inside = eye[0] >= lo.x
&& eye[0] <= hi.x
&& eye[1] >= lo.y
&& eye[1] <= hi.y
&& eye[2] >= lo.z
&& eye[2] <= hi.z;
if inside {
m.extra.ints[STUCK] += 1;
m.extra.ints[STUCK] > 4
} else {
m.extra.ints[STUCK] = 0;
false
}
}
/// The nearest attackable player the creaking can see.
fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool {
let Some(p) = &cx.w.player else {
return false;
};
let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2);
p.alive && !p.creative && near && m.sees(cx.w, Who::Player)
}
/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the
/// nearest visible player.
#[derive(Clone, Debug)]
struct HuntPlayer;
impl Goal for HuntPlayer {
goal_clone!();
fn flags(&self) -> u8 {
TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !is_active(m) || !sees_attackable_player(m, cx) {
return false;
}
m.ai.target = Some(Who::Player);
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx)
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
if m.ai.target == Some(Who::Player) {
m.ai.target = None;
}
}
}
/// `CreakingModel.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!("CreakingAnimation.CREAKING_{n}"));
if can_move(m)
&& let Some(walk) = get("WALK")
{
walk.apply_walk(s.pos, s.speed, 1.0, 1.0, p);
}
for (state, name) in [
(&m.anim.states[0], "ATTACK"),
(&m.anim.states[1], "INVULNERABLE"),
(&m.anim.states[2], "DEATH"),
] {
if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) {
a.apply(ms, 1.0, p);
}
}
}
/// The creaking species exists in the species table.
pub fn is_creaking(m: &Mob) -> bool {
m.species() == Species::Creaking
}
+8 -1
View File
@@ -731,6 +731,8 @@ pub struct MeleeAttack {
pub until_attack: i32,
last_check: i64,
raise_arm: i32,
/// Ticks between attacks (20 unless set).
pub interval: i32,
}
impl MeleeAttack {
pub fn new(speed: f64, follow_unseen: bool) -> Self {
@@ -743,12 +745,17 @@ impl MeleeAttack {
until_attack: 0,
last_check: i64::MIN / 2,
raise_arm: 0,
interval: 20,
}
}
pub fn zombie(mut self) -> Self {
self.zombie = true;
self
}
pub fn interval(mut self, ticks: i32) -> Self {
self.interval = ticks;
self
}
}
impl Goal for MeleeAttack {
goal_clone!();
@@ -834,7 +841,7 @@ impl Goal for MeleeAttack {
}
self.until_attack = (self.until_attack - 1).max(0);
if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) {
self.until_attack = adjusted(true, 20);
self.until_attack = adjusted(true, self.interval);
m.swing();
super::ai::do_hurt_target(m, who, cx);
}
+43
View File
@@ -36,6 +36,7 @@ pub fn register_iron(m: &mut Mob) {
);
g.add(7, LookAtPlayer::new(6.0));
g.add(8, RandomLookAround::default());
m.ai.targets.add(1, DefendVillage);
m.ai.targets.add(2, HurtByTarget::new());
m.ai.targets.add(
3,
@@ -48,6 +49,48 @@ pub fn register_iron(m: &mut Mob) {
NearestTarget::new(Prey::Filter(golem_prey), false).interval(5),
);
}
/// `DefendVillageTargetGoal`: a player that a villager nearby has no
/// good word for (reputation of -100 or worse) is attacked on sight.
#[derive(Clone, Debug)]
struct DefendVillage;
impl Goal for DefendVillage {
goal_clone!();
fn flags(&self) -> u8 {
super::goals::TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(p) = &cx.w.player else { return false };
if !p.alive || p.creative || p.spectator {
return false;
}
// The box around the golem: 10 across, 8 up and down.
let b = m.bounds().inflate(Vec3::new(10.0, 8.0, 10.0));
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
return false;
}
let bad = cx.w.others.iter().any(|s| {
s.species == Species::Villager
&& s.alive
&& s.player_rep <= -100
&& b.contains(s.position)
&& s.position.distance_squared(m.position) <= 64.0 * 64.0
});
bad && m.sees(cx.w, Who::Player)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.target_info(cx.w).is_some_and(|t| {
t.alive
&& !(t.is_player && t.creative)
&& m.position.distance_squared(t.position) <= 64.0 * 64.0
})
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = Some(Who::Player);
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = None;
}
}
/// `MoveTowardsTargetGoal`: close in on a target within range.
#[derive(Clone, Debug)]
struct MoveTowardsTarget {
+27 -5
View File
@@ -384,8 +384,10 @@ impl CrossbowAttack {
pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal {
CrossbowAttack::new(speed, radius)
}
/// `CrossbowItem.getChargeDuration` without Quick Charge.
const CHARGE: i32 = 25;
/// `CrossbowItem.getChargeDuration` (25 ticks, 5 fewer per level of Quick Charge).
pub fn charge_ticks(m: &Mob) -> i32 {
25 - 5 * i32::from(super::raider::state(m).map_or(0, |s| s.enchant))
}
fn holding_crossbow(m: &Mob) -> bool {
m.extra.main_hand.as_deref() == Some("minecraft:crossbow")
}
@@ -469,7 +471,7 @@ impl Goal for CrossbowAttack {
}
Crossbow::Charging => {
m.extra.using_item += 1;
if m.extra.using_item >= CHARGE {
if m.extra.using_item >= charge_ticks(m) {
m.extra.using_item = 0;
m.extra.flag = false;
self.state = Crossbow::Charged;
@@ -534,6 +536,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
enum ArmPose {
Spellcasting,
Crossed,
Celebrating,
Neutral,
Attacking,
CrossbowHold,
@@ -554,16 +557,22 @@ fn arm_pose(m: &Mob) -> ArmPose {
}
}
Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Evoker if celebrating(m) => ArmPose::Celebrating,
Species::Evoker => ArmPose::Crossed,
_ => {
if m.ai.aggressive {
ArmPose::Attacking
} else if celebrating(m) {
ArmPose::Celebrating
} else {
ArmPose::Crossed
}
}
}
}
fn celebrating(m: &Mob) -> bool {
super::raider::state(m).is_some_and(|s| s.celebrating)
}
/// Whether the held item shows (vindicators only draw their axe when angry).
pub fn shows_item(m: &Mob) -> bool {
m.species() != Species::Vindicator || m.ai.aggressive
@@ -637,8 +646,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
ArmPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
let a =
(m.extra.using_item as f32 + s.partial).clamp(0.0, CHARGE as f32) / CHARGE as f32;
let charge = charge_ticks(m) as f32;
let a = (m.extra.using_item as f32 + s.partial).clamp(0.0, charge) / charge;
p.yrot("left_arm", 0.4 + (0.85 - 0.4) * a);
p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a);
}
@@ -655,6 +664,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
v[5] = z_rot;
}
}
ArmPose::Celebrating => {
for (arm, x, z_rot) in [
("right_arm", -5.0, 2.670_354),
("left_arm", 5.0, -PI * 0.75),
] {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.05;
v[4] = 0.0;
v[5] = z_rot;
}
}
ArmPose::Crossed | ArmPose::Neutral => {}
}
if pose == ArmPose::Crossed {
+6 -1
View File
@@ -437,7 +437,12 @@ impl Mob {
let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32;
self.previous_limb_speed = self.limb_speed;
if self.alive() {
let target = (distance * 4.0).min(1.0);
// Creaking.updateWalkAnimation walks the model faster.
let target = if self.species() == super::Species::Creaking {
(distance * 25.0).min(3.0)
} else {
(distance * 4.0).min(1.0)
};
self.limb_speed += (target - self.limb_speed) * 0.4;
self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 };
} else {
+678
View File
@@ -0,0 +1,678 @@
//! Raiders (`PatrollingMonster` and `Raider`): the patrol state every
//! pillager, vindicator, evoker, witch and ravager carries, the long
//! distance patrol and hold-ground goals, the ominous banner a patrol leader
//! wears, and the saved fields.
use super::{
Mob, MobEvent, MobWorld, Species, Who,
goals::{Cx, Goal, LOOK, MOVE, goal_clone},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_world::nbt::Tag;
/// The ominous banner is a white banner with the raid patterns; raiders wear
/// it as their head item.
pub const BANNER: &str = "minecraft:white_banner";
/// `PatrollingMonster` and `Raider` state (saved as `patrol_target`,
/// `PatrolLeader`, `Patrolling`, `Wave`, `CanJoinRaid`, `RaidId`).
#[derive(Clone, Debug, Default)]
pub struct State {
pub patrol_leader: bool,
pub patrolling: bool,
pub patrol_target: Option<[i32; 3]>,
/// Goal cooldown after a failed long distance path (game time).
pub patrol_cooldown_until: i64,
pub wave: i32,
pub can_join_raid: bool,
/// The raid this raider belongs to.
pub raid_id: Option<i32>,
pub ticks_outside_raid: i32,
pub celebrating: bool,
/// The raid is active (`hasActiveRaid`); set by the game every tick.
pub active_raid: bool,
/// The raid is won or lost (`Raid.isOver`), lost (`isLoss`).
pub raid_over: bool,
pub raid_loss: bool,
pub raid_center: [i32; 3],
/// Standing in or beside a village (`ServerLevel.isVillage`).
pub in_village: bool,
/// A dropped ominous banner this raider may fetch.
pub banner_at: Option<[f64; 3]>,
/// Beds around the raid's centre.
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
/// The ravager this raider rides, and (for a ravager) that it carries one.
pub vehicle: Option<u32>,
pub rider: bool,
/// Quick Charge (pillager crossbows) or Sharpness (vindicator axes) from
/// the raid's enchanting.
pub enchant: u8,
}
impl State {
/// A ravager carrying a raider (`hasControllingPassenger`).
pub fn has_rider(&self) -> bool {
self.rider
}
}
/// The raider species (`EntityTypeTags.RAIDERS`).
pub fn is_raider(s: Species) -> bool {
matches!(
s,
Species::Pillager
| Species::Vindicator
| Species::Evoker
| Species::Witch
| Species::Ravager
)
}
/// `canBeLeader`: witches and ravagers never lead.
pub fn can_be_leader(s: Species) -> bool {
is_raider(s) && !matches!(s, Species::Witch | Species::Ravager)
}
pub fn state(m: &Mob) -> Option<&State> {
m.extra.raider.as_deref()
}
pub fn state_mut(m: &mut Mob) -> &mut State {
m.extra.raider.get_or_insert_with(Box::default)
}
pub fn has_active_raid(m: &Mob) -> bool {
state(m).is_some_and(|s| s.active_raid)
}
/// `Raider.isCaptain`: the banner on the head of a patrol leader.
pub fn is_captain(m: &Mob) -> bool {
m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader)
}
pub fn register(m: &mut Mob) {
if !is_raider(m.species()) {
return;
}
m.extra.raider = Some(Box::default());
let species = m.species();
m.ai.goals.add(1, ObtainBanner);
m.ai.goals.add(3, PathfindToRaid);
m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0));
m.ai.goals.add(5, Celebration);
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
// The illagers hold their ground in a patrol (Witch and Ravager do not).
if matches!(species, Species::Pillager | Species::Vindicator) {
m.ai.goals.add(
if species == Species::Pillager { 2 } else { 4 },
HoldGroundAttack::new(10.0),
);
}
}
/// `Raid.getOminousBannerInstance`.
pub fn ominous_banner() -> crate::items::ItemStack {
let mut stack = crate::items::ItemStack::new(BANNER, 1);
stack.data_mut().ominous_banner = true;
stack
}
/// `PatrollingMonster.setPatrolLeader`.
pub fn set_patrol_leader(m: &mut Mob, leader: bool) {
let s = state_mut(m);
s.patrol_leader = leader;
s.patrolling = true;
}
/// `PatrollingMonster.setPatrolTarget`.
pub fn set_patrol_target(m: &mut Mob, target: [i32; 3]) {
let s = state_mut(m);
s.patrol_target = Some(target);
s.patrolling = true;
}
/// `PatrollingMonster.findPatrolTarget`: somewhere within 500 blocks.
pub fn find_patrol_target(m: &mut Mob) {
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
find_patrol_target_from(m, at);
}
/// `findPatrolTarget` from a given block position.
pub fn find_patrol_target_from(m: &mut Mob, [x, y, z]: [i32; 3]) {
let dx = -500 + m.random.next_int_bound(1000).unwrap_or(0);
let dz = -500 + m.random.next_int_bound(1000).unwrap_or(0);
let s = state_mut(m);
s.patrol_target = Some([x + dx, y, z + dz]);
s.patrolling = true;
}
/// The leader's ominous banner and its drop chance of 2.0 (always dropped).
pub fn wear_banner(m: &mut Mob) {
m.extra.head = Some(BANNER.into());
}
/// Why a mob was spawned (`EntitySpawnReason`), as far as raiders care.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
/// Natural spawning: one leader in 17, and witches stay out of raids.
Natural,
/// Commands, eggs and other spawns: one leader in 17.
Other,
Patrol,
Event,
}
/// `PatrollingMonster.finalizeSpawn` and `Raider.finalizeSpawn`: a spawn
/// other than a patrol, raid or structure leads one time in 17, a patrol
/// leader wears the ominous banner, and every raider but a naturally spawned
/// witch can join a raid.
pub fn finalize(m: &mut Mob, reason: Reason) {
if !is_raider(m.species()) {
return;
}
let roll = matches!(reason, Reason::Natural | Reason::Other);
if roll && m.random.next_float() < 0.06 && can_be_leader(m.species()) {
state_mut(m).patrol_leader = true;
}
if state_mut(m).patrol_leader {
wear_banner(m);
}
let witch = m.species() == Species::Witch;
let s = state_mut(m);
if reason == Reason::Patrol {
s.patrolling = true;
}
s.can_join_raid = !witch || reason != Reason::Natural;
}
/// `PatrollingMonster.removeWhenFarAway`: patrollers and raiders in a raid
/// are only despawned beyond 128 blocks (never inside a raid).
pub fn keeps_alive(m: &Mob, distance_squared: f64) -> bool {
match state(m) {
Some(s) => s.raid_id.is_some() || s.patrolling && distance_squared <= 16384.0,
None => false,
}
}
/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` position above (x, z).
pub fn heightmap_pos(w: &MobWorld, x: i32, z: i32) -> [i32; 3] {
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;
let y = (crate::chunk::MIN_Y..top)
.rev()
.find(|&y| {
let f = w.facts.get(w.world.block(x, y, z));
(f.full_collision || f.fluid != crate::blocks::Fluid::None)
&& !f.name.ends_with("leaves")
})
.map_or(crate::chunk::MIN_Y, |y| y + 1);
[x, y, z]
}
/// `Vec3.yRot` (the angle is in radians, and the patrol goal passes 90).
fn y_rot(v: Vec3, angle: f32) -> Vec3 {
let (cos, sin) = (f64::from(angle.cos()), f64::from(angle.sin()));
Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin)
}
/// `PatrollingMonster.LongDistancePatrolGoal`: walk toward the patrol target
/// in 10 block hops (curving around it), the leader dragging its companions.
#[derive(Clone, Debug)]
pub struct LongDistancePatrol {
speed: f64,
leader_speed: f64,
}
impl LongDistancePatrol {
pub fn new(speed: f64, leader_speed: f64) -> Self {
Self {
speed,
leader_speed,
}
}
}
/// Patrol companions within 16 blocks that are not in a raid.
fn companions(m: &Mob, w: &MobWorld) -> Vec<u32> {
w.others
.iter()
.filter(|s| {
s.id != m.id
&& s.alive
&& is_raider(s.species)
&& !s.active_raid
&& (s.position.x - m.position.x).abs() <= 16.0 + f64::from(m.width())
&& (s.position.y - m.position.y).abs() <= 16.0 + f64::from(m.height())
&& (s.position.z - m.position.z).abs() <= 16.0 + f64::from(m.width())
})
.map(|s| s.id)
.collect()
}
impl Goal for LongDistancePatrol {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(s) = state(m) else { return false };
cx.w.game_time >= s.patrol_cooldown_until
&& s.patrolling
&& m.ai.target.is_none()
&& s.patrol_target.is_some()
&& !s.has_rider()
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if !m.ai.nav.is_done() {
return;
}
let leader = state(m).is_some_and(|s| s.patrol_leader);
let friends = companions(m, cx.w);
let Some(target) = state(m).and_then(|s| s.patrol_target) else {
return;
};
if state(m).is_some_and(|s| s.patrolling) && friends.is_empty() {
state_mut(m).patrolling = false;
} else if leader && close_to_center(target, m.position, 10.0) {
find_patrol_target(m);
} else {
let to = Vec3::new(
f64::from(target[0]) + 0.5,
f64::from(target[1]),
f64::from(target[2]) + 0.5,
);
let own = m.position;
let distance = own.subtract(to);
let to = y_rot(distance, 90.0).scale(0.4).add_vector(to);
let hop = to.subtract(own).normalize().scale(10.0).add_vector(own);
let at = heightmap_pos(cx.w, hop.x.floor() as i32, hop.z.floor() as i32);
let speed = if leader {
self.leader_speed
} else {
self.speed
};
let to = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])];
if !m.nav_move_to(cx.w, to, speed) {
self.move_randomly(m, cx);
state_mut(m).patrol_cooldown_until = cx.w.game_time + 200;
} else if leader {
for id in friends {
cx.events.push(MobEvent::PatrolTarget {
mob: id,
target: at,
});
}
}
}
}
}
impl LongDistancePatrol {
fn move_randomly(&self, m: &mut Mob, cx: &mut Cx) -> bool {
let (x, z) = (
m.position.x.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
m.position.z.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
);
let at = heightmap_pos(cx.w, x, z);
m.nav_move_to(
cx.w,
[f64::from(at[0]), f64::from(at[1]), f64::from(at[2])],
self.speed,
)
}
}
/// `Vec3i.closerToCenterThan`.
fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool {
Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
)
.distance_squared(at)
< distance * distance
}
/// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when
/// the wave has no living leader (the game finds the banner and picks it up).
#[derive(Clone, Debug)]
pub struct ObtainBanner;
impl Goal for ObtainBanner {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
state(m).is_some_and(|s| s.banner_at.is_some())
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some())
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(at) = state(m).and_then(|s| s.banner_at) {
m.nav_move_to(cx.w, at, 1.15);
}
}
}
/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in
/// hops of up to 15 blocks.
#[derive(Clone, Debug)]
pub struct PathfindToRaid;
impl PathfindToRaid {
fn valid(s: &State) -> bool {
s.active_raid && !s.raid_over && !s.in_village
}
}
impl Goal for PathfindToRaid {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
m.ai.target.is_none() && state(m).is_some_and(|s| !s.has_rider() && Self::valid(s))
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
state(m).is_some_and(Self::valid)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(c) = state(m).map(|s| s.raid_center) else {
return;
};
if m.ai.nav.is_done() {
let to = [
f64::from(c[0]) + 0.5,
f64::from(c[1]),
f64::from(c[2]) + 0.5,
];
if let Some(at) =
m.default_random_pos_towards(cx.w, 15, 4, to, std::f64::consts::FRAC_PI_2)
{
m.nav_move_to(cx.w, at, 1.0);
}
}
}
}
/// `Raider.RaiderMoveThroughVillageGoal`: walk to a bed of the village not
/// visited lately, then onwards to the next one.
#[derive(Clone, Debug)]
pub struct MoveThroughVillage {
speed: f64,
distance: f64,
poi: Option<[i32; 3]>,
visited: Vec<[i32; 3]>,
stuck: bool,
}
impl MoveThroughVillage {
pub fn new(speed: f64, distance: f64) -> Self {
Self {
speed,
distance,
poi: None,
visited: Vec::new(),
stuck: false,
}
}
}
impl Goal for MoveThroughVillage {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if self.visited.len() > 2 {
self.visited.remove(0);
}
let Some(s) = state(m) else { return false };
if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() {
return false;
}
let Some(homes) = s.homes.clone() else {
return false;
};
let near: Vec<[i32; 3]> = homes
.iter()
.copied()
.filter(|p| !self.visited.contains(p) && close_to_center(*p, m.position, 48.0))
.collect();
if near.is_empty() {
return false;
}
self.poi = Some(near[m.random.next_int_bound(near.len() as i32).unwrap_or(0) as usize]);
true
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
let Some(p) = self.poi else { return false };
!m.ai.nav.is_done()
&& m.ai.target.is_none()
&& !close_to_center(p, m.position, f64::from(m.width()) + self.distance)
&& !self.stuck
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.no_action_time = 0;
if let Some(p) = self.poi {
m.nav_move_to(
cx.w,
[f64::from(p[0]), f64::from(p[1]), f64::from(p[2])],
self.speed,
);
}
self.stuck = false;
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
if let Some(p) = self.poi
&& close_to_center(p, m.position, self.distance)
{
self.visited.push(p);
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = self.poi else { return };
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(p[0]) + 0.5,
f64::from(p[1]),
f64::from(p[2]) + 0.5,
];
let next = m
.default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
match next {
Some(at) => {
m.nav_move_to(cx.w, at, self.speed);
}
None => self.stuck = true,
}
}
}
/// `Raider.RaiderCelebration`: after a lost village, cheer and jump.
#[derive(Clone, Debug)]
pub struct Celebration;
impl Goal for Celebration {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
m.alive()
&& m.ai.target.is_none()
&& state(m).is_some_and(|s| s.raid_loss && s.raid_id.is_some())
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
state_mut(m).celebrating = true;
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
state_mut(m).celebrating = false;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if m.random
.next_int_bound(super::goals::reduced(100))
.unwrap_or(1)
== 0
{
let sound = match m.species() {
Species::Pillager => "entity.pillager.celebrate",
Species::Vindicator => "entity.vindicator.celebrate",
Species::Evoker => "entity.evoker.celebrate",
Species::Ravager => "entity.ravager.celebrate",
_ => "entity.witch.celebrate",
};
m.voice(sound, cx.events);
}
if m.random
.next_int_bound(super::goals::reduced(50))
.unwrap_or(1)
== 0
{
m.ai.jumping = true;
}
}
}
/// `Raider.HoldGroundAttackGoal`: while patrolling, stand still and let the
/// patrol shout when something shows up; attack once it comes close.
#[derive(Clone, Debug)]
pub struct HoldGroundAttack {
hostile_radius_sqr: f64,
}
impl HoldGroundAttack {
pub fn new(radius: f64) -> Self {
Self {
hostile_radius_sqr: radius * radius,
}
}
}
/// Raiders within 8 blocks, nearest first (`shoutTargeting`).
fn shout_range(m: &Mob, w: &MobWorld) -> Vec<u32> {
w.others
.iter()
.filter(|s| {
s.id != m.id
&& s.alive
&& is_raider(s.species)
&& (s.position.x - m.position.x).abs() <= 8.0 + f64::from(m.width())
&& (s.position.y - m.position.y).abs() <= 8.0 + f64::from(m.height())
&& (s.position.z - m.position.z).abs() <= 8.0 + f64::from(m.width())
&& s.position.distance_squared(m.position) <= 64.0
})
.map(|s| s.id)
.collect()
}
impl Goal for HoldGroundAttack {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
let Some(s) = state(m) else { return false };
s.raid_id.is_none()
&& s.patrolling
&& m.ai.target.is_some()
&& !m.ai.aggressive
&& m.ai.last_hurt_by != Some(Who::Player)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.nav.stop();
if let Some(target) = m.ai.target {
for id in shout_range(m, cx.w) {
cx.events.push(MobEvent::RaiderTarget {
mob: id,
target,
aggressive: false,
});
}
}
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(target) = m.ai.target {
for id in shout_range(m, cx.w) {
cx.events.push(MobEvent::RaiderTarget {
mob: id,
target,
aggressive: true,
});
}
m.ai.aggressive = true;
}
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(t) = m.target_info(cx.w) else { return };
if m.distance_sqr(t.position) > self.hostile_radius_sqr {
m.look_at([t.position.x, t.eye_y, t.position.z]);
if m.random.next_int_bound(50).unwrap_or(1) == 0 {
let sound = m.kind.sounds[0];
if !sound.is_empty() {
m.voice(sound, cx.events);
}
}
} else {
m.ai.aggressive = true;
}
}
}
/// The saved fields (`PatrollingMonster` and `Raider.addAdditionalSaveData`).
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
let Some(s) = state(m) else { return };
match s.patrol_target {
Some(p) => {
map.insert("patrol_target".into(), Tag::IntArray(p.to_vec()));
}
None => {
map.remove(&"patrol_target".into());
}
}
map.insert("PatrolLeader".into(), Tag::Byte(i8::from(s.patrol_leader)));
map.insert("Patrolling".into(), Tag::Byte(i8::from(s.patrolling)));
map.insert("Wave".into(), Tag::Int(s.wave));
map.insert("CanJoinRaid".into(), Tag::Byte(i8::from(s.can_join_raid)));
match s.raid_id {
Some(id) => {
map.insert("RaidId".into(), Tag::Int(id));
}
None => {
map.remove(&"RaidId".into());
}
}
}
pub fn read_nbt(m: &mut Mob, tag: &Tag) {
if !is_raider(m.species()) {
return;
}
let int = |t: Option<&Tag>| match t {
Some(Tag::Int(v)) => Some(*v),
Some(Tag::Byte(v)) => Some(i32::from(*v)),
Some(Tag::Short(v)) => Some(i32::from(*v)),
_ => None,
};
let flag = |t: Option<&Tag>| int(t).unwrap_or(0) != 0;
let s = state_mut(m);
s.patrol_target = match tag.get("patrol_target") {
Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]),
_ => None,
};
s.patrol_leader = flag(tag.get("PatrolLeader"));
s.patrolling = flag(tag.get("Patrolling"));
s.wave = int(tag.get("Wave")).unwrap_or(0);
s.can_join_raid = flag(tag.get("CanJoinRaid"));
s.raid_id = int(tag.get("RaidId"));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raiders_and_leaders() {
assert!(is_raider(Species::Ravager) && is_raider(Species::Witch));
assert!(!is_raider(Species::Zombie));
assert!(can_be_leader(Species::Pillager) && can_be_leader(Species::Evoker));
assert!(!can_be_leader(Species::Witch) && !can_be_leader(Species::Ravager));
}
#[test]
fn long_distance_patrol_turns_by_ninety_radians() {
// PatrollingMonster passes 90.0F to Vec3.yRot (radians).
let v = y_rot(Vec3::new(10.0, 3.0, 0.0), 90.0);
let (c, s) = (90f64.cos(), 90f64.sin());
assert!((v.x - 10.0 * c).abs() < 1e-4 && (v.z + 10.0 * s).abs() < 1e-4);
assert_eq!(v.y, 3.0);
}
#[test]
fn closer_to_center_uses_block_centres() {
let at = Vec3::new(10.5, 64.5, 10.5);
assert!(close_to_center([10, 64, 10], at, 1.0));
assert!(!close_to_center([30, 64, 10], at, 10.0));
}
}
+12 -3
View File
@@ -403,6 +403,13 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
);
}
}
S::Creaking if super::creaking::eyes_glowing(m) => push(
&mut v,
"creaking#eyes",
"entity/creaking/creaking_eyes",
white,
true,
),
S::Spider | S::CaveSpider => push(
&mut v,
&m.kind.model_key(),
@@ -622,7 +629,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
if m.death_time > 0 {
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
.min(1.0);
@@ -740,7 +747,8 @@ pub fn render_with(
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let s = anim::state(m, alpha);
let (model_key, texture) = body(m);
let model = m
@@ -793,7 +801,8 @@ pub fn render_single(
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let s = anim::state(m, alpha);
let model = m.kind.model.clone();
let mut poses = Poses::new(&model);
+18 -4
View File
@@ -299,7 +299,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => {
// Zombie.finalizeSpawn: 5% babies (normal difficulty).
// Zombie.finalizeSpawn: pick up loot 55% of the time (scaled by
// difficulty), 5% babies (normal difficulty).
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
if m.random.next_float() < 0.05 {
m.extra.age = i32::MIN / 2;
}
@@ -348,8 +350,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
}
// AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on
// registration).
S::Skeleton | S::Stray | S::Bogged | S::Parched => populate_armor(m, difficulty),
S::Pillager => m.extra.main_hand = Some("minecraft:crossbow".into()),
S::Skeleton | S::Stray | S::Bogged | S::Parched => {
populate_armor(m, difficulty);
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
}
S::Pillager => {
m.extra.main_hand = Some("minecraft:crossbow".into());
m.extra.pick_up_loot = true;
}
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => {
super::equine::finalize(m)
}
@@ -358,6 +366,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
// Piglin.createSpawnWeapon: half crossbows, half golden swords, and
// each piece of golden armour one time in ten.
S::Piglin if !m.is_baby() => {
m.extra.pick_up_loot = true;
for i in 0..4 {
if m.random.next_float() < 0.1 {
let (slot, piece) = match i {
@@ -379,11 +388,16 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
.into(),
);
}
S::PiglinBrute => m.extra.main_hand = Some("minecraft:golden_axe".into()),
S::PiglinBrute => {
m.extra.main_hand = Some("minecraft:golden_axe".into());
m.extra.pick_up_loot = true;
}
S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()),
S::Villager => {
m.extra.variant = villager_type(biome);
m.extra.pick_up_loot = true;
}
S::Fox | S::Panda | S::Dolphin => m.extra.pick_up_loot = true,
S::TropicalFish => super::aquatic::finalize(m),
S::Slime | S::MagmaCube => super::cube::finalize(m),
_ => {}
+15
View File
@@ -83,6 +83,7 @@ pub enum Species {
Wither,
Camel,
Allay,
Creaking,
}
/// Baby bounding boxes (each class's BABY_DIMENSIONS).
#[derive(Clone, Copy, Debug)]
@@ -914,6 +915,20 @@ pub const ALL: &[Def] = &[
None,
Baby::None
),
def!(
Creaking,
"creaking",
"creaking#main",
"entity/creaking/creaking",
A::Creaking,
[
"entity.creaking.ambient",
"entity.generic.hurt",
"entity.creaking.death"
],
Some("entity.creaking.step"),
Baby::None
),
def!(
Camel,
"camel",
+782 -3
View File
@@ -5,13 +5,14 @@
//! (work and restock at the job site, meet at the bell, sleep in the bed),
//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake.
use super::{
Mob, MobEvent, MobWorld, Species,
Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll,
goal_clone,
Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround,
Stroll, goal_clone,
},
};
use crate::items::ItemStack;
use horizon_core::random::RandomSource;
use std::{collections::HashMap, f32::consts::PI};
@@ -74,6 +75,10 @@ pub fn register(m: &mut Mob) {
AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75),
);
g.add(1, Panic::new(0.75));
g.add(2, RaidBehavior::default());
g.add(3, Social::default());
g.add(0, GolemCall);
g.add(3, GiftToHero::default());
g.add(3, JobSite::default());
g.add(3, AcquireHome::default());
g.add(4, Schedule::default());
@@ -456,6 +461,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
_ => 4,
};
m.nav_stop();
ext_mut(m).last_slept = Some(w.game_time);
m.velocity = horizon_core::geometry::Vec3::ZERO;
m.position = horizon_core::geometry::Vec3::new(
f64::from(p[0]) + 0.5,
@@ -516,6 +522,23 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
if m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
if m.species() == Species::Villager {
let now = w.game_time;
let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0
&& w.others.iter().any(|s| {
s.species == Species::IronGolem
&& s.alive
&& (s.position.x - m.position.x).abs() <= 16.0
&& (s.position.y - m.position.y).abs() <= 16.0
&& (s.position.z - m.position.z).abs() <= 16.0
});
let e = ext_mut(m);
// Villager.maybeDecayGossip and the GolemSensor (every 200 ticks).
e.maybe_decay(now);
if seen_golem {
e.golem_until = now + 599;
}
}
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
if sleeping(m) {
let bed_gone = m
@@ -594,3 +617,759 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
}
// ---- Raids: the raid activities and the gift for a hero.
pub const RAID_NONE: u8 = 0;
/// A raid is near but no wave is on (`Activity.PRE_RAID`).
pub const PRE_RAID: u8 = 1;
/// A wave is on (`Activity.RAID`).
pub const RAID: u8 = 2;
/// The raid was won: the villagers celebrate.
pub const RAID_VICTORY: u8 = 3;
/// Villager state beyond `Extra`'s scratch fields.
#[derive(Clone, Debug, Default)]
pub struct Ext {
/// Which raid package the villager follows.
pub raid: u8,
/// What the villager remembers of players (`gossips`).
pub gossips: crate::gossip::Gossips,
pub last_gossip_time: i64,
pub last_gossip_decay: i64,
/// `foodLevel`: eaten but not yet digested, in food points.
pub food_level: i32,
/// The eight-slot inventory (`InventoryCarrier`).
pub inventory: Vec<ItemStack>,
/// `LAST_SLEPT` memory.
pub last_slept: Option<i64>,
/// `GOLEM_DETECTED_RECENTLY` expires at this game time.
pub golem_until: i64,
/// The `last_hurt_by_time` of the player's hit already counted.
pub hurt_seen: i32,
}
pub fn ext(m: &Mob) -> Option<&Ext> {
m.extra.villager.as_deref()
}
pub fn ext_mut(m: &mut Mob) -> &mut Ext {
m.extra.villager.get_or_insert_with(Box::default)
}
fn raid_status(m: &Mob) -> u8 {
ext(m).map_or(RAID_NONE, |e| e.raid)
}
/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at
/// home (`LocateHidingPlace`), before one they gather at the bell and ring it
/// (`RingBell`), and after a victory they look for the sky to celebrate
/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`).
#[derive(Clone, Debug, Default)]
struct RaidBehavior {
next_move: i32,
}
impl Goal for RaidBehavior {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
raid_status(m) != RAID_NONE && !sleeping(m)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.next_move = 0;
m.nav_stop();
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.next_move -= 1;
let p = m.position;
match raid_status(m) {
RAID => {
// LocateHidingPlace(24, 0.7, 1): back to the bed.
let Some(home) = m.extra.bed else { return };
if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
if distance(m, home) <= 24.0 {
m.nav_move_to(cx.w, center(home), 0.7);
}
self.next_move = 40;
}
}
PRE_RAID => {
// RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75).
let Some(bell) = m.extra.meeting else { return };
if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
m.nav_move_to(cx.w, center(bell), 0.75);
self.next_move = 40;
}
if distance(m, bell) < 3.0
&& m.random.next_float() > 0.95
&& cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell"
{
cx.events.push(MobEvent::SoundId(
"minecraft:block.bell.use".into(),
center(bell),
2.0,
1.0,
));
}
}
RAID_VICTORY => {
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
if cx.w.can_see_sky(x, y, z) {
// CelebrateVillagersSurvivedRaid.tick.
if m.random.next_int_bound(100).unwrap_or(1) == 0 {
m.voice("entity.villager.celebrate", cx.events);
}
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
let color = m.random.next_int_bound(16).unwrap_or(0) as usize;
let flight = m.random.next_int_bound(3).unwrap_or(0) as u8;
cx.events.push(MobEvent::Firework {
at: [p.x, m.eye_y(), p.z],
color,
flight,
});
}
m.nav_stop();
} else if self.next_move <= 0 || m.ai.nav.is_done() {
// MoveToSkySeeingSpot: a random spot with a view of the sky.
for _ in 0..5 {
if let Some(at) = m.land_random_pos(cx.w, 15, 7)
&& cx.w.can_see_sky(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
)
{
m.nav_move_to(cx.w, at, 0.5);
break;
}
}
self.next_move = 40;
}
}
_ => {}
}
}
}
/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and
/// throws a gift of its profession, every so often.
#[derive(Clone, Debug)]
struct GiftToHero {
until_next: i32,
started: i64,
given: bool,
}
impl Default for GiftToHero {
fn default() -> Self {
Self {
until_next: 600,
started: 0,
given: false,
}
}
}
/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`).
fn gift_table(m: &Mob) -> String {
if m.is_baby() {
return "minecraft:gameplay/hero_of_the_village/baby_gift".into();
}
let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15];
let name = match profession {
"none" | "nitwit" => "unemployed",
other => other,
};
format!("minecraft:gameplay/hero_of_the_village/{name}_gift")
}
fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool {
let Some(p) = &cx.w.player else { return false };
p.hero
&& p.alive
&& !p.spectator
&& m.position.distance_squared(p.position) <= 16.0 * 16.0
&& m.sees(cx.w, Who::Player)
}
impl Goal for GiftToHero {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !hero_in_view(m, cx) || sleeping(m) {
return false;
}
if self.until_next > 0 {
self.until_next -= 1;
return false;
}
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
hero_in_view(m, cx) && !self.given
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.given = false;
self.started = cx.w.game_time;
if let Some(p) = &cx.w.player {
m.look_at(p.eye);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0);
m.nav_stop();
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = cx.w.player.clone() else { return };
m.look_at(p.eye);
let near = m.position.distance_squared(p.position) < 25.0;
if near {
if cx.w.game_time - self.started > 20 {
cx.events.push(MobEvent::ThrowGift {
table: gift_table(m),
from: [m.position.x, m.eye_y() - 0.3, m.position.z],
to: [p.position.x, p.position.y, p.position.z],
});
self.given = true;
}
m.nav_stop();
} else if m.ai.nav.is_done() {
m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5);
}
}
}
// ---- Gossip, food, breeding and golems.
/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`).
pub fn food_points(item: &str) -> i32 {
match item {
"minecraft:bread" => 4,
"minecraft:potato" | "minecraft:carrot" | "minecraft:beetroot" => 1,
_ => 0,
}
}
/// The farmer's `requestedItems`.
pub fn farmer_items() -> &'static [&'static str] {
&[
"minecraft:bread",
"minecraft:potato",
"minecraft:carrot",
"minecraft:wheat",
"minecraft:wheat_seeds",
"minecraft:beetroot",
"minecraft:beetroot_seeds",
"minecraft:torchflower_seeds",
"minecraft:pitcher_pod",
]
}
/// A villager's `requestedItems` by profession.
pub fn requested_items(m: &Mob) -> &'static [&'static str] {
if super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" {
farmer_items()
} else {
&[]
}
}
pub fn is_farmer(m: &Mob) -> bool {
super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer"
}
/// `SimpleContainer(8)`: stacks the villager carries.
const INVENTORY_SLOTS: usize = 8;
impl Ext {
/// `countFoodPointsInInventory`.
pub fn food_in_inventory(&self) -> i32 {
self.inventory
.iter()
.map(|s| food_points(&s.item) * s.count as i32)
.sum()
}
/// `hasExcessFood` and `wantsMoreFood`.
pub fn has_excess_food(&self) -> bool {
self.food_in_inventory() >= 24
}
pub fn wants_more_food(&self) -> bool {
self.food_in_inventory() < 12
}
fn hungry(&self) -> bool {
self.food_level < 12
}
/// `Villager.eatAndDigestFood`: eat until full, then digest 12 points.
pub fn eat_and_digest(&mut self) {
if self.hungry() {
let mut slot = 0;
while slot < self.inventory.len() && self.hungry() {
let points = food_points(&self.inventory[slot].item);
if points > 0 {
while self.inventory[slot].count > 0 && self.hungry() {
self.food_level += points;
self.inventory[slot].count -= 1;
}
if self.inventory[slot].count == 0 {
self.inventory.remove(slot);
continue;
}
}
slot += 1;
}
}
self.food_level -= 12;
}
/// Whether the stack fits (`SimpleContainer.canAddItem`).
pub fn can_add(&self, stack: &ItemStack, max_stack: u32) -> bool {
self.inventory.len() < INVENTORY_SLOTS
|| self
.inventory
.iter()
.any(|s| s.same_item_same_components(stack) && s.count < max_stack)
}
/// `SimpleContainer.addItem`: merge into stacks, then free slots; the
/// part that did not fit is returned.
pub fn add_item(&mut self, mut stack: ItemStack, max_stack: u32) -> Option<ItemStack> {
for s in &mut self.inventory {
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max_stack {
let n = (max_stack - s.count).min(stack.count);
s.count += n;
stack.count -= n;
}
}
while stack.count > 0 && self.inventory.len() < INVENTORY_SLOTS {
let n = stack.count.min(max_stack);
self.inventory.push(ItemStack {
count: n,
..stack.clone()
});
stack.count -= n;
}
(stack.count > 0).then_some(stack)
}
pub fn count_item(&self, item: &str) -> u32 {
self.inventory
.iter()
.filter(|s| &*s.item == item)
.map(|s| s.count)
.sum()
}
/// `TradeWithVillager.throwHalfStack`: the half of a big matching stack
/// (or whatever is over 24) leaves the inventory.
pub fn take_half_stack(
&mut self,
wanted: impl Fn(&ItemStack) -> bool,
max_stack: impl Fn(&str) -> u32,
) -> Option<ItemStack> {
for i in 0..self.inventory.len() {
let s = &self.inventory[i];
if s.count == 0 || !wanted(s) {
continue;
}
let count = if s.count > max_stack(&s.item) / 2 {
s.count / 2
} else if s.count > 24 {
s.count - 24
} else {
continue;
};
let taken = ItemStack { count, ..s.clone() };
self.inventory[i].count -= count;
if self.inventory[i].count == 0 {
self.inventory.remove(i);
}
return Some(taken);
}
None
}
/// `Villager.wantsToSpawnGolem`: slept within the last day and no golem
/// seen lately.
pub fn wants_golem(&self, now: i64) -> bool {
self.last_slept.is_some_and(|t| now - t < 24000) && now >= self.golem_until
}
/// `maybeDecayGossip`: once a day.
pub fn maybe_decay(&mut self, now: i64) {
if self.last_gossip_decay == 0 {
self.last_gossip_decay = now;
} else if now >= self.last_gossip_decay + 24000 {
self.gossips.decay();
self.last_gossip_decay = now;
}
}
/// `Villager.gossip` timing: hearing again waits 1200 ticks.
pub fn can_gossip(&self, now: i64) -> bool {
now < self.last_gossip_time || now >= self.last_gossip_time + 1200
}
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
&& m.extra.age == 0
&& !sleeping(m)
&& ext(m).map_or(0, |e| e.food_level + e.food_in_inventory()) >= 12
}
/// The saved fields (`FoodLevel`, `Gossips`, `LastGossipDecay`, `Inventory`
/// and the sleep and golem memories).
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
map.insert(
"FoodLevel".into(),
Tag::Byte(e.food_level.clamp(-128, 127) as i8),
);
map.insert("Gossips".into(), e.gossips.to_nbt());
map.insert("LastGossipDecay".into(), Tag::Long(e.last_gossip_decay));
map.insert(
"Inventory".into(),
Tag::List(e.inventory.iter().map(crate::save::item_to_nbt).collect()),
);
}
/// The memories of `Brain.memories` the villager keeps besides positions.
pub fn write_memories(m: &Mob, memories: &mut Vec<(&'static str, horizon_world::nbt::Tag)>) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
if let Some(t) = e.last_slept {
memories.push((
"minecraft:last_slept",
Tag::compound([("value", Tag::Long(t))]),
));
}
}
pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
use horizon_world::nbt::Tag;
let int = |t: Option<&Tag>| match t {
Some(Tag::Int(v)) => Some(i64::from(*v)),
Some(Tag::Byte(v)) => Some(i64::from(*v)),
Some(Tag::Short(v)) => Some(i64::from(*v)),
Some(Tag::Long(v)) => Some(*v),
_ => None,
};
let last_slept = int(tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get("minecraft:last_slept"))
.and_then(|j| j.get("value")));
let e = ext_mut(m);
e.food_level = int(tag.get("FoodLevel")).unwrap_or(0) as i32;
e.gossips = tag
.get("Gossips")
.map(crate::gossip::Gossips::from_nbt)
.unwrap_or_default();
e.last_gossip_decay = int(tag.get("LastGossipDecay")).unwrap_or(0);
e.last_slept = last_slept;
if let Some(Tag::List(items)) = tag.get("Inventory") {
e.inventory = items
.iter()
.filter_map(crate::save::item_from_nbt)
.take(INVENTORY_SLOTS)
.collect();
}
}
/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while
/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap
/// gossip and food, and make a baby with a willing partner.
#[derive(Clone, Debug, Default)]
struct Social {
target: Option<u32>,
breed: bool,
ticks: i32,
cooldown: i32,
birth_at: i64,
}
impl Social {
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let breedable = can_breed(m);
let id = m.id;
let nearest =
cx.w.nearby(m.position, 8.0, move |s| {
s.species == Species::Villager && s.id != id
})
.filter(|s| m.position.distance_squared(s.position) <= 64.0)
.map(|s| (s.id, s.in_love))
.collect::<Vec<_>>();
let visible: Vec<(u32, bool)> = nearest
.into_iter()
.filter(|(i, _)| m.sees(cx.w, Who::Mob(*i)))
.collect();
let Some(&(target, partner_willing)) = visible.first() else {
return false;
};
// RunOne weights: interact 2, breed 1 (when both are willing).
let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0;
self.target = Some(target);
self.breed = breed;
true
}
}
impl Goal for Social {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.cooldown > 0 {
self.cooldown -= 1;
return false;
}
match activity(m, cx.w.day_time) {
Activity::Idle => self.pick(m, cx),
Activity::Meet => {
// SocializeAtBell: one tick in a hundred, near the bell.
let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0);
near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && {
let ok = self.pick(m, cx);
self.breed = false;
ok
}
}
_ => false,
}
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(t) = self.target else { return false };
let Some(s) = cx.w.seen(t) else { return false };
if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.breed {
self.ticks < 350 && can_breed(m) && s.in_love
} else {
self.ticks < 60
}
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 0;
self.birth_at = 0;
if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) {
let at = [s.position.x, s.position.y, s.position.z];
m.nav_move_to(cx.w, at, 0.5);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
self.target = None;
self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0);
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks += 1;
let Some(t) = self.target else { return };
let Some(s) = cx.w.seen(t) else { return };
let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y);
m.look_at([at[0], eye, at[2]]);
if m.position.distance_squared(s.position) > 5.0 {
if m.ai.nav.is_done() && self.ticks % 10 == 1 {
m.nav_move_to(cx.w, at, 0.5);
}
return;
}
m.nav_stop();
if !self.breed {
cx.events.push(MobEvent::VillagerMeet {
mob: m.id,
other: t,
});
return;
}
let now = cx.w.game_time;
if self.birth_at == 0 {
self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
}
if now >= self.birth_at {
cx.events.push(MobEvent::VillagerBirth {
parent: m.id,
partner: t,
});
self.ticks = 1000;
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
for p in [m.position, s.position] {
cx.events.push(MobEvent::Particles {
kind: "heart",
at: [p.x, p.y + 1.8, p.z],
count: 1,
});
}
}
}
}
/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem
/// every five seconds.
#[derive(Clone, Debug, Default)]
struct GolemCall;
/// `VillagerHostilesSensor`: how close each hostile must be to scare.
fn hostile_range(s: Species) -> f64 {
match s {
Species::Drowned
| Species::Husk
| Species::Vex
| Species::Zombie
| Species::ZombieVillager => 8.0,
Species::Evoker | Species::Ravager => 12.0,
Species::Pillager => 15.0,
Species::Vindicator | Species::Zoglin => 10.0,
_ => 0.0,
}
}
fn frightened(m: &Mob, cx: &Cx) -> bool {
// HURT_BY lasts 100 ticks.
let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100;
hurt || cx.w.others.iter().any(|s| {
s.alive && {
let r = hostile_range(s.species);
r > 0.0 && s.position.distance_squared(m.position) <= r * r
}
})
}
impl Goal for GolemCall {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
!m.is_baby() && frightened(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if cx.w.game_time % 100 == 0 {
cx.events.push(MobEvent::GolemCheck {
mob: m.id,
needed: 3,
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stack(item: &str, count: u32) -> ItemStack {
ItemStack::new(item, count)
}
#[test]
fn eating_fills_the_food_level_then_digests() {
let mut e = Ext {
inventory: vec![stack("minecraft:bread", 3), stack("minecraft:carrot", 5)],
..Default::default()
};
assert_eq!(e.food_in_inventory(), 17);
// Hungry below 12: three breads fill it exactly, then 12 digest away.
e.eat_and_digest();
assert_eq!(e.food_level, 0);
assert_eq!(e.inventory.len(), 1);
assert_eq!(e.inventory[0].count, 5);
// Five carrots are not enough to be full again, and are all eaten.
e.eat_and_digest();
assert_eq!(e.food_level, 5 - 12);
assert!(e.inventory.is_empty());
}
#[test]
fn willingness_to_breed_needs_twelve_food_points() {
let mut e = Ext::default();
assert!(e.wants_more_food() && !e.has_excess_food());
e.inventory.push(stack("minecraft:bread", 6));
assert!(e.has_excess_food() && !e.wants_more_food());
e.food_level = -5;
assert_eq!(e.food_level + e.food_in_inventory(), 19);
}
#[test]
fn the_inventory_has_eight_stacking_slots() {
let mut e = Ext::default();
assert!(e.add_item(stack("minecraft:bread", 100), 64).is_none());
assert_eq!(e.inventory.len(), 2);
assert_eq!(e.inventory[0].count, 64);
for i in 0..6 {
assert!(
e.add_item(stack(&format!("minecraft:item_{i}"), 1), 64)
.is_none()
);
}
assert_eq!(e.inventory.len(), 8);
// Full: another kind is refused, the same kind tops up the stack.
assert!(!e.can_add(&stack("minecraft:stick", 1), 64));
let left = e.add_item(stack("minecraft:bread", 40), 64).unwrap();
assert_eq!(left.count, 40 - 28);
}
#[test]
fn half_stacks_are_thrown() {
let mut e = Ext {
inventory: vec![
stack("minecraft:bread", 10),
stack("minecraft:wheat", 50),
stack("minecraft:wheat", 20),
],
..Default::default()
};
let max = |_: &str| 64;
// Bread is under half a stack and under 24: nothing.
assert!(
e.take_half_stack(|s| &*s.item == "minecraft:bread", max)
.is_none()
);
// 50 wheat is over half a stack: 25 go.
let t = e
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
.unwrap();
assert_eq!(t.count, 25);
assert_eq!(e.count_item("minecraft:wheat"), 25 + 20);
}
#[test]
fn golems_need_sleep_and_no_golem_nearby() {
let mut e = Ext::default();
assert!(!e.wants_golem(100));
e.last_slept = Some(0);
assert!(e.wants_golem(23_999));
assert!(!e.wants_golem(24_000));
e.last_slept = Some(1000);
e.golem_until = 2000 + 599;
assert!(!e.wants_golem(2500));
assert!(e.wants_golem(2700));
}
#[test]
fn gossip_decays_once_a_day_and_heard_gossip_waits() {
let player = [1, 2, 3, 4];
let mut e = Ext::default();
e.gossips
.add(player, crate::gossip::GossipType::MajorNegative, 25);
e.maybe_decay(100);
assert_eq!(e.last_gossip_decay, 100);
e.maybe_decay(24_099);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
25
);
e.maybe_decay(24_100);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
15
);
e.last_gossip_time = 5000;
assert!(!e.can_gossip(5100));
assert!(e.can_gossip(6200));
assert!(e.can_gossip(4000));
}
#[test]
fn villager_food_values() {
assert_eq!(food_points("minecraft:bread"), 4);
assert_eq!(food_points("minecraft:beetroot"), 1);
assert_eq!(food_points("minecraft:apple"), 0);
}
}
+29 -1
View File
@@ -19,6 +19,18 @@ pub fn register(m: &mut Mob) {
g.add(3, LookAtPlayer::new(8.0));
g.add(3, RandomLookAround::default());
m.ai.targets.add(1, HurtByTarget::new());
// NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders.
m.ai.targets.add(
2,
NearestTarget::new(
super::goals::Prey::Filter(|s| {
super::raider::is_raider(s.species) && s.species != Species::Witch
}),
true,
)
.interval(1)
.when(|m, _| super::raider::has_active_raid(m)),
);
m.ai.targets
.add(3, NearestTarget::player(true).interval(10));
}
@@ -129,7 +141,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
})
.map_or(20.0, |s| s.health)
};
let (effect, ticks, amplifier) = if dist >= 8.0 {
// A raider target is healed instead: Healing when nearly dead, else
// Regeneration, and the witch drops the target afterwards.
let heals = match who {
Who::Mob(id) => {
cx.w.seen(id)
.is_some_and(|s| super::raider::is_raider(s.species))
}
Who::Player => false,
};
let (effect, ticks, amplifier) = if heals {
m.ai.target = None;
if health <= 4.0 {
("minecraft:instant_health", 1, 0)
} else {
("minecraft:regeneration", 900, 0)
}
} else if dist >= 8.0 {
("minecraft:slowness", 1800, 0)
} else if health >= 8.0 {
("minecraft:poison", 900, 0)
+52
View File
@@ -41,6 +41,7 @@ macro_rules! particle_types {
particle_types! {
Block = "block",
BlockCrumble = "block_crumble",
Trail = "trail",
DustPillar = "dust_pillar",
FallingDust = "falling_dust",
Smoke = "smoke",
@@ -140,6 +141,8 @@ pub struct ParticleOptions {
pub color: [f32; 4],
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`.
pub scale: f32,
/// `TrailParticleOption`: the point it flies to and how many ticks it takes.
pub trail: Option<([f64; 3], i32)>,
}
impl ParticleOptions {
pub fn simple(ty: ParticleType) -> Self {
@@ -148,6 +151,20 @@ impl ParticleOptions {
block: None,
color: [1.0; 4],
scale: 1.0,
trail: None,
}
}
/// `TrailParticleOption(target, color, duration)`.
pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self {
Self {
color: [
((rgb >> 16) & 255) as f32 / 255.0,
((rgb >> 8) & 255) as f32 / 255.0,
(rgb & 255) as f32 / 255.0,
1.0,
],
trail: Some((target, duration)),
..Self::simple(ParticleType::Trail)
}
}
pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self {
@@ -261,6 +278,10 @@ enum Behaviour {
DragonBreath {
hit_ground: bool,
},
/// `TrailParticle`: eases towards its target over its lifetime.
Trail {
target: [f64; 3],
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum DripStage {
@@ -1662,6 +1683,24 @@ impl ParticleEngine {
q.set_power(o.scale);
q
}
T::Trail => {
let (target, duration) = o.trail?;
let mut q = Particle::at(r, ty, p);
let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25;
let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r));
q.set_color(
(o.color[0] * jr).min(1.0),
(o.color[1] * jg).min(1.0),
(o.color[2] * jb).min(1.0),
);
q.size = 0.26;
q.lifetime = duration;
q.has_physics = false;
q.free_move = true;
q.light = Light::FullBright;
q.behaviour = Behaviour::Trail { target };
q
}
};
if particle.set.is_some() {
particle.sprite = self.first(ty);
@@ -2146,6 +2185,19 @@ impl ParticleEngine {
start[2] + p.velocity[2] * f64::from(pos),
];
}
Behaviour::Trail { target } => {
p.previous = p.position;
let age = p.age;
p.age += 1;
if age >= p.lifetime {
p.removed = true;
return;
}
let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1));
for i in 0..3 {
p.position[i] += (target[i] - p.position[i]) * alpha;
}
}
Behaviour::HugeExplosion => {
p.previous = p.position;
let age = p.age;
File diff suppressed because it is too large Load Diff
+685
View File
@@ -0,0 +1,685 @@
//! The recipe book: what the book shows for each menu (`RecipeBookType`
//! tabs, `RecipeBookCategories`, groups), which recipes the player can craft
//! with the items at hand (`StackedItemContents.canCraft` and the biggest
//! craftable stack), where a recipe goes in a grid (`PlaceRecipeHelper`) and
//! the book's saved settings.
use crate::{
crafting::{Ingredient, Recipe, Recipes},
items::{ItemStack, Items},
};
use horizon_world::nbt::Tag;
use std::collections::{BTreeSet, HashMap};
/// `RecipeBookType`: the menus with a recipe book and their own settings.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum BookType {
Crafting,
Furnace,
BlastFurnace,
Smoker,
}
impl BookType {
pub const ALL: [Self; 4] = [
Self::Crafting,
Self::Furnace,
Self::BlastFurnace,
Self::Smoker,
];
pub fn index(self) -> usize {
self as usize
}
/// `RecipeBookSettings` keys in the player's `recipeBook` compound.
fn keys(self) -> (&'static str, &'static str) {
match self {
Self::Crafting => ("isGuiOpen", "isFilteringCraftable"),
Self::Furnace => ("isFurnaceGuiOpen", "isFurnaceFilteringCraftable"),
Self::BlastFurnace => (
"isBlastingFurnaceGuiOpen",
"isBlastingFurnaceFilteringCraftable",
),
Self::Smoker => ("isSmokerGuiOpen", "isSmokerFilteringCraftable"),
}
}
/// The tab buttons of the book's screen, search first.
pub fn tabs(self) -> Vec<Tab> {
use Category::*;
let categories: &[Category] = match self {
Self::Crafting => &[
CraftingEquipment,
CraftingBuilding,
CraftingMisc,
CraftingRedstone,
],
Self::Furnace => &[FurnaceFood, FurnaceBlocks, FurnaceMisc],
Self::BlastFurnace => &[BlastBlocks, BlastMisc],
Self::Smoker => &[SmokerFood],
};
std::iter::once(Tab::Search)
.chain(categories.iter().map(|c| Tab::Category(*c)))
.collect()
}
/// The categories the search tab lists, in `SearchRecipeBookCategory` order.
fn search_categories(self) -> &'static [Category] {
use Category::*;
match self {
Self::Crafting => &[
CraftingEquipment,
CraftingBuilding,
CraftingMisc,
CraftingRedstone,
],
Self::Furnace => &[FurnaceFood, FurnaceBlocks, FurnaceMisc],
Self::BlastFurnace => &[BlastBlocks, BlastMisc],
Self::Smoker => &[SmokerFood],
}
}
}
/// `RecipeBookCategories` of the four menus' recipes.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Category {
CraftingBuilding,
CraftingRedstone,
CraftingEquipment,
CraftingMisc,
FurnaceFood,
FurnaceBlocks,
FurnaceMisc,
BlastBlocks,
BlastMisc,
SmokerFood,
}
/// A tab button: the search tab or one category.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Tab {
Search,
Category(Category),
}
impl Tab {
/// The tab's icon items (`TabInfo`).
pub fn icons(self) -> (&'static str, Option<&'static str>) {
use Category::*;
match self {
Self::Search => ("minecraft:compass", None),
Self::Category(c) => match c {
CraftingEquipment => ("minecraft:iron_axe", Some("minecraft:golden_sword")),
CraftingBuilding => ("minecraft:bricks", None),
CraftingMisc => ("minecraft:lava_bucket", Some("minecraft:apple")),
CraftingRedstone => ("minecraft:redstone", None),
FurnaceFood | SmokerFood => ("minecraft:porkchop", None),
FurnaceBlocks => ("minecraft:stone", None),
FurnaceMisc => ("minecraft:lava_bucket", Some("minecraft:emerald")),
BlastBlocks => ("minecraft:redstone_ore", None),
BlastMisc => ("minecraft:iron_shovel", Some("minecraft:golden_leggings")),
},
}
}
}
/// `RecipeDisplay`: how a recipe is laid out.
#[derive(Clone, Debug)]
pub enum Display {
Shaped {
width: usize,
height: usize,
cells: Vec<Option<Ingredient>>,
},
Shapeless(Vec<Ingredient>),
/// A smelting-type recipe: its input; the fuel is any fuel.
Furnace(Ingredient),
}
/// One recipe of the book (`RecipeDisplayEntry`).
#[derive(Clone, Debug)]
pub struct Entry {
/// The recipe id, `minecraft:name`.
pub id: String,
pub category: Category,
pub group: Option<String>,
pub display: Display,
pub result: ItemStack,
}
impl Entry {
/// The ingredients that must be matched to craft it, in order.
pub fn requirements(&self) -> Vec<&Ingredient> {
match &self.display {
Display::Shaped { cells, .. } => cells.iter().flatten().collect(),
Display::Shapeless(list) => list.iter().collect(),
Display::Furnace(i) => vec![i],
}
}
/// `CraftingRecipeBookComponent.canDisplay` for a grid.
pub fn fits(&self, grid_width: usize, grid_height: usize) -> bool {
match &self.display {
Display::Shaped { width, height, .. } => grid_width >= *width && grid_height >= *height,
Display::Shapeless(list) => grid_width * grid_height >= list.len(),
Display::Furnace(_) => true,
}
}
/// The size the recipe takes in the grid (`PlaceRecipeHelper`).
pub fn size_in(&self, grid_width: usize, grid_height: usize) -> (usize, usize) {
match &self.display {
Display::Shaped { width, height, .. } => (*width, *height),
_ => (grid_width, grid_height),
}
}
/// The ingredient of each grid cell the recipe fills, with its grid index
/// (the ghost recipe and the placement use the same layout).
pub fn grid_cells(&self, grid_width: usize, grid_height: usize) -> Vec<(Option<usize>, usize)> {
let (w, h) = self.size_in(grid_width, grid_height);
// One entry per recipe cell: the index of its ingredient, if any.
let entries: Vec<Option<usize>> = match &self.display {
Display::Shaped { cells, .. } => {
let mut next = 0;
cells
.iter()
.map(|c| {
c.as_ref().map(|_| {
next += 1;
next - 1
})
})
.collect()
}
Display::Shapeless(list) => (0..list.len()).map(Some).collect(),
Display::Furnace(_) => vec![Some(0)],
};
place_cells(grid_width, grid_height, w, h, &entries)
}
}
/// `PlaceRecipeHelper.placeRecipe`: the grid index each entry goes to; a
/// recipe smaller than half the grid is centred.
pub fn place_cells<T: Clone>(
grid_width: usize,
grid_height: usize,
recipe_width: usize,
recipe_height: usize,
entries: &[T],
) -> Vec<(T, usize)> {
let mut out = Vec::new();
let mut iter = entries.iter().peekable();
let mut index = 0usize;
let mut y = 0;
while y < grid_height {
let center_rows = (recipe_height as f32) < grid_height as f32 / 2.0;
let start_row = (grid_height as f32 / 2.0 - recipe_height as f32 / 2.0).floor() as usize;
if center_rows && start_row > y {
index += grid_width;
y += 1;
}
for x in 0..grid_width {
if iter.peek().is_none() {
return out;
}
let center_cols = (recipe_width as f32) < grid_width as f32 / 2.0;
let start_col = (grid_width as f32 / 2.0 - recipe_width as f32 / 2.0).floor() as usize;
let mut total = recipe_width;
let mut add = x < recipe_width;
if center_cols {
total = start_col + recipe_width;
add = start_col <= x && x < start_col + recipe_width;
}
if add {
if let Some(item) = iter.next() {
out.push((item.clone(), index));
}
} else if total == x {
index += grid_width - x;
break;
}
index += 1;
}
y += 1;
}
out
}
/// A group of recipes shown as one button (`RecipeCollection`).
#[derive(Clone, Debug, Default)]
pub struct Collection {
/// Indices into `Book::entries`.
pub entries: Vec<usize>,
}
/// Every recipe the menus' books can show.
#[derive(Default)]
pub struct Book {
pub entries: Vec<Entry>,
/// Item id -> registry position, to order ingredient choices.
pub order: HashMap<String, usize>,
}
fn crafting_category(name: &str) -> Category {
match name {
"building" => Category::CraftingBuilding,
"redstone" => Category::CraftingRedstone,
"equipment" => Category::CraftingEquipment,
_ => Category::CraftingMisc,
}
}
impl Book {
pub fn build(recipes: &Recipes, items: &Items) -> Self {
let mut entries = Vec::new();
let group = |s: &str| (!s.is_empty()).then(|| s.to_owned());
for (name, recipe) in &recipes.crafting {
let (category, grp) = recipes.meta.get(name).cloned().unwrap_or_default();
let (display, result) = match recipe {
Recipe::Shaped {
width,
height,
cells,
result,
} => (
Display::Shaped {
width: *width,
height: *height,
cells: cells.clone(),
},
result,
),
Recipe::Shapeless {
ingredients,
result,
} => (Display::Shapeless(ingredients.clone()), result),
Recipe::Special(_) => continue,
};
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result: result.clone(),
});
}
for c in &recipes.cooking {
let category = match (c.kind.as_str(), c.category.as_str()) {
("minecraft:smelting", "food") => Category::FurnaceFood,
("minecraft:smelting", "blocks") => Category::FurnaceBlocks,
("minecraft:smelting", _) => Category::FurnaceMisc,
("minecraft:blasting", "blocks") => Category::BlastBlocks,
("minecraft:blasting", _) => Category::BlastMisc,
("minecraft:smoking", _) => Category::SmokerFood,
_ => continue,
};
entries.push(Entry {
id: format!("minecraft:{}", c.id),
category,
group: group(&c.group),
display: Display::Furnace(c.ingredient.clone()),
result: c.result.clone(),
});
}
let order = items
.order
.iter()
.enumerate()
.map(|(i, id)| (id.to_string(), i))
.collect();
Self { entries, order }
}
/// The unlocked recipes of one tab as collections (`ClientRecipeBook.rebuildCollections`).
pub fn collections(
&self,
unlocked: &BTreeSet<String>,
book: BookType,
tab: Tab,
) -> Vec<Collection> {
let categories: Vec<Category> = match tab {
Tab::Search => book.search_categories().to_vec(),
Tab::Category(c) => vec![c],
};
let mut out = Vec::new();
for category in categories {
let mut by_group: HashMap<&str, usize> = HashMap::new();
let start = out.len();
for (i, e) in self.entries.iter().enumerate() {
if e.category != category || !unlocked.contains(&e.id) {
continue;
}
match e.group.as_deref().and_then(|g| by_group.get(g).copied()) {
Some(c) => {
let c: usize = c;
let collection: &mut Collection = &mut out[start + c];
collection.entries.push(i);
}
None => {
if let Some(g) = e.group.as_deref() {
by_group.insert(g, out.len() - start);
}
out.push(Collection { entries: vec![i] });
}
}
}
}
out
}
/// Which book a recipe id belongs to.
pub fn book_of(&self, id: &str) -> Option<BookType> {
let e = self.entries.iter().find(|e| e.id == id)?;
Some(match e.category {
Category::CraftingBuilding
| Category::CraftingRedstone
| Category::CraftingEquipment
| Category::CraftingMisc => BookType::Crafting,
Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => {
BookType::Furnace
}
Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace,
Category::SmokerFood => BookType::Smoker,
})
}
pub fn entry(&self, id: &str) -> Option<&Entry> {
self.entries.iter().find(|e| e.id == id)
}
/// `ingredient`'s items in registry order (the cycling order of ghost slots).
pub fn items_of(&self, ingredient: &Ingredient) -> Vec<String> {
let mut items: Vec<String> = ingredient.0.iter().cloned().collect();
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
}
/// `RecipeCollection` search: the result's name or registry path, or
/// `@namespace`.
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
let query = query.to_lowercase();
if let Some(ns) = query.strip_prefix('@') {
return entry
.result
.item
.split(':')
.next()
.is_some_and(|n| n.starts_with(ns));
}
name.to_lowercase().contains(&query)
|| entry
.result
.item
.trim_start_matches("minecraft:")
.contains(&query)
}
}
/// `StackedItemContents`: simple stacks (undamaged, unenchanted, unnamed) by item.
#[derive(Clone, Debug, Default)]
pub struct Available {
pub counts: HashMap<String, u32>,
}
impl Available {
/// `accountSimpleStack`.
pub fn add(&mut self, stack: &ItemStack) {
if stack.count > 0
&& stack.damage == 0
&& stack.enchantments().is_empty()
&& stack.custom_name().is_none()
{
*self.counts.entry(stack.item.to_string()).or_default() += stack.count;
}
}
pub fn from_stacks<'a>(stacks: impl IntoIterator<Item = &'a ItemStack>) -> Self {
let mut a = Self::default();
for s in stacks {
a.add(s);
}
a
}
/// `StackedItemContents.canCraft(ingredients, null)`.
pub fn can_craft(&self, requirements: &[&Ingredient]) -> bool {
!requirements.is_empty() && pick(requirements, &self.counts, 1, &HashMap::new()).is_some()
}
/// `canCraft(recipe, amount, output)`: the item each ingredient uses when
/// `amount` sets can be made, preferring earlier registry items.
pub fn pick(
&self,
requirements: &[&Ingredient],
amount: u32,
order: &HashMap<String, usize>,
) -> Option<Vec<String>> {
pick(requirements, &self.counts, amount, order)
}
/// `getBiggestCraftableStack`: how many sets can be made, up to 99.
pub fn biggest_stack(&self, requirements: &[&Ingredient]) -> u32 {
if !self.can_craft(requirements) {
return 0;
}
let none = HashMap::new();
let (mut lo, mut hi) = (1u32, 99u32);
while lo < hi {
let mid = (lo + hi).div_ceil(2);
if pick(requirements, &self.counts, mid, &none).is_some() {
lo = mid;
} else {
hi = mid - 1;
}
}
lo
}
}
/// Bipartite assignment of one item to each ingredient where an item can
/// serve `count / amount` ingredients.
fn pick(
requirements: &[&Ingredient],
counts: &HashMap<String, u32>,
amount: u32,
order: &HashMap<String, usize>,
) -> Option<Vec<String>> {
let amount = amount.max(1);
let capacity = |item: &str| counts.get(item).copied().unwrap_or(0) / amount;
let candidates: Vec<Vec<String>> = requirements
.iter()
.map(|ing| {
let mut v: Vec<String> = ing.0.iter().filter(|i| capacity(i) > 0).cloned().collect();
v.sort_by_key(|i| (order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
v
})
.collect();
let mut used: HashMap<String, Vec<usize>> = HashMap::new();
fn assign(
i: usize,
candidates: &[Vec<String>],
used: &mut HashMap<String, Vec<usize>>,
visited: &mut Vec<String>,
capacity: &dyn Fn(&str) -> u32,
) -> bool {
for item in &candidates[i] {
if visited.contains(item) {
continue;
}
visited.push(item.clone());
let holders = used.get(item).cloned().unwrap_or_default();
if (holders.len() as u32) < capacity(item) {
used.entry(item.clone()).or_default().push(i);
return true;
}
for j in holders {
if assign(j, candidates, used, visited, capacity) {
// j moved elsewhere: drop it from this item and take its place.
if let Some(list) = used.get_mut(item) {
list.retain(|x| *x != j);
list.push(i);
}
return true;
}
}
}
false
}
for i in 0..requirements.len() {
let mut visited = Vec::new();
if !assign(i, &candidates, &mut used, &mut visited, &capacity) {
return None;
}
}
let mut result = vec![String::new(); requirements.len()];
for (item, holders) in used {
for i in holders {
result[i] = item.clone();
}
}
Some(result)
}
/// The recipe book's saved state: the `recipeBook` compound of the player.
#[derive(Clone, Debug, Default)]
pub struct Settings {
/// `isGuiOpen`-style flags per `BookType`.
pub open: [bool; 4],
pub filtering: [bool; 4],
/// Unlocked recipe ids (`recipes`).
pub recipes: Vec<String>,
}
impl Settings {
pub fn read(tag: Option<&Tag>) -> Self {
let mut s = Self::default();
let Some(tag) = tag else { return s };
let flag = |k: &str| matches!(tag.get(k), Some(Tag::Byte(b)) if *b != 0);
for b in BookType::ALL {
let (open, filter) = b.keys();
s.open[b.index()] = flag(open);
s.filtering[b.index()] = flag(filter);
}
if let Some(Tag::List(list)) = tag.get("recipes") {
s.recipes = list
.iter()
.filter_map(|t| match t {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
})
.collect();
}
s
}
/// The compound written to the player file; `toBeDisplayed` stays empty.
pub fn write(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
for b in BookType::ALL {
let (open, filter) = b.keys();
entries.push((open, Tag::Byte(i8::from(self.open[b.index()]))));
entries.push((filter, Tag::Byte(i8::from(self.filtering[b.index()]))));
}
let list = |ids: &[String]| {
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
};
entries.push(("recipes", list(&self.recipes)));
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
Tag::compound(entries)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ing(items: &[&str]) -> Ingredient {
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
}
fn have(items: &[(&str, u32)]) -> Available {
Available {
counts: items.iter().map(|(i, n)| ((*i).to_owned(), *n)).collect(),
}
}
#[test]
fn small_recipes_are_centred_in_the_grid() {
// One ingredient in a 3x3 grid goes to the middle cell.
assert_eq!(place_cells(3, 3, 1, 1, &['a']), vec![('a', 4)]);
// A 2x2 recipe fills the top-left corner.
let cells: Vec<usize> = place_cells(3, 3, 2, 2, &['a', 'b', 'c', 'd'])
.into_iter()
.map(|(_, i)| i)
.collect();
assert_eq!(cells, vec![0, 1, 3, 4]);
// A one-row recipe sits on the middle row.
let row: Vec<usize> = place_cells(3, 3, 3, 1, &['a', 'b', 'c'])
.into_iter()
.map(|(_, i)| i)
.collect();
assert_eq!(row, vec![3, 4, 5]);
// The 2x2 grid is never centred.
let small: Vec<usize> = place_cells(2, 2, 1, 1, &['a'])
.into_iter()
.map(|(_, i)| i)
.collect();
assert_eq!(small, vec![0]);
}
#[test]
fn a_single_item_can_fill_several_ingredients() {
let planks = ing(&["minecraft:oak_planks", "minecraft:birch_planks"]);
let reqs = [&planks, &planks, &planks, &planks];
let a = have(&[("minecraft:oak_planks", 2), ("minecraft:birch_planks", 2)]);
assert!(a.can_craft(&reqs));
let none = HashMap::new();
// Two sets need 8 planks, but only 4 are there.
assert!(a.pick(&reqs, 2, &none).is_none());
assert!(a.pick(&reqs, 1, &none).is_some());
assert_eq!(a.biggest_stack(&reqs), 1);
assert_eq!(
have(&[("minecraft:oak_planks", 64)]).biggest_stack(&reqs),
16
);
}
#[test]
fn the_matching_reassigns_flexible_ingredients() {
// The first ingredient takes either item, the second only the stick:
// one stick must not be wasted on the first.
let any = ing(&["minecraft:stick", "minecraft:bone"]);
let stick = ing(&["minecraft:stick"]);
let a = have(&[("minecraft:stick", 1), ("minecraft:bone", 1)]);
let mut order = HashMap::new();
order.insert("minecraft:stick".to_owned(), 0);
order.insert("minecraft:bone".to_owned(), 1);
let picked = a.pick(&[&any, &stick], 1, &order).expect("matching");
assert_eq!(picked, vec!["minecraft:bone", "minecraft:stick"]);
assert!(!have(&[("minecraft:stick", 1)]).can_craft(&[&any, &stick]));
}
#[test]
fn damaged_or_named_stacks_are_not_counted() {
let mut named = ItemStack::new("minecraft:stick", 4);
named.data_mut().custom_name = Some("x".into());
let mut damaged = ItemStack::new("minecraft:iron_sword", 1);
damaged.damage = 3;
let a = Available::from_stacks([&named, &damaged, &ItemStack::new("minecraft:stick", 2)]);
assert_eq!(a.counts.get("minecraft:stick"), Some(&2));
assert!(!a.counts.contains_key("minecraft:iron_sword"));
}
#[test]
fn collections_group_recipes_of_a_category() {
let entry = |id: &str, group: Option<&str>, category| Entry {
id: id.into(),
category,
group: group.map(str::to_owned),
display: Display::Shapeless(vec![ing(&["minecraft:stick"])]),
result: ItemStack::new("minecraft:stick", 1),
};
let book = Book {
entries: vec![
entry("minecraft:a", Some("planks"), Category::CraftingBuilding),
entry("minecraft:b", Some("planks"), Category::CraftingBuilding),
entry("minecraft:c", None, Category::CraftingBuilding),
entry("minecraft:d", Some("planks"), Category::CraftingMisc),
],
order: HashMap::new(),
};
let unlocked: BTreeSet<String> = ["a", "b", "c", "d"]
.iter()
.map(|n| format!("minecraft:{n}"))
.collect();
let tab = Tab::Category(Category::CraftingBuilding);
let c = book.collections(&unlocked, BookType::Crafting, tab);
assert_eq!(c.len(), 2);
assert_eq!(c[0].entries, vec![0, 1]);
// The search tab lists every category; the same group in another category is separate.
let all = book.collections(&unlocked, BookType::Crafting, Tab::Search);
assert_eq!(all.len(), 3);
// Locked recipes are hidden.
let some: BTreeSet<String> = ["minecraft:c".to_owned()].into();
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
}
#[test]
fn settings_round_trip() {
let mut s = Settings::default();
s.open[BookType::Furnace.index()] = true;
s.filtering[BookType::Crafting.index()] = true;
s.recipes = vec!["minecraft:stick".into()];
let back = Settings::read(Some(&s.write()));
assert_eq!(back.open, s.open);
assert_eq!(back.filtering, s.filtering);
assert_eq!(back.recipes, s.recipes);
}
}
+250 -3
View File
@@ -404,6 +404,33 @@ pub fn encode_block_entity(
entries.push(("Page", Tag::Int(l.page)));
}
}
BlockEntity::Crafter(c) => {
entries.push(("Items", encode_items(&c.items)));
entries.push((
"disabled_slots",
Tag::IntArray(
(0..9)
.filter(|&i| c.disabled[i])
.map(|i| i as i32)
.collect(),
),
));
entries.push(("triggered", Tag::Int(i32::from(c.triggered))));
entries.push(("crafting_ticks_remaining", Tag::Int(c.crafting_ticks)));
}
BlockEntity::Banner(b) => {
if !b.layers.is_empty() {
entries.push(("patterns", crate::banner::layers_to_nbt(&b.layers)));
}
if let Some(name) = &b.name {
entries.push(("CustomName", string(name)));
}
}
BlockEntity::CreakingHeart(h) => {
if let Some((_, uuid)) = h.creaking {
entries.push(("creaking", uuid_tag(uuid)));
}
}
}
Tag::compound(entries)
}
@@ -425,6 +452,13 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
}),
));
}
if id == "minecraft:creaking_heart" {
let heart = crate::containers::CreakingHeart {
creaking: uuid_from_tag(tag.get("creaking")).map(|uuid| (None, uuid)),
..Default::default()
};
return Some((pos, BlockEntity::CreakingHeart(Box::new(heart))));
}
if id == "minecraft:lectern" {
let lectern = crate::containers::Lectern {
book: tag.get("Book").and_then(item_from_nbt),
@@ -432,6 +466,15 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
};
return Some((pos, BlockEntity::Lectern(lectern)));
}
if id == "minecraft:banner" {
return Some((
pos,
BlockEntity::Banner(crate::containers::Banner {
layers: crate::banner::layers_from_nbt(tag.get("patterns")),
name: text(tag.get("CustomName")),
}),
));
}
if id == "minecraft:beacon" {
let beacon = crate::containers::Beacon {
levels: int("Levels").unwrap_or(0),
@@ -478,7 +521,25 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
};
}
BlockEntity::Sign(sign) => sign.decode(tag),
BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {}
BlockEntity::Crafter(c) => {
for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() {
c.items[slot] = item;
}
if let Some(Tag::IntArray(slots)) = tag.get("disabled_slots") {
for &slot in slots {
if (0..9).contains(&slot) && c.items[slot as usize].is_none() {
c.disabled[slot as usize] = true;
}
}
}
c.triggered = int("triggered").unwrap_or(0) != 0;
c.crafting_ticks = int("crafting_ticks_remaining").unwrap_or(0);
}
BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_) => {}
}
Some((pos, entity))
}
@@ -905,6 +966,60 @@ pub fn decode_with(
Some(chunk)
}
/// Read the stored `SkyLight`/`BlockLight` layers of a chunk saved with
/// `isLightOn` (`SerializableChunkData.read` + `ThreadedLevelLightEngine`),
/// so it needs no relighting. A missing sky layer repeats the bottom layer of
/// the section above it (15 above the highest stored one); a missing block
/// layer is dark.
pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
if tag.get("isLightOn") != Some(&Tag::Byte(1)) {
return;
}
let Some(Tag::List(sections)) = tag.get("sections") else {
return;
};
let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS];
for section in sections {
let Some(y) = number(section.get("Y")) else {
continue;
};
let si = y as i32 - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&si) {
continue;
}
let layer = |name: &str| match section.get(name) {
Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]),
_ => None,
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let sky_default = if sky_light { 15u8 } else { 0 };
// Sky nibbles of the section above's bottom layer, going down.
let mut above: [u8; 256] = [sky_default; 256];
for si in (0..SECTIONS).rev() {
let (sky, block) = layers[si];
let mut data = Box::new([0u8; 4096]);
let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15;
for (i, packed) in data.iter_mut().enumerate() {
let s = match sky {
Some(a) if sky_light => nibble(a, i),
_ => above[i & 255],
};
let b = block.map_or(0, |a| nibble(a, i));
*packed = s << 4 | b;
}
for (i, a) in above.iter_mut().enumerate() {
*a = data[i] >> 4;
}
let mut section = (*chunk.sections[si]).clone();
section.light = Light::Full(data);
section.compact();
chunk.sections[si] = Arc::new(section);
}
chunk.lit = true;
chunk.light_loaded = true;
}
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
/// One dimension folder (`dimensions/minecraft/<name>`). Region files are
/// read lazily by worker threads.
@@ -955,7 +1070,9 @@ impl SaveDir {
pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option<Chunk> {
let root = self.read_record("region", x, z)?;
let tables = self.tables.get().map(|t| &**t);
decode_with(&root, registry, biomes, tables)
let mut chunk = decode_with(&root, registry, biomes, tables)?;
load_light(&root.tag, &mut chunk, self.sky_light);
Some(chunk)
}
/// Entities saved for a chunk (`entities/`; older chunks may still keep
/// them in the chunk's own `entities` list).
@@ -1314,6 +1431,8 @@ pub struct Level {
pub active_effects: Vec<(String, i32, i32, bool, bool)>,
/// Player.EnderItems: the ender chest inventory (27 slots).
pub ender_items: Vec<Option<crate::items::ItemStack>>,
/// The `recipeBook` compound: open/filter settings and unlocked recipes.
pub recipe_book: crate::recipe_book::Settings,
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
@@ -1526,6 +1645,7 @@ impl Level {
}
self.inventory = inventory;
self.ender_items = decode_items(p.get("EnderItems"), 27);
self.recipe_book = crate::recipe_book::Settings::read(p.get("recipeBook"));
self.inventory_components = inventory_components;
self.xp_seed = n("XpSeed").unwrap_or(0) as i32;
self.active_effects = match p.get("active_effects") {
@@ -1551,7 +1671,14 @@ impl Level {
let mut p = compound_or_empty(self.player_extra.clone());
// Keys rewritten from scratch.
if let Tag::Compound(map) = &mut p {
for key in ["Inventory", "EnderItems", "equipment", "Pos", "respawn"] {
for key in [
"Inventory",
"EnderItems",
"equipment",
"Pos",
"respawn",
"recipeBook",
] {
map.remove(&JavaString::from(key));
}
}
@@ -1646,6 +1773,7 @@ impl Level {
("playerGameType", Tag::Int(self.mode())),
("Inventory", Tag::List(inventory)),
("EnderItems", encode_items(&self.ender_items)),
("recipeBook", self.recipe_book.write()),
("abilities", abilities),
(
"Dimension",
@@ -1997,6 +2125,48 @@ impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
#[cfg(test)]
mod tests {
#[test]
fn crafter_block_entity_round_trips() {
let mut crafter = crate::containers::Crafter::default();
crafter.items[2] = Some(crate::items::ItemStack::new("minecraft:stick", 5));
crafter.disabled[4] = true;
crafter.triggered = true;
crafter.crafting_ticks = 3;
let tag = encode_block_entity(
(7, 8, 9),
&crate::containers::BlockEntity::Crafter(crafter),
"minecraft:crafter",
);
let (pos, back) = decode_block_entity(&tag).expect("crafter");
assert_eq!(pos, (7, 8, 9));
let crate::containers::BlockEntity::Crafter(back) = back else {
panic!("not a crafter");
};
assert_eq!(back.items[2].as_ref().map(|s| s.count), Some(5));
assert!(back.disabled[4] && !back.disabled[3]);
assert!(back.triggered);
assert_eq!(back.crafting_ticks, 3);
assert_eq!(back.redstone_signal(), 2);
}
#[test]
fn banner_block_entity_round_trips() {
let banner = crate::containers::Banner {
layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")],
name: Some("Flag".into()),
};
let tag = encode_block_entity(
(1, 2, 3),
&crate::containers::BlockEntity::Banner(banner.clone()),
"minecraft:red_banner",
);
let (pos, back) = decode_block_entity(&tag).expect("banner");
assert_eq!(pos, (1, 2, 3));
let crate::containers::BlockEntity::Banner(back) = back else {
panic!("not a banner");
};
assert_eq!(back.layers, banner.layers);
assert_eq!(back.name, banner.name);
}
use super::*;
#[test]
@@ -2011,6 +2181,37 @@ mod tests {
assert_eq!((r[1] >> 12) & 0xF, 4, "version 4");
}
#[test]
fn creaking_heart_keeps_its_protector_uuid() {
use crate::containers::{BlockEntity, CreakingHeart};
let heart = CreakingHeart {
creaking: Some((Some(7), [1, 2, 3, 4])),
..Default::default()
};
let tag = encode_block_entity(
(3, 70, -5),
&BlockEntity::CreakingHeart(Box::new(heart)),
"minecraft:creaking_heart",
);
assert_eq!(
tag.get("creaking"),
Some(&Tag::IntArray(vec![1, 2, 3, 4])),
"vanilla stores the protector's UUID under `creaking`"
);
let (pos, entity) = decode_block_entity(&tag).expect("heart decodes");
assert_eq!(pos, (3, 70, -5));
let BlockEntity::CreakingHeart(h) = entity else {
panic!("a creaking heart");
};
// The entity id is resolved again once the creaking is loaded.
assert_eq!(h.creaking, Some((None, [1, 2, 3, 4])));
let lonely = encode_block_entity(
(0, 0, 0),
&BlockEntity::CreakingHeart(Box::default()),
"minecraft:creaking_heart",
);
assert!(lonely.get("creaking").is_none());
}
#[test]
fn light_nibbles_use_vanilla_order() {
let mut a = Box::new([0u8; 4096]);
a[0] = 0xF3; // sky 15, block 3 at x=0
@@ -2020,6 +2221,52 @@ mod tests {
assert_eq!(nibbles(&light, true)[0], 0x5F);
}
#[test]
fn stored_light_loads_with_vanilla_defaults() {
let mut sky = vec![0u8; 2048];
sky[0] = 0x5A; // x=0 -> 10, x=1 -> 5
let section = |y: i8, entries: Vec<(&str, Tag)>| {
let mut all = vec![("Y", Tag::Byte(y))];
all.extend(entries);
Tag::compound(all)
};
let tag = Tag::compound([
("isLightOn", Tag::Byte(1)),
(
"sections",
Tag::List(vec![
section(
-4,
vec![
("SkyLight", Tag::ByteArray(sky)),
("BlockLight", Tag::ByteArray(vec![0x21; 2048])),
],
),
// No sky layer: repeats the bottom layer of the section above.
section(-3, vec![]),
]),
),
]);
let mut chunk = Chunk::empty(0, 0);
load_light(&tag, &mut chunk, true);
assert!(chunk.lit && chunk.light_loaded);
let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i);
assert_eq!(at(&chunk, 0, 0), 0xA1, "stored sky 10, block 1");
assert_eq!(at(&chunk, 0, 1), 0x52, "stored sky 5, block 2");
// Section -3 has no layers; above it (-2..) sky defaults to 15.
assert_eq!(at(&chunk, 1, 0), 0xF0);
assert_eq!(at(&chunk, SECTIONS - 1, 5), 0xF0);
let mut dark = Chunk::empty(0, 0);
load_light(&tag, &mut dark, false);
assert_eq!(at(&dark, 1, 0), 0x00, "no skylight dimension");
let mut unlit = Chunk::empty(0, 0);
load_light(
&Tag::compound([("isLightOn", Tag::Byte(0))]),
&mut unlit,
true,
);
assert!(!unlit.lit && !unlit.light_loaded);
}
#[test]
fn level_round_trips_through_the_vanilla_files() {
let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
+2
View File
@@ -18,6 +18,7 @@ pub struct StationData {
pub recipes: StationRecipes,
pub brewing: crate::brewing::Brewing,
pub trades: crate::merchant::Trades,
pub banners: crate::banner::Banners,
}
impl StationData {
pub fn load(root: &Path, items: &Items) -> Self {
@@ -26,6 +27,7 @@ impl StationData {
recipes: StationRecipes::load(root, items),
brewing: crate::brewing::Brewing::load(root, items),
trades: crate::merchant::Trades::load(root),
banners: crate::banner::Banners::load(root),
}
}
}
+14 -1
View File
@@ -332,10 +332,23 @@ impl Streaming {
self.decorated.insert(key);
if self.in_range(key.0, key.1, 2) {
self.generated_total += 1;
// A chunk saved with its light needs no light job; its
// unlit neighbours still light themselves from it.
let loaded = chunk.light_loaded;
world.chunks.insert(key, Arc::new(chunk));
if loaded {
self.lit.insert(key);
for sy in 0..SECTIONS as i32 {
world.dirty_sections.insert((key.0, sy, key.1));
}
}
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
let n = (key.0 + dx, key.1 + dz);
if !loaded || world.chunks.get(&n).is_some_and(|c| !c.light_loaded)
{
world.dirty_light.insert(n);
}
}
}
}
+12 -5
View File
@@ -59,11 +59,18 @@ pub fn block_entities(
.iter_mut()
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
*slot = stack.map(|s| ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
*slot = stack.map(|s| {
let mut item = ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
};
// An ominous bottle's level (the default, 0, is no component).
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
}
item
});
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Dispenser use of buckets: `BucketPickup.pickupBlock` for an empty bucket and
//! `DispensibleContainerItem.emptyContents` for filled ones (`BucketItem`,
//! `MobBucketItem`, `SolidBucketItem`), both without a player.
use super::{
Behaviours, Dimension, LevelAccess, Sim, Ticks,
classes::{Class, Interface},
};
use crate::{
fluid::{FluidKind, FluidState},
registry::BlockStateId,
};
use horizon_core::{position::BlockPos, random::RandomSource};
use std::sync::Arc;
/// What a filled bucket empties into the world.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BucketContent {
/// Water or lava (mob buckets hold water).
Fluid(FluidKind),
/// `SolidBucketItem`: the block placed into an empty space (powder snow).
Powder,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `BucketPickup.pickupBlock(null, level, pos, state)`: the filled bucket
/// that results, None when the block gives nothing.
pub(crate) fn bucket_pickup(&mut self, pos: BlockPos) -> Option<&'static str> {
let b = self.b;
let state = self.state(pos);
let item = if b.instance_of(state, Class::Liquid) {
match b.fluid(state).kind() {
FluidKind::Water | FluidKind::FlowingWater => "minecraft:water_bucket",
FluidKind::Lava | FluidKind::FlowingLava => "minecraft:lava_bucket",
FluidKind::Empty => return None,
}
} else if b.implements(state, Interface::SimpleWaterlogged)
&& b.table.has(state, b.props.waterlogged)
{
"minecraft:water_bucket"
} else if b.is_block(state, b.named.powder_snow) {
"minecraft:powder_snow_bucket"
} else {
return None;
};
self.pickup_block(pos, state).then_some(item)
}
/// `BucketItem.emptyContents(null, level, pos, null)`. `sound` is the
/// bucket's empty sound (mob buckets have their own).
pub(crate) fn bucket_empty(
&mut self,
pos: BlockPos,
content: BucketContent,
sound: &str,
) -> bool {
let b = self.b;
let fluid = match content {
BucketContent::Powder => {
if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) {
let snow = b.table.default_state(b.named.powder_snow);
self.set_block_and_update(pos, snow);
self.game_event(pos, "minecraft:fluid_place");
self.empty_sound(pos, sound);
return true;
}
return false;
}
BucketContent::Fluid(fluid) => fluid,
};
let state = self.state(pos);
// canBeReplaced(fluid): replaceable or not solid (portals refuse).
let may_replace = !b.instance_of(state, Class::EndPortal)
&& !b.instance_of(state, Class::EndGateway)
&& (b.is_replaceable(state) || !b.is_solid(state));
let liquid_container = self.is_liquid_container(state);
let container = liquid_container && self.can_place_liquid(state, fluid);
let place_liquid = may_replace || container;
if !(b.is_air(state) || place_liquid) {
return false;
}
let water = matches!(fluid, FluidKind::Water | FluidKind::FlowingWater);
if water && self.level.dimension() == Dimension::Nether {
// WATER_EVAPORATES: the water hisses away.
let pitch = 2.6 + (self.random().next_float() - self.random().next_float()) * 0.8;
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.fire.extinguish".into(),
volume: 0.5,
pitch,
});
return true;
}
if liquid_container && water {
self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false));
self.empty_sound(pos, sound);
return true;
}
if may_replace && !b.instance_of(state, Class::Liquid) {
self.destroy_block(pos, true, super::flags::UPDATE_LIMIT);
}
let source = FluidState::new(
if water {
FluidKind::Water
} else {
FluidKind::Lava
},
8,
false,
);
let legacy: BlockStateId = b.legacy_block(source);
if !self.set_block(pos, legacy, super::flags::UPDATE_ALL_IMMEDIATE)
&& !self.fluid_at(pos).is_source()
{
return false;
}
self.empty_sound(pos, sound);
true
}
fn empty_sound(&mut self, pos: BlockPos, sound: &str) {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
self.game_event(pos, "minecraft:fluid_place");
}
}
impl Behaviours {
/// `BucketPickup.pickupBlock` by a dispenser: the filled bucket item.
pub fn bucket_pickup<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) -> Option<&'static str> {
self.sim(level, ticks).bucket_pickup(pos)
}
/// `DispensibleContainerItem.emptyContents(null, level, pos, null)`.
pub fn bucket_empty<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
content: BucketContent,
sound: &str,
) -> bool {
self.sim(level, ticks).bucket_empty(pos, content, sound)
}
}
@@ -0,0 +1,83 @@
//! The creaking heart block (`CreakingHeartBlock`): its state follows the
//! pale oak logs on both ends of its axis and the `creaking_active`
//! environment attribute. The block entity (protector, particles, resin)
//! lives with the entities in the client.
use super::{Behaviours, Dimension, LevelAccess, Sim, Ticks, update::rel};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
/// `Direction.Axis.getDirections()`.
fn axis_directions(axis: &str) -> [Direction; 2] {
match axis {
"x" => [Direction::West, Direction::East],
"z" => [Direction::North, Direction::South],
_ => [Direction::Down, Direction::Up],
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld day timeline
/// turns it on from 12600 to 23400.
pub(crate) fn creaking_active(&self) -> bool {
self.level.dimension() == Dimension::Overworld
&& (12600..23401).contains(&self.level.day_time().rem_euclid(24000))
}
/// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs along the axis.
pub(crate) fn heart_has_required_logs(&self, state: BlockStateId, pos: BlockPos) -> bool {
let b = self.b;
let axis = b.table.text(state, b.props.axis);
axis_directions(axis).into_iter().all(|d| {
let neighbour = self.state(rel(pos, d));
b.in_set(neighbour, &b.tags.pale_oak_logs)
&& b.table.text(neighbour, b.props.axis) == axis
})
}
/// `CreakingHeartBlock.updateState`: an uprooted heart with its logs wakes
/// (at night) or goes dormant.
pub(crate) fn heart_update_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId {
let b = self.b;
let uprooted = b.table.text(state, b.props.creaking_heart_state) == "uprooted";
if uprooted && self.heart_has_required_logs(state, pos) {
let next = if self.creaking_active() {
"awake"
} else {
"dormant"
};
b.table.set_text(state, b.props.creaking_heart_state, next)
} else {
state
}
}
/// `CreakingHeartBlock.tick` (scheduled by `updateShape`).
pub(crate) fn heart_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let next = self.heart_update_state(state, pos);
if next != state {
self.set_block_and_update(pos, next);
}
}
/// `CreakingHeartBlock.getStateForPlacement` after the axis is set.
pub(crate) fn heart_placement(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId {
self.heart_update_state(state, pos)
}
}
impl Behaviours {
/// `EnvironmentAttributes.CREAKING_ACTIVE` at the level's time.
pub fn creaking_active<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
) -> bool {
self.sim(level, ticks).creaking_active()
}
/// `CreakingHeartBlock.hasRequiredLogs`.
pub fn creaking_heart_has_logs<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
state: BlockStateId,
) -> bool {
self.sim(level, ticks).heart_has_required_logs(state, pos)
}
}
+2
View File
@@ -451,6 +451,7 @@ tags! {
enables_bubble_column_push_up = "enables_bubble_column_push_up",
enables_bubble_column_drag_down = "enables_bubble_column_drag_down",
shulker_boxes = "shulker_boxes",
pale_oak_logs = "pale_oak_logs",
convertible_to_mud = "convertible_to_mud",
grows_crops = "grows_crops",
candles = "candles",
@@ -553,6 +554,7 @@ props! {
honey_level = "honey_level",
bloom = "bloom",
natural = "natural",
creaking_heart_state = "creaking_heart_state",
cracked = "cracked",
has_book = "has_book",
signal_fire = "signal_fire",
+1 -1
View File
@@ -178,7 +178,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
// ---- liquid containers ----
/// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause).
fn is_liquid_container(&self, state: BlockStateId) -> bool {
pub(super) fn is_liquid_container(&self, state: BlockStateId) -> bool {
self.b.implements(state, Interface::LiquidBlockContainer)
|| self.b.implements(state, Interface::SimpleWaterlogged)
}
+3
View File
@@ -101,6 +101,8 @@ pub mod states;
pub mod ticks;
mod bonemeal;
mod buckets;
mod creaking;
mod falling;
mod feature_world;
mod fluids;
@@ -126,6 +128,7 @@ mod growth_tests;
#[cfg(test)]
mod tests;
pub use buckets::BucketContent;
pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags};
pub use falling::Landing;
pub use interact::{InteractionResult, PlayerContext, PlayerEffect};
+6 -1
View File
@@ -786,7 +786,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
);
Some(table.set_text(default, p.orientation, &orientation))
}
Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => {
Class::CreakingHeart => {
let state =
table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face)));
Some(self.heart_placement(state, ctx.pos))
}
Class::RotatedPillar | Class::InfestedRotatedPillar => {
Some(table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face))))
}
Class::DecoratedPot => {
+113
View File
@@ -43,6 +43,7 @@ pub(crate) struct TestLevel {
air: BlockStateId,
random: LegacyRandom,
pub time: i64,
pub day_time: i64,
pub events: Vec<LevelEvent>,
pub block_light: HashMap<BlockPos, i32>,
}
@@ -53,6 +54,7 @@ impl TestLevel {
air: b.air(),
random: LegacyRandom::new(42),
time: 0,
day_time: 0,
events: Vec::new(),
block_light: HashMap::new(),
}
@@ -74,6 +76,9 @@ impl LevelAccess for TestLevel {
fn game_time(&self) -> i64 {
self.time
}
fn day_time(&self) -> i64 {
self.day_time
}
fn block_light(&self, pos: BlockPos) -> i32 {
self.block_light.get(&pos).copied().unwrap_or(0)
}
@@ -917,3 +922,111 @@ fn dripstone_fills_cauldrons() {
}
assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]");
}
#[test]
fn dispenser_buckets_pick_up_and_empty() {
let mut w = world!();
let at = BlockPos::new(0, 10, 0);
let water = w.id("water", &[("level", "0")]);
w.put(at, water);
let picked = w.b().bucket_pickup(&mut w.level, &mut w.ticks, at);
assert_eq!(picked, Some("minecraft:water_bucket"));
assert_eq!(w.get(at), w.b().air());
// Flowing water gives nothing.
let flowing = w.id("water", &[("level", "3")]);
w.put(at, flowing);
assert_eq!(w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), None);
// A waterlogged slab is drained and stays a slab.
let slab = w.id("oak_slab", &[("waterlogged", "true")]);
w.put(at, slab);
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:water_bucket")
);
assert_eq!(w.prop(at, "waterlogged"), "false");
// Powder snow comes up as its bucket.
let snow = w.id("powder_snow", &[]);
w.put(at, snow);
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:powder_snow_bucket")
);
// Emptying water into air makes a source; stone refuses.
let sound = "minecraft:item.bucket.empty";
let content = BucketContent::Fluid(crate::fluid::FluidKind::Water);
assert!(
w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
assert_eq!(w.name(at), "water[level=0]");
let stone = w.id("stone", &[]);
w.put(at, stone);
assert!(
!w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
// Water fills a waterloggable slab instead of replacing it.
let dry = w.id("oak_slab", &[]);
w.put(at, dry);
assert!(
w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
assert_eq!(w.prop(at, "waterlogged"), "true");
// Powder snow only goes into empty space.
let air = w.b().air();
w.put(at, air);
assert!(w.b().bucket_empty(
&mut w.level,
&mut w.ticks,
at,
BucketContent::Powder,
"minecraft:item.bucket.empty_powder_snow"
));
assert_eq!(w.name(at), "powder_snow[]");
}
#[test]
fn creaking_heart_follows_its_logs_and_the_night() {
let mut w = world!();
let heart_at = BlockPos::new(0, 10, 0);
let log = |w: &World, axis: &str| w.id("pale_oak_log", &[("axis", axis)]);
let heart = w.id(
"creaking_heart",
&[("axis", "y"), ("creaking_heart_state", "uprooted")],
);
let (below, above) = (BlockPos::new(0, 9, 0), BlockPos::new(0, 11, 0));
w.put(heart_at, heart);
w.put(below, log(&w, "y"));
// A log along another axis does not count.
w.put(above, log(&w, "x"));
assert!(
!w.b()
.creaking_heart_has_logs(&mut w.level, &mut w.ticks, heart_at, heart)
);
// Day: a log update wakes the uprooted heart to dormant.
let up = log(&w, "y");
w.set(above, up);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "dormant");
// Night: the same trunk wakes a fresh heart up.
w.level.day_time = 14000;
w.put(heart_at, heart);
w.put(above, w.b().air());
w.set(above, up);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "awake");
// Placed without logs it stays uprooted.
w.put(above, w.b().air());
w.put(heart_at, heart);
let air = w.b().air();
w.set(above, air);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted");
}
+1
View File
@@ -146,6 +146,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
Class::Observer => self.observer_tick(pos, state),
Class::Eyeblossom => self.eyeblossom_tick(state, pos, false),
Class::CreakingHeart => self.heart_tick(state, pos),
Class::DriedGhast => self.dried_ghast_tick(state, pos),
Class::RedstoneLamp => self.lamp_tick(pos, state),
Class::RedstoneTorch => self.torch_tick(pos, state),
+4 -1
View File
@@ -23,6 +23,8 @@ pub struct LootStack {
pub potion: Option<String>,
/// Set by exploration_map (the map_id component of a found map).
pub map: bool,
/// Set by set_ominous_bottle_amplifier.
pub ominous_amplifier: Option<i32>,
}
impl LootStack {
fn new(item: &str) -> Self {
@@ -33,6 +35,7 @@ impl LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
ominous_amplifier: None,
}
}
pub fn is_empty(&self) -> bool {
@@ -584,7 +587,7 @@ impl Context<'_> {
}
}
"minecraft:set_ominous_bottle_amplifier" => {
self.int(&f["amplifier"]);
stack.ominous_amplifier = Some(self.int(&f["amplifier"]));
}
"minecraft:set_instrument" => {
let options = data.holder_set("instrument", &f["options"]);
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Compare Horizon's light engine with the vanilla 26.3 server.
Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass,
leaves, water and glowstone in a fresh vanilla world, lets the vanilla light
engine settle, stops the server so the SkyLight/BlockLight arrays are saved,
then relights every saved chunk with `examples/light_parity` and requires every
value to agree. The example also replays block edits through the incremental
`light::relight` and checks them against a full relight.
test_light_parity.py [--seed N] [--keep]
"""
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
LOCAL = ROOT / '.local'
RESOURCES = LOCAL / 'horizon-client' / '26.3'
SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar'
# Absolute coordinates well above the terrain, inside force-loaded chunks.
SCENE = [
'forceload add 0 0 63 63',
'sleep 6',
# Closed room with a bottom-slab roof and a glowstone lamp.
'fill 2 170 2 20 175 20 stone hollow',
'fill 2 176 2 20 176 20 stone_slab[type=bottom]',
'setblock 10 171 10 glowstone',
# Stairs, top and bottom; snow layers; trapdoors; lanterns; water.
'fill 4 171 4 4 171 18 oak_stairs[facing=east,half=top]',
'fill 6 171 4 6 171 18 stone_brick_stairs[facing=north,half=bottom,shape=inner_left]',
'fill 12 171 4 18 171 6 snow[layers=3]',
'fill 12 172 8 18 172 8 oak_trapdoor[half=bottom,open=false]',
'fill 12 173 12 18 173 12 oak_trapdoor[half=top,open=true,facing=north]',
'setblock 14 171 14 lantern',
'setblock 15 175 15 soul_lantern[hanging=true]',
'fill 8 171 16 9 172 17 water',
# Open-air structures: sky light through slabs, stairs and leaves.
'fill 24 170 24 46 170 46 stone',
'fill 26 171 26 44 171 26 stone_slab[type=top]',
'fill 26 171 28 44 171 28 stone_slab[type=bottom]',
'fill 26 172 30 44 172 30 oak_leaves[persistent=true]',
'fill 26 171 32 30 171 40 glass',
'fill 32 171 32 36 171 40 oak_stairs[facing=south,half=bottom]',
'fill 38 171 32 38 175 40 stone_brick_wall',
'fill 40 171 32 44 171 40 dirt_path',
'fill 40 172 34 44 172 34 daylight_detector',
'fill 24 180 50 46 180 50 stone_slab[type=double]',
'fill 24 178 52 46 178 52 oak_stairs[facing=west,half=top]',
'setblock 30 171 44 torch',
'setblock 34 171 44 campfire',
'setblock 38 171 44 sea_lantern',
'setblock 42 171 44 lava',
'sleep 10',
# Edits after the first lighting pass, so vanilla updates incrementally.
'setblock 10 171 10 air',
'setblock 10 176 10 air',
'setblock 30 171 26 air',
'fill 26 172 30 30 172 30 air',
# Vanilla saves a chunk only when its blocks changed, so light that
# reached an untouched chunk later is stale on disk: mark every compared
# chunk (0..2, 0..3) as edited so it is written at shutdown.
*[f'setblock {x * 16 + 8} 169 {z * 16 + 8} stone' for x in range(3) for z in range(4)],
'sleep 8',
]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', default='4242')
parser.add_argument('--keep', action='store_true')
args = parser.parse_args()
run = LOCAL / 'rust-light-parity'
shutil.rmtree(run, ignore_errors=True)
run.mkdir(parents=True)
command = [sys.executable, str(ROOT / 'tools' / 'vanilla_world_check.py'), '--jar', str(SERVER),
'--dir', str(run), '--world', 'world', '--seed', args.seed, '--wait-after', '8']
for step in SCENE:
command += ['--command', step]
if subprocess.run(command).returncode:
sys.exit('vanilla server reported problems')
dimension = run / 'world' / 'dimensions' / 'minecraft' / 'overworld'
if not (dimension / 'region').is_dir():
dimension = run / 'world'
for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']):
status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client',
'--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra],
cwd=ROOT).returncode
if status:
sys.exit('light mismatch against vanilla')
print('light parity ok')
if not args.keep:
shutil.rmtree(run, ignore_errors=True)
if __name__ == '__main__':
main()