Add /data, /tag and NBT summoning
/data now supports get, merge, modify and remove on entities, block entities and command storage, with NBT paths (children, indices, [] and [{...}] matches, root matches), scaling for numeric reads, the append, prepend, insert, set and merge modifiers, and from, string and value sources. Command storage is saved per namespace in data/<namespace>/command_storage.dat. /tag adds, removes and lists entity tags, which selectors' tag=, nbt= and advancements= options now check. /summon accepts a full NBT compound (custom name, tags, health, NoAI, Invulnerable, item contents and so on), and armor stands, item frames, paintings, boats and minecarts can now be selected, teleported and killed like other entities.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,6 +35,8 @@ pub struct Registries {
|
||||
pub tracked: Vec<String>,
|
||||
/// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
|
||||
pub functions: Vec<String>,
|
||||
/// `/data ... storage` ids.
|
||||
pub storages: Vec<String>,
|
||||
pub function_tags: Vec<String>,
|
||||
/// The block the source is looking at (relevant coordinates).
|
||||
pub target_block: Option<[i32; 3]>,
|
||||
@@ -141,6 +143,10 @@ pub enum ArgType {
|
||||
TeamColor,
|
||||
/// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`).
|
||||
IntRange,
|
||||
/// NbtPathArgument (kept as text).
|
||||
NbtPath,
|
||||
/// NbtTagArgument: any SNBT value (kept as text).
|
||||
NbtTag,
|
||||
}
|
||||
pub fn integer(min: i32) -> ArgType {
|
||||
ArgType::Integer { min, max: i32::MAX }
|
||||
@@ -1551,7 +1557,11 @@ impl ArgType {
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(read_braced(reader, '{', '}')?)
|
||||
let text = read_braced(reader, '{', '}')?;
|
||||
if let Err(e) = horizon_world::nbt::parse_snbt(&text) {
|
||||
return Err(CommandError::at(crate::text::Text::literal(e), reader));
|
||||
}
|
||||
Arg::Str(text)
|
||||
}
|
||||
ArgType::Component => {
|
||||
let (value, used) =
|
||||
@@ -1662,6 +1672,24 @@ impl ArgType {
|
||||
Arg::Str(name.to_owned())
|
||||
}
|
||||
ArgType::IntRange => Arg::IntRange(range_int(reader)?),
|
||||
ArgType::NbtPath => {
|
||||
let (path, used) = crate::nbt_path::NbtPath::parse_prefix(reader.remaining())
|
||||
.map_err(|e| {
|
||||
reader.cursor += e.cursor.min(reader.remaining().len());
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
e.args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr_at(e.key, &args, reader)
|
||||
})?;
|
||||
reader.cursor += used;
|
||||
Arg::Str(path.as_str().to_owned())
|
||||
}
|
||||
ArgType::NbtTag => {
|
||||
let (_, used) = horizon_world::nbt::parse_snbt(reader.remaining())
|
||||
.map_err(|e| CommandError::at(crate::text::Text::literal(e), reader))?;
|
||||
let text = reader.remaining()[..used].to_owned();
|
||||
reader.cursor += used;
|
||||
Arg::Str(text)
|
||||
}
|
||||
ArgType::Anchor => {
|
||||
let name = reader.read_unquoted_string();
|
||||
match name {
|
||||
@@ -1718,6 +1746,7 @@ impl ArgType {
|
||||
}
|
||||
ArgType::Id(list) => {
|
||||
let values = match *list {
|
||||
"storages" => reg.storages.clone(),
|
||||
"time_markers" => reg.time_markers.clone(),
|
||||
"advancements" => reg.advancements.clone(),
|
||||
_ => Vec::new(),
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! usage text and the vanilla error messages. Argument types live in
|
||||
//! [`args`]; the vanilla command tree in [`vanilla`].
|
||||
pub mod args;
|
||||
pub mod tree_data;
|
||||
pub mod tree_scoreboard;
|
||||
pub mod vanilla;
|
||||
|
||||
|
||||
@@ -215,3 +215,43 @@ fn local_coordinates_follow_view() {
|
||||
]);
|
||||
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_and_tag_commands_parse() {
|
||||
let (id, args) = run("data get entity @s Pos 2.5").unwrap();
|
||||
assert_eq!(id, "data.get");
|
||||
assert_eq!(args, ["target", "path", "scale"]);
|
||||
assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get");
|
||||
assert_eq!(run("data get storage my:store").unwrap().0, "data.get");
|
||||
assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge");
|
||||
assert_eq!(
|
||||
run("data remove entity @s foo.bar[1]").unwrap().0,
|
||||
"data.remove"
|
||||
);
|
||||
let (id, args) = run("data modify storage a:b x.y insert 2 from entity @s Pos[0]").unwrap();
|
||||
assert_eq!(id, "data.modify");
|
||||
assert_eq!(
|
||||
args,
|
||||
["target", "targetPath", "index", "source", "sourcePath"]
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify block 1 2 3 Text1 set string storage a:b x 1 3")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert_eq!(
|
||||
run("data modify storage a:b l append value [1,2]")
|
||||
.unwrap()
|
||||
.0,
|
||||
"data.modify"
|
||||
);
|
||||
assert!(run("data modify storage a:b l explode value 1").is_err());
|
||||
assert!(run("data get storage a:b {broken").is_err());
|
||||
assert!(run("data merge storage a:b 5").is_err());
|
||||
assert_eq!(run("tag @e[tag=!x] add foo").unwrap().0, "tag.add");
|
||||
assert_eq!(run("tag @s list").unwrap().0, "tag.list");
|
||||
// Selector options added for scoreboards and NBT.
|
||||
assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok());
|
||||
assert!(run("kill @e[scores={a=1..]").is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The `/data` and `/tag` command trees (DataCommands, TagCommand).
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
|
||||
/// `ArgProvider.wrap` for each of entity, block and storage: calls `then`
|
||||
/// with the node holding the provider's argument.
|
||||
fn providers(
|
||||
d: &mut Dispatcher,
|
||||
parent: usize,
|
||||
role: &str,
|
||||
mut then: impl FnMut(&mut Dispatcher, usize),
|
||||
) {
|
||||
let e = d.literal(parent, "entity");
|
||||
let a = d.argument(e, role, ENTITY);
|
||||
then(d, a);
|
||||
let b = d.literal(parent, "block");
|
||||
let a = d.argument(b, &format!("{role}Pos"), ArgType::BlockPos);
|
||||
then(d, a);
|
||||
let s = d.literal(parent, "storage");
|
||||
let a = d.argument(s, role, ArgType::Id("storages"));
|
||||
then(d, a);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let data = d.literal(root, "data");
|
||||
d.requires(data, GAMEMASTERS);
|
||||
|
||||
let merge = d.literal(data, "merge");
|
||||
providers(d, merge, "target", |d, a| {
|
||||
let nbt = d.argument(a, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "data.merge");
|
||||
});
|
||||
let get = d.literal(data, "get");
|
||||
providers(d, get, "target", |d, a| {
|
||||
d.executes(a, "data.get");
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.get");
|
||||
let scale = d.argument(
|
||||
path,
|
||||
"scale",
|
||||
ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "data.get");
|
||||
});
|
||||
let remove = d.literal(data, "remove");
|
||||
providers(d, remove, "target", |d, a| {
|
||||
let path = d.argument(a, "path", ArgType::NbtPath);
|
||||
d.executes(path, "data.remove");
|
||||
});
|
||||
let modify = d.literal(data, "modify");
|
||||
providers(d, modify, "target", |d, a| {
|
||||
let target_path = d.argument(a, "targetPath", ArgType::NbtPath);
|
||||
// insert <index> | prepend | append | set | merge, then the source.
|
||||
let mut ops = Vec::new();
|
||||
let insert = d.literal(target_path, "insert");
|
||||
let index = d.argument(
|
||||
insert,
|
||||
"index",
|
||||
ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
);
|
||||
ops.push(index);
|
||||
for op in ["prepend", "append", "set", "merge"] {
|
||||
ops.push(d.literal(target_path, op));
|
||||
}
|
||||
for op in ops {
|
||||
let from = d.literal(op, "from");
|
||||
providers(d, from, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
});
|
||||
let string = d.literal(op, "string");
|
||||
providers(d, string, "source", |d, s| {
|
||||
d.executes(s, "data.modify");
|
||||
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
|
||||
d.executes(sp, "data.modify");
|
||||
let int = || ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
};
|
||||
let start = d.argument(sp, "start", int());
|
||||
d.executes(start, "data.modify");
|
||||
let end = d.argument(start, "end", int());
|
||||
d.executes(end, "data.modify");
|
||||
});
|
||||
let value = d.literal(op, "value");
|
||||
let v = d.argument(value, "value", ArgType::NbtTag);
|
||||
d.executes(v, "data.modify");
|
||||
}
|
||||
});
|
||||
|
||||
// tag <targets> add|remove <name> | list
|
||||
let tag = d.literal(root, "tag");
|
||||
d.requires(tag, GAMEMASTERS);
|
||||
let targets = d.argument(tag, "targets", ENTITIES);
|
||||
for word in ["add", "remove"] {
|
||||
let w = d.literal(targets, word);
|
||||
let name = d.argument(w, "name", ArgType::Word);
|
||||
d.executes(
|
||||
name,
|
||||
if word == "add" {
|
||||
"tag.add"
|
||||
} else {
|
||||
"tag.remove"
|
||||
},
|
||||
);
|
||||
}
|
||||
let list = d.literal(targets, "list");
|
||||
d.executes(list, "tag.list");
|
||||
}
|
||||
@@ -11,19 +11,19 @@ use crate::gamerules::{RULES, Value};
|
||||
pub const ALL: u8 = 0;
|
||||
pub const GAMEMASTERS: u8 = 2;
|
||||
|
||||
const PLAYERS: ArgType = ArgType::Entity {
|
||||
pub const PLAYERS: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: true,
|
||||
};
|
||||
const PLAYER: ArgType = ArgType::Entity {
|
||||
pub const PLAYER: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: true,
|
||||
};
|
||||
const ENTITIES: ArgType = ArgType::Entity {
|
||||
pub const ENTITIES: ArgType = ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
const ENTITY: ArgType = ArgType::Entity {
|
||||
pub const ENTITY: ArgType = ArgType::Entity {
|
||||
single: true,
|
||||
players: false,
|
||||
};
|
||||
@@ -343,6 +343,7 @@ pub fn build() -> Dispatcher {
|
||||
d.executes(fade_out, "title");
|
||||
|
||||
super::tree_scoreboard::register(&mut d, root);
|
||||
super::tree_data::register(&mut d, root);
|
||||
execute(&mut d, root);
|
||||
d
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `CommandStorage`: named compounds for `/data ... storage <id>`, kept per
|
||||
//! namespace in `data/<namespace>/command_storage.dat`.
|
||||
use crate::save;
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CommandStorage {
|
||||
/// namespace -> path -> contents.
|
||||
namespaces: BTreeMap<String, BTreeMap<String, Tag>>,
|
||||
dirty: bool,
|
||||
}
|
||||
fn split_id(id: &str) -> (&str, &str) {
|
||||
id.split_once(':').unwrap_or(("minecraft", id))
|
||||
}
|
||||
fn file(root: &Path, namespace: &str) -> PathBuf {
|
||||
root.join("data")
|
||||
.join(namespace)
|
||||
.join("command_storage.dat")
|
||||
}
|
||||
impl CommandStorage {
|
||||
/// Read every `data/<namespace>/command_storage.dat` under a world.
|
||||
pub fn load(root: &Path) -> Self {
|
||||
let mut s = Self::default();
|
||||
let Ok(dirs) = std::fs::read_dir(root.join("data")) else {
|
||||
return s;
|
||||
};
|
||||
for dir in dirs.flatten() {
|
||||
let namespace = dir.file_name().to_string_lossy().into_owned();
|
||||
let Some(data) =
|
||||
save::read_dat(&file(root, &namespace)).and_then(|t| t.get("data").cloned())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Tag::Compound(contents)) = data.get("contents") {
|
||||
let map = contents
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string_lossy(), v.clone()))
|
||||
.collect();
|
||||
s.namespaces.insert(namespace, map);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
pub fn save(&mut self, root: &Path) {
|
||||
if !self.dirty {
|
||||
return;
|
||||
}
|
||||
self.dirty = false;
|
||||
for (namespace, map) in &self.namespaces {
|
||||
let contents: Compound = map
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str().into(), v.clone()))
|
||||
.collect();
|
||||
let _ = save::write_dat(
|
||||
&file(root, namespace),
|
||||
Tag::compound([
|
||||
(
|
||||
"data",
|
||||
Tag::compound([("contents", Tag::Compound(contents))]),
|
||||
),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `get`: an empty compound when unset.
|
||||
pub fn get(&self, id: &str) -> Tag {
|
||||
let (ns, path) = split_id(id);
|
||||
self.namespaces
|
||||
.get(ns)
|
||||
.and_then(|m| m.get(path))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Tag::Compound(Compound::new()))
|
||||
}
|
||||
/// `set`: empty contents remove the entry.
|
||||
pub fn set(&mut self, id: &str, contents: Tag) {
|
||||
let (ns, path) = split_id(id);
|
||||
let empty = matches!(&contents, Tag::Compound(c) if c.is_empty());
|
||||
let map = self.namespaces.entry(ns.to_owned()).or_default();
|
||||
if empty {
|
||||
map.remove(path);
|
||||
} else {
|
||||
map.insert(path.to_owned(), contents);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
/// Every stored id (`keys`).
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
self.namespaces
|
||||
.iter()
|
||||
.flat_map(|(ns, m)| m.keys().map(move |k| format!("{ns}:{k}")))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
#[test]
|
||||
fn stores_per_namespace_and_persists() {
|
||||
let dir = std::env::temp_dir().join(format!("hz-storage-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = CommandStorage::default();
|
||||
assert_eq!(s.get("minecraft:x"), Tag::Compound(Compound::new()));
|
||||
s.set("minecraft:x", parse_snbt("{a:1}").unwrap().0);
|
||||
s.set("my:pack/y", parse_snbt("{b:[1,2]}").unwrap().0);
|
||||
s.save(&dir);
|
||||
let back = CommandStorage::load(&dir);
|
||||
assert_eq!(back.get("x"), parse_snbt("{a:1}").unwrap().0);
|
||||
assert_eq!(back.get("my:pack/y"), parse_snbt("{b:[1,2]}").unwrap().0);
|
||||
assert_eq!(back.keys(), vec!["minecraft:x", "my:pack/y"]);
|
||||
// Empty contents delete.
|
||||
let mut s = back;
|
||||
s.set("x", Tag::Compound(Compound::new()));
|
||||
assert_eq!(s.keys(), vec!["my:pack/y"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! The pure parts of `/data` (DataCommands): merging compounds, the
|
||||
//! `modify` operations over an NBT path, string sources and the numeric
|
||||
//! result of `get`.
|
||||
use crate::{
|
||||
command::CommandError,
|
||||
nbt_path::{CollectionError, NbtPath, PathError, too_deep},
|
||||
snbt::to_snbt,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
/// `CompoundTag.merge`: compounds merge recursively, anything else replaces.
|
||||
pub fn merge_compound(target: &mut Compound, source: &Compound) {
|
||||
for (k, v) in source {
|
||||
match (target.get_mut(k), v) {
|
||||
(Some(Tag::Compound(t)), Tag::Compound(s)) => merge_compound(t, s),
|
||||
_ => {
|
||||
target.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `old.copy().merge(nbt)`.
|
||||
pub fn merged(old: &Tag, nbt: &Tag) -> Tag {
|
||||
let mut result = old.clone();
|
||||
if let (Tag::Compound(t), Tag::Compound(s)) = (&mut result, nbt) {
|
||||
merge_compound(t, s);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn path_error(e: PathError) -> CommandError {
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
e.args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr(e.key, &args)
|
||||
}
|
||||
pub fn collection_error(e: CollectionError) -> CommandError {
|
||||
match e {
|
||||
CollectionError::Path(p) => path_error(p),
|
||||
CollectionError::ExpectedList(t) => {
|
||||
CommandError::tr("commands.data.modify.expected_list", &[&t])
|
||||
}
|
||||
CollectionError::InvalidIndex(i) => {
|
||||
CommandError::tr("commands.data.modify.invalid_index", &[&i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `modify` operation words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Op {
|
||||
Insert(i32),
|
||||
Prepend,
|
||||
Append,
|
||||
Set,
|
||||
Merge,
|
||||
}
|
||||
/// Run a `modify` operation; the count is how many tags changed (0 = fail).
|
||||
pub fn modify(
|
||||
op: Op,
|
||||
target: &mut Tag,
|
||||
path: &NbtPath,
|
||||
sources: &[Tag],
|
||||
) -> Result<usize, CommandError> {
|
||||
match op {
|
||||
Op::Insert(i) => path.insert(i, target, sources).map_err(collection_error),
|
||||
Op::Prepend => path.insert(0, target, sources).map_err(collection_error),
|
||||
Op::Append => path.insert(-1, target, sources).map_err(collection_error),
|
||||
Op::Set => {
|
||||
let Some(last) = sources.last() else {
|
||||
return Ok(0);
|
||||
};
|
||||
path.set(target, last).map_err(path_error)
|
||||
}
|
||||
Op::Merge => {
|
||||
let mut combined = Compound::new();
|
||||
for s in sources {
|
||||
if too_deep(s, 0) {
|
||||
return Err(CommandError::tr("arguments.nbtpath.too_deep", &[]));
|
||||
}
|
||||
let Tag::Compound(c) = s else {
|
||||
return Err(CommandError::tr(
|
||||
"commands.data.modify.expected_object",
|
||||
&[&to_snbt(s)],
|
||||
));
|
||||
};
|
||||
merge_compound(&mut combined, c);
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut error = None;
|
||||
path.get_or_create(target, &|| Tag::Compound(Compound::new()), &mut |t| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
match t {
|
||||
Tag::Compound(c) => {
|
||||
let before = c.clone();
|
||||
merge_compound(c, &combined);
|
||||
changed += usize::from(before != *c);
|
||||
}
|
||||
other => {
|
||||
error = Some(CommandError::tr(
|
||||
"commands.data.modify.expected_object",
|
||||
&[&to_snbt(other)],
|
||||
));
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(path_error)?;
|
||||
match error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(changed),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `getAsText`: strings and numbers as text, anything else is an error.
|
||||
pub fn as_text(tag: &Tag) -> Result<String, CommandError> {
|
||||
match tag {
|
||||
Tag::String(s) => Ok(s.to_string_lossy()),
|
||||
Tag::Byte(_)
|
||||
| Tag::Short(_)
|
||||
| Tag::Int(_)
|
||||
| Tag::Long(_)
|
||||
| Tag::Float(_)
|
||||
| Tag::Double(_) => {
|
||||
// PrimitiveTag.toString: the SNBT form (with its suffix).
|
||||
Ok(to_snbt(tag))
|
||||
}
|
||||
other => Err(CommandError::tr(
|
||||
"commands.data.modify.expected_value",
|
||||
&[&to_snbt(other)],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// `substring(input, start[, end])` with negative offsets from the end.
|
||||
pub fn substring(input: &str, start: i32, end: Option<i32>) -> Result<String, CommandError> {
|
||||
let chars: Vec<u16> = input.encode_utf16().collect();
|
||||
let len = chars.len() as i32;
|
||||
let offset = |i: i32| if i >= 0 { i } else { len + i };
|
||||
let (s, e) = (offset(start), end.map_or(len, offset));
|
||||
if s >= 0 && e <= len && s <= e {
|
||||
Ok(String::from_utf16_lossy(&chars[s as usize..e as usize]))
|
||||
} else {
|
||||
Err(CommandError::tr(
|
||||
"commands.data.modify.invalid_substring",
|
||||
&[&s, &e],
|
||||
))
|
||||
}
|
||||
}
|
||||
/// `getSingleTag`: exactly one tag at the path.
|
||||
pub fn single_tag(path: &NbtPath, data: &Tag) -> Result<Tag, CommandError> {
|
||||
let mut tags = path.get(data).map_err(path_error)?;
|
||||
if tags.len() > 1 {
|
||||
return Err(CommandError::tr("commands.data.get.multiple", &[]));
|
||||
}
|
||||
Ok(tags.remove(0))
|
||||
}
|
||||
/// The value of a tag as a double (NumericTag.doubleValue).
|
||||
pub fn numeric(tag: &Tag) -> Option<f64> {
|
||||
Some(match tag {
|
||||
Tag::Byte(v) => f64::from(*v),
|
||||
Tag::Short(v) => f64::from(*v),
|
||||
Tag::Int(v) => f64::from(*v),
|
||||
Tag::Long(v) => *v as f64,
|
||||
Tag::Float(v) => f64::from(f32::from_bits(*v)),
|
||||
Tag::Double(v) => f64::from_bits(*v),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `data get <path>`'s return value: the number's floor, or a size.
|
||||
pub fn get_value(tag: &Tag, path: &NbtPath) -> Result<i32, CommandError> {
|
||||
Ok(match tag {
|
||||
Tag::List(l) => l.len() as i32,
|
||||
Tag::ByteArray(a) => a.len() as i32,
|
||||
Tag::IntArray(a) => a.len() as i32,
|
||||
Tag::LongArray(a) => a.len() as i32,
|
||||
Tag::Compound(c) => c.len() as i32,
|
||||
Tag::String(s) => s.0.len() as i32,
|
||||
Tag::End => {
|
||||
return Err(CommandError::tr(
|
||||
"commands.data.get.unknown",
|
||||
&[&path.as_str()],
|
||||
));
|
||||
}
|
||||
other => numeric(other).map_or(0, |v| v.floor() as i32),
|
||||
})
|
||||
}
|
||||
/// `Mth.floor(value * scale)` for `data get <path> <scale>`.
|
||||
pub fn scaled_value(tag: &Tag, path: &NbtPath, scale: f64) -> Result<i32, CommandError> {
|
||||
match numeric(tag) {
|
||||
Some(v) => Ok((v * scale).floor() as i32),
|
||||
None => Err(CommandError::tr(
|
||||
"commands.data.get.invalid",
|
||||
&[&path.as_str()],
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// The text `data get ... <scale>` prints for the scale (`%.2f`).
|
||||
pub fn scale_text(scale: f64) -> Text {
|
||||
Text::literal(format!("{scale:.2}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn tag(s: &str) -> Tag {
|
||||
parse_snbt(s).unwrap().0
|
||||
}
|
||||
fn path(s: &str) -> NbtPath {
|
||||
NbtPath::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_is_recursive() {
|
||||
let old = tag("{a:{b:1,c:2},d:[1]}");
|
||||
assert_eq!(
|
||||
to_snbt(&merged(&old, &tag("{a:{b:9},e:1}"))),
|
||||
"{a:{b:9,c:2},d:[1],e:1}"
|
||||
);
|
||||
assert_eq!(merged(&old, &tag("{}")), old);
|
||||
// Lists and scalars are replaced, not merged.
|
||||
assert_eq!(
|
||||
to_snbt(&merged(&old, &tag("{d:[2]}"))),
|
||||
"{a:{b:1,c:2},d:[2]}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_operations() {
|
||||
let mut t = tag("{l:[1,2],o:{a:1}}");
|
||||
assert_eq!(
|
||||
modify(Op::Append, &mut t, &path("l"), &[tag("3")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Prepend, &mut t, &path("l"), &[tag("0")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Insert(2), &mut t, &path("l"), &[tag("9")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(to_snbt(&t), "{l:[0,1,9,2,3],o:{a:1}}");
|
||||
assert_eq!(
|
||||
modify(Op::Set, &mut t, &path("o.a"), &[tag("1"), tag("2")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Set, &mut t, &path("o.a"), &[tag("2")]).unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("o"), &[tag("{b:1}")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("o"), &[tag("{b:1}")]).unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(to_snbt(&t), "{l:[0,1,9,2,3],o:{a:2,b:1}}");
|
||||
let e = modify(Op::Merge, &mut t, &path("o"), &[tag("3")]).unwrap_err();
|
||||
assert_eq!(e.message.plain(), "commands.data.modify.expected_object");
|
||||
let e = modify(Op::Append, &mut t, &path("o"), &[tag("3")]).unwrap_err();
|
||||
assert_eq!(e.message.plain(), "commands.data.modify.expected_list");
|
||||
// Merge creates the target compound when missing.
|
||||
assert_eq!(
|
||||
modify(Op::Merge, &mut t, &path("new.deep"), &[tag("{x:1}")]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(single_tag(&path("new.deep.x"), &t).unwrap(), Tag::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_values() {
|
||||
assert_eq!(substring("abcdef", 1, Some(3)).unwrap(), "bc");
|
||||
assert_eq!(substring("abcdef", -2, None).unwrap(), "ef");
|
||||
assert_eq!(substring("abcdef", 0, Some(-1)).unwrap(), "abcde");
|
||||
assert!(substring("abc", 2, Some(1)).is_err());
|
||||
assert!(substring("abc", 0, Some(9)).is_err());
|
||||
assert_eq!(as_text(&tag("\"x\"")).unwrap(), "x");
|
||||
assert_eq!(as_text(&tag("5b")).unwrap(), "5b");
|
||||
assert!(as_text(&tag("[1]")).is_err());
|
||||
let data = tag("{n:2.7d,s:\"abcd\",l:[1,2,3],c:{a:1,b:2},m:[1,2]}");
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("n"), &data).unwrap(), &path("n")).unwrap(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("s"), &data).unwrap(), &path("s")).unwrap(),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("l"), &data).unwrap(), &path("l")).unwrap(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
get_value(&single_tag(&path("c"), &data).unwrap(), &path("c")).unwrap(),
|
||||
2
|
||||
);
|
||||
assert_eq!(scaled_value(&Tag::Int(7), &path("n"), 0.5).unwrap(), 3);
|
||||
assert_eq!(
|
||||
scaled_value(&Tag::Double((-0.5f64).to_bits()), &path("n"), 1.0).unwrap(),
|
||||
-1
|
||||
);
|
||||
assert!(scaled_value(&tag("\"x\""), &path("s"), 1.0).is_err());
|
||||
assert_eq!(
|
||||
single_tag(&path("m[]"), &data).unwrap_err().message.plain(),
|
||||
"commands.data.get.multiple"
|
||||
);
|
||||
assert_eq!(scale_text(1.0).plain(), "1.00");
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,17 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let Tag::Compound(map) = &mut tag else {
|
||||
return tag;
|
||||
};
|
||||
for (key, on) in [
|
||||
("NoAI", m.no_ai),
|
||||
("Silent", m.silent),
|
||||
("Invulnerable", m.invulnerable_flag),
|
||||
] {
|
||||
if on {
|
||||
map.insert(key.into(), Tag::Byte(1));
|
||||
} else {
|
||||
map.remove(&horizon_world::nbt::JavaString::from(key));
|
||||
}
|
||||
}
|
||||
for (key, value) in [
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
@@ -452,6 +463,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.age_locked = flag(tag, "AgeLocked");
|
||||
}
|
||||
m.name_visible = flag(tag, "CustomNameVisible");
|
||||
m.no_ai = flag(tag, "NoAI");
|
||||
m.silent = flag(tag, "Silent");
|
||||
m.invulnerable_flag = flag(tag, "Invulnerable");
|
||||
m.no_gravity = m.no_gravity || flag(tag, "NoGravity");
|
||||
if m.species() == crate::mobs::Species::Creeper {
|
||||
m.extra.charged = flag(tag, "powered");
|
||||
}
|
||||
|
||||
@@ -6493,24 +6493,8 @@ impl Game<'_> {
|
||||
self.carried = None;
|
||||
}
|
||||
}
|
||||
fn save_game(&mut self) -> Result<()> {
|
||||
if self.remote.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks: Vec<_> = keys
|
||||
.iter()
|
||||
.filter_map(|k| self.world.chunks.get(k))
|
||||
.map(|c| self.with_entities(c))
|
||||
.collect();
|
||||
self.save
|
||||
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_entities()?;
|
||||
self.save_maps();
|
||||
self.save_fight();
|
||||
self.save_stats();
|
||||
self.save_advancements();
|
||||
self.save_scoreboard();
|
||||
/// Copy the live player and world state into the `Level` that gets saved.
|
||||
pub(super) fn sync_level(&mut self) {
|
||||
self.level.selected_slot = self.selected as i32;
|
||||
let mode = self.mode_id();
|
||||
let level = &mut self.level;
|
||||
@@ -6587,7 +6571,27 @@ impl Game<'_> {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
level.write(&self.world_root)?;
|
||||
}
|
||||
fn save_game(&mut self) -> Result<()> {
|
||||
if self.remote.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks: Vec<_> = keys
|
||||
.iter()
|
||||
.filter_map(|k| self.world.chunks.get(k))
|
||||
.map(|c| self.with_entities(c))
|
||||
.collect();
|
||||
self.save
|
||||
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_entities()?;
|
||||
self.save_maps();
|
||||
self.save_fight();
|
||||
self.save_stats();
|
||||
self.save_advancements();
|
||||
self.save_scoreboard();
|
||||
self.sync_level();
|
||||
self.level.write(&self.world_root)?;
|
||||
self.save_world_state();
|
||||
self.message = Some(("Saved the game".into(), Instant::now()));
|
||||
Ok(())
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Command execution (the `execute` side of each vanilla command class):
|
||||
//! entity selectors resolved against the game, vanilla feedback and errors.
|
||||
mod data;
|
||||
mod effects;
|
||||
pub(super) mod execute;
|
||||
mod text_commands;
|
||||
@@ -28,6 +29,11 @@ pub(super) enum Target {
|
||||
Item(u32),
|
||||
Orb(usize),
|
||||
Arrow(usize),
|
||||
Stand(u32),
|
||||
Frame(u32),
|
||||
Painting(u32),
|
||||
Boat(u32),
|
||||
Cart(u32),
|
||||
}
|
||||
fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError {
|
||||
CommandError::tr(key, args)
|
||||
@@ -153,7 +159,7 @@ impl Game<'_> {
|
||||
self.coords(ctx, name).map(|c| self.resolve_coords(&c))
|
||||
}
|
||||
/// BlockPosArgument.getLoadedBlockPos.
|
||||
fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> {
|
||||
pub(super) fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> {
|
||||
let c = self
|
||||
.coords(ctx, name)
|
||||
.ok_or_else(|| err("argument.pos.missing.int", &[]))?;
|
||||
@@ -201,6 +207,37 @@ impl Game<'_> {
|
||||
.arrows
|
||||
.get(i)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Stand(id) => self
|
||||
.armor_stands
|
||||
.iter()
|
||||
.find(|a| a.id == id)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Frame(id) => self.item_frames.iter().find(|f| f.id == id).map(|f| {
|
||||
let (lo, hi) = f.bounds();
|
||||
[
|
||||
(lo[0] + hi[0]) / 2.0,
|
||||
(lo[1] + hi[1]) / 2.0,
|
||||
(lo[2] + hi[2]) / 2.0,
|
||||
]
|
||||
}),
|
||||
Target::Painting(id) => self.paintings.iter().find(|p| p.id == id).map(|p| {
|
||||
let (lo, hi) = p.bounds();
|
||||
[
|
||||
(lo[0] + hi[0]) / 2.0,
|
||||
(lo[1] + hi[1]) / 2.0,
|
||||
(lo[2] + hi[2]) / 2.0,
|
||||
]
|
||||
}),
|
||||
Target::Boat(id) => self
|
||||
.boats
|
||||
.iter()
|
||||
.find(|b| b.id == id)
|
||||
.map(|b| [b.position.x, b.position.y, b.position.z]),
|
||||
Target::Cart(id) => self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map(|c| [c.position.x, c.position.y, c.position.z]),
|
||||
}
|
||||
}
|
||||
fn target_type(&self, t: Target) -> String {
|
||||
@@ -216,6 +253,27 @@ impl Game<'_> {
|
||||
Target::Item(_) => "minecraft:item".into(),
|
||||
Target::Orb(_) => "minecraft:experience_orb".into(),
|
||||
Target::Arrow(_) => "minecraft:arrow".into(),
|
||||
Target::Stand(_) => "minecraft:armor_stand".into(),
|
||||
Target::Frame(id) => {
|
||||
if self.item_frames.iter().any(|f| f.id == id && f.glow) {
|
||||
"minecraft:glow_item_frame".into()
|
||||
} else {
|
||||
"minecraft:item_frame".into()
|
||||
}
|
||||
}
|
||||
Target::Painting(_) => "minecraft:painting".into(),
|
||||
Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else(
|
||||
|| "minecraft:oak_boat".into(),
|
||||
|b| {
|
||||
let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" };
|
||||
format!("minecraft:{}_{kind}", b.wood)
|
||||
},
|
||||
),
|
||||
Target::Cart(id) => self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map_or_else(|| "minecraft:minecart".into(), |c| c.kind.id().into()),
|
||||
}
|
||||
}
|
||||
/// Entity.getDisplayName.
|
||||
@@ -231,6 +289,19 @@ impl Game<'_> {
|
||||
.unwrap_or_default();
|
||||
Text::literal(self.res.names.item(&item))
|
||||
}
|
||||
Target::Mob(id)
|
||||
if self
|
||||
.mobs
|
||||
.iter()
|
||||
.any(|m| m.id == id && m.custom_name.is_some()) =>
|
||||
{
|
||||
let name = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.and_then(|m| m.custom_name.clone());
|
||||
Text::literal(name.unwrap_or_default())
|
||||
}
|
||||
other => {
|
||||
let ty = self.target_type(other);
|
||||
Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[])
|
||||
@@ -271,6 +342,11 @@ impl Game<'_> {
|
||||
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
|
||||
candidates.extend((0..self.orbs.len()).map(Target::Orb));
|
||||
candidates.extend((0..self.arrows.len()).map(Target::Arrow));
|
||||
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
|
||||
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
|
||||
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)));
|
||||
}
|
||||
let level = self.experience.level;
|
||||
let creative = self.creative;
|
||||
@@ -374,7 +450,7 @@ impl Game<'_> {
|
||||
})
|
||||
}
|
||||
/// EntityArgument.getEntities / getPlayers / getEntity / getPlayer.
|
||||
fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
|
||||
pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
|
||||
let Some(Arg::Entity(s)) = ctx.get(name).cloned() else {
|
||||
return Ok(vec![Target::Player]);
|
||||
};
|
||||
@@ -448,6 +524,8 @@ impl Game<'_> {
|
||||
"spawnpoint" => self.cmd_spawnpoint(ctx),
|
||||
"setworldspawn" => self.cmd_setworldspawn(ctx),
|
||||
"clear" => self.cmd_clear(ctx),
|
||||
id if id.starts_with("data.") => self.cmd_data(id, ctx),
|
||||
id if id.starts_with("tag.") => self.cmd_tag(id, ctx),
|
||||
id if id.starts_with("scoreboard.")
|
||||
|| id.starts_with("team.")
|
||||
|| id.starts_with("trigger") =>
|
||||
@@ -703,6 +781,34 @@ impl Game<'_> {
|
||||
a.previous = v;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) {
|
||||
a.position = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
a.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Boat(id) => {
|
||||
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
|
||||
b.position = v;
|
||||
b.previous = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
b.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Cart(id) => {
|
||||
if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
|
||||
c.position = v;
|
||||
c.previous = v;
|
||||
if let Some([yaw, _]) = rotation {
|
||||
c.yaw = yaw;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wall-mounted entities do not move.
|
||||
Target::Frame(_) | Target::Painting(_) => {}
|
||||
}
|
||||
}
|
||||
fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
@@ -999,6 +1105,11 @@ impl Game<'_> {
|
||||
self.arrows[i].age = u32::MAX / 2;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
|
||||
Target::Frame(id) => self.item_frames.retain(|f| f.id != id),
|
||||
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),
|
||||
}
|
||||
}
|
||||
fn cmd_kill(&mut self, ctx: &Context) -> R<i32> {
|
||||
@@ -1044,6 +1155,25 @@ impl Game<'_> {
|
||||
return Err(err("commands.summon.invalidPosition", &[]));
|
||||
}
|
||||
let short = kind.trim_start_matches("minecraft:").to_owned();
|
||||
if let Some(Arg::Str(nbt)) = ctx.get("nbt").cloned() {
|
||||
// With an NBT argument the entity is built from it, unfinalized.
|
||||
if self.ui.difficulty == 0
|
||||
&& self
|
||||
.res
|
||||
.mob_types
|
||||
.get(&format!("minecraft:{short}"))
|
||||
.is_some_and(|t| t.category == "monster")
|
||||
{
|
||||
return Err(err("commands.summon.failed.peaceful", &[]));
|
||||
}
|
||||
let Some(target) = self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)?
|
||||
else {
|
||||
return Err(err("commands.summon.failed", &[]));
|
||||
};
|
||||
let name = self.target_name(target);
|
||||
self.feedback(Text::translate("commands.summon.success", &[name]));
|
||||
return Ok(1);
|
||||
}
|
||||
let name;
|
||||
if let Some(t) = self
|
||||
.res
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
//! `/data` (DataCommands), `/tag` (TagCommand) and `/summon` with NBT: entity,
|
||||
//! block entity and storage data accessors over the game state.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use horizon_client::{
|
||||
data_cmd::{self, Op, path_error},
|
||||
entity_nbt,
|
||||
nbt_path::NbtPath,
|
||||
save::{self, random_uuid},
|
||||
scoreboard_cmd::{Holder, Tracker, format_list},
|
||||
snbt,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
|
||||
|
||||
/// A `DataAccessor`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(in crate::game) enum DataRef {
|
||||
Entity(Target),
|
||||
Block([i32; 3]),
|
||||
Storage(String),
|
||||
}
|
||||
|
||||
fn empty() -> Tag {
|
||||
Tag::Compound(Compound::new())
|
||||
}
|
||||
fn set_key(tag: &mut Tag, key: &str, value: Tag) {
|
||||
if let Tag::Compound(c) = tag {
|
||||
c.insert(JavaString::from(key), value);
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
// ---- entity data ---------------------------------------------------
|
||||
|
||||
/// `NbtPredicate.getEntityTagToCompare`: the entity as saved.
|
||||
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option<Tag> {
|
||||
let player_uuid = self.level.player_uuid;
|
||||
Some(match t {
|
||||
Target::Player => {
|
||||
self.player.as_ref()?;
|
||||
self.sync_level();
|
||||
let mut tag = self.level.player_tag();
|
||||
if let Some(u) = player_uuid {
|
||||
set_key(&mut tag, "UUID", Tag::IntArray(u.to_vec()));
|
||||
}
|
||||
tag
|
||||
}
|
||||
Target::Mob(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let m = self.mobs.iter().find(|m| m.id == id)?;
|
||||
entity_nbt::mob_to_nbt(m, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Item(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let e = self.dropped.iter().find(|e| e.id == id)?;
|
||||
entity_nbt::item_entity_to_nbt(e, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let a = self.armor_stands.iter().find(|a| a.id == id)?;
|
||||
entity_nbt::armor_stand_to_nbt(a, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Frame(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let f = self.item_frames.iter().find(|f| f.id == id)?;
|
||||
entity_nbt::item_frame_to_nbt(f, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Painting(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let p = self.paintings.iter().find(|p| p.id == id)?;
|
||||
entity_nbt::painting_to_nbt(p, uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Boat(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let b = self.boats.iter().find(|b| b.id == id)?;
|
||||
entity_nbt::boat_to_nbt(
|
||||
&b.wood,
|
||||
b.position,
|
||||
b.velocity,
|
||||
b.yaw,
|
||||
uuid,
|
||||
self.persist.raw.get(&id),
|
||||
)
|
||||
}
|
||||
Target::Cart(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let c = self.carts.iter().find(|c| c.id == id)?;
|
||||
c.to_nbt(uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
|
||||
Target::Arrow(i) => {
|
||||
let a = self.arrows.get(i)?;
|
||||
let owner = if a.from_player { player_uuid } else { None };
|
||||
entity_nbt::arrow_to_nbt(a, random_uuid(), owner)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is
|
||||
/// rebuilt from its compound, keeping its id and UUID.
|
||||
fn apply_entity_nbt(&mut self, t: Target, mut tag: Tag) -> R<()> {
|
||||
let stale = || err("commands.data.merge.failed", &[]);
|
||||
match t {
|
||||
Target::Player => return Err(err("commands.data.entity.invalid", &[])),
|
||||
Target::Mob(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let kind = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id)
|
||||
.map(|m| m.kind.id.clone());
|
||||
set_key(&mut tag, "UUID", Tag::IntArray(uuid.to_vec()));
|
||||
if let Some(k) = kind {
|
||||
set_key(&mut tag, "id", Tag::String(k.as_str().into()));
|
||||
}
|
||||
let new =
|
||||
entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
// Runtime-only state (AI, animation) carries over.
|
||||
let old = std::mem::replace(slot, new);
|
||||
slot.ai = old.ai;
|
||||
slot.age = old.age;
|
||||
slot.previous = slot.position;
|
||||
}
|
||||
}
|
||||
Target::Item(id) => {
|
||||
let new = entity_nbt::item_entity_from_nbt(&tag, id, 0.0).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.dropped.iter_mut().find(|e| e.id == id) {
|
||||
let bob = slot.bob_offset;
|
||||
*slot = new;
|
||||
slot.bob_offset = bob;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => {
|
||||
let new = entity_nbt::armor_stand_from_nbt(&tag, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.armor_stands.iter_mut().find(|a| a.id == id) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
Target::Frame(id) => {
|
||||
let new = entity_nbt::item_frame_from_nbt(&tag, id).ok_or_else(stale)?;
|
||||
if let Some(slot) = self.item_frames.iter_mut().find(|f| f.id == id) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
_ => return Err(stale()),
|
||||
}
|
||||
if let Target::Mob(id) | Target::Item(id) | Target::Stand(id) | Target::Frame(id) = t {
|
||||
self.persist.raw.insert(id, tag);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn data_block_name(&self, p: [i32; 3]) -> String {
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
self.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.map_or_else(|| "minecraft:air".into(), |s| s.name.to_string())
|
||||
}
|
||||
fn raw_mut(&mut self, t: Target) -> Option<&mut Tag> {
|
||||
match t {
|
||||
Target::Player => Some(self.level.player_extra.get_or_insert_with(empty)),
|
||||
Target::Mob(id)
|
||||
| Target::Item(id)
|
||||
| Target::Stand(id)
|
||||
| Target::Frame(id)
|
||||
| Target::Painting(id)
|
||||
| Target::Boat(id)
|
||||
| Target::Cart(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn set_entity_tags(&mut self, t: Target, tags: &[String]) {
|
||||
if let Some(raw) = self.raw_mut(t) {
|
||||
let list = tags
|
||||
.iter()
|
||||
.map(|s| Tag::String(s.as_str().into()))
|
||||
.collect();
|
||||
set_key(raw, "Tags", Tag::List(list));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- accessors -----------------------------------------------------
|
||||
|
||||
/// The `role`th provider of the command (`entity`, `block` or `storage`).
|
||||
fn data_ref(&mut self, ctx: &Context, role: usize) -> R<DataRef> {
|
||||
let kind = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.filter(|l| matches!(l.as_str(), "entity" | "block" | "storage"))
|
||||
.nth(role)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let prefix = if role == 0 { "target" } else { "source" };
|
||||
match kind.as_str() {
|
||||
"entity" => {
|
||||
let Some(Arg::Entity(sel)) = ctx.get(prefix).cloned() else {
|
||||
return Err(err("argument.entity.notfound.entity", &[]));
|
||||
};
|
||||
let found = self.select(&sel);
|
||||
found
|
||||
.first()
|
||||
.map(|t| DataRef::Entity(*t))
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[]))
|
||||
}
|
||||
"block" => {
|
||||
let p = self.block_pos_arg(ctx, &format!("{prefix}Pos"))?;
|
||||
if !self.world.block_entities.contains_key(&(p[0], p[1], p[2])) {
|
||||
return Err(err("commands.data.block.invalid", &[]));
|
||||
}
|
||||
Ok(DataRef::Block(p))
|
||||
}
|
||||
_ => match ctx.get(prefix) {
|
||||
Some(Arg::Resource(id)) => Ok(DataRef::Storage(id.clone())),
|
||||
_ => Err(err("command.failed", &[])),
|
||||
},
|
||||
}
|
||||
}
|
||||
fn data_of(&mut self, r: &DataRef) -> R<Tag> {
|
||||
match r {
|
||||
DataRef::Entity(t) => self
|
||||
.entity_nbt(*t)
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[])),
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
let name = self.data_block_name(*p);
|
||||
let e = self
|
||||
.world
|
||||
.block_entities
|
||||
.get(&key)
|
||||
.ok_or_else(|| err("commands.data.block.invalid", &[]))?;
|
||||
Ok(save::encode_block_entity(key, e, &name))
|
||||
}
|
||||
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
|
||||
}
|
||||
}
|
||||
fn set_data_of(&mut self, r: &DataRef, tag: Tag) -> R<()> {
|
||||
match r {
|
||||
DataRef::Entity(t) => self.apply_entity_nbt(*t, tag),
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
if let Some((_, new)) = save::decode_block_entity(&tag) {
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
// Redraw what shows the block entity (signs, banners).
|
||||
let _ = self.world.set(p[0], p[1], p[2], state);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
DataRef::Storage(id) => {
|
||||
self.score.storage.set(id, tag);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
fn data_name(&self, r: &DataRef) -> Text {
|
||||
match r {
|
||||
DataRef::Entity(t) => self.target_name(*t),
|
||||
DataRef::Block(p) => Text::literal(format!("{}, {}, {}", p[0], p[1], p[2])),
|
||||
DataRef::Storage(id) => Text::literal(id.clone()),
|
||||
}
|
||||
}
|
||||
fn modified_text(&self, r: &DataRef) -> Text {
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.modified", &[self.data_name(r)])
|
||||
}
|
||||
DataRef::Block(p) => Text::translate(
|
||||
"commands.data.block.modified",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal(p[1].to_string()),
|
||||
Text::literal(p[2].to_string()),
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.modified",
|
||||
&[Text::literal(id.clone())],
|
||||
),
|
||||
}
|
||||
}
|
||||
fn query_text(&self, r: &DataRef, data: &Tag) -> Text {
|
||||
let pretty = snbt::pretty(data);
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.query", &[self.data_name(r), pretty])
|
||||
}
|
||||
DataRef::Block(p) => Text::translate(
|
||||
"commands.data.block.query",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal(p[1].to_string()),
|
||||
Text::literal(p[2].to_string()),
|
||||
pretty,
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.query",
|
||||
&[Text::literal(id.clone()), pretty],
|
||||
),
|
||||
}
|
||||
}
|
||||
fn get_text(&self, r: &DataRef, path: &NbtPath, scale: f64, value: i32) -> Text {
|
||||
let p = Text::literal(path.as_str());
|
||||
let (s, v) = (
|
||||
data_cmd::scale_text(scale),
|
||||
Text::literal(value.to_string()),
|
||||
);
|
||||
match r {
|
||||
DataRef::Entity(_) => {
|
||||
Text::translate("commands.data.entity.get", &[p, self.data_name(r), s, v])
|
||||
}
|
||||
DataRef::Block(b) => Text::translate(
|
||||
"commands.data.block.get",
|
||||
&[
|
||||
p,
|
||||
Text::literal(b[0].to_string()),
|
||||
Text::literal(b[1].to_string()),
|
||||
Text::literal(b[2].to_string()),
|
||||
s,
|
||||
v,
|
||||
],
|
||||
),
|
||||
DataRef::Storage(id) => Text::translate(
|
||||
"commands.data.storage.get",
|
||||
&[p, Text::literal(id.clone()), s, v],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /data -----------------------------------------------------------
|
||||
|
||||
fn path_arg(&self, ctx: &Context, name: &str) -> R<NbtPath> {
|
||||
let Some(Arg::Str(text)) = ctx.get(name) else {
|
||||
return Err(err("command.failed", &[]));
|
||||
};
|
||||
NbtPath::parse(text).map_err(path_error)
|
||||
}
|
||||
pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let target = self.data_ref(ctx, 0)?;
|
||||
match id {
|
||||
"data.merge" => {
|
||||
let Some(Arg::Str(nbt)) = ctx.get("nbt") else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (nbt, _) = parse_snbt(nbt).map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
let old = self.data_of(&target)?;
|
||||
if horizon_client::nbt_path::too_deep(&nbt, 0) {
|
||||
return Err(err("arguments.nbtpath.too_deep", &[]));
|
||||
}
|
||||
let result = data_cmd::merged(&old, &nbt);
|
||||
if old == result {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, result)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(1)
|
||||
}
|
||||
"data.get" => {
|
||||
let data = self.data_of(&target)?;
|
||||
if ctx.get("path").is_none() {
|
||||
let message = self.query_text(&target, &data);
|
||||
self.system_feedback(message);
|
||||
return Ok(1);
|
||||
}
|
||||
let path = self.path_arg(ctx, "path")?;
|
||||
let tag = data_cmd::single_tag(&path, &data)?;
|
||||
if let Some(Arg::Double(scale)) = ctx.get("scale") {
|
||||
let value = data_cmd::scaled_value(&tag, &path, *scale)?;
|
||||
let message = self.get_text(&target, &path, *scale, value);
|
||||
self.system_feedback(message);
|
||||
return Ok(value);
|
||||
}
|
||||
let value = data_cmd::get_value(&tag, &path)?;
|
||||
let message = self.query_text(&target, &tag);
|
||||
self.system_feedback(message);
|
||||
Ok(value)
|
||||
}
|
||||
"data.remove" => {
|
||||
let path = self.path_arg(ctx, "path")?;
|
||||
let mut data = self.data_of(&target)?;
|
||||
let count = path.remove(&mut data);
|
||||
if count == 0 {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, data)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(count as i32)
|
||||
}
|
||||
"data.modify" => self.cmd_data_modify(ctx, target),
|
||||
_ => Err(err("command.failed", &[])),
|
||||
}
|
||||
}
|
||||
/// A message sent without the feedback gamerule check (`sendSuccess(.., false)`).
|
||||
fn system_feedback(&mut self, message: Text) {
|
||||
self.feedback(message);
|
||||
}
|
||||
fn cmd_data_modify(&mut self, ctx: &Context, target: DataRef) -> R<i32> {
|
||||
let target_path = self.path_arg(ctx, "targetPath")?;
|
||||
let after_modify: Vec<&String> = ctx
|
||||
.literals
|
||||
.iter()
|
||||
.skip_while(|l| l.as_str() != "modify")
|
||||
.collect();
|
||||
let op = after_modify
|
||||
.iter()
|
||||
.find_map(|l| match l.as_str() {
|
||||
"prepend" => Some(Op::Prepend),
|
||||
"append" => Some(Op::Append),
|
||||
"set" => Some(Op::Set),
|
||||
"merge" => Some(Op::Merge),
|
||||
"insert" => Some(Op::Insert(match ctx.get("index") {
|
||||
Some(Arg::Int(i)) => *i,
|
||||
_ => 0,
|
||||
})),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(Op::Set);
|
||||
let sources: Vec<Tag> = if ctx.has("value") {
|
||||
let Some(Arg::Str(text)) = ctx.get("value") else {
|
||||
return Ok(0);
|
||||
};
|
||||
vec![
|
||||
parse_snbt(text)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?
|
||||
.0,
|
||||
]
|
||||
} else {
|
||||
let source = self.data_ref(ctx, 1)?;
|
||||
let data = self.data_of(&source)?;
|
||||
let tags = if ctx.get("sourcePath").is_some() {
|
||||
self.path_arg(ctx, "sourcePath")?
|
||||
.get(&data)
|
||||
.map_err(path_error)?
|
||||
} else {
|
||||
vec![data]
|
||||
};
|
||||
if ctx.has("string") {
|
||||
let start = match ctx.get("start") {
|
||||
Some(Arg::Int(i)) => Some(*i),
|
||||
_ => None,
|
||||
};
|
||||
let end = match ctx.get("end") {
|
||||
Some(Arg::Int(i)) => Some(*i),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for t in &tags {
|
||||
let text = data_cmd::as_text(t)?;
|
||||
let text = match start {
|
||||
Some(s) => data_cmd::substring(&text, s, end)?,
|
||||
None => text,
|
||||
};
|
||||
out.push(Tag::String(text.as_str().into()));
|
||||
}
|
||||
out
|
||||
} else {
|
||||
tags
|
||||
}
|
||||
};
|
||||
let mut data = self.data_of(&target)?;
|
||||
let changed = data_cmd::modify(op, &mut data, &target_path, &sources)?;
|
||||
if changed == 0 {
|
||||
return Err(err("commands.data.merge.failed", &[]));
|
||||
}
|
||||
self.set_data_of(&target, data)?;
|
||||
let message = self.modified_text(&target);
|
||||
self.feedback(message);
|
||||
Ok(changed as i32)
|
||||
}
|
||||
|
||||
// ---- /tag ------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_tag(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", false)?;
|
||||
let name = match ctx.get("name") {
|
||||
Some(Arg::Str(n)) => n.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let mut tracker = Tracker::default();
|
||||
let holder = |g: &Self, t: Target| Holder {
|
||||
name: String::new(),
|
||||
text: g.target_name(t),
|
||||
display: None,
|
||||
};
|
||||
let mut all: Vec<String> = Vec::new();
|
||||
for &t in &targets {
|
||||
let mut tags = self.tags_of(t);
|
||||
let h = holder(self, t);
|
||||
match id {
|
||||
"tag.add" => {
|
||||
let added = tags.len() < 1024 && !tags.contains(&name);
|
||||
if added {
|
||||
tags.push(name.clone());
|
||||
self.set_entity_tags(t, &tags);
|
||||
}
|
||||
tracker.track(&h, i32::from(added));
|
||||
}
|
||||
"tag.remove" => {
|
||||
let before = tags.len();
|
||||
tags.retain(|x| x != &name);
|
||||
let removed = tags.len() != before;
|
||||
if removed {
|
||||
self.set_entity_tags(t, &tags);
|
||||
}
|
||||
tracker.track(&h, i32::from(removed));
|
||||
}
|
||||
_ => {
|
||||
tracker.track(&h, tags.len() as i32);
|
||||
for tag in tags {
|
||||
if !all.contains(&tag) {
|
||||
all.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let num = |n: usize| Text::literal(n.to_string());
|
||||
let n = name.clone();
|
||||
let (message, total) = match id {
|
||||
"tag.add" => tracker.message(
|
||||
false,
|
||||
Some(err("commands.tag.add.failed", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.add.success.single",
|
||||
&[Text::literal(n.clone()), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.add.success.multiple",
|
||||
&[Text::literal(n.clone()), num(c)],
|
||||
)
|
||||
},
|
||||
),
|
||||
"tag.remove" => tracker.message(
|
||||
false,
|
||||
Some(err("commands.tag.remove.failed", &[])),
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.remove.success.single",
|
||||
&[Text::literal(n.clone()), h.text.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.remove.success.multiple",
|
||||
&[Text::literal(n.clone()), num(c)],
|
||||
)
|
||||
},
|
||||
),
|
||||
_ => {
|
||||
let count = all.len();
|
||||
let message = if all.is_empty() {
|
||||
tracker
|
||||
.message(
|
||||
false,
|
||||
None,
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.single.empty",
|
||||
std::slice::from_ref(&h.text),
|
||||
)
|
||||
},
|
||||
|c, _| Text::translate("commands.tag.list.multiple.empty", &[num(c)]),
|
||||
)?
|
||||
.0
|
||||
} else {
|
||||
let list = {
|
||||
let mut sorted = all.clone();
|
||||
sorted.sort();
|
||||
format_list(
|
||||
sorted
|
||||
.into_iter()
|
||||
.map(|s| Text::literal(s).with_color(horizon_client::text::GREEN))
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
tracker
|
||||
.message(
|
||||
true,
|
||||
None,
|
||||
|h, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.single.success",
|
||||
&[h.text.clone(), num(count), list.clone()],
|
||||
)
|
||||
},
|
||||
|c, _| {
|
||||
Text::translate(
|
||||
"commands.tag.list.multiple.success",
|
||||
&[num(c), num(count), list.clone()],
|
||||
)
|
||||
},
|
||||
)?
|
||||
.0
|
||||
};
|
||||
self.feedback(message);
|
||||
return Ok(count as i32);
|
||||
}
|
||||
}?;
|
||||
self.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
// ---- /summon ---------------------------------------------------------
|
||||
|
||||
/// Spawn an entity from its compound (`EntityType.loadEntityRecursive`);
|
||||
/// returns what was created.
|
||||
pub(super) fn spawn_entity_from_nbt(&mut self, tag: Tag) -> Option<Target> {
|
||||
let before = self.next_entity;
|
||||
let key = {
|
||||
let p = entity_nbt::position(&tag)?;
|
||||
((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4)
|
||||
};
|
||||
self.world.loaded_entities.push((key, vec![tag]));
|
||||
self.spawn_loaded_entities();
|
||||
let id = self.next_entity;
|
||||
if id == before {
|
||||
return None;
|
||||
}
|
||||
if self.mobs.iter().any(|m| m.id == id) {
|
||||
Some(Target::Mob(id))
|
||||
} else if self.dropped.iter().any(|e| e.id == id) {
|
||||
Some(Target::Item(id))
|
||||
} else if self.armor_stands.iter().any(|a| a.id == id) {
|
||||
Some(Target::Stand(id))
|
||||
} else if self.item_frames.iter().any(|f| f.id == id) {
|
||||
Some(Target::Frame(id))
|
||||
} else if self.paintings.iter().any(|p| p.id == id) {
|
||||
Some(Target::Painting(id))
|
||||
} else if self.boats.iter().any(|b| b.id == id) {
|
||||
Some(Target::Boat(id))
|
||||
} else if self.carts.iter().any(|c| c.id == id) {
|
||||
Some(Target::Cart(id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// The `summon <entity> <pos> <nbt>` form.
|
||||
pub(super) fn summon_with_nbt(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
pos: [f64; 3],
|
||||
nbt: &str,
|
||||
) -> R<Option<Target>> {
|
||||
let (mut tag, _) = parse_snbt(nbt).map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
if !matches!(tag, Tag::Compound(_)) {
|
||||
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()),
|
||||
]),
|
||||
);
|
||||
}
|
||||
Ok(self.spawn_entity_from_nbt(tag))
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ pub(super) struct Recorded {
|
||||
#[derive(Default)]
|
||||
pub(super) struct ScoreState {
|
||||
pub board: Scoreboard,
|
||||
/// `/data ... storage`.
|
||||
pub storage: horizon_client::command_storage::CommandStorage,
|
||||
loaded: bool,
|
||||
recorded: Recorded,
|
||||
}
|
||||
@@ -53,12 +55,15 @@ impl Game<'_> {
|
||||
{
|
||||
self.score.board = Scoreboard::unpack(data);
|
||||
}
|
||||
self.score.storage =
|
||||
horizon_client::command_storage::CommandStorage::load(&self.world_root);
|
||||
self.sync_score_registries();
|
||||
}
|
||||
pub(super) fn save_scoreboard(&self) {
|
||||
pub(super) fn save_scoreboard(&mut self) {
|
||||
if !self.score.loaded || self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.score.storage.save(&self.world_root);
|
||||
let path = self.scoreboard_path();
|
||||
let board = &self.score.board;
|
||||
if board == &Scoreboard::default() && !path.exists() {
|
||||
@@ -79,6 +84,7 @@ impl Game<'_> {
|
||||
reg.objectives = board.objectives.iter().map(|o| o.name.clone()).collect();
|
||||
reg.teams = board.teams.iter().map(|t| t.name.clone()).collect();
|
||||
reg.tracked = board.tracked();
|
||||
reg.storages = self.score.storage.keys();
|
||||
}
|
||||
|
||||
// ---- score holders ---------------------------------------------------
|
||||
@@ -190,6 +196,22 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if ok && !s.nbt.is_empty() {
|
||||
// NbtPredicate: the entity's saved data contains the pattern.
|
||||
let data = self.entity_nbt(t);
|
||||
for (pattern, negated) in &s.nbt {
|
||||
let matches = match (&data, horizon_world::nbt::parse_snbt(pattern)) {
|
||||
(Some(d), Ok((p, _))) => horizon_client::nbt_path::compare_nbt(&p, Some(d)),
|
||||
_ => false,
|
||||
};
|
||||
if matches == *negated {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ok && !s.advancements.is_empty() {
|
||||
ok = t == Target::Player && self.advancements_match(&s.advancements);
|
||||
}
|
||||
if ok {
|
||||
pass.insert(t);
|
||||
}
|
||||
@@ -197,6 +219,25 @@ impl Game<'_> {
|
||||
pass
|
||||
}
|
||||
|
||||
/// `advancements=` of a selector, against the player's progress.
|
||||
fn advancements_match(
|
||||
&self,
|
||||
wanted: &[(String, horizon_client::command::args::AdvCondition)],
|
||||
) -> bool {
|
||||
use horizon_client::command::args::AdvCondition;
|
||||
wanted.iter().all(|(id, cond)| {
|
||||
let Some(a) = self.adv.tree.get(id) else {
|
||||
return false;
|
||||
};
|
||||
match cond {
|
||||
AdvCondition::Done(want) => self.adv.progress.done(a) == *want,
|
||||
AdvCondition::Criteria(list) => list
|
||||
.iter()
|
||||
.all(|(c, want)| self.adv.progress.has(id, c) == *want),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- criteria ----------------------------------------------------------
|
||||
|
||||
/// `ServerPlayer.doTick` score updates and the statistic criteria.
|
||||
|
||||
@@ -16,11 +16,13 @@ pub mod chunk;
|
||||
pub mod clock;
|
||||
pub mod collisions;
|
||||
pub mod command;
|
||||
pub mod command_storage;
|
||||
pub mod component;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
pub mod creative;
|
||||
pub mod data_cmd;
|
||||
pub mod effects;
|
||||
pub mod enchant;
|
||||
pub mod entities;
|
||||
@@ -47,6 +49,7 @@ pub mod models;
|
||||
pub mod motion;
|
||||
pub mod multiplayer;
|
||||
pub mod music;
|
||||
pub mod nbt_path;
|
||||
pub mod net;
|
||||
pub mod options_ui;
|
||||
pub mod packs;
|
||||
@@ -60,6 +63,7 @@ pub mod screen_effects;
|
||||
pub mod settings;
|
||||
pub mod shadows;
|
||||
pub mod signs;
|
||||
pub mod snbt;
|
||||
pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
|
||||
@@ -515,6 +515,12 @@ pub struct Mob {
|
||||
pub extra: Extra,
|
||||
pub fluids: living::Fluids,
|
||||
pub no_gravity: bool,
|
||||
/// `NoAI`: no goals and no movement.
|
||||
pub no_ai: bool,
|
||||
/// `Silent`.
|
||||
pub silent: bool,
|
||||
/// `Invulnerable`: immune to damage (but not to `/kill`).
|
||||
pub invulnerable_flag: bool,
|
||||
pub climbing: bool,
|
||||
pub fire_ticks: i32,
|
||||
pub air: i32,
|
||||
@@ -785,6 +791,9 @@ impl Mob {
|
||||
extra: Extra::default(),
|
||||
fluids: living::Fluids::default(),
|
||||
no_gravity: false,
|
||||
no_ai: false,
|
||||
silent: false,
|
||||
invulnerable_flag: false,
|
||||
climbing: false,
|
||||
fire_ticks: 0,
|
||||
air: 300,
|
||||
@@ -858,7 +867,7 @@ impl Mob {
|
||||
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
|
||||
}
|
||||
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
|
||||
if !self.alive() || self.removed {
|
||||
if !self.alive() || self.removed || self.invulnerable_flag {
|
||||
return false;
|
||||
}
|
||||
if source.is_fire() && (self.kind.flags.fire_immune) {
|
||||
|
||||
@@ -254,7 +254,9 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
if m.death_time >= 20 {
|
||||
return false;
|
||||
}
|
||||
ai_step(m, w, events);
|
||||
if !m.no_ai {
|
||||
ai_step(m, w, events);
|
||||
}
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick
|
||||
if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
|
||||
@@ -0,0 +1,901 @@
|
||||
//! NBT paths (`NbtPathArgument`): `foo.bar[0]`, `[]`, `list[{id:1}]`,
|
||||
//! `{root:match}`, with get, set, insert and remove on a tag tree, and the
|
||||
//! partial NBT comparison (`NbtUtils.compareNbt`) selectors and conditions use.
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
|
||||
|
||||
/// An error carrying the translation key and its arguments.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PathError {
|
||||
pub key: &'static str,
|
||||
pub args: Vec<String>,
|
||||
/// Byte offset in the path text (parse errors).
|
||||
pub cursor: usize,
|
||||
}
|
||||
impl PathError {
|
||||
fn new(key: &'static str, args: Vec<String>, cursor: usize) -> Self {
|
||||
Self { key, args, cursor }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Node {
|
||||
/// `name`
|
||||
Child(String),
|
||||
/// `name{pattern}`
|
||||
MatchChild(String, Tag),
|
||||
/// `[]`
|
||||
AllElements,
|
||||
/// `[n]`
|
||||
Index(i32),
|
||||
/// `[{pattern}]`
|
||||
MatchElement(Tag),
|
||||
/// `{pattern}` at the start.
|
||||
MatchRoot(Tag),
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NbtPath {
|
||||
original: String,
|
||||
nodes: Vec<Node>,
|
||||
/// Byte offset just after each node in `original`.
|
||||
ends: Vec<usize>,
|
||||
}
|
||||
|
||||
fn key(s: &str) -> JavaString {
|
||||
JavaString::from(s)
|
||||
}
|
||||
fn get_child<'a>(c: &'a Compound, name: &str) -> Option<&'a Tag> {
|
||||
c.get(&key(name))
|
||||
}
|
||||
|
||||
/// `NbtUtils.compareNbt(expected, actual, true)`.
|
||||
pub fn compare_nbt(expected: &Tag, actual: Option<&Tag>) -> bool {
|
||||
let Some(actual) = actual else { return false };
|
||||
if std::mem::discriminant(expected) != std::mem::discriminant(actual) {
|
||||
return false;
|
||||
}
|
||||
match (expected, actual) {
|
||||
(Tag::Compound(e), Tag::Compound(a)) => {
|
||||
a.len() >= e.len() && e.iter().all(|(k, v)| compare_nbt(v, a.get(k)))
|
||||
}
|
||||
(Tag::List(e), Tag::List(a)) => {
|
||||
if e.is_empty() {
|
||||
return a.is_empty();
|
||||
}
|
||||
a.len() >= e.len() && e.iter().all(|x| a.iter().any(|y| compare_nbt(x, Some(y))))
|
||||
}
|
||||
_ => expected == actual,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- list-like tags ----------------------------------------------------------
|
||||
|
||||
/// The elements of a list or array tag.
|
||||
fn elements(tag: &Tag) -> Option<Vec<Tag>> {
|
||||
Some(match tag {
|
||||
Tag::List(l) => l.clone(),
|
||||
Tag::ByteArray(a) => a.iter().map(|b| Tag::Byte(*b as i8)).collect(),
|
||||
Tag::IntArray(a) => a.iter().map(|v| Tag::Int(*v)).collect(),
|
||||
Tag::LongArray(a) => a.iter().map(|v| Tag::Long(*v)).collect(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn number(t: &Tag) -> Option<i64> {
|
||||
match t {
|
||||
Tag::Byte(v) => Some(i64::from(*v)),
|
||||
Tag::Short(v) => Some(i64::from(*v)),
|
||||
Tag::Int(v) => Some(i64::from(*v)),
|
||||
Tag::Long(v) => Some(*v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Run `f` over the elements of a list/array, writing array results back.
|
||||
/// None when `tag` is not list-like.
|
||||
fn with_elements<R>(tag: &mut Tag, f: impl FnOnce(&mut Vec<Tag>) -> R) -> Option<R> {
|
||||
match tag {
|
||||
Tag::List(l) => Some(f(l)),
|
||||
Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_) => {
|
||||
let mut v = elements(tag)?;
|
||||
let r = f(&mut v);
|
||||
let nums: Vec<i64> = v.iter().filter_map(number).collect();
|
||||
match tag {
|
||||
Tag::ByteArray(a) => *a = nums.iter().map(|n| *n as u8).collect(),
|
||||
Tag::IntArray(a) => *a = nums.iter().map(|n| *n as i32).collect(),
|
||||
Tag::LongArray(a) => *a = nums,
|
||||
_ => {}
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtPath {
|
||||
/// `NbtPathArgument.parse` from the start of `text`; returns the path and
|
||||
/// the bytes consumed (it stops at a space).
|
||||
pub fn parse_prefix(text: &str) -> Result<(NbtPath, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut nodes = Vec::new();
|
||||
let mut ends = Vec::new();
|
||||
let mut first = true;
|
||||
while i < b.len() && b[i] != b' ' {
|
||||
let (node, next) = parse_node(text, i, first)?;
|
||||
nodes.push(node);
|
||||
i = next;
|
||||
ends.push(i);
|
||||
first = false;
|
||||
if i < b.len() && !matches!(b[i], b' ' | b'[' | b'{') {
|
||||
if b[i] != b'.' {
|
||||
return Err(PathError::new("parsing.expected", vec![".".into()], i));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
NbtPath {
|
||||
original: text[..i].to_owned(),
|
||||
nodes,
|
||||
ends,
|
||||
},
|
||||
i,
|
||||
))
|
||||
}
|
||||
pub fn parse(text: &str) -> Result<NbtPath, PathError> {
|
||||
let (p, used) = Self::parse_prefix(text)?;
|
||||
if used != text.len() {
|
||||
return Err(PathError::new(
|
||||
"arguments.nbtpath.node.invalid",
|
||||
vec![],
|
||||
used,
|
||||
));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.original
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty()
|
||||
}
|
||||
fn not_found(&self, node: usize) -> PathError {
|
||||
let end = self.ends[node];
|
||||
PathError::new(
|
||||
"arguments.nbtpath.nothing_found",
|
||||
vec![self.original[..end.min(self.original.len())].to_owned()],
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- reading --------------------------------------------------------
|
||||
|
||||
fn step<'a>(node: &Node, parent: &'a Tag, out: &mut Vec<&'a Tag>) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter());
|
||||
}
|
||||
}
|
||||
Node::Index(i) => {
|
||||
if let Tag::List(l) = parent {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out.push(&l[idx as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter().filter(|t| compare_nbt(pattern, Some(t))));
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out.push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Array tags read as lists of their elements.
|
||||
fn read_steps(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
let mut current: Vec<Tag> = vec![root.clone()];
|
||||
for (i, node) in self.nodes.iter().enumerate() {
|
||||
let mut next = Vec::new();
|
||||
for parent in ¤t {
|
||||
// Arrays expose their elements to element nodes.
|
||||
let list;
|
||||
let p = if matches!(node, Node::AllElements | Node::Index(_)) {
|
||||
match elements(parent) {
|
||||
Some(l) if !matches!(parent, Tag::List(_)) => {
|
||||
list = Tag::List(l);
|
||||
&list
|
||||
}
|
||||
_ => parent,
|
||||
}
|
||||
} else {
|
||||
parent
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
Self::step(node, p, &mut out);
|
||||
next.extend(out.into_iter().cloned());
|
||||
}
|
||||
if next.is_empty() {
|
||||
return Err(self.not_found(i));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
/// `get`: every matching tag (an error when nothing matches).
|
||||
pub fn get(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
self.read_steps(root)
|
||||
}
|
||||
/// `countMatching`.
|
||||
pub fn count(&self, root: &Tag) -> usize {
|
||||
self.read_steps(root).map_or(0, |v| v.len())
|
||||
}
|
||||
|
||||
// ---- writing --------------------------------------------------------
|
||||
|
||||
/// The parents of the last node, creating the missing ones (`getOrCreateParents`).
|
||||
fn visit_parents(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
create: bool,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len().saturating_sub(1), root, create, None, f)
|
||||
}
|
||||
/// Walk `nodes[from..to]` from `tag`, calling `f` on every tag reached.
|
||||
fn descend(
|
||||
&self,
|
||||
from: usize,
|
||||
to: usize,
|
||||
tag: &mut Tag,
|
||||
create: bool,
|
||||
last_value: Option<&dyn Fn() -> Tag>,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
if from >= to {
|
||||
f(tag);
|
||||
return Ok(());
|
||||
}
|
||||
let node = &self.nodes[from];
|
||||
// What a created child should be: the next node's preferred parent,
|
||||
// or the caller's value for the last node.
|
||||
let default_child = || -> Tag {
|
||||
match (self.nodes.get(from + 1), last_value) {
|
||||
(Some(next), _) if from + 1 < to => preferred_parent(next),
|
||||
(_, Some(v)) => v(),
|
||||
(Some(next), None) => preferred_parent(next),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
};
|
||||
let mut found = false;
|
||||
let mut error = None;
|
||||
let mut visit = |child: &mut Tag| {
|
||||
found = true;
|
||||
if error.is_none()
|
||||
&& let Err(e) = self.descend(from + 1, to, child, create, last_value, f)
|
||||
{
|
||||
error = Some(e);
|
||||
}
|
||||
};
|
||||
step_mut(
|
||||
node,
|
||||
tag,
|
||||
create.then_some(&default_child as &dyn Fn() -> Tag),
|
||||
&mut visit,
|
||||
);
|
||||
if let Some(e) = error {
|
||||
return Err(e);
|
||||
}
|
||||
if !found {
|
||||
return Err(self.not_found(from));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `getOrCreate`: the tags at the path, creating missing ones as
|
||||
/// `new_value` (used for the last node).
|
||||
pub fn get_or_create(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
new_value: &dyn Fn() -> Tag,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len(), root, true, Some(new_value), f)
|
||||
}
|
||||
/// `set`: returns how many tags changed.
|
||||
pub fn set(&self, root: &mut Tag, value: &Tag) -> Result<usize, PathError> {
|
||||
if too_deep(value, self.nodes.len()) {
|
||||
return Err(PathError::new("arguments.nbtpath.too_deep", vec![], 0));
|
||||
}
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut changed = 0;
|
||||
self.visit_parents(root, true, &mut |parent| {
|
||||
changed += set_tag(last, parent, value);
|
||||
})?;
|
||||
Ok(changed)
|
||||
}
|
||||
/// `remove`: returns how many tags were removed.
|
||||
pub fn remove(&self, root: &mut Tag) -> usize {
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return 0;
|
||||
};
|
||||
let mut removed = 0;
|
||||
let _ = self.visit_parents(root, false, &mut |parent| {
|
||||
removed += remove_tag(last, parent);
|
||||
});
|
||||
removed
|
||||
}
|
||||
/// `insert` (also append and prepend): into every list the path reaches.
|
||||
pub fn insert(
|
||||
&self,
|
||||
index: i32,
|
||||
root: &mut Tag,
|
||||
values: &[Tag],
|
||||
) -> Result<usize, CollectionError> {
|
||||
for v in values {
|
||||
if too_deep(v, self.nodes.len()) {
|
||||
return Err(CollectionError::Path(PathError::new(
|
||||
"arguments.nbtpath.too_deep",
|
||||
vec![],
|
||||
0,
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut modified = 0;
|
||||
let mut error: Option<CollectionError> = None;
|
||||
self.get_or_create(root, &|| Tag::List(Vec::new()), &mut |target| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
let shown = crate::snbt::to_snbt(target);
|
||||
let result = with_elements(target, |list| {
|
||||
let start = if index < 0 {
|
||||
list.len() as i64 + i64::from(index) + 1
|
||||
} else {
|
||||
i64::from(index)
|
||||
};
|
||||
let mut any = false;
|
||||
for (n, v) in values.iter().enumerate() {
|
||||
let at = start + n as i64;
|
||||
if at < 0 || at as usize > list.len() {
|
||||
return Err(CollectionError::InvalidIndex(at as i32));
|
||||
}
|
||||
list.insert(at as usize, v.clone());
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
});
|
||||
match result {
|
||||
None => error = Some(CollectionError::ExpectedList(shown)),
|
||||
Some(Err(e)) => error = Some(e),
|
||||
Some(Ok(any)) => modified += usize::from(any),
|
||||
}
|
||||
})
|
||||
.map_err(CollectionError::Path)?;
|
||||
match error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(modified),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum CollectionError {
|
||||
Path(PathError),
|
||||
/// `commands.data.modify.expected_list` with the offending tag.
|
||||
ExpectedList(String),
|
||||
/// `commands.data.modify.invalid_index`.
|
||||
InvalidIndex(i32),
|
||||
}
|
||||
|
||||
/// `isTooDeep`.
|
||||
pub fn too_deep(tag: &Tag, depth: usize) -> bool {
|
||||
if depth >= 512 {
|
||||
return true;
|
||||
}
|
||||
match tag {
|
||||
Tag::Compound(c) => c.values().any(|t| too_deep(t, depth + 1)),
|
||||
Tag::List(l) => l.iter().any(|t| too_deep(t, depth + 1)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn preferred_parent(node: &Node) -> Tag {
|
||||
match node {
|
||||
Node::AllElements | Node::Index(_) | Node::MatchElement(_) => Tag::List(Vec::new()),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
}
|
||||
/// `getOrCreateTag` (or `getTag` without `create`): the children of `parent`.
|
||||
fn step_mut(
|
||||
node: &Node,
|
||||
parent: &mut Tag,
|
||||
create: Option<&dyn Fn() -> Tag>,
|
||||
out: &mut dyn FnMut(&mut Tag),
|
||||
) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
let Some(make) = create else { return };
|
||||
c.insert(k.clone(), make());
|
||||
}
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
if create.is_none() {
|
||||
return;
|
||||
}
|
||||
c.insert(k.clone(), pattern.clone());
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
} else if let Some(t) = c.get_mut(&k)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
let make = create;
|
||||
let _ = with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
if let Some(make) = make {
|
||||
list.push(make());
|
||||
out(&mut list[0]);
|
||||
}
|
||||
} else {
|
||||
for t in list.iter_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::Index(i) => {
|
||||
let _ = with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out(&mut list[idx as usize]);
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(list) = parent {
|
||||
let mut any = false;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) {
|
||||
any = true;
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
if !any && create.is_some() {
|
||||
list.push(pattern.clone());
|
||||
if let Some(t) = list.last_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Node.setTag`: replace the child(ren) of `parent` with `value`.
|
||||
fn set_tag(node: &Node, parent: &mut Tag, value: &Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let prev = c.insert(key(name), value.clone());
|
||||
return usize::from(prev.as_ref() != Some(value));
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) && c.get(&k) != Some(value) {
|
||||
c.insert(k, value.clone());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::AllElements => with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let changed = list.iter().filter(|t| *t != value).count();
|
||||
if changed == 0 {
|
||||
return 0;
|
||||
}
|
||||
for t in list.iter_mut() {
|
||||
*t = value.clone();
|
||||
}
|
||||
changed
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) && list[idx as usize] != *value {
|
||||
list[idx as usize] = value.clone();
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => {
|
||||
let Tag::List(list) = parent else { return 0 };
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let mut changed = 0;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) && t != value {
|
||||
*t = value.clone();
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
fn remove_tag(node: &Node, parent: &mut Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => match parent {
|
||||
Tag::Compound(c) => usize::from(c.remove(&key(name)).is_some()),
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchChild(name, pattern) => match parent {
|
||||
Tag::Compound(c) => {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) {
|
||||
usize::from(c.remove(&k).is_some())
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::AllElements => with_elements(parent, |l| {
|
||||
let n = l.len();
|
||||
l.clear();
|
||||
n
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |l| {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
l.remove(idx as usize);
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => match parent {
|
||||
Tag::List(l) => {
|
||||
let before = l.len();
|
||||
l.retain(|t| !compare_nbt(pattern, Some(t)));
|
||||
before - l.len()
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- parsing -------------------------------------------------------------------
|
||||
|
||||
fn parse_node(text: &str, i: usize, first: bool) -> Result<(Node, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let invalid = |at: usize| PathError::new("arguments.nbtpath.node.invalid", vec![], at);
|
||||
match b[i] {
|
||||
b'"' | b'\'' => {
|
||||
let (name, next) = read_quoted(text, i)?;
|
||||
read_object_node(text, name, next)
|
||||
}
|
||||
b'[' => {
|
||||
let mut j = i + 1;
|
||||
match b.get(j) {
|
||||
Some(b'{') => {
|
||||
let (pattern, next) = parse_compound(text, j)?;
|
||||
j = next;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::MatchElement(pattern), j + 1))
|
||||
}
|
||||
Some(b']') => Ok((Node::AllElements, j + 1)),
|
||||
_ => {
|
||||
let start = j;
|
||||
if b.get(j) == Some(&b'-') {
|
||||
j += 1;
|
||||
}
|
||||
while b.get(j).is_some_and(u8::is_ascii_digit) {
|
||||
j += 1;
|
||||
}
|
||||
let n: i32 = text[start..j].parse().map_err(|_| {
|
||||
PathError::new(
|
||||
"parsing.int.invalid",
|
||||
vec![text[start..j].to_owned()],
|
||||
start,
|
||||
)
|
||||
})?;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::Index(n), j + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
if !first {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
Ok((Node::MatchRoot(pattern), next))
|
||||
}
|
||||
_ => {
|
||||
let mut j = i;
|
||||
while j < b.len()
|
||||
&& !matches!(b[j], b' ' | b'"' | b'\'' | b'[' | b']' | b'.' | b'{' | b'}')
|
||||
{
|
||||
j += 1;
|
||||
}
|
||||
if j == i {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
read_object_node(text, text[i..j].to_owned(), j)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_object_node(text: &str, name: String, i: usize) -> Result<(Node, usize), PathError> {
|
||||
if name.is_empty() {
|
||||
return Err(PathError::new("arguments.nbtpath.node.invalid", vec![], i));
|
||||
}
|
||||
if text.as_bytes().get(i) == Some(&b'{') {
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
return Ok((Node::MatchChild(name, pattern), next));
|
||||
}
|
||||
Ok((Node::Child(name), i))
|
||||
}
|
||||
fn expect(text: &str, i: usize, c: u8) -> Result<(), PathError> {
|
||||
if text.as_bytes().get(i) == Some(&c) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PathError::new(
|
||||
"parsing.expected",
|
||||
vec![(c as char).to_string()],
|
||||
i,
|
||||
))
|
||||
}
|
||||
}
|
||||
fn read_quoted(text: &str, i: usize) -> Result<(String, usize), PathError> {
|
||||
let quote = text.as_bytes()[i] as char;
|
||||
let mut out = String::new();
|
||||
let mut escaped = false;
|
||||
for (o, c) in text[i + 1..].char_indices() {
|
||||
if escaped {
|
||||
out.push(c);
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == quote {
|
||||
return Ok((out, i + 1 + o + c.len_utf8()));
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err(PathError::new(
|
||||
"parsing.quote.expected.end",
|
||||
vec![],
|
||||
text.len(),
|
||||
))
|
||||
}
|
||||
fn parse_compound(text: &str, i: usize) -> Result<(Tag, usize), PathError> {
|
||||
// Find the balanced end of the braces, then parse the SNBT inside.
|
||||
let b = text.as_bytes();
|
||||
let mut depth = 0;
|
||||
let mut quote: Option<u8> = None;
|
||||
let mut j = i;
|
||||
while j < b.len() {
|
||||
let c = b[j];
|
||||
match quote {
|
||||
Some(_) if c == b'\\' => j += 1,
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if c == b'"' || c == b'\'' => quote = Some(c),
|
||||
None if c == b'{' || c == b'[' => depth += 1,
|
||||
None if c == b'}' || c == b']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
let (tag, _) = parse_snbt(&text[i..=j])
|
||||
.map_err(|e| PathError::new("argument.nbt.invalid", vec![e], i))?;
|
||||
return Ok((tag, j + 1));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
Err(PathError::new("argument.nbt.expected.compound", vec![], i))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(s: &str) -> Tag {
|
||||
parse_snbt(s).unwrap().0
|
||||
}
|
||||
fn path(s: &str) -> NbtPath {
|
||||
NbtPath::parse(s).unwrap_or_else(|e| panic!("{s}: {e:?}"))
|
||||
}
|
||||
fn show(v: &[Tag]) -> Vec<String> {
|
||||
v.iter().map(crate::snbt::to_snbt).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_follows_the_path() {
|
||||
let root = tag("{a:{b:[{id:1,n:\"x\"},{id:2,n:\"y\"},{id:3}]},c:5,\"d e\":7}");
|
||||
assert_eq!(show(&path("c").get(&root).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("\"d e\"").get(&root).unwrap()), ["7"]);
|
||||
assert_eq!(show(&path("a.b[0].n").get(&root).unwrap()), ["\"x\""]);
|
||||
assert_eq!(show(&path("a.b[-1]").get(&root).unwrap()), ["{id:3}"]);
|
||||
assert_eq!(show(&path("a.b[].id").get(&root).unwrap()), ["1", "2", "3"]);
|
||||
assert_eq!(show(&path("a.b[{id:2}].n").get(&root).unwrap()), ["\"y\""]);
|
||||
assert_eq!(
|
||||
show(&path("a{b:[{id:1}]}.b[0].id").get(&root).unwrap()),
|
||||
["1"]
|
||||
);
|
||||
assert_eq!(show(&path("{c:5}.c").get(&root).unwrap()), ["5"]);
|
||||
assert!(path("{c:6}.c").get(&root).is_err());
|
||||
let e = path("a.zzz.q").get(&root).unwrap_err();
|
||||
assert_eq!(e.key, "arguments.nbtpath.nothing_found");
|
||||
assert_eq!(e.args, ["a.zzz"]);
|
||||
assert_eq!(path("a.b[].id").count(&root), 3);
|
||||
assert_eq!(path("a.nope").count(&root), 0);
|
||||
// Arrays act like lists.
|
||||
let arr = tag("{v:[I;4,5,6]}");
|
||||
assert_eq!(show(&path("v[1]").get(&arr).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("v[]").get(&arr).unwrap()), ["4", "5", "6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_errors() {
|
||||
assert_eq!(
|
||||
NbtPath::parse("a..b").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(
|
||||
NbtPath::parse("a.{b:1}").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(NbtPath::parse("a[1").unwrap_err().key, "parsing.expected");
|
||||
assert_eq!(NbtPath::parse("a]").unwrap_err().key, "parsing.expected");
|
||||
let (p, used) = NbtPath::parse_prefix("a.b[0] rest").unwrap();
|
||||
assert_eq!((p.as_str(), used), ("a.b[0]", 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_creates_and_reports_changes() {
|
||||
let mut root = tag("{a:{x:1}}");
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 1);
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 0);
|
||||
assert_eq!(path("b.c.d").set(&mut root, &tag("\"deep\"")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{a:{x:2},b:{c:{d:\"deep\"}}}");
|
||||
let mut root = tag("{l:[1,2,3]}");
|
||||
assert_eq!(path("l[1]").set(&mut root, &tag("9")).unwrap(), 1);
|
||||
assert_eq!(path("l[7]").set(&mut root, &tag("9")).unwrap(), 0);
|
||||
assert_eq!(path("l[]").set(&mut root, &tag("0")).unwrap(), 3);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,0,0]}");
|
||||
let mut root = tag("{l:[{id:1,v:0},{id:2,v:0}]}");
|
||||
assert_eq!(path("l[{id:2}].v").set(&mut root, &tag("5")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{id:1,v:0},{id:2,v:5}]}");
|
||||
// A missing match is created from the pattern.
|
||||
assert_eq!(path("l[{id:3}].v").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(path("l[{id:3}].v").count(&root), 1);
|
||||
// New lists come from index nodes.
|
||||
let mut root = tag("{}");
|
||||
assert_eq!(path("x[].y").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{x:[{y:1}]}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_counts() {
|
||||
let mut root = tag("{a:1,l:[1,2,3,2],c:{d:1}}");
|
||||
assert_eq!(path("a").remove(&mut root), 1);
|
||||
assert_eq!(path("a").remove(&mut root), 0);
|
||||
assert_eq!(path("l[1]").remove(&mut root), 1);
|
||||
assert_eq!(path("c.d").remove(&mut root), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{c:{},l:[1,3,2]}");
|
||||
let mut root = tag("{l:[{k:1},{k:2},{k:1}]}");
|
||||
assert_eq!(path("l[{k:1}]").remove(&mut root), 2);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{k:2}]}");
|
||||
assert_eq!(path("l[]").remove(&mut root), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_positions() {
|
||||
let mut root = tag("{l:[1,2]}");
|
||||
assert_eq!(path("l").insert(0, &mut root, &[tag("0")]).unwrap(), 1);
|
||||
assert_eq!(path("l").insert(-1, &mut root, &[tag("9")]).unwrap(), 1);
|
||||
assert_eq!(
|
||||
path("l")
|
||||
.insert(1, &mut root, &[tag("5"), tag("6")])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,5,6,1,2,9]}");
|
||||
assert_eq!(
|
||||
path("l").insert(99, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::InvalidIndex(99)
|
||||
);
|
||||
// A missing list is created.
|
||||
assert_eq!(path("n").insert(-1, &mut root, &[tag("1")]).unwrap(), 1);
|
||||
assert!(matches!(
|
||||
path("l[0]").insert(0, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::ExpectedList(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_comparison() {
|
||||
let actual = tag("{a:1,b:{c:[1,2,3],d:\"x\"},e:2}");
|
||||
assert!(compare_nbt(&tag("{b:{c:[2]}}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{a:1}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:2}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:1L}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{z:1}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{b:{c:[]}}"), Some(&tag("{b:{c:[]}}"))));
|
||||
assert!(!compare_nbt(&tag("{b:{c:[]}}"), Some(&actual)));
|
||||
}
|
||||
}
|
||||
@@ -349,7 +349,11 @@ fn block_entity_id(e: &crate::containers::BlockEntity, block: &str) -> String {
|
||||
_ => e.id().to_owned(),
|
||||
}
|
||||
}
|
||||
fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, block: &str) -> Tag {
|
||||
pub fn encode_block_entity(
|
||||
p: (i32, i32, i32),
|
||||
e: &crate::containers::BlockEntity,
|
||||
block: &str,
|
||||
) -> Tag {
|
||||
use crate::containers::BlockEntity;
|
||||
let mut entries = vec![
|
||||
("id", string(&block_entity_id(e, block))),
|
||||
@@ -403,7 +407,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b
|
||||
}
|
||||
Tag::compound(entries)
|
||||
}
|
||||
fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> {
|
||||
pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> {
|
||||
use crate::containers::BlockEntity;
|
||||
let int = |k: &str| number(tag.get(k)).map(|v| v as i32);
|
||||
let id = text(tag.get("id"))?;
|
||||
@@ -1543,7 +1547,7 @@ impl Level {
|
||||
};
|
||||
}
|
||||
/// The player compound: the loaded one with Horizon's state written over it.
|
||||
fn player_tag(&self) -> Tag {
|
||||
pub fn player_tag(&self) -> Tag {
|
||||
let mut p = compound_or_empty(self.player_extra.clone());
|
||||
// Keys rewritten from scratch.
|
||||
if let Tag::Compound(map) = &mut p {
|
||||
|
||||
@@ -109,6 +109,18 @@ impl Tracker {
|
||||
single: impl Fn(&Holder, i32) -> Text,
|
||||
multiple: impl Fn(usize, i32) -> Text,
|
||||
) -> CmdResult<i32> {
|
||||
let (message, total) = self.message(any, zero, single, multiple)?;
|
||||
env.feedback(message);
|
||||
Ok(total)
|
||||
}
|
||||
/// The feedback `send` would produce, and the command's result.
|
||||
pub fn message(
|
||||
&self,
|
||||
any: bool,
|
||||
zero: Option<CommandError>,
|
||||
single: impl Fn(&Holder, i32) -> Text,
|
||||
multiple: impl Fn(usize, i32) -> Text,
|
||||
) -> CmdResult<(Text, i32)> {
|
||||
let (only, count) = if any {
|
||||
(&self.only, self.count)
|
||||
} else {
|
||||
@@ -123,8 +135,7 @@ impl Tracker {
|
||||
Some(h) => single(h, self.total),
|
||||
None => multiple(count, self.total),
|
||||
};
|
||||
env.feedback(message);
|
||||
Ok(self.total)
|
||||
Ok((message, self.total))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Tag text output: `StringTagVisitor` (compact SNBT) and
|
||||
//! `TextComponentTagVisitor` (the coloured form commands print), plus Java's
|
||||
//! number formatting.
|
||||
use crate::text::{self, Style, Text};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `Double.toString`.
|
||||
pub fn java_double(v: f64) -> String {
|
||||
java_float_text(v, &format!("{v}"), &format!("{v:e}"))
|
||||
}
|
||||
/// `Float.toString`.
|
||||
pub fn java_float(v: f32) -> String {
|
||||
java_float_text(f64::from(v), &format!("{v}"), &format!("{v:e}"))
|
||||
}
|
||||
fn java_float_text(v: f64, plain: &str, sci: &str) -> String {
|
||||
if v.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if v.is_infinite() {
|
||||
return if v > 0.0 { "Infinity" } else { "-Infinity" }.into();
|
||||
}
|
||||
if v == 0.0 {
|
||||
return if v.is_sign_negative() { "-0.0" } else { "0.0" }.into();
|
||||
}
|
||||
let a = v.abs();
|
||||
if (1.0e-3..1.0e7).contains(&a) {
|
||||
if plain.contains('.') {
|
||||
plain.to_owned()
|
||||
} else {
|
||||
format!("{plain}.0")
|
||||
}
|
||||
} else {
|
||||
let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
|
||||
let mantissa = if mantissa.contains('.') {
|
||||
mantissa.to_owned()
|
||||
} else {
|
||||
format!("{mantissa}.0")
|
||||
};
|
||||
format!("{mantissa}E{exponent}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `SnbtGrammar.escapeControlCharacters`.
|
||||
fn escape_control(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'\u{8}' => "b",
|
||||
'\u{c}' => "f",
|
||||
'\n' => "n",
|
||||
'\r' => "r",
|
||||
'\t' => "t",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `StringTag.quoteAndEscape`.
|
||||
pub fn quote_and_escape(input: &str) -> String {
|
||||
let mut out = String::from(" ");
|
||||
let mut quote = '\0';
|
||||
for c in input.chars() {
|
||||
if c == '\\' {
|
||||
out.push_str("\\\\");
|
||||
} else if c != '"' && c != '\'' {
|
||||
match escape_control(c) {
|
||||
Some(e) => {
|
||||
out.push('\\');
|
||||
out.push_str(e);
|
||||
}
|
||||
None => out.push(c),
|
||||
}
|
||||
} else {
|
||||
if quote == '\0' {
|
||||
quote = if c == '"' { '\'' } else { '"' };
|
||||
}
|
||||
if quote == c {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
if quote == '\0' {
|
||||
quote = '"';
|
||||
}
|
||||
out.replace_range(0..1, "e.to_string());
|
||||
out.push(quote);
|
||||
out
|
||||
}
|
||||
fn unquoted_key(key: &str) -> bool {
|
||||
if key.eq_ignore_ascii_case("true") || key.eq_ignore_ascii_case("false") {
|
||||
return false;
|
||||
}
|
||||
let mut chars = key.chars();
|
||||
let first_ok = chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '.' || c == '_');
|
||||
// `[A-Za-z._]+[A-Za-z0-9._+-]*`
|
||||
first_ok && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'))
|
||||
}
|
||||
fn string_of(t: &horizon_world::nbt::JavaString) -> String {
|
||||
t.to_string_lossy()
|
||||
}
|
||||
|
||||
/// `Tag.toString` (StringTagVisitor).
|
||||
pub fn to_snbt(tag: &Tag) -> String {
|
||||
let mut out = String::new();
|
||||
visit(tag, &mut out);
|
||||
out
|
||||
}
|
||||
fn visit(tag: &Tag, out: &mut String) {
|
||||
match tag {
|
||||
Tag::End => out.push_str("END"),
|
||||
Tag::Byte(v) => out.push_str(&format!("{v}b")),
|
||||
Tag::Short(v) => out.push_str(&format!("{v}s")),
|
||||
Tag::Int(v) => out.push_str(&v.to_string()),
|
||||
Tag::Long(v) => out.push_str(&format!("{v}L")),
|
||||
Tag::Float(v) => {
|
||||
out.push_str(&java_float(f32::from_bits(*v)));
|
||||
out.push('f');
|
||||
}
|
||||
Tag::Double(v) => {
|
||||
out.push_str(&java_double(f64::from_bits(*v)));
|
||||
out.push('d');
|
||||
}
|
||||
Tag::String(s) => out.push_str("e_and_escape(&string_of(s))),
|
||||
Tag::ByteArray(a) => {
|
||||
out.push_str("[B;");
|
||||
out.push_str(
|
||||
&a.iter()
|
||||
.map(|v| format!("{}B", *v as i8))
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
out.push(']');
|
||||
}
|
||||
Tag::IntArray(a) => {
|
||||
out.push_str("[I;");
|
||||
out.push_str(&a.iter().map(i32::to_string).collect::<Vec<_>>().join(","));
|
||||
out.push(']');
|
||||
}
|
||||
Tag::LongArray(a) => {
|
||||
out.push_str("[L;");
|
||||
out.push_str(
|
||||
&a.iter()
|
||||
.map(|v| format!("{v}L"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
out.push(']');
|
||||
}
|
||||
Tag::List(l) => {
|
||||
out.push('[');
|
||||
for (i, t) in l.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
visit(t, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
Tag::Compound(c) => {
|
||||
out.push('{');
|
||||
let mut entries: Vec<(String, &Tag)> =
|
||||
c.iter().map(|(k, v)| (string_of(k), v)).collect();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
for (i, (k, v)) in entries.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
if unquoted_key(k) {
|
||||
out.push_str(k);
|
||||
} else {
|
||||
out.push_str("e_and_escape(k));
|
||||
}
|
||||
out.push(':');
|
||||
visit(v, out);
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the coloured form -----------------------------------------------------
|
||||
|
||||
struct Pretty {
|
||||
indentation: String,
|
||||
result: Text,
|
||||
indent_depth: usize,
|
||||
depth: usize,
|
||||
}
|
||||
fn is_numeric(t: &Tag) -> bool {
|
||||
matches!(
|
||||
t,
|
||||
Tag::Byte(_) | Tag::Short(_) | Tag::Int(_) | Tag::Long(_) | Tag::Float(_) | Tag::Double(_)
|
||||
)
|
||||
}
|
||||
impl Pretty {
|
||||
fn lit(&mut self, s: &str, color: Option<u32>) {
|
||||
let t = match color {
|
||||
Some(c) => Text::styled(s, Style::color(c)),
|
||||
None => Text::literal(s),
|
||||
};
|
||||
self.result.push(t);
|
||||
}
|
||||
fn number(&mut self, s: &str, suffix: &str) {
|
||||
self.lit(s, Some(text::GOLD));
|
||||
if !suffix.is_empty() {
|
||||
self.lit(suffix, Some(text::RED));
|
||||
}
|
||||
}
|
||||
fn quoted(&mut self, input: &str, color: u32) {
|
||||
let q = quote_and_escape(input);
|
||||
let (open, inner) = (&q[..1], &q[1..q.len() - 1]);
|
||||
self.lit(open, None);
|
||||
self.lit(inner, Some(color));
|
||||
self.lit(open, None);
|
||||
}
|
||||
fn array<T: std::fmt::Display>(&mut self, prefix: &str, items: &[T], suffix: &str) {
|
||||
self.lit("[", None);
|
||||
self.lit(prefix, Some(text::RED));
|
||||
self.lit(";", None);
|
||||
for (i, v) in items.iter().enumerate().take(128) {
|
||||
self.lit(" ", None);
|
||||
self.number(&v.to_string(), suffix);
|
||||
if i != items.len() - 1 {
|
||||
self.lit(",", None);
|
||||
}
|
||||
}
|
||||
if items.len() > 128 {
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
}
|
||||
self.lit("]", None);
|
||||
}
|
||||
fn sub(&mut self, tag: &Tag, indent: bool) {
|
||||
if indent {
|
||||
self.indent_depth += 1;
|
||||
}
|
||||
self.depth += 1;
|
||||
self.visit(tag);
|
||||
if indent {
|
||||
self.indent_depth -= 1;
|
||||
}
|
||||
self.depth -= 1;
|
||||
}
|
||||
fn visit(&mut self, tag: &Tag) {
|
||||
match tag {
|
||||
Tag::End => {}
|
||||
Tag::Byte(v) => self.number(&v.to_string(), "b"),
|
||||
Tag::Short(v) => self.number(&v.to_string(), "s"),
|
||||
Tag::Int(v) => self.number(&v.to_string(), ""),
|
||||
Tag::Long(v) => self.number(&v.to_string(), "L"),
|
||||
Tag::Float(v) => self.number(&java_float(f32::from_bits(*v)), "f"),
|
||||
Tag::Double(v) => self.number(&java_double(f64::from_bits(*v)), "d"),
|
||||
Tag::String(s) => self.quoted(&string_of(s), text::GREEN),
|
||||
Tag::ByteArray(a) => {
|
||||
let v: Vec<i8> = a.iter().map(|b| *b as i8).collect();
|
||||
self.array("B", &v, "b");
|
||||
}
|
||||
Tag::IntArray(a) => self.array("I", a, ""),
|
||||
Tag::LongArray(a) => self.array("L", a, "L"),
|
||||
Tag::List(l) => self.list(l),
|
||||
Tag::Compound(c) => self.compound(c),
|
||||
}
|
||||
}
|
||||
fn list(&mut self, l: &[Tag]) {
|
||||
if l.is_empty() {
|
||||
self.lit("[", None);
|
||||
self.lit("]", None);
|
||||
} else if self.depth >= 64 {
|
||||
self.lit("[", None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
self.lit("]", None);
|
||||
} else if l.len() >= 8 || l.iter().all(is_numeric) {
|
||||
self.lit("[", None);
|
||||
for (i, t) in l.iter().enumerate() {
|
||||
if i != 0 {
|
||||
self.lit(",", None);
|
||||
self.lit(" ", None);
|
||||
}
|
||||
self.sub(t, false);
|
||||
}
|
||||
self.lit("]", None);
|
||||
} else {
|
||||
self.lit("[", None);
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
}
|
||||
let entry = self.indentation.repeat(self.indent_depth + 1);
|
||||
let spacing = if self.indentation.is_empty() {
|
||||
" "
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
for (i, t) in l.iter().enumerate().take(128) {
|
||||
self.lit(&entry, None);
|
||||
self.sub(t, true);
|
||||
if i != l.len() - 1 {
|
||||
self.lit(",", None);
|
||||
self.lit(spacing, None);
|
||||
}
|
||||
}
|
||||
if l.len() > 128 {
|
||||
self.lit(&entry, None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
}
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
let close = self.indentation.repeat(self.indent_depth);
|
||||
self.lit(&close, None);
|
||||
}
|
||||
self.lit("]", None);
|
||||
}
|
||||
}
|
||||
fn compound(&mut self, c: &horizon_world::nbt::Compound) {
|
||||
if c.is_empty() {
|
||||
self.lit("{", None);
|
||||
self.lit("}", None);
|
||||
} else if self.depth >= 64 {
|
||||
self.lit("{", None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
self.lit("}", None);
|
||||
} else {
|
||||
self.lit("{", None);
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
}
|
||||
let entry = self.indentation.repeat(self.indent_depth + 1);
|
||||
let spacing = if self.indentation.is_empty() {
|
||||
" "
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
let n = c.len();
|
||||
for (i, (k, v)) in c.iter().enumerate() {
|
||||
self.lit(&entry, None);
|
||||
let key = string_of(k);
|
||||
if !key.is_empty()
|
||||
&& key
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '+' | '-'))
|
||||
{
|
||||
self.lit(&key, Some(text::AQUA));
|
||||
} else {
|
||||
self.quoted(&key, text::AQUA);
|
||||
}
|
||||
self.lit(":", None);
|
||||
self.lit(" ", None);
|
||||
self.sub(v, true);
|
||||
if i + 1 < n {
|
||||
self.lit(",", None);
|
||||
self.lit(spacing, None);
|
||||
}
|
||||
}
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
let close = self.indentation.repeat(self.indent_depth);
|
||||
self.lit(&close, None);
|
||||
}
|
||||
self.lit("}", None);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `NbtUtils.toPrettyComponent`: the coloured, unindented form.
|
||||
pub fn pretty(tag: &Tag) -> Text {
|
||||
pretty_indented(tag, "")
|
||||
}
|
||||
pub fn pretty_indented(tag: &Tag, indentation: &str) -> Text {
|
||||
let mut p = Pretty {
|
||||
indentation: indentation.to_owned(),
|
||||
result: Text::empty(),
|
||||
indent_depth: 0,
|
||||
depth: 0,
|
||||
};
|
||||
p.visit(tag);
|
||||
p.result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn rt(s: &str) -> String {
|
||||
to_snbt(&parse_snbt(s).unwrap().0)
|
||||
}
|
||||
#[test]
|
||||
fn compact_form_matches_vanilla() {
|
||||
assert_eq!(
|
||||
rt("{b:1b,a:\"x\",c:[1,2],d:1.5f,e:2d,f:3L,g:4s}"),
|
||||
"{a:\"x\",b:1b,c:[1,2],d:1.5f,e:2.0d,f:3L,g:4s}"
|
||||
);
|
||||
assert_eq!(rt("{\"a b\":1}"), "{\"a b\":1}");
|
||||
assert_eq!(rt("{true:1}"), "{\"true\":1}");
|
||||
assert_eq!(rt("[B;1b,2b]"), "[B;1B,2B]");
|
||||
assert_eq!(rt("[I;1,2]"), "[I;1,2]");
|
||||
assert_eq!(rt("[L;1L]"), "[L;1L]");
|
||||
assert_eq!(quote_and_escape("say \"hi\""), "'say \"hi\"'");
|
||||
assert_eq!(quote_and_escape("it's \"x\""), "\"it's \\\"x\\\"\"");
|
||||
assert_eq!(quote_and_escape("a\nb\\"), "\"a\\nb\\\\\"");
|
||||
}
|
||||
#[test]
|
||||
fn java_number_text() {
|
||||
assert_eq!(java_double(1.0), "1.0");
|
||||
assert_eq!(java_double(0.1), "0.1");
|
||||
assert_eq!(java_double(1.0e7), "1.0E7");
|
||||
assert_eq!(java_double(12345678.9), "1.23456789E7");
|
||||
assert_eq!(java_double(0.0001), "1.0E-4");
|
||||
assert_eq!(java_double(-3.5), "-3.5");
|
||||
assert_eq!(java_float(0.3), "0.3");
|
||||
assert_eq!(java_float(100.0), "100.0");
|
||||
assert_eq!(java_double(f64::NAN), "NaN");
|
||||
}
|
||||
#[test]
|
||||
fn pretty_form_is_coloured_without_changing_text() {
|
||||
let tag = parse_snbt("{Pos:[1.5d,2.0d],id:\"minecraft:pig\",n:3b}")
|
||||
.unwrap()
|
||||
.0;
|
||||
let t = pretty(&tag);
|
||||
assert_eq!(
|
||||
t.plain(),
|
||||
"{Pos: [1.5d, 2.0d], id: \"minecraft:pig\", n: 3b}"
|
||||
);
|
||||
// keys aqua, strings green, numbers gold.
|
||||
let colors: Vec<_> = t.spans.iter().filter_map(|s| s.style.color).collect();
|
||||
assert!(colors.contains(&text::AQUA));
|
||||
assert!(colors.contains(&text::GREEN));
|
||||
assert!(colors.contains(&text::GOLD));
|
||||
let long = parse_snbt("{l:[{a:1},{b:2}]}").unwrap().0;
|
||||
assert_eq!(pretty(&long).plain(), "{l: [{a: 1}, {b: 2}]}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user