diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index bded8ef1e..c55a4af0c 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1517,7 +1517,12 @@ impl Game<'_> { let _ = self.break_block(pos); self.creative = creative; } - 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( @@ -1526,6 +1531,38 @@ impl Game<'_> { )); Ok(1) } + /// 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")?; @@ -2027,6 +2064,86 @@ 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)? @@ -2047,19 +2164,27 @@ 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 { @@ -2077,35 +2202,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( @@ -2330,3 +2426,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/items.rs b/crates/horizon-client/src/game/commands/items.rs index d5fd2433e..1505ac23f 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -889,7 +889,7 @@ impl Game<'_> { if let Some(stack) = self.slot_get(&s) && predicate .as_ref() - .is_some_and(|p| self.item_matches(p, &stack.item)) + .is_some_and(|p| self.stack_matches(p, &stack)) { count += stack.count as i32; } diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 970a28bb1..6a6eebcb1 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -147,18 +147,11 @@ impl Game<'_> { // ---- /fillbiome ---------------------------------------------------------------- pub(super) fn cmd_fillbiome(&mut self, ctx: &Context) -> R { - let (Some(Arg::Resource(biome)), from, to) = ( - ctx.get("biome").cloned(), - self.coords(ctx, "from"), - self.coords(ctx, "to"), - ) else { + let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0); }; - let (Some(from), Some(to)) = (from, to) else { - return Ok(0); - }; - let (src_pos, src_rot) = (self.source_position(), self.source_rotation()); - let (a, b) = (from.block(src_pos, src_rot), to.block(src_pos, src_rot)); + // BlockPosArgument.getLoadedBlockPos on both corners first. + let (a, b) = (self.block_pos_arg(ctx, "from")?, self.block_pos_arg(ctx, "to")?); // Quantize to biome cells (`QuartPos`), then work with the box. let q = |v: i32| (v >> 2) << 2; let lo = [ diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 1ec77dbf7..00b52a0b0 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -492,6 +492,27 @@ impl Game<'_> { Some(Arg::Int(c)) => *c, _ => 0, }; + // ParticleCommand.sendParticles: the viewers it reached, each within + // 32 blocks (512 with `force`) of the particle's block centre. + let viewers = if ctx.get("viewers").is_some() { + self.entities(ctx, "viewers", true)? + } else { + vec![Target::Player] + }; + let limit = if ctx.has("force") { 512.0 } else { 32.0 }; + let reached = viewers + .iter() + .filter(|&&t| { + self.target_position(t).is_some_and(|p| { + let c = p.map(|v| v.floor() + 0.5); + (c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2) + < limit * limit + }) + }) + .count() as i32; + if reached == 0 { + return Err(err("commands.particle.failed", &[])); + } // `ServerLevel.sendParticles`: no count means one particle with the delta as velocity. if count <= 0 { self.particles.create(&options, pos, delta); @@ -515,7 +536,7 @@ impl Game<'_> { "commands.particle.success", &[Text::literal(name.to_owned())], )); - Ok(count.max(1)) + Ok(reached) } // ---- /attribute --------------------------------------------------------------------- diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java index ba41c44ca..a22f72af4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java @@ -202,7 +202,7 @@ public final class VanillaCommandExecOracle { messages.clear(); // Answers computed off-thread (profile lookups) reach the // server's task queue before the next tick. - for (int wait = 0; wait < 100 && this.getPendingTasksCount() == 0 && op.has("record"); wait++) { + for (int wait = 0; wait < 2000 && this.getPendingTasksCount() == 0 && op.has("record"); wait++) { try { Thread.sleep(5); } catch (InterruptedException e) { throw new RuntimeException(e); } } for (int i = 0; i < n; i++) { diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 1342d21b4..66a303c6e 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -335,7 +335,7 @@ def execute(): cmd('/execute positioned 4 210 4 run setblock ~ ~ ~ minecraft:stone'), cmd('/execute positioned 4 210 4 if block ~ ~ ~ minecraft:stone'), cmd('/execute positioned as @s run tp @s ~ ~ ~'), - cmd('/execute align xyz run summon minecraft:armor_stand ~ ~-20 ~ {NoGravity:1b,Tags:["ex"]}'), + cmd('/execute align xyz run summon minecraft:armor_stand ~ ~-20 ~ {NoGravity:1b,Tags:["ex"],UUID:[I;1,2,3,4]}'), 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]'), @@ -499,6 +499,9 @@ def world_misc(): cmd('/forceload query'), cmd('/forceload add 0 0 1000 1000'), cmd('/particle minecraft:flame 4 210 4'), + cmd('/particle minecraft:flame 4 300 4'), + cmd('/particle minecraft:flame 4 300 4 0 0 0 0 1 force'), + cmd('/particle minecraft:flame 4 300 4 0 0 0 0 1 force @e[type=minecraft:pig]'), cmd('/particle minecraft:dust{color:[1.0,0.0,0.0],scale:1.0} 4 210 4 0 0 0 0 5 force @s'), cmd('/particle minecraft:block{block_state:"minecraft:stone"} 4 210 4 1 1 1 0.1 10 normal @a'), cmd('/playsound minecraft:block.note_block.harp master @s'), @@ -562,6 +565,8 @@ def world_misc(): cmd('/kill @e[type=minecraft:pig,tag=w]'), {'op': 'tick', 'n': 1}, cmd('/waypoint list'), + {'op': 'tick', 'n': 25}, + cmd('/waypoint list'), cmd('/attribute @s minecraft:waypoint_transmit_range base reset'), {'op': 'tick', 'n': 1}, cmd('/waypoint list'),