diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 3b2335ab5..8f0ad3b98 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -23,5 +23,9 @@ cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" +[features] +# Records the call sites of mob random draws (`mob_ai_probe` traces). +rng-trace = ["horizon-core/rng-trace"] + [lints] workspace = true diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/block_entity_anim_fixture.rs new file mode 100644 index 000000000..3347a8104 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_anim_fixture.rs @@ -0,0 +1,455 @@ +//! Headless transport for the block-entity animation parity gate: replays each +//! scripted case (block, neighbourhood, entities, block events, game times) +//! through `horizon_client::block_entity_anim` and prints the same lines as +//! `VanillaBlockEntityAnimOracle`: the block entity's fields, the level calls +//! its tick made and the render state the renderer derives from `BlockAnim`. +#![forbid(unsafe_code)] +use horizon_client::{ + assets::Assets, + block_entity_anim::{ + Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS, + PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index, + }, + block_entity_render::BlockEntityRenderer, + blocks::{BlockFacts, Fluid}, + items::Items, +}; +use horizon_core::random::LegacyRandom; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{ + collections::HashMap, + fmt::Write as _, + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn f(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} +fn bx(b: [f64; 6]) -> String { + b.map(d).join(" ") +} + +fn find_state(registry: &BlockRegistry, spec: &str) -> Option { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let wanted: Vec<(&str, &str)> = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .collect(); + let default = registry.state(registry.default_state(name)?)?.clone(); + (0..registry.len() as u32).find(|&id| { + registry.state(BlockStateId(id)).is_some_and(|s| { + s.name == name + && s.properties.iter().all(|(k, v)| { + wanted + .iter() + .find(|(wk, _)| wk == k) + .map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v) + }) + }) + }) +} + +fn prop<'a>(spec: &'a str, key: &str) -> Option<&'a str> { + let props = spec.split_once('[')?.1.trim_end_matches(']'); + props + .split(',') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v) +} + +fn offset(key: &str) -> [i32; 3] { + let mut it = key.split(',').map(|v| v.parse::().unwrap_or(0)); + [ + it.next().unwrap_or(0), + it.next().unwrap_or(0), + it.next().unwrap_or(0), + ] +} + +fn mob(e: &Value) -> BellEntity { + let p = |i: usize| e["pos"][i].as_f64().unwrap_or(0.0); + BellEntity { + position: [p(0), p(1), p(2)], + alive: e["alive"].as_bool().unwrap_or(true) && !e["removed"].as_bool().unwrap_or(false), + raider: e["raider"].as_bool().unwrap_or(false), + } +} + +fn lid_text(l: Option<&ChestLid>) -> String { + l.map_or("-".to_owned(), |l| { + format!("{} {} {}", l.should_be_open, f(l.openness), f(l.o_openness)) + }) +} + +/// The case's players: feet positions and whether each is a spectator. +fn players(v: &Value) -> Vec<([f64; 3], bool)> { + v.as_array() + .into_iter() + .flatten() + .map(|p| { + let c = |i: usize| p["pos"][i].as_f64().unwrap_or(0.0); + ( + [c(0), c(1), c(2)], + p["spectator"].as_bool().unwrap_or(false), + ) + }) + .collect() +} + +fn status(s: ShulkerStatus) -> &'static str { + match s { + ShulkerStatus::Closed => "CLOSED", + ShulkerStatus::Opening => "OPENING", + ShulkerStatus::Opened => "OPENED", + ShulkerStatus::Closing => "CLOSING", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [root, inputs, output] = args.as_slice() else { + return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); + }; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; + let tags = Items::tags_only(root)?; + let frames = tags + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let case: Value = serde_json::from_str(line)?; + writeln!(out, "case {}", case["name"].as_str().unwrap_or_default())?; + let block = case["block"].as_str().unwrap_or_default().to_owned(); + let int = |v: &Value| v.as_i64().unwrap_or(0) as i32; + let pos = [ + int(&case["pos"][0]), + int(&case["pos"][1]), + int(&case["pos"][2]), + ]; + // The neighbourhood as block states (conduits). + let mut blocks: HashMap<[i32; 3], String> = HashMap::new(); + blocks.insert(pos, block.clone()); + let place = |blocks: &mut HashMap<[i32; 3], String>, set: &Value| { + for (k, v) in set.as_object().into_iter().flatten() { + let o = offset(k); + blocks.insert( + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], + v.as_str().unwrap_or_default().to_owned(), + ); + } + }; + place(&mut blocks, &case["world"]); + let entities: Vec = case["entities"] + .as_array() + .into_iter() + .flatten() + .map(mob) + .collect(); + let target = case.get("target").map(|t| { + let e = mob(t); + ConduitTarget { + position: e.position, + eye_y: e.position[1] + f64::from(t["eye"].as_f64().unwrap_or(0.0) as f32), + width: t["width"].as_f64().unwrap_or(0.0) as f32, + height: t["height"].as_f64().unwrap_or(0.0) as f32, + } + }); + let mut random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + let name = block.split('[').next().unwrap_or_default().to_owned(); + let mut anims = BlockEntityAnims::default(); + let partner = case["partner"].as_str().map(|k| { + let o = offset(k); + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]] + }); + let mut gamers = players(&case["players"]); + if name == "minecraft:enchanting_table" { + anims.book_random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + } + let facing = prop(&block, "facing") + .and_then(direction_index) + .unwrap_or(1); + let mut text = String::new(); + for step in case["steps"].as_array().into_iter().flatten() { + let time = step["time"].as_i64().unwrap_or(0); + let partial = step["partial"].as_f64().unwrap_or(0.0) as f32; + let mut log = String::new(); + place(&mut blocks, &step["set"]); + let event = step["event"].as_array().map(|e| (int(&e[0]), int(&e[1]))); + text.clear(); + if step.get("players").is_some() { + gamers = players(&step["players"]); + } + if name.ends_with("chest") { + let lid = anims.chests.entry(pos).or_default(); + if let Some((a, b)) = event { + let handled = lid.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + if let Some(other) = partner { + let lid = anims.chests.entry(other).or_default(); + if let Some(e) = step["partnerEvent"].as_array() { + let handled = lid.trigger_event(int(&e[0]), int(&e[1])); + let _ = write!(log, " partner event {handled}"); + } + } + // lidAnimateTick: this chest, then the other half. + if let Some(l) = anims.chests.get_mut(&pos) { + l.tick(); + } + if let Some(l) = partner.and_then(|p| anims.chests.get_mut(&p)) { + l.tick(); + } + let state_at = |p: [i32; 3]| { + find_state( + registry, + blocks.get(&p).map_or("minecraft:air", String::as_str), + ) + .unwrap_or(0) + }; + let (open, _) = renderer + .chest_openness_of(pos, state_at(pos), &state_at, &|p| anims.lid(p, partial)); + let _ = write!( + text, + "{} partner {} render {} {}", + lid_text(anims.chests.get(&pos)), + partner.map_or("none".to_owned(), |p| lid_text(anims.chests.get(&p))), + f(open), + f(chest_lid_x_rot(open)) + ); + } else if name == "minecraft:enchanting_table" { + let feet: Vec<[f64; 3]> = gamers + .iter() + .filter(|(_, spectator)| !spectator) + .map(|(p, _)| *p) + .collect(); + let BlockEntityAnims { + books, book_random, .. + } = &mut anims; + books.entry(pos).or_default().tick(pos, &feet, book_random); + let b = anims.books[&pos]; + let r = anims + .block_anim(pos, time, partial, Default::default()) + .book + .render(partial); + let _ = write!( + text, + "{} {} {} {} {} {} {} {} {} {} render {} {} {} {} book {} {} {}", + b.time, + f(b.flip), + f(b.o_flip), + f(b.flip_t), + f(b.flip_a), + f(b.open), + f(b.o_open), + f(b.rot), + f(b.o_rot), + f(b.t_rot), + f(r.flip), + f(r.open), + f(r.time), + f(r.y_rot), + f(r.openness), + f(r.page_flip1), + f(r.page_flip2) + ); + } else if name.ends_with("shulker_box") { + let s = anims.shulkers.entry(pos).or_insert_with(Shulker::default); + if let Some((a, b)) = event { + let handled = s.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + let tick = s.tick(pos, facing); + for _ in 0..tick.neighbor_updates { + log.push_str(" neighbors"); + } + if let Some(b) = tick.push { + let _ = write!(log, " push {}", bx(b)); + } + let (count, st) = (s.open_count, s.status); + let a = anims.block_anim(pos, time, partial, Default::default()); + // ShulkerBoxRenderer: getProgress(partial). + let (progress, old) = a.shulker; + let render = old + partial * (progress - old); + let s = &anims.shulkers[&pos]; + let _ = write!( + text, + "{} {} {} {} render {}", + status(st), + count, + f(s.progress), + f(s.progress_old), + f(render) + ); + } else if name == "minecraft:bell" { + let b = anims.bells.entry(pos).or_insert_with(Bell::default); + if let Some((e0, e1)) = event { + let handled = b.trigger_event(e0, e1, time, || { + let inflated = [ + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + f64::from(pos[0]) + 1.0 + 48.0, + f64::from(pos[1]) + 1.0 + 48.0, + f64::from(pos[2]) + 1.0 + 48.0, + ]; + let _ = write!(log, " gather {}", bx(inflated)); + (0..entities.len() as u64) + .filter(|&i| { + let p = entities[i as usize].position; + (0..3).all(|a| p[a] >= inflated[a] && p[a] < inflated[a + 3]) + }) + .collect() + }); + let _ = write!(log, " event {handled}"); + } + if !step["noTick"].as_bool().unwrap_or(false) { + let tick = b.tick(pos, |h| entities.get(h as usize).copied()); + if tick.resonate { + log.push_str(" sound minecraft:block.bell.resonate"); + } + if let Some((particles, _)) = tick.ended { + for (p, color) in particles { + let _ = write!( + log, + " particle minecraft:entity_effect {color} {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(0.0), + d(0.0), + d(0.0) + ); + } + } + } + let b = &anims.bells[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let dir = |d: Option<&str>| d.map_or("null".to_owned(), str::to_owned); + let _ = write!( + text, + "{} {} {} {} {} {} render {} {}", + b.ticks, + b.shaking, + dir(b.click_direction.map(|d| DIRECTIONS[usize::from(d)])), + b.resonating, + b.resonation_ticks, + b.last_ring_timestamp, + f(a.bell_ticks as f32 + partial), + dir(a.bell_shake) + ); + } else if name == "minecraft:conduit" { + let c = anims.conduits.entry(pos).or_insert_with(Conduit::default); + let state_of = |p: [i32; 3]| -> Option { + find_state( + registry, + blocks.get(&p).map_or("minecraft:air", String::as_str), + ) + }; + let is_water = |p: [i32; 3]| { + state_of(p).is_some_and(|s| facts.get(BlockStateId(s)).fluid == Fluid::Water) + }; + let is_frame = |p: [i32; 3]| { + let spec = blocks.get(&p).map_or("minecraft:air", String::as_str); + frames.contains(spec.split('[').next().unwrap_or_default()) + }; + let particles = c.client_tick(pos, time, is_water, is_frame, target, &mut random); + for (p, v) in particles { + let _ = write!( + log, + " particle minecraft:nautilus {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(v[0]), + d(v[1]), + d(v[2]) + ); + } + let c = &anims.conduits[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // ConduitRenderer.extractRenderState as block_entity_render derives it. + let (ticks, active, hunting, raw) = a.conduit; + let rotation = (raw + if active { partial } else { 0.0 }) * -0.0375; + let _ = write!( + text, + "{} {} {} {} {} render {} {} {} {} {}", + c.tick_count, + c.is_active, + c.is_hunting, + f(c.active_rotation), + c.effect_blocks.len(), + active, + f(rotation), + f(ticks as f32 + partial), + ticks / 66 % 3, + hunting + ); + } else if name.ends_with("_head") || name.ends_with("_skull") { + let now = step["state"].as_str().unwrap_or(&block); + let s = anims.skulls.entry(pos).or_insert_with(Skull::default); + s.tick(prop(now, "powered") == Some("true")); + let s = anims.skulls[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // block_entity_render: count + partial while animating. + let (animating, count) = a.skull; + let render = count as f32 + if animating { partial } else { 0.0 }; + let _ = write!( + text, + "{} {} render {}", + s.animating, + s.tick_count, + f(render) + ); + } else if name == "minecraft:decorated_pot" { + let w = anims.pots.entry(pos).or_insert_with(PotWobble::default); + if let Some((e0, e1)) = event { + let handled = w.trigger_event(e0, e1, time); + let _ = write!(log, " event {handled}"); + } + let w = anims.pots[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let (style, progress) = match a.wobble { + Some((true, p)) => ("POSITIVE", p), + Some((false, p)) => ("null", p), + None => ("null", 0.0), + }; + let _ = write!( + text, + "{} {} render {} {}", + w.started_at, + match w.style { + Some(WobbleStyle::Positive) => "POSITIVE", + Some(WobbleStyle::Negative) => "NEGATIVE", + None => "null", + }, + f(progress), + style + ); + } else { + text = format!("unsupported {block}"); + } + writeln!(out, "{text} |{log}")?; + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index f29cebc0c..aa4a14a58 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -7,7 +7,10 @@ use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_client::{ assets::Assets, banner::{self, Banners}, - block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall}, + block_entity_anim::EnchantingBook, + block_entity_render::{ + BlockAnim, BlockEntityRenderer, END_GATEWAY_LAYER, END_PORTAL_LAYER, Scene, TextCall, + }, chunk::{Chunk, Light}, hud::{HudAtlas, Rect}, signs::{DYE_TEXT, SignData, SignText}, @@ -113,7 +116,7 @@ fn main() -> Result<()> { }; let assets = Assets::load(root)?; let registry = assets.registry; - let mut renderer = BlockEntityRenderer::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; let atlas = HudAtlas::build(root)?; let banners = Banners::load(root); let (sprites, names, grid) = fake_sprites(textures)?; @@ -196,13 +199,41 @@ fn main() -> Result<()> { world.chunks.insert((cx, cz), Arc::new(chunk)); } } - if let Some(book) = case.get("book") { - renderer.set_book( - pos, - int(&book["time"]), - ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])), - ); + // Neighbour blocks the case sets (End gateway faces). + for (direction, spec) in case["neighbours"].as_object().into_iter().flatten() { + let d = match direction.as_str() { + "down" => [0, -1, 0], + "up" => [0, 1, 0], + "north" => [0, 0, -1], + "south" => [0, 0, 1], + "west" => [-1, 0, 0], + _ => [1, 0, 0], + }; + let neighbour = find_state(registry, spec.as_str().unwrap_or_default()) + .ok_or("unknown neighbour state")?; + world.set( + pos[0] + d[0], + pos[1] + d[1], + pos[2] + d[2], + BlockStateId(neighbour), + )?; } + let book = case + .get("book") + .map_or_else(EnchantingBook::default, |book| { + let [flip, o_flip, open, o_open, rot, o_rot] = + ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])); + EnchantingBook { + time: int(&book["time"]), + flip, + o_flip, + open, + o_open, + rot, + o_rot, + ..EnchantingBook::default() + } + }); let sign = case.get("sign").map(|s| { let mut data = SignData { hanging: block.contains("hanging"), @@ -246,6 +277,16 @@ fn main() -> Result<()> { wobble: case["wobble"] .as_array() .map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))), + book, + gateway: ( + case["gateway"]["age"].as_i64().unwrap_or(0), + int(&case["gateway"]["cooldown"]), + ), + }; + // The case's level height (minimum y, height): the End's by default. + let max_y = match case["level"].as_array() { + Some(l) => int(&l[0]) + int(&l[1]) - 1, + None => 255, }; let open = float(&case["open"]); let near = case["sign"]["near"].as_bool().unwrap_or(false); @@ -279,7 +320,8 @@ fn main() -> Result<()> { anim: &|_| anim.clone(), texts: Some(&texts), partial: float(&case["partial"]), - game_time: 0, + game_time: case["gameTime"].as_i64().unwrap_or(0), + max_y, world: &world, sprites: &sprites, nether: false, @@ -293,6 +335,26 @@ fn main() -> Result<()> { let quads: Vec = verts .chunks(4) .map(|q| { + // Custom geometry: the End portal shader's position-only cube (its + // render type samples end_sky first) and End gateway beams. + if q[0].layer == END_PORTAL_LAYER || q[0].layer == END_GATEWAY_LAYER { + let v: Vec = q + .iter() + .map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]])) + .collect(); + return json!({"texture": "environment/end_sky", "v": v, "color": q[0].color, + "light": q[0].light, "custom": true}); + } + if q[0].layer == 6 { + let texture = "entity/end_portal/end_gateway_beam"; + let u0 = sprites.get(texture).map_or(0.0, |r| r.u0); + let v: Vec = q + .iter() + .map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0] - u0, v.uv[1]])) + .collect(); + return json!({"texture": texture, "v": v, "color": q[0].color, + "light": q[0].light, "custom": true}); + } let (cu, cv) = ((q[0].uv[0] / 2.0).floor(), (q[0].uv[1] / 2.0).floor()); let texture = names .get(cu as usize + cv as usize * grid) diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index 1b6905bef..39d738b7f 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -61,6 +61,7 @@ fn parser_id(ty: &ArgType) -> String { _ => "minecraft:template_rotation".into(), }, ArgType::HexColor => "minecraft:hex_color".into(), + ArgType::ResourceSelector(_) => "minecraft:resource_selector".into(), ArgType::Uuid => "minecraft:uuid".into(), ArgType::GameProfile => "minecraft:game_profile".into(), ArgType::Style => "minecraft:style".into(), @@ -120,7 +121,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { } children.insert(child.name().to_owned(), v); } - let mut v = json!({"children": children}); + let order: Vec<&str> = n.children.iter().map(|&c| d.nodes[c].name()).collect(); + let mut v = json!({"children": children, "order": order}); if n.command.is_some() { v["executable"] = json!(true); } diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/hud_fixture.rs index 3b3285baf..dcb594088 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/hud_fixture.rs @@ -1,11 +1,14 @@ -//! Headless transport for the HUD parity gate: replays each player state -//! through `horizon_client::hud_layout` (crosshair, hotbar, health, mount -//! hearts, experience bar and level) and writes the draw calls in vanilla's -//! GuiGraphicsExtractor terms. +//! Headless transport for the HUD parity gate: replays each case through +//! `horizon_client::hud_layout` and writes the draw calls in vanilla's +//! GuiGraphicsExtractor terms. Case kinds: `decorations` (crosshair, +//! hotbar, health, mount hearts, experience bar and level) and the +//! overlays handled in `kinds`. #![forbid(unsafe_code)] use horizon_client::{ hud::{HudAtlas, HudBatch}, - hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs}, + hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs, IDENTITY, Pose}, + lang, + text::Text, }; use serde_json::{Value, json}; use std::{ @@ -14,6 +17,8 @@ use std::{ path::PathBuf, }; type Result = std::result::Result>; +#[path = "hud_fixture/kinds.rs"] +mod kinds; fn main() -> Result<()> { let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); @@ -21,123 +26,245 @@ fn main() -> Result<()> { return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into()); }; let atlas = HudAtlas::build(root)?; + lang::set(lang::Language::load(&[root], lang::DEFAULT)); let mut out = BufWriter::new(fs::File::create(output)?); for line in fs::read_to_string(inputs)? .lines() .filter(|l| !l.is_empty()) { let c: Value = serde_json::from_str(line)?; - let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32; - let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32; - let (w, h) = (int("width", 0), int("height", 0)); - let mode = c["gameMode"].as_str().unwrap_or("survival"); - let survival = mode == "survival" || mode == "adventure"; - let indicator = c["attackIndicator"].as_str().unwrap_or("OFF"); - let partial = float("partial", 0.0); - let effects: Vec<&str> = c["effects"] - .as_array() - .into_iter() - .flatten() - .filter_map(Value::as_str) - .collect(); - let has = |e: &str| effects.contains(&e); - let mut draws = Vec::new(); - // Spectators only see it over a spectatable target (none here). - if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" { - let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0)); - draws.extend(hud_layout::crosshair(w, h, attack, false)); - } - if mode != "spectator" { - let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial); - let slots: [Option; 9] = std::array::from_fn(|i| pop(&c["slots"][i])); - let inputs = HotbarInputs { - selected: int("selected", 0), - right_handed: c["rightHanded"].as_bool().unwrap_or(true), - offhand: !c["offhand"].is_null(), - slots, - offhand_pop: pop(&c["offhand"]).unwrap_or(0.0), - attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)), - }; - draws.extend(hud_layout::hotbar(w, h, &inputs)); - } - let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() { - hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0)) - } else { - 0 + // State the case reads back besides the draws (e.g. `scopeScale`). + let mut state = serde_json::Map::new(); + let draws = match c["kind"].as_str().unwrap_or("decorations") { + "decorations" => decorations(&c, &atlas), + kind => kinds::run(kind, &c, &atlas, &mut state), }; - if survival { - let millis = 1_000_000_000i64; - let mut hud = HealthHud { - last_health: int("lastHealth", 0), - display_health: int("displayHealth", 0), - last_health_time: millis - i64::from(int("lastHealthAgo", 0)), - health_blink_time: i64::from(int("healthBlinkTime", 0)), - }; - let kind = if has("minecraft:poison") { - HeartKind::Poisoned - } else if has("minecraft:wither") { - HeartKind::Withered - } else if c["frozen"].as_bool().unwrap_or(false) { - HeartKind::Frozen - } else { - HeartKind::Normal - }; - let inputs = HealthInputs { - tick: int("tick", 0), - millis, - health: float("health", 20.0), - max_health: float("maxHealth", 20.0), - absorption: float("absorption", 0.0), - armor: int("armor", 0), - food: int("food", 20), - saturation: float("saturation", 5.0), - kind, - regeneration: has("minecraft:regeneration"), - hunger: has("minecraft:hunger"), - hardcore: c["hardcore"].as_bool().unwrap_or(false), - damage_cooldown: int("damageCooldown", 0) > 0, - air: int("air", 300), - max_air: int("maxAir", 300), - under_water: c["underWater"].as_bool().unwrap_or(false), - vehicle_hearts, - }; - draws.extend(hud.layout(&inputs, w, h)); - } - if vehicle_hearts > 0 { - draws.extend(hud_layout::vehicle_health( - w, - h, - vehicle_hearts, - float("vehicleHealth", 0.0), - )); - } - let width = |s: &str| HudBatch::text_width(&atlas, s) as i32; - let level = if survival { int("xpLevel", 0) } else { 0 }; - draws.extend(hud_layout::experience( - w, - h, - float("xpProgress", 0.0), - level, - c["experienceBar"].as_bool().unwrap_or(false), - &width, - )); - let draws: Vec = draws - .iter() - .map(|d| match d { - GuiDraw::Sprite { sprite, x, y, w, h, region } => { - json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region}) - } - GuiDraw::Text { text, x, y, color, shadow } => { - json!({"type": "text", "text": text, "x": x, "y": y, "color": *color as i32, "shadow": shadow}) - } - GuiDraw::Item { slot, x, y, seed, scale, pivot } => { - // translate(pivot) * scale * translate(-pivot) as a 3x2 matrix. - let m = [scale[0], 0.0, 0.0, scale[1], pivot[0] - pivot[0] * scale[0], pivot[1] - pivot[1] * scale[1]]; - json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m}) - } - }) - .collect(); - writeln!(out, "{}", json!({ "draws": draws }))?; + state.insert("draws".into(), json!(encode(&draws))); + writeln!(out, "{}", Value::Object(state))?; } Ok(()) } + +/// Style runs of styled text: `[text, rgb|null, bold, italic]` per run of +/// equally styled characters, or none for plain text. +fn runs(t: &Text) -> Option { + let mut out: Vec<(String, Option, bool, bool)> = Vec::new(); + let mut styled = false; + for (ch, s) in t.chars() { + let key = (s.color, s.is_bold(), s.is_italic()); + styled |= key != (None, false, false); + match out.last_mut() { + Some(last) if (last.1, last.2, last.3) == key => last.0.push(ch), + _ => out.push((ch.to_string(), key.0, key.1, key.2)), + } + } + styled.then(|| { + json!( + out.into_iter() + .map(|r| json!([r.0, r.1, r.2, r.3])) + .collect::>() + ) + }) +} + +fn encode(draws: &[GuiDraw]) -> Vec { + let mut stack: Vec = vec![IDENTITY]; + let mut out = Vec::new(); + for d in draws { + let pose = *stack.last().unwrap(); + let mut v = match d { + GuiDraw::Push(ops) => { + let mut m = pose; + for op in ops { + hud_layout::pose_apply(&mut m, *op); + } + stack.push(m); + continue; + } + GuiDraw::Pop => { + stack.pop(); + continue; + } + GuiDraw::Sprite { + sprite, + x, + y, + w, + h, + region, + color, + } => { + json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32}) + } + GuiDraw::AtlasSprite { + sprite, + x, + y, + w, + h, + color, + } => { + json!({"type": "atlas", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "color": *color as i32}) + } + GuiDraw::Blit { + texture, + blend, + x, + y, + w, + h, + uv, + src, + tex, + color, + } => json!({ + "type": "blit", "texture": format!("textures/{texture}.png"), "pipeline": blend.pipeline(), + "x": x, "y": y, "w": w, "h": h, "uv": uv, "src": src, "tex": tex, "color": *color as i32}), + GuiDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => { + json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": *color as i32}) + } + GuiDraw::Text { + text, + x, + y, + color, + shadow, + } => { + let mut v = json!({"type": "text", "text": text.plain(), "x": x, "y": y, "color": *color as i32, "shadow": shadow}); + if let Some(r) = runs(text) { + v["runs"] = r; + } + v + } + GuiDraw::Item { + slot, + x, + y, + seed, + scale, + pivot, + } => { + // translate(pivot) * scale * translate(-pivot) as a 3x2 matrix. + let m = [ + scale[0], + 0.0, + 0.0, + scale[1], + pivot[0] - pivot[0] * scale[0], + pivot[1] - pivot[1] * scale[1], + ]; + out.push(json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m})); + continue; + } + }; + if pose != IDENTITY { + v["matrix"] = json!(pose); + } + out.push(v); + } + out +} + +fn decorations(c: &Value, atlas: &HudAtlas) -> Vec { + let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32; + let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32; + let (w, h) = (int("width", 0), int("height", 0)); + let mode = c["gameMode"].as_str().unwrap_or("survival"); + let survival = mode == "survival" || mode == "adventure"; + let indicator = c["attackIndicator"].as_str().unwrap_or("OFF"); + let partial = float("partial", 0.0); + let effects: Vec<&str> = c["effects"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let has = |e: &str| effects.contains(&e); + let mut draws = Vec::new(); + // Spectators only see it over a spectatable target (none here). + if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" { + let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0)); + draws.extend(hud_layout::crosshair(w, h, attack, false)); + } + if mode != "spectator" { + let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial); + let slots: [Option; 9] = std::array::from_fn(|i| pop(&c["slots"][i])); + let inputs = HotbarInputs { + selected: int("selected", 0), + right_handed: c["rightHanded"].as_bool().unwrap_or(true), + offhand: !c["offhand"].is_null(), + slots, + offhand_pop: pop(&c["offhand"]).unwrap_or(0.0), + attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)), + }; + draws.extend(hud_layout::hotbar(w, h, &inputs)); + } + let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() { + hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0)) + } else { + 0 + }; + if survival { + let millis = 1_000_000_000i64; + let mut hud = HealthHud { + last_health: int("lastHealth", 0), + display_health: int("displayHealth", 0), + last_health_time: millis - i64::from(int("lastHealthAgo", 0)), + health_blink_time: i64::from(int("healthBlinkTime", 0)), + }; + let kind = if has("minecraft:poison") { + HeartKind::Poisoned + } else if has("minecraft:wither") { + HeartKind::Withered + } else if c["frozen"].as_bool().unwrap_or(false) { + HeartKind::Frozen + } else { + HeartKind::Normal + }; + let inputs = HealthInputs { + tick: int("tick", 0), + millis, + health: float("health", 20.0), + max_health: float("maxHealth", 20.0), + absorption: float("absorption", 0.0), + armor: int("armor", 0), + food: int("food", 20), + saturation: float("saturation", 5.0), + kind, + regeneration: has("minecraft:regeneration"), + hunger: has("minecraft:hunger"), + hardcore: c["hardcore"].as_bool().unwrap_or(false), + damage_cooldown: int("damageCooldown", 0) > 0, + air: int("air", 300), + max_air: int("maxAir", 300), + under_water: c["underWater"].as_bool().unwrap_or(false), + vehicle_hearts, + }; + draws.extend(hud.layout(&inputs, w, h)); + } + if vehicle_hearts > 0 { + draws.extend(hud_layout::vehicle_health( + w, + h, + vehicle_hearts, + float("vehicleHealth", 0.0), + )); + } + let width = |s: &str| HudBatch::text_width(atlas, s) as i32; + let level = if survival { int("xpLevel", 0) } else { 0 }; + draws.extend(hud_layout::experience( + w, + h, + float("xpProgress", 0.0), + level, + c["experienceBar"].as_bool().unwrap_or(false), + &width, + )); + draws +} diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs new file mode 100644 index 000000000..550da026b --- /dev/null +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -0,0 +1,326 @@ +//! The overlay case kinds of the HUD parity fixture. +use horizon_client::{ + brewing, + chat::{Chat, ChatOptions}, + component, + hud::HudAtlas, + hud_layout::{self, GuiDraw}, + hud_overlays::{ + self, BossBar, CameraOverlays, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight, + }, + scoreboard::{NumberFormat, RenderType, Scoreboard}, + text::{self, Text}, +}; +use serde_json::Value; + +fn int(c: &Value, k: &str, d: i64) -> i32 { + c[k].as_i64().unwrap_or(d) as i32 +} +fn float(c: &Value, k: &str, d: f64) -> f32 { + c[k].as_f64().unwrap_or(d) as f32 +} +/// A text component in its JSON form. +fn comp(v: &Value) -> Text { + component::to_text(v, &mut |s| Text::literal(s)) +} +/// `Options.getBackgroundColor(0.0F)` from the case's text background options. +fn background(c: &Value) -> u32 { + hud_layout::background_color( + c["chatOnly"].as_bool().unwrap_or(true), + c["textOpacity"].as_f64().unwrap_or(0.5), + 0.0, + ) +} + +pub fn run( + kind: &str, + c: &Value, + atlas: &HudAtlas, + state: &mut serde_json::Map, +) -> Vec { + let (w, h) = (int(c, "width", 0), int(c, "height", 0)); + match kind { + "effects" => effects(c, w), + "title" => title(c, w, h, atlas), + "selected" => selected(c, w, h, atlas), + "boss" => boss(c, w, h, atlas), + "jump" => hud_overlays::jump_bar(w, h, int(c, "cooldown", 0), float(c, "jumpScale", 0.0)), + "sidebar" => sidebar(c, w, h, atlas), + "decor" => decor(c, atlas), + "overlays" => overlays(c, w, h, state), + "chat" => chat(c, h, atlas), + _ => Vec::new(), + } +} + +fn effects(c: &Value, w: i32) -> Vec { + let icons: Vec = c["active"] + .as_array() + .into_iter() + .flatten() + .map(|e| { + let id = e["id"] + .as_str() + .unwrap_or("") + .trim_start_matches("minecraft:"); + let def = brewing::effect(id).expect("effect"); + EffectIcon { + id: id.to_owned(), + beneficial: def.category == brewing::Category::Beneficial, + color: def.color as i32, + ambient: e["ambient"].as_bool().unwrap_or(false), + duration: e["duration"].as_i64().unwrap_or(0) as i32, + show_icon: e["icon"].as_bool().unwrap_or(true), + } + }) + .collect(); + hud_overlays::effects(w, c["demo"].as_bool().unwrap_or(false), &icons) +} + +/// Replays `Hud.setTitle` / `setSubtitle` / `setTimes` / `clearTitles` / +/// `resetTitleTimes` / `setOverlayMessage` and ticks, then extracts the +/// action bar and the title. +fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut t = Titles::default(); + for op in c["ops"].as_array().into_iter().flatten() { + let n = |i: usize| op[i].as_i64().unwrap_or(0) as i32; + match op[0].as_str().unwrap_or("") { + "title" => t.set_title(comp(&op[1])), + "subtitle" => t.set_subtitle(comp(&op[1])), + "times" => t.set_times(n(1), n(2), n(3)), + "clear" => t.clear(), + "reset" => t.reset_times(), + "overlay" => t.set_overlay(comp(&op[1]), op[2].as_bool().unwrap_or(false)), + "tick" => { + for _ in 0..n(1) { + t.tick(); + } + } + other => panic!("unknown title op {other}"), + } + } + let partial = float(c, "partial", 0.0); + let bg = background(c); + let mut out = t.overlay_message(w, h, partial, &atlas.font, bg); + out.extend(t.title(w, h, partial, &atlas.font, bg)); + out +} + +/// Ticks `toolHighlightTimer` through the selected stacks, then extracts the name. +fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut highlight = ToolHighlight::default(); + let time = c["displayTime"].as_f64().unwrap_or(1.0); + for step in c["steps"].as_array().into_iter().flatten() { + let held = (!step.is_null()).then(|| { + let custom = &step["custom"]; + HeldName { + item: step["item"].as_str().unwrap_or("").to_owned(), + hover_name: if custom.is_null() { + Text::translate(step["key"].as_str().unwrap_or(""), &[]) + } else { + comp(custom) + }, + rarity_color: text::named_color(step["rarity"].as_str().unwrap_or("white")) + .unwrap_or(0xFFFFFF), + custom_name: !custom.is_null(), + } + }); + highlight.tick(held, time); + } + let mode = c["gameMode"].as_str().unwrap_or("survival"); + let can_hurt = mode == "survival" || mode == "adventure"; + highlight.draw(w, h, can_hurt, &atlas.font, background(c)) +} + +fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let bars: Vec = c["bars"] + .as_array() + .into_iter() + .flatten() + .map(|b| BossBar { + name: comp(&b["name"]), + progress: b["progress"].as_f64().unwrap_or(0.0) as f32, + color: b["color"].as_u64().unwrap_or(0) as usize, + overlay: b["overlay"].as_u64().unwrap_or(0) as usize, + }) + .collect(); + hud_overlays::boss_overlay(w, h, &bars, &atlas.font) +} + +/// A `NumberFormat` from the case: null, `{type: blank}`, `{type: fixed, +/// value}` or `{type: styled, style}`. +fn number_format(v: &Value) -> Option { + match v["type"].as_str()? { + "blank" => Some(NumberFormat::Blank), + "fixed" => Some(NumberFormat::Fixed(v["value"].clone())), + "styled" => Some(NumberFormat::Styled(v["style"].clone())), + other => panic!("unknown number format {other}"), + } +} + +fn sidebar(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut board = Scoreboard::default(); + let o = &c["objective"]; + board.add_objective( + "sidebar", + "dummy", + o["display"].clone(), + RenderType::Integer, + false, + number_format(&o["format"]), + ); + for s in c["scores"].as_array().into_iter().flatten() { + let owner = s["owner"].as_str().unwrap_or(""); + let score = board.score_mut(owner, "sidebar"); + score.value = s["value"].as_i64().unwrap_or(0) as i32; + score.display = (!s["display"].is_null()).then(|| s["display"].clone()); + score.number_format = number_format(&s["format"]); + } + for t in c["teams"].as_array().into_iter().flatten() { + let name = t["name"].as_str().unwrap_or(""); + let team = board.add_team(name); + team.prefix = t["prefix"].clone(); + team.suffix = t["suffix"].clone(); + team.color = t["color"].as_str().map(str::to_owned); + for m in t["members"].as_array().into_iter().flatten() { + board.add_to_team(m.as_str().unwrap_or(""), name); + } + } + let opacity = c["textOpacity"].as_f64().unwrap_or(0.5); + let chat_only = c["chatOnly"].as_bool().unwrap_or(true); + let objective = board.objective("sidebar").expect("objective").clone(); + hud_overlays::sidebar( + w, + h, + &board, + &objective, + &atlas.font, + hud_layout::background_color(chat_only, opacity, 0.3), + hud_layout::background_color(chat_only, opacity, 0.4), + ) +} + +/// `itemDecorations` for a stack with a count, damage and an item cooldown +/// `elapsed` ticks into `duration` (ItemCooldowns.getCooldownPercent). +fn decor(c: &Value, atlas: &HudAtlas) -> Vec { + let count = int(c, "count", 1); + if count <= 0 { + return Vec::new(); + } + let cd = &c["cooldown"]; + let cooldown = if cd.is_null() { + 0.0 + } else { + let (duration, elapsed) = (int(cd, "duration", 0), int(cd, "elapsed", 0)); + if duration <= elapsed { + 0.0 // ItemCooldowns.tick dropped it + } else { + let remaining = duration as f32 - (elapsed as f32 + float(c, "partial", 0.0)); + (remaining / duration as f32).clamp(0.0, 1.0) + } + }; + let max_damage = if c["unbreakable"].as_bool().unwrap_or(false) { + 0 + } else { + int(c, "maxDamage", 0) + }; + let d = ItemDecorations { + count: count as u32, + count_text: c["countText"].as_str().map(str::to_owned), + bar: hud_overlays::damage_bar(int(c, "damage", 0), max_damage), + cooldown, + }; + hud_overlays::item_decorations(int(c, "x", 0), int(c, "y", 0), &d, &atlas.font) +} + +/// `Hud.extractCameraOverlays` then `extractSleepOverlay`; the border is +/// static, so only its warning blocks matter. +fn overlays(c: &Value, w: i32, h: i32, state: &mut serde_json::Map) -> Vec { + let partial = float(c, "partial", 0.0); + let warning = match &c["border"] { + Value::Null => 0.0, + b => { + // WorldBorder.getDistanceToBorder with the static extent's clamped box. + let max = 29_999_984.0; + let half = b["size"].as_f64().unwrap_or(0.0) / 2.0; + let (cx, cz) = ( + b["centerX"].as_f64().unwrap_or(0.0), + b["centerZ"].as_f64().unwrap_or(0.0), + ); + let (min_x, max_x) = ((cx - half).clamp(-max, max), (cx + half).clamp(-max, max)); + let (min_z, max_z) = ((cz - half).clamp(-max, max), (cz + half).clamp(-max, max)); + let (x, z) = ( + f64::from(float(c, "camX", 0.0)), + f64::from(float(c, "camZ", 0.0)), + ); + let distance = (x - min_x).min(max_x - x).min(z - min_z).min(max_z - z); + hud_overlays::border_warning( + distance as f32, + int(b, "warningBlocks", 5), + int(b, "warningTime", 15), + 0.0, + 0.0, + ) + } + }; + let ticks_frozen = int(c, "ticksFrozen", 0); + let inputs = CameraOverlays { + vignette: c["vignette"] + .as_bool() + .unwrap_or(false) + .then(|| (float(c, "vignetteBrightness", 1.0), warning)), + first_person: c["firstPerson"].as_bool().unwrap_or(false), + scoping: c["scoping"].as_bool().unwrap_or(false), + game_time_delta: partial, + equipment: match c["head"].as_str() { + Some("carved_pumpkin") => vec!["misc/pumpkinblur".to_owned()], + _ => Vec::new(), + }, + ticks_frozen, + percent_frozen: ticks_frozen.min(140) as f32 / 140.0, + partial, + portal: [ + c["portal"][0].as_f64().unwrap_or(0.0) as f32, + c["portal"][1].as_f64().unwrap_or(0.0) as f32, + ], + nausea: float(c, "nausea", 0.0), + screen_effect_scale: float(c, "screenEffectScale", 1.0), + }; + let mut scope = float(c, "scopeScale", 0.5); + let mut out = hud_overlays::camera_overlays(w, h, &inputs, &mut scope); + out.extend(hud_overlays::sleep_overlay(w, h, int(c, "sleepTimer", 0))); + state.insert("scopeScale".into(), serde_json::json!(scope)); + out +} + +/// Messages added at their ticks (`Hud.tickCount`), then the chat in +/// background mode at tick `now`. +fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { + let option = |k: &str| c[k].as_f64().unwrap_or(0.0); + let mut chat = Chat::default(); + chat.options = ChatOptions { + opacity: option("chatOpacity"), + background_opacity: option("textOpacity"), + scale: option("chatScale"), + width: option("chatWidth"), + height_focused: option("chatHeightFocused"), + height_unfocused: option("chatHeightUnfocused"), + line_spacing: option("chatLineSpacing"), + }; + for m in c["messages"].as_array().into_iter().flatten() { + // GuiMessageTag indicator colours: systemSinglePlayer and chatError. + let indicator = match m["tag"].as_str() { + Some("system") => Some(13684944), + Some("error") => Some(16733525), + _ => None, + }; + chat.add( + atlas, + comp(&m["text"]), + indicator, + m["at"].as_u64().unwrap_or(0), + false, + ); + } + chat.layout(h, c["now"].as_u64().unwrap_or(0), false) +} diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index ab6cce246..4c5178fae 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -142,6 +142,8 @@ fn goal_name(m: &Mob, name: &str) -> String { let vanilla = match name { "Float" => "FloatGoal", "Stroll" => "WaterAvoidingRandomStrollGoal", + "RandomStroll" => "RandomStrollGoal", + "RandomSwimming" => "RandomSwimmingGoal", "LookAtPlayer" => "LookAtPlayerGoal", "RandomLookAround" => "RandomLookAroundGoal", "HurtByTarget" => "HurtByTargetGoal", @@ -171,6 +173,12 @@ fn goal_name(m: &Mob, name: &str) -> String { "TryFindWater" => "TryFindWaterGoal", "RangedAttack" => "RangedAttackGoal", "MoveTowardsTarget" => "MoveTowardsTargetGoal", + "DrownedGoToWater" => "DrownedGoToWaterGoal", + "TakeBlock" => "EndermanTakeBlockGoal", + "LeaveBlock" => "EndermanLeaveBlockGoal", + "FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt", + "LookForPlayer" => "EndermanLookForPlayerGoal", + "HealRaiders" => "NearestHealableRaiderTargetGoal", other => return other.to_owned(), }; vanilla.to_owned() @@ -221,13 +229,43 @@ fn seen(m: &Mob) -> Seen { hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: horizon_client::mobs::raider::has_active_raid(m), player_rep: 0, + pushable: m.pushable(), + category: m.category(), + potential_job: horizon_client::mobs::villager_brain::potential_job_site(m), + meeting: (m.species() == Species::Villager) + .then_some(m.extra.meeting) + .flatten(), + profession: m.extra.variant2, + xp: horizon_client::mobs::villager::xp(m), + } +} + +/// Whether an event hurts the scenario's player (survival, normal difficulty, +/// no armour, made hurtable again every tick by the oracle). +fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { + let Some(p) = player.filter(|p| !p.creative) else { + return false; + }; + match e { + MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, + // ServerExplosion.hurtEntities: within twice the radius every hit does damage. + MobEvent::Explode(at, radius) => { + let d = Vec3::new(at[0], at[1], at[2]) + .distance_squared(p.position) + .sqrt(); + let r = 2.0 * f64::from(*radius); + d / r <= 1.0 && d != 0.0 + } + _ => false, } } fn print(out: &mut String, t: i32, i: usize, m: &Mob) { let _ = write!(out, "{t} {i}"); if m.removed { - let _ = writeln!(out, " removed DISCARDED"); + // Entity.RemovalReason: the end of the death animation, else a discard. + let reason = if m.alive() { "DISCARDED" } else { "KILLED" }; + let _ = writeln!(out, " removed {reason}"); return; } let p = m.position; @@ -316,7 +354,11 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { f(m.ai.speed), u8::from(m.ai.jumping) ); - let _ = writeln!(out, "\trng {:x}", m.random.state()); + let _ = write!(out, "\trng {:x}", m.random.state()); + if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) { + let _ = write!(out, "\tact {acts}\tmem {mem}"); + } + out.push('\n'); } fn main() -> horizon_client::Result<()> { @@ -429,6 +471,16 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + if m.species() == Species::Villager { + // The oracle seeds the random after the brain is built, then + // delays the sensors again and seeds the gates' shuffles. + horizon_client::mobs::villager_brain::init( + &mut m, + world.game_time, + s.time, + spec.seed, + ); + } mobs.push(m); } let player = s.player.map(|p| { @@ -485,16 +537,38 @@ fn main() -> horizon_client::Result<()> { difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), end: false, world_seed: 0, + // FlatLevelSource.getSeaLevel. + sea_level: -63, }; let mut events = Vec::new(); - for m in &mut mobs { + #[allow(unused_mut)] // filled only with the rng-trace feature + let mut traces: Vec = Vec::new(); + let mut pushes = Vec::new(); + for (i, m) in mobs.iter_mut().enumerate() { if m.removed { continue; } - if !m.tick(&w, &mut scratch, &mut events) { + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + let from = events.len(); + #[cfg(feature = "rng-trace")] + horizon_core::random::trace::set(true); + let alive = m.tick(&w, &mut scratch, &mut events); + #[cfg(feature = "rng-trace")] + { + horizon_core::random::trace::set(false); + for line in horizon_core::random::trace::take() { + traces.push(format!("{t} trace {i} {line}")); + } + } + horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + let _ = i; + if !alive { m.removed = true; } } + for m in &mut mobs { + horizon_client::mobs::apply_mob_pushes(m, &mut pushes); + } for (i, m) in mobs.iter().enumerate() { print(&mut out, t, i, m); } @@ -508,8 +582,18 @@ fn main() -> horizon_client::Result<()> { ); } else if let MobEvent::SoundId(name, _, volume, pitch) = e { let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch)); + } else if player_hurt(player.as_ref(), e) { + // The oracle's survival player, healed and made hurtable every tick, + // takes the damage (LivingEntity.playHurtSound). + let _ = writeln!( + out, + "{t} sound minecraft:entity.player.hurt 3f800000 3f800000" + ); } } + for line in traces { + let _ = writeln!(out, "{line}"); + } } } fs::write(&args[2], out)?; diff --git a/crates/horizon-client/src/attack_strength.rs b/crates/horizon-client/src/attack_strength.rs new file mode 100644 index 000000000..f8d8d5c34 --- /dev/null +++ b/crates/horizon-client/src/attack_strength.rs @@ -0,0 +1,106 @@ +//! The player's attack strength (`Player.attackStrengthTicker`, +//! `itemSwapTicker`, `getAttackStrengthScale`, `getCurrentItemAttackStrengthDelay`): +//! the charge the attack indicator shows and attacks scale their damage by. + +/// `Attributes.ATTACK_SPEED` base value. +pub const BASE_ATTACK_SPEED: f64 = 4.0; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AttackStrength { + /// `LivingEntity.attackStrengthTicker`. + pub ticker: i32, + /// `LivingEntity.itemSwapTicker`. + pub swap_ticker: i32, + /// `Player.lastItemInMainHand`: the stack as last compared. + last_item: Option, +} +/// What `ItemStack.matches` / `isSameItem` compare of the main-hand stack: +/// its item id and the rest of the stack (count and components) as a key. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HeldStack { + pub item: String, + pub rest: String, +} +/// `Player.getCurrentItemAttackStrengthDelay` for an ATTACK_SPEED value. +pub fn delay(attack_speed: f64) -> f32 { + (1.0 / attack_speed * 20.0) as f32 +} +impl AttackStrength { + /// The attack-strength part of `Player.tick`: both tickers advance, and a + /// main-hand change to a different item resets them + /// (`!ItemStack.matches` and `!ItemStack.isSameItem`). + pub fn tick(&mut self, main_hand: Option) { + self.ticker += 1; + self.swap_ticker += 1; + if self.last_item != main_hand { + let same_item = match (&self.last_item, &main_hand) { + (Some(a), Some(b)) => a.item == b.item, + (None, None) => true, + _ => false, + }; + if !same_item { + self.reset(); + } + self.last_item = main_hand; + } + } + /// `resetAttackStrengthTicker`: swinging at nothing, attacking or + /// stopping a block break. + pub fn reset(&mut self) { + self.ticker = 0; + self.swap_ticker = 0; + } + /// `resetOnlyAttackStrengthTicker` (`Player.onAttack`). + pub fn reset_attack(&mut self) { + self.ticker = 0; + } + /// `getAttackStrengthScale(a)` with the ATTACK_SPEED attribute value. + pub fn scale(&self, a: f32, attack_speed: f64) -> f32 { + ((self.ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0) + } + /// `getItemSwapScale(a)`. + pub fn swap_scale(&self, a: f32, attack_speed: f64) -> f32 { + ((self.swap_ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn held(item: &str, rest: &str) -> Option { + Some(HeldStack { + item: item.into(), + rest: rest.into(), + }) + } + #[test] + fn charges_over_the_attack_delay() { + let mut s = AttackStrength::default(); + // A sword's 1.6 attacks per second: 12.5 ticks to full strength. + assert_eq!(delay(1.6), 12.5); + for _ in 0..6 { + s.tick(None); + } + assert_eq!(s.scale(0.25, 1.6), 6.25 / 12.5); + for _ in 0..10 { + s.tick(None); + } + assert_eq!(s.scale(0.0, 1.6), 1.0); + } + #[test] + fn switching_items_resets_but_restacking_does_not() { + let mut s = AttackStrength::default(); + s.tick(held("minecraft:stone", "64")); + assert_eq!(s.ticker, 0, "picking up an item resets"); + s.tick(held("minecraft:stone", "63")); + assert_eq!( + s.ticker, 1, + "the same item with another count keeps charging" + ); + s.tick(held("minecraft:diamond_sword", "")); + assert_eq!((s.ticker, s.swap_ticker), (0, 0)); + s.tick(held("minecraft:diamond_sword", "")); + s.reset_attack(); + assert_eq!((s.ticker, s.swap_ticker), (0, 1)); + } +} diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs new file mode 100644 index 000000000..70a57cc64 --- /dev/null +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -0,0 +1,905 @@ +//! Client-ticked block-entity animation state, as vanilla's block entities +//! keep it: `ChestLidController` (chests, trapped and copper chests, ender +//! chests), `EnchantingTableBlockEntity.bookAnimationTick`, +//! `ShulkerBoxBlockEntity` (open count, animation status, progress), +//! `BellBlockEntity` (ring ticks, shake direction, resonation), +//! `ConduitBlockEntity.clientTick` (tick count, shape check, rotation, +//! hunting, nautilus particles), `SkullBlockEntity.animation` (powered dragon +//! and piglin heads) and `DecoratedPotBlockEntity` wobbles. +//! +//! [`BlockEntityAnims`] holds the state per position and turns it into the +//! renderer's [`BlockAnim`]. Its tick methods take what the level answers +//! (blocks, entities, game time) as closures, so the parity fixture can drive +//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). +use crate::block_entity_render::BlockAnim; +use horizon_core::{ + geometry::trig::{self, Mth}, + random::{LegacyRandom, RandomSource}, +}; +use std::collections::HashMap; + +/// `Direction` names by `get3DDataValue`. +pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +fn step(direction: u8) -> [i32; 3] { + match direction { + 0 => [0, -1, 0], + 1 => [0, 1, 0], + 2 => [0, 0, -1], + 3 => [0, 0, 1], + 4 => [-1, 0, 0], + _ => [1, 0, 0], + } +} + +/// `Direction.from3DDataValue`: `BY_3D_DATA[Mth.abs(data % 6)]`. +pub fn from_3d_data_value(data: i32) -> u8 { + (data % 6).unsigned_abs() as u8 +} + +/// The 3D data value of a direction name. +pub fn direction_index(name: &str) -> Option { + DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8) +} + +/// `ChestLidController`, shared by `ChestBlockEntity` (chests, trapped and +/// copper chests) and `EnderChestBlockEntity`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ChestLid { + pub should_be_open: bool, + pub openness: f32, + pub o_openness: f32, +} + +impl ChestLid { + /// `triggerEvent(1, openCount)`: the lid opens while anyone has it open. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 == 1 { + self.should_be_open = b1 > 0; + true + } else { + false + } + } + /// `tickLid` (the client ticker `lidAnimateTick`). + pub fn tick(&mut self) { + self.o_openness = self.openness; + if !self.should_be_open && self.openness > 0.0 { + self.openness = (self.openness - 0.1).max(0.0); + } else if self.should_be_open && self.openness < 1.0 { + self.openness = (self.openness + 0.1).min(1.0); + } + } + /// `getOpenness(a)`: `Mth.lerp(a, oOpenness, openness)`. + pub fn get_openness(&self, a: f32) -> f32 { + self.o_openness + a * (self.openness - self.o_openness) + } +} + +/// `ChestBlock.opennessCombiner`: a double chest opens as far as its more +/// open half (`Math.max(first, second)`, first being the `right` half). +pub fn combined_openness(first: f32, second: Option) -> f32 { + match second { + Some(second) => java_max(first, second), + None => first, + } +} + +/// `Math.max(float, float)`. +fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() { + a + } else if a == 0.0 && b == 0.0 && a.to_bits() != b.to_bits() { + 0.0 + } else if a >= b { + a + } else { + b + } +} + +/// `ChestRenderer.submit` and `ChestModel.setupAnim`: the lid and lock +/// `xRot` for a render-state openness. +pub fn chest_lid_x_rot(open: f32) -> f32 { + let open = 1.0 - open; + let open = 1.0 - open * open * open; + -(open * std::f32::consts::FRAC_PI_2) +} + +/// `EnchantingTableBlockEntity` book fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct EnchantingBook { + pub time: i32, + pub flip: f32, + pub o_flip: f32, + pub flip_t: f32, + pub flip_a: f32, + pub open: f32, + pub o_open: f32, + pub rot: f32, + pub o_rot: f32, + pub t_rot: f32, +} + +/// The `while (a >= PI) a -= 2PI; while (a < -PI) a += 2PI` loops. +fn wrap_pi(mut a: f32) -> f32 { + use std::f32::consts::PI; + while a >= PI { + a -= 2.0 * PI; + } + while a < -PI { + a += 2.0 * PI; + } + a +} + +/// `Mth.floor(float)`. +fn mth_floor(v: f32) -> i32 { + let i = v as i32; + if v < i as f32 { i - 1 } else { i } +} + +/// `Mth.frac(float)`. +pub fn mth_frac(v: f32) -> f32 { + v - mth_floor(v) as f32 +} + +/// `EnchantTableRenderState` (`EnchantTableRenderer.extractRenderState`) and +/// the `BookModel.State` its `submit` builds. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BookRender { + pub flip: f32, + pub open: f32, + pub time: f32, + pub y_rot: f32, + /// `BookModel.State.forAnimation`: openness, pageFlip1, pageFlip2. + pub openness: f32, + pub page_flip1: f32, + pub page_flip2: f32, +} + +impl EnchantingBook { + /// `bookAnimationTick`. `players` are the feet positions of the level's + /// non-spectator players (`getNearestPlayer(centre, 3.0, false)`); + /// `random` is the block entity class's shared static `RANDOM`. + pub fn tick(&mut self, pos: [i32; 3], players: &[[f64; 3]], random: &mut impl RandomSource) { + self.o_open = self.open; + self.o_rot = self.rot; + let c = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + let mut best = -1.0; + let mut nearest = None; + for p in players { + let (dx, dy, dz) = (p[0] - c[0], p[1] - c[1], p[2] - c[2]); + let dist = dx * dx + dy * dy + dz * dz; + if dist < 9.0 && (best == -1.0 || dist < best) { + best = dist; + nearest = Some(*p); + } + } + if let Some(p) = nearest { + let xd = p[0] - c[0]; + let zd = p[2] - c[2]; + self.t_rot = trig::atan2(zd, xd) as f32; + self.open += 0.1; + if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { + let old = self.flip_t; + loop { + let a = random.next_int_bound(4).unwrap_or(0); + let b = random.next_int_bound(4).unwrap_or(0); + self.flip_t += (a - b) as f32; + if old != self.flip_t { + break; + } + } + } + } else { + self.t_rot += 0.02; + self.open -= 0.1; + } + self.rot = wrap_pi(self.rot); + self.t_rot = wrap_pi(self.t_rot); + let dir = wrap_pi(self.t_rot - self.rot); + self.rot += dir * 0.4; + self.open = self.open.clamp(0.0, 1.0); + self.time += 1; + self.o_flip = self.flip; + let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); + self.flip_a += (diff - self.flip_a) * 0.9; + self.flip += self.flip_a; + } + /// `EnchantTableRenderer.extractRenderState` and the book state of its + /// `submit`. + pub fn render(&self, a: f32) -> BookRender { + let flip = self.o_flip + a * (self.flip - self.o_flip); + let open = self.o_open + a * (self.open - self.o_open); + let time = self.time as f32 + a; + let y_rot = self.o_rot + wrap_pi(self.rot - self.o_rot) * a; + let ff1 = mth_frac(flip + 0.25) * 1.6 - 0.3; + let ff2 = mth_frac(flip + 0.75) * 1.6 - 0.3; + BookRender { + flip, + open, + time, + y_rot, + openness: ((time * 0.02).msin() * 0.1 + 1.25) * open, + page_flip1: ff1.clamp(0.0, 1.0), + page_flip2: ff2.clamp(0.0, 1.0), + } + } +} + +/// `ShulkerBoxBlockEntity.AnimationStatus`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ShulkerStatus { + #[default] + Closed, + Opening, + Opened, + Closing, +} + +/// `ShulkerBoxBlockEntity` lid state. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Shulker { + pub open_count: i32, + pub status: ShulkerStatus, + pub progress: f32, + pub progress_old: f32, +} + +/// Side effects of one [`Shulker::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShulkerTick { + /// `doNeighborUpdates` calls (shape and neighbour updates around the box). + pub neighbor_updates: u32, + /// `moveCollidedEntities`: the swept lid box (min x, y, z, max x, y, z); + /// entities in it move out along the facing. + pub push: Option<[f64; 6]>, +} + +/// `Shulker.getProgressDeltaAabb(size, direction, from, to, position)`. +pub fn progress_delta_aabb( + size: f32, + direction: u8, + from: f32, + to: f32, + position: [f64; 3], +) -> [f64; 6] { + let size_d = f64::from(size); + let mut b = [ + -size_d * 0.5, + 0.0, + -size_d * 0.5, + size_d * 0.5, + size_d, + size_d * 0.5, + ]; + let max = f64::from(from.max(to)); + let min = f64::from(from.min(to)); + let s = step(direction); + for axis in 0..3 { + // expandTowards + let a = f64::from(s[axis]) * max * size_d; + if a < 0.0 { + b[axis] += a; + } else if a > 0.0 { + b[axis + 3] += a; + } + } + for axis in 0..3 { + // contract + let a = -f64::from(s[axis]) * (1.0 + min) * size_d; + if a < 0.0 { + b[axis] -= a; + } else if a > 0.0 { + b[axis + 3] -= a; + } + } + // new AABB keeps min <= max; then move to the position. + let mut out = [0.0; 6]; + for axis in 0..3 { + out[axis] = b[axis].min(b[axis + 3]) + position[axis]; + out[axis + 3] = b[axis].max(b[axis + 3]) + position[axis]; + } + out +} + +impl Shulker { + /// `triggerEvent(1, openCount)`. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 != 1 { + return false; + } + self.open_count = b1; + if b1 == 0 { + self.status = ShulkerStatus::Closing; + } + if b1 == 1 { + self.status = ShulkerStatus::Opening; + } + true + } + /// `startOpen`/`stopOpen` for a non-spectator user: the new open count to + /// send as block event 1, and whether this was the first opener (open) or + /// the last closer (close), which play the sound and game event. + pub fn start_open(&mut self) -> (i32, bool) { + if self.open_count < 0 { + self.open_count = 0; + } + self.open_count += 1; + (self.open_count, self.open_count == 1) + } + pub fn stop_open(&mut self) -> (i32, bool) { + self.open_count -= 1; + (self.open_count, self.open_count <= 0) + } + /// `updateAnimation` (`ShulkerBoxBlockEntity.tick`); `facing` is the + /// block's facing as a 3D data value. + pub fn tick(&mut self, pos: [i32; 3], facing: u8) -> ShulkerTick { + let mut out = ShulkerTick::default(); + self.progress_old = self.progress; + match self.status { + ShulkerStatus::Closed => self.progress = 0.0, + ShulkerStatus::Opening => { + self.progress += 0.1; + if self.progress_old == 0.0 { + out.neighbor_updates += 1; + } + if self.progress >= 1.0 { + self.status = ShulkerStatus::Opened; + self.progress = 1.0; + out.neighbor_updates += 1; + } + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + out.push = Some(progress_delta_aabb( + 1.0, + facing, + self.progress_old, + self.progress, + bottom, + )); + } + ShulkerStatus::Opened => self.progress = 1.0, + ShulkerStatus::Closing => { + self.progress -= 0.1; + if self.progress_old == 1.0 { + out.neighbor_updates += 1; + } + if self.progress <= 0.0 { + self.status = ShulkerStatus::Closed; + self.progress = 0.0; + out.neighbor_updates += 1; + } + } + } + out + } + /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. + pub fn get_progress(&self, a: f32) -> f32 { + self.progress_old + a * (self.progress - self.progress_old) + } + /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room + /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). + pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let mut b = progress_delta_aabb(1.0, facing, 0.0, 0.5, bottom); + for axis in 0..3 { + b[axis] += 1.0e-6; + b[axis + 3] -= 1.0e-6; + } + b + } +} + +/// What the bell's tick asks about an entity it gathered when rung. +#[derive(Clone, Copy, Debug)] +pub struct BellEntity { + pub position: [f64; 3], + /// `isAlive() && !isRemoved()`. + pub alive: bool, + /// In `EntityTypeTags.RAIDERS`. + pub raider: bool, +} + +/// `BellBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Bell { + pub ticks: i32, + pub shaking: bool, + /// `clickDirection` as a 3D data value. + pub click_direction: Option, + pub last_ring_timestamp: i64, + /// `nearbyEntities`: the living entities around the bell when it was last + /// gathered, as caller-defined handles. + pub nearby: Option>, + pub resonating: bool, + pub resonation_ticks: i32, +} + +/// Side effects of one [`Bell::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BellTick { + /// Resonation started: `BELL_RESONATE` (played by the server). + pub resonate: bool, + /// Resonation ended (`ResonationEndAction`): the client's + /// `showBellParticles` entity-effect particles (position and colour) and + /// the server's `makeRaidersGlow` targets. + pub ended: Option<(Vec<([f64; 3], i32)>, Vec)>, +} + +fn closer_to_center_than(pos: [i32; 3], p: [f64; 3], distance: f64) -> bool { + let dx = f64::from(pos[0]) + 0.5 - p[0]; + let dy = f64::from(pos[1]) + 0.5 - p[1]; + let dz = f64::from(pos[2]) + 0.5 - p[2]; + dx * dx + dy * dy + dz * dz < distance * distance +} + +impl Bell { + /// `triggerEvent(1, direction)`. `gather` lists the living entities whose + /// position is inside the bell's block box inflated by 48 + /// (`updateEntities`, refreshed at most every 60 ticks). + pub fn trigger_event( + &mut self, + b0: i32, + b1: i32, + game_time: i64, + gather: impl FnOnce() -> Vec, + ) -> bool { + if b0 != 1 { + return false; + } + if game_time > self.last_ring_timestamp + 60 || self.nearby.is_none() { + self.last_ring_timestamp = game_time; + self.nearby = Some(gather()); + } + self.resonation_ticks = 0; + self.click_direction = Some(from_3d_data_value(b1)); + self.ticks = 0; + self.shaking = true; + true + } + /// `BellBlockEntity.tick` with the client's resonation end action. + pub fn tick(&mut self, pos: [i32; 3], entity: impl Fn(u64) -> Option) -> BellTick { + let mut out = BellTick::default(); + if self.shaking { + self.ticks += 1; + } + if self.ticks >= 50 { + self.shaking = false; + self.ticks = 0; + } + let nearby = self.nearby.clone().unwrap_or_default(); + let raider_in = |e: &BellEntity, distance: f64| { + e.alive && closer_to_center_than(pos, e.position, distance) && e.raider + }; + if self.ticks >= 5 + && self.resonation_ticks == 0 + && nearby + .iter() + .filter_map(|&h| entity(h)) + .any(|e| raider_in(&e, 32.0)) + { + self.resonating = true; + out.resonate = true; + } + if self.resonating { + if self.resonation_ticks < 40 { + self.resonation_ticks += 1; + } else { + // showBellParticles / makeRaidersGlow. + let mut color = 16_700_985; + let views: Vec<(u64, BellEntity)> = nearby + .iter() + .filter_map(|&h| Some((h, entity(h)?))) + .collect(); + let count = views + .iter() + .filter(|(_, e)| closer_to_center_than(pos, e.position, 48.0)) + .count() as i32; + let per = ((count - 21) / -2).clamp(3, 15); + let mut particles = Vec::new(); + let mut glow = Vec::new(); + for (h, e) in &views { + if !raider_in(e, 48.0) { + continue; + } + glow.push(*h); + let (bx, bz) = (f64::from(pos[0]), f64::from(pos[2])); + let dist = ((e.position[0] - bx) * (e.position[0] - bx) + + (e.position[2] - bz) * (e.position[2] - bz)) + .sqrt(); + let x3 = bx + f64::from(0.5f32) + 1.0 / dist * (e.position[0] - bx); + let z3 = bz + f64::from(0.5f32) + 1.0 / dist * (e.position[2] - bz); + for _ in 0..per { + color += 5; + particles.push(([x3, f64::from(pos[1]) + 0.5, z3], color)); + } + } + out.ended = Some((particles, glow)); + self.resonating = false; + } + } + out + } +} + +/// The conduit's `destroyTarget` as the client sees it. +#[derive(Clone, Copy, Debug)] +pub struct ConduitTarget { + pub position: [f64; 3], + pub eye_y: f64, + pub width: f32, + pub height: f32, +} + +/// `ConduitBlockEntity` (client side). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Conduit { + pub tick_count: i32, + pub active_rotation: f32, + pub is_active: bool, + pub is_hunting: bool, + pub effect_blocks: Vec<[i32; 3]>, +} + +/// One nautilus particle: position and velocity. +pub type Particle = ([f64; 3], [f64; 3]); + +impl Conduit { + /// `updateShape`: water all around, then the frame blocks + /// (`BlockTags.CONDUIT_EFFECT_BLOCK`) in the three 5x5 rings. + fn update_shape( + &mut self, + pos: [i32; 3], + is_water: &impl Fn([i32; 3]) -> bool, + is_frame: &impl Fn([i32; 3]) -> bool, + ) -> bool { + self.effect_blocks.clear(); + for ox in -1..=1 { + for oy in -1..=1 { + for oz in -1..=1 { + if !is_water([pos[0] + ox, pos[1] + oy, pos[2] + oz]) { + return false; + } + } + } + } + for ox in -2i32..=2 { + for oy in -2i32..=2 { + for oz in -2i32..=2 { + let (ax, ay, az) = (ox.abs(), oy.abs(), oz.abs()); + if (ax > 1 || ay > 1 || az > 1) + && (ox == 0 && (ay == 2 || az == 2) + || oy == 0 && (ax == 2 || az == 2) + || oz == 0 && (ax == 2 || ay == 2)) + { + let p = [pos[0] + ox, pos[1] + oy, pos[2] + oz]; + if is_frame(p) { + self.effect_blocks.push(p); + } + } + } + } + } + self.effect_blocks.len() >= 16 + } + /// `ConduitBlockEntity.clientTick`: returns the nautilus particles of + /// `animationTick`, drawn from the client level's random. + pub fn client_tick( + &mut self, + pos: [i32; 3], + game_time: i64, + is_water: impl Fn([i32; 3]) -> bool, + is_frame: impl Fn([i32; 3]) -> bool, + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + self.tick_count += 1; + if game_time % 40 == 0 { + self.is_active = self.update_shape(pos, &is_water, &is_frame); + self.is_hunting = self.effect_blocks.len() >= 42; + } + let particles = self.animation_tick(pos, target, random); + if self.is_active { + self.active_rotation += 1.0; + } + particles + } + fn animation_tick( + &self, + pos: [i32; 3], + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + let mut out = Vec::new(); + let hh = f64::from(((self.tick_count + 35) as f32 * 0.1).msin() / 2.0 + 0.5); + let hh = (hh * hh + hh) * f64::from(0.3f32); + let end = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.5 + hh, + f64::from(pos[2]) + 0.5, + ]; + for p in &self.effect_blocks { + if random.next_int_bound(50).unwrap_or(1) == 0 { + let dx = -0.5 + random.next_float() + (p[0] - pos[0]) as f32; + let dy = -2.0 + random.next_float() + (p[1] - pos[1]) as f32; + let dz = -0.5 + random.next_float() + (p[2] - pos[2]) as f32; + out.push((end, [f64::from(dx), f64::from(dy), f64::from(dz)])); + } + } + if let Some(t) = target { + let randx = (-0.5 + random.next_float()) * (3.0 + t.width); + let randy = -1.0 + random.next_float() * t.height; + let randz = (-0.5 + random.next_float()) * (3.0 + t.width); + out.push(( + [t.position[0], t.eye_y, t.position[2]], + [f64::from(randx), f64::from(randy), f64::from(randz)], + )); + } + out + } +} + +/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Skull { + pub animating: bool, + pub tick_count: i32, +} +impl Skull { + /// `SkullBlockEntity.animation`. + pub fn tick(&mut self, powered: bool) { + if powered { + self.animating = true; + self.tick_count += 1; + } else { + self.animating = false; + } + } + /// `getAnimation(a)`. + pub fn get_animation(&self, a: f32) -> f32 { + if self.animating { + self.tick_count as f32 + a + } else { + self.tick_count as f32 + } + } +} + +/// `DecoratedPotBlockEntity.WobbleStyle`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WobbleStyle { + Positive, + Negative, +} +impl WobbleStyle { + pub fn duration(self) -> i32 { + match self { + Self::Positive => 7, + Self::Negative => 10, + } + } +} + +/// `DecoratedPotBlockEntity` wobble fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PotWobble { + pub started_at: i64, + pub style: Option, +} +impl PotWobble { + /// `triggerEvent(1, style)`. + pub fn trigger_event(&mut self, event: i32, data: i32, game_time: i64) -> bool { + if event == 1 && (0..2).contains(&data) { + self.started_at = game_time; + self.style = Some(if data == 0 { + WobbleStyle::Positive + } else { + WobbleStyle::Negative + }); + true + } else { + false + } + } + /// `DecoratedPotRenderer.extractRenderState`'s `wobbleProgress`. + pub fn progress(&self, game_time: i64, partial: f32) -> f32 { + match self.style { + Some(style) => { + ((game_time - self.started_at) as f32 + partial) / style.duration() as f32 + } + None => 0.0, + } + } +} + +/// The client ticker a block entity runs (`getTicker` on a client level), +/// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ticker { + /// `ChestBlockEntity` / `EnderChestBlockEntity.lidAnimateTick`. + Lid, + /// `EnchantingTableBlockEntity.bookAnimationTick`. + Book, + /// `ShulkerBoxBlockEntity.tick`, with the box's facing. + Shulker { + facing: u8, + }, + /// `BellBlockEntity.clientTick`. + Bell, + /// `ConduitBlockEntity.clientTick`. + Conduit, + /// `SkullBlockEntity.animation` (dragon and piglin heads only). + Skull { + powered: bool, + }, + Pot, +} + +/// The [`Ticker`] of a block state, by block name and property lookup. +pub fn ticker(name: &str, prop: impl Fn(&str) -> Option) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); + Some(match unwaxed { + "chest" + | "trapped_chest" + | "ender_chest" + | "copper_chest" + | "exposed_copper_chest" + | "weathered_copper_chest" + | "oxidized_copper_chest" => Ticker::Lid, + "enchanting_table" => Ticker::Book, + "bell" => Ticker::Bell, + "conduit" => Ticker::Conduit, + "decorated_pot" => Ticker::Pot, + "dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull { + powered: prop("powered").as_deref() == Some("true"), + }, + n if n.ends_with("shulker_box") => Ticker::Shulker { + facing: prop("facing") + .as_deref() + .and_then(direction_index) + .unwrap_or(1), + }, + _ => return None, + }) +} + +/// The animated block entities of a level, by position. +#[derive(Clone, Debug)] +pub struct BlockEntityAnims { + pub chests: HashMap<[i32; 3], ChestLid>, + pub books: HashMap<[i32; 3], EnchantingBook>, + /// `EnchantingTableBlockEntity.RANDOM`, shared by every table. + pub book_random: LegacyRandom, + pub shulkers: HashMap<[i32; 3], Shulker>, + pub bells: HashMap<[i32; 3], Bell>, + pub conduits: HashMap<[i32; 3], Conduit>, + pub skulls: HashMap<[i32; 3], Skull>, + pub pots: HashMap<[i32; 3], PotWobble>, + /// The client level's random (conduit particles). + pub random: LegacyRandom, + /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). + pub kinds: Vec>, +} +impl Default for BlockEntityAnims { + fn default() -> Self { + Self { + chests: HashMap::new(), + books: HashMap::new(), + book_random: LegacyRandom::new(0x626f6f6b), + shulkers: HashMap::new(), + bells: HashMap::new(), + conduits: HashMap::new(), + skulls: HashMap::new(), + pots: HashMap::new(), + random: LegacyRandom::new(0x6c6576656c), + kinds: Vec::new(), + } + } +} +impl BlockEntityAnims { + /// Fills [`Self::kinds`] for every state of the registry. + pub fn classify(&mut self, registry: &horizon_world::registry::BlockRegistry) { + self.kinds = (0..registry.len() as u32) + .map(|id| { + registry + .state(horizon_world::registry::BlockStateId(id)) + .and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned())) + }) + .collect(); + } + /// The ticker of a block state. + pub fn ticker(&self, state: u32) -> Option { + self.kinds.get(state as usize).copied().flatten() + } + /// Drops the state of block entities that are gone or changed kind: + /// `present` maps the loaded block entities to their tickers. + pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) { + let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f); + self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid)); + self.books.retain(|p, _| is(p, |t| *t == Ticker::Book)); + self.shulkers + .retain(|p, _| is(p, |t| matches!(t, Ticker::Shulker { .. }))); + self.bells.retain(|p, _| is(p, |t| *t == Ticker::Bell)); + self.conduits + .retain(|p, _| is(p, |t| *t == Ticker::Conduit)); + self.skulls + .retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. }))); + self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot)); + } + /// Drops the state of positions whose block entity is gone. + pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) { + self.chests.retain(|p, _| keep(*p)); + self.books.retain(|p, _| keep(*p)); + self.shulkers.retain(|p, _| keep(*p)); + self.bells.retain(|p, _| keep(*p)); + self.conduits.retain(|p, _| keep(*p)); + self.skulls.retain(|p, _| keep(*p)); + self.pots.retain(|p, _| keep(*p)); + } + /// `getOpenNess(partial)` of the chest or ender chest at `pos`. + pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.chests + .get(&pos) + .map_or(0.0, |l| l.get_openness(partial)) + } + /// The renderer's view of the block entity at `pos`; `sherds` are the + /// pot's decorations (back, left, right, front), when it is a pot. + pub fn block_anim( + &self, + pos: [i32; 3], + game_time: i64, + partial: f32, + sherds: [Option; 4], + ) -> BlockAnim { + let mut anim = BlockAnim { + sherds, + // End gateway ages and cooldowns are not tracked on the client yet: + // gateways render settled (no beam). + gateway: (i64::MAX, 0), + ..BlockAnim::default() + }; + if let Some(b) = self.books.get(&pos) { + anim.book = *b; + } + if let Some(s) = self.shulkers.get(&pos) { + anim.shulker = (s.progress, s.progress_old); + } + if let Some(b) = self.bells.get(&pos) { + anim.bell_ticks = b.ticks; + anim.bell_shake = b + .shaking + .then_some(b.click_direction) + .flatten() + .map(|d| DIRECTIONS[usize::from(d)]); + } + if let Some(c) = self.conduits.get(&pos) { + anim.conduit = (c.tick_count, c.is_active, c.is_hunting, c.active_rotation); + } + if let Some(s) = self.skulls.get(&pos) { + anim.skull = (s.animating, s.tick_count); + } + if let Some(w) = self.pots.get(&pos) + && w.style.is_some() + { + // extractRenderState never copies lastWobbleStyle into the render + // state, so DecoratedPotRenderer.submit always takes the + // non-POSITIVE branch (with the style's own duration). + anim.wobble = Some((false, w.progress(game_time, partial))); + } + anim + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index f3638865b..7380bb75e 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1,19 +1,22 @@ //! Block-entity renderers (`BlockEntityRenderers`): chests (single, double, //! trapped, ender, copper), shulker boxes, banners, skulls and heads, bells, //! decorated pots, conduits, enchanting-table and lectern books and copper -//! golem statues. Models are vanilla's baked `LayerDefinitions` layers +//! golem statues, End portals and End gateways. Models are vanilla's baked `LayerDefinitions` layers //! (`entity-models.json`); transforms, animation and textures follow each //! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at //! the block plus `minecraft_mix_light` with the level's two diffuse lights. use crate::{hud::Rect, mesher::Vertex, world::World}; use glam::{DVec3, Mat4, Quat, Vec3}; -use horizon_core::{ - geometry::trig::Mth, - random::{LegacyRandom, RandomSource}, +use horizon_core::geometry::{ + Direction, + trig::{self, Mth}, +}; +use horizon_world::{ + block_render::FaceVisibility, + registry::{BlockRegistry, BlockStateId}, }; -use horizon_world::registry::{BlockRegistry, BlockStateId}; use serde_json::Value; -use std::{collections::HashMap, f32::consts::PI, path::Path}; +use std::{collections::HashMap, f32::consts::PI, path::Path, sync::Mutex}; /// One baked `ModelPart`: initial pose, textured polygons (pixel units, /// normalized UVs) and named children. @@ -256,6 +259,8 @@ enum SkullType { enum Kind { None, Chest { + /// The block (`neighbourState.is(state.getBlock())`). + block: String, texture: &'static str, part: ChestPart, y_rot: f32, @@ -289,6 +294,12 @@ enum Kind { pose: &'static str, facing: &'static str, }, + /// `TheEndPortalRenderer`: the top and bottom faces of a 6/16-tall slab. + EndPortal, + /// `TheEndGatewayRenderer`: the visible faces of the cube and the beam. + EndGateway { + state: u32, + }, /// Sign text (`StandingSignRenderer` / `HangingSignRenderer`); the boards are block models. Sign { hanging: bool, @@ -323,6 +334,7 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { ChestPart::Right => Some(step(opposite(clockwise(facing)))), }; Kind::Chest { + block: name.to_owned(), texture: match part { ChestPart::Single => texture, ChestPart::Left => left, @@ -413,6 +425,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { }; } "conduit" => return Kind::Conduit, + "end_portal" => return Kind::EndPortal, + "end_gateway" => return Kind::EndGateway { state: 0 }, "enchanting_table" => return Kind::EnchantingTable, "lectern" => { return if prop("has_book").as_deref() == Some("true") { @@ -512,72 +526,6 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { Kind::None } -/// `EnchantingTableBlockEntity` book animation state. -#[derive(Clone, Copy, Default)] -struct Book { - time: i32, - flip: f32, - o_flip: f32, - flip_t: f32, - flip_a: f32, - open: f32, - o_open: f32, - rot: f32, - o_rot: f32, - t_rot: f32, -} -fn wrap(mut a: f32) -> f32 { - while a >= PI { - a -= 2.0 * PI; - } - while a < -PI { - a += 2.0 * PI; - } - a -} -impl Book { - /// `EnchantingTableBlockEntity.bookAnimationTick`. - fn tick(&mut self, pos: [i32; 3], player: Option<[f64; 3]>, random: &mut LegacyRandom) { - self.o_open = self.open; - self.o_rot = self.rot; - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - let near = player.filter(|p| { - (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) < 9.0 - }); - if let Some(p) = near { - self.t_rot = (p[2] - c[2]).atan2(p[0] - c[0]) as f32; - self.open += 0.1; - if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { - let old = self.flip_t; - loop { - let a = random.next_int_bound(4).unwrap_or(0); - let b = random.next_int_bound(4).unwrap_or(0); - self.flip_t += (a - b) as f32; - if old != self.flip_t { - break; - } - } - } - } else { - self.t_rot += 0.02; - self.open -= 0.1; - } - self.rot = wrap(self.rot); - self.t_rot = wrap(self.t_rot); - let dir = wrap(self.t_rot - self.rot); - self.rot += dir * 0.4; - self.open = self.open.clamp(0.0, 1.0); - self.time += 1; - self.o_flip = self.flip; - let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); - self.flip_a += (diff - self.flip_a) * 0.9; - self.flip += self.flip_a; - } -} /// `BookModel.setupAnim` for `BookModel.State(openness, pageFlip1, pageFlip2)`. fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) { move |name, p| match name { @@ -737,6 +685,10 @@ pub struct BlockAnim { pub sherds: [Option; 4], /// `DecoratedPotRenderState` wobble style (positive) and progress. pub wobble: Option<(bool, f32)>, + /// `EnchantingTableBlockEntity` book fields. + pub book: crate::block_entity_anim::EnchantingBook, + /// `TheEndGatewayBlockEntity` age and teleportCooldown. + pub gateway: (i64, i32), } /// One `submitText` call (`AbstractSignRenderer.submitSignText`). @@ -765,6 +717,8 @@ pub struct Scene<'a> { pub texts: Option<&'a std::cell::RefCell>>, pub partial: f32, pub game_time: i64, + /// `Level.getMaxY` (End gateway beams while spawning). + pub max_y: i32, pub world: &'a World, pub sprites: &'a HashMap, pub nether: bool, @@ -781,10 +735,10 @@ pub struct Scene<'a> { pub struct BlockEntityRenderer { models: HashMap<&'static str, ModelPart>, kinds: Vec, - books: HashMap<[i32; 3], Book>, - random: LegacyRandom, /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, + /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). + visibility: Option>, } const MODELS: [(&str, &str); 27] = [ ("chest", "minecraft:chest#main"), @@ -835,6 +789,7 @@ impl BlockEntityRenderer { .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) .collect(); let mut renderer = Self::new(models, registry); + renderer.visibility = Some(Mutex::new(crate::models::load_visibility(root, registry)?)); // Sherd items: provides_pottery_pattern -> decorated_pot_pattern asset id. if let Ok(bytes) = std::fs::read(root.join("items.json")) { let items: Value = serde_json::from_slice(&bytes)?; @@ -864,16 +819,18 @@ impl BlockEntityRenderer { .map(|id| { registry.state(BlockStateId(id)).map_or(Kind::None, |s| { let prop = |k: &str| s.properties.get(k).cloned(); - classify(&s.name, &prop) + match classify(&s.name, &prop) { + Kind::EndGateway { .. } => Kind::EndGateway { state: id }, + kind => kind, + } }) }) .collect(); Self { models, kinds, - books: HashMap::new(), - random: LegacyRandom::new(0x5EED_B00C), pot_patterns: HashMap::new(), + visibility: None, } } /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). @@ -886,24 +843,6 @@ impl BlockEntityRenderer { fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } - /// Client-side block-entity ticks (enchanting-table books). - pub fn tick<'a>( - &mut self, - blocks: impl Iterator, - player: Option<[f64; 3]>, - ) { - let mut seen = Vec::new(); - for (pos, state) in blocks { - if matches!(self.kind(*state), Kind::EnchantingTable) { - seen.push(*pos); - } - } - self.books.retain(|p, _| seen.contains(p)); - for pos in seen { - let book = self.books.entry(pos).or_default(); - book.tick(pos, player, &mut self.random); - } - } pub fn render<'a>( &self, scene: &Scene, @@ -921,7 +860,13 @@ impl BlockEntityRenderer { f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5, ); - if center.distance_squared(scene.camera) > VIEW_DISTANCE * VIEW_DISTANCE { + // BlockEntityRenderer.getViewDistance: 256 for End gateways. + let distance = if matches!(kind, Kind::EndGateway { .. }) { + 256.0 + } else { + VIEW_DISTANCE + }; + if center.distance_squared(scene.camera) > distance * distance { continue; } let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) @@ -951,21 +896,65 @@ impl BlockEntityRenderer { pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } - /// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`): - /// time, flip, oFlip, open, oOpen, rot, oRot. - pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) { - let [flip, o_flip, open, o_open, rot, o_rot] = fields; - let book = self.books.entry(pos).or_default(); - *book = Book { - time, - flip, - o_flip, - open, - o_open, - rot, - o_rot, - ..*book + /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` + /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) + /// pairs a double half with its neighbour only when that is the same + /// block, the other half and faces the same way; `opennessCombiner` then + /// takes the more open of both. Also returns the paired half's position. + /// `lid` is `getOpenNess(partial)` at a position; non-chests give 0. + pub fn chest_openness_of( + &self, + pos: [i32; 3], + state: u32, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + self.chest_openness(pos, self.kind(state), block_at, lid) + } + fn chest_openness( + &self, + pos: [i32; 3], + kind: &Kind, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + let Kind::Chest { + block, + part, + y_rot, + double_with, + .. + } = kind + else { + return (0.0, None); }; + let open = lid(pos); + let Some(d) = double_with else { + return (open, None); + }; + let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + match self.kind(block_at(other)) { + Kind::Chest { + block: other_block, + part: other_part, + y_rot: other_y_rot, + .. + } if other_block == block + && *other_part != ChestPart::Single + && other_part != part + && other_y_rot == y_rot => + { + let other_open = lid(other); + // The right half is the first. + let open = if *part == ChestPart::Right { + crate::block_entity_anim::combined_openness(open, Some(other_open)) + } else { + crate::block_entity_anim::combined_openness(other_open, Some(open)) + }; + (open, Some(other)) + } + _ => (open, None), + } } /// One block entity of `state` drawn under `base` (minecart contents). pub fn render_state( @@ -1060,7 +1049,7 @@ impl BlockEntityRenderer { texture, part, y_rot, - double_with, + .. } => { let model = match part { ChestPart::Single => "chest", @@ -1070,22 +1059,24 @@ impl BlockEntityRenderer { let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { return; }; - // ChestBlock.opennessCombiner / BrightnessCombiner: both halves. - let mut open = (scene.lid)(pos); + let (open, other) = self.chest_openness( + pos, + kind, + &|p| scene.world.block(p[0], p[1], p[2]).0, + scene.lid, + ); + // BrightnessCombiner: the brighter of both halves, per channel. let mut packed = packed; - if let Some(d) = double_with { - let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; - open = open.max((scene.lid)(other)); + if let Some(other) = other { let l = scene.world.light(other[0], other[1], other[2]); packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); } - let open = 1.0 - (1.0 - open).powi(3); let m = base * around( Mat4::from_rotation_y((-y_rot).to_radians()), Vec3::new(0.5, 0.0, 0.5), ); - let lid = -(open * PI / 2.0); + let lid = crate::block_entity_anim::chest_lid_x_rot(open); let adjust = move |name: &str, p: &mut [f32; 9]| { if name == "lid" || name == "lock" { p[3] = lid; @@ -1291,6 +1282,73 @@ impl BlockEntityRenderer { } } } + Kind::EndPortal => { + // TheEndPortalRenderer.TRANSFORMATION: y from 6/16 to 12/16; only the + // vertical faces (TheEndPortalBlockEntity.shouldRenderFace). + let m = base + * Mat4::from_translation(Vec3::new(0.0, 0.375, 0.0)) + * Mat4::from_scale(Vec3::new(1.0, 0.375, 1.0)); + portal_cube(m, &[Direction::Down, Direction::Up], END_PORTAL_LAYER, out); + } + Kind::EndGateway { state } => { + let anim = (scene.anim)(pos); + let (age, cooldown) = anim.gateway; + // TheEndGatewayRenderer.extractRenderState. + let spawning = age < 200; + if spawning || cooldown > 0 { + let a = scene.partial; + let percent = if spawning { + ((age as f32 + a) / 200.0).clamp(0.0, 1.0) + } else { + 1.0 - ((cooldown as f32 - a) / 40.0).clamp(0.0, 1.0) + }; + let distance = if spawning { + f64::from(scene.max_y) + } else { + 50.0 + }; + let scale = trig::sin(f64::from(percent * PI)); + let height = (f64::from(scale) * distance).floor() as i32; + // DyeColor.MAGENTA / PURPLE getTextureDiffuseColor. + let color = if spawning { 0xC7_4EBD } else { 0x89_32B8 }; + let time = scene.game_time.rem_euclid(40) as f32 + a; + if height > 0 + && let Some(s) = sprite("entity/end_portal/end_gateway_beam") + { + beam( + base, + BeamShape { + scale, + time, + start: -height, + height: height * 2, + color, + solid_radius: 0.15, + glow_radius: 0.175, + }, + s, + out, + ); + } + } + // AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace. + let faces: Vec = Direction::ALL + .into_iter() + .filter(|&d| { + let [dx, dy, dz] = d.normal(); + let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); + self.visibility.as_ref().is_none_or(|v| { + v.lock() + .map(|mut v| { + v.should_render_face(BlockStateId(*state), neighbor, d, true) + .unwrap_or(true) + }) + .unwrap_or(true) + }) + }) + .collect(); + portal_cube(base, &faces, END_GATEWAY_LAYER, out); + } Kind::Conduit => { let (ticks, active, hunting, raw_rotation) = (scene.anim)(pos).conduit; // ConduitRenderer.extractRenderState. @@ -1363,21 +1421,18 @@ impl BlockEntityRenderer { ) else { return; }; - let b = self.books.get(&pos).copied().unwrap_or_default(); - let a = scene.partial; - let flip = b.o_flip + (b.flip - b.o_flip) * a; - let open = b.o_open + (b.open - b.o_open) * a; - let time = b.time as f32 + a; - let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a; + // EnchantTableRenderer.extractRenderState and submit. + let b = (scene.anim)(pos).book.render(scene.partial); let m = base * Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5)) - * Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0)) - * Mat4::from_rotation_y(-y_rot) + * Mat4::from_translation(Vec3::new( + 0.0, + 0.1 + (b.time * 0.1).msin() * 0.01, + 0.0, + )) + * Mat4::from_rotation_y(-b.y_rot) * Mat4::from_rotation_z(80f32.to_radians()); - let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0); - let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0); - // BookModel.State.forAnimation. - let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open; + let (openness, ff1, ff2) = (b.openness, b.page_flip1, b.page_flip2); draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out); } Kind::Lectern { y_rot } => { @@ -1438,8 +1493,7 @@ impl BlockEntityRenderer { /// rotating solid beam and its translucent glow, the last section 2048 /// blocks tall. `origin` is the beacon block's corner relative to the camera, /// `time` the animation time (game time mod 40 plus partial tick) and `scale` -/// the radius scale. The sprite's v range rides in the light bytes (the -/// entity shader wraps v for layer 6). +/// the radius scale. pub fn beacon_beam( origin: Vec3, sections: &[(u32, i32)], @@ -1448,9 +1502,7 @@ pub fn beacon_beam( s: Rect, out: &mut Vec, ) { - let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; - let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; - let o = origin + Vec3::new(0.5, 0.0, 0.5); + let base = Mat4::from_translation(origin); let mut start = 0i32; for (i, &(color, height)) in sections.iter().enumerate() { let height = if i == sections.len() - 1 { @@ -1458,63 +1510,140 @@ pub fn beacon_beam( } else { height }; - let end = start + height; - let scroll = if height < 0 { time } else { -time }; - let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); - let abgr = - |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); - // Solid beam: radius 0.2 * scale, rotated with time. - let r = 0.2 * scale; - let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); - let corners = [ - rot * Vec3::new(0.0, 0.0, r), - rot * Vec3::new(r, 0.0, 0.0), - rot * Vec3::new(-r, 0.0, 0.0), - rot * Vec3::new(0.0, 0.0, -r), - ]; - let v2 = -1.0 + v_off; - let v1 = height as f32 * (0.5 / r) + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); - // Glow: radius 0.25 * scale, translucent. - let g = 0.25 * scale; - let corners = [ - Vec3::new(-g, 0.0, -g), - Vec3::new(g, 0.0, -g), - Vec3::new(-g, 0.0, g), - Vec3::new(g, 0.0, g), - ]; - let v1 = height as f32 + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); - start = end; + let shape = BeamShape { + scale: 1.0, + time, + start, + height, + color, + solid_radius: 0.2 * scale, + glow_radius: 0.25 * scale, + }; + beam(base, shape, s, out); + start += height; } } -/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). -#[allow(clippy::too_many_arguments)] -fn beam_part( - out: &mut Vec, - o: Vec3, +/// The arguments of `BeaconRenderer.submitBeaconBeam`. +pub struct BeamShape { + /// Scales the v range (End gateways shrink and grow their beam with it). + pub scale: f32, + /// Animation time: game time mod 40 plus the partial tick. + pub time: f32, + pub start: i32, + pub height: i32, + /// RGB. + pub color: u32, + pub solid_radius: f32, + pub glow_radius: f32, +} +/// `BeaconRenderer.submitBeaconBeam` under `base` (the block's corner): the +/// rotating solid beam and its translucent glow. The sprite's v range rides +/// in the light bytes (the entity shader wraps v for layer 6). +pub fn beam(base: Mat4, b: BeamShape, s: Rect, out: &mut Vec) { + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; + let color = b.color; + let end = b.start + b.height; + let scroll = if b.height < 0 { b.time } else { -b.time }; + let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); + let abgr = + |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); + // Solid beam, rotated with time. + let r = b.solid_radius; + let rot = glam::Mat3::from_rotation_y((b.time * 2.25 - 45.0).to_radians()); + let corners = [ + rot * Vec3::new(0.0, 0.0, r), + rot * Vec3::new(r, 0.0, 0.0), + rot * Vec3::new(-r, 0.0, 0.0), + rot * Vec3::new(0.0, 0.0, -r), + ]; + let v2 = -1.0 + v_off; + let v1 = b.height as f32 * b.scale * (0.5 / r) + v2; + let part = BeamPart { + base, + start: b.start, + end, + s, + wrap, + }; + part.emit(out, corners, [v1, v2], abgr(255)); + // Glow, translucent. + let g = b.glow_radius; + let corners = [ + Vec3::new(-g, 0.0, -g), + Vec3::new(g, 0.0, -g), + Vec3::new(-g, 0.0, g), + Vec3::new(g, 0.0, g), + ]; + let v1 = b.height as f32 * b.scale + v2; + part.emit(out, corners, [v1, v2], abgr(32)); +} +struct BeamPart { + base: Mat4, start: i32, end: i32, - [wn, en, ws, es]: [Vec3; 4], - [v1, v2]: [f32; 2], - color: u32, s: Rect, wrap: u32, -) { - for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { - let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); - for (p, uv) in [ - (at(a, end), [s.u1, v1]), - (at(a, start), [s.u1, v2]), - (at(b, start), [s.u0, v2]), - (at(b, end), [s.u0, v1]), - ] { +} +impl BeamPart { + /// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). + fn emit( + &self, + out: &mut Vec, + [wn, en, ws, es]: [Vec3; 4], + [v1, v2]: [f32; 2], + color: u32, + ) { + let s = self.s; + for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { + let at = |c: Vec3, y: i32| { + self.base + .transform_point3(Vec3::new(0.5, 0.0, 0.5) + c + Vec3::new(0.0, y as f32, 0.0)) + }; + for (p, uv) in [ + (at(a, self.end), [s.u1, v1]), + (at(a, self.start), [s.u1, v2]), + (at(b, self.start), [s.u0, v2]), + (at(b, self.end), [s.u0, v1]), + ] { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 6, + color, + light: self.wrap, + }); + } + } + } +} + +/// Entity-shader layers for `rendertype_end_portal`: end portals draw 15 +/// layers of `end_portal.png` over `end_sky.png`, End gateways 16. +pub const END_PORTAL_LAYER: u32 = 9; +pub const END_GATEWAY_LAYER: u32 = 10; +/// `AbstractEndPortalRenderer.FACES`: the unit cube's corners for each face +/// (`Direction` order) in `FaceInfo` vertex order. +#[rustfmt::skip] +const PORTAL_FACES: [[[f32; 3]; 4]; 6] = [ + [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0]], + [[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]], + [[1.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + [[0.0, 1.0, 1.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]], + [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0]], + [[1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]], +]; +/// `AbstractEndPortalRenderer.submitCube`: position-only quads (the portal +/// shader projects its textures from the screen; uv, colour and light are unused). +fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec) { + for &d in faces { + for c in PORTAL_FACES[d as usize] { out.push(Vertex { - pos: p.to_array(), - uv, - layer: 6, - color, - light: wrap, + pos: m.transform_point3(Vec3::from(c)).to_array(), + uv: [0.0; 2], + layer, + color: 0, + light: 0, }); } } diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index 9df17431c..a976258f9 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -57,7 +57,9 @@ impl BossBar { hover: Some(Box::new(Text::literal(self.id.clone()))), ..Style::default() }; - bracketed(comp_text(&self.name).with_style(&style)) + // ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the + // brackets take the colour too. + bracketed(comp_text(&self.name)).with_style(&style) } /// The filled fraction of the bar (`BossEvent.getProgress`). pub fn progress(&self) -> f32 { diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 1c5abe777..eccd5b0d3 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -5,6 +5,7 @@ use crate::{ command::{Dispatcher, ParseResults, Registries, Suggestion}, hud::{HudAtlas, HudBatch, rgba}, + hud_layout::{self, GuiDraw, PoseOp}, text::{self, Style, Text}, ui::{EditBox, char_len}, }; @@ -12,15 +13,16 @@ use crate::{ /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; +/// The chat options (doubles, as vanilla keeps them). #[derive(Clone, Copy, Debug)] pub struct ChatOptions { - pub opacity: f32, - pub background_opacity: f32, - pub scale: f32, - pub width: f32, - pub height_focused: f32, - pub height_unfocused: f32, - pub line_spacing: f32, + pub opacity: f64, + pub background_opacity: f64, + pub scale: f64, + pub width: f64, + pub height_focused: f64, + pub height_unfocused: f64, + pub line_spacing: f64, } impl Default for ChatOptions { fn default() -> Self { @@ -37,20 +39,21 @@ impl Default for ChatOptions { } impl ChatOptions { /// ChatComponent.getWidth/getHeight. - pub fn width_px(&self) -> f32 { - (self.width * 280.0 + 40.0).floor() + pub fn width_px(&self) -> i32 { + (self.width * 280.0 + 40.0).floor() as i32 } - pub fn height_px(&self, focused: bool) -> f32 { + pub fn height_px(&self, focused: bool) -> i32 { ((if focused { self.height_focused } else { self.height_unfocused }) * 160.0 + 20.0) - .floor() + .floor() as i32 } - pub fn line_height(&self) -> f32 { - (9.0 * (self.line_spacing + 1.0)).floor() + /// `getLineHeight`. + pub fn line_height(&self) -> i32 { + (9.0 * (self.line_spacing + 1.0)) as i32 } } #[derive(Clone, Debug)] @@ -59,12 +62,25 @@ struct Message { content: Text, indicator: Option, } +/// A wrapped line (`GuiMessage.Line`). #[derive(Clone, Debug)] struct Line { added: u64, content: Text, indicator: Option, } + +/// `ChatComponent.AlphaCalculator.timeBased`: opaque for 180 ticks, then +/// fading out quadratically over 20. +fn time_alpha(ticks: u64, added: u64) -> f32 { + let delta = ticks as i64 - added as i64; + let mut t = delta as f64 / 200.0; + t = 1.0 - t; + t *= 10.0; + t = t.clamp(0.0, 1.0); + t *= t; + t as f32 +} #[derive(Default)] pub struct Chat { messages: Vec, @@ -80,10 +96,11 @@ pub struct Chat { } impl Chat { pub fn lines_per_page(&self, focused: bool) -> usize { - (self.options.height_px(focused) / self.options.line_height().max(1.0)) as usize + (self.options.height_px(focused) / self.options.line_height().max(1)) as usize } - fn max_width(&self) -> f32 { - (self.options.width_px() / self.options.scale.max(0.01)).floor() + /// The wrapping width, `Mth.floor(getWidth() / getScale())`. + fn max_width(&self) -> i32 { + (f64::from(self.options.width_px()) / self.options.scale).floor() as i32 } /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. pub fn add( @@ -108,7 +125,7 @@ impl Chat { } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); - for line in atlas.font.split(&message.content, width) { + for line in atlas.font.wrap_components(&message.content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -164,116 +181,113 @@ impl Chat { self.scroll = pos as usize; } } - /// ChatComponent.extractRenderState. - pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { - if self.lines.is_empty() { - return; + /// `ChatComponent.extractRenderState` (background mode unless `focused`) + /// on a screen `height` GUI pixels tall at `Hud.tickCount` `ticks`. + pub fn layout(&self, height: i32, ticks: u64, focused: bool) -> Vec { + let total = self.lines.len(); + if total == 0 { + return Vec::new(); } let o = &self.options; - let scale = o.scale; - if scale <= 0.0 { - return; - } - let max_width = (o.width_px() / scale).ceil(); - let chat_bottom = ((batch.height - 40.0) / scale).floor(); - let text_opacity = o.opacity * 0.9 + 0.1; + let scale = o.scale as f32; + let max_width = hud_layout::ceil(o.width_px() as f32 / scale); + let chat_bottom = hud_layout::floor((height - 40) as f32 / scale); + let text_opacity = o.opacity as f32 * 0.9 + 0.1; + let background_opacity = o.background_opacity as f32; let entry_height = o.line_height(); - let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing).round(); - let per_page = self.lines_per_page(focused); - let alpha_of = |line: &Line| -> f32 { + let bottom_to_text = + (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32; + let alpha_of = |line: &Line| { if focused { - return 1.0; + 1.0 + } else { + time_alpha(ticks, line.added) } - let t = - ((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0); - (t * t) as f32 }; - let visible = self.lines.len().saturating_sub(self.scroll).min(per_page); - let mut count = 0; - // Pass 1: backgrounds; pass 2: text (same order as vanilla). - let s = |v: f32| v * scale; - for i in (0..visible).rev() { - let line = &self.lines[i + self.scroll]; - let alpha = alpha_of(line); - if alpha <= 1.0e-5 { - continue; - } - count += 1; - let bottom = chat_bottom - i as f32 * entry_height; - let top = bottom - entry_height; - batch.fill( - atlas, - 0.0, - s(top), - s(max_width + 8.0), - s(entry_height), - rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8), - ); + let visible = total + .saturating_sub(self.scroll) + .min(self.lines_per_page(focused)); + let lines: Vec<(usize, &Line, f32)> = (0..visible) + .rev() + .map(|i| (i, &self.lines[i + self.scroll])) + .map(|(i, line)| (i, line, alpha_of(line))) + .filter(|(_, _, alpha)| *alpha > 1.0e-5) + .collect(); + let mut out = vec![GuiDraw::Push(vec![ + PoseOp::Scale(scale, scale), + PoseOp::Translate(4.0, 0.0), + ])]; + for &(i, _, alpha) in &lines { + let bottom = chat_bottom - i as i32 * entry_height; + out.push(hud_layout::fill( + -4, + bottom - entry_height, + max_width + 4 + 4, + bottom, + hud_layout::as8(alpha * background_opacity) << 24, + )); } - for i in (0..visible).rev() { - let line = &self.lines[i + self.scroll]; - let alpha = alpha_of(line); - if alpha <= 1.0e-5 { - continue; + for &(i, line, alpha) in &lines { + let bottom = chat_bottom - i as i32 * entry_height; + let opacity = alpha * text_opacity; + let color = hud_layout::white(opacity); + if color >> 24 != 0 { + out.push(GuiDraw::Text { + text: line.content.clone(), + x: 0, + y: bottom - bottom_to_text, + color, + shadow: true, + }); } - let bottom = chat_bottom - i as f32 * entry_height; - let top = bottom - entry_height; - let text_top = bottom - bottom_to_text; - let a = (alpha * text_opacity * 255.0) as u8; - if let Some(c) = line.indicator { - batch.fill( - atlas, - 0.0, - s(top), - s(2.0), - s(entry_height), - rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a), - ); - } - if a > 3 { - batch.text_styled( - atlas, - &line.content, - s(4.0), - s(text_top), - rgba(255, 255, 255, a), - true, - ); + if let Some(indicator) = line.indicator { + let color = hud_layout::as8(opacity) << 24 | indicator & 0xFF_FFFF; + out.push(hud_layout::fill( + -4, + bottom - entry_height, + -2, + bottom, + color, + )); } } - // Scroll bar while focused and scrolled content exists. - if focused && count > 0 { - let total = self.lines.len() as f32; - let chat_height = count as f32 * entry_height; - let virtual_height = total * entry_height; + if focused { + let count = lines.len() as i32; + let chat_height = count * entry_height; + let virtual_height = total as i32 * entry_height; + let y = self.scroll as i32 * chat_height / total as i32 - chat_bottom; + let height = chat_height * chat_height / virtual_height; if virtual_height != chat_height { - let y = self.scroll as f32 * chat_height / total - chat_bottom; - let height = chat_height * chat_height / virtual_height; - let alpha = if y > 0.0 { 170 } else { 96 }; - let c = if self.new_since_scroll { + let alpha: u32 = if y > 0 { 170 } else { 96 }; + let color = if self.new_since_scroll { 0xCC3333 } else { 0x3333AA }; - let x = max_width + 4.0 + 4.0; - batch.fill( - atlas, - s(x), - s(-y - height), - s(2.0), - s(height), - rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha), - ); - batch.fill( - atlas, - s(x + 1.0), - s(-y - height), - s(1.0), - s(height), - rgba(0xCC, 0xCC, 0xCC, alpha), - ); + let x = max_width + 4; + out.push(hud_layout::fill( + x, + -y, + x + 2, + -y - height, + alpha << 24 | color, + )); + out.push(hud_layout::fill( + x + 2, + -y, + x + 1, + -y - height, + alpha << 24 | 0xCCCCCC, + )); } } + out.push(GuiDraw::Pop); + out + } + /// Draws [`Chat::layout`] into the HUD batch. + pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { + let draws = self.layout(batch.height as i32, ticks, focused); + hud_layout::paint(batch, atlas, &draws); } /// Plain text of the newest messages (for tests and the control socket). pub fn recent_lines(&self, n: usize) -> Vec { diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 43770802f..219f59654 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -83,6 +83,73 @@ pub struct RegistryIds { } const EMPTY: &[String] = &[]; impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers + .insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria + .insert(id.clone(), strings(criteria)); + } + } + } /// The element ids of a registry (sorted). pub fn ids(&self, registry: &str) -> &[String] { if let Some(r) = self.by_registry.get(registry) { @@ -254,6 +321,47 @@ pub enum ArgType { SlotSource, /// ResourceOrIdArgument over a registry: an id or an inline SNBT value. ResourceOrId(&'static str), + /// ResourceSelectorArgument: a `*`/`?` pattern over a registry's ids. + ResourceSelector(&'static str), +} + +/// FilenameUtils.wildcardMatch (case-sensitive) of `*` and `?` patterns. +pub fn wildcard_match(text: &str, pattern: &str) -> bool { + let t: Vec = text.chars().collect(); + let p: Vec = pattern.chars().collect(); + let (mut ti, mut pi) = (0, 0); + let (mut star, mut mark) = (None, 0); + while ti < t.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { + ti += 1; + pi += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == '*' { + pi += 1; + } + pi == p.len() +} +/// ResourceSelectorArgument: the registry ids a pattern selects. +pub fn select_resources<'a>(ids: &'a [String], pattern: &str) -> Vec<&'a String> { + let pattern = if pattern.contains(':') { + pattern.to_owned() + } else { + format!("minecraft:{pattern}") + }; + ids.iter() + .filter(|id| wildcard_match(id, &pattern)) + .collect() } /// SlotRanges.SLOTS: every slot range name and its size, in vanilla order. @@ -1348,6 +1456,29 @@ impl ArgType { } Arg::Str(name.to_owned()) } + ArgType::ResourceSelector(registry) => { + let start = reader.cursor; + while reader.can_read() && { + let c = reader.peek(); + is_id_char(c) || c == '*' || c == '?' + } { + reader.skip(); + } + let raw = reader.string[start..reader.cursor].to_owned(); + let pattern = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + if select_resources(reg.ids(registry), &pattern).is_empty() { + return Err(CommandError::tr_at( + "argument.resource_selector.not_found", + &[&pattern, registry], + reader, + )); + } + Arg::Str(pattern) + } ArgType::HexColor => { let text = reader.read_unquoted_string(); if !matches!(text.len(), 3 | 6) { @@ -1579,7 +1710,8 @@ impl ArgType { if block { parse_coord_int(reader) } else { - parse_coord_double(reader, false) + // Vec2Argument.vec2(): integers are centred on the block. + parse_coord_double(reader, true) } }; let x = one(reader)?; @@ -1741,6 +1873,9 @@ impl ArgType { } ArgType::StrEnum(values, _) => builder.suggest_matching(values.iter().copied()), ArgType::HexColor => builder.suggest_matching(["F00", "FF0000"]), + ArgType::ResourceSelector(registry) => { + suggest_resources(builder, reg.ids(registry), "") + } ArgType::GameProfile => { let players = reg.players.clone(); super::selector::suggest(builder, reg, &|b| { diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-client/src/command/codec.rs index 783d26e30..7c4d26682 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-client/src/command/codec.rs @@ -77,11 +77,23 @@ fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> { Err(missing.join("; ")) } } +/// The required fields of each context number provider type, in the +/// order DataFixerUpper reports them missing (the reverse of the record's). fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> { - match id { - "minecraft:uniform" => require(map, t, &["max", "min"]), - "minecraft:constant" => require(map, t, &["value"]), - "minecraft:binomial" => require(map, t, &["n", "p"]), + match id.trim_start_matches("minecraft:") { + "uniform" => require(map, t, &["max", "min"]), + "constant" => require(map, t, &["value"]), + "binomial" => require(map, t, &["p", "n"]), + "add" | "mul" | "avg" | "max" | "min" | "length" => require(map, t, &["inputs"]), + "sub" | "div" | "mod" | "floor_div" | "floor_mod" => require(map, t, &["right", "left"]), + "pow" => require(map, t, &["exponent", "base"]), + "abs" | "negate" | "from_float" | "from_int" | "floor" | "ceil" | "round" | "sqrt" + | "sin" | "cos" | "truncate" => require(map, t, &["input"]), + "conditional" => require(map, t, &["on_true", "condition"]), + "number_dispatcher" => require(map, t, &["cases"]), + "weighted_list" => require(map, t, &["distribution"]), + "enchantment_level" => require(map, t, &["amount"]), + "score" => require(map, t, &["score", "target"]), _ => Ok(()), } } @@ -130,7 +142,19 @@ pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> { "minecraft:slot_source" => element_or_list(t, &|x| { dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(())) }), - "minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|_, _, _| Ok(())), + // Dialog types: CommonDialogData's title, then each type's own. + "minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|id, map, t| { + let own: &[&str] = match id { + "minecraft:confirmation" => &["yes", "no"], + "minecraft:multi_action" => &["actions"], + "minecraft:dialog_list" => &["dialogs"], + _ => &[], + }; + let keys: Vec<&str> = std::iter::once("title") + .chain(own.iter().copied()) + .collect(); + require(map, t, &keys) + }), "minecraft:worldgen/feature" | "minecraft:loot_table" => match t { Tag::Compound(_) => Ok(()), _ => Err(not_map(t)), diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e6931852a..79041beb5 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -18,6 +18,7 @@ pub mod tree_misc; pub mod tree_scoreboard; pub mod tree_world; pub mod vanilla; +mod vanilla_order; use crate::text::Text; pub use args::{Arg, ArgType, Registries}; diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-client/src/command/tree_extra.rs index 636aaf0db..a4f0d15ff 100644 --- a/crates/horizon-client/src/command/tree_extra.rs +++ b/crates/horizon-client/src/command/tree_extra.rs @@ -1,7 +1,6 @@ -//! Commands Horizon parses but does not run (multiplayer, profiling and -//! server-only features): `/dialog`, `/kick`, `/posteffect`, `/fetchprofile`, -//! `/spectate`, `/publish`, `/unpublish`, `/waypoint`, `/debug`, `/jfr` and -//! the `/test` root. +//! Commands of the hosted game rather than the world: `/dialog`, `/kick`, +//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`, +//! `/waypoint`, `/debug`, `/jfr` and `/test`. use super::{ Dispatcher, args::ArgType, @@ -126,7 +125,84 @@ pub fn register(d: &mut Dispatcher, root: usize) { d.executes(l, "jfr"); } - // TestCommand (game tests; only its root is modelled) + // TestCommand (release build: no export subcommands) let test = d.literal(root, "test"); d.requires(test, GAMEMASTERS); + let tests = ArgType::ResourceSelector("minecraft:test_instance"); + let int0 = ArgType::Integer { + min: 0, + max: i32::MAX, + }; + let int = ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }; + // numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only + // the first two. + let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| { + let n = d.argument(node, "numberOfTimes", int0.clone()); + d.executes(n, id); + let u = d.argument(n, "untilFailed", ArgType::Bool); + d.executes(u, id); + if build_info { + let r = d.argument(u, "rotationSteps", int.clone()); + d.executes(r, id); + let t = d.argument(r, "testsPerRow", int.clone()); + d.executes(t, id); + } + }; + let run = d.literal(test, "run"); + let t = d.argument(run, "tests", tests.clone()); + d.executes(t, "test.run"); + retry(d, t, "test.run", true); + let multiple = d.literal(test, "runmultiple"); + let t = d.argument(multiple, "tests", tests.clone()); + d.executes(t, "test.run"); + let a = d.argument(t, "amount", int.clone()); + d.executes(a, "test.run"); + for name in ["runthese", "runclosest", "runthat"] { + let l = d.literal(test, name); + d.executes(l, "test.run.found"); + retry(d, l, "test.run.found", false); + } + let failed = d.literal(test, "runfailed"); + d.executes(failed, "test.run.found"); + let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool); + d.executes(only, "test.run.found"); + retry(d, only, "test.run.found", true); + retry(d, failed, "test.run.found", true); + let verify = d.literal(test, "verify"); + let t = d.argument(verify, "tests", tests.clone()); + d.executes(t, "test.verify"); + let locate = d.literal(test, "locate"); + let t = d.argument(locate, "tests", tests); + d.executes(t, "test.locate"); + for name in [ + "resetclosest", + "resetthese", + "resetthat", + "clearthat", + "clearthese", + ] { + let l = d.literal(test, name); + d.executes(l, "test.clear"); + } + let all = d.literal(test, "clearall"); + d.executes(all, "test.clear"); + let r = d.argument(all, "radius", int.clone()); + d.executes(r, "test.clear"); + let stop = d.literal(test, "stop"); + d.executes(stop, "test.stop"); + let pos = d.literal(test, "pos"); + d.executes(pos, "test.pos"); + let var = d.argument(pos, "var", ArgType::Word); + d.executes(var, "test.pos"); + let create = d.literal(test, "create"); + let id = d.argument(create, "id", ArgType::Id("none")); + d.executes(id, "test.create"); + let w = d.argument(id, "width", int.clone()); + d.executes(w, "test.create"); + let h = d.argument(w, "height", int.clone()); + let depth = d.argument(h, "depth", int); + d.executes(depth, "test.create"); } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 495f36966..daf4ecf86 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -403,6 +403,7 @@ pub fn build_with(dev: bool) -> Dispatcher { super::tree_misc::register(&mut d, root); super::tree_world::register(&mut d, root); super::tree_extra::register(&mut d, root); + apply_vanilla_order(&mut d); d } @@ -506,6 +507,42 @@ pub fn game_modes() -> [&'static str; 4] { GameMode::ALL.map(GameMode::name) } /// The shared vanilla tree. +/// Reorder node children as vanilla registers them (Brigadier keeps +/// children in registration order; smart usage lists them that way). +fn apply_vanilla_order(d: &mut Dispatcher) { + for (path, order) in super::vanilla_order::ORDER { + let mut node = Some(0usize); + for name in path.split(' ').filter(|n| !n.is_empty()) { + node = node.and_then(|n| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + }); + } + let Some(n) = node else { continue }; + let mut children = d.nodes[n].children.clone(); + let rank = |c: usize| { + order + .iter() + .position(|o| *o == d.nodes[c].name()) + .unwrap_or(order.len()) + }; + children.sort_by_key(|&c| rank(c)); + d.nodes[n].children = children; + } +} +/// The tree the game runs: a release integrated server's, or with +/// `HORIZON_DEV_COMMANDS` set the development one +/// (SharedConstants.DEBUG_DEV_COMMANDS). +pub fn game_dispatcher() -> &'static Dispatcher { + if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { + dispatcher() + } else { + release_dispatcher() + } +} pub fn dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(build) diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-client/src/command/vanilla_order.rs new file mode 100644 index 000000000..fb7dcde2b --- /dev/null +++ b/crates/horizon-client/src/command/vanilla_order.rs @@ -0,0 +1,234 @@ +//! The order of node children in vanilla's command tree, for the nodes +//! where Horizon's tree registers them differently (path of node names +//! from the root, children in vanilla's order). Generated by +//! tools/generate_command_order.py; do not edit by hand. + +pub const ORDER: &[(&str, &[&str])] = &[ + ( + "", + &[ + "advancement", + "attribute", + "execute", + "bossbar", + "clear", + "clone", + "compute", + "damage", + "data", + "datapack", + "debug", + "defaultgamemode", + "dialog", + "difficulty", + "effect", + "me", + "enchant", + "experience", + "xp", + "fill", + "fillbiome", + "forceload", + "function", + "gamemode", + "gamerule", + "give", + "help", + "item", + "kick", + "kill", + "list", + "locate", + "loot", + "msg", + "tell", + "w", + "swing", + "particle", + "place", + "playsound", + "posteffect", + "random", + "reload", + "recipe", + "fetchprofile", + "return", + "ride", + "rotate", + "say", + "schedule", + "scoreboard", + "seed", + "version", + "setblock", + "spawnpoint", + "setworldspawn", + "spectate", + "spreadplayers", + "stopsound", + "stopwatch", + "summon", + "tag", + "team", + "teammsg", + "tm", + "teleport", + "tp", + "tellraw", + "test", + "tick", + "time", + "title", + "trigger", + "waypoint", + "weather", + "worldborder", + "jfr", + "publish", + "unpublish", + ], + ), + ( + "execute", + &[ + "run", + "if", + "unless", + "as", + "at", + "store", + "positioned", + "rotated", + "facing", + "align", + "anchored", + "in", + "summon", + "on", + ], + ), + ( + "execute if", + &[ + "block", + "biome", + "loaded", + "dimension", + "score", + "blocks", + "entity", + "predicate", + "function", + "stopwatch", + "data", + "items", + "slots", + ], + ), + ( + "execute unless", + &[ + "block", + "biome", + "loaded", + "dimension", + "score", + "blocks", + "entity", + "predicate", + "function", + "stopwatch", + "data", + "items", + "slots", + ], + ), + ("execute facing", &["entity", "pos"]), + ("datapack", &["enable", "disable", "list", "create"]), + ( + "datapack enable name", + &["after", "before", "last", "first"], + ), + ("item", &["replace", "fill", "override", "modify"]), + ("item replace entity target slots", &["from", "with"]), + ("item fill entity target slots", &["from", "with"]), + ("item override entity target slots", &["from", "with"]), + ( + "loot replace entity entities slot", + &["fish", "loot", "kill", "mine", "count"], + ), + ( + "loot replace entity entities slot fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot count fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace entity entities slot count mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot", + &["fish", "loot", "kill", "mine", "count"], + ), + ( + "loot replace block targetPos slot fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot count fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot replace block targetPos slot count mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot insert targetPos fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot insert targetPos mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot give players fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot give players mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot spawn targetPos fish loot_table pos", + &["tool", "mainhand", "offhand"], + ), + ( + "loot spawn targetPos mine pos", + &["tool", "mainhand", "offhand"], + ), + ( + "scoreboard players", + &[ + "list", + "set", + "get", + "add", + "remove", + "reset", + "enable", + "display", + "operation", + ], + ), +]; diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 2ead4d13a..0e04eab5e 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -152,9 +152,34 @@ impl Parser<'_> { Err("unterminated string".into()) } } +/// The style fields of a component object. +fn object_style(o: &serde_json::Map) -> Style { + let mut style = Style::default(); + if let Some(c) = o.get("color").and_then(Value::as_str) { + style.color = named_color(c).or_else(|| { + c.strip_prefix('#') + .and_then(|h| u32::from_str_radix(h, 16).ok()) + }); + } + let flag = |k: &str| o.get(k).and_then(Value::as_bool); + style.bold = flag("bold"); + style.italic = flag("italic"); + style.underlined = flag("underlined"); + style.strikethrough = flag("strikethrough"); + style.obfuscated = flag("obfuscated"); + style +} /// `ComponentSerialization.CODEC` decoding into text. `selector` components /// are resolved by `resolve` (ComponentUtils.updateForEntity). pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { + to_text_with(v, resolve, &mut |_| None) +} +/// `to_text` with a hook resolving other contents (`nbt`) from the object. +pub fn to_text_with( + v: &Value, + resolve: &mut dyn FnMut(&str) -> Text, + contents: &mut dyn FnMut(&serde_json::Map) -> Option, +) -> Text { match v { Value::String(s) => Text::literal(s.clone()), Value::Number(n) => Text::literal(n.to_string()), @@ -164,32 +189,27 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { let Some((first, rest)) = list.split_first() else { return Text::empty(); }; - let mut base = to_text(first, resolve); - let style = base - .spans - .first() - .map(|s| s.style.clone()) - .unwrap_or_default(); + let mut base = to_text_with(first, resolve, contents); + // The siblings take the first component's own style, even when + // its text is empty. + let style = match first { + Value::Object(o) => object_style(o), + _ => base + .spans + .first() + .map(|s| s.style.clone()) + .unwrap_or_default(), + }; for sibling in rest { - base.push(to_text(sibling, resolve).with_style(&style)); + base.push(to_text_with(sibling, resolve, contents).with_style(&style)); } base } Value::Object(o) => { - let mut style = Style::default(); - if let Some(c) = o.get("color").and_then(Value::as_str) { - style.color = named_color(c).or_else(|| { - c.strip_prefix('#') - .and_then(|h| u32::from_str_radix(h, 16).ok()) - }); - } - let flag = |k: &str| o.get(k).and_then(Value::as_bool); - style.bold = flag("bold"); - style.italic = flag("italic"); - style.underlined = flag("underlined"); - style.strikethrough = flag("strikethrough"); - style.obfuscated = flag("obfuscated"); - let content = if let Some(t) = o.get("text") { + let style = object_style(o); + let content = if let Some(t) = contents(o) { + t + } else if let Some(t) = o.get("text") { match t { Value::String(s) => Text::literal(s.clone()), other => Text::literal(other.to_string()), @@ -198,7 +218,11 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { let args: Vec = o .get("with") .and_then(Value::as_array) - .map(|a| a.iter().map(|x| to_text(x, resolve)).collect()) + .map(|a| { + a.iter() + .map(|x| to_text_with(x, resolve, contents)) + .collect() + }) .unwrap_or_default(); let translated = Text::translate(key, &args); match o.get("fallback").and_then(Value::as_str) { @@ -219,7 +243,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text { .into_iter() .flatten() { - out.push(to_text(extra, resolve).with_style(&style)); + out.push(to_text_with(extra, resolve, contents).with_style(&style)); } out } diff --git a/crates/horizon-client/src/datapack.rs b/crates/horizon-client/src/datapack.rs index d0874ac03..b76a4f243 100644 --- a/crates/horizon-client/src/datapack.rs +++ b/crates/horizon-client/src/datapack.rs @@ -67,6 +67,15 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec) { } } } +impl DataPack { + /// The built-in `vanilla` pack: the game's own data directory. + pub fn builtin(root: &Path) -> Self { + DataPack { + id: "vanilla".into(), + source: Source::Dir(root.to_path_buf()), + } + } +} /// The packs in `/datapacks`, sorted by name. pub fn discover(world: &Path) -> Vec { let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else { diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 043723cbf..8a8a598f7 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -11,6 +11,10 @@ struct Globals { sun: vec4, // x: sky fog end, y: cloud fog end fog_ends: vec4, + // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. + end_portal_sprites: array, 2>, + // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) + time: vec4, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -27,11 +31,14 @@ struct Out { @location(4) @interpolate(flat) overlay: u32, // Overlay 6: the sprite's v origin and height, for v repeated inside it. @location(6) @interpolate(flat) wrap: vec2, + // Overlays 9 and 10: projection_from_position(gl_Position), the End portal's texProj0. + @location(7) proj: vec4, } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4) -> Out { var out: Out; out.clip = globals.view_proj * vec4(position, 1.0); + out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw); out.uv = uv; let l = vec2(f32(light.y), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, @@ -52,6 +59,41 @@ struct Out { if overlay == 4u { out.spherical = length(position); } return out; } +// rendertype_end_portal.fsh: the layer colours. +const PORTAL_COLORS = array, 16>( + vec3(0.022087, 0.098399, 0.110818), + vec3(0.011892, 0.095924, 0.089485), + vec3(0.027636, 0.101689, 0.100326), + vec3(0.046564, 0.109883, 0.114838), + vec3(0.064901, 0.117696, 0.097189), + vec3(0.063761, 0.086895, 0.123646), + vec3(0.084817, 0.111994, 0.166380), + vec3(0.097489, 0.154120, 0.091064), + vec3(0.106152, 0.131144, 0.195191), + vec3(0.097721, 0.110188, 0.187229), + vec3(0.133516, 0.138278, 0.148582), + vec3(0.070006, 0.243332, 0.235792), + vec3(0.196766, 0.142899, 0.214696), + vec3(0.047281, 0.315338, 0.321970), + vec3(0.204675, 0.390010, 0.302066), + vec3(0.080955, 0.314821, 0.661491), +); +// textureProj on a repeating texture that lives in the atlas at `rect`. +fn portal_sample(rect: vec4, p: vec4) -> vec3 { + let st = fract(p.xy / p.w); + return textureSampleLevel(atlas, atlas_sampler, rect.xy + st * rect.zw, 0.0).rgb; +} +// texProj0 * end_portal_layer(layer): the row vector through mat4(scale * rotate), +// translate and SCALE_TRANSLATE in turn. +fn portal_layer(p: vec4, layer: f32) -> vec4 { + let a = radians((layer * layer * 4321.0 + layer * 9.0) * 2.0); + let c = cos(a); + let s = sin(a); + let k = (4.5 - layer / 4.0) * 2.0; + var v = vec4(k * (c * p.x - s * p.y), k * (s * p.x + c * p.y), p.z, p.w); + v = vec4(v.x + 17.0 / layer * v.w, v.y + (2.0 + layer / 1.5) * (globals.time.x * 1.5) * v.w, v.z, v.w); + return vec4(0.5 * v.x + 0.25 * v.w, 0.5 * v.y + 0.25 * v.w, v.z, v.w); +} fn linear_fog(d: f32, start: f32, end: f32) -> f32 { if d <= start { return 0.0; } if d >= end { return 1.0; } @@ -61,7 +103,16 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } var color = textureSample(atlas, atlas_sampler, uv) * in.color; - if in.overlay == 4u { + if in.overlay == 9u || in.overlay == 10u { + // rendertype_end_portal: end_sky and PORTAL_LAYERS (15 for portals, 16 + // for gateways) layers of end_portal.png projected from the screen. + let layers = select(15, 16, in.overlay == 10u); + var c = portal_sample(globals.end_portal_sprites[0], in.proj) * PORTAL_COLORS[0]; + for (var i = 0; i < layers; i++) { + c += portal_sample(globals.end_portal_sprites[1], portal_layer(in.proj, f32(i + 1))) * PORTAL_COLORS[i]; + } + color = vec4(c, 1.0); + } else if in.overlay == 4u { // clouds.fsh: alpha fades out towards the cloud fog end. return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y))); } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index f5f9306db..1afcd4f91 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -407,7 +407,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } // Skeletons are spawned holding a bow (finalizeSpawn); a mob loaded // from NBT keeps only its saved equipment. - "minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" if raw.is_none() => { + "minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" + if raw.is_none() && m.extra.main_hand.as_deref() == Some("minecraft:bow") => + { map.entry("equipment".into()).or_insert_with(|| { Tag::compound([( "mainhand", @@ -1118,6 +1120,25 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> { put(&mut tag, "Health", Tag::Float(20f32.to_bits())); } + // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. + if let Tag::Compound(map) = &mut tag { + for (key, value) in [ + ("HurtTime", Tag::Short(0)), + ("DeathTime", Tag::Short(0)), + ("AbsorptionAmount", Tag::Float(0)), + ("FallFlying", Tag::Byte(0)), + ("current_impulse_context_reset_grace_time", Tag::Int(0)), + ("attributes", Tag::List(Vec::new())), + ( + "Brain", + Tag::compound([("memories", Tag::Compound(Compound::new()))]), + ), + ("DisabledSlots", Tag::Int(0)), + ("Pose", Tag::Compound(Compound::new())), + ] { + map.entry(key.into()).or_insert(value); + } + } tag } pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client/src/fastutil_order.rs new file mode 100644 index 000000000..6065763d2 --- /dev/null +++ b/crates/horizon-client/src/fastutil_order.rs @@ -0,0 +1,153 @@ +//! Iteration order of fastutil's `Object2ObjectOpenHashMap` (open +//! addressing with linear probing, backward-shift deletion and rehashing at +//! the load factor), for the vanilla collections whose order commands show: +//! the scoreboard's objectives and teams. + +/// The keys of an open hash map in their table slots. +#[derive(Clone, Debug, PartialEq)] +pub struct OpenOrder { + keys: Vec>, + size: usize, + min_n: usize, + load: f32, +} +impl Default for OpenOrder { + /// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75. + fn default() -> Self { + Self::new(16, 0.75) + } +} +/// `String.hashCode`. +fn java_hash(s: &str) -> i32 { + s.encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) +} +/// `HashCommon.mix`. +fn mix(x: i32) -> usize { + let h = (x as u32).wrapping_mul(0x9E37_79B9); + (h ^ (h >> 16)) as usize +} +/// `HashCommon.arraySize`. +fn array_size(expected: usize, f: f32) -> usize { + let wanted = (expected as f64 / f64::from(f)).ceil() as usize; + wanted.max(2).next_power_of_two() +} +impl OpenOrder { + pub fn new(expected: usize, load: f32) -> Self { + let n = array_size(expected, load); + Self { + keys: vec![None; n], + size: 0, + min_n: n, + load, + } + } + fn max_fill(&self) -> usize { + ((self.keys.len() as f64 * f64::from(self.load)).ceil() as usize).min(self.keys.len() - 1) + } + fn slot(&self, key: &str) -> usize { + mix(java_hash(key)) & (self.keys.len() - 1) + } + pub fn insert(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + while let Some(k) = &self.keys[pos] { + if k == key { + return; + } + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key.to_owned()); + self.size += 1; + if self.size >= self.max_fill() { + self.rehash(array_size(self.size + 1, self.load)); + } + } + pub fn remove(&mut self, key: &str) { + let mask = self.keys.len() - 1; + let mut pos = self.slot(key); + loop { + match &self.keys[pos] { + None => return, + Some(k) if k == key => break, + Some(_) => pos = (pos + 1) & mask, + } + } + self.size -= 1; + self.shift_keys(pos); + let n = self.keys.len(); + if n > self.min_n && self.size < self.max_fill() / 4 && n > 16 { + self.rehash(n / 2); + } + } + fn shift_keys(&mut self, mut pos: usize) { + let mask = self.keys.len() - 1; + loop { + let last = pos; + pos = (last + 1) & mask; + loop { + let Some(curr) = self.keys[pos].clone() else { + self.keys[last] = None; + return; + }; + let slot = self.slot(&curr); + let stop = if last <= pos { + last >= slot || slot > pos + } else { + last >= slot && slot > pos + }; + if stop { + self.keys[last] = Some(curr); + break; + } + pos = (pos + 1) & mask; + } + } + } + fn rehash(&mut self, new_n: usize) { + let old = std::mem::replace(&mut self.keys, vec![None; new_n]); + let mask = new_n - 1; + for key in old.into_iter().rev().flatten() { + let mut pos = mix(java_hash(&key)) & mask; + while self.keys[pos].is_some() { + pos = (pos + 1) & mask; + } + self.keys[pos] = Some(key); + } + } + /// The iteration order (`keySet().iterator()`: from the last slot down). + pub fn keys(&self) -> impl Iterator { + self.keys.iter().rev().flatten().map(String::as_str) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hash_and_order() { + assert_eq!( + java_hash("harness"), + "harness" + .chars() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32)) + ); + let mut o = OpenOrder::new(16, 0.5); + for k in ["harness", "harness_h"] { + o.insert(k); + } + let keys: Vec<&str> = o.keys().collect(); + assert_eq!(keys.len(), 2); + o.remove("harness"); + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + for i in 0..40 { + o.insert(&format!("k{i}")); + } + assert_eq!(o.keys().count(), 41); + for i in 0..40 { + o.remove(&format!("k{i}")); + } + assert_eq!(o.keys().collect::>(), vec!["harness_h"]); + } +} diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index a69e3f030..aba0581c6 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -451,6 +451,72 @@ impl Font { .sum::() .ceil() } + /// `StringSplitter.splitLines`: each line and whether it continues a + /// wrapped one. A line breaks at a `\n`, or once a character overflows + /// `max_width` (never the first visible one) at the last space so far, or + /// before that character; the `\n` or space at the break is dropped. + pub fn split_lines(&self, t: &Text, max_width: f32) -> Vec<(Text, bool)> { + let max_width = max_width.max(1.0); + let chars: Vec<(char, &Style)> = t.chars().collect(); + let n = chars.len(); + let mut out = Vec::new(); + let (mut start, mut wrapped, mut force_new_line) = (0, false, false); + loop { + // LineBreakFinder over what is left. + let (mut width, mut had_visible, mut last_space) = (0.0f32, false, None); + let mut split = None; + for (i, &(c, style)) in chars.iter().enumerate().skip(start) { + if c == '\n' { + split = Some(i); + break; + } + if c == ' ' { + last_space = Some(i); + } + let advance = self.advance(c, style); + width += advance; + if !had_visible || width <= max_width { + had_visible |= advance != 0.0; + } else { + split = Some(last_space.unwrap_or(i)); + break; + } + } + let Some(at) = split else { break }; + let new_line = chars[at].0 == '\n'; + let skip = usize::from(new_line || chars[at].0 == ' '); + force_new_line = new_line; + out.push((t.slice(start, at), wrapped)); + wrapped = !new_line; + start = at + skip; + } + if start < n { + out.push((t.slice(start, n), wrapped)); + } else if force_new_line { + out.push((Text::empty(), false)); + } + out + } + /// `ComponentRenderUtils.wrapComponents`: the split lines, wrapped ones + /// indented by an unstyled space; one empty line for empty text. + pub fn wrap_components(&self, t: &Text, max_width: i32) -> Vec { + let lines: Vec = self + .split_lines(t, max_width as f32) + .into_iter() + .map(|(line, wrapped)| { + if wrapped { + Text::literal(" ").append(line) + } else { + line + } + }) + .collect(); + if lines.is_empty() { + vec![Text::empty()] + } else { + lines + } + } /// StringSplitter.splitLines: wrap at the last space that fits (or /// mid-word when none does); `\n` always breaks. Styles are kept. pub fn split(&self, t: &Text, max_width: f32) -> Vec { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..642ddb08f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6,6 +6,7 @@ mod allays; mod armor_stands; mod banners; mod beacon; +mod block_entity_anims; mod blockctl; mod boats; mod books; @@ -14,6 +15,7 @@ mod breezes; mod cartography; mod chat; mod combat; +mod command_harness; mod commands; mod control; mod creaking; @@ -109,7 +111,7 @@ use horizon_client::{ environment::Environment, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, - hud_layout, + hud_layout, hud_overlays, items::{ItemStack, Items}, keymapping::KeyAction, light::LightTables, @@ -612,7 +614,8 @@ struct Game<'a> { raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, - chest_open: HashMap<(i32, i32, i32), (f32, f32)>, + /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). + be_anims: horizon_client::block_entity_anim::BlockEntityAnims, /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, /// Camera.oldFovModifier / fovModifier. @@ -635,6 +638,8 @@ struct Game<'a> { /// The source of a command run through /execute (the player otherwise). command_source: Option, titles: titles::Titles, + /// `Hud.toolHighlightTimer`: the selected item name. + tool_highlight: horizon_client::hud_overlays::ToolHighlight, applied_modifiers: Vec<(String, String)>, experience: Experience, orbs: Vec, @@ -679,6 +684,8 @@ struct Game<'a> { map_frame_model: frames::FrameModel, glow_map_frame_model: frames::FrameModel, armor_stands: Vec, + /// Entities of types Horizon does not simulate. + others: Vec, armor_stand_assets: armor_stands::ArmorStandAssets, boats: Vec, boat_models: boats::BoatModels, @@ -738,7 +745,9 @@ struct Game<'a> { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_acting: Option, /// Command feedback to forward to a guest. - chat_capture: Option>, + chat_capture: Option>, + /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. + cmds: commands::extra::CommandExtras, /// Allow Cheats: whether guests may be given commands. cheats: bool, ui: chat::UiState, @@ -781,6 +790,13 @@ impl Dim { _ => Self::Overworld, } } + /// `Level.getMaxY`: the dimension type's minimum y plus height, less one. + fn max_y(self) -> i32 { + match self { + Self::Overworld => MIN_Y + HEIGHT - 1, + Self::Nether | Self::End => 255, + } + } } fn facing_offset(facing: &str) -> [i32; 3] { match facing { @@ -1585,6 +1601,9 @@ impl Game<'_> { state, kind: "shrieker_respond", } => self.shrieker_block_event(pos, state), + LevelEvent::BlockEntityEvent { pos, a, b, .. } => { + self.block_entity_event([pos.x, pos.y, pos.z], a, b) + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} @@ -1609,6 +1628,7 @@ impl Game<'_> { self.craft_size = 3; } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); + self.container_opener_event(key, true); let at = [ f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, @@ -1621,9 +1641,12 @@ impl Game<'_> { self.world.block_entities.entry(key).or_insert_with(|| { BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new())) }); + } else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) { + // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); + self.container_opener_event(key, true); self.post_block_game_event( "minecraft:container_open", [key.0, key.1, key.2], @@ -1860,6 +1883,7 @@ impl Game<'_> { let name = facts.name.clone(); self.release_contents(pos, entity, &name); if self.container == Some((pos[0], pos[1], pos[2])) { + self.container_opener_event((pos[0], pos[1], pos[2]), false); self.container = None; self.screen = Screen::Playing; } @@ -2500,6 +2524,8 @@ impl Game<'_> { } self.apply_totem(); self.update_totem_ready(); + self.tick_command_extras(); + let camera_eye = self.camera_eye_height(); if self.riding.is_some() && self.player.is_some() { let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); @@ -2597,7 +2623,7 @@ impl Game<'_> { } let feet = [player.position.x, player.position.y, player.position.z]; self.previous_eye = self.eye; - self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); self.record_combat(&events); @@ -2707,7 +2733,7 @@ impl Game<'_> { self.tick_effects(); self.tick_burning(); self.tick_using(); - self.titles.tick(); + self.tick_hud(); if running { self.tick_paintings(); self.tick_item_frames(); @@ -2749,17 +2775,10 @@ impl Game<'_> { self.tick_sculk()?; self.tick_brewing_stands()?; } - if let Some(r) = &self.renderer { - let eye = self.player.as_ref().map(|p| { - [ - p.position.x, - p.position.y + f64::from(self.eye), - p.position.z, - ] - }); - self.res.block_entity_render.tick(r.block_entities(), eye); - } if running { + // ClientLevel.tickBlockEntities (not while paused or frozen): + // chest lids, books, shulker boxes, bells, conduits, heads. + self.tick_block_entity_anims(); self.tick_particles(); } if self.right && self.use_delay == 0 && self.screen == Screen::Playing { @@ -2854,26 +2873,30 @@ impl Game<'_> { // `GuiGraphics.renderItem`: the resolved item model (tints, foil and // special renderers included), then the decorations. self.draw_item_model(batch, stack, x, y); - let atlas = &self.res.atlas; - if stack.count > 1 { - let text = stack.count.to_string(); - let w = HudBatch::text_width(atlas, &text); - batch.text(atlas, &text, x + 17.0 - w, y + 9.0, u32::MAX, true); - } - if let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 - && stack.damage > 0 - { - let f = 1.0 - stack.damage as f32 / info.max_damage as f32; - let width = (13.0 * f).round(); - let hue = f / 3.0; - let (r, g) = ( - (255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8, - (255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8, - ); - batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255)); - batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255)); - } + // GuiGraphicsExtractor.itemDecorations, laid out at the origin and + // moved to (x, y). Horizon tracks no item cooldowns to shade yet. + let max_damage = self + .res + .items + .get(&stack.item) + .map_or(0, |info| info.max_damage as i32); + let decorations = hud_overlays::ItemDecorations { + count: stack.count, + count_text: None, + bar: hud_overlays::damage_bar(stack.damage as i32, max_damage), + cooldown: 0.0, + }; + let mut draws = vec![hud_layout::GuiDraw::Push(vec![ + hud_layout::PoseOp::Translate(x, y), + ])]; + draws.extend(hud_overlays::item_decorations( + 0, + 0, + &decorations, + &self.res.atlas.font, + )); + draws.push(hud_layout::GuiDraw::Pop); + hud_layout::paint(batch, &self.res.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = HudBatch::new(size); @@ -2941,8 +2964,12 @@ impl Game<'_> { } self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). - self.draw_boss_bar(&mut batch); - self.draw_custom_bossbars(&mut batch, 12.0 + 19.0 * self.builtin_bar_count() as f32); + self.draw_boss_bars(&mut batch); + // Hud.extractSleepOverlay, under the sidebar, titles and chat. + if let Some((_, ticks)) = self.sleeping { + let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); + hud_layout::paint(&mut batch, &self.res.atlas, &draws); + } self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); @@ -3012,6 +3039,9 @@ impl Game<'_> { let draws = self.health_hud.layout(&inputs, wi, hi); hud_layout::paint(&mut batch, atlas, &draws); } + if !spectator { + self.draw_selected_name(&mut batch, !self.creative); + } let atlas = &self.res.atlas; if self.debug { let p = self @@ -3113,12 +3143,6 @@ impl Game<'_> { batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true); } self.draw_chat(&mut batch); - let atlas = &self.res.atlas; - if let Some((_, ticks)) = self.sleeping { - // Gui sleep overlay fading in over 100 ticks. - let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8; - batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a)); - } match self.screen { Screen::Paused => self.draw_pause_menu(&mut batch), Screen::Dead => self.draw_death_screen(&mut batch), @@ -3470,6 +3494,7 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { + self.container_opener_event(key, false); self.post_block_game_event( "minecraft:container_close", [key.0, key.1, key.2], @@ -4115,14 +4140,8 @@ impl Game<'_> { } // Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls... if let Some(r) = &self.renderer { - let lid = |p: [i32; 3]| { - let (prev, cur) = self - .chest_open - .get(&(p[0], p[1], p[2])) - .copied() - .unwrap_or((0.0, 0.0)); - prev + (cur - prev) * alpha as f32 - }; + let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32); + let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32); let (view_yaw, view_pitch) = if self.camera_type == perspective::CameraType::ThirdPersonFront { (self.yaw + 180.0, -self.pitch) @@ -4138,10 +4157,11 @@ impl Game<'_> { -view_pitch.to_radians(), 0.0, ), - anim: &|_| horizon_client::block_entity_render::BlockAnim::default(), + anim: &anim, texts: None, partial: alpha as f32, game_time: self.world.game_time, + max_y: self.dim.max_y(), world: &self.world, sprites: &self.res.atlas.sprites, nether: self.dim == Dim::Nether, @@ -4603,20 +4623,6 @@ impl Game<'_> { 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)); - } - let open = self.container; - self.chest_open.retain(|k, (prev, cur)| { - *prev = *cur; - *cur = if Some(*k) == open { - (*cur + 0.1).min(1.0) - } else { - (*cur - 0.1).max(0.0) - }; - *cur > 0.0 || *prev > 0.0 - }); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -5001,6 +5007,11 @@ impl Game<'_> { self.restore_effects(); self.mining = None; self.container = None; + let kinds = std::mem::take(&mut self.be_anims.kinds); + self.be_anims = horizon_client::block_entity_anim::BlockEntityAnims { + kinds, + ..Default::default() + }; self.carried = None; self.using = None; self.screen = Screen::Playing; @@ -7079,6 +7090,14 @@ impl Game<'_> { hand: &hand, screen: &screen, game_time: self.world.game_time as f32, + shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0, + end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { + self.res + .atlas + .sprites + .get(n) + .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) + }), ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), night_vision: self.night_vision_intensity(), @@ -8035,7 +8054,11 @@ pub fn run() -> Result<()> { raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), - chest_open: HashMap::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry_owner.registry); + anims + }, using: None, view: Default::default(), limiter: horizon_client::window::FramerateLimiter::new(0), @@ -8048,6 +8071,7 @@ pub fn run() -> Result<()> { shield_cooldown: 0, command_source: None, titles: Default::default(), + tool_highlight: Default::default(), applied_modifiers: Vec::new(), experience: Experience::default(), orbs: Vec::new(), @@ -8083,6 +8107,7 @@ pub fn run() -> Result<()> { map_frame_model: frames::bake_frame(&root, "item_frame_map"), glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), armor_stands: Vec::new(), + others: Vec::new(), armor_stand_assets: armor_stands::ArmorStandAssets::load(&root), boats: Vec::new(), boat_models: boats::BoatModels::load(&root), @@ -8126,6 +8151,7 @@ pub fn run() -> Result<()> { lan_events: Vec::new(), lan_acting: None, chat_capture: None, + cmds: Default::default(), cheats: true, ui: Default::default(), combat: Default::default(), @@ -8172,6 +8198,12 @@ pub fn run() -> Result<()> { } None => game.title = Some(Title::new(std::env::current_dir()?.join("saves"))), } + if let (Some(script), Some(output)) = ( + std::env::var_os("HORIZON_COMMAND_SCRIPT"), + std::env::var_os("HORIZON_COMMAND_OUTPUT"), + ) { + return game.run_command_harness(script.as_ref(), output.as_ref()); + } EventLoop::new()?.run_app(&mut game)?; if let Some(path) = &game.options.report { let report = serde_json::json!({ diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 6742e7043..3c8a406cc 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -168,6 +168,12 @@ fn now_text() -> String { rem % 60 ) } +impl Game<'_> { + /// `ItemPredicate.test` (the `item_filter` of a filtered item modifier). + pub(super) fn loot_item_filter(&self, predicate: &Value, s: &ItemStack) -> bool { + adv::item(predicate, &item_view(s), &View(self)) + } +} pub(super) fn item_view(s: &ItemStack) -> ItemView { ItemView { id: s.item.to_string(), @@ -505,6 +511,17 @@ impl Game<'_> { return; } self.check_inventory_trigger(); + // ServerPlayer.tick: PlayerTrigger.TICK every tick. + let me = self.player_entity(); + self.trigger("minecraft:tick", |c, w| { + let ctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &ctx, w) + }); if self.ticks.is_multiple_of(20) { let me = self.player_entity(); self.trigger("minecraft:location", |c, w| { diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs new file mode 100644 index 000000000..d1597a7a3 --- /dev/null +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -0,0 +1,291 @@ +//! The client side of animated block entities (`horizon_client::block_entity_anim`): +//! their client tickers (`Level.tickBlockEntities` on the client level) and +//! the block events that drive them (`ClientboundBlockEventPacket` reaching +//! `BlockEntity.triggerEvent`). The renderer reads the resulting state through +//! [`Game::block_anim`] and [`Game::chest_lid`]. +use super::Game; +use horizon_client::{ + block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker}, + block_entity_render::BlockAnim, + collisions::{SceneCollisions, no_collision_empty}, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use std::collections::HashMap; + +/// The handle of the local player among a bell's gathered entities. +const PLAYER: u64 = u64::MAX; + +impl Game<'_> { + /// `BlockEntity.triggerEvent(a, b)` on the client copy of the block entity at `pos`. + pub(super) fn block_entity_event(&mut self, pos: [i32; 3], a: i32, b: i32) { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + let time = self.world.game_time; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + self.be_anims + .chests + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Shulker { .. }) => { + self.be_anims + .shulkers + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Bell) => { + let gathered = self.bell_gather(pos); + self.be_anims + .bells + .entry(pos) + .or_default() + .trigger_event(a, b, time, || gathered); + } + Some(Ticker::Pot) => { + self.be_anims + .pots + .entry(pos) + .or_default() + .trigger_event(a, b, time); + } + _ => {} + } + } + /// A player opened (`open`) or closed the container at `key`: the opener + /// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity` + /// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes, + /// on both halves of a double chest (`CompoundContainer`). + pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) { + // Spectators never count as openers. + if self.spectator() { + return; + } + let pos = [key.0, key.1, key.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + let count = i32::from(open); + self.block_entity_event(pos, 1, count); + if let Some(other) = self.chest_other_half(key) { + self.block_entity_event([other.0, other.1, other.2], 1, count); + } + } + Some(Ticker::Shulker { .. }) => { + let shulker = self.be_anims.shulkers.entry(pos).or_default(); + let (count, _) = if open { + shulker.start_open() + } else { + shulker.stop_open() + }; + self.block_entity_event(pos, 1, count); + } + _ => {} + } + } + /// `BellBlockEntity.updateEntities`: the living entities whose bounding + /// box meets the bell's block box inflated by 48. + fn bell_gather(&self, pos: [i32; 3]) -> Vec { + let area = Aabb::new( + Vec3::new( + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + ), + Vec3::new( + f64::from(pos[0]) + 49.0, + f64::from(pos[1]) + 49.0, + f64::from(pos[2]) + 49.0, + ), + ); + let mut out = Vec::new(); + if self + .player_view() + .is_some_and(|p| p.bounds.intersects(area)) + { + out.push(PLAYER); + } + for m in &self.mobs { + if !m.removed && m.bounds().intersects(area) { + out.push(u64::from(m.id)); + } + } + out + } + /// `ShulkerBoxBlock.canOpen`: a closed box opens only when its lid has + /// room to rise (`level.noCollision` of the half-open lid box). + pub(super) fn shulker_can_open(&self, pos: [i32; 3]) -> bool { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + let Some(Ticker::Shulker { facing }) = self.be_anims.ticker(state) else { + return true; + }; + let closed = self + .be_anims + .shulkers + .get(&pos) + .is_none_or(|s| s.status == ShulkerStatus::Closed); + if !closed { + return true; + } + let b = Shulker::lid_box(pos, facing); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + no_collision_empty( + &mut scene, + Aabb::new(Vec3::new(b[0], b[1], b[2]), Vec3::new(b[3], b[4], b[5])), + ) + } + /// The client tickers of the loaded animated block entities, once per + /// client tick (`ClientLevel.tickBlockEntities`). + pub(super) fn tick_block_entity_anims(&mut self) { + let Some(r) = &self.renderer else { + return; + }; + let present: HashMap<[i32; 3], Ticker> = r + .block_entities() + .filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) + .collect(); + self.be_anims.retain_present(&present); + let players: Vec<[f64; 3]> = match &self.player { + Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]], + _ => Vec::new(), + }; + let raiders = self + .res + .stations + .enchantments + .entity_tags + .get("minecraft:raiders") + .cloned() + .unwrap_or_default(); + let frames = self + .res + .items + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect(); + positions.sort_unstable_by_key(|(p, _)| *p); + for (pos, ticker) in positions { + match ticker { + Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(), + Ticker::Book => { + let anims = &mut self.be_anims; + anims + .books + .entry(pos) + .or_default() + .tick(pos, &players, &mut anims.book_random); + } + Ticker::Shulker { facing } => { + // The lid's push of entities in its way (moveCollidedEntities) + // and the neighbour updates are left to the level. + self.be_anims + .shulkers + .entry(pos) + .or_default() + .tick(pos, facing); + } + Ticker::Skull { powered } => { + self.be_anims.skulls.entry(pos).or_default().tick(powered); + } + Ticker::Bell => { + let player = self.player_view().map(|p| BellEntity { + position: [p.position.x, p.position.y, p.position.z], + alive: p.alive, + raider: false, + }); + let mobs = &self.mobs; + let entity = |h: u64| { + if h == PLAYER { + return player; + } + let m = mobs.iter().find(|m| u64::from(m.id) == h)?; + Some(BellEntity { + position: [m.position.x, m.position.y, m.position.z], + alive: m.alive() && !m.removed, + raider: raiders.contains(&m.kind.id), + }) + }; + let tick = self + .be_anims + .bells + .entry(pos) + .or_default() + .tick(pos, entity); + let centre = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + if tick.resonate { + // The server's copy plays the resonance for everyone. + self.audio + .play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0); + } + if let Some((particles, glow)) = tick.ended { + for (p, color) in particles { + // ColorParticleOption.create(ENTITY_EFFECT, color): ARGB. + let c = color as u32; + let channel = |shift: u32| ((c >> shift) & 255) as f32 / 255.0; + let options = ParticleOptions { + color: [channel(16), channel(8), channel(0), channel(24)], + ..ParticleOptions::simple(ParticleType::EntityEffect) + }; + self.particles.add(&options, p, [0.0; 3]); + } + // makeRaidersGlow. + for m in self.mobs.iter_mut() { + if glow.contains(&u64::from(m.id)) { + m.add_effect("minecraft:glowing", 60, 0); + } + } + } + } + Ticker::Conduit => { + let world = &self.world; + let facts = &self.res.facts; + let registry = self.res.assets.registry; + let is_water = |p: [i32; 3]| { + facts.get(world.block(p[0], p[1], p[2])).fluid + == horizon_client::blocks::Fluid::Water + }; + let is_frame = |p: [i32; 3]| { + registry + .state(world.block(p[0], p[1], p[2])) + .is_some_and(|s| frames.contains(&s.name)) + }; + let time = world.game_time; + let anims = &mut self.be_anims; + let particles = anims.conduits.entry(pos).or_default().client_tick( + pos, + time, + is_water, + is_frame, + None, + self.particles.random(), + ); + let nautilus = ParticleOptions::simple(ParticleType::Nautilus); + for (p, v) in particles { + self.particles.add(&nautilus, p, v); + } + } + Ticker::Pot => {} + } + } + } + /// The renderer's view of the block entity at `pos`. + pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { + self.be_anims + .block_anim(pos, self.world.game_time, partial, Default::default()) + } + /// `ChestLidController.getOpenness(partial)` at `pos`. + pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.be_anims.lid(pos, partial) + } +} diff --git a/crates/horizon-client/src/game/bossbars.rs b/crates/horizon-client/src/game/bossbars.rs index 2863546ac..ec7b72632 100644 --- a/crates/horizon-client/src/game/bossbars.rs +++ b/crates/horizon-client/src/game/bossbars.rs @@ -4,10 +4,9 @@ use super::{ commands::{R, err}, }; use horizon_client::{ - bossbar::BossBars, + bossbar::{self, BossBars}, command::{Arg, Context}, - hud::{HudBatch, rgba}, - save, + hud_overlays, save, scoreboard::{self as sb, Comp, comp_text}, scoreboard_cmd::format_list, text::Text, @@ -334,26 +333,10 @@ impl Game<'_> { Ok(self.resolve_component(value)) } - /// How many boss bars the dragon and withers already show. - pub(super) fn builtin_bar_count(&self) -> usize { - let dragon = usize::from(self.dragon.is_some() && self.dim == super::Dim::End); - let withers = self.player.as_ref().map_or(0, |p| { - self.mobs - .iter() - .filter(|m| { - m.species() == horizon_client::mobs::Species::Wither - && m.alive() - && m.position.distance_squared(p.position) <= 64.0 * 64.0 - }) - .count() - }); - dragon + withers - } // ---- drawing ------------------------------------------------------------------ - /// `BossHealthOverlay`: the visible custom bars under the built-in ones. - pub(super) fn draw_custom_bossbars(&self, batch: &mut HudBatch, mut y: f32) { - let atlas = &self.res.atlas; + /// The visible custom bars (`/bossbar`), after the built-in ones. + pub(super) fn custom_bossbars(&self, bars: &mut Vec) { for b in self .bosses .bars @@ -361,44 +344,18 @@ impl Game<'_> { .iter() .filter(|b| b.visible && b.player) { - if y >= batch.height / 3.0 { - break; - } - let x = (batch.width / 2.0 - 91.0).floor(); - let sprite = |kind: &str| format!("gui/sprites/boss_bar/{kind}"); - batch.sprite(atlas, &sprite(&format!("{}_background", b.color)), x, y); - if b.progress() > 0.0 { - batch.sprite_part( - atlas, - &sprite(&format!("{}_progress", b.color)), - x, - y, - b.progress(), - ); - } - if b.style != "progress" { - batch.sprite(atlas, &sprite(&format!("{}_background", b.style)), x, y); - if b.progress() > 0.0 { - batch.sprite_part( - atlas, - &sprite(&format!("{}_progress", b.style)), - x, - y, - b.progress(), - ); - } - } - let name = comp_text(&b.name); - let w = atlas.font.width_text(&name); - batch.text_styled( - atlas, - &name, - (batch.width / 2.0 - w / 2.0).floor(), - y - 9.0, - rgba(255, 255, 255, 255), - true, - ); - y += 19.0; + bars.push(hud_overlays::BossBar { + name: comp_text(&b.name), + progress: b.progress(), + color: bossbar::COLORS + .iter() + .position(|c| *c == b.color) + .unwrap_or(0), + overlay: bossbar::STYLES + .iter() + .position(|s| *s == b.style) + .unwrap_or(0), + }); } } } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 812ac6118..c4c235aca 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -286,7 +286,11 @@ impl Game<'_> { reg.structures = list("data/minecraft/worldgen/structure"); reg.biomes = list("data/minecraft/worldgen/biome"); reg.clocks = list("data/minecraft/world_clock"); - reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()]; + reg.dimensions = vec![ + "minecraft:overworld".into(), + "minecraft:the_nether".into(), + "minecraft:the_end".into(), + ]; reg.players = vec![PLAYER_NAME.into()]; // Timelines of the overworld clock and their time markers. self.ui.markers.clear(); @@ -324,6 +328,15 @@ impl Game<'_> { ); } } + // Vanilla's built-in registries (mob effects, components, dialogs...). + for dir in [&self.options.resources, &self.ui.vanilla_root] { + if let Ok(bytes) = std::fs::read(dir.join("command-registries.json")) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + self.ui.registries.fill_from_export(&v); + break; + } + } let reg = &mut self.ui.registries; reg.timelines = self.ui.timelines.keys().cloned().collect(); reg.time_markers = self @@ -368,7 +381,7 @@ impl Game<'_> { /// A chat message from the game (ChatComponent.addServerSystemMessage). pub(super) fn system_message(&mut self, text: Text) { if let Some(capture) = self.chat_capture.as_mut() { - capture.push(text.plain()); + capture.push(text); return; } let focused = self.screen == Screen::Chat; @@ -397,7 +410,7 @@ impl Game<'_> { return; }; let atlas = &self.res.atlas; - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) { self.ui.chat_screen = Some(screen); return; @@ -511,11 +524,11 @@ impl Game<'_> { return; }; screen.resize(batch.width, batch.height); - let bg = self.ui.chat.options.background_opacity; + let bg = self.ui.chat.options.background_opacity as f32; screen.draw( batch, &self.res.atlas, - vanilla::dispatcher(), + vanilla::game_dispatcher(), &self.ui.registries, self.cursor, bg, diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs new file mode 100644 index 000000000..0409b410c --- /dev/null +++ b/crates/horizon-client/src/game/command_harness.rs @@ -0,0 +1,137 @@ +//! Headless command runner for `tools/test_command_exec_parity.py`: with +//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world +//! runs without a window. Each script line is a JSON operation: `cmd` runs a +//! command as the player (Commands.performPrefixedCommand) and records every +//! system message it produced, as styled spans, with the results reported to +//! the player's `CommandResultCallback`; `tick` advances the game; `settle` +//! waits until the terrain around the player is loaded. +use super::Game; +use horizon_client::{Result, text::Text}; +use serde_json::{Value, json}; +use std::{ + path::Path, + time::{Duration, Instant}, +}; + +/// A message as `[text, style]` runs with adjacent equal styles merged; the +/// style lists colour, bold, italic, underlined, strikethrough, obfuscated +/// and the suggested command. +pub(super) fn spans(text: &Text) -> Value { + let mut out: Vec<(String, Value)> = Vec::new(); + for span in &text.spans { + if span.text.is_empty() { + continue; + } + let s = &span.style; + let style = json!([ + s.color, + s.bold == Some(true), + s.italic == Some(true), + s.underlined == Some(true), + s.strikethrough == Some(true), + s.obfuscated == Some(true), + ]); + match out.last_mut() { + Some((t, last)) if *last == style => t.push_str(&span.text), + _ => out.push((span.text.clone(), style)), + } + } + Value::Array(out.into_iter().map(|(t, s)| json!([t, s])).collect()) +} + +impl Game<'_> { + /// Load terrain until the player stands in lit chunks. + fn harness_settle(&mut self, deadline: Instant) -> Result<()> { + loop { + self.update_world(); + self.spawn_player()?; + if let Some(p) = &self.player { + let (cx, cz) = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); + if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return Ok(()); + } + } + if std::env::var_os("HORIZON_HARNESS_DEBUG").is_some() { + eprintln!( + "settle: player {:?} center {:?} chunks {} pending {}", + self.player.as_ref().map(|p| p.position), + self.streaming.center, + self.world.chunks.len(), + self.streaming.pending() + ); + } + if Instant::now() > deadline { + return Err("command harness: terrain did not load".into()); + } + std::thread::sleep(Duration::from_millis(2)); + } + } + pub(super) fn run_command_harness(&mut self, script: &Path, output: &Path) -> Result<()> { + let deadline = Instant::now() + + Duration::from_secs( + std::env::var("HORIZON_HARNESS_TIMEOUT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(600), + ); + self.harness_settle(deadline)?; + let mut out = String::new(); + for line in std::fs::read_to_string(script)?.lines() { + if line.trim().is_empty() { + continue; + } + let op: Value = serde_json::from_str(line)?; + match op["op"].as_str().unwrap_or("") { + "cmd" => { + let command = op["cmd"].as_str().unwrap_or(""); + self.chat_capture = Some(Vec::new()); + self.cmds.results = Some(Vec::new()); + self.run_command(command.strip_prefix('/').unwrap_or(command)); + let messages = self.chat_capture.take().unwrap_or_default(); + let results = self.cmds.results.take().unwrap_or_default(); + if op["record"].as_bool() != Some(false) { + let record = json!({ + "cmd": command, + "messages": messages.iter().map(spans).collect::>(), + "results": results.iter().map(|(s, v)| json!([s, v])).collect::>(), + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "tick" => { + self.chat_capture = Some(Vec::new()); + // The oracle's player has no client moving it: hold the + // player where commands put it while the game ticks. + let held = self.player.as_ref().map(|p| p.position); + for _ in 0..op["n"].as_u64().unwrap_or(1) { + self.update_world(); + self.tick()?; + if let (Some(p), Some(at)) = (self.player.as_mut(), held) { + p.position = at; + p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0); + p.fall_distance = 0.0; + } + } + let messages = self.chat_capture.take().unwrap_or_default(); + if op["record"].as_bool() == Some(true) { + let record = json!({ + "cmd": "#tick", + "messages": messages.iter().map(spans).collect::>(), + "results": [], + }); + out.push_str(&record.to_string()); + out.push('\n'); + } + } + "settle" => self.harness_settle(deadline)?, + other => return Err(format!("command harness: unknown op {other}").into()), + } + } + std::fs::write(output, out)?; + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 2f0a7acc9..d45e10e8a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,8 +1,10 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. +mod compute; mod data; mod effects; pub(super) mod execute; +pub(super) mod extra; mod items; mod misc; mod place; @@ -40,6 +42,19 @@ pub(super) enum Target { Painting(u32), Boat(u32), Cart(u32), + /// An entity of a type Horizon does not simulate (markers, displays, + /// interactions...): kept as its saved data at a position. + Other(u32), +} +/// An entity of a type Horizon does not simulate: its compound lives in the +/// entity memory (`persist.raw`), its position and rotation here. +#[derive(Clone, Debug)] +pub(in crate::game) struct OtherEntity { + pub id: u32, + pub kind: String, + pub position: Vec3, + pub yaw: f32, + pub pitch: f32, } pub(super) fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError { CommandError::tr(key, args) @@ -63,7 +78,7 @@ fn format_double(v: f64) -> String { impl Game<'_> { /// Commands.performCommand for a line without its slash. pub(super) fn run_command(&mut self, command: &str) { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(command, &self.ui.registries); let result = match parse.executable() { Err(e) => { @@ -84,6 +99,10 @@ impl Game<'_> { self.command_failure(e.message); } } + // InventoryChangeTrigger fires as slots change, not on the next tick. + if self.player.is_some() { + self.check_inventory_trigger(); + } } fn syntax_failure(&mut self, e: &CommandError, command: &str) { self.command_failure(e.message.clone()); @@ -169,7 +188,8 @@ impl Game<'_> { .ok_or_else(|| err("argument.pos.missing.int", &[]))?; // BlockPos.containing(getPosition) let p = self.resolve_coords(&c).map(|v| v.floor() as i32); - if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { + let elsewhere = self.command_source.is_some_and(|s| s.elsewhere); + if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { return Err(err("argument.pos.unloaded", &[])); } if p[1] < horizon_client::chunk::MIN_Y @@ -242,6 +262,11 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map(|c| [c.position.x, c.position.y, c.position.z]), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map(|o| [o.position.x, o.position.y, o.position.z]), } } pub(super) fn target_type(&self, t: Target) -> String { @@ -276,12 +301,21 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map_or_else(|| "minecraft:minecart".into(), |c| c.kind.id().into()), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map_or_else(String::new, |o| o.kind.clone()), } } /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { - Target::Player => Text::literal(PLAYER_NAME), + Target::Player => match self.score.board.players_team(PLAYER_NAME) { + // PlayerTeam.formatNameForTeam. + Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)), + None => Text::literal(PLAYER_NAME), + }, Target::Item(id) => { let item = self .dropped @@ -305,6 +339,21 @@ impl Game<'_> { Text::literal(name.unwrap_or_default()) } other => { + // Entity.getDisplayName: the CustomName component, else the type. + let custom = match other { + Target::Stand(id) + | Target::Frame(id) + | Target::Painting(id) + | Target::Boat(id) + | Target::Cart(id) + | Target::Other(id) => self.persist_raw(id).and_then(|r| r.get("CustomName")), + _ => None, + }; + if let Some(c) = custom { + return horizon_client::scoreboard::comp_text( + &horizon_client::scoreboard::tag_to_json(c), + ); + } let ty = self.target_type(other); Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[]) } @@ -349,6 +398,7 @@ impl Game<'_> { candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); + candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); } let level = self.experience.level; let creative = self.creative; @@ -535,7 +585,23 @@ impl Game<'_> { "clear" => self.cmd_clear(ctx), "item" => self.cmd_item(ctx), "item.modify" => self.cmd_item_modify(ctx), + "spectate" => self.cmd_spectate(ctx), + id if id.starts_with("waypoint.") => self.cmd_waypoint(id, ctx), + id if id.starts_with("dialog.") => self.cmd_dialog(id, ctx), + id if id.starts_with("posteffect.") => self.cmd_posteffect(id, ctx), + "kick" => self.cmd_kick(ctx), + "fetchprofile" => self.cmd_fetchprofile(ctx), + "publish" => self.cmd_publish(ctx), + "unpublish" => self.cmd_unpublish(), + "debug" => self.cmd_debug(ctx), + "jfr" => self.cmd_jfr(ctx), + "version" => self.cmd_version(), + id if id.starts_with("test.") => self.cmd_test(id, ctx), + "compute" => self.cmd_compute(ctx), "place" => self.cmd_place(ctx), + "place.feature" | "place.jigsaw" | "place.structure" => { + self.cmd_place_generated(id, ctx) + } "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), "rotate" => self.cmd_rotate(ctx), @@ -543,7 +609,18 @@ impl Game<'_> { "playsound" => self.cmd_playsound(ctx), "stopsound" => self.cmd_stopsound(ctx), "particle" => self.cmd_particle(ctx), - id if id.starts_with("attribute.") => self.cmd_attribute(id, ctx), + id if id.starts_with("attribute.") => { + let result = self.cmd_attribute(id, ctx); + // AttributeInstance.setDirty: the entity reacts when it ticks. + if result.is_ok() + && matches!(ctx.get("attribute"), Some(Arg::Resource(a)) if a == "minecraft:waypoint_transmit_range") + && !id.ends_with("get") + && let Ok(t) = self.entities(ctx, "target", false) + { + self.cmds.waypoint_dirty.push(t[0]); + } + result + } "ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx), "spreadplayers" => self.cmd_spreadplayers(ctx), id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx), @@ -569,6 +646,7 @@ impl Game<'_> { self.cmd_scoreboard(id, ctx) } "locate.structure" | "locate.biome" => self.cmd_locate(id, ctx), + "locate.poi" => self.cmd_locate_poi(ctx), "warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => { let level = Self::int(ctx, "warning_level"); self.cmd_warden_spawn_tracker(level); @@ -581,7 +659,7 @@ impl Game<'_> { "commands.list.nameAndId", &[ Text::literal(PLAYER_NAME), - Text::literal("00000000-0000-0000-0000-000000000000"), + Text::literal(self.player_uuid_string()), ], ) } else { @@ -597,7 +675,7 @@ impl Game<'_> { } } fn cmd_help(&mut self, ctx: &Context) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let level = self.ui.registries.permission; match ctx.get("command") { None => { @@ -653,16 +731,23 @@ impl Game<'_> { } count += 1; let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); - if ctx.get("target").is_none() { + // GameModeCommand.logGamemodeChange: the source's own entity. + let own = match self.command_source { + None => true, + Some(s) => s.entity == Some(t), + }; + if own { self.feedback(Text::translate( "commands.gamemode.success.self", &[mode_name], )); } else { - self.system_message(Text::translate( - "gameMode.changed", - std::slice::from_ref(&mode_name), - )); + if self.ui.rules.bool("send_command_feedback") { + self.system_message(Text::translate( + "gameMode.changed", + std::slice::from_ref(&mode_name), + )); + } self.feedback(Text::translate( "commands.gamemode.success.other", &[Text::literal(PLAYER_NAME), mode_name], @@ -685,7 +770,58 @@ impl Game<'_> { .append("]") .with_color(color) } - fn item_rarity(&self, item: &str) -> String { + /// `ItemStack.getDisplayName`: the hover name (custom name in italics, + /// a written book's title, a potion's effect name...) in brackets, in the + /// rarity colour unless the stack is empty. + pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text { + let item = &*s.item; + let empty = item == "minecraft:air" || s.count == 0; + let custom = s.custom_name(); + let hover = if let Some(c) = custom { + Text::literal(c).italic() + } else if let Some(title) = s + .data() + .and_then(|d| d.written.as_ref()) + .map(|w| w.title.clone()) + .filter(|t| !t.trim().is_empty()) + { + Text::literal(title) + } else if matches!( + item, + "minecraft:potion" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:tipped_arrow" + ) && s.potion().is_some() + { + Text::translate( + &horizon_client::brewing::potion_name_key(item, s.potion()), + &[], + ) + } else { + Text::literal(self.res.names.item(item)) + }; + let wrapped = Text::translate("chat.square_brackets", &[hover]); + if empty { + return wrapped; + } + let mut rarity = self.item_rarity(item); + if !s.enchantments().is_empty() { + rarity = match rarity.as_str() { + "rare" => "epic".into(), + "epic" => rarity, + _ => "rare".into(), + }; + } + let color = match rarity.as_str() { + "uncommon" => text::YELLOW, + "rare" => text::AQUA, + "epic" => text::LIGHT_PURPLE, + _ => text::WHITE, + }; + wrapped.with_color(color) + } + pub(super) fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); let map = RARITY.get_or_init(|| { @@ -731,7 +867,9 @@ impl Game<'_> { ], ))); } - for _ in &targets { + // An air stack is empty: nothing is given (but the message still is). + let empty = id == "minecraft:air"; + for _ in targets.iter().filter(|_| !empty) { let mut remaining = count; while remaining > 0 { let size = remaining.min(max_stack); @@ -755,7 +893,12 @@ impl Game<'_> { } } } - let name = self.item_display_name(&id); + let name = self.stack_display_name(&ItemStack { + item: id.as_str().into(), + count: count.max(1) as u32, + damage, + extra: extra.clone(), + }); let message = if targets.len() == 1 { Text::translate( "commands.give.success.single", @@ -848,6 +991,15 @@ impl Game<'_> { } } } + Target::Other(id) => { + if let Some(o) = self.others.iter_mut().find(|o| o.id == id) { + o.position = v; + if let Some([yaw, pitch]) = rotation { + o.yaw = yaw; + o.pitch = pitch; + } + } + } // Wall-mounted entities do not move. Target::Frame(_) | Target::Painting(_) => {} } @@ -1117,7 +1269,7 @@ impl Game<'_> { w.raining = raining; w.thundering = thundering; self.feedback(Text::translate(key, &[])); - Ok(duration.unwrap_or(0)) + Ok(duration.unwrap_or(-1)) } fn kill_target(&mut self, t: Target) { match t { @@ -1151,6 +1303,7 @@ impl Game<'_> { Target::Painting(id) => self.paintings.retain(|p| p.id != id), Target::Boat(id) => self.boats.retain(|b| b.id != id), Target::Cart(id) => self.carts.retain(|c| c.id != id), + Target::Other(id) => self.others.retain(|o| o.id != id), } } fn cmd_kill(&mut self, ctx: &Context) -> R { @@ -1185,6 +1338,13 @@ impl Game<'_> { let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else { return Ok(0); }; + // ResourceArgument.getSummonableEntityType. + if matches!( + kind.as_str(), + "minecraft:player" | "minecraft:fishing_bobber" + ) { + return Err(err("entity.not_summonable", &[&kind])); + } let pos = self .position_arg(ctx, "pos") .unwrap_or(self.source_position()); @@ -1355,12 +1515,14 @@ impl Game<'_> { return Err(err("commands.setblock.failed", &[])); } if ctx.has("destroy") && current != self.world.air { - let creative = self.creative; - self.creative = false; - let _ = self.break_block(pos); - self.creative = creative; + self.destroy_block_dropping(pos)?; } - if !self.place_state(pos, state, ctx.has("strict"))? { + let placed = self.place_state(pos, state, ctx.has("strict"))?; + let loaded = match &b.nbt { + Some(nbt) => self.load_block_entity_nbt(pos, nbt), + None => false, + }; + if !placed && !loaded { return Err(err("commands.setblock.failed", &[])); } self.feedback(Text::tr( @@ -1369,6 +1531,64 @@ impl Game<'_> { )); Ok(1) } + /// `Level.destroyBlock(pos, true)`: the block's drops without a tool or + /// breaker (its loot table, contents of a container), then air. + pub(super) fn destroy_block_dropping(&mut self, pos: [i32; 3]) -> R<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + self.destroy_particles(pos, state); + self.jukebox_removed(pos); + if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) { + let name = self.res.facts.get(state).name.clone(); + self.release_contents(pos, entity, &name); + } + let drops = self.res.items.block_drops_in( + self.res.assets.registry, + state, + None, + &mut self.world.random, + Some((&mut self.rand_sequences, self.level.seed)), + ); + for d in drops { + if &*d.item != "minecraft:air" { + self.pop_resource(pos, d); + } + } + let air = self.world.air; + self.place_state(pos, air, false)?; + Ok(()) + } + /// The block entity part of `BlockInput.place`: load the block entity + /// from the argument's tag; true when its saved data changed. + pub(super) fn load_block_entity_nbt(&mut self, pos: [i32; 3], nbt: &str) -> bool { + use horizon_world::nbt::Tag; + let key = (pos[0], pos[1], pos[2]); + let Some(e) = self.world.block_entities.get(&key) else { + return false; + }; + let name = self.data_block_name(pos); + let before = horizon_client::save::encode_block_entity(key, e, &name); + let Ok((mut tag, _)) = horizon_world::nbt::parse_snbt(nbt) else { + return false; + }; + if let Tag::Compound(c) = &mut tag { + for k in ["id", "x", "y", "z"] { + if let Some(v) = before.get(k) { + c.insert(k.into(), v.clone()); + } + } + } + let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else { + return false; + }; + let after = horizon_client::save::encode_block_entity(key, &new, &name); + if after == before { + return false; + } + self.world.block_entities.insert(key, new); + let state = self.world.block(pos[0], pos[1], pos[2]); + let _ = self.world.set(pos[0], pos[1], pos[2], state); + true + } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; @@ -1418,10 +1638,7 @@ impl Game<'_> { || z == max[2]; let mut affected = false; if destroy && current != air { - let creative = self.creative; - self.creative = false; - let _ = self.break_block([x, y, z]); - self.creative = creative; + self.destroy_block_dropping([x, y, z])?; affected = true; } let target = if (outline || hollow) && !edge { @@ -1497,21 +1714,29 @@ impl Game<'_> { dest[2] + z - min[2], ], s, + self.world.block_entities.get(&(x, y, z)).cloned(), )); } } } if moving { - for (from, _, _) in &copies { + for (from, _, _, _) in &copies { self.place_state(*from, air, true)?; } } let strict = ctx.has("strict"); + // CloneCommands.clone sets every destination to a barrier first, so + // each copied state but a barrier counts as placed. + let barrier = self.res.assets.registry.default_state("minecraft:barrier"); let mut count = 0; - for (_, to, s) in copies { - if self.place_state(to, s, strict)? { + for (_, to, s, entity) in copies { + self.place_state(to, s, strict)?; + if Some(s) != barrier { count += 1; } + if let Some(e) = entity { + self.world.block_entities.insert((to[0], to[1], to[2]), e); + } } if count == 0 { return Err(err("commands.clone.failed", &[])); @@ -1758,7 +1983,7 @@ impl Game<'_> { if self.ui.difficulty == i { return Err(CommandError::new(Text::translate( "commands.difficulty.failure", - &[Text::literal(DIFFICULTIES[i as usize])], + &[name(i)], ))); } self.ui.difficulty = i; @@ -1808,7 +2033,7 @@ impl Game<'_> { dim, ]; let key = if targets.len() == 1 { - args.push(Text::literal(PLAYER_NAME)); + args.push(self.target_name(targets[0])); "commands.spawnpoint.success.single" } else { args.push(Text::literal(targets.len().to_string())); @@ -1828,9 +2053,6 @@ impl Game<'_> { p[2].floor() as i32, ] }; - if self.dim != Dim::Overworld { - return Err(err("commands.setworldspawn.failure.not_overworld", &[])); - } let rot = match ctx.get("rotation") { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), _ => [0.0, 0.0], @@ -1865,6 +2087,89 @@ impl Game<'_> { } predicate.id == item } + /// `ItemPredicateArgument`: the item test and its `[...]` component + /// tests (presence, `=` equality, `!` negation, `|` alternatives). + pub(super) fn stack_matches(&self, predicate: &ItemInput, stack: &ItemStack) -> bool { + if !self.item_matches(predicate, &stack.item) { + return false; + } + let Some(tests) = predicate.components.as_deref() else { + return true; + }; + let inner = tests + .trim() + .strip_prefix('[') + .and_then(|t| t.strip_suffix(']')) + .unwrap_or(""); + let components = match horizon_client::item_data::encode_components(stack) { + Some(horizon_world::nbt::Tag::Compound(c)) => c, + _ => Default::default(), + }; + let test = |term: &str| -> bool { + let term = term.trim(); + let (negated, term) = match term.strip_prefix('!') { + Some(t) => (true, t.trim()), + None => (false, term), + }; + let split = term.find(['=', '~']).unwrap_or(term.len()); + let id = term[..split].trim(); + let id = if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + }; + let present = components.get(&id.as_str().into()); + let result = match term[split..].chars().next() { + Some('=') => { + let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim()) + .ok() + .map(|(t, _)| t); + match (present, value) { + (Some(have), Some(want)) => { + horizon_client::nbt_path::compare_nbt(&want, Some(have)) + && horizon_client::nbt_path::compare_nbt(have, Some(&want)) + } + _ => false, + } + } + Some('~') => { + // Sub-predicates: `count` and component predicates. + let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim()) + .ok() + .map(|(t, _)| t); + match (id.as_str(), value) { + ("minecraft:count", Some(v)) => { + let n = i64::from(stack.count); + match &v { + horizon_world::nbt::Tag::Compound(_) => { + let get = |k: &str| match v.get(k) { + Some(horizon_world::nbt::Tag::Int(i)) => { + Some(i64::from(*i)) + } + _ => None, + }; + get("min").is_none_or(|m| n >= m) + && get("max").is_none_or(|m| n <= m) + } + horizon_world::nbt::Tag::Int(i) => n == i64::from(*i), + _ => false, + } + } + (_, Some(v)) => present.is_some_and(|have| { + horizon_client::nbt_path::compare_nbt(&v, Some(have)) + }), + _ => false, + } + } + _ => present.is_some(), + }; + result != negated + }; + split_top_level(inner, ',') + .iter() + .filter(|t| !t.trim().is_empty()) + .all(|term| split_top_level(term, '|').iter().any(|alt| test(alt))) + } fn cmd_clear(&mut self, ctx: &Context) -> R { let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? @@ -1885,19 +2190,30 @@ impl Game<'_> { // Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried. let mut removed = 0i32; let mut budget = if max < 0 { i32::MAX } else { max }; + let all = |g: &Self| -> Vec> { + let mut v: Vec> = g.inventory.clone(); + v.extend(g.armor.iter().cloned()); + v.extend(g.craft_grid.iter().cloned()); + v.push(g.carried.clone()); + v + }; + let matching: Vec = all(self) + .iter() + .map(|s| { + s.as_ref() + .is_some_and(|s| self.stack_matches(&predicate, s)) + }) + .collect(); let mut slots: Vec<&mut Option> = Vec::new(); slots.extend(self.inventory.iter_mut()); slots.extend(self.armor.iter_mut()); slots.extend(self.craft_grid.iter_mut()); slots.push(&mut self.carried); - for slot in slots { + for (slot, matches) in slots.into_iter().zip(matching) { + if !matches { + continue; + } let Some(stack) = slot.as_mut() else { continue }; - if !(predicate.any || predicate.tag || predicate.id == *stack.item) && !predicate.tag { - continue; - } - if predicate.tag { - continue; - } let take = if counting { stack.count as i32 } else { @@ -1915,35 +2231,6 @@ impl Game<'_> { } } } - if predicate.tag { - // Tag predicates: match against item tags. - let pred = predicate.clone(); - let mut budget = if max < 0 { i32::MAX } else { max }; - let items: Vec<(usize, String, u32)> = self - .inventory - .iter() - .enumerate() - .filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count))) - .collect(); - for (i, item, count) in items { - if !self.item_matches(&pred, &item) { - continue; - } - let take = if counting { - count as i32 - } else { - (count as i32).min(budget) - }; - removed += take; - if !counting && let Some(s) = self.inventory[i].as_mut() { - budget -= take; - s.count -= take as u32; - if s.count == 0 { - self.inventory[i] = None; - } - } - } - } if removed == 0 { return Err(if targets.len() == 1 { CommandError::new(Text::translate( @@ -1964,35 +2251,179 @@ impl Game<'_> { )); Ok(removed) } + /// `PoiTypes`: the point of interest type of a block state. + fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { + let s = self.res.assets.registry.state(state)?; + let name = s.name.strip_prefix("minecraft:")?; + Some(match name { + "blast_furnace" => "minecraft:armorer", + "smoker" => "minecraft:butcher", + "cartography_table" => "minecraft:cartographer", + "brewing_stand" => "minecraft:cleric", + "composter" => "minecraft:farmer", + "barrel" => "minecraft:fisherman", + "fletching_table" => "minecraft:fletcher", + "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { + "minecraft:leatherworker" + } + "lectern" => "minecraft:librarian", + "stonecutter" => "minecraft:mason", + "loom" => "minecraft:shepherd", + "smithing_table" => "minecraft:toolsmith", + "grindstone" => "minecraft:weaponsmith", + "bell" => "minecraft:meeting", + "beehive" => "minecraft:beehive", + "bee_nest" => "minecraft:bee_nest", + "nether_portal" => "minecraft:nether_portal", + "lodestone" => "minecraft:lodestone", + "test_instance_block" => "minecraft:test_instance", + n if n.ends_with("_bed") => { + if s.properties.get("part").map(String::as_str) != Some("head") { + return None; + } + "minecraft:home" + } + n if n.ends_with("lightning_rod") => "minecraft:lightning_rod", + _ => return None, + }) + } + /// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within + /// 256 blocks of the source, over the loaded chunks. + fn cmd_locate_poi(&mut self, ctx: &Context) -> R { + let Some(Arg::Resource(poi)) = ctx.get("poi").cloned() else { + return Ok(0); + }; + let wanted: Vec = match poi.strip_prefix('#') { + Some(tag) => self.tag_entries("point_of_interest_type", tag), + None => vec![poi.clone()], + }; + let from = self.source_position().map(|v| v.floor() as i32); + const RANGE: i32 = 256; + let mut cache: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut best: Option<(i64, [i32; 3], &'static str)> = None; + let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4); + let (cx1, cz1) = ((from[0] + RANGE) >> 4, (from[2] + RANGE) >> 4); + for cx in cx0..=cx1 { + for cz in cz0..=cz1 { + let Some(chunk) = self.world.chunks.get(&(cx, cz)) else { + continue; + }; + for (i, section) in chunk.sections.iter().enumerate() { + let mut wanted_state = |v: u32| { + let state = v as u16; + cache + .entry(state) + .or_insert_with(|| { + self.poi_type(horizon_world::registry::BlockStateId(u32::from( + state, + ))) + .filter(|t| wanted.iter().any(|w| w == t)) + }) + .is_some() + }; + if !section.blocks.maybe_has(&mut wanted_state) { + continue; + } + let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32; + for j in 0..4096 { + let state = section.get(j); + let Some(kind) = cache.get(&state).copied().flatten() else { + continue; + }; + let p = [ + cx * 16 + (j & 15) as i32, + base_y + (j >> 8) as i32, + cz * 16 + ((j >> 4) & 15) as i32, + ]; + let d = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| i64::from(d) * i64::from(d)) + .iter() + .sum::(); + if d <= i64::from(RANGE * RANGE) && best.is_none_or(|(b, _, _)| d < b) { + best = Some((d, p, kind)); + } + } + } + } + } + let Some((_, p, kind)) = best else { + return Err(CommandError::new(Text::tr( + "commands.locate.poi.not_found", + &[&poi], + ))); + }; + let coords = Text::translate( + "chat.coordinates", + &[ + Text::literal(p[0].to_string()), + Text::literal("~"), + Text::literal(p[2].to_string()), + ], + ); + let link = Text::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + color: Some(text::GREEN), + suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), + ..Style::default() + }); + let (dx, dz) = (p[0] - from[0], p[2] - from[2]); + let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32; + let shown = if poi.starts_with('#') { + format!("{poi} ({kind})") + } else { + poi + }; + self.feedback(Text::translate( + "commands.locate.poi.success", + &[ + Text::literal(shown), + link, + Text::literal(distance.to_string()), + ], + )); + Ok(distance) + } fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R { let origin = self.source_position(); if id == "locate.biome" { let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0); }; - // Search loaded chunks around the player (BiomeSource.findClosestBiome3d - // samples a 6400-block radius; Horizon searches what is generated). - let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32); - let mut best: Option<([i32; 3], f64)> = None; - for (&(cx, cz), chunk) in &self.world.chunks { - for (dx, dz) in [(0, 0), (8, 8)] { - let (x, z) = (cx * 16 + dx, cz * 16 + dz); - let y = origin[1].floor() as i32; - let b = self.res.biomes.get(chunk.biome(x, y, z)); - if b.name == biome { - let d = f64::from((x - px).pow(2) + (z - pz).pow(2)); - if best.is_none_or(|(_, bd)| d < bd) { - best = Some(([x, y, z], d)); - } - } - } - } - let Some((p, d2)) = best else { + // LocateCommand.locateBiome: BiomeSource.findClosestBiome3d with + // a 6400-block radius, 32-block columns and 64-block layers. + let from = origin.map(|v| v.floor() as i32); + let allowed = |name: &str| self.biome_matches(&biome, name); + let search = horizon_world::worldgen::generator::BiomeSearch { + allowed: &allowed, + origin: from, + radius: 6400, + horizontal: 32, + vertical: 64, + min_y: horizon_client::chunk::MIN_Y, + max_y: horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT - 1, + }; + let found = self + .end + .locator() + .and_then(|t| t.find_closest_biome(&search)); + let Some((name, p)) = found else { return Err(CommandError::new(Text::tr( "commands.locate.biome.not_found", &[&biome], ))); }; + let d2 = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| f64::from(d) * f64::from(d)) + .iter() + .sum::(); + let shown = if biome.starts_with('#') { + format!("{biome} ({name})") + } else { + biome.clone() + }; let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); let link = Text::literal("[") .append(coords) @@ -2002,11 +2433,11 @@ impl Game<'_> { suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), ..Style::default() }); - let distance = d2.sqrt().floor() as i32; - self.system_message(Text::translate( + let distance = (d2 as f32).sqrt().floor() as i32; + self.feedback(Text::translate( "commands.locate.biome.success", &[ - Text::literal(biome), + Text::literal(shown), link, Text::literal(distance.to_string()), ], @@ -2064,6 +2495,10 @@ impl Game<'_> { } /// The structures of a `worldgen/structure` tag, nested tags expanded. pub(super) fn structure_tag(&self, tag: &str) -> Vec { + self.tag_entries("worldgen/structure", tag) + } + /// The entries of a data pack tag of `registry`, nested tags expanded. + pub(super) fn tag_entries(&self, registry: &str, tag: &str) -> Vec { let mut out = Vec::new(); let mut pending = vec![tag.to_owned()]; let mut seen = std::collections::HashSet::new(); @@ -2075,7 +2510,7 @@ impl Game<'_> { let file = self .options .resources - .join(format!("data/{ns}/tags/worldgen/structure/{path}.json")); + .join(format!("data/{ns}/tags/{registry}/{path}.json")); let Ok(v) = std::fs::read(file) .map_err(|_| ()) .and_then(|b| serde_json::from_slice::(&b).map_err(|_| ())) @@ -2126,6 +2561,9 @@ impl Game<'_> { .italic() } }; + if let Some(capture) = self.chat_capture.as_mut() { + capture.push(line.clone()); + } let focused = self.screen == Screen::Chat; self.ui .chat @@ -2165,3 +2603,33 @@ impl Game<'_> { out } } + +/// Split at a separator outside brackets, braces and quotes. +fn split_top_level(s: &str, sep: char) -> Vec<&str> { + let mut out = Vec::new(); + let (mut depth, mut quote, mut escaped, mut start) = (0i32, None::, false, 0); + for (i, ch) in s.char_indices() { + if let Some(q) = quote { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == q { + quote = None; + } + continue; + } + match ch { + '"' | '\'' => quote = Some(ch), + '[' | '{' => depth += 1, + ']' | '}' => depth -= 1, + c if c == sep && depth == 0 => { + out.push(&s[start..i]); + start = i + ch.len_utf8(); + } + _ => {} + } + } + out.push(&s[start..]); + out +} diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs new file mode 100644 index 000000000..8ffcfac03 --- /dev/null +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -0,0 +1,542 @@ +//! `/compute` (ComputeCommand): context number providers +//! (`context_int_provider`, `context_float_provider`) evaluated in a loot +//! context of the source, optionally with a block or a target entity. +use super::{Arg, Context, Game, R, Target, err}; +use horizon_client::{command::CommandError, text::Text}; +use horizon_core::random::RandomSource; +use serde_json::Value; + +/// The loot context parameters of `LootContextSources`. +#[derive(Clone, Copy, Default)] +pub(in crate::game) struct ComputeContext { + /// `BLOCK_STATE` (`compute block `). + pub block: Option<[i32; 3]>, + /// `TARGET_ENTITY` (`compute entity `). + pub target: Option, +} + +/// An ArithmeticException's message. +type Arith = String; + +fn java_float(v: f32) -> String { + horizon_client::snbt::java_float(v) +} + +impl Game<'_> { + /// A provider argument: its registry id (None when inline) and value. + pub(in crate::game) fn provider_arg( + &self, + ctx: &Context, + registry: &str, + ) -> R<(Option, Value)> { + let raw = match ctx.get("provider") { + Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(), + _ => return Err(err("command.failed", &[])), + }; + let first = raw.trim_start().chars().next().unwrap_or(' '); + if first == '{' || first == '[' || first == '-' || first.is_ascii_digit() || first == '"' { + let (tag, _) = horizon_world::nbt::parse_snbt(&raw) + .map_err(|e| err("argument.nbt.invalid", &[&e]))?; + return Ok((None, horizon_client::scoreboard::tag_to_json(&tag))); + } + let id = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + let value = self + .provider_file(registry, &id) + .ok_or_else(|| err("argument.resource_or_id.no_such_element", &[&id, ®istry]))?; + Ok((Some(id), value)) + } + /// A registered provider's definition. + fn provider_file(&self, registry: &str, id: &str) -> Option { + let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); + let dir = registry.trim_start_matches("minecraft:"); + let file = self + .options + .resources + .join(format!("data/{ns}/{dir}/{path}.json")); + serde_json::from_slice(&std::fs::read(file).ok()?).ok() + } + /// The compute context the command's source literal selects. + pub(in crate::game) fn compute_context(&mut self, ctx: &Context) -> R { + let mut c = ComputeContext::default(); + if ctx.literals.iter().any(|l| l == "block") && ctx.get("computePos").is_some() { + c.block = Some(self.block_pos_arg(ctx, "computePos")?); + } + if ctx.get("computeTarget").is_some() { + let t = self.entities(ctx, "computeTarget", false)?; + if t.len() > 1 { + return Err(err("argument.entity.toomany", &[])); + } + c.target = t.first().copied(); + } + Ok(c) + } + /// `ComputeCommand.computeAsInt` / `computeAsFloat`. + pub(super) fn cmd_compute(&mut self, ctx: &Context) -> R { + let integer = ctx.literals.iter().any(|l| l == "integer"); + let registry = if integer { + "minecraft:context_int_provider" + } else { + "minecraft:context_float_provider" + }; + let (id, provider) = self.provider_arg(ctx, registry)?; + let c = self.compute_context(ctx)?; + let invalid = |value: String| -> CommandError { + match &id { + Some(id) => CommandError::new(Text::translate( + "command.compute.result.named.invalid", + &[Text::literal(id.clone()), Text::literal(value)], + )), + None => CommandError::new(Text::translate( + "command.compute.result.unnamed.invalid", + &[Text::literal(value)], + )), + } + }; + let exact = |result: i32| match &id { + Some(id) => Text::translate( + "command.compute.result.named.exact", + &[Text::literal(id.clone()), Text::literal(result.to_string())], + ), + None => Text::translate( + "command.compute.result.unnamed.exact", + &[Text::literal(result.to_string())], + ), + }; + if integer { + let result = self.provider_int(&provider, &c, 0).map_err(invalid)?; + self.feedback(exact(result)); + return Ok(result); + } + let scale = match ctx.get("scale") { + Some(Arg::Float(s)) => *s, + _ => 1.0, + }; + let original = self.provider_float(&provider, &c, 0).map_err(invalid)?; + if !original.is_finite() { + return Err(invalid(java_float(original))); + } + // Mth.floor(original * scale) + let result = (original * scale).floor() as i32; + if result as f32 == original { + self.feedback(exact(result)); + } else { + let original_text = Text::literal(java_float(original)); + let message = match &id { + Some(id) => Text::translate( + "command.compute.result.named.rounded", + &[ + Text::literal(id.clone()), + original_text, + Text::literal(result.to_string()), + ], + ), + None => Text::translate( + "command.compute.result.unnamed.rounded", + &[original_text, Text::literal(result.to_string())], + ), + }; + self.feedback(message); + } + Ok(result) + } + + // ---- evaluation --------------------------------------------------------------- + + /// `ContextIntProvider.getIntUnsafe`. + pub(in crate::game) fn provider_int( + &mut self, + v: &Value, + c: &ComputeContext, + depth: u32, + ) -> Result { + if depth > 64 { + return Ok(0); + } + let d = depth + 1; + match v { + Value::Number(n) => Ok(n + .as_i64() + .map_or_else(|| n.as_f64().unwrap_or(0.0) as i32, |i| i as i32)), + Value::Bool(b) => Ok(i32::from(*b)), + Value::String(id) => match self.provider_file("minecraft:context_int_provider", id) { + Some(def) => self.provider_int(&def, c, d), + None => Ok(0), + }, + Value::Object(o) => { + let ty = o + .get("type") + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:") + .to_owned(); + let inputs = |g: &mut Self| -> Result, Arith> { + let list: Vec = match o.get("inputs") { + Some(Value::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + None => Vec::new(), + }; + list.iter().map(|x| g.provider_int(x, c, d)).collect() + }; + let field = |g: &mut Self, k: &str| -> Result { + match o.get(k) { + Some(x) => g.provider_int(x, c, d), + None => Ok(0), + } + }; + let overflow = || "integer overflow".to_owned(); + let long_to_int = |v: i64| -> Result { + i32::try_from(v) + .map_err(|_| format!("Value {v} can't be safely converted to int")) + }; + Ok(match ty.as_str() { + "constant" => field(self, "value")?, + "add" => long_to_int(inputs(self)?.iter().map(|&x| i64::from(x)).sum())?, + "mul" => long_to_int( + inputs(self)? + .iter() + .fold(1i64, |a, &x| a.wrapping_mul(i64::from(x))), + )?, + "avg" => { + let xs = inputs(self)?; + if xs.is_empty() { + return Err("/ by zero".into()); + } + let sum: i64 = xs.iter().map(|&x| i64::from(x)).sum(); + long_to_int(sum / xs.len() as i64)? + } + "max" => inputs(self)?.into_iter().fold(i32::MIN, i32::max), + "min" => inputs(self)?.into_iter().fold(i32::MAX, i32::min), + "sub" => { + let (a, b) = (field(self, "left")?, field(self, "right")?); + a.checked_sub(b).ok_or_else(overflow)? + } + "div" | "mod" | "floor_div" | "floor_mod" => { + let (a, b) = (field(self, "left")?, field(self, "right")?); + if b == 0 { + return Err("/ by zero".into()); + } + match ty.as_str() { + "div" => a.wrapping_div(b), + "mod" => a.wrapping_rem(b), + "floor_mod" => { + a.rem_euclid(b) + if b < 0 && a.rem_euclid(b) != 0 { b } else { 0 } + } + _ => { + if a == i32::MIN && b == -1 { + return Err(overflow()); + } + a.div_euclid(b) - if b < 0 && a.rem_euclid(b) != 0 { 1 } else { 0 } + } + } + } + "pow" => { + let (base, exp) = (field(self, "base")?, field(self, "exponent")?); + if base == 0 && exp == 0 { + return Err("Result of 0 to the power of 0 is undefined".into()); + } + if exp < 0 { + return Err("Negative exponent".into()); + } + base.checked_pow(exp as u32).ok_or_else(overflow)? + } + // Math.absExact's message. + "abs" => field(self, "input")?.checked_abs().ok_or_else(|| { + "Overflow to represent absolute value of Integer.MIN_VALUE".to_owned() + })?, + "negate" => field(self, "input")?.checked_neg().ok_or_else(overflow)?, + "from_float" => { + let f = match o.get("input") { + Some(x) => self.provider_float(x, c, d)?, + None => 0.0, + }; + if !f.is_finite() { + return Err(format!( + "Value {} can't be safely converted to int", + java_float(f) + )); + } + long_to_int(f as i64)? + } + "uniform" => { + let (lo, hi) = (field(self, "min")?, field(self, "max")?); + if lo >= hi { + lo + } else { + self.world.random.next_int_bound(hi - lo + 1).unwrap_or(0) + lo + } + } + "binomial" => { + let n = field(self, "n")?; + let p = match o.get("p") { + Some(x) => self.provider_float(x, c, d)?, + None => 0.0, + }; + (0..n.max(0)) + .filter(|_| self.world.random.next_float() < p) + .count() as i32 + } + "conditional" | "number_dispatcher" | "weighted_list" => { + match self.provider_select(o, c)? { + Some(x) => self.provider_int(&x, c, d)?, + None => 0, + } + } + _ => 0, + }) + } + _ => Ok(0), + } + } + /// `ContextFloatProvider.getFloatUnsafe`. + pub(in crate::game) fn provider_float( + &mut self, + v: &Value, + c: &ComputeContext, + depth: u32, + ) -> Result { + if depth > 64 { + return Ok(0.0); + } + let d = depth + 1; + match v { + Value::Number(n) => Ok(n.as_f64().unwrap_or(0.0) as f32), + Value::String(id) => match self.provider_file("minecraft:context_float_provider", id) { + Some(def) => self.provider_float(&def, c, d), + None => Ok(0.0), + }, + Value::Object(o) => { + let ty = o + .get("type") + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:") + .to_owned(); + let inputs = |g: &mut Self| -> Result, Arith> { + let list: Vec = match o.get("inputs") { + Some(Value::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + None => Vec::new(), + }; + list.iter().map(|x| g.provider_float(x, c, d)).collect() + }; + let field = |g: &mut Self, k: &str| -> Result { + match o.get(k) { + Some(x) => g.provider_float(x, c, d), + None => Ok(0.0), + } + }; + Ok(match ty.as_str() { + "constant" => field(self, "value")?, + "add" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x), + "mul" => inputs(self)?.iter().fold(1.0f32, |a, &x| a * x), + "avg" => { + let xs = inputs(self)?; + xs.iter().fold(0.0f32, |a, &x| a + x) / xs.len() as f32 + } + "length" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x * x).sqrt(), + "max" => inputs(self)?.into_iter().fold(-f32::MAX, f32::max), + "min" => inputs(self)?.into_iter().fold(f32::MAX, f32::min), + "sub" => field(self, "left")? - field(self, "right")?, + "div" => field(self, "left")? / field(self, "right")?, + "mod" => { + let right = field(self, "right")?; + if right == 0.0 { + f32::NAN + } else { + field(self, "left")? % right + } + } + "pow" => { + let (base, exp) = (field(self, "base")?, field(self, "exponent")?); + if base == 0.0 && exp == 0.0 { + f32::NAN + } else { + f64::from(base).powf(f64::from(exp)) as f32 + } + } + "abs" => field(self, "input")?.abs(), + "negate" => -field(self, "input")?, + "floor" => field(self, "input")?.floor(), + // Mth.ceil returns an int. + "ceil" => field(self, "input")?.ceil() as i32 as f32, + // Math.round(float): floor(x + 0.5) as int. + "round" => (field(self, "input")? + 0.5).floor() as i32 as f32, + "truncate" => field(self, "input")?.trunc(), + "sqrt" => field(self, "input")?.sqrt(), + "sin" => horizon_core::geometry::trig::sin(f64::from(field(self, "input")?)), + "cos" => horizon_core::geometry::trig::cos(f64::from(field(self, "input")?)), + "from_int" => match o.get("input") { + Some(x) => self.provider_int(x, c, d)? as f32, + None => 0.0, + }, + "uniform" => { + let (lo, hi) = (field(self, "min")?, field(self, "max")?); + if lo >= hi { + lo + } else { + self.world.random.next_float() * (hi - lo) + lo + } + } + "conditional" | "number_dispatcher" | "weighted_list" => { + match self.provider_select(o, c)? { + Some(x) => self.provider_float(&x, c, d)?, + None => 0.0, + } + } + _ => 0.0, + }) + } + _ => Ok(0.0), + } + } + /// The branch a conditional, dispatcher or weighted list provider picks. + fn provider_select( + &mut self, + o: &serde_json::Map, + c: &ComputeContext, + ) -> Result, Arith> { + match o + .get("type") + .and_then(Value::as_str) + .map(|t| t.trim_start_matches("minecraft:")) + { + Some("conditional") => { + let holds = o + .get("condition") + .is_some_and(|x| self.compute_condition(x, c)); + Ok(if holds { + o.get("on_true").cloned() + } else { + Some(o.get("on_false").cloned().unwrap_or(Value::from(0))) + }) + } + Some("number_dispatcher") => { + for case in o + .get("cases") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + if case + .get("condition") + .is_some_and(|x| self.compute_condition(x, c)) + { + return Ok(case.get("value").cloned()); + } + } + Ok(Some(o.get("default").cloned().unwrap_or(Value::from(0)))) + } + _ => { + // WeightedList.getRandomOrThrow. + let list: Vec<(Value, i32)> = o + .get("distribution") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|e| { + ( + e.get("data").cloned().unwrap_or(Value::Null), + e.get("weight").and_then(Value::as_i64).unwrap_or(1) as i32, + ) + }) + .collect(); + let total: i32 = list.iter().map(|(_, w)| *w).sum(); + if total <= 0 { + return Ok(None); + } + let mut pick = self.world.random.next_int_bound(total).unwrap_or(0); + for (v, w) in list { + pick -= w; + if pick < 0 { + return Ok(Some(v)); + } + } + Ok(None) + } + } + } + /// A loot condition in the compute context: references, the logical + /// combinators and `match_block` on the context's block state. + fn compute_condition(&mut self, cond: &Value, c: &ComputeContext) -> bool { + match cond { + Value::String(id) => match self.provider_file("minecraft:predicate", id) { + Some(def) => self.compute_condition(&def, c), + None => false, + }, + Value::Array(list) => list.iter().all(|x| self.compute_condition(x, c)), + Value::Object(o) => { + let ty = o + .get("type") + .or_else(|| o.get("condition")) + .and_then(Value::as_str) + .unwrap_or("") + .trim_start_matches("minecraft:"); + match ty { + "inverted" => !o.get("term").is_some_and(|x| self.compute_condition(x, c)), + "all_of" => o + .get("terms") + .and_then(Value::as_array) + .into_iter() + .flatten() + .all(|x| self.compute_condition(x, c)), + "any_of" => o + .get("terms") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|x| self.compute_condition(x, c)), + "match_block" | "block_state_property" => { + let Some(p) = c.block else { + return false; + }; + let state = self.world.block(p[0], p[1], p[2]); + let Some(s) = self.res.assets.registry.state(state) else { + return false; + }; + let name = s.name.to_string(); + let blocks_ok = match o.get("blocks").or_else(|| o.get("block")) { + Some(Value::String(b)) => match b.strip_prefix('#') { + Some(tag) => self + .res + .items + .block_tags + .get(tag.trim_start_matches("minecraft:")) + .is_some_and(|set| { + set.contains(&*name) + || set.contains(name.trim_start_matches("minecraft:")) + }), + None => *b == name, + }, + Some(Value::Array(list)) => { + list.iter().any(|b| b.as_str() == Some(&name)) + } + _ => true, + }; + let props_ok = o + .get("state") + .or_else(|| o.get("properties")) + .and_then(Value::as_object) + .into_iter() + .flatten() + .all(|(k, v)| s.properties.get(k).map(String::as_str) == v.as_str()); + blocks_ok && props_ok + } + "random_chance" => { + let chance = o.get("chance").and_then(Value::as_f64).unwrap_or(0.0) as f32; + self.world.random.next_float() < chance + } + _ => { + let source = self.command_source.unwrap_or_else(|| self.player_source()); + let view = source.entity.map(|t| self.entity_view_of(t)); + self.conditions_hold(cond, view.as_ref(), source.pos) + } + } + } + _ => false, + } + } +} diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 85d298f8f..3398aa7dd 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -42,6 +42,21 @@ impl Game<'_> { if let Some(u) = player_uuid { set_key(&mut tag, "UUID", Tag::IntArray(u.to_vec())); } + // NbtPredicate.getEntityTagToCompare: a player's held stack. + let selected = self.level.selected_slot; + let held = match tag.get("Inventory") { + Some(Tag::List(items)) => items + .iter() + .find(|i| matches!(i.get("Slot"), Some(Tag::Byte(b)) if i32::from(*b) == selected)) + .cloned(), + _ => None, + }; + if let Some(mut stack) = held { + if let Tag::Compound(c) = &mut stack { + c.remove(&"Slot".into()); + } + set_key(&mut tag, "SelectedItem", stack); + } tag } Target::Mob(id) => { @@ -87,6 +102,11 @@ impl Game<'_> { let c = self.carts.iter().find(|c| c.id == id)?; c.to_nbt(uuid, self.persist.raw.get(&id)) } + Target::Other(id) => { + let uuid = self.uuid_for(id); + let o = self.others.iter().find(|o| o.id == id)?.clone(); + self.other_to_nbt(&o, uuid) + } Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()), Target::Arrow(i) => { let a = self.arrows.get(i)?; @@ -166,7 +186,8 @@ impl Game<'_> { | Target::Frame(id) | Target::Painting(id) | Target::Boat(id) - | Target::Cart(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)), + | Target::Cart(id) + | Target::Other(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)), _ => None, } } @@ -226,9 +247,16 @@ impl Game<'_> { } pub(in crate::game) fn data_of(&mut self, r: &DataRef) -> R { match r { - DataRef::Entity(t) => self - .entity_nbt(*t) - .ok_or_else(|| err("argument.entity.notfound.entity", &[])), + // EntityDataAccessor.getData: Entity.saveWithoutId. + DataRef::Entity(t) => { + let mut tag = self + .entity_nbt(*t) + .ok_or_else(|| err("argument.entity.notfound.entity", &[]))?; + if let Tag::Compound(c) = &mut tag { + c.remove(&"id".into()); + } + Ok(tag) + } DataRef::Block(p) => { let key = (p[0], p[1], p[2]); let name = self.data_block_name(*p); @@ -237,7 +265,12 @@ impl Game<'_> { .block_entities .get(&key) .ok_or_else(|| err("commands.data.block.invalid", &[]))?; - Ok(save::encode_block_entity(key, e, &name)) + // BlockEntity.saveWithFullMetadata: no chunk-only keepPacked. + let mut tag = save::encode_block_entity(key, e, &name); + if let Tag::Compound(c) = &mut tag { + c.remove(&"keepPacked".into()); + } + Ok(tag) } DataRef::Storage(id) => Ok(self.score.storage.get(id)), } @@ -626,10 +659,11 @@ impl Game<'_> { }; self.world.loaded_entities.push((key, vec![tag])); self.spawn_loaded_entities(); - let id = self.next_entity; - if id == before { + if self.next_entity == before { return None; } + // The root of the stack is the first entity spawned. + let id = before + 1; if self.mobs.iter().any(|m| m.id == id) { Some(Target::Mob(id)) } else if self.dropped.iter().any(|e| e.id == id) { @@ -644,6 +678,8 @@ impl Game<'_> { Some(Target::Boat(id)) } else if self.carts.iter().any(|c| c.id == id) { Some(Target::Cart(id)) + } else if self.others.iter().any(|o| o.id == id) { + Some(Target::Other(id)) } else { None } @@ -660,18 +696,36 @@ impl Game<'_> { return Err(err("argument.nbt.expected.compound", &[])); } set_key(&mut tag, "id", Tag::String(kind.into())); - let p = pos.map(|v| Tag::Double(v.to_bits())); - set_key(&mut tag, "Pos", Tag::List(p.to_vec())); - if tag.get("Rotation").is_none() { - set_key( - &mut tag, - "Rotation", - Tag::List(vec![ - Tag::Float(0.0f32.to_bits()), - Tag::Float(0.0f32.to_bits()), - ]), - ); + // EntityType.loadEntityRecursive snaps every entity of the stack, + // passengers included, to the position. + fn place(tag: &mut Tag, pos: [f64; 3]) { + let p = pos.map(|v| Tag::Double(v.to_bits())); + set_key(tag, "Pos", Tag::List(p.to_vec())); + // Entity.load: an absent Fire reads as 0 (until the entity moves). + if tag.get("Fire").is_none() { + set_key(tag, "Fire", Tag::Short(0)); + } + if tag.get("Rotation").is_none() { + set_key( + tag, + "Rotation", + Tag::List(vec![ + Tag::Float(0.0f32.to_bits()), + Tag::Float(0.0f32.to_bits()), + ]), + ); + } + if let Tag::Compound(c) = tag + && let Some(Tag::List(riders)) = c.get_mut(&"Passengers".into()) + { + for r in riders { + if matches!(r, Tag::Compound(_)) { + place(r, pos); + } + } + } } + place(&mut tag, pos); Ok(self.spawn_entity_from_nbt(tag)) } } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 2fda44bfe..a913b07c5 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -23,6 +23,9 @@ pub(in crate::game) struct Source { pub silent: bool, /// Index of the newest `store` in `ExecState::stores`. pub store: Option, + /// `execute in` another dimension than the one Horizon has loaded: none + /// of its chunks are loaded. + pub elsewhere: bool, } /// Where `execute store` writes. @@ -70,6 +73,7 @@ impl Game<'_> { eyes: false, silent: false, store: None, + elsewhere: false, } } /// The server as a source (function ticks and schedules): the world spawn. @@ -81,6 +85,7 @@ impl Game<'_> { eyes: false, silent: true, store: None, + elsewhere: false, } } pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] { @@ -106,6 +111,11 @@ impl Game<'_> { .iter() .find(|c| c.id == id) .map_or([0.0; 2], |c| [c.yaw, 0.0]), + Target::Other(id) => self + .others + .iter() + .find(|o| o.id == id) + .map_or([0.0; 2], |o| [o.yaw, o.pitch]), _ => [0.0; 2], } } @@ -147,7 +157,7 @@ impl Game<'_> { /// Run one command line with `source` (no error reporting): the entry /// for functions and `execute run`. pub(in crate::game) fn execute_line(&mut self, line: &str, source: Source) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(line, &self.ui.registries); let (ctx, _) = parse.executable()?; let ctx = ctx.clone(); @@ -189,6 +199,12 @@ impl Game<'_> { } /// `CommandResultCallback`s of a source's `store` chain, oldest first. fn deliver(&mut self, store: Option, success: bool, value: i32) { + // The outermost source's own CommandResultCallback (harness record). + if self.exec.function_depth == 0 + && let Some(results) = self.cmds.results.as_mut() + { + results.push((success, value)); + } let mut chain = Vec::new(); let mut at = store; while let Some(i) = at { @@ -235,6 +251,10 @@ impl Game<'_> { pub(in crate::game) fn run_execute(&mut self, ctx: &Context) -> R { let mut sources = vec![self.command_source.unwrap_or_else(|| self.player_source())]; let mut c = ctx; + // A fork modifier (as, at, positioned as, rotated as, facing entity, + // on, a non-terminal if/unless) makes later errors silent + // (CommandSourceStack.handleError with `forked`). + let mut forked = false; loop { let word = c .literals @@ -257,7 +277,8 @@ impl Game<'_> { for s in sources { match self.with_source(s, |g| g.run_chain(command, last)) { Ok(n) => total += n, - // Forked executions report failures and carry on. + Err(_) if forked => {} + // Several sources: report each failure and carry on. Err(e) if many => self.command_failure(e.message), Err(e) => failure = Some(e), } @@ -275,6 +296,7 @@ impl Game<'_> { if c.child.is_none() { return self.run_conditional_terminal(c, sources, want); } + forked = true; let mut kept = Vec::new(); for s in sources { let (keep, _) = self.with_source(s, |g| g.condition(c, want))?; @@ -285,6 +307,12 @@ impl Game<'_> { sources = kept; } _ => { + forked |= match word { + "as" | "at" | "on" => true, + "positioned" | "rotated" => c.has("as"), + "facing" => c.has("entity"), + _ => false, + }; let mut next = Vec::new(); for s in sources { next.extend(self.with_source(s, |g| g.modify(word, c, s))?); @@ -407,6 +435,7 @@ impl Game<'_> { Some(Source { pos: self.target_position(t)?, rot: self.target_rotation(t), + elsewhere: false, ..s }) }) @@ -497,14 +526,21 @@ impl Game<'_> { ..s }], "in" => { - // Horizon keeps one dimension loaded; others cannot be a source. + // Horizon keeps one dimension loaded: in another one, no + // chunk is loaded (as in vanilla without a player there). let Some(Arg::Resource(dim)) = c.get("dimension") else { return Ok(vec![s]); }; - if dim != self.dim.id() { + if !matches!( + dim.as_str(), + "minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end" + ) { return Err(err("argument.dimension.invalid", &[dim])); } - vec![s] + vec![Source { + elsewhere: dim != self.dim.id(), + ..s + }] } "summon" => { let Some(Arg::Resource(kind)) = c.get("entity").cloned() else { diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs new file mode 100644 index 000000000..0b437d692 --- /dev/null +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -0,0 +1,1037 @@ +//! Commands that act on the player and the hosted game rather than the world: +//! `/spectate` (SpectateCommand), `/waypoint` (WaypointCommand), `/dialog` +//! (DialogCommand), `/posteffect` (PostEffectCommand), `/kick`, +//! `/fetchprofile`, `/publish`, `/unpublish`, `/debug`, `/jfr` and +//! `/version`, with vanilla's feedback and failures. +use super::{Arg, Context, Game, R, Target, err}; +use horizon_client::{ + command::CommandError, + text::{self, Style, Text}, +}; +use std::{collections::HashMap, time::Instant}; + +/// Waypoint.Icon: the locator bar style and colour of a transmitter. +#[derive(Clone, Debug, PartialEq)] +pub(in crate::game) struct WaypointIcon { + pub style: String, + pub color: Option, +} +impl Default for WaypointIcon { + fn default() -> Self { + Self { + style: "minecraft:default".into(), + color: None, + } + } +} + +/// Server-side player and server state these commands keep. +#[derive(Default)] +pub(in crate::game) struct CommandExtras { + /// ServerPlayer.camera: the entity `/spectate` attached the view to. + pub camera: Option, + /// ServerPlayer.postEffects, in insertion order. + pub post_effects: Vec, + /// MinecraftServer's tick profiler (`/debug start`): when it started and + /// the tick count then. + pub profiler: Option<(Instant, u64)>, + /// `debugCommandProfilerDelayStart`: the profiler starts with the next tick. + pub profiler_delay: bool, + /// Messages the server sends on a later tick (profile lookups). + pub pending: Vec, + /// The `/jfr start` recording: when it started and the tick count then. + pub jfr: Option<(Instant, u64, String)>, + /// Waypoint icons changed by `/waypoint modify`. + pub waypoint_icons: HashMap, + /// The dialog `/dialog show` opened (its id or inline definition). + pub dialog: Option, + /// `/datapack disable vanilla` took the built-in pack out of the selection. + pub vanilla_disabled: bool, + /// The waypoint manager's tracked transmitters (None until first used). + pub waypoints: Option>, + /// Entities whose waypoint transmit range changed since they last ticked. + pub waypoint_dirty: Vec, + /// Attribute maps of living entities whose attributes Horizon does not + /// model (an armor stand's, a mob's beyond its modelled three). + pub attributes: HashMap, + /// The `CommandResultCallback` results of the outermost source, when a + /// harness records them. + pub results: Option>, +} + +/// `version.json` of the 26.3 jars. +const VERSION_ID: &str = "26.3"; +const DATA_VERSION: i32 = 5023; +const STABLE: bool = true; +/// `Date.toString()` of the build time in UTC. +const BUILD_TIME: &str = "Tue Sep 15 11:20:48 UTC 2026"; + +fn num(n: impl std::fmt::Display) -> Text { + Text::literal(n.to_string()) +} +fn tr_error(key: &str, args: &[Text]) -> CommandError { + CommandError::new(Text::translate(key, args)) +} +/// `String.format(Locale.ROOT, "%.2f", v)`. +fn two_places(v: f64) -> String { + format!("{v:.2}") +} +/// `Util.getFilenameFormattedDateTime` (`yyyy-MM-dd_HH.mm.ss`, local time). +fn filename_date_time() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64); + let (y, mo, d, h, mi, s) = civil(secs); + format!("{y:04}-{mo:02}-{d:02}_{h:02}.{mi:02}.{s:02}") +} +/// UTC civil date and time of a Unix timestamp. +fn civil(secs: i64) -> (i64, i64, i64, i64, i64, i64) { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + 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 = yoe + era * 400 + i64::from(m <= 2); + (y, m, d, rem / 3600, rem % 3600 / 60, rem % 60) +} + +impl Game<'_> { + /// CommandSourceStack.getPlayerOrException. + fn source_player(&self) -> R { + match self.command_source.map(|s| s.entity) { + None | Some(Some(Target::Player)) => Ok(Target::Player), + _ => Err(err("permissions.requires.player", &[])), + } + } + /// EntityArgument.getEntity / getPlayer. + fn one_entity(&mut self, ctx: &Context, name: &str, player: bool) -> R { + Ok(self.entities(ctx, name, player)?[0]) + } + + // ---- /spectate ------------------------------------------------------ + + /// `SpectateCommand.spectate`. + pub(super) fn cmd_spectate(&mut self, ctx: &Context) -> R { + let target = if ctx.get("target").is_some() { + Some(self.one_entity(ctx, "target", false)?) + } else { + None + }; + let player = if ctx.get("player").is_some() { + self.one_entity(ctx, "player", true)? + } else { + self.source_player()? + }; + if target == Some(player) { + return Err(err("commands.spectate.self", &[])); + } + if !self.spectator() { + return Err(tr_error( + "commands.spectate.not_spectator", + &[self.target_name(player)], + )); + } + // EntityType.clientTrackingRange: only a marker's is zero. + if let Some(t) = target + && self.target_type(t) == "minecraft:marker" + { + return Err(tr_error( + "commands.spectate.cannot_spectate", + &[self.target_name(t)], + )); + } + self.set_camera(target); + match target { + Some(t) => { + let name = self.target_name(t); + self.feedback(Text::translate( + "commands.spectate.success.started", + &[name], + )); + } + None => self.feedback(Text::translate("commands.spectate.success.stopped", &[])), + } + Ok(1) + } + /// `ServerPlayer.setCamera`: a new camera moves the player to it. + pub(in crate::game) fn set_camera(&mut self, target: Option) { + let target = target.filter(|t| *t != Target::Player); + if self.cmds.camera == target { + return; + } + self.cmds.camera = target; + if let Some(t) = target + && let Some(p) = self.target_position(t) + && let Some(player) = self.player.as_mut() + { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + self.previous_position = player.position; + } + } + /// Per-tick server work of these commands: the delayed tick profiler + /// start, queued messages and the spectator camera. + pub(in crate::game) fn tick_command_extras(&mut self) { + if self.cmds.profiler_delay { + self.cmds.profiler_delay = false; + self.cmds.profiler = Some((Instant::now(), self.ticks)); + } + for message in std::mem::take(&mut self.cmds.pending) { + self.system_message(message); + } + self.tick_camera(); + self.tick_waypoints(); + } + /// The camera part of `ServerPlayer.tick`: follow a living camera, drop a + /// removed one, and stop when the player sneaks or leaves spectator mode. + fn tick_camera(&mut self) { + let Some(t) = self.cmds.camera else { + return; + }; + if !self.spectator() { + self.set_camera(None); + return; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) + && self.screen == super::Screen::Playing; + match self.target_position(t) { + Some(p) if !sneaking => { + let rot = self.target_rotation(t); + if let Some(player) = self.player.as_mut() { + player.position = horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + } + self.yaw = rot[0]; + self.pitch = rot[1]; + } + _ => self.set_camera(None), + } + } + /// The eye height the camera follows (`Camera.tick`'s entity). + pub(in crate::game) fn camera_eye_height(&self) -> Option { + self.cmds.camera.map(|t| self.target_eye_height(t) as f32) + } + + // ---- /waypoint ------------------------------------------------------ + + /// A living entity's `waypoint_transmit_range` (`isTransmittingWaypoint`). + fn transmit_range(&mut self, t: Target) -> f64 { + if t == Target::Player { + return self + .player + .as_mut() + .and_then(|p| { + let k = p.attributes.key("minecraft:waypoint_transmit_range")?; + p.attributes + .value(Some(k), horizon_world::attribute_map::ValueKind::Computed) + .ok() + }) + .unwrap_or(0.0); + } + let catalog = self.motion.attributes.clone(); + let Some(key) = catalog.id("minecraft:waypoint_transmit_range") else { + return 0.0; + }; + match self.cmds.attributes.get_mut(&t) { + Some(map) => map.value(key).unwrap_or(0.0), + None => 0.0, + } + } + /// `ServerWaypointManager.transmitters()`: the tracked set. The player + /// joins tracked when transmitting; a changed range takes effect when the + /// entity next ticks (`LivingEntity.onAttributeUpdated`), and + /// `/waypoint modify` re-tracks its waypoint whatever its range. + fn waypoint_transmitters(&mut self) -> Vec { + if self.cmds.waypoints.is_none() { + let tracked = if self.transmit_range(Target::Player) > 0.0 { + vec![Target::Player] + } else { + Vec::new() + }; + self.cmds.waypoints = Some(tracked); + } + let tracked = self.cmds.waypoints.clone().unwrap_or_default(); + let alive: Vec = tracked + .into_iter() + .filter(|t| self.target_position(*t).is_some()) + .collect(); + self.cmds.waypoints = Some(alive.clone()); + alive + } + /// The waypoint part of a living entity's tick: dirty transmit ranges + /// track or untrack it. + pub(in crate::game) fn tick_waypoints(&mut self) { + let dirty = std::mem::take(&mut self.cmds.waypoint_dirty); + if dirty.is_empty() { + return; + } + self.waypoint_transmitters(); + for t in dirty { + let on = self.transmit_range(t) > 0.0; + if let Some(tracked) = self.cmds.waypoints.as_mut() { + tracked.retain(|x| *x != t); + if on { + tracked.push(t); + } + } + } + } + fn waypoint_icon(&self, t: Target) -> WaypointIcon { + self.cmds + .waypoint_icons + .get(&t) + .cloned() + .unwrap_or_default() + } + /// `WaypointArgument.getWaypoint`. + fn waypoint_arg(&mut self, ctx: &Context) -> R { + let t = self.one_entity(ctx, "waypoint", false)?; + if !self.is_living(t) { + return Err(err("argument.waypoint.invalid", &[])); + } + Ok(t) + } + fn is_living(&self, t: Target) -> bool { + matches!(t, Target::Player | Target::Mob(_) | Target::Stand(_)) + } + pub(super) fn cmd_waypoint(&mut self, id: &str, ctx: &Context) -> R { + if id == "waypoint.list" { + let dimension = self.dim.id(); + let waypoints = self.waypoint_transmitters(); + if waypoints.is_empty() { + self.feedback(Text::translate( + "commands.waypoint.list.empty", + &[Text::literal(dimension)], + )); + return Ok(0); + } + let mut names = Text::empty(); + for (i, t) in waypoints.iter().enumerate() { + if i > 0 { + names.push(", "); + } + let pos = self + .target_position(*t) + .unwrap_or_default() + .map(|v| v.floor() as i32); + let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF; + let style = Style { + color: Some(color), + suggest: Some(format!( + "/execute in {dimension} run tp @s {} {} {}", + pos[0], pos[1], pos[2] + )), + hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))), + ..Style::default() + }; + // getFeedbackDisplayName().copy().withStyle(color): the + // waypoint colour replaces the team colour of the name. + let name = match ( + *t, + self.score + .board + .players_team(super::super::chat::PLAYER_NAME), + ) { + (Target::Player, Some(team)) => { + let mut n = Text::empty(); + n.push(horizon_client::scoreboard::comp_text(&team.prefix)); + n.push(super::super::chat::PLAYER_NAME); + n.push(horizon_client::scoreboard::comp_text(&team.suffix)); + n + } + _ => self.target_name(*t), + }; + names.push(name.with_style(&style)); + } + let n = waypoints.len() as i32; + self.feedback(Text::translate( + "commands.waypoint.list.success", + &[num(n), Text::literal(dimension), names], + )); + return Ok(n); + } + let t = self.waypoint_arg(ctx)?; + let mut icon = self.waypoint_icon(t); + let style_literal = ctx.literals.iter().any(|l| l == "style"); + let message = if style_literal { + icon.style = if ctx.literals.iter().any(|l| l == "reset") { + "minecraft:default".into() + } else { + match ctx.get("style") { + Some(Arg::Resource(s)) => s.clone(), + _ => "minecraft:default".into(), + } + }; + Text::translate("commands.waypoint.modify.style", &[]) + } else if ctx.literals.iter().any(|l| l == "reset") { + icon.color = None; + Text::translate("commands.waypoint.modify.color.reset", &[]) + } else if ctx.literals.iter().any(|l| l == "hex") { + let rgb = match ctx.get("color") { + Some(Arg::Int(v)) => *v, + _ => 0, + }; + icon.color = Some(rgb); + let hex = format!("{:06X}", rgb as u32 & 0xFF_FFFF); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(hex, rgb as u32 & 0xFF_FFFF)], + ) + } else { + let name = match ctx.get("color") { + Some(Arg::Str(s)) => s.clone(), + _ => "white".into(), + }; + let rgb = text::named_color(&name).unwrap_or(0xFF_FFFF); + icon.color = Some(rgb as i32); + Text::translate( + "commands.waypoint.modify.color", + &[Text::colored(name, rgb)], + ) + }; + self.cmds.waypoint_icons.insert(t, icon); + // WaypointCommand.mutateIcon: untrack, change, track again. + self.waypoint_transmitters(); + if let Some(tracked) = self.cmds.waypoints.as_mut() { + tracked.retain(|x| *x != t); + tracked.push(t); + } + self.feedback(message); + Ok(0) + } + + // ---- /dialog -------------------------------------------------------- + + pub(super) fn cmd_dialog(&mut self, id: &str, ctx: &Context) -> R { + let targets = self.entities(ctx, "targets", true)?; + let n = targets.len() as i32; + if id == "dialog.show" { + let Some(Arg::Resource(dialog)) = ctx.get("dialog").cloned() else { + return Ok(0); + }; + self.open_dialog(&dialog)?; + } else { + self.close_dialog(); + } + let (single, multiple) = if id == "dialog.show" { + ( + "commands.dialog.show.single", + "commands.dialog.show.multiple", + ) + } else { + ( + "commands.dialog.clear.single", + "commands.dialog.clear.multiple", + ) + }; + let message = if n == 1 { + Text::translate(single, &[self.target_name(targets[0])]) + } else { + Text::translate(multiple, &[num(n)]) + }; + self.feedback(message); + Ok(n) + } + + // ---- /posteffect ---------------------------------------------------- + + pub(super) fn cmd_posteffect(&mut self, id: &str, ctx: &Context) -> R { + if id == "posteffect.list" { + let t = self.one_entity(ctx, "target", true)?; + let name = self.target_name(t); + let effects = self.cmds.post_effects.clone(); + if effects.is_empty() { + self.feedback(Text::translate("commands.posteffect.list.empty", &[name])); + } else { + self.feedback(Text::translate( + "commands.posteffect.list.success", + &[name, num(effects.len()), Text::literal(effects.join(", "))], + )); + } + return Ok(effects.len() as i32); + } + let targets = self.entities(ctx, "targets", true)?; + let effect = match ctx.get("posteffect") { + Some(Arg::Resource(s)) => s.clone(), + _ => String::new(), + }; + let mut changed: Vec = Vec::new(); + for t in &targets { + let done = match id { + "posteffect.add" => { + if self.cmds.post_effects.contains(&effect) { + false + } else { + self.cmds.post_effects.push(effect.clone()); + true + } + } + "posteffect.remove" => { + let before = self.cmds.post_effects.len(); + if let Some(i) = self.cmds.post_effects.iter().position(|e| *e == effect) { + self.cmds.post_effects.remove(i); + } + before != self.cmds.post_effects.len() + } + _ => !std::mem::take(&mut self.cmds.post_effects).is_empty(), + }; + if done { + changed.push(*t); + } + } + let key = id.trim_start_matches("posteffect."); + if changed.is_empty() { + return Err(err(&format!("commands.posteffect.{key}.failed"), &[])); + } + let n = changed.len() as i32; + let effect_text = Text::literal(effect); + let message = match (key, n) { + ("clear", 1) => Text::translate( + "commands.posteffect.clear.success.single", + &[self.target_name(changed[0])], + ), + ("clear", _) => { + Text::translate("commands.posteffect.clear.success.multiple", &[num(n)]) + } + (_, 1) => Text::translate( + &format!("commands.posteffect.{key}.success.single"), + &[effect_text, self.target_name(changed[0])], + ), + _ => Text::translate( + &format!("commands.posteffect.{key}.success.multiple"), + &[effect_text, num(n)], + ), + }; + self.feedback(message); + Ok(n) + } + + // ---- /test ---------------------------------------------------------- + + /// `TestCommand`. Horizon has no game test instances or test runner: every + /// finder comes back empty, as in a world without test instance blocks. + pub(super) fn cmd_test(&mut self, id: &str, ctx: &Context) -> R { + match id { + // run , runmultiple, verify: GameTestRunner. + "test.run" | "test.verify" | "test.create" => Err(err("command.failed", &[])), + // runthese/runclosest/runthat/runfailed: TestFinder finds nothing. + "test.run.found" => { + if ctx.literals.iter().any(|l| l == "runthat") { + self.source_player()?; + } + self.feedback(Text::translate("commands.test.no_tests", &[])); + Ok(0) + } + // reset*/clear*: TestCommand.reset throws CLEAR_NO_TESTS too. + "test.clear" => { + if ctx + .literals + .iter() + .any(|l| l == "resetthat" || l == "clearthat") + { + self.source_player()?; + } + Err(err("commands.test.clear.error.no_tests", &[])) + } + "test.stop" => Ok(1), + "test.locate" => { + // CommandSourceStack.sendSystemMessage: no feedback rule. + if !self.command_source.is_some_and(|s| s.silent) { + self.system_message(Text::translate("commands.test.locate.started", &[])); + } + Err(err("commands.test.error.no_test_instances", &[])) + } + _ => { + // TestCommand.showPos: the block the player looks at (10 blocks). + self.source_player()?; + let p = self.test_pick_block(); + Err(err( + "commands.test.error.no_test_containing_pos", + &[&p[0], &p[1], &p[2]], + )) + } + } + } + /// `Entity.pick(10, 1, false)`: the first non-air block on the view ray, + /// else the block at the ray's end. + fn test_pick_block(&self) -> [i32; 3] { + use horizon_core::{ + geometry::{Vec3, traverse_blocks}, + position::BlockPos, + }; + let Some(p) = self.player.as_ref() else { + return [0; 3]; + }; + let eye = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ); + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); + let dir = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let end = Vec3::new( + eye.x + dir[0] * 10.0, + eye.y + dir[1] * 10.0, + eye.z + dir[2] * 10.0, + ); + let hit = traverse_blocks(eye, end, 256, |b: BlockPos| { + let state = self.world.block(b.x, b.y, b.z); + (!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z]) + }); + hit.ok().flatten().unwrap_or([ + end.x.floor() as i32, + end.y.floor() as i32, + end.z.floor() as i32, + ]) + } + + // ---- /kick ---------------------------------------------------------- + + /// `KickCommand.kickPlayers`: only guests of a published world can be + /// kicked; the owner never. + pub(super) fn cmd_kick(&mut self, ctx: &Context) -> R { + let selector = match ctx.get("targets") { + Some(Arg::Entity(s)) => Some(s.clone()), + _ => None, + }; + // EntityArgument.getPlayers runs before the published check. + let host = self.entities(ctx, "targets", true).unwrap_or_default(); + let guests: Vec<(u32, String)> = match (&self.lan, &selector) { + (Some(lan), Some(s)) => lan + .hub + .guests + .iter() + .filter(|g| match &s.player_name { + Some(name) => g.name.eq_ignore_ascii_case(name), + None => s.kind == 'a' || s.kind == 'e', + }) + .map(|g| (g.conn, g.name.clone())) + .collect(), + _ => Vec::new(), + }; + if host.is_empty() && guests.is_empty() { + return Err(err("argument.entity.notfound.player", &[])); + } + if self.lan.is_none() { + return Err(err("commands.kick.singleplayer.failed", &[])); + } + let reason_raw = match ctx.get("reason") { + Some(Arg::Str(s)) => Some(s.clone()), + _ => None, + }; + let reason = match &reason_raw { + Some(raw) => self.expand_selectors(raw), + None => Text::translate("multiplayer.disconnect.kicked", &[]), + }; + let tag = match &reason_raw { + Some(_) => horizon_world::nbt::Tag::String(reason.plain().as_str().into()), + None => horizon_world::nbt::Tag::compound([( + "translate", + horizon_world::nbt::Tag::String("multiplayer.disconnect.kicked".into()), + )]), + }; + let mut count = 0; + for (conn, name) in guests { + if let Some(lan) = self.lan.as_mut() { + lan.hub.kick(conn, tag.clone()); + } + self.feedback(Text::translate( + "commands.kick.success", + &[Text::literal(name), reason.clone()], + )); + count += 1; + } + if count == 0 { + return Err(err("commands.kick.owner.failed", &[])); + } + Ok(count) + } + + // ---- /fetchprofile -------------------------------------------------- + + /// `FetchProfileCommand`: Horizon resolves no profiles over the network, + /// so name and id lookups fail like an unreachable profile service; an + /// entity with a profile (the player) prints its resolved profile. + pub(super) fn cmd_fetchprofile(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "name") { + let name = match ctx.get("name") { + Some(Arg::Str(s)) => s.clone(), + _ => String::new(), + }; + // Resolved off-thread; the answer arrives on a later tick. + self.cmds.pending.push( + Text::translate("commands.fetchprofile.name.failure", &[Text::literal(name)]) + .with_color(text::RED), + ); + return Ok(1); + } + if ctx.literals.iter().any(|l| l == "id") { + let id = match ctx.get("id") { + Some(Arg::Str(s)) => s.to_ascii_lowercase(), + _ => String::new(), + }; + self.cmds.pending.push( + Text::translate("commands.fetchprofile.id.failure", &[Text::literal(id)]) + .with_color(text::RED), + ); + return Ok(1); + } + let t = self.one_entity(ctx, "entity", false)?; + if t != Target::Player { + return Err(tr_error( + "commands.fetchprofile.no_profile", + &[self.target_name(t)], + )); + } + let profile = self.player_profile_snbt(); + let name = super::super::chat::PLAYER_NAME; + let head = format!("{{type:\"minecraft:player\",player:{profile}}}"); + let item = |key: &str, args: &[Text], run: Option| { + let inner = Text::translate(key, args).with_color(text::GREEN); + let mut t = Text::translate("chat.square_brackets", &[inner]); + if let Some(cmd) = run { + t = t.with_style(&Style { + suggest: None, + ..Style::default() + }); + let _ = cmd; + } + t + }; + let placeholder = Text::literal("\u{FFFC}").with_color(text::WHITE); + let mut clickable = item("commands.fetchprofile.copy_component", &[], None); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.give_item", + &[], + Some(format!("give @s minecraft:player_head[profile={profile}]")), + )); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.summon_mannequin", + &[], + Some(format!( + "summon minecraft:mannequin ~ ~ ~ {{profile:{profile}}}" + )), + )); + clickable.push(" "); + clickable.push(item( + "commands.fetchprofile.copy_text", + &[placeholder], + None, + )); + let _ = head; + self.feedback(Text::translate( + "commands.fetchprofile.entity.success", + &[Text::literal(name), clickable], + )); + Ok(1) + } + /// ResolvableProfile.CODEC of the player's profile as SNBT. + fn player_profile_snbt(&self) -> String { + let [a, b, c, d] = self.level.player_uuid.unwrap_or([0; 4]); + format!( + "{{id:[I;{a},{b},{c},{d}],name:\"{}\",properties:[]}}", + super::super::chat::PLAYER_NAME + ) + } + + // ---- /publish, /unpublish ------------------------------------------- + + /// `PublishCommand.publish` with `IntegratedServer.publishServer`. + pub(super) fn cmd_publish(&mut self, ctx: &Context) -> R { + let allow = matches!(ctx.get("allowCommands"), Some(Arg::Bool(true))); + let port = match ctx.get("port") { + Some(Arg::Int(p)) => *p, + // HttpUtil.getAvailablePort. + _ => std::net::TcpListener::bind(("0.0.0.0", 0)) + .and_then(|l| l.local_addr()) + .map_or(25564, |a| i32::from(a.port())), + }; + if let Some(lan) = &self.lan { + return Err(err( + "commands.publish.alreadyPublished.lan", + &[&lan.settings.port], + )); + } + let settings = super::super::lan::LanSettings { + port: port as u16, + guest_commands: allow, + force_game_mode: false, + }; + if self.lan_start(settings).is_err() { + return Err(err("commands.publish.failed", &[])); + } + let port_text = port.to_string(); + let link = Text::literal(port_text.clone()).with_style(&Style { + color: Some(text::GREEN), + hover: Some(Box::new(Text::translate("chat.copy.click", &[]))), + ..Style::default() + }); + self.feedback(Text::translate( + "commands.publish.started.lan", + &[Text::translate("chat.square_brackets", &[link])], + )); + Ok(port) + } + pub(super) fn cmd_unpublish(&mut self) -> R { + if self.lan.is_none() { + return Err(err("commands.unpublish.notPublished", &[])); + } + self.lan_close(false); + self.feedback(Text::translate("commands.unpublish.success", &[])); + Ok(1) + } + + // ---- /debug, /jfr, /version ----------------------------------------- + + pub(super) fn cmd_debug(&mut self, ctx: &Context) -> R { + if ctx.literals.iter().any(|l| l == "function") { + return self.cmd_debug_function(ctx); + } + // MinecraftServer.isTimeProfilerRunning / startTimeProfiler / + // stopTimeProfiler: a stop before the delayed start took effect + // reports empty results and leaves the start pending. + let running = self.cmds.profiler_delay || self.cmds.profiler.is_some(); + if ctx.literals.iter().any(|l| l == "start") { + if running { + return Err(err("commands.debug.alreadyRunning", &[])); + } + self.cmds.profiler_delay = true; + self.feedback(Text::translate("commands.debug.started", &[])); + return Ok(0); + } + if !running { + return Err(err("commands.debug.notRunning", &[])); + } + let (seconds, ticks) = match self.cmds.profiler.take() { + Some((started, ticks)) => ( + started.elapsed().as_nanos() as f64 / 1.0e9, + (self.ticks - ticks) as f64, + ), + None => (0.0, 0.0), + }; + let tps = ticks / seconds; + self.feedback(Text::translate( + "commands.debug.stopped", + &[ + Text::literal(two_places(seconds)), + num(ticks as i64), + Text::literal(two_places(tps)), + ], + )); + Ok(tps as i32) + } + /// `DebugCommand.TraceCustomExecutor`: run the functions with a tracer + /// writing to `debug/debug-trace-