diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs new file mode 100644 index 000000000..62413bada --- /dev/null +++ b/crates/horizon-client/src/advancements.rs @@ -0,0 +1,683 @@ +//! Advancements: the tree loaded from `data/*/advancement`, the player's +//! progress (`PlayerAdvancements`) and the predicates criteria test +//! (`EntityPredicate`, `ItemPredicate`, `LocationPredicate`, the loot +//! conditions advancements use). +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap}, + path::Path, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Frame { + Task, + Goal, + Challenge, +} +#[derive(Clone, Debug)] +pub struct Display { + pub icon: String, + pub title: Value, + pub description: Value, + pub frame: Frame, + pub background: Option, + pub show_toast: bool, + pub announce: bool, + pub hidden: bool, +} +#[derive(Clone, Debug)] +pub struct Criterion { + pub name: String, + pub trigger: String, + pub conditions: Value, +} +#[derive(Clone, Debug, Default)] +pub struct Rewards { + pub recipes: Vec, + pub experience: i32, + pub loot: Vec, +} +#[derive(Clone, Debug)] +pub struct Advancement { + pub id: String, + pub parent: Option, + pub display: Option, + pub criteria: Vec, + pub requirements: Vec>, + pub rewards: Rewards, +} +/// Every advancement, indexed by id and by trigger. +#[derive(Default)] +pub struct Tree { + pub list: Vec, + pub by_id: HashMap, + /// trigger id -> (advancement index, criterion index). + pub by_trigger: HashMap>, +} +fn frame(v: &Value) -> Frame { + match v.as_str() { + Some("goal") => Frame::Goal, + Some("challenge") => Frame::Challenge, + _ => Frame::Task, + } +} +impl Tree { + /// Loads `//advancement/**/*.json`. + pub fn load(data: &Path) -> Tree { + let mut tree = Tree::default(); + let Ok(namespaces) = std::fs::read_dir(data) else { + return tree; + }; + let mut files = Vec::new(); + for ns in namespaces.flatten() { + let root = ns.path().join("advancement"); + collect(&root, &root, &ns.file_name().to_string_lossy(), &mut files); + } + files.sort(); + for (id, path) in files { + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(v) = serde_json::from_str::(&text) else { + continue; + }; + if let Some(a) = parse(&id, &v) { + let index = tree.list.len(); + for (ci, c) in a.criteria.iter().enumerate() { + tree.by_trigger + .entry(c.trigger.clone()) + .or_default() + .push((index, ci)); + } + tree.by_id.insert(id, index); + tree.list.push(a); + } + } + tree + } + pub fn get(&self, id: &str) -> Option<&Advancement> { + self.by_id.get(id).map(|&i| &self.list[i]) + } +} +fn collect(root: &Path, dir: &Path, ns: &str, out: &mut Vec<(String, std::path::PathBuf)>) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + collect(root, &p, ns, out); + } else if p.extension().is_some_and(|x| x == "json") { + let rel = p.strip_prefix(root).unwrap_or(&p).with_extension(""); + let rel = rel.to_string_lossy().replace('\\', "/"); + out.push((format!("{ns}:{rel}"), p)); + } + } +} +fn parse(id: &str, v: &Value) -> Option { + let criteria: Vec = v["criteria"] + .as_object()? + .iter() + .map(|(name, c)| Criterion { + name: name.clone(), + trigger: c["trigger"].as_str().unwrap_or("").to_owned(), + conditions: c["conditions"].clone(), + }) + .collect(); + let requirements = match v["requirements"].as_array() { + Some(r) => r + .iter() + .map(|group| { + group + .as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() + }) + .collect(), + // AdvancementRequirements.allOf: every criterion. + None => criteria.iter().map(|c| vec![c.name.clone()]).collect(), + }; + let d = &v["display"]; + let display = d.is_object().then(|| Display { + icon: d["icon"]["id"] + .as_str() + .unwrap_or("minecraft:air") + .to_owned(), + title: d["title"].clone(), + description: d["description"].clone(), + frame: frame(&d["frame"]), + background: d["background"].as_str().map(str::to_owned), + show_toast: d["show_toast"].as_bool().unwrap_or(true), + announce: d["announce_to_chat"].as_bool().unwrap_or(true), + hidden: d["hidden"].as_bool().unwrap_or(false), + }); + let r = &v["rewards"]; + let strings = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() + }; + Some(Advancement { + id: id.to_owned(), + parent: v["parent"].as_str().map(str::to_owned), + display, + criteria, + requirements, + rewards: Rewards { + recipes: strings(&r["recipes"]), + experience: r["experience"].as_i64().unwrap_or(0) as i32, + loot: strings(&r["loot"]), + }, + }) +} + +/// The player's progress: advancement -> criterion -> obtained date. +#[derive(Default, Clone)] +pub struct Progress { + pub criteria: BTreeMap>, +} +impl Progress { + pub fn has(&self, adv: &str, criterion: &str) -> bool { + self.criteria + .get(adv) + .is_some_and(|m| m.contains_key(criterion)) + } + /// `AdvancementProgress.isDone`. + pub fn done(&self, a: &Advancement) -> bool { + !a.requirements.is_empty() + && a.requirements + .iter() + .all(|group| group.iter().any(|c| self.has(&a.id, c))) + } + /// Completed requirement groups and their count (the screen's tooltip). + pub fn counts(&self, a: &Advancement) -> (usize, usize) { + let done = a + .requirements + .iter() + .filter(|g| g.iter().any(|c| self.has(&a.id, c))) + .count(); + (done, a.requirements.len()) + } + pub fn grant(&mut self, adv: &str, criterion: &str, date: &str) -> bool { + let m = self.criteria.entry(adv.to_owned()).or_default(); + if m.contains_key(criterion) { + return false; + } + m.insert(criterion.to_owned(), date.to_owned()); + true + } + pub fn revoke(&mut self, adv: &str, criterion: &str) -> bool { + self.criteria + .get_mut(adv) + .is_some_and(|m| m.remove(criterion).is_some()) + } + pub fn from_json(v: &Value) -> Progress { + let mut p = Progress::default(); + if let Some(o) = v.as_object() { + for (adv, entry) in o { + if adv == "DataVersion" { + continue; + } + if let Some(c) = entry["criteria"].as_object() { + let m = p.criteria.entry(adv.clone()).or_default(); + for (k, d) in c { + m.insert(k.clone(), d.as_str().unwrap_or("").to_owned()); + } + } + } + } + p + } + pub fn to_json(&self, tree: &Tree, data_version: i32) -> Value { + let mut o = serde_json::Map::new(); + for (adv, m) in &self.criteria { + if m.is_empty() { + continue; + } + let done = tree.get(adv).is_some_and(|a| self.done(a)); + o.insert( + adv.clone(), + serde_json::json!({ "criteria": m, "done": done }), + ); + } + o.insert("DataVersion".into(), data_version.into()); + Value::Object(o) + } +} + +/// What predicates may ask about the world. +pub trait World { + fn dimension(&self) -> &str; + fn biome(&self, pos: [i32; 3]) -> String; + fn structures(&self, pos: [i32; 3]) -> Vec; + /// Block name and properties. + fn block(&self, pos: [i32; 3]) -> (String, BTreeMap); + fn fluid(&self, pos: [i32; 3]) -> Option; + fn can_see_sky(&self, pos: [i32; 3]) -> bool; + fn light(&self, pos: [i32; 3]) -> i32; + fn smokey(&self, pos: [i32; 3]) -> bool; + fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool; +} +/// An item stack as predicates see it. +#[derive(Clone, Debug, Default)] +pub struct ItemView { + pub id: String, + pub count: u32, + pub damage: u32, + pub enchantments: Vec<(String, u32)>, + pub potion: Option, + pub custom_name: bool, +} +/// An entity as predicates see it. +#[derive(Clone, Debug, Default)] +pub struct EntityView { + pub kind: String, + pub position: [f64; 3], + pub on_fire: bool, + pub sneaking: bool, + pub sprinting: bool, + pub swimming: bool, + pub flying: bool, + pub baby: bool, + pub on_ground: bool, + /// mainhand, offhand, head, chest, legs, feet, body. + pub equipment: [Option; 7], + pub vehicle: Option>, + pub effects: Vec<(String, i32, i32)>, + /// Player: game mode name. + pub gamemode: Option, + /// Lightning: entities it struck. + pub struck: Vec, + pub fishing_open_water: Option, + pub variant: Option, +} +fn range_f(v: &Value, x: f64) -> bool { + match v { + Value::Null => true, + Value::Number(n) => n.as_f64().is_some_and(|n| (n - x).abs() < 1e-9), + Value::Object(o) => { + o.get("min").and_then(Value::as_f64).is_none_or(|m| x >= m) + && o.get("max").and_then(Value::as_f64).is_none_or(|m| x <= m) + } + _ => false, + } +} +fn range_i(v: &Value, x: i64) -> bool { + range_f(v, x as f64) +} +/// A registry id, `#tag`, or list matched against one id. +fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool { + match v { + Value::Null => true, + Value::String(s) => match s.strip_prefix('#') { + Some(tag) => w.in_tag(registry, tag, id), + None => s == id, + }, + Value::Array(a) => a.iter().any(|x| id_matches(x, registry, id, w)), + _ => false, + } +} +/// `ItemPredicate`. +pub fn item(v: &Value, it: &ItemView, w: &dyn World) -> bool { + if v.is_null() { + return true; + } + if !id_matches(&v["items"], "item", &it.id, w) { + return false; + } + if !range_i(&v["count"], i64::from(it.count)) { + return false; + } + // Data components: exact matches on the few the data uses. + let comps = &v["components"]; + if let Some(p) = comps["minecraft:potion_contents"].as_str() + && it.potion.as_deref() != Some(p) + { + return false; + } + let preds = &v["predicates"]; + if let Some(list) = preds["minecraft:enchantments"].as_array() { + for e in list { + let ok = it.enchantments.iter().any(|(id, lvl)| { + id_matches(&e["enchantments"], "enchantment", id, w) + && range_i(&e["levels"], i64::from(*lvl)) + }); + if !ok { + return false; + } + } + } + if let Some(d) = preds["minecraft:damage"].as_object() { + let damage = Value::Object(d.clone()); + if !range_i(&damage["damage"], i64::from(it.damage)) { + return false; + } + } + true +} +/// `BlockPredicate`. +pub fn block(v: &Value, pos: [i32; 3], w: &dyn World) -> bool { + if v.is_null() { + return true; + } + let (name, props) = w.block(pos); + if !id_matches(&v["blocks"], "block", &name, w) { + return false; + } + if let Some(state) = v["state"].as_object() { + for (k, want) in state { + let have = props.get(k).cloned().unwrap_or_default(); + let ok = match want { + Value::String(s) => have == *s, + Value::Bool(b) => have == b.to_string(), + Value::Number(n) => have == n.to_string(), + Value::Object(_) => have.parse::().is_ok_and(|h| range_f(want, h)), + _ => false, + }; + if !ok { + return false; + } + } + } + true +} +/// `LocationPredicate`. +pub fn location(v: &Value, p: [f64; 3], w: &dyn World) -> bool { + if v.is_null() { + return true; + } + let pos = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + let posv = &v["position"]; + if !range_f(&posv["x"], p[0]) || !range_f(&posv["y"], p[1]) || !range_f(&posv["z"], p[2]) { + return false; + } + if let Some(d) = v["dimension"].as_str() + && d != w.dimension() + { + return false; + } + if !v["biomes"].is_null() && !id_matches(&v["biomes"], "worldgen/biome", &w.biome(pos), w) { + return false; + } + if !v["structures"].is_null() { + let here = w.structures(pos); + if !here + .iter() + .any(|s| id_matches(&v["structures"], "worldgen/structure", s, w)) + { + return false; + } + } + if let Some(b) = v["can_see_sky"].as_bool() + && b != w.can_see_sky(pos) + { + return false; + } + if let Some(b) = v["smokey"].as_bool() + && b != w.smokey(pos) + { + return false; + } + if !v["light"].is_null() && !range_i(&v["light"]["light"], i64::from(w.light(pos))) { + return false; + } + if !v["block"].is_null() && !block(&v["block"], pos, w) { + return false; + } + if !v["fluid"].is_null() { + let Some(f) = w.fluid(pos) else { + return false; + }; + if !id_matches(&v["fluid"]["fluids"], "fluid", &f, w) { + return false; + } + } + true +} +/// `EntityPredicate` (26.x keyed sub-predicates). +pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool { + if v.is_null() { + return true; + } + let Some(o) = v.as_object() else { + return false; + }; + for (key, p) in o { + let ok = match key.as_str() { + "minecraft:entity_type" | "type" => id_matches(p, "entity_type", &e.kind, w), + "minecraft:location" | "location" => location(p, e.position, w), + "minecraft:stepping_on" => { + location(p, [e.position[0], e.position[1] - 0.5, e.position[2]], w) + } + "minecraft:distance" | "distance" => { + let d = [ + e.position[0] - origin[0], + e.position[1] - origin[1], + e.position[2] - origin[2], + ]; + range_f(&p["x"], d[0].abs()) + && range_f(&p["y"], d[1].abs()) + && range_f(&p["z"], d[2].abs()) + && range_f(&p["horizontal"], (d[0] * d[0] + d[2] * d[2]).sqrt()) + && range_f( + &p["absolute"], + (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(), + ) + } + "minecraft:flags" | "flags" => { + let f = |k: &str, have: bool| p[k].as_bool().is_none_or(|want| want == have); + f("is_on_fire", e.on_fire) + && f("is_sneaking", e.sneaking) + && f("is_sprinting", e.sprinting) + && f("is_swimming", e.swimming) + && f("is_flying", e.flying) + && f("is_baby", e.baby) + && f("is_on_ground", e.on_ground) + } + "minecraft:equipment" | "equipment" => { + let slots = [ + "mainhand", "offhand", "head", "chest", "legs", "feet", "body", + ]; + slots.iter().enumerate().all(|(i, s)| { + p[*s].is_null() + || e.equipment[i] + .as_ref() + .is_some_and(|it| item(&p[*s], it, w)) + }) + } + "minecraft:vehicle" | "vehicle" => e + .vehicle + .as_ref() + .is_some_and(|veh| entity(p, veh, w, origin)), + "minecraft:effects" | "effects" => p.as_object().is_some_and(|m| { + m.iter().all(|(id, want)| { + e.effects.iter().any(|(eid, amp, dur)| { + eid == id + && range_i(&want["amplifier"], i64::from(*amp)) + && range_i(&want["duration"], i64::from(*dur)) + }) + }) + }), + "minecraft:type_specific/player" => p["gamemode"].as_array().is_none_or(|modes| { + e.gamemode + .as_deref() + .is_some_and(|g| modes.iter().any(|m| m.as_str() == Some(g))) + }), + "minecraft:type_specific/lightning" => { + range_i(&p["blocks_set_on_fire"], 0) + && (p["entity_struck"].is_null() + || e.struck + .iter() + .any(|s| entity(&p["entity_struck"], s, w, origin))) + } + "minecraft:type_specific/fishing_hook" => p["in_open_water"] + .as_bool() + .is_none_or(|want| e.fishing_open_water == Some(want)), + "minecraft:components" | "minecraft:predicates" => true, + _ => false, + }; + if !ok { + return false; + } + } + true +} +/// The entities a loot-style condition list may refer to. +pub struct Entities<'a> { + pub this: Option<&'a EntityView>, + pub origin: [f64; 3], + pub tool: Option<&'a ItemView>, + pub block_pos: Option<[i32; 3]>, +} +/// A `ContextAwarePredicate`: a list of loot conditions (or one condition). +pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool { + match v { + Value::Null => true, + Value::Array(list) => list.iter().all(|c| conditions(c, ctx, w)), + Value::Object(o) if o.contains_key("condition") || o.contains_key("type") => { + let ty = o + .get("condition") + .or_else(|| o.get("type")) + .and_then(Value::as_str) + .unwrap_or(""); + match ty { + "minecraft:entity_properties" => ctx + .this + .is_some_and(|e| entity(&v["predicate"], e, w, ctx.origin)), + "minecraft:location_check" => { + let base = ctx.block_pos.map_or(ctx.origin, |b| { + [ + f64::from(b[0]) + 0.5, + f64::from(b[1]) + 0.5, + f64::from(b[2]) + 0.5, + ] + }); + let off = [ + v["offsetX"].as_f64().unwrap_or(0.0), + v["offsetY"].as_f64().unwrap_or(0.0), + v["offsetZ"].as_f64().unwrap_or(0.0), + ]; + location( + &v["predicate"], + [base[0] + off[0], base[1] + off[1], base[2] + off[2]], + w, + ) + } + "minecraft:block_state_property" => ctx.block_pos.is_some_and(|b| { + let mut pred = serde_json::Map::new(); + pred.insert("blocks".into(), v["block"].clone()); + if !v["properties"].is_null() { + pred.insert("state".into(), v["properties"].clone()); + } + block(&Value::Object(pred), b, w) + }), + "minecraft:match_tool" => ctx.tool.is_some_and(|t| item(&v["predicate"], t, w)), + "minecraft:inverted" => !conditions(&v["term"], ctx, w), + "minecraft:all_of" => v["terms"] + .as_array() + .into_iter() + .flatten() + .all(|t| conditions(t, ctx, w)), + "minecraft:any_of" => v["terms"] + .as_array() + .into_iter() + .flatten() + .any(|t| conditions(t, ctx, w)), + _ => false, + } + } + // An inline entity predicate (old-style). + Value::Object(_) => ctx.this.is_some_and(|e| entity(v, e, w, ctx.origin)), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + struct Flat; + impl World for Flat { + fn dimension(&self) -> &str { + "minecraft:overworld" + } + fn biome(&self, _: [i32; 3]) -> String { + "minecraft:plains".into() + } + fn structures(&self, _: [i32; 3]) -> Vec { + vec!["minecraft:village_plains".into()] + } + fn block(&self, _: [i32; 3]) -> (String, BTreeMap) { + ("minecraft:stone".into(), BTreeMap::new()) + } + fn fluid(&self, _: [i32; 3]) -> Option { + None + } + fn can_see_sky(&self, _: [i32; 3]) -> bool { + true + } + fn light(&self, _: [i32; 3]) -> i32 { + 15 + } + fn smokey(&self, _: [i32; 3]) -> bool { + false + } + fn in_tag(&self, _: &str, tag: &str, id: &str) -> bool { + tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone" + } + } + #[test] + fn predicates_match_tags_ranges_and_locations() { + let w = Flat; + let stone = ItemView { + id: "minecraft:cobblestone".into(), + count: 3, + ..Default::default() + }; + assert!(item( + &serde_json::json!({"items": "#minecraft:stone_tool_materials"}), + &stone, + &w + )); + assert!(!item( + &serde_json::json!({"items": "minecraft:dirt"}), + &stone, + &w + )); + assert!(item(&serde_json::json!({"count": {"min": 2}}), &stone, &w)); + let player = EntityView { + kind: "minecraft:player".into(), + position: [0.5, 64.0, 0.5], + ..Default::default() + }; + let cond = serde_json::json!({ + "type": "minecraft:entity_properties", + "entity": "this", + "predicate": {"minecraft:location": {"structures": "minecraft:village_plains"}} + }); + let ctx = Entities { + this: Some(&player), + origin: player.position, + tool: None, + block_pos: None, + }; + assert!(conditions(&cond, &ctx, &w)); + let mut p = Progress::default(); + let a = parse( + "minecraft:t", + &serde_json::json!({"criteria": {"a": {"trigger": "minecraft:tick"}, "b": {"trigger": "minecraft:tick"}}, + "requirements": [["a", "b"]]}), + ) + .unwrap(); + assert!(!p.done(&a)); + p.grant("minecraft:t", "b", "now"); + assert!(p.done(&a)); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d5f11d14..8594e8608 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,5 +1,6 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. +mod advancements; mod armor_stands; mod beacon; mod blockctl; @@ -48,6 +49,7 @@ mod stations; mod stats; mod stats_screen; mod storage; +mod structures; mod titles; mod tnt; mod totem; @@ -617,6 +619,7 @@ struct Game<'a> { combat: combat::CombatTracker, mount: mounts::MountState, stats: stats::Stats, + adv: advancements::AdvState, stats_ui: stats_screen::StatsUi, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1803,8 +1806,9 @@ impl Game<'_> { sounds.pitch * 0.8, ); self.process_level_events()?; - // BlockItem.place: the used statistic. + // BlockItem.place: the used statistic and the placed_block trigger. self.stats.add("used", &stack.item, 1); + self.trigger_block("minecraft:placed_block", target, &stack); self.consume_held(); Ok(()) } @@ -1929,6 +1933,7 @@ impl Game<'_> { 0.5, self.world.random.next_float() * 0.1 + 0.9, ); + self.trigger_item("minecraft:consume_item", &stack); self.consume_held(); } } else { @@ -2369,6 +2374,11 @@ impl Game<'_> { self.stats.custom("deaths", 1); if let Some(kind) = killer { self.stats.add("killed_by", &kind, 1); + let view = horizon_client::advancements::EntityView { + kind, + ..Default::default() + }; + self.trigger_entity("minecraft:entity_killed_player", "entity", &view); } self.stats.reset("custom", "minecraft:time_since_death"); self.stats.reset("custom", "minecraft:time_since_rest"); @@ -2971,6 +2981,7 @@ impl Game<'_> { Screen::Chat => self.draw_chat_screen(&mut batch), Screen::Playing | Screen::Options => {} } + self.draw_toasts(&mut batch); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); @@ -4288,6 +4299,7 @@ impl Game<'_> { self.position_rider(); self.tick_stats(); self.spawn_phantoms(); + self.tick_advancements(); Ok(()) } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. @@ -4708,7 +4720,9 @@ impl Game<'_> { self.streaming = streaming; self.world = world; self.save = save; + let from = self.dim; self.dim = target; + self.trigger_dimension(from, target); self.level.dimension = target.id().to_owned(); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); @@ -5256,6 +5270,7 @@ impl Game<'_> { self.world .set(hit.pos[0], hit.pos[1], hit.pos[2], self.world.air)?; self.audio.play(sound, Some(at(hit.pos)), 1.0, 1.0); + self.trigger_item("minecraft:filled_bucket", &ItemStack::new(filled, 1)); if !self.creative { self.consume_held(); let filled = ItemStack { @@ -6136,6 +6151,7 @@ impl Game<'_> { self.message = Some(("Respawn point set".into(), Instant::now())); self.sleeping = Some((head, 0)); self.stats.custom("sleep_in_bed", 1); + self.trigger_player("minecraft:slept_in_bed"); self.stats.reset("custom", "minecraft:time_since_rest"); } fn tick_sleep(&mut self) { @@ -6414,6 +6430,7 @@ impl Game<'_> { self.save_maps(); self.save_fight(); self.save_stats(); + self.save_advancements(); self.level.selected_slot = self.selected as i32; let mode = self.mode_id(); let level = &mut self.level; @@ -7567,6 +7584,7 @@ pub fn run() -> Result<()> { combat: Default::default(), mount: Default::default(), stats: Default::default(), + adv: Default::default(), stats_ui: Default::default(), }; game.ui.vanilla_root = vanilla_root; diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs new file mode 100644 index 000000000..d5c150a65 --- /dev/null +++ b/crates/horizon-client/src/game/advancements.rs @@ -0,0 +1,587 @@ +//! The player's advancements in the game: criteria triggered from game +//! events (`CriteriaTriggers`), awarding with rewards, the toast and the +//! chat announcement, and `players/advancements/.json`. +use super::{Dim, Game}; +use horizon_client::{ + advancements::{self as adv, EntityView, Frame, ItemView, Progress, Tree}, + hud::HudBatch, + items::ItemStack, + text::{self, Style, Text}, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet, VecDeque}, + sync::Arc, + time::Instant, +}; + +pub(super) struct Toast { + icon: String, + frame: Frame, + title: Text, + shown: Option, +} +#[derive(Default)] +pub(super) struct AdvState { + pub(super) tree: Arc, + pub(super) progress: Progress, + loaded: bool, + pub(super) recipes: BTreeSet, + toasts: VecDeque, + /// The inventory last seen by `inventory_changed`. + last_inventory: u64, +} +/// The game's world for predicates. +struct View<'a, 'g>(&'a Game<'g>); +impl adv::World for View<'_, '_> { + fn dimension(&self) -> &str { + self.0.dim.id() + } + fn biome(&self, p: [i32; 3]) -> String { + self.0 + .world + .chunks + .get(&(p[0] >> 4, p[2] >> 4)) + .map(|c| { + self.0 + .res + .biomes + .get(c.biome(p[0], p[1], p[2])) + .name + .clone() + }) + .unwrap_or_default() + } + fn structures(&self, p: [i32; 3]) -> Vec { + self.0.structures_at(p) + } + fn block(&self, p: [i32; 3]) -> (String, BTreeMap) { + let state = self.0.world.block(p[0], p[1], p[2]); + let name = self.0.res.facts.get(state).name.to_string(); + let props = self + .0 + .res + .assets + .registry + .state(state) + .map(|s| { + s.properties + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }) + .unwrap_or_default(); + (name, props) + } + fn fluid(&self, p: [i32; 3]) -> Option { + match self + .0 + .res + .facts + .get(self.0.world.block(p[0], p[1], p[2])) + .fluid + { + horizon_client::blocks::Fluid::Water => Some("minecraft:water".into()), + horizon_client::blocks::Fluid::Lava => Some("minecraft:lava".into()), + _ => None, + } + } + fn can_see_sky(&self, p: [i32; 3]) -> bool { + (p[1] + 1..p[1] + 200).all(|y| { + !self + .0 + .res + .facts + .get(self.0.world.block(p[0], y, p[2])) + .full_collision + }) + } + fn light(&self, p: [i32; 3]) -> i32 { + let l = self.0.world.light(p[0], p[1], p[2]); + i32::from((l >> 4).max(l & 15)) + } + fn smokey(&self, p: [i32; 3]) -> bool { + (1..=5).any(|d| { + self.0 + .res + .facts + .get(self.0.world.block(p[0], p[1] - d, p[2])) + .name + .ends_with("campfire") + }) + } + fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { + let items = &self.0.res.items; + match registry { + "item" => items.item_tags.get(tag).is_some_and(|t| t.contains(id)), + "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), + "entity_type" => self.0.res.mob_data.entity_has(tag, id), + "worldgen/biome" => self.0.res.mob_data.biome_has(tag, id), + _ => false, + } + } +} +fn now_text() -> String { + // "yyyy-MM-dd HH:mm:ss Z" in UTC. + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) as i64; + let days = secs.div_euclid(86400); + let rem = secs.rem_euclid(86400); + // Civil from days (Howard Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} +pub(super) fn item_view(s: &ItemStack) -> ItemView { + ItemView { + id: s.item.to_string(), + count: s.count, + damage: s.damage, + enchantments: s + .enchantments() + .iter() + .map(|(id, l)| (id.to_string(), *l)) + .collect(), + potion: s.potion().map(str::to_owned), + custom_name: s.custom_name().is_some(), + } +} +impl Game<'_> { + fn adv_path(&self) -> Option { + let uuid = self.level.player_uuid?; + let hex: String = uuid.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + let text = format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ); + Some( + self.world_root + .join("players/advancements") + .join(format!("{text}.json")), + ) + } + pub(super) fn load_advancements(&mut self) { + if self.adv.loaded || self.remote.is_some() { + return; + } + self.adv.loaded = true; + if self.adv.tree.list.is_empty() { + self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data"))); + } + let progress = self + .adv_path() + .and_then(|p| std::fs::read_to_string(p).ok()) + .and_then(|t| serde_json::from_str::(&t).ok()) + .map(|v| Progress::from_json(&v)) + .unwrap_or_default(); + // Unlocked recipes come from the done recipe advancements' rewards. + let tree = self.adv.tree.clone(); + for a in &tree.list { + if progress.done(a) { + self.adv.recipes.extend(a.rewards.recipes.iter().cloned()); + } + } + self.adv.progress = progress; + } + pub(super) fn save_advancements(&self) { + if !self.adv.loaded || self.remote.is_some() { + return; + } + let Some(path) = self.adv_path() else { + return; + }; + let json = self + .adv + .progress + .to_json(&self.adv.tree, horizon_world::DATA_VERSION); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(text) = serde_json::to_string_pretty(&json) { + let _ = std::fs::write(path, text); + } + } + /// The player as predicates see it. + pub(super) fn player_entity(&self) -> EntityView { + let Some(p) = self.player.as_ref() else { + return EntityView::default(); + }; + let mut eq: [Option; 7] = Default::default(); + eq[0] = self.held().map(item_view); + eq[1] = self.offhand.as_ref().map(item_view); + for (i, a) in self.armor.iter().enumerate() { + eq[2 + i] = a.as_ref().map(item_view); + } + let vehicle = self.riding.and_then(|id| { + self.mobs + .iter() + .find(|m| m.id == id) + .map(|m| Box::new(self.mob_entity(m))) + }); + EntityView { + kind: "minecraft:player".into(), + position: [p.position.x, p.position.y, p.position.z], + sneaking: p.pose == horizon_client::pose::Pose::Crouching, + sprinting: p.sprinting, + swimming: p.pose == horizon_client::pose::Pose::Swimming, + flying: p.flying, + on_ground: p.ground.on_ground, + equipment: eq, + vehicle, + effects: self + .potions + .effects + .list + .iter() + .map(|e| (format!("minecraft:{}", e.id), e.amplifier, e.duration)) + .collect(), + gamemode: Some(self.mode.name().to_owned()), + ..Default::default() + } + } + pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView { + 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, + ..Default::default() + } + } + /// `SimpleCriterionTrigger.trigger`: test each open criterion of the + /// trigger and award what it completes. + pub(super) fn trigger(&mut self, name: &str, test: impl Fn(&Value, &dyn adv::World) -> bool) { + if self.remote.is_some() { + return; + } + self.load_advancements(); + let tree = self.adv.tree.clone(); + let Some(list) = tree.by_trigger.get(name) else { + return; + }; + let mut hits = Vec::new(); + { + let view = View(self); + for &(ai, ci) in list { + let a = &tree.list[ai]; + let c = &a.criteria[ci]; + if self.adv.progress.has(&a.id, &c.name) || self.adv.progress.done(a) { + continue; + } + if test(&c.conditions, &view) { + hits.push((ai, ci)); + } + } + } + let date = now_text(); + for (ai, ci) in hits { + let a = &tree.list[ai]; + let was = self.adv.progress.done(a); + self.adv.progress.grant(&a.id, &a.criteria[ci].name, &date); + if !was && self.adv.progress.done(a) { + self.award(ai); + } + } + } + /// `PlayerAdvancements.award` once done: rewards, toast, announcement. + fn award(&mut self, index: usize) { + let tree = self.adv.tree.clone(); + let a = &tree.list[index]; + // AdvancementRewards.grant + if a.rewards.experience > 0 { + self.experience.give(a.rewards.experience); + } + let mut unlocked = Vec::new(); + for r in &a.rewards.recipes { + if self.adv.recipes.insert(r.clone()) { + unlocked.push(r.clone()); + } + } + for table in &a.rewards.loot { + let items = self + .res + .items + .loot_table(table, false, None, &mut self.world.random); + for s in items { + if let Some(rest) = self.give(s) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0; 3], 0); + } + } + } + if let Some(d) = &a.display { + if d.show_toast { + self.adv.toasts.push_back(Toast { + icon: d.icon.clone(), + frame: d.frame, + title: text_of(&d.title), + shown: None, + }); + } + if d.announce && self.ui.rules.bool("show_advancement_messages") { + let (key, color) = match d.frame { + Frame::Task => ("chat.type.advancement.task", text::GREEN), + Frame::Goal => ("chat.type.advancement.goal", text::GREEN), + Frame::Challenge => ("chat.type.advancement.challenge", text::DARK_PURPLE), + }; + let name = Text::literal("[") + .append(text_of(&d.title)) + .append("]") + .with_style(&Style { + color: Some(color), + ..Style::default() + }); + self.system_message(Text::translate( + key, + &[Text::literal(super::chat::PLAYER_NAME), name], + )); + } + } + for r in unlocked { + self.trigger("minecraft:recipe_unlocked", |c, _| { + c["recipe"].as_str().is_none_or(|want| want == r) + }); + } + } + /// `InventoryChangeTrigger`, checked when the inventory changes. + pub(super) fn check_inventory_trigger(&mut self) { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for s in self + .inventory + .iter() + .chain(self.armor.iter()) + .chain(std::iter::once(&self.offhand)) + { + s.as_ref().map(|s| (&s.item, s.count)).hash(&mut h); + } + let key = h.finish(); + if key == self.adv.last_inventory { + return; + } + self.adv.last_inventory = key; + let stacks: Vec = self + .inventory + .iter() + .chain(self.armor.iter()) + .chain(std::iter::once(&self.offhand)) + .flatten() + .map(item_view) + .collect(); + self.trigger("minecraft:inventory_changed", |c, w| { + let mut wanted: Vec<&Value> = c["items"] + .as_array() + .map(|a| a.iter().collect()) + .unwrap_or_default(); + for s in &stacks { + wanted.retain(|p| !adv::item(p, s, w)); + } + wanted.is_empty() + }); + } + /// `PlayerTrigger.LOCATION` every second, and the other per-tick checks. + pub(super) fn tick_advancements(&mut self) { + if self.player.is_none() || self.remote.is_some() { + return; + } + self.check_inventory_trigger(); + if self.ticks.is_multiple_of(20) { + let me = self.player_entity(); + self.trigger("minecraft:location", |c, w| { + let ctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &ctx, w) + }); + } + } + /// A player condition plus one entity (`player`, `entity` keys). + pub(super) fn trigger_entity(&mut self, name: &str, key: &str, target: &EntityView) { + let me = self.player_entity(); + let target = target.clone(); + let key = key.to_owned(); + self.trigger(name, move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let ectx = adv::Entities { + this: Some(&target), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w) + }); + } + /// A player condition plus one item (`item` key). + pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) { + let me = self.player_entity(); + let it = item_view(stack); + self.trigger(name, move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w) + }); + } + /// `ItemUsedOnLocationTrigger` (placed_block, item_used_on_block). + pub(super) fn trigger_block(&mut self, name: &str, pos: [i32; 3], stack: &ItemStack) { + let me = self.player_entity(); + let it = item_view(stack); + self.trigger(name, move |c, w| { + let ctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: Some(&it), + block_pos: Some(pos), + }; + adv::conditions(&c["location"], &ctx, w) + }); + } + /// A trigger with only the player condition (slept_in_bed, started_riding). + pub(super) fn trigger_player(&mut self, name: &str) { + let me = self.player_entity(); + self.trigger(name, move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + }); + } + /// `BredAnimalsTrigger`. + pub(super) fn trigger_bred( + &mut self, + parent: &EntityView, + partner: &EntityView, + child: Option<&EntityView>, + ) { + let me = self.player_entity(); + let (parent, partner, child) = (parent.clone(), partner.clone(), child.cloned()); + self.trigger("minecraft:bred_animals", move |c, w| { + let ctx = |e: &EntityView| { + adv::Entities { + this: Some(e), + origin: me.position, + tool: None, + block_pos: None, + } + .this + .map(|_| ()) + }; + let _ = ctx; + let test = |key: &str, e: Option<&EntityView>| { + c[key].is_null() + || e.is_some_and(|e| { + adv::conditions( + &c[key], + &adv::Entities { + this: Some(e), + origin: me.position, + tool: None, + block_pos: None, + }, + w, + ) + }) + }; + // matches(parent, partner, child) or (partner, parent, child). + (test("parent", Some(&parent)) && test("partner", Some(&partner)) + || test("parent", Some(&partner)) && test("partner", Some(&parent))) + && test("child", child.as_ref()) + }); + } + /// `ChangeDimensionTrigger`. + pub(super) fn trigger_dimension(&mut self, from: Dim, to: Dim) { + let (from, to) = (from.id().to_owned(), to.id().to_owned()); + self.trigger("minecraft:changed_dimension", move |c, _| { + c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to) + }); + } + /// `ToastManager` with the `AdvancementToast`. + pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) { + let Some(t) = self.adv.toasts.front_mut() else { + return; + }; + let shown = *t.shown.get_or_insert_with(Instant::now); + let ms = shown.elapsed().as_millis() as f32; + // AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out. + if ms > 5600.0 { + self.adv.toasts.pop_front(); + return; + } + let slide = if ms < 600.0 { + ms / 600.0 + } else if ms > 5000.0 { + 1.0 - (ms - 5000.0) / 600.0 + } else { + 1.0 + }; + let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone()); + if frame == Frame::Challenge && ms < 50.0 { + self.audio + .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); + } + let atlas = &self.res.atlas; + let x = batch.width - 160.0 * slide; + batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); + let (key, color) = match frame { + Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), + Frame::Goal => ("advancements.toast.goal", 0xFF00_FFFF), + Frame::Challenge => ("advancements.toast.challenge", 0xFFFF_88FF), + }; + batch.text_styled( + atlas, + &Text::translate(key, &[]), + x + 30.0, + 7.0, + color, + false, + ); + batch.text_styled(atlas, &title, x + 30.0, 18.0, u32::MAX, false); + self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0); + } +} +/// A text component from advancement JSON (`translate` or `text`). +pub(super) fn text_of(v: &Value) -> Text { + if let Some(key) = v["translate"].as_str() { + Text::translate(key, &[]) + } else if let Some(s) = v["text"].as_str() { + Text::literal(s) + } else if let Some(s) = v.as_str() { + Text::literal(s) + } else { + Text::empty() + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index aeb0ecace..2d2ac53c4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -567,6 +567,8 @@ impl Game<'_> { if by_player { self.stats.add("killed", &m.kind.id, 1); self.stats.custom("mob_kills", 1); + let view = self.mob_entity(m); + self.trigger_entity("minecraft:player_killed_entity", "entity", &view); } let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; @@ -892,6 +894,28 @@ impl Game<'_> { // Animal.finalizeSpawnChildFromBreeding: the player who fed them. if p.extra.love_player { self.stats.custom("animals_bred", 1); + let parent = self.mob_entity(&p); + let partner_view = self + .mobs + .iter() + .find(|m| m.id == partner) + .map(|m| self.mob_entity(m)) + .unwrap_or_else(|| parent.clone()); + let mut child = parent.clone(); + child.baby = true; + if matches!( + ( + p.species(), + self.mobs + .iter() + .find(|m| m.id == partner) + .map(|m| m.species()) + ), + (Species::Horse, Some(Species::Donkey)) | (Species::Donkey, Some(Species::Horse)) + ) { + child.kind = "minecraft:mule".into(); + } + self.trigger_bred(&parent, &partner_view, Some(&child)); } if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) { q.extra.age = 6000; @@ -1595,6 +1619,10 @@ impl Game<'_> { // TamableAnimal.spawnTamingParticles. let kind = if tamed { "heart" } else { "smoke" }; self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + if tamed { + let view = self.mob_entity(&self.mobs[index]); + self.trigger_entity("minecraft:tame_animal", "entity", &view); + } let m = &self.mobs[index]; self.world.modified.insert(( m.position.x.floor() as i32 >> 4, @@ -1663,6 +1691,10 @@ impl Game<'_> { } let kind = if tamed { "heart" } else { "smoke" }; self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + if tamed { + let view = self.mob_entity(&self.mobs[index]); + self.trigger_entity("minecraft:tame_animal", "entity", &view); + } let m = &self.mobs[index]; self.world.modified.insert(( m.position.x.floor() as i32 >> 4, diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index ef12f91ee..649c97728 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -61,6 +61,7 @@ impl Game<'_> { return false; } self.riding = Some(m.id); + self.trigger_player("minecraft:started_riding"); true } /// `FoodOnAStickItem.use` while riding: boost the mount, wear the stick. @@ -145,6 +146,7 @@ impl Game<'_> { self.riding = Some(m.id); self.mount.jump_ticks = 0; self.mount.jump_scale = 0.0; + self.trigger_player("minecraft:started_riding"); true } /// `AbstractHorse.handleEating`. @@ -330,6 +332,14 @@ impl Game<'_> { match *e { MobEvent::Tamed { mob } => { let owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + if let Some(view) = self + .mobs + .iter() + .find(|m| m.id == mob) + .map(|m| self.mob_entity(m)) + { + self.trigger_entity("minecraft:tame_animal", "entity", &view); + } if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { m.extra.owner = owner; m.persistent = true; diff --git a/crates/horizon-client/src/game/structures.rs b/crates/horizon-client/src/game/structures.rs new file mode 100644 index 000000000..a11a662ca --- /dev/null +++ b/crates/horizon-client/src/game/structures.rs @@ -0,0 +1,9 @@ +//! Which structures contain a position (`StructureManager.getStructureWithPieceAt`). +use super::Game; + +impl Game<'_> { + /// The structures with a piece containing `pos`. + pub(super) fn structures_at(&self, _pos: [i32; 3]) -> Vec { + Vec::new() + } +} diff --git a/crates/horizon-client/src/game/totem.rs b/crates/horizon-client/src/game/totem.rs index c3e8fbf42..257c65db2 100644 --- a/crates/horizon-client/src/game/totem.rs +++ b/crates/horizon-client/src/game/totem.rs @@ -60,6 +60,10 @@ impl Game<'_> { } self.audio .play("minecraft:item.totem.use", Some(at), 1.0, 1.0); + self.trigger_item( + "minecraft:used_totem", + &horizon_client::items::ItemStack::new("minecraft:totem_of_undying", 1), + ); self.particles.tracking_emitter_for( ParticleOptions::simple(ParticleType::TotemOfUndying), at, diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 3c86f669c..4d9ef4fbc 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -1,6 +1,7 @@ //! Horizon native client: resources, world streaming, rendering and the //! bindings between the validated simulation pieces and the game loop. #![forbid(unsafe_code)] +pub mod advancements; pub mod ambience; pub mod animate_tick; pub mod assets; diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 5dde4f59b..490b207b0 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -46,6 +46,8 @@ pub struct MobData { pub animations: HashMap, /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. pub biome_tags: HashMap>, + /// Entity type tags (`data/*/tags/entity_type`). + pub entity_tags: HashMap>, } impl MobData { pub fn load(root: &Path, facts: &BlockFacts) -> Self { @@ -63,8 +65,14 @@ impl MobData { _ => Self::fallback(facts), }; data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(); + data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); data } + pub fn entity_has(&self, tag: &str, entity: &str) -> bool { + self.entity_tags + .get(tag) + .is_some_and(|s| s.contains(entity)) + } pub fn biome_has(&self, tag: &str, biome: &str) -> bool { self.biome_tags.get(tag).is_some_and(|s| s.contains(biome)) } @@ -104,6 +112,7 @@ impl MobData { placements, animations, biome_tags: HashMap::new(), + entity_tags: HashMap::new(), } } /// Without the export, approximate path types from the gameplay facts. @@ -156,6 +165,7 @@ impl MobData { placements: HashMap::new(), animations: HashMap::new(), biome_tags: HashMap::new(), + entity_tags: HashMap::new(), } } pub fn state(&self, id: horizon_world::registry::BlockStateId) -> StateData { diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 553f8365e..434a9f339 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -32,6 +32,7 @@ pub const YELLOW: u32 = 0xFFFF55; pub const GOLD: u32 = 0xFFAA00; pub const WHITE: u32 = 0xFFFFFF; pub const LIGHT_PURPLE: u32 = 0xFF55FF; +pub const DARK_PURPLE: u32 = 0xAA00AA; pub fn named_color(name: &str) -> Option { COLORS.iter().find(|c| c.1 == name).map(|c| c.2)