diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b38fb8469..971b29d0b 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1118,6 +1118,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/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 6742e7043..be0a6b0df 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(), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index e61a2ad00..bded8ef1e 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -335,6 +335,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(':', ".")), &[]) } @@ -585,7 +600,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), @@ -734,6 +760,57 @@ impl Game<'_> { .append("]") .with_color(color) } + /// `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) + } /// ItemStack.getDisplayName of a renamed stack: the name in italics. pub(super) fn item_display_name_custom(&self, item: &str, custom: &str) -> Text { let color = self.item_display_name(item).spans.first().and_then(|s| s.style.color); @@ -813,10 +890,12 @@ impl Game<'_> { } } } - let name = match extra.as_ref().and_then(|e| e.custom_name.clone()) { - Some(custom) => self.item_display_name_custom(&id, &custom), - None => 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", @@ -1256,6 +1335,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()); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index ce3869428..ea2bc49e2 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) => { @@ -231,9 +246,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); @@ -242,7 +264,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)), } @@ -631,10 +658,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) { @@ -667,18 +695,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/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index 6184cb7f6..498898d92 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -45,6 +45,13 @@ pub(in crate::game) struct CommandExtras { pub waypoint_icons: HashMap, /// The dialog `/dialog show` opened (its id or inline definition). pub dialog: Option, + /// 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>, @@ -127,6 +134,15 @@ impl Game<'_> { &[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) => { @@ -163,6 +179,7 @@ impl Game<'_> { 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. @@ -197,19 +214,67 @@ impl Game<'_> { // ---- /waypoint ------------------------------------------------------ - /// `ServerWaypointManager.transmitters()`: living entities whose - /// `waypoint_transmit_range` is positive. - fn waypoint_transmitters(&mut self) -> Vec { - let mut out = Vec::new(); - if let Some(p) = self.player.as_mut() - && let Some(k) = p.attributes.key("minecraft:waypoint_transmit_range") - && p.attributes - .value(Some(k), horizon_world::attribute_map::ValueKind::Computed) - .is_ok_and(|v| v > 0.0) - { - out.push(Target::Player); + /// 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); + } + } } - out } fn waypoint_icon(&self, t: Target) -> WaypointIcon { self.cmds.waypoint_icons.get(&t).cloned().unwrap_or_default() @@ -316,6 +381,12 @@ impl Game<'_> { ) }; 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) } diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index fb1bf3c27..d5fd2433e 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -7,6 +7,7 @@ use horizon_client::{ scoreboard_cmd::{Holder, Tracker}, text::Text, }; +use horizon_world::nbt::Tag; /// One addressable slot. #[derive(Clone, Debug, PartialEq)] @@ -290,7 +291,7 @@ impl Game<'_> { } } fn stack_name(&self, s: &ItemStack) -> Text { - self.item_display_name(&s.item) + self.stack_display_name(s) } fn item_from_input(&self, ctx: &Context) -> R> { let Some(Arg::Item(ItemInput { id, components, .. })) = ctx.get("item").cloned() else { @@ -351,12 +352,13 @@ impl Game<'_> { }, Value::Object(_) => { let mut stack = stack?; - if !m["conditions"].is_null() - && !self.conditions_hold(&m["conditions"], this, origin) + // 26.3 item modifiers: a single `condition`, dispatched on `type`. + if !m["condition"].is_null() + && !self.conditions_hold(&m["condition"], this, origin) { return Some(stack); } - match m["function"].as_str().unwrap_or("") { + match m["type"].as_str().unwrap_or("") { "minecraft:sequence" => { #[allow(clippy::manual_try_fold)] return m["functions"] @@ -408,9 +410,19 @@ impl Game<'_> { } } "minecraft:set_name" => { - let t = horizon_client::packs::component(&m["name"]); - stack.extra.get_or_insert_with(Default::default).custom_name = - Some(t.plain()); + if m["name"].is_null() { + return Some(stack); + } + if m["target"].as_str() == Some("item_name") { + let name = horizon_client::scoreboard::json_to_tag(&m["name"]); + edit_components(&mut stack, |c| { + c.insert("minecraft:item_name".into(), name); + }); + } else { + let t = horizon_client::packs::component(&m["name"]); + stack.extra.get_or_insert_with(Default::default).custom_name = + Some(t.plain()); + } } "minecraft:set_enchantments" => { let add = m["add"].as_bool() == Some(true); @@ -440,6 +452,126 @@ impl Game<'_> { Some(p.into()); } } + "minecraft:set_lore" => { + let lines: Vec = m["lore"] + .as_array() + .into_iter() + .flatten() + .map(horizon_client::scoreboard::json_to_tag) + .collect(); + edit_components(&mut stack, |c| { + let old: Vec = match c.get(&"minecraft:lore".into()) { + Some(Tag::List(l)) => l.clone(), + _ => Vec::new(), + }; + let new = list_operation(&m, old, lines); + c.insert("minecraft:lore".into(), Tag::List(new)); + }); + } + "minecraft:set_custom_data" => { + let tag = match &m["tag"] { + Value::String(snbt) => horizon_world::nbt::parse_snbt(snbt) + .map(|(t, _)| t) + .unwrap_or(Tag::Compound(Default::default())), + v => horizon_client::scoreboard::json_to_tag(v), + }; + edit_components(&mut stack, |c| { + let mut data = match c.get(&"minecraft:custom_data".into()) { + Some(t @ Tag::Compound(_)) => t.clone(), + _ => Tag::Compound(Default::default()), + }; + merge_compound(&mut data, &tag); + c.insert("minecraft:custom_data".into(), data); + }); + } + "minecraft:set_components" => { + let patch = m["components"].clone(); + edit_components(&mut stack, |c| { + for (k, v) in patch.as_object().into_iter().flatten() { + let (remove, key) = match k.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, k.as_str()), + }; + let key = if key.contains(':') { + key.to_owned() + } else { + format!("minecraft:{key}") + }; + if remove { + c.remove(&key.as_str().into()); + } else { + c.insert( + key.as_str().into(), + horizon_client::scoreboard::json_to_tag(v), + ); + } + } + }); + } + "minecraft:toggle_tooltips" => { + let toggles = m["toggles"].clone(); + edit_components(&mut stack, |c| { + let mut hidden: Vec = c + .get(&"minecraft:tooltip_display".into()) + .and_then(|d| d.get("hidden_components")) + .and_then(|l| match l { + Tag::List(l) => Some( + l.iter() + .filter_map(|t| match t { + Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + }) + .collect(), + ), + _ => None, + }) + .unwrap_or_default(); + let hide_tooltip = c + .get(&"minecraft:tooltip_display".into()) + .and_then(|d| d.get("hide_tooltip")) + .cloned(); + for (k, shown) in toggles.as_object().into_iter().flatten() { + let key = if k.contains(':') { + k.clone() + } else { + format!("minecraft:{k}") + }; + hidden.retain(|h| *h != key); + if shown.as_bool() == Some(false) { + hidden.push(key); + } + } + let mut display: Vec<(&str, Tag)> = Vec::new(); + if let Some(h) = hide_tooltip { + display.push(("hide_tooltip", h)); + } + if !hidden.is_empty() { + display.push(( + "hidden_components", + Tag::List( + hidden.iter().map(|h| Tag::String(h.as_str().into())).collect(), + ), + )); + } + c.insert("minecraft:tooltip_display".into(), Tag::compound(display)); + }); + } + "minecraft:filtered" => { + let pass = self.loot_item_filter(&m["item_filter"], &stack); + let branch = if pass { &m["on_pass"] } else { &m["on_fail"] }; + if branch.is_null() { + return Some(stack); + } + return self.apply_item_modifier( + branch, + Some(stack), + rng, + this, + origin, + depth + 1, + ); + } + "minecraft:discard" => stack.count = 0, _ => {} } (stack.count > 0).then_some(stack) @@ -447,6 +579,38 @@ impl Game<'_> { _ => stack, } } + /// `ItemStack.getMaxStackSize`: the max_stack_size component, else the + /// item's. + pub(super) fn stack_max_size(&self, s: &ItemStack) -> u32 { + if let Some(Tag::Int(n)) = s.data().and_then(|d| d.other("minecraft:max_stack_size")) { + return (*n).clamp(1, 99) as u32; + } + self.res.items.get(&s.item).map_or(64, |i| i.max_stack) + } + /// `ResourceOrIdArgument.getItemModifier`: an inline modifier (SNBT) or + /// a registered one. + pub(super) fn item_modifier_arg(&mut self, ctx: &Context, name: &str) -> R { + let raw = match ctx.get(name) { + Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(), + _ => return Err(err("command.failed", &[])), + }; + if raw.starts_with('{') || raw.starts_with('[') { + let (tag, _) = horizon_world::nbt::parse_snbt(&raw) + .map_err(|e| err("argument.nbt.invalid", &[&e]))?; + return Ok(horizon_client::scoreboard::tag_to_json(&tag)); + } + let id = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + self.fns + .store + .item_modifiers + .get(&id) + .cloned() + .ok_or_else(|| err("argument.item_modifier.unknown", &[&id])) + } /// `/item modify (entity|block) `. pub(super) fn cmd_item_modify(&mut self, ctx: &Context) -> R { self.ensure_datapacks(); @@ -454,17 +618,7 @@ impl Game<'_> { let Some(Arg::Str(slot_name)) = ctx.get("slot").cloned() else { return Ok(0); }; - let Some(Arg::Str(id)) = ctx.get("modifier").cloned() else { - return Ok(0); - }; - let id = if id.contains(':') { - id - } else { - format!("minecraft:{id}") - }; - let Some(modifier) = self.fns.store.item_modifiers.get(&id).cloned() else { - return Err(err("argument.item_modifier.unknown", &[&id])); - }; + let modifier = self.item_modifier_arg(ctx, "modifier")?; let source = self.command_source.unwrap_or_else(|| self.player_source()); let view = source.entity.map(|t| self.entity_view_of(t)); let seed = std::time::SystemTime::now() @@ -501,7 +655,14 @@ impl Game<'_> { source.pos, 0, ); - if new.as_ref() != Some(¤t) && self.slot_set(slot, new) { + // CountingModifier: every slot set counts, changed or not; + // ItemStack.limitSize to the (new) max stack size. + let new = new.map(|mut s| { + let max = self.stack_max_size(&s); + s.count = s.count.min(max); + s + }); + if self.slot_set(slot, new) { changed += 1; } } @@ -582,6 +743,28 @@ impl Game<'_> { _ => err("commands.item.source.no_such_slot", &[&source_slots]), }); } + // ItemCommands.applyModifier on each source stack. + if ctx.get("modifier").is_some() { + let modifier = self.item_modifier_arg(ctx, "modifier")?; + let source = self.command_source.unwrap_or_else(|| self.player_source()); + let view = source.entity.map(|t| self.entity_view_of(t)); + let mut rng = horizon_core::random::LegacyRandom::new(0); + found = found + .into_iter() + .map(|s| { + s.and_then(|s| { + self.apply_item_modifier( + &modifier, + Some(s), + &mut rng, + view.as_ref(), + source.pos, + 0, + ) + }) + }) + .collect(); + } // A source with nothing in the slot contributes air. (found, None) }; @@ -715,3 +898,62 @@ impl Game<'_> { Ok((count > 0, count)) } } + +/// Edit a stack's components as their saved compound. +fn edit_components(stack: &mut ItemStack, f: impl FnOnce(&mut horizon_world::nbt::Compound)) { + let mut c = match horizon_client::item_data::encode_components(stack) { + Some(Tag::Compound(c)) => c, + _ => horizon_world::nbt::Compound::new(), + }; + f(&mut c); + let tag = Tag::Compound(c); + let (damage, extra) = horizon_client::item_data::decode_components(Some(&tag)); + stack.damage = damage; + stack.extra = extra; + stack.tidy(); +} +/// `CompoundTag.merge`: nested compounds merge, other values replace. +fn merge_compound(into: &mut Tag, from: &Tag) { + let (Tag::Compound(a), Tag::Compound(b)) = (into, from) else { + return; + }; + for (k, v) in b { + match (a.get_mut(k), v) { + (Some(existing @ Tag::Compound(_)), Tag::Compound(_)) => merge_compound(existing, v), + _ => { + a.insert(k.clone(), v.clone()); + } + } + } +} +/// `ListOperation.apply` (`mode`: replace_all, replace_section, insert, +/// append) with a 256-entry limit. +fn list_operation(m: &serde_json::Value, old: Vec, new: Vec) -> Vec { + let offset = m["offset"].as_u64().unwrap_or(0) as usize; + let mut out = match m["mode"].as_str().unwrap_or("") { + "replace_all" => new, + "insert" => { + let at = offset.min(old.len()); + let mut out = old[..at].to_vec(); + out.extend(new); + out.extend_from_slice(&old[at..]); + out + } + "replace_section" => { + let at = offset.min(old.len()); + let size = m["size"].as_u64().map_or(new.len(), |s| s as usize); + let mut out = old[..at].to_vec(); + out.extend(new); + let end = (at + size).min(old.len()); + out.extend_from_slice(&old[end..]); + out + } + _ => { + let mut out = old; + out.extend(new); + out + } + }; + out.truncate(256); + out +} diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 948190d67..1ec77dbf7 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -254,6 +254,8 @@ impl Game<'_> { m.ai.swing_time = -1; } } + // An armor stand is a LivingEntity: it swings (invisibly). + Target::Stand(_) => {} _ => continue, } let h = holder(self.target_name(t)); @@ -623,10 +625,7 @@ impl Game<'_> { .has_modifier(Some(key), &modifier_id) .unwrap_or(false) { - return Err(err( - "commands.attribute.failed.modifier_already_present", - &[&modifier_id, &description.plain(), &name.plain()], - )); + return Err(text_error("commands.attribute.failed.modifier_already_present", &[Text::literal(modifier_id.clone()), description.clone(), name.clone()])); } let op = ctx .literals @@ -648,10 +647,7 @@ impl Game<'_> { .has_modifier(Some(key), &modifier_id) .unwrap_or(false) { - return Err(err( - "commands.attribute.failed.no_modifier", - &[&description.plain(), &name.plain(), &modifier_id], - )); + return Err(text_error("commands.attribute.failed.no_modifier", &[description.clone(), name.clone(), Text::literal(modifier_id.clone())])); } let _ = player.set_modifier(&attribute, &modifier_id, 0.0, "add_value", false); @@ -678,10 +674,7 @@ impl Game<'_> { .ok() .flatten(); let Some(v) = found else { - return Err(err( - "commands.attribute.failed.no_modifier", - &[&description.plain(), &name.plain(), &modifier_id], - )); + return Err(text_error("commands.attribute.failed.no_modifier", &[description.clone(), name.clone(), Text::literal(modifier_id.clone())])); }; self.feedback(Text::translate( "commands.attribute.modifier.value.get.success", @@ -696,6 +689,26 @@ impl Game<'_> { } } } + Target::Mob(_) | Target::Stand(_) + if !(matches!(target, Target::Mob(_)) + && matches!( + short.as_str(), + "max_health" | "movement_speed" | "attack_damage" + )) => + { + let op = ctx + .literals + .last() + .cloned() + .unwrap_or_else(|| "add_value".into()); + self.generic_attribute( + target, + id, + &attribute, + (&name, &description), + (value_arg, scale, &modifier_id, &op), + ) + } Target::Mob(mob_id) => { let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) else { return Ok(0); @@ -755,16 +768,143 @@ impl Game<'_> { )); Ok(1) } - _ => Err(err( - "commands.attribute.failed.no_modifier", - &[&description.plain(), &name.plain(), &modifier_id], - )), + _ => Err(text_error("commands.attribute.failed.no_modifier", &[description.clone(), name.clone(), Text::literal(modifier_id.clone())])), } } - _ => Err(err("commands.attribute.failed.entity", &[&name.plain()])), + _ => Err(text_error("commands.attribute.failed.entity", &[name.clone()])), } } + /// The attribute map of a living entity whose attributes Horizon does + /// not model, created from its type's defaults on first use. + pub(in crate::game) fn generic_attributes( + &mut self, + t: Target, + ) -> Option<&mut horizon_world::attributes::entity::EntityAttributes> { + if !self.cmds.attributes.contains_key(&t) { + let ty = self.target_type(t); + let map = self.motion.attributes.create(&ty)?; + self.cmds.attributes.insert(t, map); + } + self.cmds.attributes.get_mut(&t) + } + /// AttributeCommand on a living entity through its generic attribute map. + fn generic_attribute( + &mut self, + target: Target, + id: &str, + attribute: &str, + (name, description): (&Text, &Text), + (value_arg, scale, modifier_id, op): (f64, f64, &str, &str), + ) -> R { + use horizon_world::attributes::{Modifier, Operation}; + let no_attribute = || { + text_error( + "commands.attribute.failed.no_attribute", + &[name.clone(), description.clone()], + ) + }; + let no_modifier = || { + text_error( + "commands.attribute.failed.no_modifier", + &[description.clone(), name.clone(), Text::literal(modifier_id)], + ) + }; + let catalog = self.motion.attributes.clone(); + let key = catalog.id(attribute).ok_or_else(no_attribute)?; + let map = self.generic_attributes(target).ok_or_else(no_attribute)?; + if !map.has(key) { + return Err(no_attribute()); + } + let (message, args, result) = match id { + "attribute.get" | "attribute.base.get" => { + let v = if id == "attribute.get" { + map.value(key).map_err(|_| no_attribute())? + } else { + map.base_value(key).map_err(|_| no_attribute())? + }; + let k = if id == "attribute.get" { + "commands.attribute.value.get.success" + } else { + "commands.attribute.base_value.get.success" + }; + (k, vec![description.clone(), name.clone(), java_double_text(v)], (v * scale) as i32) + } + "attribute.base.set" => { + map.edit(key, |a, o| { + let _ = a.set_base_value(value_arg, o); + }); + ( + "commands.attribute.base_value.set.success", + vec![description.clone(), name.clone(), java_double_text(value_arg)], + 1, + ) + } + "attribute.base.reset" => { + map.reset_base(key); + let v = map.base_value(key).unwrap_or(0.0); + ( + "commands.attribute.base_value.reset.success", + vec![description.clone(), name.clone(), java_double_text(v)], + 1, + ) + } + "attribute.modifier.add" => { + if map.has_modifier(key, modifier_id) { + return Err(text_error( + "commands.attribute.failed.modifier_already_present", + &[Text::literal(modifier_id), description.clone(), name.clone()], + )); + } + let operation = match op { + "add_multiplied_base" => Operation::AddMultipliedBase, + "add_multiplied_total" => Operation::AddMultipliedTotal, + _ => Operation::AddValue, + }; + let m = Modifier::new(modifier_id, value_arg, operation) + .map_err(|_| no_attribute())?; + map.edit(key, |a, o| { + let _ = a.add_permanent(m, o); + }); + ( + "commands.attribute.modifier.add.success", + vec![Text::literal(modifier_id), description.clone(), name.clone()], + 1, + ) + } + "attribute.modifier.remove" => { + if !map.has_modifier(key, modifier_id) { + return Err(no_modifier()); + } + map.edit(key, |a, o| { + let _ = a.remove(modifier_id, o); + }); + ( + "commands.attribute.modifier.remove.success", + vec![Text::literal(modifier_id), description.clone(), name.clone()], + 1, + ) + } + _ => { + let v = map + .modifier_value(key, modifier_id) + .map_err(|_| no_modifier())?; + ( + "commands.attribute.modifier.value.get.success", + vec![ + Text::literal(modifier_id), + description.clone(), + name.clone(), + java_double_text(v), + ], + (v * scale) as i32, + ) + } + }; + self.feedback(Text::translate(message, &args)); + Ok(result) + } + // ---- /ride ---------------------------------------------------------------------------- pub(super) fn cmd_ride(&mut self, id: &str, ctx: &Context) -> R { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 5d51e5e34..31fa56c67 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -443,6 +443,10 @@ impl Game<'_> { } tag } + /// The compound an entity was loaded with (and commands have edited). + pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { + self.persist.raw.get(&id) + } fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) { if let Some(u) = uuid { self.persist.uuids.insert(id, u); diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index e4329a140..1780ccedf 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -56,6 +56,48 @@ pub struct StackData { pub stew_effects: Vec<(Arc, i32)>, /// `minecraft:map_post_processing`: 0 lock, 1 scale. pub map_post_processing: Option, + /// Components Horizon does not model (lore, custom data, item name, + /// max stack size...), kept as their saved values in key order. + pub other: Vec<(String, Tag)>, +} +/// The components `components_tag` writes from modelled fields. +const MODELLED: &[&str] = &[ + "minecraft:banner_patterns", + "minecraft:base_color", + "minecraft:bundle_contents", + "minecraft:charged_projectiles", + "minecraft:container", + "minecraft:custom_name", + "minecraft:damage", + "minecraft:dyed_color", + "minecraft:enchantments", + "minecraft:firework_explosion", + "minecraft:fireworks", + "minecraft:map_id", + "minecraft:map_post_processing", + "minecraft:ominous_bottle_amplifier", + "minecraft:pot_decorations", + "minecraft:potion_contents", + "minecraft:repair_cost", + "minecraft:stored_enchantments", + "minecraft:suspicious_stew_effects", + "minecraft:trim", + "minecraft:writable_book_content", + "minecraft:written_book_content", +]; +impl StackData { + /// An unmodelled component's saved value. + pub fn other(&self, id: &str) -> Option<&Tag> { + self.other.iter().find(|(k, _)| k == id).map(|(_, v)| v) + } + /// Set (or with None remove) an unmodelled component. + pub fn set_other(&mut self, id: &str, value: Option) { + self.other.retain(|(k, _)| k != id); + if let Some(v) = value { + self.other.push((id.to_owned(), v)); + self.other.sort_by(|a, b| a.0.cmp(&b.0)); + } + } } /// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers. pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ @@ -596,7 +638,17 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { entries.push(("minecraft:container", Tag::List(slots))); } } - (!entries.is_empty()).then(|| Tag::compound(entries)) + let mut out: horizon_world::nbt::Compound = entries + .into_iter() + .map(|(k, v)| (JavaString::from(k), v)) + .collect(); + if let Some(d) = data { + for (k, v) in &d.other { + out.entry(JavaString::from(k.as_str())) + .or_insert_with(|| v.clone()); + } + } + (!out.is_empty()).then_some(Tag::Compound(out)) } /// Damage and extra components from a stack's `components` compound. pub fn decode_components(components: Option<&Tag>) -> (u32, Option>) { @@ -729,7 +781,23 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option` a `CompoundTag` holds, +/// for a map that grew to its size by insertion: buckets by +/// `HashMap.hash(String.hashCode())`, keys sharing a bucket in key order. +pub fn java_hash_order( + c: &horizon_world::nbt::Compound, +) -> Vec<(&horizon_world::nbt::JavaString, &Tag)> { + let mut capacity = 16usize; + while c.len() > capacity * 3 / 4 { + capacity *= 2; + } + let bucket = |k: &horizon_world::nbt::JavaString| { + let h = string_of(k) + .encode_utf16() + .fold(0u32, |h, ch| h.wrapping_mul(31).wrapping_add(u32::from(ch))); + ((h ^ (h >> 16)) as usize) & (capacity - 1) + }; + // Keys sharing a bucket iterate in insertion order: the order vanilla's + // savers write them, as far as it is known here. + const WRITE_ORDER: &[&str] = &[ + // ItemStack.CODEC, block entities. + "id", "count", "components", "x", "y", "z", + // Entity.saveWithoutId. + "Pos", "Motion", "Rotation", "fall_distance", "Fire", "Air", "OnGround", + "Invulnerable", "PortalCooldown", "UUID", "CustomName", "CustomNameVisible", + "Silent", "NoGravity", "Glowing", "TicksFrozen", "HasVisualFire", "Tags", + "data", "Passengers", + // LivingEntity.addAdditionalSaveData. + "Health", "HurtTime", "DeathTime", "AbsorptionAmount", + "current_impulse_context_reset_grace_time", "current_explosion_impact_pos", + "attributes", "active_effects", "FallFlying", "sleeping_pos", "Brain", + "equipment", + // ArmorStand. + "Invisible", "Small", "ShowArms", "DisabledSlots", "NoBasePlate", "Marker", + "Pose", + ]; + let rank = |k: &horizon_world::nbt::JavaString| { + let k = string_of(k); + WRITE_ORDER + .iter() + .position(|w| *w == k) + .unwrap_or(WRITE_ORDER.len()) + }; + let mut entries: Vec<_> = c.iter().collect(); + entries.sort_by_key(|(k, _)| (bucket(k), rank(k))); + entries +} /// `NbtUtils.toPrettyComponent`: the coloured, unindented form. pub fn pretty(tag: &Tag) -> Text { pretty_indented(tag, "") diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index ee6fe2fbd..1342d21b4 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -173,7 +173,7 @@ def player_state(): cmd('/enchant @s minecraft:efficiency 9'), cmd('/item replace entity @s armor.head with minecraft:golden_helmet'), cmd('/clear @s minecraft:golden_helmet 0'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_count",count:1}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:1}'), cmd('/clear @s'), cmd('/clear @s'), cmd('/attribute @s minecraft:max_health get'), @@ -338,6 +338,8 @@ def execute(): cmd('/execute align xyz run summon minecraft:armor_stand ~ ~-20 ~ {NoGravity:1b,Tags:["ex"]}'), cmd('/execute if entity @e[tag=ex]'), cmd('/execute as @e[tag=ex] run data get entity @s Pos'), + cmd('/data get entity @e[tag=ex,limit=1]'), + cmd('/data get entity @e[tag=ex,limit=1] Pose'), cmd('/execute anchored eyes run tp @s ^ ^ ^'), cmd('/execute rotated 90 0 run tp @s ~ ~ ~ ~ ~'), cmd('/execute rotated as @e[tag=ex,limit=1] run tp @s ~ ~ ~ ~ ~'), @@ -392,45 +394,46 @@ def execute(): def items_and_loot(): return [ *setup('/clear @s', '/gamemode survival'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_count",count:3}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:3}'), cmd('/item replace entity @s weapon.mainhand with minecraft:stone 10'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_count",count:3}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:3}'), cmd('/clear @s minecraft:stone 0'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_count",count:5,add:true}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:5,add:true}'), cmd('/clear @s minecraft:stone 0'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:limit_count",limit:{max:4}}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:limit_count",limit:{max:4}}'), cmd('/clear @s minecraft:stone 0'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_name",name:"Rock"}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_name",name:"Rock"}'), cmd('/data get entity @s SelectedItem'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_name",name:{text:"Item",color:"red"},target:"item_name"}'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_lore",lore:["one","two"],mode:"replace_all"}'), - cmd('/item modify entity @s weapon.mainhand [{function:"minecraft:set_count",count:2},{function:"minecraft:set_custom_data",tag:{a:1b}}]'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_name",name:{text:"Item",color:"red"},target:"item_name"}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_lore",lore:["one","two"],mode:"replace_all"}'), + cmd('/item modify entity @s weapon.mainhand [{type:"minecraft:set_count",count:2},{type:"minecraft:set_custom_data",tag:{a:1b}}]'), cmd('/data get entity @s SelectedItem'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_components",components:{"minecraft:max_stack_size":16}}'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:filtered",item_filter:{items:"minecraft:dirt"},on_pass:{function:"minecraft:set_count",count:1}}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_components",components:{"minecraft:max_stack_size":16}}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:filtered",item_filter:{items:"minecraft:dirt"},on_pass:{type:"minecraft:set_count",count:1}}'), cmd('/clear @s minecraft:stone 0'), cmd('/item replace entity @s weapon.mainhand with minecraft:diamond_sword'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_damage",damage:0.5}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_damage",damage:0.5}'), cmd('/data get entity @s SelectedItem.components'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":3}}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":3}}'), cmd('/data get entity @s SelectedItem.components."minecraft:enchantments"'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":1},add:true}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":1},add:true}'), cmd('/data get entity @s SelectedItem.components."minecraft:enchantments"'), - cmd('/item modify entity @s weapon.mainhand {function:"minecraft:toggle_tooltips",toggles:{"minecraft:enchantments":false}}'), - cmd('/item modify entity @s armor.head {function:"minecraft:set_count",count:1}'), - cmd('/item modify entity @s weapon.offhand {function:"minecraft:set_count",count:1}'), - cmd('/item modify entity @s hotbar.* {function:"minecraft:set_count",count:1}'), + cmd('/item modify entity @s weapon.mainhand {type:"minecraft:toggle_tooltips",toggles:{"minecraft:enchantments":false}}'), + cmd('/item modify entity @s armor.head {type:"minecraft:set_count",count:1}'), + cmd('/item modify entity @s weapon.offhand {type:"minecraft:set_count",count:1}'), + cmd('/item modify entity @s hotbar.* {type:"minecraft:set_count",count:1}'), cmd('/item modify entity @s weapon.mainhand minecraft:nonexistent'), cmd('/item replace entity @s hotbar.1 from entity @s weapon.mainhand'), - cmd('/item replace entity @s hotbar.2 from entity @s weapon.mainhand {function:"minecraft:set_count",count:1}'), + cmd('/item replace entity @s hotbar.2 from entity @s weapon.mainhand {type:"minecraft:set_count",count:1}'), cmd('/clear @s minecraft:diamond_sword 0'), cmd('/setblock 3 206 3 minecraft:barrel'), cmd('/item replace block 3 206 3 container.4 with minecraft:emerald 7'), - cmd('/item modify block 3 206 3 container.4 {function:"minecraft:set_count",count:2}'), - cmd('/item modify block 3 206 3 container.5 {function:"minecraft:set_count",count:2}'), - cmd('/item modify block 3 206 3 container.99 {function:"minecraft:set_count",count:2}'), - cmd('/item modify block 3 207 3 container.0 {function:"minecraft:set_count",count:2}'), + cmd('/item modify block 3 206 3 container.4 {type:"minecraft:set_count",count:2}'), + cmd('/item modify block 3 206 3 container.5 {type:"minecraft:set_count",count:2}'), + cmd('/item modify block 3 206 3 container.99 {type:"minecraft:set_count",count:2}'), + cmd('/item modify block 3 207 3 container.0 {type:"minecraft:set_count",count:2}'), cmd('/data get block 3 206 3 Items'), + cmd('/data get block 3 206 3'), cmd('/item replace entity @s hotbar.3 from block 3 206 3 container.4'), cmd('/item replace block 3 206 3 container.0 from entity @s hotbar.3'), cmd('/data get block 3 206 3 Items'), @@ -440,7 +443,7 @@ def items_and_loot(): cmd('/loot replace block 3 206 3 container.8 loot minecraft:blocks/cobblestone'), cmd('/loot replace entity @s hotbar.5 loot minecraft:blocks/glass'), cmd('/loot spawn 3 210 3 loot minecraft:blocks/stone'), - cmd('/loot give @s loot {pools:[{rolls:1,entries:[{type:"minecraft:item",name:"minecraft:apple",functions:[{function:"minecraft:set_count",count:4}]}]}]}'), + cmd('/loot give @s loot {pools:[{rolls:1,entries:[{type:"minecraft:item",name:"minecraft:apple",functions:[{type:"minecraft:set_count",count:4}]}]}]}'), cmd('/setblock 2 205 2 minecraft:stone'), cmd('/loot give @s mine 2 205 2'), cmd('/loot give @s mine 2 205 2 mainhand'), @@ -524,17 +527,43 @@ def world_misc(): cmd('/spectate'), cmd('/spectate @e[tag=nothing,limit=1]'), cmd('/gamemode creative'), + # The waypoint manager is a HashSet of entities (identity hash order), + # so at most one transmitter at a time. Range changes take effect when + # the entity ticks. + cmd('/attribute @s minecraft:waypoint_transmit_range base set 0'), + cmd('/waypoint list'), + {'op': 'tick', 'n': 1}, + cmd('/waypoint list'), cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range base set 100'), + cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range get'), + cmd('/waypoint list'), + {'op': 'tick', 'n': 1}, cmd('/waypoint list'), cmd('/waypoint modify @e[type=minecraft:pig,tag=w,limit=1] color gold'), cmd('/waypoint modify @e[tag=mk,limit=1] color gold'), cmd('/waypoint list'), cmd('/waypoint modify @e[tag=w] color gold'), - cmd('/attribute @s minecraft:waypoint_transmit_range base set 0'), - cmd('/waypoint list'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:max_health get'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier add harness:big 1 add_multiplied_base'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale get'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier add harness:big 1 add_value'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier value get harness:big'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier remove harness:big'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier remove harness:big'), + cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:attack_damage get'), + cmd('/attribute @e[tag=mk,limit=1] minecraft:scale get'), cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range base set 0'), + {'op': 'tick', 'n': 1}, + cmd('/waypoint list'), + cmd('/waypoint modify @e[type=minecraft:pig,tag=w,limit=1] style set minecraft:bowtie'), + cmd('/waypoint list'), + {'op': 'tick', 'n': 1}, + cmd('/waypoint list'), + cmd('/kill @e[type=minecraft:pig,tag=w]'), + {'op': 'tick', 'n': 1}, cmd('/waypoint list'), cmd('/attribute @s minecraft:waypoint_transmit_range base reset'), + {'op': 'tick', 'n': 1}, cmd('/waypoint list'), cmd('/dialog show @s minecraft:custom_options'), cmd('/dialog show @s minecraft:nonexistent'), diff --git a/tools/test_command_exec_parity.py b/tools/test_command_exec_parity.py index c4e345f45..c6994e0bb 100644 --- a/tools/test_command_exec_parity.py +++ b/tools/test_command_exec_parity.py @@ -82,7 +82,7 @@ def main(): rust_dir = build / 'rust' shutil.rmtree(rust_dir, ignore_errors=True) rust_dir.mkdir() - env = dict(os.environ, HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl')) + env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl')) run([binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env) vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]