Merge branches 'parity/tooling', 'parity/score-subtitles' and 'parity/block-followups' into parity-base
This commit is contained in:
@@ -14,7 +14,7 @@ Horizon is a Rust rewrite of Minecraft Java **26.3** targeting one-to-one vanill
|
||||
- shields, maps, books, fireworks, beacons, advancements and statistics;
|
||||
- Anvil saves.
|
||||
|
||||
Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, the loom, crafter and recipe book, scoreboards, subtitles, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md).
|
||||
Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, the loom, crafter and recipe book, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md).
|
||||
|
||||
### Java parity: 84%
|
||||
|
||||
@@ -42,7 +42,7 @@ round-trip harness has not been rerun.
|
||||
| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences |
|
||||
| Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering |
|
||||
| Audio | 0.75 | Sound engine, music and ambience not compared with vanilla |
|
||||
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems |
|
||||
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers and block entity removal (containers spill, 4,000 cases) match vanilla; the copper golem's chest-sorting AI is not compared |
|
||||
|
||||
### Next steps
|
||||
|
||||
@@ -50,7 +50,7 @@ round-trip harness has not been rerun.
|
||||
2. Draw every item through the item model pipeline, and add the resource pack screen.
|
||||
3. An audio harness: sound engine attenuation, weighted sound events, music and ambience.
|
||||
4. A mob AI harness, and an oracle for drowned, villagers, traders and the wither.
|
||||
5. The missing commands, containers spilling when replaced, copper golems, the tab list and world border rendering.
|
||||
5. The missing commands, the copper golem's brain (chest sorting) in the mob AI harness, the tab list and world border rendering.
|
||||
6. Test LAN hosting with a vanilla client, and add a dedicated server mode.
|
||||
|
||||
```sh
|
||||
|
||||
@@ -23,5 +23,9 @@ cpal = "0.16"
|
||||
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
|
||||
miniz_oxide = "0.8"
|
||||
|
||||
[features]
|
||||
# Records the call sites of mob random draws (`mob_ai_probe` traces).
|
||||
rng-trace = ["horizon-core/rng-trace"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Headless transport for the block-entity animation parity gate: replays each
|
||||
//! scripted case (block, neighbourhood, entities, block events, game times)
|
||||
//! through `horizon_client::block_entity_anim` and prints the same lines as
|
||||
//! `VanillaBlockEntityAnimOracle`: the block entity's fields, the level calls
|
||||
//! its tick made and the render state the renderer derives from `BlockAnim`.
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
block_entity_anim::{
|
||||
Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS,
|
||||
PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index,
|
||||
},
|
||||
block_entity_render::BlockEntityRenderer,
|
||||
blocks::{BlockFacts, Fluid},
|
||||
items::Items,
|
||||
};
|
||||
use horizon_core::random::LegacyRandom;
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::Write as _,
|
||||
fs,
|
||||
io::{BufWriter, Write},
|
||||
path::PathBuf,
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn f(v: f32) -> String {
|
||||
format!("{:08x}", v.to_bits())
|
||||
}
|
||||
fn d(v: f64) -> String {
|
||||
format!("{:016x}", v.to_bits())
|
||||
}
|
||||
fn bx(b: [f64; 6]) -> String {
|
||||
b.map(d).join(" ")
|
||||
}
|
||||
|
||||
fn find_state(registry: &BlockRegistry, spec: &str) -> Option<u32> {
|
||||
let (name, props) = match spec.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (spec, ""),
|
||||
};
|
||||
let wanted: Vec<(&str, &str)> = props
|
||||
.split(',')
|
||||
.filter(|p| !p.is_empty())
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.collect();
|
||||
let default = registry.state(registry.default_state(name)?)?.clone();
|
||||
(0..registry.len() as u32).find(|&id| {
|
||||
registry.state(BlockStateId(id)).is_some_and(|s| {
|
||||
s.name == name
|
||||
&& s.properties.iter().all(|(k, v)| {
|
||||
wanted
|
||||
.iter()
|
||||
.find(|(wk, _)| wk == k)
|
||||
.map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn prop<'a>(spec: &'a str, key: &str) -> Option<&'a str> {
|
||||
let props = spec.split_once('[')?.1.trim_end_matches(']');
|
||||
props
|
||||
.split(',')
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
fn offset(key: &str) -> [i32; 3] {
|
||||
let mut it = key.split(',').map(|v| v.parse::<i32>().unwrap_or(0));
|
||||
[
|
||||
it.next().unwrap_or(0),
|
||||
it.next().unwrap_or(0),
|
||||
it.next().unwrap_or(0),
|
||||
]
|
||||
}
|
||||
|
||||
fn mob(e: &Value) -> BellEntity {
|
||||
let p = |i: usize| e["pos"][i].as_f64().unwrap_or(0.0);
|
||||
BellEntity {
|
||||
position: [p(0), p(1), p(2)],
|
||||
alive: e["alive"].as_bool().unwrap_or(true) && !e["removed"].as_bool().unwrap_or(false),
|
||||
raider: e["raider"].as_bool().unwrap_or(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn lid_text(l: Option<&ChestLid>) -> String {
|
||||
l.map_or("-".to_owned(), |l| {
|
||||
format!("{} {} {}", l.should_be_open, f(l.openness), f(l.o_openness))
|
||||
})
|
||||
}
|
||||
|
||||
/// The case's players: feet positions and whether each is a spectator.
|
||||
fn players(v: &Value) -> Vec<([f64; 3], bool)> {
|
||||
v.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|p| {
|
||||
let c = |i: usize| p["pos"][i].as_f64().unwrap_or(0.0);
|
||||
(
|
||||
[c(0), c(1), c(2)],
|
||||
p["spectator"].as_bool().unwrap_or(false),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn status(s: ShulkerStatus) -> &'static str {
|
||||
match s {
|
||||
ShulkerStatus::Closed => "CLOSED",
|
||||
ShulkerStatus::Opening => "OPENING",
|
||||
ShulkerStatus::Opened => "OPENED",
|
||||
ShulkerStatus::Closing => "CLOSING",
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
let assets = Assets::load(root)?;
|
||||
let registry = assets.registry;
|
||||
let facts = BlockFacts::load(root, registry)?;
|
||||
let renderer = BlockEntityRenderer::load(root, registry)?;
|
||||
let tags = Items::tags_only(root)?;
|
||||
let frames = tags
|
||||
.block_tags
|
||||
.get("minecraft:conduit_effect_block")
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
writeln!(out, "case {}", case["name"].as_str().unwrap_or_default())?;
|
||||
let block = case["block"].as_str().unwrap_or_default().to_owned();
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
|
||||
let pos = [
|
||||
int(&case["pos"][0]),
|
||||
int(&case["pos"][1]),
|
||||
int(&case["pos"][2]),
|
||||
];
|
||||
// The neighbourhood as block states (conduits).
|
||||
let mut blocks: HashMap<[i32; 3], String> = HashMap::new();
|
||||
blocks.insert(pos, block.clone());
|
||||
let place = |blocks: &mut HashMap<[i32; 3], String>, set: &Value| {
|
||||
for (k, v) in set.as_object().into_iter().flatten() {
|
||||
let o = offset(k);
|
||||
blocks.insert(
|
||||
[pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]],
|
||||
v.as_str().unwrap_or_default().to_owned(),
|
||||
);
|
||||
}
|
||||
};
|
||||
place(&mut blocks, &case["world"]);
|
||||
let entities: Vec<BellEntity> = case["entities"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(mob)
|
||||
.collect();
|
||||
let target = case.get("target").map(|t| {
|
||||
let e = mob(t);
|
||||
ConduitTarget {
|
||||
position: e.position,
|
||||
eye_y: e.position[1] + f64::from(t["eye"].as_f64().unwrap_or(0.0) as f32),
|
||||
width: t["width"].as_f64().unwrap_or(0.0) as f32,
|
||||
height: t["height"].as_f64().unwrap_or(0.0) as f32,
|
||||
}
|
||||
});
|
||||
let mut random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0));
|
||||
let name = block.split('[').next().unwrap_or_default().to_owned();
|
||||
let mut anims = BlockEntityAnims::default();
|
||||
let partner = case["partner"].as_str().map(|k| {
|
||||
let o = offset(k);
|
||||
[pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]]
|
||||
});
|
||||
let mut gamers = players(&case["players"]);
|
||||
if name == "minecraft:enchanting_table" {
|
||||
anims.book_random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0));
|
||||
}
|
||||
let facing = prop(&block, "facing")
|
||||
.and_then(direction_index)
|
||||
.unwrap_or(1);
|
||||
let mut text = String::new();
|
||||
for step in case["steps"].as_array().into_iter().flatten() {
|
||||
let time = step["time"].as_i64().unwrap_or(0);
|
||||
let partial = step["partial"].as_f64().unwrap_or(0.0) as f32;
|
||||
let mut log = String::new();
|
||||
place(&mut blocks, &step["set"]);
|
||||
let event = step["event"].as_array().map(|e| (int(&e[0]), int(&e[1])));
|
||||
text.clear();
|
||||
if step.get("players").is_some() {
|
||||
gamers = players(&step["players"]);
|
||||
}
|
||||
if name.ends_with("chest") {
|
||||
let lid = anims.chests.entry(pos).or_default();
|
||||
if let Some((a, b)) = event {
|
||||
let handled = lid.trigger_event(a, b);
|
||||
let _ = write!(log, " event {handled}");
|
||||
}
|
||||
if let Some(other) = partner {
|
||||
let lid = anims.chests.entry(other).or_default();
|
||||
if let Some(e) = step["partnerEvent"].as_array() {
|
||||
let handled = lid.trigger_event(int(&e[0]), int(&e[1]));
|
||||
let _ = write!(log, " partner event {handled}");
|
||||
}
|
||||
}
|
||||
// lidAnimateTick: this chest, then the other half.
|
||||
if let Some(l) = anims.chests.get_mut(&pos) {
|
||||
l.tick();
|
||||
}
|
||||
if let Some(l) = partner.and_then(|p| anims.chests.get_mut(&p)) {
|
||||
l.tick();
|
||||
}
|
||||
let state_at = |p: [i32; 3]| {
|
||||
find_state(
|
||||
registry,
|
||||
blocks.get(&p).map_or("minecraft:air", String::as_str),
|
||||
)
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (open, _) = renderer
|
||||
.chest_openness_of(pos, state_at(pos), &state_at, &|p| anims.lid(p, partial));
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} partner {} render {} {}",
|
||||
lid_text(anims.chests.get(&pos)),
|
||||
partner.map_or("none".to_owned(), |p| lid_text(anims.chests.get(&p))),
|
||||
f(open),
|
||||
f(chest_lid_x_rot(open))
|
||||
);
|
||||
} else if name == "minecraft:enchanting_table" {
|
||||
let feet: Vec<[f64; 3]> = gamers
|
||||
.iter()
|
||||
.filter(|(_, spectator)| !spectator)
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
let BlockEntityAnims {
|
||||
books, book_random, ..
|
||||
} = &mut anims;
|
||||
books.entry(pos).or_default().tick(pos, &feet, book_random);
|
||||
let b = anims.books[&pos];
|
||||
let r = anims
|
||||
.block_anim(pos, time, partial, Default::default())
|
||||
.book
|
||||
.render(partial);
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} {} {} {} {} {} {} {} {} render {} {} {} {} book {} {} {}",
|
||||
b.time,
|
||||
f(b.flip),
|
||||
f(b.o_flip),
|
||||
f(b.flip_t),
|
||||
f(b.flip_a),
|
||||
f(b.open),
|
||||
f(b.o_open),
|
||||
f(b.rot),
|
||||
f(b.o_rot),
|
||||
f(b.t_rot),
|
||||
f(r.flip),
|
||||
f(r.open),
|
||||
f(r.time),
|
||||
f(r.y_rot),
|
||||
f(r.openness),
|
||||
f(r.page_flip1),
|
||||
f(r.page_flip2)
|
||||
);
|
||||
} else if name.ends_with("shulker_box") {
|
||||
let s = anims.shulkers.entry(pos).or_insert_with(Shulker::default);
|
||||
if let Some((a, b)) = event {
|
||||
let handled = s.trigger_event(a, b);
|
||||
let _ = write!(log, " event {handled}");
|
||||
}
|
||||
let tick = s.tick(pos, facing);
|
||||
for _ in 0..tick.neighbor_updates {
|
||||
log.push_str(" neighbors");
|
||||
}
|
||||
if let Some(b) = tick.push {
|
||||
let _ = write!(log, " push {}", bx(b));
|
||||
}
|
||||
let (count, st) = (s.open_count, s.status);
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
// ShulkerBoxRenderer: getProgress(partial).
|
||||
let (progress, old) = a.shulker;
|
||||
let render = old + partial * (progress - old);
|
||||
let s = &anims.shulkers[&pos];
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} {} {} render {}",
|
||||
status(st),
|
||||
count,
|
||||
f(s.progress),
|
||||
f(s.progress_old),
|
||||
f(render)
|
||||
);
|
||||
} else if name == "minecraft:bell" {
|
||||
let b = anims.bells.entry(pos).or_insert_with(Bell::default);
|
||||
if let Some((e0, e1)) = event {
|
||||
let handled = b.trigger_event(e0, e1, time, || {
|
||||
let inflated = [
|
||||
f64::from(pos[0]) - 48.0,
|
||||
f64::from(pos[1]) - 48.0,
|
||||
f64::from(pos[2]) - 48.0,
|
||||
f64::from(pos[0]) + 1.0 + 48.0,
|
||||
f64::from(pos[1]) + 1.0 + 48.0,
|
||||
f64::from(pos[2]) + 1.0 + 48.0,
|
||||
];
|
||||
let _ = write!(log, " gather {}", bx(inflated));
|
||||
(0..entities.len() as u64)
|
||||
.filter(|&i| {
|
||||
let p = entities[i as usize].position;
|
||||
(0..3).all(|a| p[a] >= inflated[a] && p[a] < inflated[a + 3])
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let _ = write!(log, " event {handled}");
|
||||
}
|
||||
if !step["noTick"].as_bool().unwrap_or(false) {
|
||||
let tick = b.tick(pos, |h| entities.get(h as usize).copied());
|
||||
if tick.resonate {
|
||||
log.push_str(" sound minecraft:block.bell.resonate");
|
||||
}
|
||||
if let Some((particles, _)) = tick.ended {
|
||||
for (p, color) in particles {
|
||||
let _ = write!(
|
||||
log,
|
||||
" particle minecraft:entity_effect {color} {} {} {} {} {} {}",
|
||||
d(p[0]),
|
||||
d(p[1]),
|
||||
d(p[2]),
|
||||
d(0.0),
|
||||
d(0.0),
|
||||
d(0.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let b = &anims.bells[&pos];
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
let dir = |d: Option<&str>| d.map_or("null".to_owned(), str::to_owned);
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} {} {} {} {} render {} {}",
|
||||
b.ticks,
|
||||
b.shaking,
|
||||
dir(b.click_direction.map(|d| DIRECTIONS[usize::from(d)])),
|
||||
b.resonating,
|
||||
b.resonation_ticks,
|
||||
b.last_ring_timestamp,
|
||||
f(a.bell_ticks as f32 + partial),
|
||||
dir(a.bell_shake)
|
||||
);
|
||||
} else if name == "minecraft:conduit" {
|
||||
let c = anims.conduits.entry(pos).or_insert_with(Conduit::default);
|
||||
let state_of = |p: [i32; 3]| -> Option<u32> {
|
||||
find_state(
|
||||
registry,
|
||||
blocks.get(&p).map_or("minecraft:air", String::as_str),
|
||||
)
|
||||
};
|
||||
let is_water = |p: [i32; 3]| {
|
||||
state_of(p).is_some_and(|s| facts.get(BlockStateId(s)).fluid == Fluid::Water)
|
||||
};
|
||||
let is_frame = |p: [i32; 3]| {
|
||||
let spec = blocks.get(&p).map_or("minecraft:air", String::as_str);
|
||||
frames.contains(spec.split('[').next().unwrap_or_default())
|
||||
};
|
||||
let particles = c.client_tick(pos, time, is_water, is_frame, target, &mut random);
|
||||
for (p, v) in particles {
|
||||
let _ = write!(
|
||||
log,
|
||||
" particle minecraft:nautilus {} {} {} {} {} {}",
|
||||
d(p[0]),
|
||||
d(p[1]),
|
||||
d(p[2]),
|
||||
d(v[0]),
|
||||
d(v[1]),
|
||||
d(v[2])
|
||||
);
|
||||
}
|
||||
let c = &anims.conduits[&pos];
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
// ConduitRenderer.extractRenderState as block_entity_render derives it.
|
||||
let (ticks, active, hunting, raw) = a.conduit;
|
||||
let rotation = (raw + if active { partial } else { 0.0 }) * -0.0375;
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} {} {} {} render {} {} {} {} {}",
|
||||
c.tick_count,
|
||||
c.is_active,
|
||||
c.is_hunting,
|
||||
f(c.active_rotation),
|
||||
c.effect_blocks.len(),
|
||||
active,
|
||||
f(rotation),
|
||||
f(ticks as f32 + partial),
|
||||
ticks / 66 % 3,
|
||||
hunting
|
||||
);
|
||||
} else if name.ends_with("_head") || name.ends_with("_skull") {
|
||||
let now = step["state"].as_str().unwrap_or(&block);
|
||||
let s = anims.skulls.entry(pos).or_insert_with(Skull::default);
|
||||
s.tick(prop(now, "powered") == Some("true"));
|
||||
let s = anims.skulls[&pos];
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
// block_entity_render: count + partial while animating.
|
||||
let (animating, count) = a.skull;
|
||||
let render = count as f32 + if animating { partial } else { 0.0 };
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} render {}",
|
||||
s.animating,
|
||||
s.tick_count,
|
||||
f(render)
|
||||
);
|
||||
} else if name == "minecraft:decorated_pot" {
|
||||
let w = anims.pots.entry(pos).or_insert_with(PotWobble::default);
|
||||
if let Some((e0, e1)) = event {
|
||||
let handled = w.trigger_event(e0, e1, time);
|
||||
let _ = write!(log, " event {handled}");
|
||||
}
|
||||
let w = anims.pots[&pos];
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
let (style, progress) = match a.wobble {
|
||||
Some((true, p)) => ("POSITIVE", p),
|
||||
Some((false, p)) => ("null", p),
|
||||
None => ("null", 0.0),
|
||||
};
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} render {} {}",
|
||||
w.started_at,
|
||||
match w.style {
|
||||
Some(WobbleStyle::Positive) => "POSITIVE",
|
||||
Some(WobbleStyle::Negative) => "NEGATIVE",
|
||||
None => "null",
|
||||
},
|
||||
f(progress),
|
||||
style
|
||||
);
|
||||
} else {
|
||||
text = format!("unsupported {block}");
|
||||
}
|
||||
writeln!(out, "{text} |{log}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,7 +7,10 @@ use glam::{DVec3, Mat4, Quat, Vec3};
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
banner::{self, Banners},
|
||||
block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall},
|
||||
block_entity_anim::EnchantingBook,
|
||||
block_entity_render::{
|
||||
BlockAnim, BlockEntityRenderer, END_GATEWAY_LAYER, END_PORTAL_LAYER, Scene, TextCall,
|
||||
},
|
||||
chunk::{Chunk, Light},
|
||||
hud::{HudAtlas, Rect},
|
||||
signs::{DYE_TEXT, SignData, SignText},
|
||||
@@ -113,7 +116,7 @@ fn main() -> Result<()> {
|
||||
};
|
||||
let assets = Assets::load(root)?;
|
||||
let registry = assets.registry;
|
||||
let mut renderer = BlockEntityRenderer::load(root, registry)?;
|
||||
let renderer = BlockEntityRenderer::load(root, registry)?;
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let banners = Banners::load(root);
|
||||
let (sprites, names, grid) = fake_sprites(textures)?;
|
||||
@@ -196,13 +199,41 @@ fn main() -> Result<()> {
|
||||
world.chunks.insert((cx, cz), Arc::new(chunk));
|
||||
}
|
||||
}
|
||||
if let Some(book) = case.get("book") {
|
||||
renderer.set_book(
|
||||
pos,
|
||||
int(&book["time"]),
|
||||
["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])),
|
||||
);
|
||||
// Neighbour blocks the case sets (End gateway faces).
|
||||
for (direction, spec) in case["neighbours"].as_object().into_iter().flatten() {
|
||||
let d = match direction.as_str() {
|
||||
"down" => [0, -1, 0],
|
||||
"up" => [0, 1, 0],
|
||||
"north" => [0, 0, -1],
|
||||
"south" => [0, 0, 1],
|
||||
"west" => [-1, 0, 0],
|
||||
_ => [1, 0, 0],
|
||||
};
|
||||
let neighbour = find_state(registry, spec.as_str().unwrap_or_default())
|
||||
.ok_or("unknown neighbour state")?;
|
||||
world.set(
|
||||
pos[0] + d[0],
|
||||
pos[1] + d[1],
|
||||
pos[2] + d[2],
|
||||
BlockStateId(neighbour),
|
||||
)?;
|
||||
}
|
||||
let book = case
|
||||
.get("book")
|
||||
.map_or_else(EnchantingBook::default, |book| {
|
||||
let [flip, o_flip, open, o_open, rot, o_rot] =
|
||||
["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k]));
|
||||
EnchantingBook {
|
||||
time: int(&book["time"]),
|
||||
flip,
|
||||
o_flip,
|
||||
open,
|
||||
o_open,
|
||||
rot,
|
||||
o_rot,
|
||||
..EnchantingBook::default()
|
||||
}
|
||||
});
|
||||
let sign = case.get("sign").map(|s| {
|
||||
let mut data = SignData {
|
||||
hanging: block.contains("hanging"),
|
||||
@@ -246,6 +277,16 @@ fn main() -> Result<()> {
|
||||
wobble: case["wobble"]
|
||||
.as_array()
|
||||
.map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))),
|
||||
book,
|
||||
gateway: (
|
||||
case["gateway"]["age"].as_i64().unwrap_or(0),
|
||||
int(&case["gateway"]["cooldown"]),
|
||||
),
|
||||
};
|
||||
// The case's level height (minimum y, height): the End's by default.
|
||||
let max_y = match case["level"].as_array() {
|
||||
Some(l) => int(&l[0]) + int(&l[1]) - 1,
|
||||
None => 255,
|
||||
};
|
||||
let open = float(&case["open"]);
|
||||
let near = case["sign"]["near"].as_bool().unwrap_or(false);
|
||||
@@ -279,7 +320,8 @@ fn main() -> Result<()> {
|
||||
anim: &|_| anim.clone(),
|
||||
texts: Some(&texts),
|
||||
partial: float(&case["partial"]),
|
||||
game_time: 0,
|
||||
game_time: case["gameTime"].as_i64().unwrap_or(0),
|
||||
max_y,
|
||||
world: &world,
|
||||
sprites: &sprites,
|
||||
nether: false,
|
||||
@@ -293,6 +335,26 @@ fn main() -> Result<()> {
|
||||
let quads: Vec<Value> = verts
|
||||
.chunks(4)
|
||||
.map(|q| {
|
||||
// Custom geometry: the End portal shader's position-only cube (its
|
||||
// render type samples end_sky first) and End gateway beams.
|
||||
if q[0].layer == END_PORTAL_LAYER || q[0].layer == END_GATEWAY_LAYER {
|
||||
let v: Vec<Value> = q
|
||||
.iter()
|
||||
.map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]]))
|
||||
.collect();
|
||||
return json!({"texture": "environment/end_sky", "v": v, "color": q[0].color,
|
||||
"light": q[0].light, "custom": true});
|
||||
}
|
||||
if q[0].layer == 6 {
|
||||
let texture = "entity/end_portal/end_gateway_beam";
|
||||
let u0 = sprites.get(texture).map_or(0.0, |r| r.u0);
|
||||
let v: Vec<Value> = q
|
||||
.iter()
|
||||
.map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0] - u0, v.uv[1]]))
|
||||
.collect();
|
||||
return json!({"texture": texture, "v": v, "color": q[0].color,
|
||||
"light": q[0].light, "custom": true});
|
||||
}
|
||||
let (cu, cv) = ((q[0].uv[0] / 2.0).floor(), (q[0].uv[1] / 2.0).floor());
|
||||
let texture = names
|
||||
.get(cu as usize + cv as usize * grid)
|
||||
|
||||
@@ -61,6 +61,7 @@ fn parser_id(ty: &ArgType) -> String {
|
||||
_ => "minecraft:template_rotation".into(),
|
||||
},
|
||||
ArgType::HexColor => "minecraft:hex_color".into(),
|
||||
ArgType::ResourceSelector(_) => "minecraft:resource_selector".into(),
|
||||
ArgType::Uuid => "minecraft:uuid".into(),
|
||||
ArgType::GameProfile => "minecraft:game_profile".into(),
|
||||
ArgType::Style => "minecraft:style".into(),
|
||||
@@ -120,7 +121,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value {
|
||||
}
|
||||
children.insert(child.name().to_owned(), v);
|
||||
}
|
||||
let mut v = json!({"children": children});
|
||||
let order: Vec<&str> = n.children.iter().map(|&c| d.nodes[c].name()).collect();
|
||||
let mut v = json!({"children": children, "order": order});
|
||||
if n.command.is_some() {
|
||||
v["executable"] = json!(true);
|
||||
}
|
||||
|
||||
@@ -370,6 +370,22 @@ fn main() -> horizon_client::Result<()> {
|
||||
},
|
||||
&animations,
|
||||
),
|
||||
Species::CopperGolem => {
|
||||
// CopperGolemRenderState's animation states, in the golem's slots.
|
||||
for (slot, key) in [
|
||||
"idleAnimationState",
|
||||
"interactionGetItem",
|
||||
"interactionGetNoItem",
|
||||
"interactionDropItem",
|
||||
"interactionDropNoItem",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
mob.anim.states[slot] = started(key);
|
||||
}
|
||||
horizon_client::mobs::copper_golem::anim(&mob, s, p, &animations);
|
||||
}
|
||||
Species::Rabbit => b_anim::rabbit(
|
||||
p,
|
||||
s,
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
//! Headless transport for the HUD parity gate: replays each player state
|
||||
//! through `horizon_client::hud_layout` (crosshair, hotbar, health, mount
|
||||
//! hearts, experience bar and level) and writes the draw calls in vanilla's
|
||||
//! GuiGraphicsExtractor terms.
|
||||
//! Headless transport for the HUD parity gate: replays each case through
|
||||
//! `horizon_client::hud_layout` and writes the draw calls in vanilla's
|
||||
//! GuiGraphicsExtractor terms. Case kinds: `decorations` (crosshair,
|
||||
//! hotbar, health, mount hearts, experience bar and level) and the
|
||||
//! overlays handled in `kinds`.
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
hud::{HudAtlas, HudBatch},
|
||||
hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs},
|
||||
hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs, IDENTITY, Pose},
|
||||
lang,
|
||||
text::Text,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
@@ -14,6 +17,8 @@ use std::{
|
||||
path::PathBuf,
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
#[path = "hud_fixture/kinds.rs"]
|
||||
mod kinds;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
@@ -21,123 +26,245 @@ fn main() -> Result<()> {
|
||||
return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
lang::set(lang::Language::load(&[root], lang::DEFAULT));
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32;
|
||||
let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32;
|
||||
let (w, h) = (int("width", 0), int("height", 0));
|
||||
let mode = c["gameMode"].as_str().unwrap_or("survival");
|
||||
let survival = mode == "survival" || mode == "adventure";
|
||||
let indicator = c["attackIndicator"].as_str().unwrap_or("OFF");
|
||||
let partial = float("partial", 0.0);
|
||||
let effects: Vec<&str> = c["effects"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
let has = |e: &str| effects.contains(&e);
|
||||
let mut draws = Vec::new();
|
||||
// Spectators only see it over a spectatable target (none here).
|
||||
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
|
||||
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
|
||||
draws.extend(hud_layout::crosshair(w, h, attack, false));
|
||||
}
|
||||
if mode != "spectator" {
|
||||
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
|
||||
let slots: [Option<f32>; 9] = std::array::from_fn(|i| pop(&c["slots"][i]));
|
||||
let inputs = HotbarInputs {
|
||||
selected: int("selected", 0),
|
||||
right_handed: c["rightHanded"].as_bool().unwrap_or(true),
|
||||
offhand: !c["offhand"].is_null(),
|
||||
slots,
|
||||
offhand_pop: pop(&c["offhand"]).unwrap_or(0.0),
|
||||
attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)),
|
||||
};
|
||||
draws.extend(hud_layout::hotbar(w, h, &inputs));
|
||||
}
|
||||
let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() {
|
||||
hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0))
|
||||
} else {
|
||||
0
|
||||
// State the case reads back besides the draws (e.g. `scopeScale`).
|
||||
let mut state = serde_json::Map::new();
|
||||
let draws = match c["kind"].as_str().unwrap_or("decorations") {
|
||||
"decorations" => decorations(&c, &atlas),
|
||||
kind => kinds::run(kind, &c, &atlas, &mut state),
|
||||
};
|
||||
if survival {
|
||||
let millis = 1_000_000_000i64;
|
||||
let mut hud = HealthHud {
|
||||
last_health: int("lastHealth", 0),
|
||||
display_health: int("displayHealth", 0),
|
||||
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
|
||||
health_blink_time: i64::from(int("healthBlinkTime", 0)),
|
||||
};
|
||||
let kind = if has("minecraft:poison") {
|
||||
HeartKind::Poisoned
|
||||
} else if has("minecraft:wither") {
|
||||
HeartKind::Withered
|
||||
} else if c["frozen"].as_bool().unwrap_or(false) {
|
||||
HeartKind::Frozen
|
||||
} else {
|
||||
HeartKind::Normal
|
||||
};
|
||||
let inputs = HealthInputs {
|
||||
tick: int("tick", 0),
|
||||
millis,
|
||||
health: float("health", 20.0),
|
||||
max_health: float("maxHealth", 20.0),
|
||||
absorption: float("absorption", 0.0),
|
||||
armor: int("armor", 0),
|
||||
food: int("food", 20),
|
||||
saturation: float("saturation", 5.0),
|
||||
kind,
|
||||
regeneration: has("minecraft:regeneration"),
|
||||
hunger: has("minecraft:hunger"),
|
||||
hardcore: c["hardcore"].as_bool().unwrap_or(false),
|
||||
damage_cooldown: int("damageCooldown", 0) > 0,
|
||||
air: int("air", 300),
|
||||
max_air: int("maxAir", 300),
|
||||
under_water: c["underWater"].as_bool().unwrap_or(false),
|
||||
vehicle_hearts,
|
||||
};
|
||||
draws.extend(hud.layout(&inputs, w, h));
|
||||
}
|
||||
if vehicle_hearts > 0 {
|
||||
draws.extend(hud_layout::vehicle_health(
|
||||
w,
|
||||
h,
|
||||
vehicle_hearts,
|
||||
float("vehicleHealth", 0.0),
|
||||
));
|
||||
}
|
||||
let width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
|
||||
let level = if survival { int("xpLevel", 0) } else { 0 };
|
||||
draws.extend(hud_layout::experience(
|
||||
w,
|
||||
h,
|
||||
float("xpProgress", 0.0),
|
||||
level,
|
||||
c["experienceBar"].as_bool().unwrap_or(false),
|
||||
&width,
|
||||
));
|
||||
let draws: Vec<Value> = draws
|
||||
.iter()
|
||||
.map(|d| match d {
|
||||
GuiDraw::Sprite { sprite, x, y, w, h, region } => {
|
||||
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region})
|
||||
}
|
||||
GuiDraw::Text { text, x, y, color, shadow } => {
|
||||
json!({"type": "text", "text": text, "x": x, "y": y, "color": *color as i32, "shadow": shadow})
|
||||
}
|
||||
GuiDraw::Item { slot, x, y, seed, scale, pivot } => {
|
||||
// translate(pivot) * scale * translate(-pivot) as a 3x2 matrix.
|
||||
let m = [scale[0], 0.0, 0.0, scale[1], pivot[0] - pivot[0] * scale[0], pivot[1] - pivot[1] * scale[1]];
|
||||
json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m})
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
writeln!(out, "{}", json!({ "draws": draws }))?;
|
||||
state.insert("draws".into(), json!(encode(&draws)));
|
||||
writeln!(out, "{}", Value::Object(state))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Style runs of styled text: `[text, rgb|null, bold, italic]` per run of
|
||||
/// equally styled characters, or none for plain text.
|
||||
fn runs(t: &Text) -> Option<Value> {
|
||||
let mut out: Vec<(String, Option<u32>, bool, bool)> = Vec::new();
|
||||
let mut styled = false;
|
||||
for (ch, s) in t.chars() {
|
||||
let key = (s.color, s.is_bold(), s.is_italic());
|
||||
styled |= key != (None, false, false);
|
||||
match out.last_mut() {
|
||||
Some(last) if (last.1, last.2, last.3) == key => last.0.push(ch),
|
||||
_ => out.push((ch.to_string(), key.0, key.1, key.2)),
|
||||
}
|
||||
}
|
||||
styled.then(|| {
|
||||
json!(
|
||||
out.into_iter()
|
||||
.map(|r| json!([r.0, r.1, r.2, r.3]))
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn encode(draws: &[GuiDraw]) -> Vec<Value> {
|
||||
let mut stack: Vec<Pose> = vec![IDENTITY];
|
||||
let mut out = Vec::new();
|
||||
for d in draws {
|
||||
let pose = *stack.last().unwrap();
|
||||
let mut v = match d {
|
||||
GuiDraw::Push(ops) => {
|
||||
let mut m = pose;
|
||||
for op in ops {
|
||||
hud_layout::pose_apply(&mut m, *op);
|
||||
}
|
||||
stack.push(m);
|
||||
continue;
|
||||
}
|
||||
GuiDraw::Pop => {
|
||||
stack.pop();
|
||||
continue;
|
||||
}
|
||||
GuiDraw::Sprite {
|
||||
sprite,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
region,
|
||||
color,
|
||||
} => {
|
||||
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32})
|
||||
}
|
||||
GuiDraw::AtlasSprite {
|
||||
sprite,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color,
|
||||
} => {
|
||||
json!({"type": "atlas", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "color": *color as i32})
|
||||
}
|
||||
GuiDraw::Blit {
|
||||
texture,
|
||||
blend,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
uv,
|
||||
src,
|
||||
tex,
|
||||
color,
|
||||
} => json!({
|
||||
"type": "blit", "texture": format!("textures/{texture}.png"), "pipeline": blend.pipeline(),
|
||||
"x": x, "y": y, "w": w, "h": h, "uv": uv, "src": src, "tex": tex, "color": *color as i32}),
|
||||
GuiDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => {
|
||||
json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": *color as i32})
|
||||
}
|
||||
GuiDraw::Text {
|
||||
text,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => {
|
||||
let mut v = json!({"type": "text", "text": text.plain(), "x": x, "y": y, "color": *color as i32, "shadow": shadow});
|
||||
if let Some(r) = runs(text) {
|
||||
v["runs"] = r;
|
||||
}
|
||||
v
|
||||
}
|
||||
GuiDraw::Item {
|
||||
slot,
|
||||
x,
|
||||
y,
|
||||
seed,
|
||||
scale,
|
||||
pivot,
|
||||
} => {
|
||||
// translate(pivot) * scale * translate(-pivot) as a 3x2 matrix.
|
||||
let m = [
|
||||
scale[0],
|
||||
0.0,
|
||||
0.0,
|
||||
scale[1],
|
||||
pivot[0] - pivot[0] * scale[0],
|
||||
pivot[1] - pivot[1] * scale[1],
|
||||
];
|
||||
out.push(json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m}));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if pose != IDENTITY {
|
||||
v["matrix"] = json!(pose);
|
||||
}
|
||||
out.push(v);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decorations(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32;
|
||||
let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32;
|
||||
let (w, h) = (int("width", 0), int("height", 0));
|
||||
let mode = c["gameMode"].as_str().unwrap_or("survival");
|
||||
let survival = mode == "survival" || mode == "adventure";
|
||||
let indicator = c["attackIndicator"].as_str().unwrap_or("OFF");
|
||||
let partial = float("partial", 0.0);
|
||||
let effects: Vec<&str> = c["effects"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
let has = |e: &str| effects.contains(&e);
|
||||
let mut draws = Vec::new();
|
||||
// Spectators only see it over a spectatable target (none here).
|
||||
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
|
||||
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
|
||||
draws.extend(hud_layout::crosshair(w, h, attack, false));
|
||||
}
|
||||
if mode != "spectator" {
|
||||
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
|
||||
let slots: [Option<f32>; 9] = std::array::from_fn(|i| pop(&c["slots"][i]));
|
||||
let inputs = HotbarInputs {
|
||||
selected: int("selected", 0),
|
||||
right_handed: c["rightHanded"].as_bool().unwrap_or(true),
|
||||
offhand: !c["offhand"].is_null(),
|
||||
slots,
|
||||
offhand_pop: pop(&c["offhand"]).unwrap_or(0.0),
|
||||
attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)),
|
||||
};
|
||||
draws.extend(hud_layout::hotbar(w, h, &inputs));
|
||||
}
|
||||
let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() {
|
||||
hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0))
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if survival {
|
||||
let millis = 1_000_000_000i64;
|
||||
let mut hud = HealthHud {
|
||||
last_health: int("lastHealth", 0),
|
||||
display_health: int("displayHealth", 0),
|
||||
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
|
||||
health_blink_time: i64::from(int("healthBlinkTime", 0)),
|
||||
};
|
||||
let kind = if has("minecraft:poison") {
|
||||
HeartKind::Poisoned
|
||||
} else if has("minecraft:wither") {
|
||||
HeartKind::Withered
|
||||
} else if c["frozen"].as_bool().unwrap_or(false) {
|
||||
HeartKind::Frozen
|
||||
} else {
|
||||
HeartKind::Normal
|
||||
};
|
||||
let inputs = HealthInputs {
|
||||
tick: int("tick", 0),
|
||||
millis,
|
||||
health: float("health", 20.0),
|
||||
max_health: float("maxHealth", 20.0),
|
||||
absorption: float("absorption", 0.0),
|
||||
armor: int("armor", 0),
|
||||
food: int("food", 20),
|
||||
saturation: float("saturation", 5.0),
|
||||
kind,
|
||||
regeneration: has("minecraft:regeneration"),
|
||||
hunger: has("minecraft:hunger"),
|
||||
hardcore: c["hardcore"].as_bool().unwrap_or(false),
|
||||
damage_cooldown: int("damageCooldown", 0) > 0,
|
||||
air: int("air", 300),
|
||||
max_air: int("maxAir", 300),
|
||||
under_water: c["underWater"].as_bool().unwrap_or(false),
|
||||
vehicle_hearts,
|
||||
};
|
||||
draws.extend(hud.layout(&inputs, w, h));
|
||||
}
|
||||
if vehicle_hearts > 0 {
|
||||
draws.extend(hud_layout::vehicle_health(
|
||||
w,
|
||||
h,
|
||||
vehicle_hearts,
|
||||
float("vehicleHealth", 0.0),
|
||||
));
|
||||
}
|
||||
let width = |s: &str| HudBatch::text_width(atlas, s) as i32;
|
||||
let level = if survival { int("xpLevel", 0) } else { 0 };
|
||||
draws.extend(hud_layout::experience(
|
||||
w,
|
||||
h,
|
||||
float("xpProgress", 0.0),
|
||||
level,
|
||||
c["experienceBar"].as_bool().unwrap_or(false),
|
||||
&width,
|
||||
));
|
||||
draws
|
||||
}
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//! The overlay case kinds of the HUD parity fixture.
|
||||
use horizon_client::{
|
||||
brewing,
|
||||
chat::{Chat, ChatOptions},
|
||||
component,
|
||||
hud::HudAtlas,
|
||||
hud_layout::{self, GuiDraw},
|
||||
hud_overlays::{
|
||||
self, BossBar, CameraOverlays, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight,
|
||||
},
|
||||
scoreboard::{NumberFormat, RenderType, Scoreboard},
|
||||
text::{self, Text},
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
fn int(c: &Value, k: &str, d: i64) -> i32 {
|
||||
c[k].as_i64().unwrap_or(d) as i32
|
||||
}
|
||||
fn float(c: &Value, k: &str, d: f64) -> f32 {
|
||||
c[k].as_f64().unwrap_or(d) as f32
|
||||
}
|
||||
/// A text component in its JSON form.
|
||||
fn comp(v: &Value) -> Text {
|
||||
component::to_text(v, &mut |s| Text::literal(s))
|
||||
}
|
||||
/// `Options.getBackgroundColor(0.0F)` from the case's text background options.
|
||||
fn background(c: &Value) -> u32 {
|
||||
hud_layout::background_color(
|
||||
c["chatOnly"].as_bool().unwrap_or(true),
|
||||
c["textOpacity"].as_f64().unwrap_or(0.5),
|
||||
0.0,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
kind: &str,
|
||||
c: &Value,
|
||||
atlas: &HudAtlas,
|
||||
state: &mut serde_json::Map<String, Value>,
|
||||
) -> Vec<GuiDraw> {
|
||||
let (w, h) = (int(c, "width", 0), int(c, "height", 0));
|
||||
match kind {
|
||||
"effects" => effects(c, w),
|
||||
"title" => title(c, w, h, atlas),
|
||||
"selected" => selected(c, w, h, atlas),
|
||||
"boss" => boss(c, w, h, atlas),
|
||||
"jump" => hud_overlays::jump_bar(w, h, int(c, "cooldown", 0), float(c, "jumpScale", 0.0)),
|
||||
"sidebar" => sidebar(c, w, h, atlas),
|
||||
"decor" => decor(c, atlas),
|
||||
"overlays" => overlays(c, w, h, state),
|
||||
"chat" => chat(c, h, atlas),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn effects(c: &Value, w: i32) -> Vec<GuiDraw> {
|
||||
let icons: Vec<EffectIcon> = c["active"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|e| {
|
||||
let id = e["id"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.trim_start_matches("minecraft:");
|
||||
let def = brewing::effect(id).expect("effect");
|
||||
EffectIcon {
|
||||
id: id.to_owned(),
|
||||
beneficial: def.category == brewing::Category::Beneficial,
|
||||
color: def.color as i32,
|
||||
ambient: e["ambient"].as_bool().unwrap_or(false),
|
||||
duration: e["duration"].as_i64().unwrap_or(0) as i32,
|
||||
show_icon: e["icon"].as_bool().unwrap_or(true),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
hud_overlays::effects(w, c["demo"].as_bool().unwrap_or(false), &icons)
|
||||
}
|
||||
|
||||
/// Replays `Hud.setTitle` / `setSubtitle` / `setTimes` / `clearTitles` /
|
||||
/// `resetTitleTimes` / `setOverlayMessage` and ticks, then extracts the
|
||||
/// action bar and the title.
|
||||
fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let mut t = Titles::default();
|
||||
for op in c["ops"].as_array().into_iter().flatten() {
|
||||
let n = |i: usize| op[i].as_i64().unwrap_or(0) as i32;
|
||||
match op[0].as_str().unwrap_or("") {
|
||||
"title" => t.set_title(comp(&op[1])),
|
||||
"subtitle" => t.set_subtitle(comp(&op[1])),
|
||||
"times" => t.set_times(n(1), n(2), n(3)),
|
||||
"clear" => t.clear(),
|
||||
"reset" => t.reset_times(),
|
||||
"overlay" => t.set_overlay(comp(&op[1]), op[2].as_bool().unwrap_or(false)),
|
||||
"tick" => {
|
||||
for _ in 0..n(1) {
|
||||
t.tick();
|
||||
}
|
||||
}
|
||||
other => panic!("unknown title op {other}"),
|
||||
}
|
||||
}
|
||||
let partial = float(c, "partial", 0.0);
|
||||
let bg = background(c);
|
||||
let mut out = t.overlay_message(w, h, partial, &atlas.font, bg);
|
||||
out.extend(t.title(w, h, partial, &atlas.font, bg));
|
||||
out
|
||||
}
|
||||
|
||||
/// Ticks `toolHighlightTimer` through the selected stacks, then extracts the name.
|
||||
fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let mut highlight = ToolHighlight::default();
|
||||
let time = c["displayTime"].as_f64().unwrap_or(1.0);
|
||||
for step in c["steps"].as_array().into_iter().flatten() {
|
||||
let held = (!step.is_null()).then(|| {
|
||||
let custom = &step["custom"];
|
||||
HeldName {
|
||||
item: step["item"].as_str().unwrap_or("").to_owned(),
|
||||
hover_name: if custom.is_null() {
|
||||
Text::translate(step["key"].as_str().unwrap_or(""), &[])
|
||||
} else {
|
||||
comp(custom)
|
||||
},
|
||||
rarity_color: text::named_color(step["rarity"].as_str().unwrap_or("white"))
|
||||
.unwrap_or(0xFFFFFF),
|
||||
custom_name: !custom.is_null(),
|
||||
}
|
||||
});
|
||||
highlight.tick(held, time);
|
||||
}
|
||||
let mode = c["gameMode"].as_str().unwrap_or("survival");
|
||||
let can_hurt = mode == "survival" || mode == "adventure";
|
||||
highlight.draw(w, h, can_hurt, &atlas.font, background(c))
|
||||
}
|
||||
|
||||
fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let bars: Vec<BossBar> = c["bars"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|b| BossBar {
|
||||
name: comp(&b["name"]),
|
||||
progress: b["progress"].as_f64().unwrap_or(0.0) as f32,
|
||||
color: b["color"].as_u64().unwrap_or(0) as usize,
|
||||
overlay: b["overlay"].as_u64().unwrap_or(0) as usize,
|
||||
})
|
||||
.collect();
|
||||
hud_overlays::boss_overlay(w, h, &bars, &atlas.font)
|
||||
}
|
||||
|
||||
/// A `NumberFormat` from the case: null, `{type: blank}`, `{type: fixed,
|
||||
/// value}` or `{type: styled, style}`.
|
||||
fn number_format(v: &Value) -> Option<NumberFormat> {
|
||||
match v["type"].as_str()? {
|
||||
"blank" => Some(NumberFormat::Blank),
|
||||
"fixed" => Some(NumberFormat::Fixed(v["value"].clone())),
|
||||
"styled" => Some(NumberFormat::Styled(v["style"].clone())),
|
||||
other => panic!("unknown number format {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn sidebar(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let mut board = Scoreboard::default();
|
||||
let o = &c["objective"];
|
||||
board.add_objective(
|
||||
"sidebar",
|
||||
"dummy",
|
||||
o["display"].clone(),
|
||||
RenderType::Integer,
|
||||
false,
|
||||
number_format(&o["format"]),
|
||||
);
|
||||
for s in c["scores"].as_array().into_iter().flatten() {
|
||||
let owner = s["owner"].as_str().unwrap_or("");
|
||||
let score = board.score_mut(owner, "sidebar");
|
||||
score.value = s["value"].as_i64().unwrap_or(0) as i32;
|
||||
score.display = (!s["display"].is_null()).then(|| s["display"].clone());
|
||||
score.number_format = number_format(&s["format"]);
|
||||
}
|
||||
for t in c["teams"].as_array().into_iter().flatten() {
|
||||
let name = t["name"].as_str().unwrap_or("");
|
||||
let team = board.add_team(name);
|
||||
team.prefix = t["prefix"].clone();
|
||||
team.suffix = t["suffix"].clone();
|
||||
team.color = t["color"].as_str().map(str::to_owned);
|
||||
for m in t["members"].as_array().into_iter().flatten() {
|
||||
board.add_to_team(m.as_str().unwrap_or(""), name);
|
||||
}
|
||||
}
|
||||
let opacity = c["textOpacity"].as_f64().unwrap_or(0.5);
|
||||
let chat_only = c["chatOnly"].as_bool().unwrap_or(true);
|
||||
let objective = board.objective("sidebar").expect("objective").clone();
|
||||
hud_overlays::sidebar(
|
||||
w,
|
||||
h,
|
||||
&board,
|
||||
&objective,
|
||||
&atlas.font,
|
||||
hud_layout::background_color(chat_only, opacity, 0.3),
|
||||
hud_layout::background_color(chat_only, opacity, 0.4),
|
||||
)
|
||||
}
|
||||
|
||||
/// `itemDecorations` for a stack with a count, damage and an item cooldown
|
||||
/// `elapsed` ticks into `duration` (ItemCooldowns.getCooldownPercent).
|
||||
fn decor(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let count = int(c, "count", 1);
|
||||
if count <= 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let cd = &c["cooldown"];
|
||||
let cooldown = if cd.is_null() {
|
||||
0.0
|
||||
} else {
|
||||
let (duration, elapsed) = (int(cd, "duration", 0), int(cd, "elapsed", 0));
|
||||
if duration <= elapsed {
|
||||
0.0 // ItemCooldowns.tick dropped it
|
||||
} else {
|
||||
let remaining = duration as f32 - (elapsed as f32 + float(c, "partial", 0.0));
|
||||
(remaining / duration as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
};
|
||||
let max_damage = if c["unbreakable"].as_bool().unwrap_or(false) {
|
||||
0
|
||||
} else {
|
||||
int(c, "maxDamage", 0)
|
||||
};
|
||||
let d = ItemDecorations {
|
||||
count: count as u32,
|
||||
count_text: c["countText"].as_str().map(str::to_owned),
|
||||
bar: hud_overlays::damage_bar(int(c, "damage", 0), max_damage),
|
||||
cooldown,
|
||||
};
|
||||
hud_overlays::item_decorations(int(c, "x", 0), int(c, "y", 0), &d, &atlas.font)
|
||||
}
|
||||
|
||||
/// `Hud.extractCameraOverlays` then `extractSleepOverlay`; the border is
|
||||
/// static, so only its warning blocks matter.
|
||||
fn overlays(c: &Value, w: i32, h: i32, state: &mut serde_json::Map<String, Value>) -> Vec<GuiDraw> {
|
||||
let partial = float(c, "partial", 0.0);
|
||||
let warning = match &c["border"] {
|
||||
Value::Null => 0.0,
|
||||
b => {
|
||||
// WorldBorder.getDistanceToBorder with the static extent's clamped box.
|
||||
let max = 29_999_984.0;
|
||||
let half = b["size"].as_f64().unwrap_or(0.0) / 2.0;
|
||||
let (cx, cz) = (
|
||||
b["centerX"].as_f64().unwrap_or(0.0),
|
||||
b["centerZ"].as_f64().unwrap_or(0.0),
|
||||
);
|
||||
let (min_x, max_x) = ((cx - half).clamp(-max, max), (cx + half).clamp(-max, max));
|
||||
let (min_z, max_z) = ((cz - half).clamp(-max, max), (cz + half).clamp(-max, max));
|
||||
let (x, z) = (
|
||||
f64::from(float(c, "camX", 0.0)),
|
||||
f64::from(float(c, "camZ", 0.0)),
|
||||
);
|
||||
let distance = (x - min_x).min(max_x - x).min(z - min_z).min(max_z - z);
|
||||
hud_overlays::border_warning(
|
||||
distance as f32,
|
||||
int(b, "warningBlocks", 5),
|
||||
int(b, "warningTime", 15),
|
||||
0.0,
|
||||
0.0,
|
||||
)
|
||||
}
|
||||
};
|
||||
let ticks_frozen = int(c, "ticksFrozen", 0);
|
||||
let inputs = CameraOverlays {
|
||||
vignette: c["vignette"]
|
||||
.as_bool()
|
||||
.unwrap_or(false)
|
||||
.then(|| (float(c, "vignetteBrightness", 1.0), warning)),
|
||||
first_person: c["firstPerson"].as_bool().unwrap_or(false),
|
||||
scoping: c["scoping"].as_bool().unwrap_or(false),
|
||||
game_time_delta: partial,
|
||||
equipment: match c["head"].as_str() {
|
||||
Some("carved_pumpkin") => vec!["misc/pumpkinblur".to_owned()],
|
||||
_ => Vec::new(),
|
||||
},
|
||||
ticks_frozen,
|
||||
percent_frozen: ticks_frozen.min(140) as f32 / 140.0,
|
||||
partial,
|
||||
portal: [
|
||||
c["portal"][0].as_f64().unwrap_or(0.0) as f32,
|
||||
c["portal"][1].as_f64().unwrap_or(0.0) as f32,
|
||||
],
|
||||
nausea: float(c, "nausea", 0.0),
|
||||
screen_effect_scale: float(c, "screenEffectScale", 1.0),
|
||||
};
|
||||
let mut scope = float(c, "scopeScale", 0.5);
|
||||
let mut out = hud_overlays::camera_overlays(w, h, &inputs, &mut scope);
|
||||
out.extend(hud_overlays::sleep_overlay(w, h, int(c, "sleepTimer", 0)));
|
||||
state.insert("scopeScale".into(), serde_json::json!(scope));
|
||||
out
|
||||
}
|
||||
|
||||
/// Messages added at their ticks (`Hud.tickCount`), then the chat in
|
||||
/// background mode at tick `now`.
|
||||
fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
|
||||
let option = |k: &str| c[k].as_f64().unwrap_or(0.0);
|
||||
let mut chat = Chat::default();
|
||||
chat.options = ChatOptions {
|
||||
opacity: option("chatOpacity"),
|
||||
background_opacity: option("textOpacity"),
|
||||
scale: option("chatScale"),
|
||||
width: option("chatWidth"),
|
||||
height_focused: option("chatHeightFocused"),
|
||||
height_unfocused: option("chatHeightUnfocused"),
|
||||
line_spacing: option("chatLineSpacing"),
|
||||
};
|
||||
for m in c["messages"].as_array().into_iter().flatten() {
|
||||
// GuiMessageTag indicator colours: systemSinglePlayer and chatError.
|
||||
let indicator = match m["tag"].as_str() {
|
||||
Some("system") => Some(13684944),
|
||||
Some("error") => Some(16733525),
|
||||
_ => None,
|
||||
};
|
||||
chat.add(
|
||||
atlas,
|
||||
comp(&m["text"]),
|
||||
indicator,
|
||||
m["at"].as_u64().unwrap_or(0),
|
||||
false,
|
||||
);
|
||||
}
|
||||
chat.layout(h, c["now"].as_u64().unwrap_or(0), false)
|
||||
}
|
||||
@@ -142,6 +142,8 @@ fn goal_name(m: &Mob, name: &str) -> String {
|
||||
let vanilla = match name {
|
||||
"Float" => "FloatGoal",
|
||||
"Stroll" => "WaterAvoidingRandomStrollGoal",
|
||||
"RandomStroll" => "RandomStrollGoal",
|
||||
"RandomSwimming" => "RandomSwimmingGoal",
|
||||
"LookAtPlayer" => "LookAtPlayerGoal",
|
||||
"RandomLookAround" => "RandomLookAroundGoal",
|
||||
"HurtByTarget" => "HurtByTargetGoal",
|
||||
@@ -171,6 +173,12 @@ fn goal_name(m: &Mob, name: &str) -> String {
|
||||
"TryFindWater" => "TryFindWaterGoal",
|
||||
"RangedAttack" => "RangedAttackGoal",
|
||||
"MoveTowardsTarget" => "MoveTowardsTargetGoal",
|
||||
"DrownedGoToWater" => "DrownedGoToWaterGoal",
|
||||
"TakeBlock" => "EndermanTakeBlockGoal",
|
||||
"LeaveBlock" => "EndermanLeaveBlockGoal",
|
||||
"FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt",
|
||||
"LookForPlayer" => "EndermanLookForPlayerGoal",
|
||||
"HealRaiders" => "NearestHealableRaiderTargetGoal",
|
||||
other => return other.to_owned(),
|
||||
};
|
||||
vanilla.to_owned()
|
||||
@@ -221,13 +229,43 @@ fn seen(m: &Mob) -> Seen {
|
||||
hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)),
|
||||
active_raid: horizon_client::mobs::raider::has_active_raid(m),
|
||||
player_rep: 0,
|
||||
pushable: m.pushable(),
|
||||
category: m.category(),
|
||||
potential_job: horizon_client::mobs::villager_brain::potential_job_site(m),
|
||||
meeting: (m.species() == Species::Villager)
|
||||
.then_some(m.extra.meeting)
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an event hurts the scenario's player (survival, normal difficulty,
|
||||
/// no armour, made hurtable again every tick by the oracle).
|
||||
fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
|
||||
let Some(p) = player.filter(|p| !p.creative) else {
|
||||
return false;
|
||||
};
|
||||
match e {
|
||||
MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0,
|
||||
// ServerExplosion.hurtEntities: within twice the radius every hit does damage.
|
||||
MobEvent::Explode(at, radius) => {
|
||||
let d = Vec3::new(at[0], at[1], at[2])
|
||||
.distance_squared(p.position)
|
||||
.sqrt();
|
||||
let r = 2.0 * f64::from(*radius);
|
||||
d / r <= 1.0 && d != 0.0
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
||||
let _ = write!(out, "{t} {i}");
|
||||
if m.removed {
|
||||
let _ = writeln!(out, " removed DISCARDED");
|
||||
// Entity.RemovalReason: the end of the death animation, else a discard.
|
||||
let reason = if m.alive() { "DISCARDED" } else { "KILLED" };
|
||||
let _ = writeln!(out, " removed {reason}");
|
||||
return;
|
||||
}
|
||||
let p = m.position;
|
||||
@@ -316,7 +354,11 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
||||
f(m.ai.speed),
|
||||
u8::from(m.ai.jumping)
|
||||
);
|
||||
let _ = writeln!(out, "\trng {:x}", m.random.state());
|
||||
let _ = write!(out, "\trng {:x}", m.random.state());
|
||||
if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) {
|
||||
let _ = write!(out, "\tact {acts}\tmem {mem}");
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
@@ -429,6 +471,16 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
}
|
||||
m.random = LegacyRandom::new(spec.seed);
|
||||
if m.species() == Species::Villager {
|
||||
// The oracle seeds the random after the brain is built, then
|
||||
// delays the sensors again and seeds the gates' shuffles.
|
||||
horizon_client::mobs::villager_brain::init(
|
||||
&mut m,
|
||||
world.game_time,
|
||||
s.time,
|
||||
spec.seed,
|
||||
);
|
||||
}
|
||||
mobs.push(m);
|
||||
}
|
||||
let player = s.player.map(|p| {
|
||||
@@ -456,6 +508,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
yaw: 0.0,
|
||||
hero: false,
|
||||
uuid: [0, 0x1234, 0, 0x5678],
|
||||
allies: Default::default(),
|
||||
}
|
||||
});
|
||||
let mut scratch = LegacyRandom::new(0);
|
||||
@@ -466,6 +519,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
world.game_time += 1;
|
||||
let snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = MobWorld {
|
||||
teams: Default::default(),
|
||||
world: &world,
|
||||
registry,
|
||||
facts: &facts,
|
||||
@@ -485,16 +539,38 @@ fn main() -> horizon_client::Result<()> {
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
for m in &mut mobs {
|
||||
#[allow(unused_mut)] // filled only with the rng-trace feature
|
||||
let mut traces: Vec<String> = Vec::new();
|
||||
let mut pushes = Vec::new();
|
||||
for (i, m) in mobs.iter_mut().enumerate() {
|
||||
if m.removed {
|
||||
continue;
|
||||
}
|
||||
if !m.tick(&w, &mut scratch, &mut events) {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
#[cfg(feature = "rng-trace")]
|
||||
horizon_core::random::trace::set(true);
|
||||
let alive = m.tick(&w, &mut scratch, &mut events);
|
||||
#[cfg(feature = "rng-trace")]
|
||||
{
|
||||
horizon_core::random::trace::set(false);
|
||||
for line in horizon_core::random::trace::take() {
|
||||
traces.push(format!("{t} trace {i} {line}"));
|
||||
}
|
||||
}
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
let _ = i;
|
||||
if !alive {
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
for (i, m) in mobs.iter().enumerate() {
|
||||
print(&mut out, t, i, m);
|
||||
}
|
||||
@@ -508,8 +584,18 @@ fn main() -> horizon_client::Result<()> {
|
||||
);
|
||||
} else if let MobEvent::SoundId(name, _, volume, pitch) = e {
|
||||
let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch));
|
||||
} else if player_hurt(player.as_ref(), e) {
|
||||
// The oracle's survival player, healed and made hurtable every tick,
|
||||
// takes the damage (LivingEntity.playHurtSound).
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{t} sound minecraft:entity.player.hurt 3f800000 3f800000"
|
||||
);
|
||||
}
|
||||
}
|
||||
for line in traces {
|
||||
let _ = writeln!(out, "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fs::write(&args[2], out)?;
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
//! The scoreboard model for differential tests against vanilla's `Scoreboard`
|
||||
//! (tools/test_scoreboard_parity.py): runs the same scripted operations as
|
||||
//! VanillaScoreboardOracle on `horizon_client::scoreboard::Scoreboard` and
|
||||
//! prints the same JSON lines (results, dumps, the packed save data before
|
||||
//! and after reloading it). With a vanilla output file it also reloads each
|
||||
//! case's vanilla NBT and packs it again (`vreload`).
|
||||
//!
|
||||
//! usage: scoreboard_fixture REGISTRIES.json INPUTS OUTPUT [VANILLA_OUTPUT]
|
||||
use horizon_client::{
|
||||
command::Registries,
|
||||
scoreboard::{
|
||||
self as sb, CollisionRule, Comp, NumberFormat, RenderType, Scoreboard, Visibility,
|
||||
canonical_component, criteria_by_name, criteria_read_only, criteria_render_type,
|
||||
},
|
||||
};
|
||||
use horizon_world::nbt::{self, NamedTag, Tag};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::{collections::BTreeMap, fs, io::Write};
|
||||
|
||||
fn canon(tag: &Tag) -> Value {
|
||||
match tag {
|
||||
Tag::Compound(c) => {
|
||||
let sorted: BTreeMap<String, &Tag> =
|
||||
c.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
|
||||
Value::Object(sorted.into_iter().map(|(k, v)| (k, canon(v))).collect())
|
||||
}
|
||||
Tag::List(l) => Value::Array(l.iter().map(canon).collect()),
|
||||
Tag::String(s) => Value::String(format!("'{}", s.to_string_lossy())),
|
||||
Tag::Byte(v) => Value::String(format!("{v}b")),
|
||||
Tag::Short(v) => Value::String(format!("{v}s")),
|
||||
Tag::Int(v) => Value::String(format!("{v}i")),
|
||||
Tag::Long(v) => Value::String(format!("{v}L")),
|
||||
Tag::Float(v) => Value::String(format!("f:{v:x}")),
|
||||
Tag::Double(v) => Value::String(format!("d:{v:x}")),
|
||||
Tag::IntArray(v) => json!({ "I;": v }),
|
||||
other => Value::String(format!("?{other:?}")),
|
||||
}
|
||||
}
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap_or(0))
|
||||
.collect()
|
||||
}
|
||||
fn encode(tag: &Tag) -> Vec<u8> {
|
||||
nbt::write_named(
|
||||
&NamedTag {
|
||||
name: "".into(),
|
||||
tag: tag.clone(),
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.expect("nbt")
|
||||
}
|
||||
fn decode(bytes: &[u8]) -> Tag {
|
||||
nbt::read_named(bytes, Default::default())
|
||||
.expect("nbt")
|
||||
.0
|
||||
.tag
|
||||
}
|
||||
|
||||
fn comp(v: Option<&Value>) -> Option<Comp> {
|
||||
v.filter(|v| !v.is_null()).cloned()
|
||||
}
|
||||
fn comp_json(c: Option<&Comp>) -> Value {
|
||||
c.map_or(Value::Null, canonical_component)
|
||||
}
|
||||
fn fmt_json(f: Option<&NumberFormat>) -> Value {
|
||||
f.map_or(Value::Null, NumberFormat::to_json)
|
||||
}
|
||||
fn fmt(v: Option<&Value>) -> Option<NumberFormat> {
|
||||
v.filter(|v| !v.is_null()).and_then(NumberFormat::from_json)
|
||||
}
|
||||
fn s<'a>(op: &'a Value, k: &str) -> &'a str {
|
||||
op[k].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
reg: Registries,
|
||||
}
|
||||
impl Fixture {
|
||||
fn criteria(&self, name: &str) -> Value {
|
||||
match criteria_by_name(name, &self.reg) {
|
||||
Ok(Some(c)) => Value::String(c),
|
||||
Ok(None) => Value::Null,
|
||||
Err(_) => Value::String("!invalid".into()),
|
||||
}
|
||||
}
|
||||
fn dump(&self, b: &Scoreboard, probes: &[Value]) -> Value {
|
||||
let objectives: Vec<Value> = b
|
||||
.objectives
|
||||
.iter()
|
||||
.map(|o| {
|
||||
json!({
|
||||
"name": o.name, "criteria": o.criteria, "display": comp_json(Some(&o.display_name)),
|
||||
"render": o.render_type.id(), "auto": o.display_auto_update,
|
||||
"format": fmt_json(o.number_format.as_ref()),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let stream: Vec<Value> = b
|
||||
.objectives_streamed()
|
||||
.iter()
|
||||
.map(|o| Value::String(o.name.clone()))
|
||||
.collect();
|
||||
let tracked = b.tracked();
|
||||
let mut lists = Map::new();
|
||||
for o in &b.objectives {
|
||||
let rows: Vec<Value> = b
|
||||
.list_scores(&o.name)
|
||||
.iter()
|
||||
.map(|e| {
|
||||
json!([
|
||||
e.owner,
|
||||
e.value,
|
||||
comp_json(e.display.as_ref()),
|
||||
fmt_json(e.number_format.as_ref())
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
lists.insert(o.name.clone(), Value::Array(rows));
|
||||
}
|
||||
let mut holders = Map::new();
|
||||
for h in &tracked {
|
||||
let mut per = Map::new();
|
||||
for o in &b.objectives {
|
||||
if let Some(sc) = b.score(h, &o.name) {
|
||||
per.insert(o.name.clone(), score_json(sc));
|
||||
}
|
||||
}
|
||||
holders.insert(h.clone(), Value::Object(per));
|
||||
}
|
||||
let teams: Vec<Value> = b
|
||||
.teams
|
||||
.iter()
|
||||
.map(|t| {
|
||||
json!({
|
||||
"name": t.name, "display": comp_json(Some(&t.display_name)), "color": t.color,
|
||||
"ff": t.allow_friendly_fire, "si": t.see_friendly_invisibles,
|
||||
"prefix": comp_json(Some(&t.prefix)), "suffix": comp_json(Some(&t.suffix)),
|
||||
"nametag": t.nametag_visibility.name(), "death": t.death_message_visibility.name(),
|
||||
"collision": t.collision_rule.name(),
|
||||
"players": t.players.iter().collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let teams_stream: Vec<Value> = b
|
||||
.teams_streamed()
|
||||
.iter()
|
||||
.map(|t| Value::String(t.name.clone()))
|
||||
.collect();
|
||||
let mut slots = Map::new();
|
||||
for slot in sb::display_slots() {
|
||||
if let Some(o) = b.display_objective(&slot) {
|
||||
slots.insert(slot, Value::String(o.name.clone()));
|
||||
}
|
||||
}
|
||||
let mut team_of = Map::new();
|
||||
for p in probes {
|
||||
let p = p.as_str().unwrap_or_default();
|
||||
team_of.insert(
|
||||
p.to_owned(),
|
||||
b.players_team(p)
|
||||
.map_or(Value::Null, |t| Value::String(t.name.clone())),
|
||||
);
|
||||
}
|
||||
json!({
|
||||
"objectives": objectives, "objectives_stream": stream, "tracked": tracked,
|
||||
"lists": lists, "holders": holders, "teams": teams, "teams_stream": teams_stream,
|
||||
"slots": slots, "team_of": team_of,
|
||||
})
|
||||
}
|
||||
fn apply(&self, b: &mut Scoreboard, op: &Value, probes: &[Value]) -> Value {
|
||||
let kind = s(op, "op");
|
||||
let holder = s(op, "holder");
|
||||
let dname = comp(op.get("dname"));
|
||||
match kind {
|
||||
"crit" => {
|
||||
let name = self.criteria(s(op, "name"));
|
||||
let mut o = json!({ "name": name });
|
||||
if let Some(n) = name.as_str().filter(|n| !n.starts_with('!')) {
|
||||
o["readonly"] = Value::Bool(criteria_read_only(n));
|
||||
o["render"] = Value::String(criteria_render_type(n).id().into());
|
||||
}
|
||||
o
|
||||
}
|
||||
"obj_add" => {
|
||||
let Some(criteria) = self
|
||||
.criteria(s(op, "criteria"))
|
||||
.as_str()
|
||||
.filter(|c| !c.starts_with('!'))
|
||||
.map(str::to_owned)
|
||||
else {
|
||||
return json!("bad");
|
||||
};
|
||||
if b.objective(s(op, "name")).is_some() {
|
||||
return json!("exists");
|
||||
}
|
||||
b.add_objective(
|
||||
s(op, "name"),
|
||||
&criteria,
|
||||
comp(op.get("display")).unwrap_or(Value::Null),
|
||||
RenderType::by_id(s(op, "render")),
|
||||
op["auto"].as_bool().unwrap_or(false),
|
||||
fmt(op.get("fmt")),
|
||||
);
|
||||
json!("ok")
|
||||
}
|
||||
"obj_rm" => {
|
||||
if b.objective(s(op, "name")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.remove_objective(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"obj_mod" => {
|
||||
let Some(o) = b.objective_mut(s(op, "name")) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let v = &op["value"];
|
||||
match s(op, "field") {
|
||||
"display" => o.display_name = v.clone(),
|
||||
"render" => o.render_type = RenderType::by_id(v.as_str().unwrap_or_default()),
|
||||
"auto" => o.display_auto_update = v.as_bool().unwrap_or(false),
|
||||
"fmt" => o.number_format = fmt(Some(v)),
|
||||
other => panic!("field {other}"),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"slot" => {
|
||||
let name = op["name"].as_str();
|
||||
if let Some(n) = name
|
||||
&& b.objective(n).is_none()
|
||||
{
|
||||
return json!("missing");
|
||||
}
|
||||
b.set_display_objective(s(op, "slot"), name);
|
||||
json!("ok")
|
||||
}
|
||||
"set" | "add" | "get" | "lock" | "unlock" | "sdisplay" | "sfmt" => {
|
||||
let name = s(op, "name");
|
||||
let Some(criteria) = b.objective(name).map(|o| o.criteria.clone()) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let force = op["force"].as_bool().unwrap_or(false);
|
||||
let writable = force || !criteria_read_only(&criteria);
|
||||
let current = b.get(holder, name);
|
||||
match kind {
|
||||
"set" | "add" => {
|
||||
if !writable {
|
||||
return json!("readonly");
|
||||
}
|
||||
let value = op["value"].as_i64().unwrap_or(0) as i32;
|
||||
let new = if kind == "add" {
|
||||
current.wrapping_add(value)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
b.set_with(holder, name, new, dname.as_ref());
|
||||
if kind == "add" {
|
||||
return json!(new);
|
||||
}
|
||||
}
|
||||
"get" => return json!(current),
|
||||
"lock" => b.score_mut(holder, name).locked = true,
|
||||
"unlock" => b.score_mut(holder, name).locked = false,
|
||||
"sdisplay" => b.score_mut(holder, name).display = comp(op.get("value")),
|
||||
"sfmt" => b.score_mut(holder, name).number_format = fmt(op.get("value")),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"info" => {
|
||||
let name = s(op, "name");
|
||||
if b.objective(name).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.score(holder, name).map_or(Value::Null, score_json)
|
||||
}
|
||||
"reset" => {
|
||||
match op["name"].as_str() {
|
||||
None => b.reset_all(holder),
|
||||
Some(name) => {
|
||||
if b.objective(name).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.reset_one(holder, name);
|
||||
}
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"all" => {
|
||||
let criteria = self.criteria(s(op, "criteria"));
|
||||
let criteria = criteria.as_str().unwrap_or_default();
|
||||
let value = op["value"].as_i64().unwrap_or(0) as i32;
|
||||
let k = s(op, "kind");
|
||||
b.for_all_objectives_with(criteria, holder, dname.as_ref(), |v| match k {
|
||||
"inc" => v.wrapping_add(1),
|
||||
"add" => v.wrapping_add(value),
|
||||
"set" => value,
|
||||
_ => 0,
|
||||
});
|
||||
json!("ok")
|
||||
}
|
||||
"team_add" => {
|
||||
if b.team(s(op, "name")).is_some() {
|
||||
return json!("exists");
|
||||
}
|
||||
b.add_team(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"team_rm" => {
|
||||
if b.team(s(op, "name")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
b.remove_team(s(op, "name"));
|
||||
json!("ok")
|
||||
}
|
||||
"join" => {
|
||||
if b.team(s(op, "team")).is_none() {
|
||||
return json!("missing");
|
||||
}
|
||||
json!(b.add_to_team(holder, s(op, "team")))
|
||||
}
|
||||
"leave" => json!(b.remove_from_team(holder)),
|
||||
"team_set" => {
|
||||
let Some(t) = b.team_mut(s(op, "name")) else {
|
||||
return json!("missing");
|
||||
};
|
||||
let v = &op["value"];
|
||||
let name = |v: &Value| v.as_str().unwrap_or_default().to_owned();
|
||||
match s(op, "field") {
|
||||
"display" => t.display_name = v.clone(),
|
||||
"color" => t.color = v.as_str().map(str::to_owned),
|
||||
"ff" => t.allow_friendly_fire = v.as_bool().unwrap_or(true),
|
||||
"si" => t.see_friendly_invisibles = v.as_bool().unwrap_or(true),
|
||||
"prefix" => t.prefix = comp(Some(v)).unwrap_or_else(|| sb::literal("")),
|
||||
"suffix" => t.suffix = comp(Some(v)).unwrap_or_else(|| sb::literal("")),
|
||||
"nametag" => {
|
||||
t.nametag_visibility = Visibility::by_name(&name(v)).expect("visibility")
|
||||
}
|
||||
"death" => {
|
||||
t.death_message_visibility =
|
||||
Visibility::by_name(&name(v)).expect("visibility")
|
||||
}
|
||||
"collision" => {
|
||||
t.collision_rule = CollisionRule::by_name(&name(v)).expect("collision")
|
||||
}
|
||||
other => panic!("field {other}"),
|
||||
}
|
||||
json!("ok")
|
||||
}
|
||||
"removed" => {
|
||||
b.entity_removed(holder);
|
||||
json!("ok")
|
||||
}
|
||||
"allied" => json!(b.allied(s(op, "a"), s(op, "b"))),
|
||||
"dump" => self.dump(b, probes),
|
||||
other => panic!("op {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn score_json(sc: &sb::Score) -> Value {
|
||||
json!({
|
||||
"value": sc.value, "locked": sc.locked, "display": comp_json(sc.display.as_ref()),
|
||||
"format": fmt_json(sc.number_format.as_ref()),
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let registries: Value =
|
||||
serde_json::from_str(&fs::read_to_string(&args[1]).expect("registries")).expect("json");
|
||||
let list = |k: &str| -> Vec<String> {
|
||||
registries[k]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let reg = Registries {
|
||||
items: list("items"),
|
||||
blocks: list("blocks")
|
||||
.into_iter()
|
||||
.map(|b| (b, Vec::new()))
|
||||
.collect(),
|
||||
entity_types: list("entity_types"),
|
||||
..Registries::default()
|
||||
};
|
||||
let fixture = Fixture { reg };
|
||||
let vanilla: BTreeMap<i64, String> = args
|
||||
.get(4)
|
||||
.and_then(|p| fs::read_to_string(p).ok())
|
||||
.map(|text| {
|
||||
text.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.filter_map(|v| Some((v["case"].as_i64()?, v["nbt"].as_str()?.to_owned())))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(&args[3]).expect("output"));
|
||||
for line in fs::read_to_string(&args[2]).expect("inputs").lines() {
|
||||
let case: Value = serde_json::from_str(line).expect("case");
|
||||
let probes = case["probes"].as_array().cloned().unwrap_or_default();
|
||||
let mut board = Scoreboard::default();
|
||||
let outs: Vec<Value> = case["ops"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|op| fixture.apply(&mut board, op, &probes))
|
||||
.collect();
|
||||
let packed = board.pack();
|
||||
let bytes = encode(&packed);
|
||||
let reloaded = Scoreboard::unpack(&decode(&bytes));
|
||||
let mut result = json!({
|
||||
"case": case["case"], "out": outs, "pack": canon(&packed), "nbt": hex(&bytes),
|
||||
"reload": canon(&reloaded.pack()), "reload_dump": fixture.dump(&reloaded, &probes),
|
||||
});
|
||||
if let Some(v) = case["case"].as_i64().and_then(|c| vanilla.get(&c)) {
|
||||
result["vreload"] = canon(&Scoreboard::unpack(&decode(&unhex(v))).pack());
|
||||
}
|
||||
writeln!(out, "{result}").expect("write");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The subtitle overlay for differential tests against vanilla's
|
||||
//! `SubtitleOverlay` (tools/test_subtitle_parity.py): replays each case's
|
||||
//! sound plays, clock changes and frames through
|
||||
//! `horizon_client::subtitles` and prints every frame's fills and texts with
|
||||
//! their pose, in VanillaSubtitleOracle's JSON lines.
|
||||
//!
|
||||
//! usage: subtitle_fixture RESOURCES INPUTS OUTPUT
|
||||
use horizon_client::{
|
||||
hud::HudAtlas,
|
||||
hud_layout::{GuiDraw, IDENTITY, background_color, pose_apply},
|
||||
hud_overlays::{SubtitleFrame, SubtitleOverlay},
|
||||
lang,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fs, io::Write, path::PathBuf};
|
||||
|
||||
fn vec3(v: &Value) -> [f64; 3] {
|
||||
std::array::from_fn(|i| v[i].as_f64().unwrap_or(0.0))
|
||||
}
|
||||
fn pose(m: [f32; 6]) -> Value {
|
||||
json!(m)
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
|
||||
let [root, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: subtitle_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
lang::set(lang::Language::load(&[root], lang::DEFAULT));
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(inputs)?
|
||||
.lines()
|
||||
.filter(|l| !l.is_empty())
|
||||
{
|
||||
let c: Value = serde_json::from_str(line)?;
|
||||
let mut overlay = SubtitleOverlay::default();
|
||||
let mut now = 0i64;
|
||||
let mut frames = Vec::new();
|
||||
for op in c["ops"].as_array().into_iter().flatten() {
|
||||
match op["op"].as_str().unwrap_or_default() {
|
||||
// Util.getMillis: nanoseconds / 1_000_000.
|
||||
"time" => now = op["ms"].as_i64().unwrap_or(0),
|
||||
"play" => {
|
||||
if overlay.listening() {
|
||||
let range = op["range"].as_f64().map_or(f32::INFINITY, |r| r as f32);
|
||||
overlay.on_play(
|
||||
op["key"].as_str(),
|
||||
vec3(&op["at"]),
|
||||
range,
|
||||
op["looping"].as_bool().unwrap_or(false),
|
||||
now,
|
||||
);
|
||||
}
|
||||
}
|
||||
"frame" => {
|
||||
let frame = SubtitleFrame {
|
||||
show: op["show"].as_bool().unwrap_or(false),
|
||||
position: vec3(&op["pos"]),
|
||||
forward: vec3(&op["forward"]),
|
||||
up: vec3(&op["up"]),
|
||||
multiplier: op["mult"].as_f64().unwrap_or(1.0),
|
||||
background: background_color(
|
||||
op["chat_only"].as_bool().unwrap_or(true),
|
||||
op["opacity"].as_f64().unwrap_or(0.5),
|
||||
0.8,
|
||||
),
|
||||
width: op["w"].as_i64().unwrap_or(0) as i32,
|
||||
height: op["h"].as_i64().unwrap_or(0) as i32,
|
||||
};
|
||||
let mut stack = vec![IDENTITY];
|
||||
let mut draws = Vec::new();
|
||||
let calls = overlay.extract(&frame, &atlas.font, now);
|
||||
if !calls.is_empty() {
|
||||
draws.push(json!({"type": "stratum"}));
|
||||
}
|
||||
for d in calls {
|
||||
let m = *stack.last().unwrap_or(&IDENTITY);
|
||||
match d {
|
||||
GuiDraw::Push(ops) => {
|
||||
let mut top = m;
|
||||
for op in ops {
|
||||
pose_apply(&mut top, op);
|
||||
}
|
||||
stack.push(top);
|
||||
}
|
||||
GuiDraw::Pop => {
|
||||
stack.pop();
|
||||
}
|
||||
GuiDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => draws.push(json!({
|
||||
"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1,
|
||||
"color": format!("{color:x}"), "pose": pose(m),
|
||||
})),
|
||||
GuiDraw::Text {
|
||||
text,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => draws.push(json!({
|
||||
"type": "text", "text": text.plain(), "x": x, "y": y,
|
||||
"color": format!("{color:x}"), "shadow": shadow, "pose": pose(m),
|
||||
})),
|
||||
other => return Err(format!("unexpected draw {other:?}").into()),
|
||||
}
|
||||
}
|
||||
frames.push(Value::Array(draws));
|
||||
}
|
||||
other => return Err(format!("op {other}").into()),
|
||||
}
|
||||
}
|
||||
writeln!(out, "{}", json!({"case": c["case"], "frames": frames}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Team rules in gameplay for differential tests against vanilla
|
||||
//! (tools/test_team_rules_parity.py): friendly fire, alliances, collision
|
||||
//! rules, seeing invisible team mates and name tag visibility, from
|
||||
//! `horizon_client::scoreboard`, in VanillaTeamRulesOracle's JSON lines.
|
||||
//!
|
||||
//! usage: team_rules_fixture INPUTS OUTPUT
|
||||
use horizon_client::scoreboard::{self as sb, CollisionRule, NameView, Scoreboard, Visibility};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fs, io::Write};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(&args[2]).expect("output"));
|
||||
for line in fs::read_to_string(&args[1]).expect("inputs").lines() {
|
||||
let c: Value = serde_json::from_str(line).expect("case");
|
||||
let mut board = Scoreboard::default();
|
||||
for name in ["A", "B"] {
|
||||
let o = &c[name];
|
||||
let t = board.add_team(name);
|
||||
t.allow_friendly_fire = o["ff"].as_bool().unwrap_or(true);
|
||||
t.see_friendly_invisibles = o["si"].as_bool().unwrap_or(true);
|
||||
t.collision_rule =
|
||||
CollisionRule::by_name(o["collision"].as_str().unwrap_or("")).expect("rule");
|
||||
t.nametag_visibility =
|
||||
Visibility::by_name(o["nametag"].as_str().unwrap_or("")).expect("visibility");
|
||||
}
|
||||
let team = |k: &str| c[k].as_str().and_then(|n| board.team(n));
|
||||
let flag = |k: &str| c[k].as_bool().unwrap_or(false);
|
||||
let (own, other, viewer) = (team("own"), team("other"), team("viewer"));
|
||||
let invisible =
|
||||
sb::invisible_to(other, viewer, flag("viewer_spectator"), flag("invisible"));
|
||||
let view = NameView {
|
||||
discrete: flag("discrete"),
|
||||
distance_sqr: c["distance"].as_f64().unwrap_or(0.0),
|
||||
invisible_to_viewer: invisible,
|
||||
hud_hidden: flag("hud_hidden"),
|
||||
is_camera: flag("camera_is_entity"),
|
||||
is_vehicle: flag("vehicle"),
|
||||
};
|
||||
let r = json!({
|
||||
"case": c["case"],
|
||||
"damage": sb::teams_allow_damage(own, other),
|
||||
"allied": sb::teams_allied(own, other),
|
||||
"pushes": !flag("spectator") && sb::pushable_by(own, other, flag("pushable")),
|
||||
"invisible": invisible,
|
||||
"name": sb::name_shown(other, viewer, view),
|
||||
});
|
||||
writeln!(out, "{r}").expect("write");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The player's attack strength (`Player.attackStrengthTicker`,
|
||||
//! `itemSwapTicker`, `getAttackStrengthScale`, `getCurrentItemAttackStrengthDelay`):
|
||||
//! the charge the attack indicator shows and attacks scale their damage by.
|
||||
|
||||
/// `Attributes.ATTACK_SPEED` base value.
|
||||
pub const BASE_ATTACK_SPEED: f64 = 4.0;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct AttackStrength {
|
||||
/// `LivingEntity.attackStrengthTicker`.
|
||||
pub ticker: i32,
|
||||
/// `LivingEntity.itemSwapTicker`.
|
||||
pub swap_ticker: i32,
|
||||
/// `Player.lastItemInMainHand`: the stack as last compared.
|
||||
last_item: Option<HeldStack>,
|
||||
}
|
||||
/// What `ItemStack.matches` / `isSameItem` compare of the main-hand stack:
|
||||
/// its item id and the rest of the stack (count and components) as a key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HeldStack {
|
||||
pub item: String,
|
||||
pub rest: String,
|
||||
}
|
||||
/// `Player.getCurrentItemAttackStrengthDelay` for an ATTACK_SPEED value.
|
||||
pub fn delay(attack_speed: f64) -> f32 {
|
||||
(1.0 / attack_speed * 20.0) as f32
|
||||
}
|
||||
impl AttackStrength {
|
||||
/// The attack-strength part of `Player.tick`: both tickers advance, and a
|
||||
/// main-hand change to a different item resets them
|
||||
/// (`!ItemStack.matches` and `!ItemStack.isSameItem`).
|
||||
pub fn tick(&mut self, main_hand: Option<HeldStack>) {
|
||||
self.ticker += 1;
|
||||
self.swap_ticker += 1;
|
||||
if self.last_item != main_hand {
|
||||
let same_item = match (&self.last_item, &main_hand) {
|
||||
(Some(a), Some(b)) => a.item == b.item,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if !same_item {
|
||||
self.reset();
|
||||
}
|
||||
self.last_item = main_hand;
|
||||
}
|
||||
}
|
||||
/// `resetAttackStrengthTicker`: swinging at nothing, attacking or
|
||||
/// stopping a block break.
|
||||
pub fn reset(&mut self) {
|
||||
self.ticker = 0;
|
||||
self.swap_ticker = 0;
|
||||
}
|
||||
/// `resetOnlyAttackStrengthTicker` (`Player.onAttack`).
|
||||
pub fn reset_attack(&mut self) {
|
||||
self.ticker = 0;
|
||||
}
|
||||
/// `getAttackStrengthScale(a)` with the ATTACK_SPEED attribute value.
|
||||
pub fn scale(&self, a: f32, attack_speed: f64) -> f32 {
|
||||
((self.ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0)
|
||||
}
|
||||
/// `getItemSwapScale(a)`.
|
||||
pub fn swap_scale(&self, a: f32, attack_speed: f64) -> f32 {
|
||||
((self.swap_ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn held(item: &str, rest: &str) -> Option<HeldStack> {
|
||||
Some(HeldStack {
|
||||
item: item.into(),
|
||||
rest: rest.into(),
|
||||
})
|
||||
}
|
||||
#[test]
|
||||
fn charges_over_the_attack_delay() {
|
||||
let mut s = AttackStrength::default();
|
||||
// A sword's 1.6 attacks per second: 12.5 ticks to full strength.
|
||||
assert_eq!(delay(1.6), 12.5);
|
||||
for _ in 0..6 {
|
||||
s.tick(None);
|
||||
}
|
||||
assert_eq!(s.scale(0.25, 1.6), 6.25 / 12.5);
|
||||
for _ in 0..10 {
|
||||
s.tick(None);
|
||||
}
|
||||
assert_eq!(s.scale(0.0, 1.6), 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn switching_items_resets_but_restacking_does_not() {
|
||||
let mut s = AttackStrength::default();
|
||||
s.tick(held("minecraft:stone", "64"));
|
||||
assert_eq!(s.ticker, 0, "picking up an item resets");
|
||||
s.tick(held("minecraft:stone", "63"));
|
||||
assert_eq!(
|
||||
s.ticker, 1,
|
||||
"the same item with another count keeps charging"
|
||||
);
|
||||
s.tick(held("minecraft:diamond_sword", ""));
|
||||
assert_eq!((s.ticker, s.swap_ticker), (0, 0));
|
||||
s.tick(held("minecraft:diamond_sword", ""));
|
||||
s.reset_attack();
|
||||
assert_eq!((s.ticker, s.swap_ticker), (0, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,905 @@
|
||||
//! Client-ticked block-entity animation state, as vanilla's block entities
|
||||
//! keep it: `ChestLidController` (chests, trapped and copper chests, ender
|
||||
//! chests), `EnchantingTableBlockEntity.bookAnimationTick`,
|
||||
//! `ShulkerBoxBlockEntity` (open count, animation status, progress),
|
||||
//! `BellBlockEntity` (ring ticks, shake direction, resonation),
|
||||
//! `ConduitBlockEntity.clientTick` (tick count, shape check, rotation,
|
||||
//! hunting, nautilus particles), `SkullBlockEntity.animation` (powered dragon
|
||||
//! and piglin heads) and `DecoratedPotBlockEntity` wobbles.
|
||||
//!
|
||||
//! [`BlockEntityAnims`] holds the state per position and turns it into the
|
||||
//! renderer's [`BlockAnim`]. Its tick methods take what the level answers
|
||||
//! (blocks, entities, game time) as closures, so the parity fixture can drive
|
||||
//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`).
|
||||
use crate::block_entity_render::BlockAnim;
|
||||
use horizon_core::{
|
||||
geometry::trig::{self, Mth},
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// `Direction` names by `get3DDataValue`.
|
||||
pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
|
||||
|
||||
fn step(direction: u8) -> [i32; 3] {
|
||||
match direction {
|
||||
0 => [0, -1, 0],
|
||||
1 => [0, 1, 0],
|
||||
2 => [0, 0, -1],
|
||||
3 => [0, 0, 1],
|
||||
4 => [-1, 0, 0],
|
||||
_ => [1, 0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
/// `Direction.from3DDataValue`: `BY_3D_DATA[Mth.abs(data % 6)]`.
|
||||
pub fn from_3d_data_value(data: i32) -> u8 {
|
||||
(data % 6).unsigned_abs() as u8
|
||||
}
|
||||
|
||||
/// The 3D data value of a direction name.
|
||||
pub fn direction_index(name: &str) -> Option<u8> {
|
||||
DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8)
|
||||
}
|
||||
|
||||
/// `ChestLidController`, shared by `ChestBlockEntity` (chests, trapped and
|
||||
/// copper chests) and `EnderChestBlockEntity`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct ChestLid {
|
||||
pub should_be_open: bool,
|
||||
pub openness: f32,
|
||||
pub o_openness: f32,
|
||||
}
|
||||
|
||||
impl ChestLid {
|
||||
/// `triggerEvent(1, openCount)`: the lid opens while anyone has it open.
|
||||
pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool {
|
||||
if b0 == 1 {
|
||||
self.should_be_open = b1 > 0;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// `tickLid` (the client ticker `lidAnimateTick`).
|
||||
pub fn tick(&mut self) {
|
||||
self.o_openness = self.openness;
|
||||
if !self.should_be_open && self.openness > 0.0 {
|
||||
self.openness = (self.openness - 0.1).max(0.0);
|
||||
} else if self.should_be_open && self.openness < 1.0 {
|
||||
self.openness = (self.openness + 0.1).min(1.0);
|
||||
}
|
||||
}
|
||||
/// `getOpenness(a)`: `Mth.lerp(a, oOpenness, openness)`.
|
||||
pub fn get_openness(&self, a: f32) -> f32 {
|
||||
self.o_openness + a * (self.openness - self.o_openness)
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChestBlock.opennessCombiner`: a double chest opens as far as its more
|
||||
/// open half (`Math.max(first, second)`, first being the `right` half).
|
||||
pub fn combined_openness(first: f32, second: Option<f32>) -> f32 {
|
||||
match second {
|
||||
Some(second) => java_max(first, second),
|
||||
None => first,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Math.max(float, float)`.
|
||||
fn java_max(a: f32, b: f32) -> f32 {
|
||||
if a.is_nan() {
|
||||
a
|
||||
} else if a == 0.0 && b == 0.0 && a.to_bits() != b.to_bits() {
|
||||
0.0
|
||||
} else if a >= b {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChestRenderer.submit` and `ChestModel.setupAnim`: the lid and lock
|
||||
/// `xRot` for a render-state openness.
|
||||
pub fn chest_lid_x_rot(open: f32) -> f32 {
|
||||
let open = 1.0 - open;
|
||||
let open = 1.0 - open * open * open;
|
||||
-(open * std::f32::consts::FRAC_PI_2)
|
||||
}
|
||||
|
||||
/// `EnchantingTableBlockEntity` book fields.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct EnchantingBook {
|
||||
pub time: i32,
|
||||
pub flip: f32,
|
||||
pub o_flip: f32,
|
||||
pub flip_t: f32,
|
||||
pub flip_a: f32,
|
||||
pub open: f32,
|
||||
pub o_open: f32,
|
||||
pub rot: f32,
|
||||
pub o_rot: f32,
|
||||
pub t_rot: f32,
|
||||
}
|
||||
|
||||
/// The `while (a >= PI) a -= 2PI; while (a < -PI) a += 2PI` loops.
|
||||
fn wrap_pi(mut a: f32) -> f32 {
|
||||
use std::f32::consts::PI;
|
||||
while a >= PI {
|
||||
a -= 2.0 * PI;
|
||||
}
|
||||
while a < -PI {
|
||||
a += 2.0 * PI;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// `Mth.floor(float)`.
|
||||
fn mth_floor(v: f32) -> i32 {
|
||||
let i = v as i32;
|
||||
if v < i as f32 { i - 1 } else { i }
|
||||
}
|
||||
|
||||
/// `Mth.frac(float)`.
|
||||
pub fn mth_frac(v: f32) -> f32 {
|
||||
v - mth_floor(v) as f32
|
||||
}
|
||||
|
||||
/// `EnchantTableRenderState` (`EnchantTableRenderer.extractRenderState`) and
|
||||
/// the `BookModel.State` its `submit` builds.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct BookRender {
|
||||
pub flip: f32,
|
||||
pub open: f32,
|
||||
pub time: f32,
|
||||
pub y_rot: f32,
|
||||
/// `BookModel.State.forAnimation`: openness, pageFlip1, pageFlip2.
|
||||
pub openness: f32,
|
||||
pub page_flip1: f32,
|
||||
pub page_flip2: f32,
|
||||
}
|
||||
|
||||
impl EnchantingBook {
|
||||
/// `bookAnimationTick`. `players` are the feet positions of the level's
|
||||
/// non-spectator players (`getNearestPlayer(centre, 3.0, false)`);
|
||||
/// `random` is the block entity class's shared static `RANDOM`.
|
||||
pub fn tick(&mut self, pos: [i32; 3], players: &[[f64; 3]], random: &mut impl RandomSource) {
|
||||
self.o_open = self.open;
|
||||
self.o_rot = self.rot;
|
||||
let c = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
let mut best = -1.0;
|
||||
let mut nearest = None;
|
||||
for p in players {
|
||||
let (dx, dy, dz) = (p[0] - c[0], p[1] - c[1], p[2] - c[2]);
|
||||
let dist = dx * dx + dy * dy + dz * dz;
|
||||
if dist < 9.0 && (best == -1.0 || dist < best) {
|
||||
best = dist;
|
||||
nearest = Some(*p);
|
||||
}
|
||||
}
|
||||
if let Some(p) = nearest {
|
||||
let xd = p[0] - c[0];
|
||||
let zd = p[2] - c[2];
|
||||
self.t_rot = trig::atan2(zd, xd) as f32;
|
||||
self.open += 0.1;
|
||||
if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 {
|
||||
let old = self.flip_t;
|
||||
loop {
|
||||
let a = random.next_int_bound(4).unwrap_or(0);
|
||||
let b = random.next_int_bound(4).unwrap_or(0);
|
||||
self.flip_t += (a - b) as f32;
|
||||
if old != self.flip_t {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.t_rot += 0.02;
|
||||
self.open -= 0.1;
|
||||
}
|
||||
self.rot = wrap_pi(self.rot);
|
||||
self.t_rot = wrap_pi(self.t_rot);
|
||||
let dir = wrap_pi(self.t_rot - self.rot);
|
||||
self.rot += dir * 0.4;
|
||||
self.open = self.open.clamp(0.0, 1.0);
|
||||
self.time += 1;
|
||||
self.o_flip = self.flip;
|
||||
let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2);
|
||||
self.flip_a += (diff - self.flip_a) * 0.9;
|
||||
self.flip += self.flip_a;
|
||||
}
|
||||
/// `EnchantTableRenderer.extractRenderState` and the book state of its
|
||||
/// `submit`.
|
||||
pub fn render(&self, a: f32) -> BookRender {
|
||||
let flip = self.o_flip + a * (self.flip - self.o_flip);
|
||||
let open = self.o_open + a * (self.open - self.o_open);
|
||||
let time = self.time as f32 + a;
|
||||
let y_rot = self.o_rot + wrap_pi(self.rot - self.o_rot) * a;
|
||||
let ff1 = mth_frac(flip + 0.25) * 1.6 - 0.3;
|
||||
let ff2 = mth_frac(flip + 0.75) * 1.6 - 0.3;
|
||||
BookRender {
|
||||
flip,
|
||||
open,
|
||||
time,
|
||||
y_rot,
|
||||
openness: ((time * 0.02).msin() * 0.1 + 1.25) * open,
|
||||
page_flip1: ff1.clamp(0.0, 1.0),
|
||||
page_flip2: ff2.clamp(0.0, 1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ShulkerBoxBlockEntity.AnimationStatus`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ShulkerStatus {
|
||||
#[default]
|
||||
Closed,
|
||||
Opening,
|
||||
Opened,
|
||||
Closing,
|
||||
}
|
||||
|
||||
/// `ShulkerBoxBlockEntity` lid state.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Shulker {
|
||||
pub open_count: i32,
|
||||
pub status: ShulkerStatus,
|
||||
pub progress: f32,
|
||||
pub progress_old: f32,
|
||||
}
|
||||
|
||||
/// Side effects of one [`Shulker::tick`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShulkerTick {
|
||||
/// `doNeighborUpdates` calls (shape and neighbour updates around the box).
|
||||
pub neighbor_updates: u32,
|
||||
/// `moveCollidedEntities`: the swept lid box (min x, y, z, max x, y, z);
|
||||
/// entities in it move out along the facing.
|
||||
pub push: Option<[f64; 6]>,
|
||||
}
|
||||
|
||||
/// `Shulker.getProgressDeltaAabb(size, direction, from, to, position)`.
|
||||
pub fn progress_delta_aabb(
|
||||
size: f32,
|
||||
direction: u8,
|
||||
from: f32,
|
||||
to: f32,
|
||||
position: [f64; 3],
|
||||
) -> [f64; 6] {
|
||||
let size_d = f64::from(size);
|
||||
let mut b = [
|
||||
-size_d * 0.5,
|
||||
0.0,
|
||||
-size_d * 0.5,
|
||||
size_d * 0.5,
|
||||
size_d,
|
||||
size_d * 0.5,
|
||||
];
|
||||
let max = f64::from(from.max(to));
|
||||
let min = f64::from(from.min(to));
|
||||
let s = step(direction);
|
||||
for axis in 0..3 {
|
||||
// expandTowards
|
||||
let a = f64::from(s[axis]) * max * size_d;
|
||||
if a < 0.0 {
|
||||
b[axis] += a;
|
||||
} else if a > 0.0 {
|
||||
b[axis + 3] += a;
|
||||
}
|
||||
}
|
||||
for axis in 0..3 {
|
||||
// contract
|
||||
let a = -f64::from(s[axis]) * (1.0 + min) * size_d;
|
||||
if a < 0.0 {
|
||||
b[axis] -= a;
|
||||
} else if a > 0.0 {
|
||||
b[axis + 3] -= a;
|
||||
}
|
||||
}
|
||||
// new AABB keeps min <= max; then move to the position.
|
||||
let mut out = [0.0; 6];
|
||||
for axis in 0..3 {
|
||||
out[axis] = b[axis].min(b[axis + 3]) + position[axis];
|
||||
out[axis + 3] = b[axis].max(b[axis + 3]) + position[axis];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Shulker {
|
||||
/// `triggerEvent(1, openCount)`.
|
||||
pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool {
|
||||
if b0 != 1 {
|
||||
return false;
|
||||
}
|
||||
self.open_count = b1;
|
||||
if b1 == 0 {
|
||||
self.status = ShulkerStatus::Closing;
|
||||
}
|
||||
if b1 == 1 {
|
||||
self.status = ShulkerStatus::Opening;
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `startOpen`/`stopOpen` for a non-spectator user: the new open count to
|
||||
/// send as block event 1, and whether this was the first opener (open) or
|
||||
/// the last closer (close), which play the sound and game event.
|
||||
pub fn start_open(&mut self) -> (i32, bool) {
|
||||
if self.open_count < 0 {
|
||||
self.open_count = 0;
|
||||
}
|
||||
self.open_count += 1;
|
||||
(self.open_count, self.open_count == 1)
|
||||
}
|
||||
pub fn stop_open(&mut self) -> (i32, bool) {
|
||||
self.open_count -= 1;
|
||||
(self.open_count, self.open_count <= 0)
|
||||
}
|
||||
/// `updateAnimation` (`ShulkerBoxBlockEntity.tick`); `facing` is the
|
||||
/// block's facing as a 3D data value.
|
||||
pub fn tick(&mut self, pos: [i32; 3], facing: u8) -> ShulkerTick {
|
||||
let mut out = ShulkerTick::default();
|
||||
self.progress_old = self.progress;
|
||||
match self.status {
|
||||
ShulkerStatus::Closed => self.progress = 0.0,
|
||||
ShulkerStatus::Opening => {
|
||||
self.progress += 0.1;
|
||||
if self.progress_old == 0.0 {
|
||||
out.neighbor_updates += 1;
|
||||
}
|
||||
if self.progress >= 1.0 {
|
||||
self.status = ShulkerStatus::Opened;
|
||||
self.progress = 1.0;
|
||||
out.neighbor_updates += 1;
|
||||
}
|
||||
let bottom = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
out.push = Some(progress_delta_aabb(
|
||||
1.0,
|
||||
facing,
|
||||
self.progress_old,
|
||||
self.progress,
|
||||
bottom,
|
||||
));
|
||||
}
|
||||
ShulkerStatus::Opened => self.progress = 1.0,
|
||||
ShulkerStatus::Closing => {
|
||||
self.progress -= 0.1;
|
||||
if self.progress_old == 1.0 {
|
||||
out.neighbor_updates += 1;
|
||||
}
|
||||
if self.progress <= 0.0 {
|
||||
self.status = ShulkerStatus::Closed;
|
||||
self.progress = 0.0;
|
||||
out.neighbor_updates += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`.
|
||||
pub fn get_progress(&self, a: f32) -> f32 {
|
||||
self.progress_old + a * (self.progress - self.progress_old)
|
||||
}
|
||||
/// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room
|
||||
/// (`level.noCollision` of the half-block lid box, deflated by 1e-6).
|
||||
pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] {
|
||||
let bottom = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
let mut b = progress_delta_aabb(1.0, facing, 0.0, 0.5, bottom);
|
||||
for axis in 0..3 {
|
||||
b[axis] += 1.0e-6;
|
||||
b[axis + 3] -= 1.0e-6;
|
||||
}
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
/// What the bell's tick asks about an entity it gathered when rung.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct BellEntity {
|
||||
pub position: [f64; 3],
|
||||
/// `isAlive() && !isRemoved()`.
|
||||
pub alive: bool,
|
||||
/// In `EntityTypeTags.RAIDERS`.
|
||||
pub raider: bool,
|
||||
}
|
||||
|
||||
/// `BellBlockEntity`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Bell {
|
||||
pub ticks: i32,
|
||||
pub shaking: bool,
|
||||
/// `clickDirection` as a 3D data value.
|
||||
pub click_direction: Option<u8>,
|
||||
pub last_ring_timestamp: i64,
|
||||
/// `nearbyEntities`: the living entities around the bell when it was last
|
||||
/// gathered, as caller-defined handles.
|
||||
pub nearby: Option<Vec<u64>>,
|
||||
pub resonating: bool,
|
||||
pub resonation_ticks: i32,
|
||||
}
|
||||
|
||||
/// Side effects of one [`Bell::tick`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BellTick {
|
||||
/// Resonation started: `BELL_RESONATE` (played by the server).
|
||||
pub resonate: bool,
|
||||
/// Resonation ended (`ResonationEndAction`): the client's
|
||||
/// `showBellParticles` entity-effect particles (position and colour) and
|
||||
/// the server's `makeRaidersGlow` targets.
|
||||
pub ended: Option<(Vec<([f64; 3], i32)>, Vec<u64>)>,
|
||||
}
|
||||
|
||||
fn closer_to_center_than(pos: [i32; 3], p: [f64; 3], distance: f64) -> bool {
|
||||
let dx = f64::from(pos[0]) + 0.5 - p[0];
|
||||
let dy = f64::from(pos[1]) + 0.5 - p[1];
|
||||
let dz = f64::from(pos[2]) + 0.5 - p[2];
|
||||
dx * dx + dy * dy + dz * dz < distance * distance
|
||||
}
|
||||
|
||||
impl Bell {
|
||||
/// `triggerEvent(1, direction)`. `gather` lists the living entities whose
|
||||
/// position is inside the bell's block box inflated by 48
|
||||
/// (`updateEntities`, refreshed at most every 60 ticks).
|
||||
pub fn trigger_event(
|
||||
&mut self,
|
||||
b0: i32,
|
||||
b1: i32,
|
||||
game_time: i64,
|
||||
gather: impl FnOnce() -> Vec<u64>,
|
||||
) -> bool {
|
||||
if b0 != 1 {
|
||||
return false;
|
||||
}
|
||||
if game_time > self.last_ring_timestamp + 60 || self.nearby.is_none() {
|
||||
self.last_ring_timestamp = game_time;
|
||||
self.nearby = Some(gather());
|
||||
}
|
||||
self.resonation_ticks = 0;
|
||||
self.click_direction = Some(from_3d_data_value(b1));
|
||||
self.ticks = 0;
|
||||
self.shaking = true;
|
||||
true
|
||||
}
|
||||
/// `BellBlockEntity.tick` with the client's resonation end action.
|
||||
pub fn tick(&mut self, pos: [i32; 3], entity: impl Fn(u64) -> Option<BellEntity>) -> BellTick {
|
||||
let mut out = BellTick::default();
|
||||
if self.shaking {
|
||||
self.ticks += 1;
|
||||
}
|
||||
if self.ticks >= 50 {
|
||||
self.shaking = false;
|
||||
self.ticks = 0;
|
||||
}
|
||||
let nearby = self.nearby.clone().unwrap_or_default();
|
||||
let raider_in = |e: &BellEntity, distance: f64| {
|
||||
e.alive && closer_to_center_than(pos, e.position, distance) && e.raider
|
||||
};
|
||||
if self.ticks >= 5
|
||||
&& self.resonation_ticks == 0
|
||||
&& nearby
|
||||
.iter()
|
||||
.filter_map(|&h| entity(h))
|
||||
.any(|e| raider_in(&e, 32.0))
|
||||
{
|
||||
self.resonating = true;
|
||||
out.resonate = true;
|
||||
}
|
||||
if self.resonating {
|
||||
if self.resonation_ticks < 40 {
|
||||
self.resonation_ticks += 1;
|
||||
} else {
|
||||
// showBellParticles / makeRaidersGlow.
|
||||
let mut color = 16_700_985;
|
||||
let views: Vec<(u64, BellEntity)> = nearby
|
||||
.iter()
|
||||
.filter_map(|&h| Some((h, entity(h)?)))
|
||||
.collect();
|
||||
let count = views
|
||||
.iter()
|
||||
.filter(|(_, e)| closer_to_center_than(pos, e.position, 48.0))
|
||||
.count() as i32;
|
||||
let per = ((count - 21) / -2).clamp(3, 15);
|
||||
let mut particles = Vec::new();
|
||||
let mut glow = Vec::new();
|
||||
for (h, e) in &views {
|
||||
if !raider_in(e, 48.0) {
|
||||
continue;
|
||||
}
|
||||
glow.push(*h);
|
||||
let (bx, bz) = (f64::from(pos[0]), f64::from(pos[2]));
|
||||
let dist = ((e.position[0] - bx) * (e.position[0] - bx)
|
||||
+ (e.position[2] - bz) * (e.position[2] - bz))
|
||||
.sqrt();
|
||||
let x3 = bx + f64::from(0.5f32) + 1.0 / dist * (e.position[0] - bx);
|
||||
let z3 = bz + f64::from(0.5f32) + 1.0 / dist * (e.position[2] - bz);
|
||||
for _ in 0..per {
|
||||
color += 5;
|
||||
particles.push(([x3, f64::from(pos[1]) + 0.5, z3], color));
|
||||
}
|
||||
}
|
||||
out.ended = Some((particles, glow));
|
||||
self.resonating = false;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The conduit's `destroyTarget` as the client sees it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ConduitTarget {
|
||||
pub position: [f64; 3],
|
||||
pub eye_y: f64,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
/// `ConduitBlockEntity` (client side).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Conduit {
|
||||
pub tick_count: i32,
|
||||
pub active_rotation: f32,
|
||||
pub is_active: bool,
|
||||
pub is_hunting: bool,
|
||||
pub effect_blocks: Vec<[i32; 3]>,
|
||||
}
|
||||
|
||||
/// One nautilus particle: position and velocity.
|
||||
pub type Particle = ([f64; 3], [f64; 3]);
|
||||
|
||||
impl Conduit {
|
||||
/// `updateShape`: water all around, then the frame blocks
|
||||
/// (`BlockTags.CONDUIT_EFFECT_BLOCK`) in the three 5x5 rings.
|
||||
fn update_shape(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
is_water: &impl Fn([i32; 3]) -> bool,
|
||||
is_frame: &impl Fn([i32; 3]) -> bool,
|
||||
) -> bool {
|
||||
self.effect_blocks.clear();
|
||||
for ox in -1..=1 {
|
||||
for oy in -1..=1 {
|
||||
for oz in -1..=1 {
|
||||
if !is_water([pos[0] + ox, pos[1] + oy, pos[2] + oz]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for ox in -2i32..=2 {
|
||||
for oy in -2i32..=2 {
|
||||
for oz in -2i32..=2 {
|
||||
let (ax, ay, az) = (ox.abs(), oy.abs(), oz.abs());
|
||||
if (ax > 1 || ay > 1 || az > 1)
|
||||
&& (ox == 0 && (ay == 2 || az == 2)
|
||||
|| oy == 0 && (ax == 2 || az == 2)
|
||||
|| oz == 0 && (ax == 2 || ay == 2))
|
||||
{
|
||||
let p = [pos[0] + ox, pos[1] + oy, pos[2] + oz];
|
||||
if is_frame(p) {
|
||||
self.effect_blocks.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.effect_blocks.len() >= 16
|
||||
}
|
||||
/// `ConduitBlockEntity.clientTick`: returns the nautilus particles of
|
||||
/// `animationTick`, drawn from the client level's random.
|
||||
pub fn client_tick(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
game_time: i64,
|
||||
is_water: impl Fn([i32; 3]) -> bool,
|
||||
is_frame: impl Fn([i32; 3]) -> bool,
|
||||
target: Option<ConduitTarget>,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Vec<Particle> {
|
||||
self.tick_count += 1;
|
||||
if game_time % 40 == 0 {
|
||||
self.is_active = self.update_shape(pos, &is_water, &is_frame);
|
||||
self.is_hunting = self.effect_blocks.len() >= 42;
|
||||
}
|
||||
let particles = self.animation_tick(pos, target, random);
|
||||
if self.is_active {
|
||||
self.active_rotation += 1.0;
|
||||
}
|
||||
particles
|
||||
}
|
||||
fn animation_tick(
|
||||
&self,
|
||||
pos: [i32; 3],
|
||||
target: Option<ConduitTarget>,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Vec<Particle> {
|
||||
let mut out = Vec::new();
|
||||
let hh = f64::from(((self.tick_count + 35) as f32 * 0.1).msin() / 2.0 + 0.5);
|
||||
let hh = (hh * hh + hh) * f64::from(0.3f32);
|
||||
let end = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 1.5 + hh,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
for p in &self.effect_blocks {
|
||||
if random.next_int_bound(50).unwrap_or(1) == 0 {
|
||||
let dx = -0.5 + random.next_float() + (p[0] - pos[0]) as f32;
|
||||
let dy = -2.0 + random.next_float() + (p[1] - pos[1]) as f32;
|
||||
let dz = -0.5 + random.next_float() + (p[2] - pos[2]) as f32;
|
||||
out.push((end, [f64::from(dx), f64::from(dy), f64::from(dz)]));
|
||||
}
|
||||
}
|
||||
if let Some(t) = target {
|
||||
let randx = (-0.5 + random.next_float()) * (3.0 + t.width);
|
||||
let randy = -1.0 + random.next_float() * t.height;
|
||||
let randz = (-0.5 + random.next_float()) * (3.0 + t.width);
|
||||
out.push((
|
||||
[t.position[0], t.eye_y, t.position[2]],
|
||||
[f64::from(randx), f64::from(randy), f64::from(randz)],
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Skull {
|
||||
pub animating: bool,
|
||||
pub tick_count: i32,
|
||||
}
|
||||
impl Skull {
|
||||
/// `SkullBlockEntity.animation`.
|
||||
pub fn tick(&mut self, powered: bool) {
|
||||
if powered {
|
||||
self.animating = true;
|
||||
self.tick_count += 1;
|
||||
} else {
|
||||
self.animating = false;
|
||||
}
|
||||
}
|
||||
/// `getAnimation(a)`.
|
||||
pub fn get_animation(&self, a: f32) -> f32 {
|
||||
if self.animating {
|
||||
self.tick_count as f32 + a
|
||||
} else {
|
||||
self.tick_count as f32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `DecoratedPotBlockEntity.WobbleStyle`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WobbleStyle {
|
||||
Positive,
|
||||
Negative,
|
||||
}
|
||||
impl WobbleStyle {
|
||||
pub fn duration(self) -> i32 {
|
||||
match self {
|
||||
Self::Positive => 7,
|
||||
Self::Negative => 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `DecoratedPotBlockEntity` wobble fields.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct PotWobble {
|
||||
pub started_at: i64,
|
||||
pub style: Option<WobbleStyle>,
|
||||
}
|
||||
impl PotWobble {
|
||||
/// `triggerEvent(1, style)`.
|
||||
pub fn trigger_event(&mut self, event: i32, data: i32, game_time: i64) -> bool {
|
||||
if event == 1 && (0..2).contains(&data) {
|
||||
self.started_at = game_time;
|
||||
self.style = Some(if data == 0 {
|
||||
WobbleStyle::Positive
|
||||
} else {
|
||||
WobbleStyle::Negative
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// `DecoratedPotRenderer.extractRenderState`'s `wobbleProgress`.
|
||||
pub fn progress(&self, game_time: i64, partial: f32) -> f32 {
|
||||
match self.style {
|
||||
Some(style) => {
|
||||
((game_time - self.started_at) as f32 + partial) / style.duration() as f32
|
||||
}
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The client ticker a block entity runs (`getTicker` on a client level),
|
||||
/// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Ticker {
|
||||
/// `ChestBlockEntity` / `EnderChestBlockEntity.lidAnimateTick`.
|
||||
Lid,
|
||||
/// `EnchantingTableBlockEntity.bookAnimationTick`.
|
||||
Book,
|
||||
/// `ShulkerBoxBlockEntity.tick`, with the box's facing.
|
||||
Shulker {
|
||||
facing: u8,
|
||||
},
|
||||
/// `BellBlockEntity.clientTick`.
|
||||
Bell,
|
||||
/// `ConduitBlockEntity.clientTick`.
|
||||
Conduit,
|
||||
/// `SkullBlockEntity.animation` (dragon and piglin heads only).
|
||||
Skull {
|
||||
powered: bool,
|
||||
},
|
||||
Pot,
|
||||
}
|
||||
|
||||
/// The [`Ticker`] of a block state, by block name and property lookup.
|
||||
pub fn ticker(name: &str, prop: impl Fn(&str) -> Option<String>) -> Option<Ticker> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
let unwaxed = name.strip_prefix("waxed_").unwrap_or(name);
|
||||
Some(match unwaxed {
|
||||
"chest"
|
||||
| "trapped_chest"
|
||||
| "ender_chest"
|
||||
| "copper_chest"
|
||||
| "exposed_copper_chest"
|
||||
| "weathered_copper_chest"
|
||||
| "oxidized_copper_chest" => Ticker::Lid,
|
||||
"enchanting_table" => Ticker::Book,
|
||||
"bell" => Ticker::Bell,
|
||||
"conduit" => Ticker::Conduit,
|
||||
"decorated_pot" => Ticker::Pot,
|
||||
"dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull {
|
||||
powered: prop("powered").as_deref() == Some("true"),
|
||||
},
|
||||
n if n.ends_with("shulker_box") => Ticker::Shulker {
|
||||
facing: prop("facing")
|
||||
.as_deref()
|
||||
.and_then(direction_index)
|
||||
.unwrap_or(1),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The animated block entities of a level, by position.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BlockEntityAnims {
|
||||
pub chests: HashMap<[i32; 3], ChestLid>,
|
||||
pub books: HashMap<[i32; 3], EnchantingBook>,
|
||||
/// `EnchantingTableBlockEntity.RANDOM`, shared by every table.
|
||||
pub book_random: LegacyRandom,
|
||||
pub shulkers: HashMap<[i32; 3], Shulker>,
|
||||
pub bells: HashMap<[i32; 3], Bell>,
|
||||
pub conduits: HashMap<[i32; 3], Conduit>,
|
||||
pub skulls: HashMap<[i32; 3], Skull>,
|
||||
pub pots: HashMap<[i32; 3], PotWobble>,
|
||||
/// The client level's random (conduit particles).
|
||||
pub random: LegacyRandom,
|
||||
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
|
||||
pub kinds: Vec<Option<Ticker>>,
|
||||
}
|
||||
impl Default for BlockEntityAnims {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
chests: HashMap::new(),
|
||||
books: HashMap::new(),
|
||||
book_random: LegacyRandom::new(0x626f6f6b),
|
||||
shulkers: HashMap::new(),
|
||||
bells: HashMap::new(),
|
||||
conduits: HashMap::new(),
|
||||
skulls: HashMap::new(),
|
||||
pots: HashMap::new(),
|
||||
random: LegacyRandom::new(0x6c6576656c),
|
||||
kinds: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl BlockEntityAnims {
|
||||
/// Fills [`Self::kinds`] for every state of the registry.
|
||||
pub fn classify(&mut self, registry: &horizon_world::registry::BlockRegistry) {
|
||||
self.kinds = (0..registry.len() as u32)
|
||||
.map(|id| {
|
||||
registry
|
||||
.state(horizon_world::registry::BlockStateId(id))
|
||||
.and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned()))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
/// The ticker of a block state.
|
||||
pub fn ticker(&self, state: u32) -> Option<Ticker> {
|
||||
self.kinds.get(state as usize).copied().flatten()
|
||||
}
|
||||
/// Drops the state of block entities that are gone or changed kind:
|
||||
/// `present` maps the loaded block entities to their tickers.
|
||||
pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) {
|
||||
let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f);
|
||||
self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid));
|
||||
self.books.retain(|p, _| is(p, |t| *t == Ticker::Book));
|
||||
self.shulkers
|
||||
.retain(|p, _| is(p, |t| matches!(t, Ticker::Shulker { .. })));
|
||||
self.bells.retain(|p, _| is(p, |t| *t == Ticker::Bell));
|
||||
self.conduits
|
||||
.retain(|p, _| is(p, |t| *t == Ticker::Conduit));
|
||||
self.skulls
|
||||
.retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. })));
|
||||
self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot));
|
||||
}
|
||||
/// Drops the state of positions whose block entity is gone.
|
||||
pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) {
|
||||
self.chests.retain(|p, _| keep(*p));
|
||||
self.books.retain(|p, _| keep(*p));
|
||||
self.shulkers.retain(|p, _| keep(*p));
|
||||
self.bells.retain(|p, _| keep(*p));
|
||||
self.conduits.retain(|p, _| keep(*p));
|
||||
self.skulls.retain(|p, _| keep(*p));
|
||||
self.pots.retain(|p, _| keep(*p));
|
||||
}
|
||||
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
|
||||
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
self.chests
|
||||
.get(&pos)
|
||||
.map_or(0.0, |l| l.get_openness(partial))
|
||||
}
|
||||
/// The renderer's view of the block entity at `pos`; `sherds` are the
|
||||
/// pot's decorations (back, left, right, front), when it is a pot.
|
||||
pub fn block_anim(
|
||||
&self,
|
||||
pos: [i32; 3],
|
||||
game_time: i64,
|
||||
partial: f32,
|
||||
sherds: [Option<String>; 4],
|
||||
) -> BlockAnim {
|
||||
let mut anim = BlockAnim {
|
||||
sherds,
|
||||
// End gateway ages and cooldowns are not tracked on the client yet:
|
||||
// gateways render settled (no beam).
|
||||
gateway: (i64::MAX, 0),
|
||||
..BlockAnim::default()
|
||||
};
|
||||
if let Some(b) = self.books.get(&pos) {
|
||||
anim.book = *b;
|
||||
}
|
||||
if let Some(s) = self.shulkers.get(&pos) {
|
||||
anim.shulker = (s.progress, s.progress_old);
|
||||
}
|
||||
if let Some(b) = self.bells.get(&pos) {
|
||||
anim.bell_ticks = b.ticks;
|
||||
anim.bell_shake = b
|
||||
.shaking
|
||||
.then_some(b.click_direction)
|
||||
.flatten()
|
||||
.map(|d| DIRECTIONS[usize::from(d)]);
|
||||
}
|
||||
if let Some(c) = self.conduits.get(&pos) {
|
||||
anim.conduit = (c.tick_count, c.is_active, c.is_hunting, c.active_rotation);
|
||||
}
|
||||
if let Some(s) = self.skulls.get(&pos) {
|
||||
anim.skull = (s.animating, s.tick_count);
|
||||
}
|
||||
if let Some(w) = self.pots.get(&pos)
|
||||
&& w.style.is_some()
|
||||
{
|
||||
// extractRenderState never copies lastWobbleStyle into the render
|
||||
// state, so DecoratedPotRenderer.submit always takes the
|
||||
// non-POSITIVE branch (with the style's own duration).
|
||||
anim.wobble = Some((false, w.progress(game_time, partial)));
|
||||
}
|
||||
anim
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,22 @@
|
||||
//! Block-entity renderers (`BlockEntityRenderers`): chests (single, double,
|
||||
//! trapped, ender, copper), shulker boxes, banners, skulls and heads, bells,
|
||||
//! decorated pots, conduits, enchanting-table and lectern books and copper
|
||||
//! golem statues. Models are vanilla's baked `LayerDefinitions` layers
|
||||
//! golem statues, End portals and End gateways. Models are vanilla's baked `LayerDefinitions` layers
|
||||
//! (`entity-models.json`); transforms, animation and textures follow each
|
||||
//! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at
|
||||
//! the block plus `minecraft_mix_light` with the level's two diffuse lights.
|
||||
use crate::{hud::Rect, mesher::Vertex, world::World};
|
||||
use glam::{DVec3, Mat4, Quat, Vec3};
|
||||
use horizon_core::{
|
||||
geometry::trig::Mth,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
use horizon_core::geometry::{
|
||||
Direction,
|
||||
trig::{self, Mth},
|
||||
};
|
||||
use horizon_world::{
|
||||
block_render::FaceVisibility,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
};
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, f32::consts::PI, path::Path};
|
||||
use std::{collections::HashMap, f32::consts::PI, path::Path, sync::Mutex};
|
||||
|
||||
/// One baked `ModelPart`: initial pose, textured polygons (pixel units,
|
||||
/// normalized UVs) and named children.
|
||||
@@ -256,6 +259,8 @@ enum SkullType {
|
||||
enum Kind {
|
||||
None,
|
||||
Chest {
|
||||
/// The block (`neighbourState.is(state.getBlock())`).
|
||||
block: String,
|
||||
texture: &'static str,
|
||||
part: ChestPart,
|
||||
y_rot: f32,
|
||||
@@ -289,6 +294,12 @@ enum Kind {
|
||||
pose: &'static str,
|
||||
facing: &'static str,
|
||||
},
|
||||
/// `TheEndPortalRenderer`: the top and bottom faces of a 6/16-tall slab.
|
||||
EndPortal,
|
||||
/// `TheEndGatewayRenderer`: the visible faces of the cube and the beam.
|
||||
EndGateway {
|
||||
state: u32,
|
||||
},
|
||||
/// Sign text (`StandingSignRenderer` / `HangingSignRenderer`); the boards are block models.
|
||||
Sign {
|
||||
hanging: bool,
|
||||
@@ -323,6 +334,7 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Kind {
|
||||
ChestPart::Right => Some(step(opposite(clockwise(facing)))),
|
||||
};
|
||||
Kind::Chest {
|
||||
block: name.to_owned(),
|
||||
texture: match part {
|
||||
ChestPart::Single => texture,
|
||||
ChestPart::Left => left,
|
||||
@@ -413,6 +425,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Kind {
|
||||
};
|
||||
}
|
||||
"conduit" => return Kind::Conduit,
|
||||
"end_portal" => return Kind::EndPortal,
|
||||
"end_gateway" => return Kind::EndGateway { state: 0 },
|
||||
"enchanting_table" => return Kind::EnchantingTable,
|
||||
"lectern" => {
|
||||
return if prop("has_book").as_deref() == Some("true") {
|
||||
@@ -512,72 +526,6 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Kind {
|
||||
Kind::None
|
||||
}
|
||||
|
||||
/// `EnchantingTableBlockEntity` book animation state.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Book {
|
||||
time: i32,
|
||||
flip: f32,
|
||||
o_flip: f32,
|
||||
flip_t: f32,
|
||||
flip_a: f32,
|
||||
open: f32,
|
||||
o_open: f32,
|
||||
rot: f32,
|
||||
o_rot: f32,
|
||||
t_rot: f32,
|
||||
}
|
||||
fn wrap(mut a: f32) -> f32 {
|
||||
while a >= PI {
|
||||
a -= 2.0 * PI;
|
||||
}
|
||||
while a < -PI {
|
||||
a += 2.0 * PI;
|
||||
}
|
||||
a
|
||||
}
|
||||
impl Book {
|
||||
/// `EnchantingTableBlockEntity.bookAnimationTick`.
|
||||
fn tick(&mut self, pos: [i32; 3], player: Option<[f64; 3]>, random: &mut LegacyRandom) {
|
||||
self.o_open = self.open;
|
||||
self.o_rot = self.rot;
|
||||
let c = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
let near = player.filter(|p| {
|
||||
(p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) < 9.0
|
||||
});
|
||||
if let Some(p) = near {
|
||||
self.t_rot = (p[2] - c[2]).atan2(p[0] - c[0]) as f32;
|
||||
self.open += 0.1;
|
||||
if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 {
|
||||
let old = self.flip_t;
|
||||
loop {
|
||||
let a = random.next_int_bound(4).unwrap_or(0);
|
||||
let b = random.next_int_bound(4).unwrap_or(0);
|
||||
self.flip_t += (a - b) as f32;
|
||||
if old != self.flip_t {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.t_rot += 0.02;
|
||||
self.open -= 0.1;
|
||||
}
|
||||
self.rot = wrap(self.rot);
|
||||
self.t_rot = wrap(self.t_rot);
|
||||
let dir = wrap(self.t_rot - self.rot);
|
||||
self.rot += dir * 0.4;
|
||||
self.open = self.open.clamp(0.0, 1.0);
|
||||
self.time += 1;
|
||||
self.o_flip = self.flip;
|
||||
let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2);
|
||||
self.flip_a += (diff - self.flip_a) * 0.9;
|
||||
self.flip += self.flip_a;
|
||||
}
|
||||
}
|
||||
/// `BookModel.setupAnim` for `BookModel.State(openness, pageFlip1, pageFlip2)`.
|
||||
fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) {
|
||||
move |name, p| match name {
|
||||
@@ -737,6 +685,10 @@ pub struct BlockAnim {
|
||||
pub sherds: [Option<String>; 4],
|
||||
/// `DecoratedPotRenderState` wobble style (positive) and progress.
|
||||
pub wobble: Option<(bool, f32)>,
|
||||
/// `EnchantingTableBlockEntity` book fields.
|
||||
pub book: crate::block_entity_anim::EnchantingBook,
|
||||
/// `TheEndGatewayBlockEntity` age and teleportCooldown.
|
||||
pub gateway: (i64, i32),
|
||||
}
|
||||
|
||||
/// One `submitText` call (`AbstractSignRenderer.submitSignText`).
|
||||
@@ -765,6 +717,8 @@ pub struct Scene<'a> {
|
||||
pub texts: Option<&'a std::cell::RefCell<Vec<TextCall>>>,
|
||||
pub partial: f32,
|
||||
pub game_time: i64,
|
||||
/// `Level.getMaxY` (End gateway beams while spawning).
|
||||
pub max_y: i32,
|
||||
pub world: &'a World,
|
||||
pub sprites: &'a HashMap<String, Rect>,
|
||||
pub nether: bool,
|
||||
@@ -781,10 +735,10 @@ pub struct Scene<'a> {
|
||||
pub struct BlockEntityRenderer {
|
||||
models: HashMap<&'static str, ModelPart>,
|
||||
kinds: Vec<Kind>,
|
||||
books: HashMap<[i32; 3], Book>,
|
||||
random: LegacyRandom,
|
||||
/// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`).
|
||||
pot_patterns: HashMap<String, String>,
|
||||
/// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock).
|
||||
visibility: Option<Mutex<FaceVisibility>>,
|
||||
}
|
||||
const MODELS: [(&str, &str); 27] = [
|
||||
("chest", "minecraft:chest#main"),
|
||||
@@ -835,6 +789,7 @@ impl BlockEntityRenderer {
|
||||
.filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v))))
|
||||
.collect();
|
||||
let mut renderer = Self::new(models, registry);
|
||||
renderer.visibility = Some(Mutex::new(crate::models::load_visibility(root, registry)?));
|
||||
// Sherd items: provides_pottery_pattern -> decorated_pot_pattern asset id.
|
||||
if let Ok(bytes) = std::fs::read(root.join("items.json")) {
|
||||
let items: Value = serde_json::from_slice(&bytes)?;
|
||||
@@ -864,16 +819,18 @@ impl BlockEntityRenderer {
|
||||
.map(|id| {
|
||||
registry.state(BlockStateId(id)).map_or(Kind::None, |s| {
|
||||
let prop = |k: &str| s.properties.get(k).cloned();
|
||||
classify(&s.name, &prop)
|
||||
match classify(&s.name, &prop) {
|
||||
Kind::EndGateway { .. } => Kind::EndGateway { state: id },
|
||||
kind => kind,
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
models,
|
||||
kinds,
|
||||
books: HashMap::new(),
|
||||
random: LegacyRandom::new(0x5EED_B00C),
|
||||
pot_patterns: HashMap::new(),
|
||||
visibility: None,
|
||||
}
|
||||
}
|
||||
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
|
||||
@@ -886,24 +843,6 @@ impl BlockEntityRenderer {
|
||||
fn kind(&self, state: u32) -> &Kind {
|
||||
self.kinds.get(state as usize).unwrap_or(&Kind::None)
|
||||
}
|
||||
/// Client-side block-entity ticks (enchanting-table books).
|
||||
pub fn tick<'a>(
|
||||
&mut self,
|
||||
blocks: impl Iterator<Item = &'a ([i32; 3], u32)>,
|
||||
player: Option<[f64; 3]>,
|
||||
) {
|
||||
let mut seen = Vec::new();
|
||||
for (pos, state) in blocks {
|
||||
if matches!(self.kind(*state), Kind::EnchantingTable) {
|
||||
seen.push(*pos);
|
||||
}
|
||||
}
|
||||
self.books.retain(|p, _| seen.contains(p));
|
||||
for pos in seen {
|
||||
let book = self.books.entry(pos).or_default();
|
||||
book.tick(pos, player, &mut self.random);
|
||||
}
|
||||
}
|
||||
pub fn render<'a>(
|
||||
&self,
|
||||
scene: &Scene,
|
||||
@@ -921,7 +860,13 @@ impl BlockEntityRenderer {
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
);
|
||||
if center.distance_squared(scene.camera) > VIEW_DISTANCE * VIEW_DISTANCE {
|
||||
// BlockEntityRenderer.getViewDistance: 256 for End gateways.
|
||||
let distance = if matches!(kind, Kind::EndGateway { .. }) {
|
||||
256.0
|
||||
} else {
|
||||
VIEW_DISTANCE
|
||||
};
|
||||
if center.distance_squared(scene.camera) > distance * distance {
|
||||
continue;
|
||||
}
|
||||
let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
|
||||
@@ -951,21 +896,65 @@ impl BlockEntityRenderer {
|
||||
pub fn renders(&self, state: u32) -> bool {
|
||||
!matches!(self.kind(state), Kind::None)
|
||||
}
|
||||
/// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`):
|
||||
/// time, flip, oFlip, open, oOpen, rot, oRot.
|
||||
pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) {
|
||||
let [flip, o_flip, open, o_open, rot, o_rot] = fields;
|
||||
let book = self.books.entry(pos).or_default();
|
||||
*book = Book {
|
||||
time,
|
||||
flip,
|
||||
o_flip,
|
||||
open,
|
||||
o_open,
|
||||
rot,
|
||||
o_rot,
|
||||
..*book
|
||||
/// `ChestRenderer.extractRenderState`'s openness for the chest of `state`
|
||||
/// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`)
|
||||
/// pairs a double half with its neighbour only when that is the same
|
||||
/// block, the other half and faces the same way; `opennessCombiner` then
|
||||
/// takes the more open of both. Also returns the paired half's position.
|
||||
/// `lid` is `getOpenNess(partial)` at a position; non-chests give 0.
|
||||
pub fn chest_openness_of(
|
||||
&self,
|
||||
pos: [i32; 3],
|
||||
state: u32,
|
||||
block_at: &dyn Fn([i32; 3]) -> u32,
|
||||
lid: &dyn Fn([i32; 3]) -> f32,
|
||||
) -> (f32, Option<[i32; 3]>) {
|
||||
self.chest_openness(pos, self.kind(state), block_at, lid)
|
||||
}
|
||||
fn chest_openness(
|
||||
&self,
|
||||
pos: [i32; 3],
|
||||
kind: &Kind,
|
||||
block_at: &dyn Fn([i32; 3]) -> u32,
|
||||
lid: &dyn Fn([i32; 3]) -> f32,
|
||||
) -> (f32, Option<[i32; 3]>) {
|
||||
let Kind::Chest {
|
||||
block,
|
||||
part,
|
||||
y_rot,
|
||||
double_with,
|
||||
..
|
||||
} = kind
|
||||
else {
|
||||
return (0.0, None);
|
||||
};
|
||||
let open = lid(pos);
|
||||
let Some(d) = double_with else {
|
||||
return (open, None);
|
||||
};
|
||||
let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]];
|
||||
match self.kind(block_at(other)) {
|
||||
Kind::Chest {
|
||||
block: other_block,
|
||||
part: other_part,
|
||||
y_rot: other_y_rot,
|
||||
..
|
||||
} if other_block == block
|
||||
&& *other_part != ChestPart::Single
|
||||
&& other_part != part
|
||||
&& other_y_rot == y_rot =>
|
||||
{
|
||||
let other_open = lid(other);
|
||||
// The right half is the first.
|
||||
let open = if *part == ChestPart::Right {
|
||||
crate::block_entity_anim::combined_openness(open, Some(other_open))
|
||||
} else {
|
||||
crate::block_entity_anim::combined_openness(other_open, Some(open))
|
||||
};
|
||||
(open, Some(other))
|
||||
}
|
||||
_ => (open, None),
|
||||
}
|
||||
}
|
||||
/// One block entity of `state` drawn under `base` (minecart contents).
|
||||
pub fn render_state(
|
||||
@@ -1060,7 +1049,7 @@ impl BlockEntityRenderer {
|
||||
texture,
|
||||
part,
|
||||
y_rot,
|
||||
double_with,
|
||||
..
|
||||
} => {
|
||||
let model = match part {
|
||||
ChestPart::Single => "chest",
|
||||
@@ -1070,22 +1059,24 @@ impl BlockEntityRenderer {
|
||||
let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else {
|
||||
return;
|
||||
};
|
||||
// ChestBlock.opennessCombiner / BrightnessCombiner: both halves.
|
||||
let mut open = (scene.lid)(pos);
|
||||
let (open, other) = self.chest_openness(
|
||||
pos,
|
||||
kind,
|
||||
&|p| scene.world.block(p[0], p[1], p[2]).0,
|
||||
scene.lid,
|
||||
);
|
||||
// BrightnessCombiner: the brighter of both halves, per channel.
|
||||
let mut packed = packed;
|
||||
if let Some(d) = double_with {
|
||||
let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]];
|
||||
open = open.max((scene.lid)(other));
|
||||
if let Some(other) = other {
|
||||
let l = scene.world.light(other[0], other[1], other[2]);
|
||||
packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15);
|
||||
}
|
||||
let open = 1.0 - (1.0 - open).powi(3);
|
||||
let m = base
|
||||
* around(
|
||||
Mat4::from_rotation_y((-y_rot).to_radians()),
|
||||
Vec3::new(0.5, 0.0, 0.5),
|
||||
);
|
||||
let lid = -(open * PI / 2.0);
|
||||
let lid = crate::block_entity_anim::chest_lid_x_rot(open);
|
||||
let adjust = move |name: &str, p: &mut [f32; 9]| {
|
||||
if name == "lid" || name == "lock" {
|
||||
p[3] = lid;
|
||||
@@ -1291,6 +1282,73 @@ impl BlockEntityRenderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::EndPortal => {
|
||||
// TheEndPortalRenderer.TRANSFORMATION: y from 6/16 to 12/16; only the
|
||||
// vertical faces (TheEndPortalBlockEntity.shouldRenderFace).
|
||||
let m = base
|
||||
* Mat4::from_translation(Vec3::new(0.0, 0.375, 0.0))
|
||||
* Mat4::from_scale(Vec3::new(1.0, 0.375, 1.0));
|
||||
portal_cube(m, &[Direction::Down, Direction::Up], END_PORTAL_LAYER, out);
|
||||
}
|
||||
Kind::EndGateway { state } => {
|
||||
let anim = (scene.anim)(pos);
|
||||
let (age, cooldown) = anim.gateway;
|
||||
// TheEndGatewayRenderer.extractRenderState.
|
||||
let spawning = age < 200;
|
||||
if spawning || cooldown > 0 {
|
||||
let a = scene.partial;
|
||||
let percent = if spawning {
|
||||
((age as f32 + a) / 200.0).clamp(0.0, 1.0)
|
||||
} else {
|
||||
1.0 - ((cooldown as f32 - a) / 40.0).clamp(0.0, 1.0)
|
||||
};
|
||||
let distance = if spawning {
|
||||
f64::from(scene.max_y)
|
||||
} else {
|
||||
50.0
|
||||
};
|
||||
let scale = trig::sin(f64::from(percent * PI));
|
||||
let height = (f64::from(scale) * distance).floor() as i32;
|
||||
// DyeColor.MAGENTA / PURPLE getTextureDiffuseColor.
|
||||
let color = if spawning { 0xC7_4EBD } else { 0x89_32B8 };
|
||||
let time = scene.game_time.rem_euclid(40) as f32 + a;
|
||||
if height > 0
|
||||
&& let Some(s) = sprite("entity/end_portal/end_gateway_beam")
|
||||
{
|
||||
beam(
|
||||
base,
|
||||
BeamShape {
|
||||
scale,
|
||||
time,
|
||||
start: -height,
|
||||
height: height * 2,
|
||||
color,
|
||||
solid_radius: 0.15,
|
||||
glow_radius: 0.175,
|
||||
},
|
||||
s,
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
// AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace.
|
||||
let faces: Vec<Direction> = Direction::ALL
|
||||
.into_iter()
|
||||
.filter(|&d| {
|
||||
let [dx, dy, dz] = d.normal();
|
||||
let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz);
|
||||
self.visibility.as_ref().is_none_or(|v| {
|
||||
v.lock()
|
||||
.map(|mut v| {
|
||||
v.should_render_face(BlockStateId(*state), neighbor, d, true)
|
||||
.unwrap_or(true)
|
||||
})
|
||||
.unwrap_or(true)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
portal_cube(base, &faces, END_GATEWAY_LAYER, out);
|
||||
}
|
||||
Kind::Conduit => {
|
||||
let (ticks, active, hunting, raw_rotation) = (scene.anim)(pos).conduit;
|
||||
// ConduitRenderer.extractRenderState.
|
||||
@@ -1363,21 +1421,18 @@ impl BlockEntityRenderer {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let b = self.books.get(&pos).copied().unwrap_or_default();
|
||||
let a = scene.partial;
|
||||
let flip = b.o_flip + (b.flip - b.o_flip) * a;
|
||||
let open = b.o_open + (b.open - b.o_open) * a;
|
||||
let time = b.time as f32 + a;
|
||||
let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a;
|
||||
// EnchantTableRenderer.extractRenderState and submit.
|
||||
let b = (scene.anim)(pos).book.render(scene.partial);
|
||||
let m = base
|
||||
* Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5))
|
||||
* Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0))
|
||||
* Mat4::from_rotation_y(-y_rot)
|
||||
* Mat4::from_translation(Vec3::new(
|
||||
0.0,
|
||||
0.1 + (b.time * 0.1).msin() * 0.01,
|
||||
0.0,
|
||||
))
|
||||
* Mat4::from_rotation_y(-b.y_rot)
|
||||
* Mat4::from_rotation_z(80f32.to_radians());
|
||||
let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0);
|
||||
let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0);
|
||||
// BookModel.State.forAnimation.
|
||||
let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open;
|
||||
let (openness, ff1, ff2) = (b.openness, b.page_flip1, b.page_flip2);
|
||||
draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out);
|
||||
}
|
||||
Kind::Lectern { y_rot } => {
|
||||
@@ -1438,8 +1493,7 @@ impl BlockEntityRenderer {
|
||||
/// rotating solid beam and its translucent glow, the last section 2048
|
||||
/// blocks tall. `origin` is the beacon block's corner relative to the camera,
|
||||
/// `time` the animation time (game time mod 40 plus partial tick) and `scale`
|
||||
/// the radius scale. The sprite's v range rides in the light bytes (the
|
||||
/// entity shader wraps v for layer 6).
|
||||
/// the radius scale.
|
||||
pub fn beacon_beam(
|
||||
origin: Vec3,
|
||||
sections: &[(u32, i32)],
|
||||
@@ -1448,9 +1502,7 @@ pub fn beacon_beam(
|
||||
s: Rect,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32;
|
||||
let wrap = q(s.v0) | q(s.v1 - s.v0) << 16;
|
||||
let o = origin + Vec3::new(0.5, 0.0, 0.5);
|
||||
let base = Mat4::from_translation(origin);
|
||||
let mut start = 0i32;
|
||||
for (i, &(color, height)) in sections.iter().enumerate() {
|
||||
let height = if i == sections.len() - 1 {
|
||||
@@ -1458,63 +1510,140 @@ pub fn beacon_beam(
|
||||
} else {
|
||||
height
|
||||
};
|
||||
let end = start + height;
|
||||
let scroll = if height < 0 { time } else { -time };
|
||||
let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor());
|
||||
let abgr =
|
||||
|a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255);
|
||||
// Solid beam: radius 0.2 * scale, rotated with time.
|
||||
let r = 0.2 * scale;
|
||||
let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians());
|
||||
let corners = [
|
||||
rot * Vec3::new(0.0, 0.0, r),
|
||||
rot * Vec3::new(r, 0.0, 0.0),
|
||||
rot * Vec3::new(-r, 0.0, 0.0),
|
||||
rot * Vec3::new(0.0, 0.0, -r),
|
||||
];
|
||||
let v2 = -1.0 + v_off;
|
||||
let v1 = height as f32 * (0.5 / r) + v2;
|
||||
beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap);
|
||||
// Glow: radius 0.25 * scale, translucent.
|
||||
let g = 0.25 * scale;
|
||||
let corners = [
|
||||
Vec3::new(-g, 0.0, -g),
|
||||
Vec3::new(g, 0.0, -g),
|
||||
Vec3::new(-g, 0.0, g),
|
||||
Vec3::new(g, 0.0, g),
|
||||
];
|
||||
let v1 = height as f32 + v2;
|
||||
beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap);
|
||||
start = end;
|
||||
let shape = BeamShape {
|
||||
scale: 1.0,
|
||||
time,
|
||||
start,
|
||||
height,
|
||||
color,
|
||||
solid_radius: 0.2 * scale,
|
||||
glow_radius: 0.25 * scale,
|
||||
};
|
||||
beam(base, shape, s, out);
|
||||
start += height;
|
||||
}
|
||||
}
|
||||
/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn beam_part(
|
||||
out: &mut Vec<Vertex>,
|
||||
o: Vec3,
|
||||
/// The arguments of `BeaconRenderer.submitBeaconBeam`.
|
||||
pub struct BeamShape {
|
||||
/// Scales the v range (End gateways shrink and grow their beam with it).
|
||||
pub scale: f32,
|
||||
/// Animation time: game time mod 40 plus the partial tick.
|
||||
pub time: f32,
|
||||
pub start: i32,
|
||||
pub height: i32,
|
||||
/// RGB.
|
||||
pub color: u32,
|
||||
pub solid_radius: f32,
|
||||
pub glow_radius: f32,
|
||||
}
|
||||
/// `BeaconRenderer.submitBeaconBeam` under `base` (the block's corner): the
|
||||
/// rotating solid beam and its translucent glow. The sprite's v range rides
|
||||
/// in the light bytes (the entity shader wraps v for layer 6).
|
||||
pub fn beam(base: Mat4, b: BeamShape, s: Rect, out: &mut Vec<Vertex>) {
|
||||
let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32;
|
||||
let wrap = q(s.v0) | q(s.v1 - s.v0) << 16;
|
||||
let color = b.color;
|
||||
let end = b.start + b.height;
|
||||
let scroll = if b.height < 0 { b.time } else { -b.time };
|
||||
let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor());
|
||||
let abgr =
|
||||
|a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255);
|
||||
// Solid beam, rotated with time.
|
||||
let r = b.solid_radius;
|
||||
let rot = glam::Mat3::from_rotation_y((b.time * 2.25 - 45.0).to_radians());
|
||||
let corners = [
|
||||
rot * Vec3::new(0.0, 0.0, r),
|
||||
rot * Vec3::new(r, 0.0, 0.0),
|
||||
rot * Vec3::new(-r, 0.0, 0.0),
|
||||
rot * Vec3::new(0.0, 0.0, -r),
|
||||
];
|
||||
let v2 = -1.0 + v_off;
|
||||
let v1 = b.height as f32 * b.scale * (0.5 / r) + v2;
|
||||
let part = BeamPart {
|
||||
base,
|
||||
start: b.start,
|
||||
end,
|
||||
s,
|
||||
wrap,
|
||||
};
|
||||
part.emit(out, corners, [v1, v2], abgr(255));
|
||||
// Glow, translucent.
|
||||
let g = b.glow_radius;
|
||||
let corners = [
|
||||
Vec3::new(-g, 0.0, -g),
|
||||
Vec3::new(g, 0.0, -g),
|
||||
Vec3::new(-g, 0.0, g),
|
||||
Vec3::new(g, 0.0, g),
|
||||
];
|
||||
let v1 = b.height as f32 * b.scale + v2;
|
||||
part.emit(out, corners, [v1, v2], abgr(32));
|
||||
}
|
||||
struct BeamPart {
|
||||
base: Mat4,
|
||||
start: i32,
|
||||
end: i32,
|
||||
[wn, en, ws, es]: [Vec3; 4],
|
||||
[v1, v2]: [f32; 2],
|
||||
color: u32,
|
||||
s: Rect,
|
||||
wrap: u32,
|
||||
) {
|
||||
for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] {
|
||||
let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0);
|
||||
for (p, uv) in [
|
||||
(at(a, end), [s.u1, v1]),
|
||||
(at(a, start), [s.u1, v2]),
|
||||
(at(b, start), [s.u0, v2]),
|
||||
(at(b, end), [s.u0, v1]),
|
||||
] {
|
||||
}
|
||||
impl BeamPart {
|
||||
/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es).
|
||||
fn emit(
|
||||
&self,
|
||||
out: &mut Vec<Vertex>,
|
||||
[wn, en, ws, es]: [Vec3; 4],
|
||||
[v1, v2]: [f32; 2],
|
||||
color: u32,
|
||||
) {
|
||||
let s = self.s;
|
||||
for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] {
|
||||
let at = |c: Vec3, y: i32| {
|
||||
self.base
|
||||
.transform_point3(Vec3::new(0.5, 0.0, 0.5) + c + Vec3::new(0.0, y as f32, 0.0))
|
||||
};
|
||||
for (p, uv) in [
|
||||
(at(a, self.end), [s.u1, v1]),
|
||||
(at(a, self.start), [s.u1, v2]),
|
||||
(at(b, self.start), [s.u0, v2]),
|
||||
(at(b, self.end), [s.u0, v1]),
|
||||
] {
|
||||
out.push(Vertex {
|
||||
pos: p.to_array(),
|
||||
uv,
|
||||
layer: 6,
|
||||
color,
|
||||
light: self.wrap,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Entity-shader layers for `rendertype_end_portal`: end portals draw 15
|
||||
/// layers of `end_portal.png` over `end_sky.png`, End gateways 16.
|
||||
pub const END_PORTAL_LAYER: u32 = 9;
|
||||
pub const END_GATEWAY_LAYER: u32 = 10;
|
||||
/// `AbstractEndPortalRenderer.FACES`: the unit cube's corners for each face
|
||||
/// (`Direction` order) in `FaceInfo` vertex order.
|
||||
#[rustfmt::skip]
|
||||
const PORTAL_FACES: [[[f32; 3]; 4]; 6] = [
|
||||
[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0]],
|
||||
[[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]],
|
||||
[[1.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
|
||||
[[0.0, 1.0, 1.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]],
|
||||
[[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0]],
|
||||
[[1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]],
|
||||
];
|
||||
/// `AbstractEndPortalRenderer.submitCube`: position-only quads (the portal
|
||||
/// shader projects its textures from the screen; uv, colour and light are unused).
|
||||
fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec<Vertex>) {
|
||||
for &d in faces {
|
||||
for c in PORTAL_FACES[d as usize] {
|
||||
out.push(Vertex {
|
||||
pos: p.to_array(),
|
||||
uv,
|
||||
layer: 6,
|
||||
color,
|
||||
light: wrap,
|
||||
pos: m.transform_point3(Vec3::from(c)).to_array(),
|
||||
uv: [0.0; 2],
|
||||
layer,
|
||||
color: 0,
|
||||
light: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,9 @@ impl BossBar {
|
||||
hover: Some(Box::new(Text::literal(self.id.clone()))),
|
||||
..Style::default()
|
||||
};
|
||||
bracketed(comp_text(&self.name).with_style(&style))
|
||||
// ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the
|
||||
// brackets take the colour too.
|
||||
bracketed(comp_text(&self.name)).with_style(&style)
|
||||
}
|
||||
/// The filled fraction of the bar (`BossEvent.getProgress`).
|
||||
pub fn progress(&self) -> f32 {
|
||||
|
||||
+124
-110
@@ -5,6 +5,7 @@
|
||||
use crate::{
|
||||
command::{Dispatcher, ParseResults, Registries, Suggestion},
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
hud_layout::{self, GuiDraw, PoseOp},
|
||||
text::{self, Style, Text},
|
||||
ui::{EditBox, char_len},
|
||||
};
|
||||
@@ -12,15 +13,16 @@ use crate::{
|
||||
/// GuiMessageTag.systemSinglePlayer's indicator colour.
|
||||
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
|
||||
|
||||
/// The chat options (doubles, as vanilla keeps them).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ChatOptions {
|
||||
pub opacity: f32,
|
||||
pub background_opacity: f32,
|
||||
pub scale: f32,
|
||||
pub width: f32,
|
||||
pub height_focused: f32,
|
||||
pub height_unfocused: f32,
|
||||
pub line_spacing: f32,
|
||||
pub opacity: f64,
|
||||
pub background_opacity: f64,
|
||||
pub scale: f64,
|
||||
pub width: f64,
|
||||
pub height_focused: f64,
|
||||
pub height_unfocused: f64,
|
||||
pub line_spacing: f64,
|
||||
}
|
||||
impl Default for ChatOptions {
|
||||
fn default() -> Self {
|
||||
@@ -37,20 +39,21 @@ impl Default for ChatOptions {
|
||||
}
|
||||
impl ChatOptions {
|
||||
/// ChatComponent.getWidth/getHeight.
|
||||
pub fn width_px(&self) -> f32 {
|
||||
(self.width * 280.0 + 40.0).floor()
|
||||
pub fn width_px(&self) -> i32 {
|
||||
(self.width * 280.0 + 40.0).floor() as i32
|
||||
}
|
||||
pub fn height_px(&self, focused: bool) -> f32 {
|
||||
pub fn height_px(&self, focused: bool) -> i32 {
|
||||
((if focused {
|
||||
self.height_focused
|
||||
} else {
|
||||
self.height_unfocused
|
||||
}) * 160.0
|
||||
+ 20.0)
|
||||
.floor()
|
||||
.floor() as i32
|
||||
}
|
||||
pub fn line_height(&self) -> f32 {
|
||||
(9.0 * (self.line_spacing + 1.0)).floor()
|
||||
/// `getLineHeight`.
|
||||
pub fn line_height(&self) -> i32 {
|
||||
(9.0 * (self.line_spacing + 1.0)) as i32
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -59,12 +62,25 @@ struct Message {
|
||||
content: Text,
|
||||
indicator: Option<u32>,
|
||||
}
|
||||
/// A wrapped line (`GuiMessage.Line`).
|
||||
#[derive(Clone, Debug)]
|
||||
struct Line {
|
||||
added: u64,
|
||||
content: Text,
|
||||
indicator: Option<u32>,
|
||||
}
|
||||
|
||||
/// `ChatComponent.AlphaCalculator.timeBased`: opaque for 180 ticks, then
|
||||
/// fading out quadratically over 20.
|
||||
fn time_alpha(ticks: u64, added: u64) -> f32 {
|
||||
let delta = ticks as i64 - added as i64;
|
||||
let mut t = delta as f64 / 200.0;
|
||||
t = 1.0 - t;
|
||||
t *= 10.0;
|
||||
t = t.clamp(0.0, 1.0);
|
||||
t *= t;
|
||||
t as f32
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Chat {
|
||||
messages: Vec<Message>,
|
||||
@@ -80,10 +96,11 @@ pub struct Chat {
|
||||
}
|
||||
impl Chat {
|
||||
pub fn lines_per_page(&self, focused: bool) -> usize {
|
||||
(self.options.height_px(focused) / self.options.line_height().max(1.0)) as usize
|
||||
(self.options.height_px(focused) / self.options.line_height().max(1)) as usize
|
||||
}
|
||||
fn max_width(&self) -> f32 {
|
||||
(self.options.width_px() / self.options.scale.max(0.01)).floor()
|
||||
/// The wrapping width, `Mth.floor(getWidth() / getScale())`.
|
||||
fn max_width(&self) -> i32 {
|
||||
(f64::from(self.options.width_px()) / self.options.scale).floor() as i32
|
||||
}
|
||||
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
|
||||
pub fn add(
|
||||
@@ -108,7 +125,7 @@ impl Chat {
|
||||
}
|
||||
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
|
||||
let width = self.max_width();
|
||||
for line in atlas.font.split(&message.content, width) {
|
||||
for line in atlas.font.wrap_components(&message.content, width) {
|
||||
if focused && self.scroll > 0 {
|
||||
self.new_since_scroll = true;
|
||||
self.scroll_by(1, focused);
|
||||
@@ -164,116 +181,113 @@ impl Chat {
|
||||
self.scroll = pos as usize;
|
||||
}
|
||||
}
|
||||
/// ChatComponent.extractRenderState.
|
||||
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
|
||||
if self.lines.is_empty() {
|
||||
return;
|
||||
/// `ChatComponent.extractRenderState` (background mode unless `focused`)
|
||||
/// on a screen `height` GUI pixels tall at `Hud.tickCount` `ticks`.
|
||||
pub fn layout(&self, height: i32, ticks: u64, focused: bool) -> Vec<GuiDraw> {
|
||||
let total = self.lines.len();
|
||||
if total == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let o = &self.options;
|
||||
let scale = o.scale;
|
||||
if scale <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let max_width = (o.width_px() / scale).ceil();
|
||||
let chat_bottom = ((batch.height - 40.0) / scale).floor();
|
||||
let text_opacity = o.opacity * 0.9 + 0.1;
|
||||
let scale = o.scale as f32;
|
||||
let max_width = hud_layout::ceil(o.width_px() as f32 / scale);
|
||||
let chat_bottom = hud_layout::floor((height - 40) as f32 / scale);
|
||||
let text_opacity = o.opacity as f32 * 0.9 + 0.1;
|
||||
let background_opacity = o.background_opacity as f32;
|
||||
let entry_height = o.line_height();
|
||||
let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing).round();
|
||||
let per_page = self.lines_per_page(focused);
|
||||
let alpha_of = |line: &Line| -> f32 {
|
||||
let bottom_to_text =
|
||||
(8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32;
|
||||
let alpha_of = |line: &Line| {
|
||||
if focused {
|
||||
return 1.0;
|
||||
1.0
|
||||
} else {
|
||||
time_alpha(ticks, line.added)
|
||||
}
|
||||
let t =
|
||||
((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0);
|
||||
(t * t) as f32
|
||||
};
|
||||
let visible = self.lines.len().saturating_sub(self.scroll).min(per_page);
|
||||
let mut count = 0;
|
||||
// Pass 1: backgrounds; pass 2: text (same order as vanilla).
|
||||
let s = |v: f32| v * scale;
|
||||
for i in (0..visible).rev() {
|
||||
let line = &self.lines[i + self.scroll];
|
||||
let alpha = alpha_of(line);
|
||||
if alpha <= 1.0e-5 {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
let bottom = chat_bottom - i as f32 * entry_height;
|
||||
let top = bottom - entry_height;
|
||||
batch.fill(
|
||||
atlas,
|
||||
0.0,
|
||||
s(top),
|
||||
s(max_width + 8.0),
|
||||
s(entry_height),
|
||||
rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8),
|
||||
);
|
||||
let visible = total
|
||||
.saturating_sub(self.scroll)
|
||||
.min(self.lines_per_page(focused));
|
||||
let lines: Vec<(usize, &Line, f32)> = (0..visible)
|
||||
.rev()
|
||||
.map(|i| (i, &self.lines[i + self.scroll]))
|
||||
.map(|(i, line)| (i, line, alpha_of(line)))
|
||||
.filter(|(_, _, alpha)| *alpha > 1.0e-5)
|
||||
.collect();
|
||||
let mut out = vec![GuiDraw::Push(vec![
|
||||
PoseOp::Scale(scale, scale),
|
||||
PoseOp::Translate(4.0, 0.0),
|
||||
])];
|
||||
for &(i, _, alpha) in &lines {
|
||||
let bottom = chat_bottom - i as i32 * entry_height;
|
||||
out.push(hud_layout::fill(
|
||||
-4,
|
||||
bottom - entry_height,
|
||||
max_width + 4 + 4,
|
||||
bottom,
|
||||
hud_layout::as8(alpha * background_opacity) << 24,
|
||||
));
|
||||
}
|
||||
for i in (0..visible).rev() {
|
||||
let line = &self.lines[i + self.scroll];
|
||||
let alpha = alpha_of(line);
|
||||
if alpha <= 1.0e-5 {
|
||||
continue;
|
||||
for &(i, line, alpha) in &lines {
|
||||
let bottom = chat_bottom - i as i32 * entry_height;
|
||||
let opacity = alpha * text_opacity;
|
||||
let color = hud_layout::white(opacity);
|
||||
if color >> 24 != 0 {
|
||||
out.push(GuiDraw::Text {
|
||||
text: line.content.clone(),
|
||||
x: 0,
|
||||
y: bottom - bottom_to_text,
|
||||
color,
|
||||
shadow: true,
|
||||
});
|
||||
}
|
||||
let bottom = chat_bottom - i as f32 * entry_height;
|
||||
let top = bottom - entry_height;
|
||||
let text_top = bottom - bottom_to_text;
|
||||
let a = (alpha * text_opacity * 255.0) as u8;
|
||||
if let Some(c) = line.indicator {
|
||||
batch.fill(
|
||||
atlas,
|
||||
0.0,
|
||||
s(top),
|
||||
s(2.0),
|
||||
s(entry_height),
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a),
|
||||
);
|
||||
}
|
||||
if a > 3 {
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&line.content,
|
||||
s(4.0),
|
||||
s(text_top),
|
||||
rgba(255, 255, 255, a),
|
||||
true,
|
||||
);
|
||||
if let Some(indicator) = line.indicator {
|
||||
let color = hud_layout::as8(opacity) << 24 | indicator & 0xFF_FFFF;
|
||||
out.push(hud_layout::fill(
|
||||
-4,
|
||||
bottom - entry_height,
|
||||
-2,
|
||||
bottom,
|
||||
color,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Scroll bar while focused and scrolled content exists.
|
||||
if focused && count > 0 {
|
||||
let total = self.lines.len() as f32;
|
||||
let chat_height = count as f32 * entry_height;
|
||||
let virtual_height = total * entry_height;
|
||||
if focused {
|
||||
let count = lines.len() as i32;
|
||||
let chat_height = count * entry_height;
|
||||
let virtual_height = total as i32 * entry_height;
|
||||
let y = self.scroll as i32 * chat_height / total as i32 - chat_bottom;
|
||||
let height = chat_height * chat_height / virtual_height;
|
||||
if virtual_height != chat_height {
|
||||
let y = self.scroll as f32 * chat_height / total - chat_bottom;
|
||||
let height = chat_height * chat_height / virtual_height;
|
||||
let alpha = if y > 0.0 { 170 } else { 96 };
|
||||
let c = if self.new_since_scroll {
|
||||
let alpha: u32 = if y > 0 { 170 } else { 96 };
|
||||
let color = if self.new_since_scroll {
|
||||
0xCC3333
|
||||
} else {
|
||||
0x3333AA
|
||||
};
|
||||
let x = max_width + 4.0 + 4.0;
|
||||
batch.fill(
|
||||
atlas,
|
||||
s(x),
|
||||
s(-y - height),
|
||||
s(2.0),
|
||||
s(height),
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha),
|
||||
);
|
||||
batch.fill(
|
||||
atlas,
|
||||
s(x + 1.0),
|
||||
s(-y - height),
|
||||
s(1.0),
|
||||
s(height),
|
||||
rgba(0xCC, 0xCC, 0xCC, alpha),
|
||||
);
|
||||
let x = max_width + 4;
|
||||
out.push(hud_layout::fill(
|
||||
x,
|
||||
-y,
|
||||
x + 2,
|
||||
-y - height,
|
||||
alpha << 24 | color,
|
||||
));
|
||||
out.push(hud_layout::fill(
|
||||
x + 2,
|
||||
-y,
|
||||
x + 1,
|
||||
-y - height,
|
||||
alpha << 24 | 0xCCCCCC,
|
||||
));
|
||||
}
|
||||
}
|
||||
out.push(GuiDraw::Pop);
|
||||
out
|
||||
}
|
||||
/// Draws [`Chat::layout`] into the HUD batch.
|
||||
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
|
||||
let draws = self.layout(batch.height as i32, ticks, focused);
|
||||
hud_layout::paint(batch, atlas, &draws);
|
||||
}
|
||||
/// Plain text of the newest messages (for tests and the control socket).
|
||||
pub fn recent_lines(&self, n: usize) -> Vec<String> {
|
||||
|
||||
@@ -83,6 +83,73 @@ pub struct RegistryIds {
|
||||
}
|
||||
const EMPTY: &[String] = &[];
|
||||
impl Registries {
|
||||
/// Fill what the game did not build itself from vanilla's exported
|
||||
/// registries (`command-registries.json`, written by
|
||||
/// `VanillaCommandParseOracle registries`): built-in registries such as
|
||||
/// mob effects, data component types and dialogs, block entities and tag
|
||||
/// members. Registries that data packs reload stay with the game.
|
||||
pub fn fill_from_export(&mut self, r: &serde_json::Value) {
|
||||
fn strings(v: &serde_json::Value) -> Vec<String> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
let fill = |field: &mut Vec<String>, key: &str| {
|
||||
if field.is_empty() {
|
||||
*field = strings(&r[key]);
|
||||
}
|
||||
};
|
||||
fill(&mut self.effects, "effects");
|
||||
fill(&mut self.enchantments, "enchantments");
|
||||
fill(&mut self.attributes, "attributes");
|
||||
fill(&mut self.damage_types, "damage_types");
|
||||
fill(&mut self.templates, "templates");
|
||||
fill(&mut self.persistent_components, "persistent_components");
|
||||
fill(&mut self.learnable_recipes, "learnable_recipes");
|
||||
const RELOADED: [&str; 5] = [
|
||||
"minecraft:advancement",
|
||||
"minecraft:recipe",
|
||||
"minecraft:loot_table",
|
||||
"minecraft:predicate",
|
||||
"minecraft:item_modifier",
|
||||
];
|
||||
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
|
||||
if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) {
|
||||
continue;
|
||||
}
|
||||
self.by_registry.insert(
|
||||
name.clone(),
|
||||
RegistryIds {
|
||||
ids: strings(&entry["ids"]),
|
||||
tags: strings(&entry["tags"]),
|
||||
},
|
||||
);
|
||||
}
|
||||
if self.block_entities.is_empty() {
|
||||
self.block_entities = strings(&r["block_entities"]).into_iter().collect();
|
||||
}
|
||||
if self.block_tag_members.is_empty() {
|
||||
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
|
||||
self.block_tag_members.insert(tag.clone(), strings(members));
|
||||
}
|
||||
}
|
||||
if self.clock_time_markers.is_empty() {
|
||||
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
|
||||
self.clock_time_markers
|
||||
.insert(clock.clone(), strings(markers));
|
||||
}
|
||||
}
|
||||
if self.advancement_criteria.is_empty() {
|
||||
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
|
||||
self.advancement_criteria
|
||||
.insert(id.clone(), strings(criteria));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The element ids of a registry (sorted).
|
||||
pub fn ids(&self, registry: &str) -> &[String] {
|
||||
if let Some(r) = self.by_registry.get(registry) {
|
||||
@@ -254,6 +321,47 @@ pub enum ArgType {
|
||||
SlotSource,
|
||||
/// ResourceOrIdArgument over a registry: an id or an inline SNBT value.
|
||||
ResourceOrId(&'static str),
|
||||
/// ResourceSelectorArgument: a `*`/`?` pattern over a registry's ids.
|
||||
ResourceSelector(&'static str),
|
||||
}
|
||||
|
||||
/// FilenameUtils.wildcardMatch (case-sensitive) of `*` and `?` patterns.
|
||||
pub fn wildcard_match(text: &str, pattern: &str) -> bool {
|
||||
let t: Vec<char> = text.chars().collect();
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let (mut ti, mut pi) = (0, 0);
|
||||
let (mut star, mut mark) = (None, 0);
|
||||
while ti < t.len() {
|
||||
if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
|
||||
ti += 1;
|
||||
pi += 1;
|
||||
} else if pi < p.len() && p[pi] == '*' {
|
||||
star = Some(pi);
|
||||
mark = ti;
|
||||
pi += 1;
|
||||
} else if let Some(s) = star {
|
||||
pi = s + 1;
|
||||
mark += 1;
|
||||
ti = mark;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while pi < p.len() && p[pi] == '*' {
|
||||
pi += 1;
|
||||
}
|
||||
pi == p.len()
|
||||
}
|
||||
/// ResourceSelectorArgument: the registry ids a pattern selects.
|
||||
pub fn select_resources<'a>(ids: &'a [String], pattern: &str) -> Vec<&'a String> {
|
||||
let pattern = if pattern.contains(':') {
|
||||
pattern.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{pattern}")
|
||||
};
|
||||
ids.iter()
|
||||
.filter(|id| wildcard_match(id, &pattern))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// SlotRanges.SLOTS: every slot range name and its size, in vanilla order.
|
||||
@@ -1348,6 +1456,29 @@ impl ArgType {
|
||||
}
|
||||
Arg::Str(name.to_owned())
|
||||
}
|
||||
ArgType::ResourceSelector(registry) => {
|
||||
let start = reader.cursor;
|
||||
while reader.can_read() && {
|
||||
let c = reader.peek();
|
||||
is_id_char(c) || c == '*' || c == '?'
|
||||
} {
|
||||
reader.skip();
|
||||
}
|
||||
let raw = reader.string[start..reader.cursor].to_owned();
|
||||
let pattern = if raw.contains(':') {
|
||||
raw
|
||||
} else {
|
||||
format!("minecraft:{raw}")
|
||||
};
|
||||
if select_resources(reg.ids(registry), &pattern).is_empty() {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.resource_selector.not_found",
|
||||
&[&pattern, registry],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Arg::Str(pattern)
|
||||
}
|
||||
ArgType::HexColor => {
|
||||
let text = reader.read_unquoted_string();
|
||||
if !matches!(text.len(), 3 | 6) {
|
||||
@@ -1521,15 +1652,26 @@ impl ArgType {
|
||||
reader.skip();
|
||||
}
|
||||
let id = &reader.string[start..reader.cursor];
|
||||
if !crate::scoreboard::criteria_exists(id, reg) {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
// ObjectiveCriteria.byName: statistics resolve to their canonical name.
|
||||
match crate::scoreboard::criteria_by_name(id, reg) {
|
||||
Ok(Some(canonical)) => Arg::Str(canonical),
|
||||
Ok(None) => {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
Err(_) => {
|
||||
reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.criteria.invalid",
|
||||
&[&id],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
Arg::Str(id.to_owned())
|
||||
}
|
||||
ArgType::ScoreboardSlot => {
|
||||
let name = reader.read_unquoted_string();
|
||||
@@ -1579,7 +1721,8 @@ impl ArgType {
|
||||
if block {
|
||||
parse_coord_int(reader)
|
||||
} else {
|
||||
parse_coord_double(reader, false)
|
||||
// Vec2Argument.vec2(): integers are centred on the block.
|
||||
parse_coord_double(reader, true)
|
||||
}
|
||||
};
|
||||
let x = one(reader)?;
|
||||
@@ -1741,6 +1884,9 @@ impl ArgType {
|
||||
}
|
||||
ArgType::StrEnum(values, _) => builder.suggest_matching(values.iter().copied()),
|
||||
ArgType::HexColor => builder.suggest_matching(["F00", "FF0000"]),
|
||||
ArgType::ResourceSelector(registry) => {
|
||||
suggest_resources(builder, reg.ids(registry), "")
|
||||
}
|
||||
ArgType::GameProfile => {
|
||||
let players = reg.players.clone();
|
||||
super::selector::suggest(builder, reg, &|b| {
|
||||
|
||||
@@ -77,11 +77,23 @@ fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> {
|
||||
Err(missing.join("; "))
|
||||
}
|
||||
}
|
||||
/// The required fields of each context number provider type, in the
|
||||
/// order DataFixerUpper reports them missing (the reverse of the record's).
|
||||
fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:uniform" => require(map, t, &["max", "min"]),
|
||||
"minecraft:constant" => require(map, t, &["value"]),
|
||||
"minecraft:binomial" => require(map, t, &["n", "p"]),
|
||||
match id.trim_start_matches("minecraft:") {
|
||||
"uniform" => require(map, t, &["max", "min"]),
|
||||
"constant" => require(map, t, &["value"]),
|
||||
"binomial" => require(map, t, &["p", "n"]),
|
||||
"add" | "mul" | "avg" | "max" | "min" | "length" => require(map, t, &["inputs"]),
|
||||
"sub" | "div" | "mod" | "floor_div" | "floor_mod" => require(map, t, &["right", "left"]),
|
||||
"pow" => require(map, t, &["exponent", "base"]),
|
||||
"abs" | "negate" | "from_float" | "from_int" | "floor" | "ceil" | "round" | "sqrt"
|
||||
| "sin" | "cos" | "truncate" => require(map, t, &["input"]),
|
||||
"conditional" => require(map, t, &["on_true", "condition"]),
|
||||
"number_dispatcher" => require(map, t, &["cases"]),
|
||||
"weighted_list" => require(map, t, &["distribution"]),
|
||||
"enchantment_level" => require(map, t, &["amount"]),
|
||||
"score" => require(map, t, &["score", "target"]),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -130,7 +142,19 @@ pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> {
|
||||
"minecraft:slot_source" => element_or_list(t, &|x| {
|
||||
dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(()))
|
||||
}),
|
||||
"minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|_, _, _| Ok(())),
|
||||
// Dialog types: CommonDialogData's title, then each type's own.
|
||||
"minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|id, map, t| {
|
||||
let own: &[&str] = match id {
|
||||
"minecraft:confirmation" => &["yes", "no"],
|
||||
"minecraft:multi_action" => &["actions"],
|
||||
"minecraft:dialog_list" => &["dialogs"],
|
||||
_ => &[],
|
||||
};
|
||||
let keys: Vec<&str> = std::iter::once("title")
|
||||
.chain(own.iter().copied())
|
||||
.collect();
|
||||
require(map, t, &keys)
|
||||
}),
|
||||
"minecraft:worldgen/feature" | "minecraft:loot_table" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod tree_misc;
|
||||
pub mod tree_scoreboard;
|
||||
pub mod tree_world;
|
||||
pub mod vanilla;
|
||||
mod vanilla_order;
|
||||
|
||||
use crate::text::Text;
|
||||
pub use args::{Arg, ArgType, Registries};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Commands Horizon parses but does not run (multiplayer, profiling and
|
||||
//! server-only features): `/dialog`, `/kick`, `/posteffect`, `/fetchprofile`,
|
||||
//! `/spectate`, `/publish`, `/unpublish`, `/waypoint`, `/debug`, `/jfr` and
|
||||
//! the `/test` root.
|
||||
//! Commands of the hosted game rather than the world: `/dialog`, `/kick`,
|
||||
//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`,
|
||||
//! `/waypoint`, `/debug`, `/jfr` and `/test`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
@@ -126,7 +125,84 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
d.executes(l, "jfr");
|
||||
}
|
||||
|
||||
// TestCommand (game tests; only its root is modelled)
|
||||
// TestCommand (release build: no export subcommands)
|
||||
let test = d.literal(root, "test");
|
||||
d.requires(test, GAMEMASTERS);
|
||||
let tests = ArgType::ResourceSelector("minecraft:test_instance");
|
||||
let int0 = ArgType::Integer {
|
||||
min: 0,
|
||||
max: i32::MAX,
|
||||
};
|
||||
let int = ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
};
|
||||
// numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only
|
||||
// the first two.
|
||||
let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| {
|
||||
let n = d.argument(node, "numberOfTimes", int0.clone());
|
||||
d.executes(n, id);
|
||||
let u = d.argument(n, "untilFailed", ArgType::Bool);
|
||||
d.executes(u, id);
|
||||
if build_info {
|
||||
let r = d.argument(u, "rotationSteps", int.clone());
|
||||
d.executes(r, id);
|
||||
let t = d.argument(r, "testsPerRow", int.clone());
|
||||
d.executes(t, id);
|
||||
}
|
||||
};
|
||||
let run = d.literal(test, "run");
|
||||
let t = d.argument(run, "tests", tests.clone());
|
||||
d.executes(t, "test.run");
|
||||
retry(d, t, "test.run", true);
|
||||
let multiple = d.literal(test, "runmultiple");
|
||||
let t = d.argument(multiple, "tests", tests.clone());
|
||||
d.executes(t, "test.run");
|
||||
let a = d.argument(t, "amount", int.clone());
|
||||
d.executes(a, "test.run");
|
||||
for name in ["runthese", "runclosest", "runthat"] {
|
||||
let l = d.literal(test, name);
|
||||
d.executes(l, "test.run.found");
|
||||
retry(d, l, "test.run.found", false);
|
||||
}
|
||||
let failed = d.literal(test, "runfailed");
|
||||
d.executes(failed, "test.run.found");
|
||||
let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool);
|
||||
d.executes(only, "test.run.found");
|
||||
retry(d, only, "test.run.found", true);
|
||||
retry(d, failed, "test.run.found", true);
|
||||
let verify = d.literal(test, "verify");
|
||||
let t = d.argument(verify, "tests", tests.clone());
|
||||
d.executes(t, "test.verify");
|
||||
let locate = d.literal(test, "locate");
|
||||
let t = d.argument(locate, "tests", tests);
|
||||
d.executes(t, "test.locate");
|
||||
for name in [
|
||||
"resetclosest",
|
||||
"resetthese",
|
||||
"resetthat",
|
||||
"clearthat",
|
||||
"clearthese",
|
||||
] {
|
||||
let l = d.literal(test, name);
|
||||
d.executes(l, "test.clear");
|
||||
}
|
||||
let all = d.literal(test, "clearall");
|
||||
d.executes(all, "test.clear");
|
||||
let r = d.argument(all, "radius", int.clone());
|
||||
d.executes(r, "test.clear");
|
||||
let stop = d.literal(test, "stop");
|
||||
d.executes(stop, "test.stop");
|
||||
let pos = d.literal(test, "pos");
|
||||
d.executes(pos, "test.pos");
|
||||
let var = d.argument(pos, "var", ArgType::Word);
|
||||
d.executes(var, "test.pos");
|
||||
let create = d.literal(test, "create");
|
||||
let id = d.argument(create, "id", ArgType::Id("none"));
|
||||
d.executes(id, "test.create");
|
||||
let w = d.argument(id, "width", int.clone());
|
||||
d.executes(w, "test.create");
|
||||
let h = d.argument(w, "height", int.clone());
|
||||
let depth = d.argument(h, "depth", int);
|
||||
d.executes(depth, "test.create");
|
||||
}
|
||||
|
||||
@@ -403,6 +403,7 @@ pub fn build_with(dev: bool) -> Dispatcher {
|
||||
super::tree_misc::register(&mut d, root);
|
||||
super::tree_world::register(&mut d, root);
|
||||
super::tree_extra::register(&mut d, root);
|
||||
apply_vanilla_order(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
@@ -506,6 +507,42 @@ pub fn game_modes() -> [&'static str; 4] {
|
||||
GameMode::ALL.map(GameMode::name)
|
||||
}
|
||||
/// The shared vanilla tree.
|
||||
/// Reorder node children as vanilla registers them (Brigadier keeps
|
||||
/// children in registration order; smart usage lists them that way).
|
||||
fn apply_vanilla_order(d: &mut Dispatcher) {
|
||||
for (path, order) in super::vanilla_order::ORDER {
|
||||
let mut node = Some(0usize);
|
||||
for name in path.split(' ').filter(|n| !n.is_empty()) {
|
||||
node = node.and_then(|n| {
|
||||
d.nodes[n]
|
||||
.children
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|&c| d.nodes[c].name() == name)
|
||||
});
|
||||
}
|
||||
let Some(n) = node else { continue };
|
||||
let mut children = d.nodes[n].children.clone();
|
||||
let rank = |c: usize| {
|
||||
order
|
||||
.iter()
|
||||
.position(|o| *o == d.nodes[c].name())
|
||||
.unwrap_or(order.len())
|
||||
};
|
||||
children.sort_by_key(|&c| rank(c));
|
||||
d.nodes[n].children = children;
|
||||
}
|
||||
}
|
||||
/// The tree the game runs: a release integrated server's, or with
|
||||
/// `HORIZON_DEV_COMMANDS` set the development one
|
||||
/// (SharedConstants.DEBUG_DEV_COMMANDS).
|
||||
pub fn game_dispatcher() -> &'static Dispatcher {
|
||||
if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() {
|
||||
dispatcher()
|
||||
} else {
|
||||
release_dispatcher()
|
||||
}
|
||||
}
|
||||
pub fn dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(build)
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The order of node children in vanilla's command tree, for the nodes
|
||||
//! where Horizon's tree registers them differently (path of node names
|
||||
//! from the root, children in vanilla's order). Generated by
|
||||
//! tools/generate_command_order.py; do not edit by hand.
|
||||
|
||||
pub const ORDER: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"",
|
||||
&[
|
||||
"advancement",
|
||||
"attribute",
|
||||
"execute",
|
||||
"bossbar",
|
||||
"clear",
|
||||
"clone",
|
||||
"compute",
|
||||
"damage",
|
||||
"data",
|
||||
"datapack",
|
||||
"debug",
|
||||
"defaultgamemode",
|
||||
"dialog",
|
||||
"difficulty",
|
||||
"effect",
|
||||
"me",
|
||||
"enchant",
|
||||
"experience",
|
||||
"xp",
|
||||
"fill",
|
||||
"fillbiome",
|
||||
"forceload",
|
||||
"function",
|
||||
"gamemode",
|
||||
"gamerule",
|
||||
"give",
|
||||
"help",
|
||||
"item",
|
||||
"kick",
|
||||
"kill",
|
||||
"list",
|
||||
"locate",
|
||||
"loot",
|
||||
"msg",
|
||||
"tell",
|
||||
"w",
|
||||
"swing",
|
||||
"particle",
|
||||
"place",
|
||||
"playsound",
|
||||
"posteffect",
|
||||
"random",
|
||||
"reload",
|
||||
"recipe",
|
||||
"fetchprofile",
|
||||
"return",
|
||||
"ride",
|
||||
"rotate",
|
||||
"say",
|
||||
"schedule",
|
||||
"scoreboard",
|
||||
"seed",
|
||||
"version",
|
||||
"setblock",
|
||||
"spawnpoint",
|
||||
"setworldspawn",
|
||||
"spectate",
|
||||
"spreadplayers",
|
||||
"stopsound",
|
||||
"stopwatch",
|
||||
"summon",
|
||||
"tag",
|
||||
"team",
|
||||
"teammsg",
|
||||
"tm",
|
||||
"teleport",
|
||||
"tp",
|
||||
"tellraw",
|
||||
"test",
|
||||
"tick",
|
||||
"time",
|
||||
"title",
|
||||
"trigger",
|
||||
"waypoint",
|
||||
"weather",
|
||||
"worldborder",
|
||||
"jfr",
|
||||
"publish",
|
||||
"unpublish",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute",
|
||||
&[
|
||||
"run",
|
||||
"if",
|
||||
"unless",
|
||||
"as",
|
||||
"at",
|
||||
"store",
|
||||
"positioned",
|
||||
"rotated",
|
||||
"facing",
|
||||
"align",
|
||||
"anchored",
|
||||
"in",
|
||||
"summon",
|
||||
"on",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute if",
|
||||
&[
|
||||
"block",
|
||||
"biome",
|
||||
"loaded",
|
||||
"dimension",
|
||||
"score",
|
||||
"blocks",
|
||||
"entity",
|
||||
"predicate",
|
||||
"function",
|
||||
"stopwatch",
|
||||
"data",
|
||||
"items",
|
||||
"slots",
|
||||
],
|
||||
),
|
||||
(
|
||||
"execute unless",
|
||||
&[
|
||||
"block",
|
||||
"biome",
|
||||
"loaded",
|
||||
"dimension",
|
||||
"score",
|
||||
"blocks",
|
||||
"entity",
|
||||
"predicate",
|
||||
"function",
|
||||
"stopwatch",
|
||||
"data",
|
||||
"items",
|
||||
"slots",
|
||||
],
|
||||
),
|
||||
("execute facing", &["entity", "pos"]),
|
||||
("datapack", &["enable", "disable", "list", "create"]),
|
||||
(
|
||||
"datapack enable name",
|
||||
&["after", "before", "last", "first"],
|
||||
),
|
||||
("item", &["replace", "fill", "override", "modify"]),
|
||||
("item replace entity target slots", &["from", "with"]),
|
||||
("item fill entity target slots", &["from", "with"]),
|
||||
("item override entity target slots", &["from", "with"]),
|
||||
(
|
||||
"loot replace entity entities slot",
|
||||
&["fish", "loot", "kill", "mine", "count"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot count fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace entity entities slot count mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot",
|
||||
&["fish", "loot", "kill", "mine", "count"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot count fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot replace block targetPos slot count mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot insert targetPos fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot insert targetPos mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot give players fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot give players mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot spawn targetPos fish loot_table pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"loot spawn targetPos mine pos",
|
||||
&["tool", "mainhand", "offhand"],
|
||||
),
|
||||
(
|
||||
"scoreboard players",
|
||||
&[
|
||||
"list",
|
||||
"set",
|
||||
"get",
|
||||
"add",
|
||||
"remove",
|
||||
"reset",
|
||||
"enable",
|
||||
"display",
|
||||
"operation",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -152,9 +152,34 @@ impl Parser<'_> {
|
||||
Err("unterminated string".into())
|
||||
}
|
||||
}
|
||||
/// The style fields of a component object.
|
||||
fn object_style(o: &serde_json::Map<String, Value>) -> Style {
|
||||
let mut style = Style::default();
|
||||
if let Some(c) = o.get("color").and_then(Value::as_str) {
|
||||
style.color = named_color(c).or_else(|| {
|
||||
c.strip_prefix('#')
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
});
|
||||
}
|
||||
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
|
||||
style.bold = flag("bold");
|
||||
style.italic = flag("italic");
|
||||
style.underlined = flag("underlined");
|
||||
style.strikethrough = flag("strikethrough");
|
||||
style.obfuscated = flag("obfuscated");
|
||||
style
|
||||
}
|
||||
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
|
||||
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
|
||||
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
to_text_with(v, resolve, &mut |_| None)
|
||||
}
|
||||
/// `to_text` with a hook resolving other contents (`nbt`) from the object.
|
||||
pub fn to_text_with(
|
||||
v: &Value,
|
||||
resolve: &mut dyn FnMut(&str) -> Text,
|
||||
contents: &mut dyn FnMut(&serde_json::Map<String, Value>) -> Option<Text>,
|
||||
) -> Text {
|
||||
match v {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
Value::Number(n) => Text::literal(n.to_string()),
|
||||
@@ -164,32 +189,27 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
let Some((first, rest)) = list.split_first() else {
|
||||
return Text::empty();
|
||||
};
|
||||
let mut base = to_text(first, resolve);
|
||||
let style = base
|
||||
.spans
|
||||
.first()
|
||||
.map(|s| s.style.clone())
|
||||
.unwrap_or_default();
|
||||
let mut base = to_text_with(first, resolve, contents);
|
||||
// The siblings take the first component's own style, even when
|
||||
// its text is empty.
|
||||
let style = match first {
|
||||
Value::Object(o) => object_style(o),
|
||||
_ => base
|
||||
.spans
|
||||
.first()
|
||||
.map(|s| s.style.clone())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
for sibling in rest {
|
||||
base.push(to_text(sibling, resolve).with_style(&style));
|
||||
base.push(to_text_with(sibling, resolve, contents).with_style(&style));
|
||||
}
|
||||
base
|
||||
}
|
||||
Value::Object(o) => {
|
||||
let mut style = Style::default();
|
||||
if let Some(c) = o.get("color").and_then(Value::as_str) {
|
||||
style.color = named_color(c).or_else(|| {
|
||||
c.strip_prefix('#')
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
});
|
||||
}
|
||||
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
|
||||
style.bold = flag("bold");
|
||||
style.italic = flag("italic");
|
||||
style.underlined = flag("underlined");
|
||||
style.strikethrough = flag("strikethrough");
|
||||
style.obfuscated = flag("obfuscated");
|
||||
let content = if let Some(t) = o.get("text") {
|
||||
let style = object_style(o);
|
||||
let content = if let Some(t) = contents(o) {
|
||||
t
|
||||
} else if let Some(t) = o.get("text") {
|
||||
match t {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
other => Text::literal(other.to_string()),
|
||||
@@ -198,7 +218,11 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
let args: Vec<Text> = o
|
||||
.get("with")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|x| to_text(x, resolve)).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|x| to_text_with(x, resolve, contents))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let translated = Text::translate(key, &args);
|
||||
match o.get("fallback").and_then(Value::as_str) {
|
||||
@@ -219,7 +243,7 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
out.push(to_text(extra, resolve).with_style(&style));
|
||||
out.push(to_text_with(extra, resolve, contents).with_style(&style));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -208,6 +208,7 @@ impl BlockEntity {
|
||||
}
|
||||
let size = match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
|
||||
n if n.ends_with("copper_chest") => 27,
|
||||
"minecraft:hopper" => 5,
|
||||
"minecraft:dispenser" | "minecraft:dropper" => 9,
|
||||
n if n.ends_with("shulker_box") => 27,
|
||||
@@ -219,6 +220,7 @@ impl BlockEntity {
|
||||
pub fn id_for_block(name: &str) -> Option<&'static str> {
|
||||
Some(match name {
|
||||
"minecraft:chest" => "minecraft:chest",
|
||||
n if n.ends_with("copper_chest") => "minecraft:chest",
|
||||
"minecraft:trapped_chest" => "minecraft:trapped_chest",
|
||||
"minecraft:barrel" => "minecraft:barrel",
|
||||
"minecraft:hopper" => "minecraft:hopper",
|
||||
|
||||
@@ -67,6 +67,15 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl DataPack {
|
||||
/// The built-in `vanilla` pack: the game's own data directory.
|
||||
pub fn builtin(root: &Path) -> Self {
|
||||
DataPack {
|
||||
id: "vanilla".into(),
|
||||
source: Source::Dir(root.to_path_buf()),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The packs in `<world>/datapacks`, sorted by name.
|
||||
pub fn discover(world: &Path) -> Vec<DataPack> {
|
||||
let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else {
|
||||
|
||||
@@ -11,6 +11,10 @@ struct Globals {
|
||||
sun: vec4<f32>,
|
||||
// x: sky fog end, y: cloud fog end
|
||||
fog_ends: vec4<f32>,
|
||||
// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: array<vec4<f32>, 2>,
|
||||
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
|
||||
time: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
@@ -27,11 +31,14 @@ struct Out {
|
||||
@location(4) @interpolate(flat) overlay: u32,
|
||||
// Overlay 6: the sprite's v origin and height, for v repeated inside it.
|
||||
@location(6) @interpolate(flat) wrap: vec2<f32>,
|
||||
// Overlays 9 and 10: projection_from_position(gl_Position), the End portal's texProj0.
|
||||
@location(7) proj: vec4<f32>,
|
||||
}
|
||||
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>) -> Out {
|
||||
var out: Out;
|
||||
out.clip = globals.view_proj * vec4(position, 1.0);
|
||||
out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw);
|
||||
out.uv = uv;
|
||||
let l = vec2(f32(light.y), f32(light.x));
|
||||
let lm = textureSampleLevel(lightmap, lightmap_sampler,
|
||||
@@ -52,6 +59,41 @@ struct Out {
|
||||
if overlay == 4u { out.spherical = length(position); }
|
||||
return out;
|
||||
}
|
||||
// rendertype_end_portal.fsh: the layer colours.
|
||||
const PORTAL_COLORS = array<vec3<f32>, 16>(
|
||||
vec3(0.022087, 0.098399, 0.110818),
|
||||
vec3(0.011892, 0.095924, 0.089485),
|
||||
vec3(0.027636, 0.101689, 0.100326),
|
||||
vec3(0.046564, 0.109883, 0.114838),
|
||||
vec3(0.064901, 0.117696, 0.097189),
|
||||
vec3(0.063761, 0.086895, 0.123646),
|
||||
vec3(0.084817, 0.111994, 0.166380),
|
||||
vec3(0.097489, 0.154120, 0.091064),
|
||||
vec3(0.106152, 0.131144, 0.195191),
|
||||
vec3(0.097721, 0.110188, 0.187229),
|
||||
vec3(0.133516, 0.138278, 0.148582),
|
||||
vec3(0.070006, 0.243332, 0.235792),
|
||||
vec3(0.196766, 0.142899, 0.214696),
|
||||
vec3(0.047281, 0.315338, 0.321970),
|
||||
vec3(0.204675, 0.390010, 0.302066),
|
||||
vec3(0.080955, 0.314821, 0.661491),
|
||||
);
|
||||
// textureProj on a repeating texture that lives in the atlas at `rect`.
|
||||
fn portal_sample(rect: vec4<f32>, p: vec4<f32>) -> vec3<f32> {
|
||||
let st = fract(p.xy / p.w);
|
||||
return textureSampleLevel(atlas, atlas_sampler, rect.xy + st * rect.zw, 0.0).rgb;
|
||||
}
|
||||
// texProj0 * end_portal_layer(layer): the row vector through mat4(scale * rotate),
|
||||
// translate and SCALE_TRANSLATE in turn.
|
||||
fn portal_layer(p: vec4<f32>, layer: f32) -> vec4<f32> {
|
||||
let a = radians((layer * layer * 4321.0 + layer * 9.0) * 2.0);
|
||||
let c = cos(a);
|
||||
let s = sin(a);
|
||||
let k = (4.5 - layer / 4.0) * 2.0;
|
||||
var v = vec4(k * (c * p.x - s * p.y), k * (s * p.x + c * p.y), p.z, p.w);
|
||||
v = vec4(v.x + 17.0 / layer * v.w, v.y + (2.0 + layer / 1.5) * (globals.time.x * 1.5) * v.w, v.z, v.w);
|
||||
return vec4(0.5 * v.x + 0.25 * v.w, 0.5 * v.y + 0.25 * v.w, v.z, v.w);
|
||||
}
|
||||
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
if d <= start { return 0.0; }
|
||||
if d >= end { return 1.0; }
|
||||
@@ -61,7 +103,16 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
var uv = in.uv;
|
||||
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
|
||||
var color = textureSample(atlas, atlas_sampler, uv) * in.color;
|
||||
if in.overlay == 4u {
|
||||
if in.overlay == 9u || in.overlay == 10u {
|
||||
// rendertype_end_portal: end_sky and PORTAL_LAYERS (15 for portals, 16
|
||||
// for gateways) layers of end_portal.png projected from the screen.
|
||||
let layers = select(15, 16, in.overlay == 10u);
|
||||
var c = portal_sample(globals.end_portal_sprites[0], in.proj) * PORTAL_COLORS[0];
|
||||
for (var i = 0; i < layers; i++) {
|
||||
c += portal_sample(globals.end_portal_sprites[1], portal_layer(in.proj, f32(i + 1))) * PORTAL_COLORS[i];
|
||||
}
|
||||
color = vec4(c, 1.0);
|
||||
} else if in.overlay == 4u {
|
||||
// clouds.fsh: alpha fades out towards the cloud fog end.
|
||||
return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y)));
|
||||
}
|
||||
|
||||
@@ -407,7 +407,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
}
|
||||
// Skeletons are spawned holding a bow (finalizeSpawn); a mob loaded
|
||||
// from NBT keeps only its saved equipment.
|
||||
"minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" if raw.is_none() => {
|
||||
"minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged"
|
||||
if raw.is_none() && m.extra.main_hand.as_deref() == Some("minecraft:bow") =>
|
||||
{
|
||||
map.entry("equipment".into()).or_insert_with(|| {
|
||||
Tag::compound([(
|
||||
"mainhand",
|
||||
@@ -430,6 +432,17 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
// CopperGolem.addAdditionalSaveData.
|
||||
"minecraft:copper_golem" => {
|
||||
map.insert(
|
||||
"next_weather_age".into(),
|
||||
Tag::Long(m.extra.vector[0] as i64),
|
||||
);
|
||||
map.insert(
|
||||
"weather_state".into(),
|
||||
string(crate::mobs::copper_golem::WEATHER[m.extra.variant.min(3) as usize]),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
crate::mobs::raider::write_nbt(m, map);
|
||||
@@ -737,6 +750,21 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
if m.species() == crate::mobs::Species::Sniffer {
|
||||
crate::mobs::sniffer::from_nbt(&mut m, tag);
|
||||
}
|
||||
if m.species() == crate::mobs::Species::CopperGolem {
|
||||
// CopperGolem.readAdditionalSaveData: -1 (unset) when missing.
|
||||
m.extra.vector[0] = match tag.get("next_weather_age") {
|
||||
Some(Tag::Long(v)) => *v as f64,
|
||||
_ => -1.0,
|
||||
};
|
||||
let weather = match tag.get("weather_state") {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => String::new(),
|
||||
};
|
||||
m.extra.variant = crate::mobs::copper_golem::WEATHER
|
||||
.iter()
|
||||
.position(|w| *w == weather)
|
||||
.unwrap_or(0) as u8;
|
||||
}
|
||||
m.extra.leash_pending = crate::mobs::leash::pending_from_nbt(tag.get("leash"));
|
||||
if m.species() == crate::mobs::Species::Warden {
|
||||
// The brain starts afresh: a minute before it digs back down.
|
||||
@@ -1118,6 +1146,25 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
|
||||
{
|
||||
put(&mut tag, "Health", Tag::Float(20f32.to_bits()));
|
||||
}
|
||||
// LivingEntity.addAdditionalSaveData and ArmorStand's own fields.
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
for (key, value) in [
|
||||
("HurtTime", Tag::Short(0)),
|
||||
("DeathTime", Tag::Short(0)),
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
("current_impulse_context_reset_grace_time", Tag::Int(0)),
|
||||
("attributes", Tag::List(Vec::new())),
|
||||
(
|
||||
"Brain",
|
||||
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
|
||||
),
|
||||
("DisabledSlots", Tag::Int(0)),
|
||||
("Pose", Tag::Compound(Compound::new())),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Iteration order of the Java hash collections vanilla's scoreboard keeps
|
||||
//! its names in: fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! addressing with linear probing, backward-shift deletion and rehashing at
|
||||
//! the load factor) and `java.util.HashSet<String>` (chained buckets split on
|
||||
//! resize). Commands list, and `scoreboard.dat` saves, in these orders.
|
||||
|
||||
/// The keys of a fastutil open hash map in their table slots.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OpenOrder {
|
||||
keys: Vec<Option<String>>,
|
||||
size: usize,
|
||||
min_n: usize,
|
||||
load: f32,
|
||||
}
|
||||
impl Default for OpenOrder {
|
||||
/// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75.
|
||||
fn default() -> Self {
|
||||
Self::new(16, 0.75)
|
||||
}
|
||||
}
|
||||
/// `String.hashCode`.
|
||||
pub fn java_hash(s: &str) -> i32 {
|
||||
s.encode_utf16()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
|
||||
}
|
||||
/// `HashCommon.mix`.
|
||||
fn mix(x: i32) -> usize {
|
||||
let h = (x as u32).wrapping_mul(0x9E37_79B9);
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
/// `HashCommon.arraySize`.
|
||||
fn array_size(expected: usize, f: f32) -> usize {
|
||||
let wanted = (expected as f64 / f64::from(f)).ceil() as usize;
|
||||
wanted.max(2).next_power_of_two()
|
||||
}
|
||||
/// `HashCommon.maxFill`.
|
||||
fn max_fill(n: usize, f: f32) -> usize {
|
||||
((n as f64 * f64::from(f)).ceil() as usize).min(n - 1)
|
||||
}
|
||||
impl OpenOrder {
|
||||
pub fn new(expected: usize, load: f32) -> Self {
|
||||
let n = array_size(expected, load);
|
||||
Self {
|
||||
keys: vec![None; n],
|
||||
size: 0,
|
||||
min_n: n,
|
||||
load,
|
||||
}
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
fn slot(&self, key: &str) -> usize {
|
||||
mix(java_hash(key)) & (self.keys.len() - 1)
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return true;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `put`: false when the key was already there.
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return false;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key.to_owned());
|
||||
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`.
|
||||
let old = self.size;
|
||||
self.size += 1;
|
||||
if old >= max_fill(self.keys.len(), self.load) {
|
||||
self.rehash(array_size(self.size + 1, self.load));
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `remove`: false when the key was not there.
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
loop {
|
||||
match &self.keys[pos] {
|
||||
None => return false,
|
||||
Some(k) if k == key => break,
|
||||
Some(_) => pos = (pos + 1) & mask,
|
||||
}
|
||||
}
|
||||
self.size -= 1;
|
||||
self.shift_keys(pos);
|
||||
let n = self.keys.len();
|
||||
if n > self.min_n && self.size < max_fill(n, self.load) / 4 && n > 16 {
|
||||
self.rehash(n / 2);
|
||||
}
|
||||
true
|
||||
}
|
||||
fn shift_keys(&mut self, mut pos: usize) {
|
||||
let mask = self.keys.len() - 1;
|
||||
loop {
|
||||
let last = pos;
|
||||
pos = (last + 1) & mask;
|
||||
loop {
|
||||
let Some(curr) = self.keys[pos].clone() else {
|
||||
self.keys[last] = None;
|
||||
return;
|
||||
};
|
||||
let slot = self.slot(&curr);
|
||||
let stop = if last <= pos {
|
||||
last >= slot || slot > pos
|
||||
} else {
|
||||
last >= slot && slot > pos
|
||||
};
|
||||
if stop {
|
||||
self.keys[last] = Some(curr);
|
||||
break;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rehash(&mut self, new_n: usize) {
|
||||
let old = std::mem::replace(&mut self.keys, vec![None; new_n]);
|
||||
let mask = new_n - 1;
|
||||
// `for (int j = realSize(); j-- != 0;) { while (key[--i] == null); ... }`
|
||||
for key in old.into_iter().rev().flatten() {
|
||||
let mut pos = mix(java_hash(&key)) & mask;
|
||||
while self.keys[pos].is_some() {
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key);
|
||||
}
|
||||
}
|
||||
/// `iterator()` and `forEach`: from the last slot down.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().rev().flatten().map(String::as_str)
|
||||
}
|
||||
/// `spliterator()` (what `stream()` uses): from the first slot up.
|
||||
pub fn stream(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().flatten().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of a `java.util.HashSet<String>` in their buckets.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HashSetOrder {
|
||||
/// Empty until the first insertion (`HashMap.resize` on first `put`).
|
||||
table: Vec<Vec<String>>,
|
||||
size: usize,
|
||||
}
|
||||
/// `HashMap.hash`.
|
||||
fn spread(s: &str) -> usize {
|
||||
let h = java_hash(s) as u32;
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
impl HashSetOrder {
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
self.table[i].iter().any(|k| k == key)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
self.table = vec![Vec::new(); 16];
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
if self.table[i].iter().any(|k| k == key) {
|
||||
return false;
|
||||
}
|
||||
self.table[i].push(key.to_owned());
|
||||
self.size += 1;
|
||||
if self.size > self.table.len() * 3 / 4 {
|
||||
self.resize();
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Doubles the table; each bucket splits into its low and high halves in order.
|
||||
fn resize(&mut self) {
|
||||
let old = std::mem::take(&mut self.table);
|
||||
let n = old.len() * 2;
|
||||
self.table = vec![Vec::new(); n];
|
||||
for bucket in old {
|
||||
for key in bucket {
|
||||
let i = spread(&key) & (n - 1);
|
||||
self.table[i].push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
let Some(at) = self.table[i].iter().position(|k| k == key) else {
|
||||
return false;
|
||||
};
|
||||
self.table[i].remove(at);
|
||||
self.size -= 1;
|
||||
true
|
||||
}
|
||||
pub fn iter(&self) -> impl Iterator<Item = &String> {
|
||||
self.table.iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_and_order() {
|
||||
assert_eq!(java_hash("harness"), {
|
||||
"harness"
|
||||
.chars()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))
|
||||
});
|
||||
let mut o = OpenOrder::new(16, 0.5);
|
||||
for k in ["harness", "harness_h"] {
|
||||
o.insert(k);
|
||||
}
|
||||
assert_eq!(o.iter().count(), 2);
|
||||
let mut asc: Vec<&str> = o.stream().collect();
|
||||
asc.reverse();
|
||||
assert_eq!(asc, o.iter().collect::<Vec<_>>());
|
||||
o.remove("harness");
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
for i in 0..40 {
|
||||
o.insert(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().count(), 41);
|
||||
for i in 0..40 {
|
||||
o.remove(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_set_buckets() {
|
||||
let mut s = HashSetOrder::default();
|
||||
for i in 0..30 {
|
||||
assert!(s.insert(&format!("p{i}")));
|
||||
}
|
||||
assert!(!s.insert("p3"));
|
||||
assert_eq!(s.len(), 30);
|
||||
assert!(s.remove("p3") && !s.contains("p3"));
|
||||
// "Aa" and "BB" share a hash: insertion order within the bucket.
|
||||
let mut t = HashSetOrder::default();
|
||||
t.insert("BB");
|
||||
t.insert("Aa");
|
||||
assert_eq!(t.iter().collect::<Vec<_>>(), vec!["BB", "Aa"]);
|
||||
}
|
||||
}
|
||||
@@ -451,6 +451,72 @@ impl Font {
|
||||
.sum::<f32>()
|
||||
.ceil()
|
||||
}
|
||||
/// `StringSplitter.splitLines`: each line and whether it continues a
|
||||
/// wrapped one. A line breaks at a `\n`, or once a character overflows
|
||||
/// `max_width` (never the first visible one) at the last space so far, or
|
||||
/// before that character; the `\n` or space at the break is dropped.
|
||||
pub fn split_lines(&self, t: &Text, max_width: f32) -> Vec<(Text, bool)> {
|
||||
let max_width = max_width.max(1.0);
|
||||
let chars: Vec<(char, &Style)> = t.chars().collect();
|
||||
let n = chars.len();
|
||||
let mut out = Vec::new();
|
||||
let (mut start, mut wrapped, mut force_new_line) = (0, false, false);
|
||||
loop {
|
||||
// LineBreakFinder over what is left.
|
||||
let (mut width, mut had_visible, mut last_space) = (0.0f32, false, None);
|
||||
let mut split = None;
|
||||
for (i, &(c, style)) in chars.iter().enumerate().skip(start) {
|
||||
if c == '\n' {
|
||||
split = Some(i);
|
||||
break;
|
||||
}
|
||||
if c == ' ' {
|
||||
last_space = Some(i);
|
||||
}
|
||||
let advance = self.advance(c, style);
|
||||
width += advance;
|
||||
if !had_visible || width <= max_width {
|
||||
had_visible |= advance != 0.0;
|
||||
} else {
|
||||
split = Some(last_space.unwrap_or(i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(at) = split else { break };
|
||||
let new_line = chars[at].0 == '\n';
|
||||
let skip = usize::from(new_line || chars[at].0 == ' ');
|
||||
force_new_line = new_line;
|
||||
out.push((t.slice(start, at), wrapped));
|
||||
wrapped = !new_line;
|
||||
start = at + skip;
|
||||
}
|
||||
if start < n {
|
||||
out.push((t.slice(start, n), wrapped));
|
||||
} else if force_new_line {
|
||||
out.push((Text::empty(), false));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `ComponentRenderUtils.wrapComponents`: the split lines, wrapped ones
|
||||
/// indented by an unstyled space; one empty line for empty text.
|
||||
pub fn wrap_components(&self, t: &Text, max_width: i32) -> Vec<Text> {
|
||||
let lines: Vec<Text> = self
|
||||
.split_lines(t, max_width as f32)
|
||||
.into_iter()
|
||||
.map(|(line, wrapped)| {
|
||||
if wrapped {
|
||||
Text::literal(" ").append(line)
|
||||
} else {
|
||||
line
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if lines.is_empty() {
|
||||
vec![Text::empty()]
|
||||
} else {
|
||||
lines
|
||||
}
|
||||
}
|
||||
/// StringSplitter.splitLines: wrap at the last space that fits (or
|
||||
/// mid-word when none does); `\n` always breaks. Styles are kept.
|
||||
pub fn split(&self, t: &Text, max_width: f32) -> Vec<Text> {
|
||||
|
||||
+245
-200
@@ -6,6 +6,7 @@ mod allays;
|
||||
mod armor_stands;
|
||||
mod banners;
|
||||
mod beacon;
|
||||
mod block_entity_anims;
|
||||
mod blockctl;
|
||||
mod boats;
|
||||
mod books;
|
||||
@@ -14,8 +15,10 @@ mod breezes;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod combat;
|
||||
mod command_harness;
|
||||
mod commands;
|
||||
mod control;
|
||||
mod copper_golems;
|
||||
mod creaking;
|
||||
mod creatures;
|
||||
mod crossbow;
|
||||
@@ -75,6 +78,7 @@ mod sculk;
|
||||
mod shield;
|
||||
mod sign_edit;
|
||||
mod sniffers;
|
||||
mod spill;
|
||||
mod station_control;
|
||||
mod stations;
|
||||
mod stats;
|
||||
@@ -109,7 +113,7 @@ use horizon_client::{
|
||||
environment::Environment,
|
||||
gfx::{Frame, Renderer},
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
hud_layout,
|
||||
hud_layout, hud_overlays,
|
||||
items::{ItemStack, Items},
|
||||
keymapping::KeyAction,
|
||||
light::LightTables,
|
||||
@@ -322,6 +326,10 @@ struct GameLevel<'w> {
|
||||
items: &'w Items,
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
rules: horizon_world::level::GameRules,
|
||||
/// Block loot random sequences (`ServerLevel.getRandomSequence`).
|
||||
rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences,
|
||||
pending: &'w mut spill::Pending,
|
||||
spill: &'w mut spill::Spill,
|
||||
}
|
||||
impl LevelAccess for GameLevel<'_> {
|
||||
fn precipitation(&self, pos: BlockPos) -> Option<horizon_world::level::Precipitation> {
|
||||
@@ -465,7 +473,26 @@ impl LevelAccess for GameLevel<'_> {
|
||||
}
|
||||
}
|
||||
fn emit(&mut self, event: LevelEvent) {
|
||||
self.events.push(event);
|
||||
match event {
|
||||
// Block.dropResources draws its loot and spots right away.
|
||||
LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state),
|
||||
// Block.popResource of the block's own item (tall flowers, flower beds).
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "pop_block_item",
|
||||
} => self.pop_block_item(pos, state),
|
||||
// ComposterBlock.extractProduce: bone meal above the composter.
|
||||
LevelEvent::Player {
|
||||
pos,
|
||||
effect: PlayerEffect::DropItem(item),
|
||||
..
|
||||
} => self.pop_above(pos, item),
|
||||
event => self.events.push(event),
|
||||
}
|
||||
}
|
||||
fn remove_block_entity(&mut self, pos: BlockPos, old: BlockStateId, side_effects: bool) -> u8 {
|
||||
self.remove_entity(pos, old, side_effects)
|
||||
}
|
||||
}
|
||||
/// FallingBlockEntity carrying a block state.
|
||||
@@ -612,7 +639,8 @@ struct Game<'a> {
|
||||
raiding: raids::Raiding,
|
||||
attack_ticks: u32,
|
||||
last_hurt_by_player: HashSet<u32>,
|
||||
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
|
||||
/// Client-ticked block-entity animation state (`game/block_entity_anims.rs`).
|
||||
be_anims: horizon_client::block_entity_anim::BlockEntityAnims,
|
||||
/// Item being used (eaten): hotbar slot and ticks used.
|
||||
using: Option<(usize, u32)>,
|
||||
/// Camera.oldFovModifier / fovModifier.
|
||||
@@ -635,6 +663,8 @@ struct Game<'a> {
|
||||
/// The source of a command run through /execute (the player otherwise).
|
||||
command_source: Option<commands::execute::Source>,
|
||||
titles: titles::Titles,
|
||||
/// `Hud.toolHighlightTimer`: the selected item name.
|
||||
tool_highlight: horizon_client::hud_overlays::ToolHighlight,
|
||||
applied_modifiers: Vec<(String, String)>,
|
||||
experience: Experience,
|
||||
orbs: Vec<ExperienceOrb>,
|
||||
@@ -679,6 +709,8 @@ struct Game<'a> {
|
||||
map_frame_model: frames::FrameModel,
|
||||
glow_map_frame_model: frames::FrameModel,
|
||||
armor_stands: Vec<horizon_client::entities::ArmorStand>,
|
||||
/// Entities of types Horizon does not simulate.
|
||||
others: Vec<commands::OtherEntity>,
|
||||
armor_stand_assets: armor_stands::ArmorStandAssets,
|
||||
boats: Vec<boats::Boat>,
|
||||
boat_models: boats::BoatModels,
|
||||
@@ -702,12 +734,13 @@ struct Game<'a> {
|
||||
/// The ender inventory (27 slots) and the ender chest showing it.
|
||||
ender_items: Vec<Option<ItemStack>>,
|
||||
ender_open: Option<(i32, i32, i32)>,
|
||||
/// Contents of broken shulker boxes waiting for their dropped item.
|
||||
pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
|
||||
/// Layers of broken banners waiting for their dropped item.
|
||||
pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>,
|
||||
/// Custom names of broken containers, for the dropped item (`copy_components`).
|
||||
pending_names: HashMap<[i32; 3], (String, String)>,
|
||||
/// Block entity data of broken blocks waiting for their dropped item.
|
||||
pending: spill::Pending,
|
||||
/// The chest each copper golem has open (`CopperGolem.openedChestPos`).
|
||||
golem_openers: HashMap<u32, (i32, i32, i32)>,
|
||||
/// Item entities spawned and block entities removed while the block
|
||||
/// behaviour ran (spilled contents, popped resources).
|
||||
spill: spill::Spill,
|
||||
/// The recipe book of the open screen (game/recipe_book.rs).
|
||||
recipe_ui: recipe_book::RecipeUi,
|
||||
/// The horse inventory (game/mount_menu.rs).
|
||||
@@ -738,7 +771,9 @@ struct Game<'a> {
|
||||
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
|
||||
lan_acting: Option<u32>,
|
||||
/// Command feedback to forward to a guest.
|
||||
chat_capture: Option<Vec<String>>,
|
||||
chat_capture: Option<Vec<horizon_client::text::Text>>,
|
||||
/// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends.
|
||||
cmds: commands::extra::CommandExtras,
|
||||
/// Allow Cheats: whether guests may be given commands.
|
||||
cheats: bool,
|
||||
ui: chat::UiState,
|
||||
@@ -781,6 +816,13 @@ impl Dim {
|
||||
_ => Self::Overworld,
|
||||
}
|
||||
}
|
||||
/// `Level.getMaxY`: the dimension type's minimum y plus height, less one.
|
||||
fn max_y(self) -> i32 {
|
||||
match self {
|
||||
Self::Overworld => MIN_Y + HEIGHT - 1,
|
||||
Self::Nether | Self::End => 255,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn facing_offset(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -1078,33 +1120,36 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Block.getDrops`: the block's loot table, drawing from its server random
|
||||
/// sequence (`LootContext.Builder.create`), else the level random.
|
||||
fn block_loot(&mut self, state: BlockStateId, held: Option<&ItemStack>) -> Vec<ItemStack> {
|
||||
fn block_loot_at(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
) -> Vec<ItemStack> {
|
||||
let registry = self.res.assets.registry;
|
||||
let dynamic = self.pending.dynamic(pos);
|
||||
match self.res.items.block_loot_sequence(registry, state) {
|
||||
Some(sequence) => {
|
||||
let random = self.rand_sequences.get(&sequence, self.level.seed);
|
||||
self.res.items.block_drops(registry, state, held, random)
|
||||
self.res
|
||||
.items
|
||||
.block_drops_with(registry, state, held, &dynamic, random)
|
||||
}
|
||||
None => self
|
||||
.res
|
||||
.items
|
||||
.block_drops(registry, state, held, &mut self.world.random),
|
||||
None => self.res.items.block_drops_with(
|
||||
registry,
|
||||
state,
|
||||
held,
|
||||
&dynamic,
|
||||
&mut self.world.random,
|
||||
),
|
||||
}
|
||||
}
|
||||
/// Block.popResource
|
||||
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
|
||||
self.attach_shulker_contents(pos, &mut stack);
|
||||
self.attach_container_name(pos, &mut stack);
|
||||
self.attach_banner_layers(pos, &mut stack);
|
||||
self.pending.attach(pos, &mut stack);
|
||||
// Block.popResource: Mth.nextDouble offsets from the level random; the
|
||||
// motion is `new ItemEntity(..)`'s own, from the item's random.
|
||||
let r = &mut self.world.random;
|
||||
let mut offset = || -0.25 + r.next_double() * 0.5;
|
||||
let p = [
|
||||
f64::from(pos[0]) + 0.5 + offset(),
|
||||
f64::from(pos[1]) + 0.5 + offset() - 0.125,
|
||||
f64::from(pos[2]) + 0.5 + offset(),
|
||||
];
|
||||
let p = spill::pop_position(&mut self.world.random, pos);
|
||||
let v = dispenser::new_item_motion();
|
||||
self.spawn_item(stack, p, v, 10);
|
||||
}
|
||||
@@ -1266,8 +1311,13 @@ impl Game<'_> {
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
rules,
|
||||
rand_sequences: &mut self.rand_sequences,
|
||||
pending: &mut self.pending,
|
||||
spill: &mut self.spill,
|
||||
};
|
||||
f(&self.res.behaviours, &mut level, &mut self.block_ticks)
|
||||
let result = f(&self.res.behaviours, &mut level, &mut self.block_ticks);
|
||||
self.flush_spill();
|
||||
result
|
||||
}
|
||||
/// Level.setBlock(pos, state, UPDATE_ALL) with neighbour/shape updates.
|
||||
fn level_set(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
|
||||
@@ -1452,18 +1502,9 @@ impl Game<'_> {
|
||||
};
|
||||
self.audio.play(&name, Some(c), volume, pitch);
|
||||
}
|
||||
// Handled as the behaviour emits it (GameLevel::emit).
|
||||
LevelEvent::DropResources { pos, state } => {
|
||||
self.jukebox_removed([pos.x, pos.y, pos.z]);
|
||||
if let Some(entity) = self.world.block_entities.remove(&(pos.x, pos.y, pos.z)) {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
self.release_contents([pos.x, pos.y, pos.z], entity, &name);
|
||||
}
|
||||
let drops = self.block_loot(state, None);
|
||||
for d in drops {
|
||||
if &*d.item != "minecraft:air" {
|
||||
self.pop_resource([pos.x, pos.y, pos.z], d);
|
||||
}
|
||||
}
|
||||
self.with_level(|_, level, _| level.drop_resources_now(pos, state));
|
||||
}
|
||||
LevelEvent::FallingBlock { pos, state } => {
|
||||
let p = Vec3::new(
|
||||
@@ -1495,15 +1536,8 @@ impl Game<'_> {
|
||||
self.pop_resource([pos.x, pos.y, pos.z], rest);
|
||||
}
|
||||
}
|
||||
PlayerEffect::DropItem(item) => self.pop_resource(
|
||||
[pos.x, pos.y + 1, pos.z],
|
||||
ItemStack {
|
||||
item,
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
),
|
||||
// Popped as the behaviour emits it (GameLevel::emit).
|
||||
PlayerEffect::DropItem(_) => {}
|
||||
PlayerEffect::EatCake => {
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
let food = &mut p.health.food;
|
||||
@@ -1561,22 +1595,6 @@ impl Game<'_> {
|
||||
state,
|
||||
kind: "spawn_ghastling",
|
||||
} => self.spawn_ghastling([pos.x, pos.y, pos.z], state),
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "pop_block_item",
|
||||
} => {
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
self.pop_resource(
|
||||
[pos.x, pos.y, pos.z],
|
||||
ItemStack {
|
||||
item,
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
LevelEvent::GameEvent { pos, event, state } => {
|
||||
self.sculk_level_event(pos, event, state)
|
||||
}
|
||||
@@ -1585,6 +1603,9 @@ impl Game<'_> {
|
||||
state,
|
||||
kind: "shrieker_respond",
|
||||
} => self.shrieker_block_event(pos, state),
|
||||
LevelEvent::BlockEntityEvent { pos, a, b, .. } => {
|
||||
self.block_entity_event([pos.x, pos.y, pos.z], a, b)
|
||||
}
|
||||
LevelEvent::GrowTree { .. }
|
||||
| LevelEvent::PlaceFeature { .. }
|
||||
| LevelEvent::BlockEvent { .. } => {}
|
||||
@@ -1609,6 +1630,7 @@ impl Game<'_> {
|
||||
self.craft_size = 3;
|
||||
} else if &*name == "minecraft:ender_chest" {
|
||||
self.open_ender_chest(key);
|
||||
self.container_opener_event(key, true);
|
||||
let at = [
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
@@ -1621,9 +1643,12 @@ impl Game<'_> {
|
||||
self.world.block_entities.entry(key).or_insert_with(|| {
|
||||
BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new()))
|
||||
});
|
||||
} else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) {
|
||||
// ShulkerBoxBlock.canOpen: the lid has no room; nothing opens.
|
||||
} else if let Some(entity) = BlockEntity::for_block(&name) {
|
||||
self.world.block_entities.entry(key).or_insert(entity);
|
||||
self.container = Some(key);
|
||||
self.container_opener_event(key, true);
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_open",
|
||||
[key.0, key.1, key.2],
|
||||
@@ -1788,23 +1813,63 @@ impl Game<'_> {
|
||||
self.with_player_actor(|game| game.break_block_as_player(pos))
|
||||
}
|
||||
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
|
||||
// ServerPlayerGameMode.destroyBlock.
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let facts = self.res.facts.get(state).clone();
|
||||
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
|
||||
if self.guarded_by_piglins(&facts.name) {
|
||||
self.anger_piglins(false);
|
||||
}
|
||||
if !self.creative {
|
||||
// Block.playerDestroy: the mined statistic and the exhaustion.
|
||||
self.stats.add("mined", &facts.name, 1);
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0);
|
||||
}
|
||||
// The block entity as it was, for what the drops copy from it.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
|
||||
let name = self.world.block_names.get(&key).cloned();
|
||||
self.pending.record(pos, &entity, &facts.name, name);
|
||||
} else if let Some(tag) = spill::saved_entity(&self.world, pos) {
|
||||
self.pending.record_saved(pos, &tag);
|
||||
}
|
||||
self.creaking_heart_broken(pos);
|
||||
// playerWillDestroy and Level.removeBlock through the vanilla behaviour
|
||||
// library: the block entity's side effects (containers spill), neighbour
|
||||
// and shape updates, and the destroy event (particles, sound).
|
||||
let creative = self.creative;
|
||||
let removed = self.with_level(|b, level, ticks| {
|
||||
b.player_destroy_block(
|
||||
level,
|
||||
ticks,
|
||||
BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
creative,
|
||||
)
|
||||
});
|
||||
if removed && !creative {
|
||||
let held = self.held().cloned();
|
||||
// ItemStack.mineBlock: tools lose durability on blocks with nonzero hardness.
|
||||
if facts.hardness > 0.0
|
||||
&& let Some(stack) = self.inventory[self.selected].clone()
|
||||
&& let Some(max) = self
|
||||
.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.filter(|i| i.max_damage > 0 && !i.tool.is_empty())
|
||||
.map(|i| i.max_damage)
|
||||
{
|
||||
let loss = self.durability_loss(&stack, 1);
|
||||
if let Some(stack) = self.inventory[self.selected].as_mut() {
|
||||
stack.damage += loss;
|
||||
if stack.damage >= max {
|
||||
self.inventory[self.selected] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let harvest = !facts.requires_tool
|
||||
|| self.res.items.correct_for_drops(held.as_ref(), &facts.name);
|
||||
if harvest {
|
||||
let drops = self.block_loot(state, held.as_ref());
|
||||
// Block.playerDestroy: the mined statistic, the exhaustion and the drops.
|
||||
self.stats.add("mined", &facts.name, 1);
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0);
|
||||
}
|
||||
let drops = self.block_loot_at(pos, state, held.as_ref());
|
||||
let silk = held
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0);
|
||||
@@ -1829,53 +1894,8 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Tools lose durability on blocks with nonzero hardness.
|
||||
if facts.hardness > 0.0
|
||||
&& let Some(stack) = self.inventory[self.selected].clone()
|
||||
&& let Some(max) = self
|
||||
.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.filter(|i| i.max_damage > 0 && !i.tool.is_empty())
|
||||
.map(|i| i.max_damage)
|
||||
{
|
||||
let loss = self.durability_loss(&stack, 1);
|
||||
if let Some(stack) = self.inventory[self.selected].as_mut() {
|
||||
stack.damage += loss;
|
||||
if stack.damage >= max {
|
||||
self.inventory[self.selected] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let replacement = if facts.waterlogged {
|
||||
self.res.assets.registry.default_state("minecraft:water")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
.unwrap_or(self.world.air);
|
||||
self.creaking_heart_broken(pos);
|
||||
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
|
||||
// Containers.dropContents (shulker boxes keep theirs).
|
||||
let name = facts.name.clone();
|
||||
self.release_contents(pos, entity, &name);
|
||||
if self.container == Some((pos[0], pos[1], pos[2])) {
|
||||
self.container = None;
|
||||
self.screen = Screen::Playing;
|
||||
}
|
||||
}
|
||||
let _ = replacement;
|
||||
// Block.playerDestroy through the vanilla behaviour library: removal,
|
||||
// neighbour and shape updates, and the destroy event (particles, sound).
|
||||
let creative = self.creative;
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.player_destroy_block(
|
||||
level,
|
||||
ticks,
|
||||
BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
creative,
|
||||
);
|
||||
});
|
||||
self.pending.clear(pos);
|
||||
self.process_level_events()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -2500,6 +2520,8 @@ impl Game<'_> {
|
||||
}
|
||||
self.apply_totem();
|
||||
self.update_totem_ready();
|
||||
self.tick_command_extras();
|
||||
let camera_eye = self.camera_eye_height();
|
||||
if self.riding.is_some() && self.player.is_some() {
|
||||
let playing = self.screen == Screen::Playing;
|
||||
let held = |k| playing && self.keys.contains(&k);
|
||||
@@ -2597,7 +2619,7 @@ impl Game<'_> {
|
||||
}
|
||||
let feet = [player.position.x, player.position.y, player.position.z];
|
||||
self.previous_eye = self.eye;
|
||||
self.eye += (player.dimensions.eye_height - self.eye) * 0.5;
|
||||
self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5;
|
||||
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
|
||||
self.tick_avatar(before, riding);
|
||||
self.record_combat(&events);
|
||||
@@ -2707,7 +2729,16 @@ impl Game<'_> {
|
||||
self.tick_effects();
|
||||
self.tick_burning();
|
||||
self.tick_using();
|
||||
self.titles.tick();
|
||||
self.tick_hud();
|
||||
// The player's digging comes in with its packets, before the level
|
||||
// ticks; ServerLevel.tick then runs the scheduled and random block
|
||||
// ticks before any entity, so what they drop or spawn (dispensed
|
||||
// items, popped crops) moves on the tick it appears, as in vanilla.
|
||||
self.tick_mining()?;
|
||||
self.postprocess_chunks()?;
|
||||
if running {
|
||||
self.tick_blocks()?;
|
||||
}
|
||||
if running {
|
||||
self.tick_paintings();
|
||||
self.tick_item_frames();
|
||||
@@ -2722,13 +2753,13 @@ impl Game<'_> {
|
||||
self.tick_tridents();
|
||||
self.tick_rockets();
|
||||
}
|
||||
self.tick_mining()?;
|
||||
if running {
|
||||
self.tick_items();
|
||||
}
|
||||
self.spawn_loaded_entities();
|
||||
if running {
|
||||
self.tick_mobs()?;
|
||||
self.tick_copper_golems();
|
||||
self.tick_experience();
|
||||
}
|
||||
self.tick_lan();
|
||||
@@ -2738,9 +2769,7 @@ impl Game<'_> {
|
||||
if running {
|
||||
self.tick_end()?;
|
||||
}
|
||||
self.postprocess_chunks()?;
|
||||
if running {
|
||||
self.tick_blocks()?;
|
||||
self.tick_falling()?;
|
||||
self.tick_tnt()?;
|
||||
}
|
||||
@@ -2749,17 +2778,10 @@ impl Game<'_> {
|
||||
self.tick_sculk()?;
|
||||
self.tick_brewing_stands()?;
|
||||
}
|
||||
if let Some(r) = &self.renderer {
|
||||
let eye = self.player.as_ref().map(|p| {
|
||||
[
|
||||
p.position.x,
|
||||
p.position.y + f64::from(self.eye),
|
||||
p.position.z,
|
||||
]
|
||||
});
|
||||
self.res.block_entity_render.tick(r.block_entities(), eye);
|
||||
}
|
||||
if running {
|
||||
// ClientLevel.tickBlockEntities (not while paused or frozen):
|
||||
// chest lids, books, shulker boxes, bells, conduits, heads.
|
||||
self.tick_block_entity_anims();
|
||||
self.tick_particles();
|
||||
}
|
||||
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
|
||||
@@ -2854,26 +2876,30 @@ impl Game<'_> {
|
||||
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
|
||||
// special renderers included), then the decorations.
|
||||
self.draw_item_model(batch, stack, x, y);
|
||||
let atlas = &self.res.atlas;
|
||||
if stack.count > 1 {
|
||||
let text = stack.count.to_string();
|
||||
let w = HudBatch::text_width(atlas, &text);
|
||||
batch.text(atlas, &text, x + 17.0 - w, y + 9.0, u32::MAX, true);
|
||||
}
|
||||
if let Some(info) = self.res.items.get(&stack.item)
|
||||
&& info.max_damage > 0
|
||||
&& stack.damage > 0
|
||||
{
|
||||
let f = 1.0 - stack.damage as f32 / info.max_damage as f32;
|
||||
let width = (13.0 * f).round();
|
||||
let hue = f / 3.0;
|
||||
let (r, g) = (
|
||||
(255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8,
|
||||
(255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8,
|
||||
);
|
||||
batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255));
|
||||
batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255));
|
||||
}
|
||||
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
||||
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
|
||||
let max_damage = self
|
||||
.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.map_or(0, |info| info.max_damage as i32);
|
||||
let decorations = hud_overlays::ItemDecorations {
|
||||
count: stack.count,
|
||||
count_text: None,
|
||||
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
|
||||
cooldown: 0.0,
|
||||
};
|
||||
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
|
||||
hud_layout::PoseOp::Translate(x, y),
|
||||
])];
|
||||
draws.extend(hud_overlays::item_decorations(
|
||||
0,
|
||||
0,
|
||||
&decorations,
|
||||
&self.res.atlas.font,
|
||||
));
|
||||
draws.push(hud_layout::GuiDraw::Pop);
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
|
||||
let mut batch = HudBatch::new(size);
|
||||
@@ -2941,8 +2967,12 @@ impl Game<'_> {
|
||||
}
|
||||
self.draw_effect_icons(&mut batch);
|
||||
// Hud: the action bar and titles draw over the hotbar (nextStratum).
|
||||
self.draw_boss_bar(&mut batch);
|
||||
self.draw_custom_bossbars(&mut batch, 12.0 + 19.0 * self.builtin_bar_count() as f32);
|
||||
self.draw_boss_bars(&mut batch);
|
||||
// Hud.extractSleepOverlay, under the sidebar, titles and chat.
|
||||
if let Some((_, ticks)) = self.sleeping {
|
||||
let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32);
|
||||
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
|
||||
}
|
||||
self.draw_titles(&mut batch);
|
||||
self.draw_scoreboard(&mut batch);
|
||||
self.draw_subtitles(&mut batch);
|
||||
@@ -3012,6 +3042,9 @@ impl Game<'_> {
|
||||
let draws = self.health_hud.layout(&inputs, wi, hi);
|
||||
hud_layout::paint(&mut batch, atlas, &draws);
|
||||
}
|
||||
if !spectator {
|
||||
self.draw_selected_name(&mut batch, !self.creative);
|
||||
}
|
||||
let atlas = &self.res.atlas;
|
||||
if self.debug {
|
||||
let p = self
|
||||
@@ -3113,12 +3146,6 @@ impl Game<'_> {
|
||||
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
|
||||
}
|
||||
self.draw_chat(&mut batch);
|
||||
let atlas = &self.res.atlas;
|
||||
if let Some((_, ticks)) = self.sleeping {
|
||||
// Gui sleep overlay fading in over 100 ticks.
|
||||
let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8;
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a));
|
||||
}
|
||||
match self.screen {
|
||||
Screen::Paused => self.draw_pause_menu(&mut batch),
|
||||
Screen::Dead => self.draw_death_screen(&mut batch),
|
||||
@@ -3470,6 +3497,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.craft_size = 2;
|
||||
if let Some(key) = self.container.take() {
|
||||
self.container_opener_event(key, false);
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_close",
|
||||
[key.0, key.1, key.2],
|
||||
@@ -4115,14 +4143,8 @@ impl Game<'_> {
|
||||
}
|
||||
// Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls...
|
||||
if let Some(r) = &self.renderer {
|
||||
let lid = |p: [i32; 3]| {
|
||||
let (prev, cur) = self
|
||||
.chest_open
|
||||
.get(&(p[0], p[1], p[2]))
|
||||
.copied()
|
||||
.unwrap_or((0.0, 0.0));
|
||||
prev + (cur - prev) * alpha as f32
|
||||
};
|
||||
let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32);
|
||||
let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32);
|
||||
let (view_yaw, view_pitch) =
|
||||
if self.camera_type == perspective::CameraType::ThirdPersonFront {
|
||||
(self.yaw + 180.0, -self.pitch)
|
||||
@@ -4138,10 +4160,11 @@ impl Game<'_> {
|
||||
-view_pitch.to_radians(),
|
||||
0.0,
|
||||
),
|
||||
anim: &|_| horizon_client::block_entity_render::BlockAnim::default(),
|
||||
anim: &anim,
|
||||
texts: None,
|
||||
partial: alpha as f32,
|
||||
game_time: self.world.game_time,
|
||||
max_y: self.dim.max_y(),
|
||||
world: &self.world,
|
||||
sprites: &self.res.atlas.sprites,
|
||||
nether: self.dim == Dim::Nether,
|
||||
@@ -4603,20 +4626,6 @@ impl Game<'_> {
|
||||
self.tick_jukeboxes();
|
||||
self.tick_beacons();
|
||||
self.tick_creaking_hearts()?;
|
||||
// ChestLidController: 0.1 per tick towards open/closed.
|
||||
if let Some(key) = self.container {
|
||||
self.chest_open.entry(key).or_insert((0.0, 0.0));
|
||||
}
|
||||
let open = self.container;
|
||||
self.chest_open.retain(|k, (prev, cur)| {
|
||||
*prev = *cur;
|
||||
*cur = if Some(*k) == open {
|
||||
(*cur + 0.1).min(1.0)
|
||||
} else {
|
||||
(*cur - 0.1).max(0.0)
|
||||
};
|
||||
*cur > 0.0 || *prev > 0.0
|
||||
});
|
||||
let mut lit_changes = Vec::new();
|
||||
for (pos, entity) in self.world.block_entities.iter_mut() {
|
||||
if let BlockEntity::Furnace(f) = entity
|
||||
@@ -5001,6 +5010,11 @@ impl Game<'_> {
|
||||
self.restore_effects();
|
||||
self.mining = None;
|
||||
self.container = None;
|
||||
let kinds = std::mem::take(&mut self.be_anims.kinds);
|
||||
self.be_anims = horizon_client::block_entity_anim::BlockEntityAnims {
|
||||
kinds,
|
||||
..Default::default()
|
||||
};
|
||||
self.carried = None;
|
||||
self.using = None;
|
||||
self.screen = Screen::Playing;
|
||||
@@ -5961,26 +5975,36 @@ impl Game<'_> {
|
||||
Ok(false)
|
||||
}
|
||||
/// ExperienceOrb.award: split into vanilla orb sizes.
|
||||
/// `ExperienceOrb.award`: orbs of the largest sizes; each draws the id
|
||||
/// `tryMergeToExisting` compares from the level random, then moves with
|
||||
/// its own random.
|
||||
fn spawn_orbs(&mut self, at: [f64; 3], mut value: u32) {
|
||||
while value > 0 {
|
||||
let v = ExperienceOrb::split(value);
|
||||
value -= v;
|
||||
let r = &mut self.world.random;
|
||||
let p = Vec3::new(at[0], at[1], at[2]);
|
||||
self.orbs.push(ExperienceOrb {
|
||||
position: p,
|
||||
previous: p,
|
||||
velocity: Vec3::new(
|
||||
(r.next_double() * 0.2 - 0.1) * 2.0,
|
||||
r.next_double() * 0.2 * 2.0,
|
||||
(r.next_double() * 0.2 - 0.1) * 2.0,
|
||||
),
|
||||
value: v,
|
||||
age: 0,
|
||||
on_ground: false,
|
||||
});
|
||||
let _merge_id = self.world.random.next_int_bound(40);
|
||||
self.add_orb(at, v);
|
||||
}
|
||||
}
|
||||
/// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from
|
||||
/// the orb's own random.
|
||||
fn add_orb(&mut self, at: [f64; 3], value: u32) {
|
||||
let mut r = dispenser::entity_random();
|
||||
let _yaw = r.next_float();
|
||||
let p = Vec3::new(at[0], at[1], at[2]);
|
||||
self.orbs.push(ExperienceOrb {
|
||||
position: p,
|
||||
previous: p,
|
||||
velocity: Vec3::new(
|
||||
(r.next_double() * 0.2 - 0.1) * 2.0,
|
||||
r.next_double() * 0.2 * 2.0,
|
||||
(r.next_double() * 0.2 - 0.1) * 2.0,
|
||||
),
|
||||
value,
|
||||
age: 0,
|
||||
on_ground: false,
|
||||
});
|
||||
}
|
||||
/// DropExperienceBlock / RedStoneOreBlock / SculkBlock experience ranges.
|
||||
fn block_experience(&mut self, name: &str) -> u32 {
|
||||
let (min, max) = match name.trim_start_matches("minecraft:") {
|
||||
@@ -7079,6 +7103,14 @@ impl Game<'_> {
|
||||
hand: &hand,
|
||||
screen: &screen,
|
||||
game_time: self.world.game_time as f32,
|
||||
shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0,
|
||||
end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| {
|
||||
self.res
|
||||
.atlas
|
||||
.sprites
|
||||
.get(n)
|
||||
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0])
|
||||
}),
|
||||
ticks: self.ticks,
|
||||
darkness: self.darkness_lighting(alpha as f32),
|
||||
night_vision: self.night_vision_intensity(),
|
||||
@@ -8035,7 +8067,11 @@ pub fn run() -> Result<()> {
|
||||
raiding: Default::default(),
|
||||
attack_ticks: 100,
|
||||
last_hurt_by_player: HashSet::new(),
|
||||
chest_open: HashMap::new(),
|
||||
be_anims: {
|
||||
let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default();
|
||||
anims.classify(registry_owner.registry);
|
||||
anims
|
||||
},
|
||||
using: None,
|
||||
view: Default::default(),
|
||||
limiter: horizon_client::window::FramerateLimiter::new(0),
|
||||
@@ -8048,6 +8084,7 @@ pub fn run() -> Result<()> {
|
||||
shield_cooldown: 0,
|
||||
command_source: None,
|
||||
titles: Default::default(),
|
||||
tool_highlight: Default::default(),
|
||||
applied_modifiers: Vec::new(),
|
||||
experience: Experience::default(),
|
||||
orbs: Vec::new(),
|
||||
@@ -8083,6 +8120,7 @@ pub fn run() -> Result<()> {
|
||||
map_frame_model: frames::bake_frame(&root, "item_frame_map"),
|
||||
glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"),
|
||||
armor_stands: Vec::new(),
|
||||
others: Vec::new(),
|
||||
armor_stand_assets: armor_stands::ArmorStandAssets::load(&root),
|
||||
boats: Vec::new(),
|
||||
boat_models: boats::BoatModels::load(&root),
|
||||
@@ -8101,9 +8139,9 @@ pub fn run() -> Result<()> {
|
||||
riding: None,
|
||||
ender_items: vec![None; 27],
|
||||
ender_open: None,
|
||||
pending_shulker: HashMap::new(),
|
||||
pending_banner: HashMap::new(),
|
||||
pending_names: HashMap::new(),
|
||||
pending: Default::default(),
|
||||
golem_openers: HashMap::new(),
|
||||
spill: Default::default(),
|
||||
recipe_ui: Default::default(),
|
||||
mount_menu: Default::default(),
|
||||
hook: None,
|
||||
@@ -8126,6 +8164,7 @@ pub fn run() -> Result<()> {
|
||||
lan_events: Vec::new(),
|
||||
lan_acting: None,
|
||||
chat_capture: None,
|
||||
cmds: Default::default(),
|
||||
cheats: true,
|
||||
ui: Default::default(),
|
||||
combat: Default::default(),
|
||||
@@ -8172,6 +8211,12 @@ pub fn run() -> Result<()> {
|
||||
}
|
||||
None => game.title = Some(Title::new(std::env::current_dir()?.join("saves"))),
|
||||
}
|
||||
if let (Some(script), Some(output)) = (
|
||||
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
|
||||
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
|
||||
) {
|
||||
return game.run_command_harness(script.as_ref(), output.as_ref());
|
||||
}
|
||||
EventLoop::new()?.run_app(&mut game)?;
|
||||
if let Some(path) = &game.options.report {
|
||||
let report = serde_json::json!({
|
||||
|
||||
@@ -168,6 +168,12 @@ fn now_text() -> String {
|
||||
rem % 60
|
||||
)
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `ItemPredicate.test` (the `item_filter` of a filtered item modifier).
|
||||
pub(super) fn loot_item_filter(&self, predicate: &Value, s: &ItemStack) -> bool {
|
||||
adv::item(predicate, &item_view(s), &View(self))
|
||||
}
|
||||
}
|
||||
pub(super) fn item_view(s: &ItemStack) -> ItemView {
|
||||
ItemView {
|
||||
id: s.item.to_string(),
|
||||
@@ -505,6 +511,17 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.check_inventory_trigger();
|
||||
// ServerPlayer.tick: PlayerTrigger.TICK every tick.
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:tick", |c, w| {
|
||||
let ctx = adv::Entities {
|
||||
this: Some(&me),
|
||||
origin: me.position,
|
||||
tool: None,
|
||||
block_pos: None,
|
||||
};
|
||||
adv::conditions(&c["player"], &ctx, w)
|
||||
});
|
||||
if self.ticks.is_multiple_of(20) {
|
||||
let me = self.player_entity();
|
||||
self.trigger("minecraft:location", |c, w| {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
banner::{self, BannerLayer},
|
||||
containers::{Banner, BlockEntity},
|
||||
containers::BlockEntity,
|
||||
items::ItemStack,
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// A placed banner takes the item's layers and name.
|
||||
pub(super) fn fill_placed_banner(&mut self, pos: [i32; 3], stack: &ItemStack) {
|
||||
self.pending_banner.remove(&pos);
|
||||
self.pending.banner.remove(&pos);
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
@@ -30,20 +30,6 @@ impl Game<'_> {
|
||||
b.name = stack.custom_name().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
/// The layers a banner dropped at `pos` carries.
|
||||
pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if !stack.item.ends_with("_banner") {
|
||||
return;
|
||||
}
|
||||
if let Some(Banner { layers, name }) = self.pending_banner.remove(&pos) {
|
||||
let data = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
if name.is_some() {
|
||||
data.custom_name = name;
|
||||
}
|
||||
stack.tidy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture names and tints of banner layers (`Sheets.getBannerSprite`).
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
//! The client side of animated block entities (`horizon_client::block_entity_anim`):
|
||||
//! their client tickers (`Level.tickBlockEntities` on the client level) and
|
||||
//! the block events that drive them (`ClientboundBlockEventPacket` reaching
|
||||
//! `BlockEntity.triggerEvent`). The renderer reads the resulting state through
|
||||
//! [`Game::block_anim`] and [`Game::chest_lid`].
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_render::BlockAnim,
|
||||
collisions::{SceneCollisions, no_collision_empty},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The handle of the local player among a bell's gathered entities.
|
||||
const PLAYER: u64 = u64::MAX;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `BlockEntity.triggerEvent(a, b)` on the client copy of the block entity at `pos`.
|
||||
pub(super) fn block_entity_event(&mut self, pos: [i32; 3], a: i32, b: i32) {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]).0;
|
||||
let time = self.world.game_time;
|
||||
match self.be_anims.ticker(state) {
|
||||
Some(Ticker::Lid) => {
|
||||
self.be_anims
|
||||
.chests
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.trigger_event(a, b);
|
||||
}
|
||||
Some(Ticker::Shulker { .. }) => {
|
||||
self.be_anims
|
||||
.shulkers
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.trigger_event(a, b);
|
||||
}
|
||||
Some(Ticker::Bell) => {
|
||||
let gathered = self.bell_gather(pos);
|
||||
self.be_anims
|
||||
.bells
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.trigger_event(a, b, time, || gathered);
|
||||
}
|
||||
Some(Ticker::Pot) => {
|
||||
self.be_anims
|
||||
.pots
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.trigger_event(a, b, time);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// A player opened (`open`) or closed the container at `key`: the opener
|
||||
/// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity`
|
||||
/// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes,
|
||||
/// on both halves of a double chest (`CompoundContainer`).
|
||||
pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) {
|
||||
// Spectators never count as openers.
|
||||
if self.spectator() {
|
||||
return;
|
||||
}
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]).0;
|
||||
match self.be_anims.ticker(state) {
|
||||
Some(Ticker::Lid) => {
|
||||
let count = i32::from(open);
|
||||
self.block_entity_event(pos, 1, count);
|
||||
if let Some(other) = self.chest_other_half(key) {
|
||||
self.block_entity_event([other.0, other.1, other.2], 1, count);
|
||||
}
|
||||
}
|
||||
Some(Ticker::Shulker { .. }) => {
|
||||
let shulker = self.be_anims.shulkers.entry(pos).or_default();
|
||||
let (count, _) = if open {
|
||||
shulker.start_open()
|
||||
} else {
|
||||
shulker.stop_open()
|
||||
};
|
||||
self.block_entity_event(pos, 1, count);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `BellBlockEntity.updateEntities`: the living entities whose bounding
|
||||
/// box meets the bell's block box inflated by 48.
|
||||
fn bell_gather(&self, pos: [i32; 3]) -> Vec<u64> {
|
||||
let area = Aabb::new(
|
||||
Vec3::new(
|
||||
f64::from(pos[0]) - 48.0,
|
||||
f64::from(pos[1]) - 48.0,
|
||||
f64::from(pos[2]) - 48.0,
|
||||
),
|
||||
Vec3::new(
|
||||
f64::from(pos[0]) + 49.0,
|
||||
f64::from(pos[1]) + 49.0,
|
||||
f64::from(pos[2]) + 49.0,
|
||||
),
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
if self
|
||||
.player_view()
|
||||
.is_some_and(|p| p.bounds.intersects(area))
|
||||
{
|
||||
out.push(PLAYER);
|
||||
}
|
||||
for m in &self.mobs {
|
||||
if !m.removed && m.bounds().intersects(area) {
|
||||
out.push(u64::from(m.id));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `ShulkerBoxBlock.canOpen`: a closed box opens only when its lid has
|
||||
/// room to rise (`level.noCollision` of the half-open lid box).
|
||||
pub(super) fn shulker_can_open(&self, pos: [i32; 3]) -> bool {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]).0;
|
||||
let Some(Ticker::Shulker { facing }) = self.be_anims.ticker(state) else {
|
||||
return true;
|
||||
};
|
||||
let closed = self
|
||||
.be_anims
|
||||
.shulkers
|
||||
.get(&pos)
|
||||
.is_none_or(|s| s.status == ShulkerStatus::Closed);
|
||||
if !closed {
|
||||
return true;
|
||||
}
|
||||
let b = Shulker::lid_box(pos, facing);
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
no_collision_empty(
|
||||
&mut scene,
|
||||
Aabb::new(Vec3::new(b[0], b[1], b[2]), Vec3::new(b[3], b[4], b[5])),
|
||||
)
|
||||
}
|
||||
/// The client tickers of the loaded animated block entities, once per
|
||||
/// client tick (`ClientLevel.tickBlockEntities`).
|
||||
pub(super) fn tick_block_entity_anims(&mut self) {
|
||||
let Some(r) = &self.renderer else {
|
||||
return;
|
||||
};
|
||||
let present: HashMap<[i32; 3], Ticker> = r
|
||||
.block_entities()
|
||||
.filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?)))
|
||||
.collect();
|
||||
self.be_anims.retain_present(&present);
|
||||
let players: Vec<[f64; 3]> = match &self.player {
|
||||
Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raiders = self
|
||||
.res
|
||||
.stations
|
||||
.enchantments
|
||||
.entity_tags
|
||||
.get("minecraft:raiders")
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let frames = self
|
||||
.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:conduit_effect_block")
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect();
|
||||
positions.sort_unstable_by_key(|(p, _)| *p);
|
||||
for (pos, ticker) in positions {
|
||||
match ticker {
|
||||
Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(),
|
||||
Ticker::Book => {
|
||||
let anims = &mut self.be_anims;
|
||||
anims
|
||||
.books
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.tick(pos, &players, &mut anims.book_random);
|
||||
}
|
||||
Ticker::Shulker { facing } => {
|
||||
// The lid's push of entities in its way (moveCollidedEntities)
|
||||
// and the neighbour updates are left to the level.
|
||||
self.be_anims
|
||||
.shulkers
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.tick(pos, facing);
|
||||
}
|
||||
Ticker::Skull { powered } => {
|
||||
self.be_anims.skulls.entry(pos).or_default().tick(powered);
|
||||
}
|
||||
Ticker::Bell => {
|
||||
let player = self.player_view().map(|p| BellEntity {
|
||||
position: [p.position.x, p.position.y, p.position.z],
|
||||
alive: p.alive,
|
||||
raider: false,
|
||||
});
|
||||
let mobs = &self.mobs;
|
||||
let entity = |h: u64| {
|
||||
if h == PLAYER {
|
||||
return player;
|
||||
}
|
||||
let m = mobs.iter().find(|m| u64::from(m.id) == h)?;
|
||||
Some(BellEntity {
|
||||
position: [m.position.x, m.position.y, m.position.z],
|
||||
alive: m.alive() && !m.removed,
|
||||
raider: raiders.contains(&m.kind.id),
|
||||
})
|
||||
};
|
||||
let tick = self
|
||||
.be_anims
|
||||
.bells
|
||||
.entry(pos)
|
||||
.or_default()
|
||||
.tick(pos, entity);
|
||||
let centre = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
if tick.resonate {
|
||||
// The server's copy plays the resonance for everyone.
|
||||
self.audio
|
||||
.play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0);
|
||||
}
|
||||
if let Some((particles, glow)) = tick.ended {
|
||||
for (p, color) in particles {
|
||||
// ColorParticleOption.create(ENTITY_EFFECT, color): ARGB.
|
||||
let c = color as u32;
|
||||
let channel = |shift: u32| ((c >> shift) & 255) as f32 / 255.0;
|
||||
let options = ParticleOptions {
|
||||
color: [channel(16), channel(8), channel(0), channel(24)],
|
||||
..ParticleOptions::simple(ParticleType::EntityEffect)
|
||||
};
|
||||
self.particles.add(&options, p, [0.0; 3]);
|
||||
}
|
||||
// makeRaidersGlow.
|
||||
for m in self.mobs.iter_mut() {
|
||||
if glow.contains(&u64::from(m.id)) {
|
||||
m.add_effect("minecraft:glowing", 60, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ticker::Conduit => {
|
||||
let world = &self.world;
|
||||
let facts = &self.res.facts;
|
||||
let registry = self.res.assets.registry;
|
||||
let is_water = |p: [i32; 3]| {
|
||||
facts.get(world.block(p[0], p[1], p[2])).fluid
|
||||
== horizon_client::blocks::Fluid::Water
|
||||
};
|
||||
let is_frame = |p: [i32; 3]| {
|
||||
registry
|
||||
.state(world.block(p[0], p[1], p[2]))
|
||||
.is_some_and(|s| frames.contains(&s.name))
|
||||
};
|
||||
let time = world.game_time;
|
||||
let anims = &mut self.be_anims;
|
||||
let particles = anims.conduits.entry(pos).or_default().client_tick(
|
||||
pos,
|
||||
time,
|
||||
is_water,
|
||||
is_frame,
|
||||
None,
|
||||
self.particles.random(),
|
||||
);
|
||||
let nautilus = ParticleOptions::simple(ParticleType::Nautilus);
|
||||
for (p, v) in particles {
|
||||
self.particles.add(&nautilus, p, v);
|
||||
}
|
||||
}
|
||||
Ticker::Pot => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The renderer's view of the block entity at `pos`.
|
||||
pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim {
|
||||
self.be_anims
|
||||
.block_anim(pos, self.world.game_time, partial, Default::default())
|
||||
}
|
||||
/// `ChestLidController.getOpenness(partial)` at `pos`.
|
||||
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
self.be_anims.lid(pos, partial)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@ use super::{
|
||||
commands::{R, err},
|
||||
};
|
||||
use horizon_client::{
|
||||
bossbar::BossBars,
|
||||
bossbar::{self, BossBars},
|
||||
command::{Arg, Context},
|
||||
hud::{HudBatch, rgba},
|
||||
save,
|
||||
hud_overlays, save,
|
||||
scoreboard::{self as sb, Comp, comp_text},
|
||||
scoreboard_cmd::format_list,
|
||||
text::Text,
|
||||
@@ -334,26 +333,10 @@ impl Game<'_> {
|
||||
Ok(self.resolve_component(value))
|
||||
}
|
||||
|
||||
/// How many boss bars the dragon and withers already show.
|
||||
pub(super) fn builtin_bar_count(&self) -> usize {
|
||||
let dragon = usize::from(self.dragon.is_some() && self.dim == super::Dim::End);
|
||||
let withers = self.player.as_ref().map_or(0, |p| {
|
||||
self.mobs
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
m.species() == horizon_client::mobs::Species::Wither
|
||||
&& m.alive()
|
||||
&& m.position.distance_squared(p.position) <= 64.0 * 64.0
|
||||
})
|
||||
.count()
|
||||
});
|
||||
dragon + withers
|
||||
}
|
||||
// ---- drawing ------------------------------------------------------------------
|
||||
|
||||
/// `BossHealthOverlay`: the visible custom bars under the built-in ones.
|
||||
pub(super) fn draw_custom_bossbars(&self, batch: &mut HudBatch, mut y: f32) {
|
||||
let atlas = &self.res.atlas;
|
||||
/// The visible custom bars (`/bossbar`), after the built-in ones.
|
||||
pub(super) fn custom_bossbars(&self, bars: &mut Vec<hud_overlays::BossBar>) {
|
||||
for b in self
|
||||
.bosses
|
||||
.bars
|
||||
@@ -361,44 +344,18 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.filter(|b| b.visible && b.player)
|
||||
{
|
||||
if y >= batch.height / 3.0 {
|
||||
break;
|
||||
}
|
||||
let x = (batch.width / 2.0 - 91.0).floor();
|
||||
let sprite = |kind: &str| format!("gui/sprites/boss_bar/{kind}");
|
||||
batch.sprite(atlas, &sprite(&format!("{}_background", b.color)), x, y);
|
||||
if b.progress() > 0.0 {
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
&sprite(&format!("{}_progress", b.color)),
|
||||
x,
|
||||
y,
|
||||
b.progress(),
|
||||
);
|
||||
}
|
||||
if b.style != "progress" {
|
||||
batch.sprite(atlas, &sprite(&format!("{}_background", b.style)), x, y);
|
||||
if b.progress() > 0.0 {
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
&sprite(&format!("{}_progress", b.style)),
|
||||
x,
|
||||
y,
|
||||
b.progress(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let name = comp_text(&b.name);
|
||||
let w = atlas.font.width_text(&name);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&name,
|
||||
(batch.width / 2.0 - w / 2.0).floor(),
|
||||
y - 9.0,
|
||||
rgba(255, 255, 255, 255),
|
||||
true,
|
||||
);
|
||||
y += 19.0;
|
||||
bars.push(hud_overlays::BossBar {
|
||||
name: comp_text(&b.name),
|
||||
progress: b.progress(),
|
||||
color: bossbar::COLORS
|
||||
.iter()
|
||||
.position(|c| *c == b.color)
|
||||
.unwrap_or(0),
|
||||
overlay: bossbar::STYLES
|
||||
.iter()
|
||||
.position(|s| *s == b.style)
|
||||
.unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +286,11 @@ impl Game<'_> {
|
||||
reg.structures = list("data/minecraft/worldgen/structure");
|
||||
reg.biomes = list("data/minecraft/worldgen/biome");
|
||||
reg.clocks = list("data/minecraft/world_clock");
|
||||
reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()];
|
||||
reg.dimensions = vec![
|
||||
"minecraft:overworld".into(),
|
||||
"minecraft:the_nether".into(),
|
||||
"minecraft:the_end".into(),
|
||||
];
|
||||
reg.players = vec![PLAYER_NAME.into()];
|
||||
// Timelines of the overworld clock and their time markers.
|
||||
self.ui.markers.clear();
|
||||
@@ -324,6 +328,15 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Vanilla's built-in registries (mob effects, components, dialogs...).
|
||||
for dir in [&self.options.resources, &self.ui.vanilla_root] {
|
||||
if let Ok(bytes) = std::fs::read(dir.join("command-registries.json"))
|
||||
&& let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||
{
|
||||
self.ui.registries.fill_from_export(&v);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.timelines = self.ui.timelines.keys().cloned().collect();
|
||||
reg.time_markers = self
|
||||
@@ -368,7 +381,7 @@ impl Game<'_> {
|
||||
/// A chat message from the game (ChatComponent.addServerSystemMessage).
|
||||
pub(super) fn system_message(&mut self, text: Text) {
|
||||
if let Some(capture) = self.chat_capture.as_mut() {
|
||||
capture.push(text.plain());
|
||||
capture.push(text);
|
||||
return;
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
@@ -397,7 +410,7 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::game_dispatcher();
|
||||
if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) {
|
||||
self.ui.chat_screen = Some(screen);
|
||||
return;
|
||||
@@ -511,11 +524,11 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
screen.resize(batch.width, batch.height);
|
||||
let bg = self.ui.chat.options.background_opacity;
|
||||
let bg = self.ui.chat.options.background_opacity as f32;
|
||||
screen.draw(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
vanilla::dispatcher(),
|
||||
vanilla::game_dispatcher(),
|
||||
&self.ui.registries,
|
||||
self.cursor,
|
||||
bg,
|
||||
@@ -655,15 +668,19 @@ impl Game<'_> {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let below_world = p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64);
|
||||
let name = self.player_display_text();
|
||||
let message = match cause {
|
||||
Some(key) => Text::translate(&key, &[Text::literal(PLAYER_NAME)]),
|
||||
None if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) => {
|
||||
Text::translate("death.attack.outOfWorld", &[Text::literal(PLAYER_NAME)])
|
||||
}
|
||||
Some(key) => Text::translate(&key, &[name]),
|
||||
None if below_world => Text::translate("death.attack.outOfWorld", &[name]),
|
||||
None => self.combat_death_message(),
|
||||
};
|
||||
self.ui.death_text = Some(message.clone());
|
||||
self.system_message(message);
|
||||
// ServerPlayer.die: a team that hides death messages keeps it out of
|
||||
// the dying player's own chat (the death screen still shows it).
|
||||
if horizon_client::scoreboard::own_death_message_shown(self.player_team()) {
|
||||
self.system_message(message);
|
||||
}
|
||||
}
|
||||
/// F1 hides the HUD (and hand); the screenshot key still works.
|
||||
pub(super) fn toggle_hide_gui(&mut self) {
|
||||
|
||||
@@ -25,6 +25,9 @@ pub(super) struct CombatTracker {
|
||||
pub(super) last_hurt_mob: Option<(u32, i64)>,
|
||||
/// The mob whose projectile is hitting the player now.
|
||||
pub(super) projectile_owner: Option<u32>,
|
||||
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
|
||||
/// fire decides whom the blast may hurt.
|
||||
pub(super) explosion_source: Option<u32>,
|
||||
/// The player's fall distance before this tick's movement (as of the
|
||||
/// end of the last one).
|
||||
fall_before: f64,
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Headless command runner for `tools/test_command_exec_parity.py`: with
|
||||
//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world
|
||||
//! runs without a window. Each script line is a JSON operation: `cmd` runs a
|
||||
//! command as the player (Commands.performPrefixedCommand) and records every
|
||||
//! system message it produced, as styled spans, with the results reported to
|
||||
//! the player's `CommandResultCallback`; `tick` advances the game; `settle`
|
||||
//! waits until the terrain around the player is loaded.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, text::Text};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// A message as `[text, style]` runs with adjacent equal styles merged; the
|
||||
/// style lists colour, bold, italic, underlined, strikethrough, obfuscated
|
||||
/// and the suggested command.
|
||||
pub(super) fn spans(text: &Text) -> Value {
|
||||
let mut out: Vec<(String, Value)> = Vec::new();
|
||||
for span in &text.spans {
|
||||
if span.text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let s = &span.style;
|
||||
let style = json!([
|
||||
s.color,
|
||||
s.bold == Some(true),
|
||||
s.italic == Some(true),
|
||||
s.underlined == Some(true),
|
||||
s.strikethrough == Some(true),
|
||||
s.obfuscated == Some(true),
|
||||
]);
|
||||
match out.last_mut() {
|
||||
Some((t, last)) if *last == style => t.push_str(&span.text),
|
||||
_ => out.push((span.text.clone(), style)),
|
||||
}
|
||||
}
|
||||
Value::Array(out.into_iter().map(|(t, s)| json!([t, s])).collect())
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Load terrain until the player stands in lit chunks.
|
||||
fn harness_settle(&mut self, deadline: Instant) -> Result<()> {
|
||||
loop {
|
||||
self.update_world();
|
||||
self.spawn_player()?;
|
||||
if let Some(p) = &self.player {
|
||||
let (cx, cz) = (
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
);
|
||||
if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if std::env::var_os("HORIZON_HARNESS_DEBUG").is_some() {
|
||||
eprintln!(
|
||||
"settle: player {:?} center {:?} chunks {} pending {}",
|
||||
self.player.as_ref().map(|p| p.position),
|
||||
self.streaming.center,
|
||||
self.world.chunks.len(),
|
||||
self.streaming.pending()
|
||||
);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
return Err("command harness: terrain did not load".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
pub(super) fn run_command_harness(&mut self, script: &Path, output: &Path) -> Result<()> {
|
||||
let deadline = Instant::now()
|
||||
+ Duration::from_secs(
|
||||
std::env::var("HORIZON_HARNESS_TIMEOUT")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(600),
|
||||
);
|
||||
self.harness_settle(deadline)?;
|
||||
let mut out = String::new();
|
||||
for line in std::fs::read_to_string(script)?.lines() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let op: Value = serde_json::from_str(line)?;
|
||||
match op["op"].as_str().unwrap_or("") {
|
||||
"cmd" => {
|
||||
let command = op["cmd"].as_str().unwrap_or("");
|
||||
self.chat_capture = Some(Vec::new());
|
||||
self.cmds.results = Some(Vec::new());
|
||||
self.run_command(command.strip_prefix('/').unwrap_or(command));
|
||||
let messages = self.chat_capture.take().unwrap_or_default();
|
||||
let results = self.cmds.results.take().unwrap_or_default();
|
||||
if op["record"].as_bool() != Some(false) {
|
||||
let record = json!({
|
||||
"cmd": command,
|
||||
"messages": messages.iter().map(spans).collect::<Vec<_>>(),
|
||||
"results": results.iter().map(|(s, v)| json!([s, v])).collect::<Vec<_>>(),
|
||||
});
|
||||
out.push_str(&record.to_string());
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
"tick" => {
|
||||
self.chat_capture = Some(Vec::new());
|
||||
// The oracle's player has no client moving it: hold the
|
||||
// player where commands put it while the game ticks.
|
||||
let held = self.player.as_ref().map(|p| p.position);
|
||||
for _ in 0..op["n"].as_u64().unwrap_or(1) {
|
||||
self.update_world();
|
||||
self.tick()?;
|
||||
if let (Some(p), Some(at)) = (self.player.as_mut(), held) {
|
||||
p.position = at;
|
||||
p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0);
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
}
|
||||
let messages = self.chat_capture.take().unwrap_or_default();
|
||||
if op["record"].as_bool() == Some(true) {
|
||||
let record = json!({
|
||||
"cmd": "#tick",
|
||||
"messages": messages.iter().map(spans).collect::<Vec<_>>(),
|
||||
"results": [],
|
||||
});
|
||||
out.push_str(&record.to_string());
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
"settle" => self.harness_settle(deadline)?,
|
||||
other => return Err(format!("command harness: unknown op {other}").into()),
|
||||
}
|
||||
}
|
||||
std::fs::write(output, out)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Command execution (the `execute` side of each vanilla command class):
|
||||
//! entity selectors resolved against the game, vanilla feedback and errors.
|
||||
mod compute;
|
||||
mod data;
|
||||
mod effects;
|
||||
pub(super) mod execute;
|
||||
pub(super) mod extra;
|
||||
mod items;
|
||||
mod misc;
|
||||
mod place;
|
||||
@@ -40,6 +42,19 @@ pub(super) enum Target {
|
||||
Painting(u32),
|
||||
Boat(u32),
|
||||
Cart(u32),
|
||||
/// An entity of a type Horizon does not simulate (markers, displays,
|
||||
/// interactions...): kept as its saved data at a position.
|
||||
Other(u32),
|
||||
}
|
||||
/// An entity of a type Horizon does not simulate: its compound lives in the
|
||||
/// entity memory (`persist.raw`), its position and rotation here.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(in crate::game) struct OtherEntity {
|
||||
pub id: u32,
|
||||
pub kind: String,
|
||||
pub position: Vec3,
|
||||
pub yaw: f32,
|
||||
pub pitch: f32,
|
||||
}
|
||||
pub(super) fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError {
|
||||
CommandError::tr(key, args)
|
||||
@@ -63,7 +78,7 @@ fn format_double(v: f64) -> String {
|
||||
impl Game<'_> {
|
||||
/// Commands.performCommand for a line without its slash.
|
||||
pub(super) fn run_command(&mut self, command: &str) {
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::game_dispatcher();
|
||||
let parse = d.parse(command, &self.ui.registries);
|
||||
let result = match parse.executable() {
|
||||
Err(e) => {
|
||||
@@ -84,6 +99,10 @@ impl Game<'_> {
|
||||
self.command_failure(e.message);
|
||||
}
|
||||
}
|
||||
// InventoryChangeTrigger fires as slots change, not on the next tick.
|
||||
if self.player.is_some() {
|
||||
self.check_inventory_trigger();
|
||||
}
|
||||
}
|
||||
fn syntax_failure(&mut self, e: &CommandError, command: &str) {
|
||||
self.command_failure(e.message.clone());
|
||||
@@ -169,7 +188,8 @@ impl Game<'_> {
|
||||
.ok_or_else(|| err("argument.pos.missing.int", &[]))?;
|
||||
// BlockPos.containing(getPosition)
|
||||
let p = self.resolve_coords(&c).map(|v| v.floor() as i32);
|
||||
if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
|
||||
let elsewhere = self.command_source.is_some_and(|s| s.elsewhere);
|
||||
if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
|
||||
return Err(err("argument.pos.unloaded", &[]));
|
||||
}
|
||||
if p[1] < horizon_client::chunk::MIN_Y
|
||||
@@ -242,6 +262,11 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map(|c| [c.position.x, c.position.y, c.position.z]),
|
||||
Target::Other(id) => self
|
||||
.others
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map(|o| [o.position.x, o.position.y, o.position.z]),
|
||||
}
|
||||
}
|
||||
pub(super) fn target_type(&self, t: Target) -> String {
|
||||
@@ -276,12 +301,21 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map_or_else(|| "minecraft:minecart".into(), |c| c.kind.id().into()),
|
||||
Target::Other(id) => self
|
||||
.others
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map_or_else(String::new, |o| o.kind.clone()),
|
||||
}
|
||||
}
|
||||
/// Entity.getDisplayName.
|
||||
pub(super) fn target_name(&self, t: Target) -> Text {
|
||||
match t {
|
||||
Target::Player => Text::literal(PLAYER_NAME),
|
||||
Target::Player => match self.score.board.players_team(PLAYER_NAME) {
|
||||
// PlayerTeam.formatNameForTeam.
|
||||
Some(team) => team.formatted_name(Text::literal(PLAYER_NAME)),
|
||||
None => Text::literal(PLAYER_NAME),
|
||||
},
|
||||
Target::Item(id) => {
|
||||
let item = self
|
||||
.dropped
|
||||
@@ -305,6 +339,21 @@ impl Game<'_> {
|
||||
Text::literal(name.unwrap_or_default())
|
||||
}
|
||||
other => {
|
||||
// Entity.getDisplayName: the CustomName component, else the type.
|
||||
let custom = match other {
|
||||
Target::Stand(id)
|
||||
| Target::Frame(id)
|
||||
| Target::Painting(id)
|
||||
| Target::Boat(id)
|
||||
| Target::Cart(id)
|
||||
| Target::Other(id) => self.persist_raw(id).and_then(|r| r.get("CustomName")),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(c) = custom {
|
||||
return horizon_client::scoreboard::comp_text(
|
||||
&horizon_client::scoreboard::tag_to_json(c),
|
||||
);
|
||||
}
|
||||
let ty = self.target_type(other);
|
||||
Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[])
|
||||
}
|
||||
@@ -349,6 +398,7 @@ impl Game<'_> {
|
||||
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
|
||||
candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id)));
|
||||
candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id)));
|
||||
candidates.extend(self.others.iter().map(|o| Target::Other(o.id)));
|
||||
}
|
||||
let level = self.experience.level;
|
||||
let creative = self.creative;
|
||||
@@ -535,7 +585,23 @@ impl Game<'_> {
|
||||
"clear" => self.cmd_clear(ctx),
|
||||
"item" => self.cmd_item(ctx),
|
||||
"item.modify" => self.cmd_item_modify(ctx),
|
||||
"spectate" => self.cmd_spectate(ctx),
|
||||
id if id.starts_with("waypoint.") => self.cmd_waypoint(id, ctx),
|
||||
id if id.starts_with("dialog.") => self.cmd_dialog(id, ctx),
|
||||
id if id.starts_with("posteffect.") => self.cmd_posteffect(id, ctx),
|
||||
"kick" => self.cmd_kick(ctx),
|
||||
"fetchprofile" => self.cmd_fetchprofile(ctx),
|
||||
"publish" => self.cmd_publish(ctx),
|
||||
"unpublish" => self.cmd_unpublish(),
|
||||
"debug" => self.cmd_debug(ctx),
|
||||
"jfr" => self.cmd_jfr(ctx),
|
||||
"version" => self.cmd_version(),
|
||||
id if id.starts_with("test.") => self.cmd_test(id, ctx),
|
||||
"compute" => self.cmd_compute(ctx),
|
||||
"place" => self.cmd_place(ctx),
|
||||
"place.feature" | "place.jigsaw" | "place.structure" => {
|
||||
self.cmd_place_generated(id, ctx)
|
||||
}
|
||||
"recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx),
|
||||
"damage" => self.cmd_damage(ctx),
|
||||
"rotate" => self.cmd_rotate(ctx),
|
||||
@@ -543,7 +609,18 @@ impl Game<'_> {
|
||||
"playsound" => self.cmd_playsound(ctx),
|
||||
"stopsound" => self.cmd_stopsound(ctx),
|
||||
"particle" => self.cmd_particle(ctx),
|
||||
id if id.starts_with("attribute.") => self.cmd_attribute(id, ctx),
|
||||
id if id.starts_with("attribute.") => {
|
||||
let result = self.cmd_attribute(id, ctx);
|
||||
// AttributeInstance.setDirty: the entity reacts when it ticks.
|
||||
if result.is_ok()
|
||||
&& matches!(ctx.get("attribute"), Some(Arg::Resource(a)) if a == "minecraft:waypoint_transmit_range")
|
||||
&& !id.ends_with("get")
|
||||
&& let Ok(t) = self.entities(ctx, "target", false)
|
||||
{
|
||||
self.cmds.waypoint_dirty.push(t[0]);
|
||||
}
|
||||
result
|
||||
}
|
||||
"ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx),
|
||||
"spreadplayers" => self.cmd_spreadplayers(ctx),
|
||||
id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx),
|
||||
@@ -569,6 +646,7 @@ impl Game<'_> {
|
||||
self.cmd_scoreboard(id, ctx)
|
||||
}
|
||||
"locate.structure" | "locate.biome" => self.cmd_locate(id, ctx),
|
||||
"locate.poi" => self.cmd_locate_poi(ctx),
|
||||
"warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => {
|
||||
let level = Self::int(ctx, "warning_level");
|
||||
self.cmd_warden_spawn_tracker(level);
|
||||
@@ -581,7 +659,7 @@ impl Game<'_> {
|
||||
"commands.list.nameAndId",
|
||||
&[
|
||||
Text::literal(PLAYER_NAME),
|
||||
Text::literal("00000000-0000-0000-0000-000000000000"),
|
||||
Text::literal(self.player_uuid_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
@@ -597,7 +675,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
fn cmd_help(&mut self, ctx: &Context) -> R<i32> {
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::game_dispatcher();
|
||||
let level = self.ui.registries.permission;
|
||||
match ctx.get("command") {
|
||||
None => {
|
||||
@@ -653,16 +731,23 @@ impl Game<'_> {
|
||||
}
|
||||
count += 1;
|
||||
let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]);
|
||||
if ctx.get("target").is_none() {
|
||||
// GameModeCommand.logGamemodeChange: the source's own entity.
|
||||
let own = match self.command_source {
|
||||
None => true,
|
||||
Some(s) => s.entity == Some(t),
|
||||
};
|
||||
if own {
|
||||
self.feedback(Text::translate(
|
||||
"commands.gamemode.success.self",
|
||||
&[mode_name],
|
||||
));
|
||||
} else {
|
||||
self.system_message(Text::translate(
|
||||
"gameMode.changed",
|
||||
std::slice::from_ref(&mode_name),
|
||||
));
|
||||
if self.ui.rules.bool("send_command_feedback") {
|
||||
self.system_message(Text::translate(
|
||||
"gameMode.changed",
|
||||
std::slice::from_ref(&mode_name),
|
||||
));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.gamemode.success.other",
|
||||
&[Text::literal(PLAYER_NAME), mode_name],
|
||||
@@ -685,7 +770,58 @@ impl Game<'_> {
|
||||
.append("]")
|
||||
.with_color(color)
|
||||
}
|
||||
fn item_rarity(&self, item: &str) -> String {
|
||||
/// `ItemStack.getDisplayName`: the hover name (custom name in italics,
|
||||
/// a written book's title, a potion's effect name...) in brackets, in the
|
||||
/// rarity colour unless the stack is empty.
|
||||
pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text {
|
||||
let item = &*s.item;
|
||||
let empty = item == "minecraft:air" || s.count == 0;
|
||||
let custom = s.custom_name();
|
||||
let hover = if let Some(c) = custom {
|
||||
Text::literal(c).italic()
|
||||
} else if let Some(title) = s
|
||||
.data()
|
||||
.and_then(|d| d.written.as_ref())
|
||||
.map(|w| w.title.clone())
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
{
|
||||
Text::literal(title)
|
||||
} else if matches!(
|
||||
item,
|
||||
"minecraft:potion"
|
||||
| "minecraft:splash_potion"
|
||||
| "minecraft:lingering_potion"
|
||||
| "minecraft:tipped_arrow"
|
||||
) && s.potion().is_some()
|
||||
{
|
||||
Text::translate(
|
||||
&horizon_client::brewing::potion_name_key(item, s.potion()),
|
||||
&[],
|
||||
)
|
||||
} else {
|
||||
Text::literal(self.res.names.item(item))
|
||||
};
|
||||
let wrapped = Text::translate("chat.square_brackets", &[hover]);
|
||||
if empty {
|
||||
return wrapped;
|
||||
}
|
||||
let mut rarity = self.item_rarity(item);
|
||||
if !s.enchantments().is_empty() {
|
||||
rarity = match rarity.as_str() {
|
||||
"rare" => "epic".into(),
|
||||
"epic" => rarity,
|
||||
_ => "rare".into(),
|
||||
};
|
||||
}
|
||||
let color = match rarity.as_str() {
|
||||
"uncommon" => text::YELLOW,
|
||||
"rare" => text::AQUA,
|
||||
"epic" => text::LIGHT_PURPLE,
|
||||
_ => text::WHITE,
|
||||
};
|
||||
wrapped.with_color(color)
|
||||
}
|
||||
pub(super) fn item_rarity(&self, item: &str) -> String {
|
||||
static RARITY: std::sync::OnceLock<std::collections::HashMap<String, String>> =
|
||||
std::sync::OnceLock::new();
|
||||
let map = RARITY.get_or_init(|| {
|
||||
@@ -731,7 +867,9 @@ impl Game<'_> {
|
||||
],
|
||||
)));
|
||||
}
|
||||
for _ in &targets {
|
||||
// An air stack is empty: nothing is given (but the message still is).
|
||||
let empty = id == "minecraft:air";
|
||||
for _ in targets.iter().filter(|_| !empty) {
|
||||
let mut remaining = count;
|
||||
while remaining > 0 {
|
||||
let size = remaining.min(max_stack);
|
||||
@@ -755,7 +893,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let name = self.item_display_name(&id);
|
||||
let name = self.stack_display_name(&ItemStack {
|
||||
item: id.as_str().into(),
|
||||
count: count.max(1) as u32,
|
||||
damage,
|
||||
extra: extra.clone(),
|
||||
});
|
||||
let message = if targets.len() == 1 {
|
||||
Text::translate(
|
||||
"commands.give.success.single",
|
||||
@@ -848,6 +991,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Other(id) => {
|
||||
if let Some(o) = self.others.iter_mut().find(|o| o.id == id) {
|
||||
o.position = v;
|
||||
if let Some([yaw, pitch]) = rotation {
|
||||
o.yaw = yaw;
|
||||
o.pitch = pitch;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wall-mounted entities do not move.
|
||||
Target::Frame(_) | Target::Painting(_) => {}
|
||||
}
|
||||
@@ -1117,7 +1269,7 @@ impl Game<'_> {
|
||||
w.raining = raining;
|
||||
w.thundering = thundering;
|
||||
self.feedback(Text::translate(key, &[]));
|
||||
Ok(duration.unwrap_or(0))
|
||||
Ok(duration.unwrap_or(-1))
|
||||
}
|
||||
fn kill_target(&mut self, t: Target) {
|
||||
match t {
|
||||
@@ -1151,6 +1303,7 @@ impl Game<'_> {
|
||||
Target::Painting(id) => self.paintings.retain(|p| p.id != id),
|
||||
Target::Boat(id) => self.boats.retain(|b| b.id != id),
|
||||
Target::Cart(id) => self.carts.retain(|c| c.id != id),
|
||||
Target::Other(id) => self.others.retain(|o| o.id != id),
|
||||
}
|
||||
}
|
||||
fn cmd_kill(&mut self, ctx: &Context) -> R<i32> {
|
||||
@@ -1185,6 +1338,13 @@ impl Game<'_> {
|
||||
let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
// ResourceArgument.getSummonableEntityType.
|
||||
if matches!(
|
||||
kind.as_str(),
|
||||
"minecraft:player" | "minecraft:fishing_bobber"
|
||||
) {
|
||||
return Err(err("entity.not_summonable", &[&kind]));
|
||||
}
|
||||
let pos = self
|
||||
.position_arg(ctx, "pos")
|
||||
.unwrap_or(self.source_position());
|
||||
@@ -1317,13 +1477,12 @@ impl Game<'_> {
|
||||
self.res.facts.get(previous).name.clone(),
|
||||
self.res.facts.get(state).name.clone(),
|
||||
);
|
||||
// The command clears the old block entity without its side effects
|
||||
// (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if old != new {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
self.jukebox_removed(pos);
|
||||
self.world.block_entities.remove(&key);
|
||||
if let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new) {
|
||||
self.world.block_entities.insert(key, entity);
|
||||
}
|
||||
}
|
||||
if strict {
|
||||
self.with_level(|b, level, ticks| {
|
||||
@@ -1342,6 +1501,12 @@ impl Game<'_> {
|
||||
self.level_set(pos, state)
|
||||
.map_err(|e| CommandError::new(Text::literal(e.to_string())))?;
|
||||
}
|
||||
if old != new
|
||||
&& self.world.block(pos[0], pos[1], pos[2]) == state
|
||||
&& let Some(entity) = horizon_client::containers::BlockEntity::for_block(&new)
|
||||
{
|
||||
self.world.block_entities.insert(key, entity);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn cmd_setblock(&mut self, ctx: &Context) -> R<i32> {
|
||||
@@ -1355,12 +1520,14 @@ impl Game<'_> {
|
||||
return Err(err("commands.setblock.failed", &[]));
|
||||
}
|
||||
if ctx.has("destroy") && current != self.world.air {
|
||||
let creative = self.creative;
|
||||
self.creative = false;
|
||||
let _ = self.break_block(pos);
|
||||
self.creative = creative;
|
||||
self.destroy_block_dropping(pos)?;
|
||||
}
|
||||
if !self.place_state(pos, state, ctx.has("strict"))? {
|
||||
let placed = self.place_state(pos, state, ctx.has("strict"))?;
|
||||
let loaded = match &b.nbt {
|
||||
Some(nbt) => self.load_block_entity_nbt(pos, nbt),
|
||||
None => false,
|
||||
};
|
||||
if !placed && !loaded {
|
||||
return Err(err("commands.setblock.failed", &[]));
|
||||
}
|
||||
self.feedback(Text::tr(
|
||||
@@ -1369,6 +1536,47 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
/// `Level.destroyBlock(pos, true)` through the behaviour library: the
|
||||
/// destroy event, the block's drops without a tool or breaker, then its
|
||||
/// fluid's block, the block entity spilling its contents on the way.
|
||||
pub(super) fn destroy_block_dropping(&mut self, pos: [i32; 3]) -> R<()> {
|
||||
let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
self.with_level(|b, level, ticks| b.destroy_block(level, ticks, at, true));
|
||||
self.process_level_events()
|
||||
.map_err(|e| CommandError::new(Text::literal(e.to_string())))
|
||||
}
|
||||
/// The block entity part of `BlockInput.place`: load the block entity
|
||||
/// from the argument's tag; true when its saved data changed.
|
||||
pub(super) fn load_block_entity_nbt(&mut self, pos: [i32; 3], nbt: &str) -> bool {
|
||||
use horizon_world::nbt::Tag;
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let Some(e) = self.world.block_entities.get(&key) else {
|
||||
return false;
|
||||
};
|
||||
let name = self.data_block_name(pos);
|
||||
let before = horizon_client::save::encode_block_entity(key, e, &name);
|
||||
let Ok((mut tag, _)) = horizon_world::nbt::parse_snbt(nbt) else {
|
||||
return false;
|
||||
};
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
for k in ["id", "x", "y", "z"] {
|
||||
if let Some(v) = before.get(k) {
|
||||
c.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else {
|
||||
return false;
|
||||
};
|
||||
let after = horizon_client::save::encode_block_entity(key, &new, &name);
|
||||
if after == before {
|
||||
return false;
|
||||
}
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], state);
|
||||
true
|
||||
}
|
||||
fn cmd_fill(&mut self, ctx: &Context) -> R<i32> {
|
||||
let a = self.block_pos_arg(ctx, "from")?;
|
||||
let b = self.block_pos_arg(ctx, "to")?;
|
||||
@@ -1418,10 +1626,7 @@ impl Game<'_> {
|
||||
|| z == max[2];
|
||||
let mut affected = false;
|
||||
if destroy && current != air {
|
||||
let creative = self.creative;
|
||||
self.creative = false;
|
||||
let _ = self.break_block([x, y, z]);
|
||||
self.creative = creative;
|
||||
self.destroy_block_dropping([x, y, z])?;
|
||||
affected = true;
|
||||
}
|
||||
let target = if (outline || hollow) && !edge {
|
||||
@@ -1497,21 +1702,29 @@ impl Game<'_> {
|
||||
dest[2] + z - min[2],
|
||||
],
|
||||
s,
|
||||
self.world.block_entities.get(&(x, y, z)).cloned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if moving {
|
||||
for (from, _, _) in &copies {
|
||||
for (from, _, _, _) in &copies {
|
||||
self.place_state(*from, air, true)?;
|
||||
}
|
||||
}
|
||||
let strict = ctx.has("strict");
|
||||
// CloneCommands.clone sets every destination to a barrier first, so
|
||||
// each copied state but a barrier counts as placed.
|
||||
let barrier = self.res.assets.registry.default_state("minecraft:barrier");
|
||||
let mut count = 0;
|
||||
for (_, to, s) in copies {
|
||||
if self.place_state(to, s, strict)? {
|
||||
for (_, to, s, entity) in copies {
|
||||
self.place_state(to, s, strict)?;
|
||||
if Some(s) != barrier {
|
||||
count += 1;
|
||||
}
|
||||
if let Some(e) = entity {
|
||||
self.world.block_entities.insert((to[0], to[1], to[2]), e);
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return Err(err("commands.clone.failed", &[]));
|
||||
@@ -1758,7 +1971,7 @@ impl Game<'_> {
|
||||
if self.ui.difficulty == i {
|
||||
return Err(CommandError::new(Text::translate(
|
||||
"commands.difficulty.failure",
|
||||
&[Text::literal(DIFFICULTIES[i as usize])],
|
||||
&[name(i)],
|
||||
)));
|
||||
}
|
||||
self.ui.difficulty = i;
|
||||
@@ -1808,7 +2021,7 @@ impl Game<'_> {
|
||||
dim,
|
||||
];
|
||||
let key = if targets.len() == 1 {
|
||||
args.push(Text::literal(PLAYER_NAME));
|
||||
args.push(self.target_name(targets[0]));
|
||||
"commands.spawnpoint.success.single"
|
||||
} else {
|
||||
args.push(Text::literal(targets.len().to_string()));
|
||||
@@ -1828,9 +2041,6 @@ impl Game<'_> {
|
||||
p[2].floor() as i32,
|
||||
]
|
||||
};
|
||||
if self.dim != Dim::Overworld {
|
||||
return Err(err("commands.setworldspawn.failure.not_overworld", &[]));
|
||||
}
|
||||
let rot = match ctx.get("rotation") {
|
||||
Some(Arg::Coords(c)) => c.rotation(self.source_rotation()),
|
||||
_ => [0.0, 0.0],
|
||||
@@ -1865,6 +2075,89 @@ impl Game<'_> {
|
||||
}
|
||||
predicate.id == item
|
||||
}
|
||||
/// `ItemPredicateArgument`: the item test and its `[...]` component
|
||||
/// tests (presence, `=` equality, `!` negation, `|` alternatives).
|
||||
pub(super) fn stack_matches(&self, predicate: &ItemInput, stack: &ItemStack) -> bool {
|
||||
if !self.item_matches(predicate, &stack.item) {
|
||||
return false;
|
||||
}
|
||||
let Some(tests) = predicate.components.as_deref() else {
|
||||
return true;
|
||||
};
|
||||
let inner = tests
|
||||
.trim()
|
||||
.strip_prefix('[')
|
||||
.and_then(|t| t.strip_suffix(']'))
|
||||
.unwrap_or("");
|
||||
let components = match horizon_client::item_data::encode_components(stack) {
|
||||
Some(horizon_world::nbt::Tag::Compound(c)) => c,
|
||||
_ => Default::default(),
|
||||
};
|
||||
let test = |term: &str| -> bool {
|
||||
let term = term.trim();
|
||||
let (negated, term) = match term.strip_prefix('!') {
|
||||
Some(t) => (true, t.trim()),
|
||||
None => (false, term),
|
||||
};
|
||||
let split = term.find(['=', '~']).unwrap_or(term.len());
|
||||
let id = term[..split].trim();
|
||||
let id = if id.contains(':') {
|
||||
id.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let present = components.get(&id.as_str().into());
|
||||
let result = match term[split..].chars().next() {
|
||||
Some('=') => {
|
||||
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
|
||||
.ok()
|
||||
.map(|(t, _)| t);
|
||||
match (present, value) {
|
||||
(Some(have), Some(want)) => {
|
||||
horizon_client::nbt_path::compare_nbt(&want, Some(have))
|
||||
&& horizon_client::nbt_path::compare_nbt(have, Some(&want))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
Some('~') => {
|
||||
// Sub-predicates: `count` and component predicates.
|
||||
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
|
||||
.ok()
|
||||
.map(|(t, _)| t);
|
||||
match (id.as_str(), value) {
|
||||
("minecraft:count", Some(v)) => {
|
||||
let n = i64::from(stack.count);
|
||||
match &v {
|
||||
horizon_world::nbt::Tag::Compound(_) => {
|
||||
let get = |k: &str| match v.get(k) {
|
||||
Some(horizon_world::nbt::Tag::Int(i)) => {
|
||||
Some(i64::from(*i))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
get("min").is_none_or(|m| n >= m)
|
||||
&& get("max").is_none_or(|m| n <= m)
|
||||
}
|
||||
horizon_world::nbt::Tag::Int(i) => n == i64::from(*i),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(_, Some(v)) => present.is_some_and(|have| {
|
||||
horizon_client::nbt_path::compare_nbt(&v, Some(have))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => present.is_some(),
|
||||
};
|
||||
result != negated
|
||||
};
|
||||
split_top_level(inner, ',')
|
||||
.iter()
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.all(|term| split_top_level(term, '|').iter().any(|alt| test(alt)))
|
||||
}
|
||||
fn cmd_clear(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", true)?
|
||||
@@ -1885,19 +2178,30 @@ impl Game<'_> {
|
||||
// Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried.
|
||||
let mut removed = 0i32;
|
||||
let mut budget = if max < 0 { i32::MAX } else { max };
|
||||
let all = |g: &Self| -> Vec<Option<ItemStack>> {
|
||||
let mut v: Vec<Option<ItemStack>> = g.inventory.clone();
|
||||
v.extend(g.armor.iter().cloned());
|
||||
v.extend(g.craft_grid.iter().cloned());
|
||||
v.push(g.carried.clone());
|
||||
v
|
||||
};
|
||||
let matching: Vec<bool> = all(self)
|
||||
.iter()
|
||||
.map(|s| {
|
||||
s.as_ref()
|
||||
.is_some_and(|s| self.stack_matches(&predicate, s))
|
||||
})
|
||||
.collect();
|
||||
let mut slots: Vec<&mut Option<ItemStack>> = Vec::new();
|
||||
slots.extend(self.inventory.iter_mut());
|
||||
slots.extend(self.armor.iter_mut());
|
||||
slots.extend(self.craft_grid.iter_mut());
|
||||
slots.push(&mut self.carried);
|
||||
for slot in slots {
|
||||
for (slot, matches) in slots.into_iter().zip(matching) {
|
||||
if !matches {
|
||||
continue;
|
||||
}
|
||||
let Some(stack) = slot.as_mut() else { continue };
|
||||
if !(predicate.any || predicate.tag || predicate.id == *stack.item) && !predicate.tag {
|
||||
continue;
|
||||
}
|
||||
if predicate.tag {
|
||||
continue;
|
||||
}
|
||||
let take = if counting {
|
||||
stack.count as i32
|
||||
} else {
|
||||
@@ -1915,35 +2219,6 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if predicate.tag {
|
||||
// Tag predicates: match against item tags.
|
||||
let pred = predicate.clone();
|
||||
let mut budget = if max < 0 { i32::MAX } else { max };
|
||||
let items: Vec<(usize, String, u32)> = self
|
||||
.inventory
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count)))
|
||||
.collect();
|
||||
for (i, item, count) in items {
|
||||
if !self.item_matches(&pred, &item) {
|
||||
continue;
|
||||
}
|
||||
let take = if counting {
|
||||
count as i32
|
||||
} else {
|
||||
(count as i32).min(budget)
|
||||
};
|
||||
removed += take;
|
||||
if !counting && let Some(s) = self.inventory[i].as_mut() {
|
||||
budget -= take;
|
||||
s.count -= take as u32;
|
||||
if s.count == 0 {
|
||||
self.inventory[i] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if removed == 0 {
|
||||
return Err(if targets.len() == 1 {
|
||||
CommandError::new(Text::translate(
|
||||
@@ -1964,35 +2239,179 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(removed)
|
||||
}
|
||||
/// `PoiTypes`: the point of interest type of a block state.
|
||||
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
|
||||
let s = self.res.assets.registry.state(state)?;
|
||||
let name = s.name.strip_prefix("minecraft:")?;
|
||||
Some(match name {
|
||||
"blast_furnace" => "minecraft:armorer",
|
||||
"smoker" => "minecraft:butcher",
|
||||
"cartography_table" => "minecraft:cartographer",
|
||||
"brewing_stand" => "minecraft:cleric",
|
||||
"composter" => "minecraft:farmer",
|
||||
"barrel" => "minecraft:fisherman",
|
||||
"fletching_table" => "minecraft:fletcher",
|
||||
"cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => {
|
||||
"minecraft:leatherworker"
|
||||
}
|
||||
"lectern" => "minecraft:librarian",
|
||||
"stonecutter" => "minecraft:mason",
|
||||
"loom" => "minecraft:shepherd",
|
||||
"smithing_table" => "minecraft:toolsmith",
|
||||
"grindstone" => "minecraft:weaponsmith",
|
||||
"bell" => "minecraft:meeting",
|
||||
"beehive" => "minecraft:beehive",
|
||||
"bee_nest" => "minecraft:bee_nest",
|
||||
"nether_portal" => "minecraft:nether_portal",
|
||||
"lodestone" => "minecraft:lodestone",
|
||||
"test_instance_block" => "minecraft:test_instance",
|
||||
n if n.ends_with("_bed") => {
|
||||
if s.properties.get("part").map(String::as_str) != Some("head") {
|
||||
return None;
|
||||
}
|
||||
"minecraft:home"
|
||||
}
|
||||
n if n.ends_with("lightning_rod") => "minecraft:lightning_rod",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within
|
||||
/// 256 blocks of the source, over the loaded chunks.
|
||||
fn cmd_locate_poi(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(poi)) = ctx.get("poi").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let wanted: Vec<String> = match poi.strip_prefix('#') {
|
||||
Some(tag) => self.tag_entries("point_of_interest_type", tag),
|
||||
None => vec![poi.clone()],
|
||||
};
|
||||
let from = self.source_position().map(|v| v.floor() as i32);
|
||||
const RANGE: i32 = 256;
|
||||
let mut cache: std::collections::HashMap<u16, Option<&'static str>> =
|
||||
std::collections::HashMap::new();
|
||||
let mut best: Option<(i64, [i32; 3], &'static str)> = None;
|
||||
let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4);
|
||||
let (cx1, cz1) = ((from[0] + RANGE) >> 4, (from[2] + RANGE) >> 4);
|
||||
for cx in cx0..=cx1 {
|
||||
for cz in cz0..=cz1 {
|
||||
let Some(chunk) = self.world.chunks.get(&(cx, cz)) else {
|
||||
continue;
|
||||
};
|
||||
for (i, section) in chunk.sections.iter().enumerate() {
|
||||
let mut wanted_state = |v: u32| {
|
||||
let state = v as u16;
|
||||
cache
|
||||
.entry(state)
|
||||
.or_insert_with(|| {
|
||||
self.poi_type(horizon_world::registry::BlockStateId(u32::from(
|
||||
state,
|
||||
)))
|
||||
.filter(|t| wanted.iter().any(|w| w == t))
|
||||
})
|
||||
.is_some()
|
||||
};
|
||||
if !section.blocks.maybe_has(&mut wanted_state) {
|
||||
continue;
|
||||
}
|
||||
let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32;
|
||||
for j in 0..4096 {
|
||||
let state = section.get(j);
|
||||
let Some(kind) = cache.get(&state).copied().flatten() else {
|
||||
continue;
|
||||
};
|
||||
let p = [
|
||||
cx * 16 + (j & 15) as i32,
|
||||
base_y + (j >> 8) as i32,
|
||||
cz * 16 + ((j >> 4) & 15) as i32,
|
||||
];
|
||||
let d = [p[0] - from[0], p[1] - from[1], p[2] - from[2]]
|
||||
.map(|d| i64::from(d) * i64::from(d))
|
||||
.iter()
|
||||
.sum::<i64>();
|
||||
if d <= i64::from(RANGE * RANGE) && best.is_none_or(|(b, _, _)| d < b) {
|
||||
best = Some((d, p, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, p, kind)) = best else {
|
||||
return Err(CommandError::new(Text::tr(
|
||||
"commands.locate.poi.not_found",
|
||||
&[&poi],
|
||||
)));
|
||||
};
|
||||
let coords = Text::translate(
|
||||
"chat.coordinates",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal("~"),
|
||||
Text::literal(p[2].to_string()),
|
||||
],
|
||||
);
|
||||
let link = Text::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
color: Some(text::GREEN),
|
||||
suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let (dx, dz) = (p[0] - from[0], p[2] - from[2]);
|
||||
let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32;
|
||||
let shown = if poi.starts_with('#') {
|
||||
format!("{poi} ({kind})")
|
||||
} else {
|
||||
poi
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
"commands.locate.poi.success",
|
||||
&[
|
||||
Text::literal(shown),
|
||||
link,
|
||||
Text::literal(distance.to_string()),
|
||||
],
|
||||
));
|
||||
Ok(distance)
|
||||
}
|
||||
fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let origin = self.source_position();
|
||||
if id == "locate.biome" {
|
||||
let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
// Search loaded chunks around the player (BiomeSource.findClosestBiome3d
|
||||
// samples a 6400-block radius; Horizon searches what is generated).
|
||||
let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32);
|
||||
let mut best: Option<([i32; 3], f64)> = None;
|
||||
for (&(cx, cz), chunk) in &self.world.chunks {
|
||||
for (dx, dz) in [(0, 0), (8, 8)] {
|
||||
let (x, z) = (cx * 16 + dx, cz * 16 + dz);
|
||||
let y = origin[1].floor() as i32;
|
||||
let b = self.res.biomes.get(chunk.biome(x, y, z));
|
||||
if b.name == biome {
|
||||
let d = f64::from((x - px).pow(2) + (z - pz).pow(2));
|
||||
if best.is_none_or(|(_, bd)| d < bd) {
|
||||
best = Some(([x, y, z], d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((p, d2)) = best else {
|
||||
// LocateCommand.locateBiome: BiomeSource.findClosestBiome3d with
|
||||
// a 6400-block radius, 32-block columns and 64-block layers.
|
||||
let from = origin.map(|v| v.floor() as i32);
|
||||
let allowed = |name: &str| self.biome_matches(&biome, name);
|
||||
let search = horizon_world::worldgen::generator::BiomeSearch {
|
||||
allowed: &allowed,
|
||||
origin: from,
|
||||
radius: 6400,
|
||||
horizontal: 32,
|
||||
vertical: 64,
|
||||
min_y: horizon_client::chunk::MIN_Y,
|
||||
max_y: horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT - 1,
|
||||
};
|
||||
let found = self
|
||||
.end
|
||||
.locator()
|
||||
.and_then(|t| t.find_closest_biome(&search));
|
||||
let Some((name, p)) = found else {
|
||||
return Err(CommandError::new(Text::tr(
|
||||
"commands.locate.biome.not_found",
|
||||
&[&biome],
|
||||
)));
|
||||
};
|
||||
let d2 = [p[0] - from[0], p[1] - from[1], p[2] - from[2]]
|
||||
.map(|d| f64::from(d) * f64::from(d))
|
||||
.iter()
|
||||
.sum::<f64>();
|
||||
let shown = if biome.starts_with('#') {
|
||||
format!("{biome} ({name})")
|
||||
} else {
|
||||
biome.clone()
|
||||
};
|
||||
let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]);
|
||||
let link = Text::literal("[")
|
||||
.append(coords)
|
||||
@@ -2002,11 +2421,11 @@ impl Game<'_> {
|
||||
suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let distance = d2.sqrt().floor() as i32;
|
||||
self.system_message(Text::translate(
|
||||
let distance = (d2 as f32).sqrt().floor() as i32;
|
||||
self.feedback(Text::translate(
|
||||
"commands.locate.biome.success",
|
||||
&[
|
||||
Text::literal(biome),
|
||||
Text::literal(shown),
|
||||
link,
|
||||
Text::literal(distance.to_string()),
|
||||
],
|
||||
@@ -2064,6 +2483,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// The structures of a `worldgen/structure` tag, nested tags expanded.
|
||||
pub(super) fn structure_tag(&self, tag: &str) -> Vec<String> {
|
||||
self.tag_entries("worldgen/structure", tag)
|
||||
}
|
||||
/// The entries of a data pack tag of `registry`, nested tags expanded.
|
||||
pub(super) fn tag_entries(&self, registry: &str, tag: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut pending = vec![tag.to_owned()];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
@@ -2075,7 +2498,7 @@ impl Game<'_> {
|
||||
let file = self
|
||||
.options
|
||||
.resources
|
||||
.join(format!("data/{ns}/tags/worldgen/structure/{path}.json"));
|
||||
.join(format!("data/{ns}/tags/{registry}/{path}.json"));
|
||||
let Ok(v) = std::fs::read(file)
|
||||
.map_err(|_| ())
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).map_err(|_| ()))
|
||||
@@ -2126,6 +2549,9 @@ impl Game<'_> {
|
||||
.italic()
|
||||
}
|
||||
};
|
||||
if let Some(capture) = self.chat_capture.as_mut() {
|
||||
capture.push(line.clone());
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
@@ -2165,3 +2591,33 @@ impl Game<'_> {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Split at a separator outside brackets, braces and quotes.
|
||||
fn split_top_level(s: &str, sep: char) -> Vec<&str> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quote, mut escaped, mut start) = (0i32, None::<char>, false, 0);
|
||||
for (i, ch) in s.char_indices() {
|
||||
if let Some(q) = quote {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == q {
|
||||
quote = None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match ch {
|
||||
'"' | '\'' => quote = Some(ch),
|
||||
'[' | '{' => depth += 1,
|
||||
']' | '}' => depth -= 1,
|
||||
c if c == sep && depth == 0 => {
|
||||
out.push(&s[start..i]);
|
||||
start = i + ch.len_utf8();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out.push(&s[start..]);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
//! `/compute` (ComputeCommand): context number providers
|
||||
//! (`context_int_provider`, `context_float_provider`) evaluated in a loot
|
||||
//! context of the source, optionally with a block or a target entity.
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use horizon_client::{command::CommandError, text::Text};
|
||||
use horizon_core::random::RandomSource;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The loot context parameters of `LootContextSources`.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(in crate::game) struct ComputeContext {
|
||||
/// `BLOCK_STATE` (`compute block <pos>`).
|
||||
pub block: Option<[i32; 3]>,
|
||||
/// `TARGET_ENTITY` (`compute entity <target>`).
|
||||
pub target: Option<Target>,
|
||||
}
|
||||
|
||||
/// An ArithmeticException's message.
|
||||
type Arith = String;
|
||||
|
||||
fn java_float(v: f32) -> String {
|
||||
horizon_client::snbt::java_float(v)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A provider argument: its registry id (None when inline) and value.
|
||||
pub(in crate::game) fn provider_arg(
|
||||
&self,
|
||||
ctx: &Context,
|
||||
registry: &str,
|
||||
) -> R<(Option<String>, Value)> {
|
||||
let raw = match ctx.get("provider") {
|
||||
Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(),
|
||||
_ => return Err(err("command.failed", &[])),
|
||||
};
|
||||
let first = raw.trim_start().chars().next().unwrap_or(' ');
|
||||
if first == '{' || first == '[' || first == '-' || first.is_ascii_digit() || first == '"' {
|
||||
let (tag, _) = horizon_world::nbt::parse_snbt(&raw)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
return Ok((None, horizon_client::scoreboard::tag_to_json(&tag)));
|
||||
}
|
||||
let id = if raw.contains(':') {
|
||||
raw
|
||||
} else {
|
||||
format!("minecraft:{raw}")
|
||||
};
|
||||
let value = self
|
||||
.provider_file(registry, &id)
|
||||
.ok_or_else(|| err("argument.resource_or_id.no_such_element", &[&id, ®istry]))?;
|
||||
Ok((Some(id), value))
|
||||
}
|
||||
/// A registered provider's definition.
|
||||
fn provider_file(&self, registry: &str, id: &str) -> Option<Value> {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
let dir = registry.trim_start_matches("minecraft:");
|
||||
let file = self
|
||||
.options
|
||||
.resources
|
||||
.join(format!("data/{ns}/{dir}/{path}.json"));
|
||||
serde_json::from_slice(&std::fs::read(file).ok()?).ok()
|
||||
}
|
||||
/// The compute context the command's source literal selects.
|
||||
pub(in crate::game) fn compute_context(&mut self, ctx: &Context) -> R<ComputeContext> {
|
||||
let mut c = ComputeContext::default();
|
||||
if ctx.literals.iter().any(|l| l == "block") && ctx.get("computePos").is_some() {
|
||||
c.block = Some(self.block_pos_arg(ctx, "computePos")?);
|
||||
}
|
||||
if ctx.get("computeTarget").is_some() {
|
||||
let t = self.entities(ctx, "computeTarget", false)?;
|
||||
if t.len() > 1 {
|
||||
return Err(err("argument.entity.toomany", &[]));
|
||||
}
|
||||
c.target = t.first().copied();
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
/// `ComputeCommand.computeAsInt` / `computeAsFloat`.
|
||||
pub(super) fn cmd_compute(&mut self, ctx: &Context) -> R<i32> {
|
||||
let integer = ctx.literals.iter().any(|l| l == "integer");
|
||||
let registry = if integer {
|
||||
"minecraft:context_int_provider"
|
||||
} else {
|
||||
"minecraft:context_float_provider"
|
||||
};
|
||||
let (id, provider) = self.provider_arg(ctx, registry)?;
|
||||
let c = self.compute_context(ctx)?;
|
||||
let invalid = |value: String| -> CommandError {
|
||||
match &id {
|
||||
Some(id) => CommandError::new(Text::translate(
|
||||
"command.compute.result.named.invalid",
|
||||
&[Text::literal(id.clone()), Text::literal(value)],
|
||||
)),
|
||||
None => CommandError::new(Text::translate(
|
||||
"command.compute.result.unnamed.invalid",
|
||||
&[Text::literal(value)],
|
||||
)),
|
||||
}
|
||||
};
|
||||
let exact = |result: i32| match &id {
|
||||
Some(id) => Text::translate(
|
||||
"command.compute.result.named.exact",
|
||||
&[Text::literal(id.clone()), Text::literal(result.to_string())],
|
||||
),
|
||||
None => Text::translate(
|
||||
"command.compute.result.unnamed.exact",
|
||||
&[Text::literal(result.to_string())],
|
||||
),
|
||||
};
|
||||
if integer {
|
||||
let result = self.provider_int(&provider, &c, 0).map_err(invalid)?;
|
||||
self.feedback(exact(result));
|
||||
return Ok(result);
|
||||
}
|
||||
let scale = match ctx.get("scale") {
|
||||
Some(Arg::Float(s)) => *s,
|
||||
_ => 1.0,
|
||||
};
|
||||
let original = self.provider_float(&provider, &c, 0).map_err(invalid)?;
|
||||
if !original.is_finite() {
|
||||
return Err(invalid(java_float(original)));
|
||||
}
|
||||
// Mth.floor(original * scale)
|
||||
let result = (original * scale).floor() as i32;
|
||||
if result as f32 == original {
|
||||
self.feedback(exact(result));
|
||||
} else {
|
||||
let original_text = Text::literal(java_float(original));
|
||||
let message = match &id {
|
||||
Some(id) => Text::translate(
|
||||
"command.compute.result.named.rounded",
|
||||
&[
|
||||
Text::literal(id.clone()),
|
||||
original_text,
|
||||
Text::literal(result.to_string()),
|
||||
],
|
||||
),
|
||||
None => Text::translate(
|
||||
"command.compute.result.unnamed.rounded",
|
||||
&[original_text, Text::literal(result.to_string())],
|
||||
),
|
||||
};
|
||||
self.feedback(message);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// ---- evaluation ---------------------------------------------------------------
|
||||
|
||||
/// `ContextIntProvider.getIntUnsafe`.
|
||||
pub(in crate::game) fn provider_int(
|
||||
&mut self,
|
||||
v: &Value,
|
||||
c: &ComputeContext,
|
||||
depth: u32,
|
||||
) -> Result<i32, Arith> {
|
||||
if depth > 64 {
|
||||
return Ok(0);
|
||||
}
|
||||
let d = depth + 1;
|
||||
match v {
|
||||
Value::Number(n) => Ok(n
|
||||
.as_i64()
|
||||
.map_or_else(|| n.as_f64().unwrap_or(0.0) as i32, |i| i as i32)),
|
||||
Value::Bool(b) => Ok(i32::from(*b)),
|
||||
Value::String(id) => match self.provider_file("minecraft:context_int_provider", id) {
|
||||
Some(def) => self.provider_int(&def, c, d),
|
||||
None => Ok(0),
|
||||
},
|
||||
Value::Object(o) => {
|
||||
let ty = o
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim_start_matches("minecraft:")
|
||||
.to_owned();
|
||||
let inputs = |g: &mut Self| -> Result<Vec<i32>, Arith> {
|
||||
let list: Vec<Value> = match o.get("inputs") {
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(other) => vec![other.clone()],
|
||||
None => Vec::new(),
|
||||
};
|
||||
list.iter().map(|x| g.provider_int(x, c, d)).collect()
|
||||
};
|
||||
let field = |g: &mut Self, k: &str| -> Result<i32, Arith> {
|
||||
match o.get(k) {
|
||||
Some(x) => g.provider_int(x, c, d),
|
||||
None => Ok(0),
|
||||
}
|
||||
};
|
||||
let overflow = || "integer overflow".to_owned();
|
||||
let long_to_int = |v: i64| -> Result<i32, Arith> {
|
||||
i32::try_from(v)
|
||||
.map_err(|_| format!("Value {v} can't be safely converted to int"))
|
||||
};
|
||||
Ok(match ty.as_str() {
|
||||
"constant" => field(self, "value")?,
|
||||
"add" => long_to_int(inputs(self)?.iter().map(|&x| i64::from(x)).sum())?,
|
||||
"mul" => long_to_int(
|
||||
inputs(self)?
|
||||
.iter()
|
||||
.fold(1i64, |a, &x| a.wrapping_mul(i64::from(x))),
|
||||
)?,
|
||||
"avg" => {
|
||||
let xs = inputs(self)?;
|
||||
if xs.is_empty() {
|
||||
return Err("/ by zero".into());
|
||||
}
|
||||
let sum: i64 = xs.iter().map(|&x| i64::from(x)).sum();
|
||||
long_to_int(sum / xs.len() as i64)?
|
||||
}
|
||||
"max" => inputs(self)?.into_iter().fold(i32::MIN, i32::max),
|
||||
"min" => inputs(self)?.into_iter().fold(i32::MAX, i32::min),
|
||||
"sub" => {
|
||||
let (a, b) = (field(self, "left")?, field(self, "right")?);
|
||||
a.checked_sub(b).ok_or_else(overflow)?
|
||||
}
|
||||
"div" | "mod" | "floor_div" | "floor_mod" => {
|
||||
let (a, b) = (field(self, "left")?, field(self, "right")?);
|
||||
if b == 0 {
|
||||
return Err("/ by zero".into());
|
||||
}
|
||||
match ty.as_str() {
|
||||
"div" => a.wrapping_div(b),
|
||||
"mod" => a.wrapping_rem(b),
|
||||
"floor_mod" => {
|
||||
a.rem_euclid(b) + if b < 0 && a.rem_euclid(b) != 0 { b } else { 0 }
|
||||
}
|
||||
_ => {
|
||||
if a == i32::MIN && b == -1 {
|
||||
return Err(overflow());
|
||||
}
|
||||
a.div_euclid(b) - if b < 0 && a.rem_euclid(b) != 0 { 1 } else { 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
"pow" => {
|
||||
let (base, exp) = (field(self, "base")?, field(self, "exponent")?);
|
||||
if base == 0 && exp == 0 {
|
||||
return Err("Result of 0 to the power of 0 is undefined".into());
|
||||
}
|
||||
if exp < 0 {
|
||||
return Err("Negative exponent".into());
|
||||
}
|
||||
base.checked_pow(exp as u32).ok_or_else(overflow)?
|
||||
}
|
||||
// Math.absExact's message.
|
||||
"abs" => field(self, "input")?.checked_abs().ok_or_else(|| {
|
||||
"Overflow to represent absolute value of Integer.MIN_VALUE".to_owned()
|
||||
})?,
|
||||
"negate" => field(self, "input")?.checked_neg().ok_or_else(overflow)?,
|
||||
"from_float" => {
|
||||
let f = match o.get("input") {
|
||||
Some(x) => self.provider_float(x, c, d)?,
|
||||
None => 0.0,
|
||||
};
|
||||
if !f.is_finite() {
|
||||
return Err(format!(
|
||||
"Value {} can't be safely converted to int",
|
||||
java_float(f)
|
||||
));
|
||||
}
|
||||
long_to_int(f as i64)?
|
||||
}
|
||||
"uniform" => {
|
||||
let (lo, hi) = (field(self, "min")?, field(self, "max")?);
|
||||
if lo >= hi {
|
||||
lo
|
||||
} else {
|
||||
self.world.random.next_int_bound(hi - lo + 1).unwrap_or(0) + lo
|
||||
}
|
||||
}
|
||||
"binomial" => {
|
||||
let n = field(self, "n")?;
|
||||
let p = match o.get("p") {
|
||||
Some(x) => self.provider_float(x, c, d)?,
|
||||
None => 0.0,
|
||||
};
|
||||
(0..n.max(0))
|
||||
.filter(|_| self.world.random.next_float() < p)
|
||||
.count() as i32
|
||||
}
|
||||
"conditional" | "number_dispatcher" | "weighted_list" => {
|
||||
match self.provider_select(o, c)? {
|
||||
Some(x) => self.provider_int(&x, c, d)?,
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
_ => Ok(0),
|
||||
}
|
||||
}
|
||||
/// `ContextFloatProvider.getFloatUnsafe`.
|
||||
pub(in crate::game) fn provider_float(
|
||||
&mut self,
|
||||
v: &Value,
|
||||
c: &ComputeContext,
|
||||
depth: u32,
|
||||
) -> Result<f32, Arith> {
|
||||
if depth > 64 {
|
||||
return Ok(0.0);
|
||||
}
|
||||
let d = depth + 1;
|
||||
match v {
|
||||
Value::Number(n) => Ok(n.as_f64().unwrap_or(0.0) as f32),
|
||||
Value::String(id) => match self.provider_file("minecraft:context_float_provider", id) {
|
||||
Some(def) => self.provider_float(&def, c, d),
|
||||
None => Ok(0.0),
|
||||
},
|
||||
Value::Object(o) => {
|
||||
let ty = o
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim_start_matches("minecraft:")
|
||||
.to_owned();
|
||||
let inputs = |g: &mut Self| -> Result<Vec<f32>, Arith> {
|
||||
let list: Vec<Value> = match o.get("inputs") {
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(other) => vec![other.clone()],
|
||||
None => Vec::new(),
|
||||
};
|
||||
list.iter().map(|x| g.provider_float(x, c, d)).collect()
|
||||
};
|
||||
let field = |g: &mut Self, k: &str| -> Result<f32, Arith> {
|
||||
match o.get(k) {
|
||||
Some(x) => g.provider_float(x, c, d),
|
||||
None => Ok(0.0),
|
||||
}
|
||||
};
|
||||
Ok(match ty.as_str() {
|
||||
"constant" => field(self, "value")?,
|
||||
"add" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x),
|
||||
"mul" => inputs(self)?.iter().fold(1.0f32, |a, &x| a * x),
|
||||
"avg" => {
|
||||
let xs = inputs(self)?;
|
||||
xs.iter().fold(0.0f32, |a, &x| a + x) / xs.len() as f32
|
||||
}
|
||||
"length" => inputs(self)?.iter().fold(0.0f32, |a, &x| a + x * x).sqrt(),
|
||||
"max" => inputs(self)?.into_iter().fold(-f32::MAX, f32::max),
|
||||
"min" => inputs(self)?.into_iter().fold(f32::MAX, f32::min),
|
||||
"sub" => field(self, "left")? - field(self, "right")?,
|
||||
"div" => field(self, "left")? / field(self, "right")?,
|
||||
"mod" => {
|
||||
let right = field(self, "right")?;
|
||||
if right == 0.0 {
|
||||
f32::NAN
|
||||
} else {
|
||||
field(self, "left")? % right
|
||||
}
|
||||
}
|
||||
"pow" => {
|
||||
let (base, exp) = (field(self, "base")?, field(self, "exponent")?);
|
||||
if base == 0.0 && exp == 0.0 {
|
||||
f32::NAN
|
||||
} else {
|
||||
f64::from(base).powf(f64::from(exp)) as f32
|
||||
}
|
||||
}
|
||||
"abs" => field(self, "input")?.abs(),
|
||||
"negate" => -field(self, "input")?,
|
||||
"floor" => field(self, "input")?.floor(),
|
||||
// Mth.ceil returns an int.
|
||||
"ceil" => field(self, "input")?.ceil() as i32 as f32,
|
||||
// Math.round(float): floor(x + 0.5) as int.
|
||||
"round" => (field(self, "input")? + 0.5).floor() as i32 as f32,
|
||||
"truncate" => field(self, "input")?.trunc(),
|
||||
"sqrt" => field(self, "input")?.sqrt(),
|
||||
"sin" => horizon_core::geometry::trig::sin(f64::from(field(self, "input")?)),
|
||||
"cos" => horizon_core::geometry::trig::cos(f64::from(field(self, "input")?)),
|
||||
"from_int" => match o.get("input") {
|
||||
Some(x) => self.provider_int(x, c, d)? as f32,
|
||||
None => 0.0,
|
||||
},
|
||||
"uniform" => {
|
||||
let (lo, hi) = (field(self, "min")?, field(self, "max")?);
|
||||
if lo >= hi {
|
||||
lo
|
||||
} else {
|
||||
self.world.random.next_float() * (hi - lo) + lo
|
||||
}
|
||||
}
|
||||
"conditional" | "number_dispatcher" | "weighted_list" => {
|
||||
match self.provider_select(o, c)? {
|
||||
Some(x) => self.provider_float(&x, c, d)?,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
_ => 0.0,
|
||||
})
|
||||
}
|
||||
_ => Ok(0.0),
|
||||
}
|
||||
}
|
||||
/// The branch a conditional, dispatcher or weighted list provider picks.
|
||||
fn provider_select(
|
||||
&mut self,
|
||||
o: &serde_json::Map<String, Value>,
|
||||
c: &ComputeContext,
|
||||
) -> Result<Option<Value>, Arith> {
|
||||
match o
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.map(|t| t.trim_start_matches("minecraft:"))
|
||||
{
|
||||
Some("conditional") => {
|
||||
let holds = o
|
||||
.get("condition")
|
||||
.is_some_and(|x| self.compute_condition(x, c));
|
||||
Ok(if holds {
|
||||
o.get("on_true").cloned()
|
||||
} else {
|
||||
Some(o.get("on_false").cloned().unwrap_or(Value::from(0)))
|
||||
})
|
||||
}
|
||||
Some("number_dispatcher") => {
|
||||
for case in o
|
||||
.get("cases")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if case
|
||||
.get("condition")
|
||||
.is_some_and(|x| self.compute_condition(x, c))
|
||||
{
|
||||
return Ok(case.get("value").cloned());
|
||||
}
|
||||
}
|
||||
Ok(Some(o.get("default").cloned().unwrap_or(Value::from(0))))
|
||||
}
|
||||
_ => {
|
||||
// WeightedList.getRandomOrThrow.
|
||||
let list: Vec<(Value, i32)> = o
|
||||
.get("distribution")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|e| {
|
||||
(
|
||||
e.get("data").cloned().unwrap_or(Value::Null),
|
||||
e.get("weight").and_then(Value::as_i64).unwrap_or(1) as i32,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let total: i32 = list.iter().map(|(_, w)| *w).sum();
|
||||
if total <= 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut pick = self.world.random.next_int_bound(total).unwrap_or(0);
|
||||
for (v, w) in list {
|
||||
pick -= w;
|
||||
if pick < 0 {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A loot condition in the compute context: references, the logical
|
||||
/// combinators and `match_block` on the context's block state.
|
||||
fn compute_condition(&mut self, cond: &Value, c: &ComputeContext) -> bool {
|
||||
match cond {
|
||||
Value::String(id) => match self.provider_file("minecraft:predicate", id) {
|
||||
Some(def) => self.compute_condition(&def, c),
|
||||
None => false,
|
||||
},
|
||||
Value::Array(list) => list.iter().all(|x| self.compute_condition(x, c)),
|
||||
Value::Object(o) => {
|
||||
let ty = o
|
||||
.get("type")
|
||||
.or_else(|| o.get("condition"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim_start_matches("minecraft:");
|
||||
match ty {
|
||||
"inverted" => !o.get("term").is_some_and(|x| self.compute_condition(x, c)),
|
||||
"all_of" => o
|
||||
.get("terms")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|x| self.compute_condition(x, c)),
|
||||
"any_of" => o
|
||||
.get("terms")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|x| self.compute_condition(x, c)),
|
||||
"match_block" | "block_state_property" => {
|
||||
let Some(p) = c.block else {
|
||||
return false;
|
||||
};
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
let Some(s) = self.res.assets.registry.state(state) else {
|
||||
return false;
|
||||
};
|
||||
let name = s.name.to_string();
|
||||
let blocks_ok = match o.get("blocks").or_else(|| o.get("block")) {
|
||||
Some(Value::String(b)) => match b.strip_prefix('#') {
|
||||
Some(tag) => self
|
||||
.res
|
||||
.items
|
||||
.block_tags
|
||||
.get(tag.trim_start_matches("minecraft:"))
|
||||
.is_some_and(|set| {
|
||||
set.contains(&*name)
|
||||
|| set.contains(name.trim_start_matches("minecraft:"))
|
||||
}),
|
||||
None => *b == name,
|
||||
},
|
||||
Some(Value::Array(list)) => {
|
||||
list.iter().any(|b| b.as_str() == Some(&name))
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
let props_ok = o
|
||||
.get("state")
|
||||
.or_else(|| o.get("properties"))
|
||||
.and_then(Value::as_object)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|(k, v)| s.properties.get(k).map(String::as_str) == v.as_str());
|
||||
blocks_ok && props_ok
|
||||
}
|
||||
"random_chance" => {
|
||||
let chance = o.get("chance").and_then(Value::as_f64).unwrap_or(0.0) as f32;
|
||||
self.world.random.next_float() < chance
|
||||
}
|
||||
_ => {
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let view = source.entity.map(|t| self.entity_view_of(t));
|
||||
self.conditions_hold(cond, view.as_ref(), source.pos)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,21 @@ impl Game<'_> {
|
||||
if let Some(u) = player_uuid {
|
||||
set_key(&mut tag, "UUID", Tag::IntArray(u.to_vec()));
|
||||
}
|
||||
// NbtPredicate.getEntityTagToCompare: a player's held stack.
|
||||
let selected = self.level.selected_slot;
|
||||
let held = match tag.get("Inventory") {
|
||||
Some(Tag::List(items)) => items
|
||||
.iter()
|
||||
.find(|i| matches!(i.get("Slot"), Some(Tag::Byte(b)) if i32::from(*b) == selected))
|
||||
.cloned(),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(mut stack) = held {
|
||||
if let Tag::Compound(c) = &mut stack {
|
||||
c.remove(&"Slot".into());
|
||||
}
|
||||
set_key(&mut tag, "SelectedItem", stack);
|
||||
}
|
||||
tag
|
||||
}
|
||||
Target::Mob(id) => {
|
||||
@@ -87,6 +102,11 @@ impl Game<'_> {
|
||||
let c = self.carts.iter().find(|c| c.id == id)?;
|
||||
c.to_nbt(uuid, self.persist.raw.get(&id))
|
||||
}
|
||||
Target::Other(id) => {
|
||||
let uuid = self.uuid_for(id);
|
||||
let o = self.others.iter().find(|o| o.id == id)?.clone();
|
||||
self.other_to_nbt(&o, uuid)
|
||||
}
|
||||
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
|
||||
Target::Arrow(i) => {
|
||||
let a = self.arrows.get(i)?;
|
||||
@@ -166,7 +186,8 @@ impl Game<'_> {
|
||||
| Target::Frame(id)
|
||||
| Target::Painting(id)
|
||||
| Target::Boat(id)
|
||||
| Target::Cart(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)),
|
||||
| Target::Cart(id)
|
||||
| Target::Other(id) => Some(self.persist.raw.entry(id).or_insert_with(empty)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -226,9 +247,16 @@ impl Game<'_> {
|
||||
}
|
||||
pub(in crate::game) fn data_of(&mut self, r: &DataRef) -> R<Tag> {
|
||||
match r {
|
||||
DataRef::Entity(t) => self
|
||||
.entity_nbt(*t)
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[])),
|
||||
// EntityDataAccessor.getData: Entity.saveWithoutId.
|
||||
DataRef::Entity(t) => {
|
||||
let mut tag = self
|
||||
.entity_nbt(*t)
|
||||
.ok_or_else(|| err("argument.entity.notfound.entity", &[]))?;
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.remove(&"id".into());
|
||||
}
|
||||
Ok(tag)
|
||||
}
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
let name = self.data_block_name(*p);
|
||||
@@ -237,7 +265,12 @@ impl Game<'_> {
|
||||
.block_entities
|
||||
.get(&key)
|
||||
.ok_or_else(|| err("commands.data.block.invalid", &[]))?;
|
||||
Ok(save::encode_block_entity(key, e, &name))
|
||||
// BlockEntity.saveWithFullMetadata: no chunk-only keepPacked.
|
||||
let mut tag = save::encode_block_entity(key, e, &name);
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.remove(&"keepPacked".into());
|
||||
}
|
||||
Ok(tag)
|
||||
}
|
||||
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
|
||||
}
|
||||
@@ -626,10 +659,11 @@ impl Game<'_> {
|
||||
};
|
||||
self.world.loaded_entities.push((key, vec![tag]));
|
||||
self.spawn_loaded_entities();
|
||||
let id = self.next_entity;
|
||||
if id == before {
|
||||
if self.next_entity == before {
|
||||
return None;
|
||||
}
|
||||
// The root of the stack is the first entity spawned.
|
||||
let id = before + 1;
|
||||
if self.mobs.iter().any(|m| m.id == id) {
|
||||
Some(Target::Mob(id))
|
||||
} else if self.dropped.iter().any(|e| e.id == id) {
|
||||
@@ -644,6 +678,8 @@ impl Game<'_> {
|
||||
Some(Target::Boat(id))
|
||||
} else if self.carts.iter().any(|c| c.id == id) {
|
||||
Some(Target::Cart(id))
|
||||
} else if self.others.iter().any(|o| o.id == id) {
|
||||
Some(Target::Other(id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -660,18 +696,36 @@ impl Game<'_> {
|
||||
return Err(err("argument.nbt.expected.compound", &[]));
|
||||
}
|
||||
set_key(&mut tag, "id", Tag::String(kind.into()));
|
||||
let p = pos.map(|v| Tag::Double(v.to_bits()));
|
||||
set_key(&mut tag, "Pos", Tag::List(p.to_vec()));
|
||||
if tag.get("Rotation").is_none() {
|
||||
set_key(
|
||||
&mut tag,
|
||||
"Rotation",
|
||||
Tag::List(vec![
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
// EntityType.loadEntityRecursive snaps every entity of the stack,
|
||||
// passengers included, to the position.
|
||||
fn place(tag: &mut Tag, pos: [f64; 3]) {
|
||||
let p = pos.map(|v| Tag::Double(v.to_bits()));
|
||||
set_key(tag, "Pos", Tag::List(p.to_vec()));
|
||||
// Entity.load: an absent Fire reads as 0 (until the entity moves).
|
||||
if tag.get("Fire").is_none() {
|
||||
set_key(tag, "Fire", Tag::Short(0));
|
||||
}
|
||||
if tag.get("Rotation").is_none() {
|
||||
set_key(
|
||||
tag,
|
||||
"Rotation",
|
||||
Tag::List(vec![
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
Tag::Float(0.0f32.to_bits()),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if let Tag::Compound(c) = tag
|
||||
&& let Some(Tag::List(riders)) = c.get_mut(&"Passengers".into())
|
||||
{
|
||||
for r in riders {
|
||||
if matches!(r, Tag::Compound(_)) {
|
||||
place(r, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
place(&mut tag, pos);
|
||||
Ok(self.spawn_entity_from_nbt(tag))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ pub(in crate::game) struct Source {
|
||||
pub silent: bool,
|
||||
/// Index of the newest `store` in `ExecState::stores`.
|
||||
pub store: Option<u32>,
|
||||
/// `execute in` another dimension than the one Horizon has loaded: none
|
||||
/// of its chunks are loaded.
|
||||
pub elsewhere: bool,
|
||||
}
|
||||
|
||||
/// Where `execute store` writes.
|
||||
@@ -70,6 +73,7 @@ impl Game<'_> {
|
||||
eyes: false,
|
||||
silent: false,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
}
|
||||
}
|
||||
/// The server as a source (function ticks and schedules): the world spawn.
|
||||
@@ -81,6 +85,7 @@ impl Game<'_> {
|
||||
eyes: false,
|
||||
silent: true,
|
||||
store: None,
|
||||
elsewhere: false,
|
||||
}
|
||||
}
|
||||
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
|
||||
@@ -106,6 +111,11 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|c| c.id == id)
|
||||
.map_or([0.0; 2], |c| [c.yaw, 0.0]),
|
||||
Target::Other(id) => self
|
||||
.others
|
||||
.iter()
|
||||
.find(|o| o.id == id)
|
||||
.map_or([0.0; 2], |o| [o.yaw, o.pitch]),
|
||||
_ => [0.0; 2],
|
||||
}
|
||||
}
|
||||
@@ -147,7 +157,7 @@ impl Game<'_> {
|
||||
/// Run one command line with `source` (no error reporting): the entry
|
||||
/// for functions and `execute run`.
|
||||
pub(in crate::game) fn execute_line(&mut self, line: &str, source: Source) -> R<i32> {
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::game_dispatcher();
|
||||
let parse = d.parse(line, &self.ui.registries);
|
||||
let (ctx, _) = parse.executable()?;
|
||||
let ctx = ctx.clone();
|
||||
@@ -189,6 +199,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// `CommandResultCallback`s of a source's `store` chain, oldest first.
|
||||
fn deliver(&mut self, store: Option<u32>, success: bool, value: i32) {
|
||||
// The outermost source's own CommandResultCallback (harness record).
|
||||
if self.exec.function_depth == 0
|
||||
&& let Some(results) = self.cmds.results.as_mut()
|
||||
{
|
||||
results.push((success, value));
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
let mut at = store;
|
||||
while let Some(i) = at {
|
||||
@@ -235,6 +251,10 @@ impl Game<'_> {
|
||||
pub(in crate::game) fn run_execute(&mut self, ctx: &Context) -> R<i32> {
|
||||
let mut sources = vec![self.command_source.unwrap_or_else(|| self.player_source())];
|
||||
let mut c = ctx;
|
||||
// A fork modifier (as, at, positioned as, rotated as, facing entity,
|
||||
// on, a non-terminal if/unless) makes later errors silent
|
||||
// (CommandSourceStack.handleError with `forked`).
|
||||
let mut forked = false;
|
||||
loop {
|
||||
let word = c
|
||||
.literals
|
||||
@@ -257,7 +277,8 @@ impl Game<'_> {
|
||||
for s in sources {
|
||||
match self.with_source(s, |g| g.run_chain(command, last)) {
|
||||
Ok(n) => total += n,
|
||||
// Forked executions report failures and carry on.
|
||||
Err(_) if forked => {}
|
||||
// Several sources: report each failure and carry on.
|
||||
Err(e) if many => self.command_failure(e.message),
|
||||
Err(e) => failure = Some(e),
|
||||
}
|
||||
@@ -275,6 +296,7 @@ impl Game<'_> {
|
||||
if c.child.is_none() {
|
||||
return self.run_conditional_terminal(c, sources, want);
|
||||
}
|
||||
forked = true;
|
||||
let mut kept = Vec::new();
|
||||
for s in sources {
|
||||
let (keep, _) = self.with_source(s, |g| g.condition(c, want))?;
|
||||
@@ -285,6 +307,12 @@ impl Game<'_> {
|
||||
sources = kept;
|
||||
}
|
||||
_ => {
|
||||
forked |= match word {
|
||||
"as" | "at" | "on" => true,
|
||||
"positioned" | "rotated" => c.has("as"),
|
||||
"facing" => c.has("entity"),
|
||||
_ => false,
|
||||
};
|
||||
let mut next = Vec::new();
|
||||
for s in sources {
|
||||
next.extend(self.with_source(s, |g| g.modify(word, c, s))?);
|
||||
@@ -407,6 +435,7 @@ impl Game<'_> {
|
||||
Some(Source {
|
||||
pos: self.target_position(t)?,
|
||||
rot: self.target_rotation(t),
|
||||
elsewhere: false,
|
||||
..s
|
||||
})
|
||||
})
|
||||
@@ -497,14 +526,21 @@ impl Game<'_> {
|
||||
..s
|
||||
}],
|
||||
"in" => {
|
||||
// Horizon keeps one dimension loaded; others cannot be a source.
|
||||
// Horizon keeps one dimension loaded: in another one, no
|
||||
// chunk is loaded (as in vanilla without a player there).
|
||||
let Some(Arg::Resource(dim)) = c.get("dimension") else {
|
||||
return Ok(vec![s]);
|
||||
};
|
||||
if dim != self.dim.id() {
|
||||
if !matches!(
|
||||
dim.as_str(),
|
||||
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
|
||||
) {
|
||||
return Err(err("argument.dimension.invalid", &[dim]));
|
||||
}
|
||||
vec![s]
|
||||
vec![Source {
|
||||
elsewhere: dim != self.dim.id(),
|
||||
..s
|
||||
}]
|
||||
}
|
||||
"summon" => {
|
||||
let Some(Arg::Resource(kind)) = c.get("entity").cloned() else {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@ use horizon_client::{
|
||||
scoreboard_cmd::{Holder, Tracker},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// One addressable slot.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -290,7 +291,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
fn stack_name(&self, s: &ItemStack) -> Text {
|
||||
self.item_display_name(&s.item)
|
||||
self.stack_display_name(s)
|
||||
}
|
||||
fn item_from_input(&self, ctx: &Context) -> R<Option<ItemStack>> {
|
||||
let Some(Arg::Item(ItemInput { id, components, .. })) = ctx.get("item").cloned() else {
|
||||
@@ -351,12 +352,12 @@ impl Game<'_> {
|
||||
},
|
||||
Value::Object(_) => {
|
||||
let mut stack = stack?;
|
||||
if !m["conditions"].is_null()
|
||||
&& !self.conditions_hold(&m["conditions"], this, origin)
|
||||
// 26.3 item modifiers: a single `condition`, dispatched on `type`.
|
||||
if !m["condition"].is_null() && !self.conditions_hold(&m["condition"], this, origin)
|
||||
{
|
||||
return Some(stack);
|
||||
}
|
||||
match m["function"].as_str().unwrap_or("") {
|
||||
match m["type"].as_str().unwrap_or("") {
|
||||
"minecraft:sequence" => {
|
||||
#[allow(clippy::manual_try_fold)]
|
||||
return m["functions"]
|
||||
@@ -408,9 +409,19 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
"minecraft:set_name" => {
|
||||
let t = horizon_client::packs::component(&m["name"]);
|
||||
stack.extra.get_or_insert_with(Default::default).custom_name =
|
||||
Some(t.plain());
|
||||
if m["name"].is_null() {
|
||||
return Some(stack);
|
||||
}
|
||||
if m["target"].as_str() == Some("item_name") {
|
||||
let name = horizon_client::scoreboard::json_to_tag(&m["name"]);
|
||||
edit_components(&mut stack, |c| {
|
||||
c.insert("minecraft:item_name".into(), name);
|
||||
});
|
||||
} else {
|
||||
let t = horizon_client::packs::component(&m["name"]);
|
||||
stack.extra.get_or_insert_with(Default::default).custom_name =
|
||||
Some(t.plain());
|
||||
}
|
||||
}
|
||||
"minecraft:set_enchantments" => {
|
||||
let add = m["add"].as_bool() == Some(true);
|
||||
@@ -440,6 +451,129 @@ impl Game<'_> {
|
||||
Some(p.into());
|
||||
}
|
||||
}
|
||||
"minecraft:set_lore" => {
|
||||
let lines: Vec<Tag> = m["lore"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(horizon_client::scoreboard::json_to_tag)
|
||||
.collect();
|
||||
edit_components(&mut stack, |c| {
|
||||
let old: Vec<Tag> = match c.get(&"minecraft:lore".into()) {
|
||||
Some(Tag::List(l)) => l.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let new = list_operation(m, old, lines);
|
||||
c.insert("minecraft:lore".into(), Tag::List(new));
|
||||
});
|
||||
}
|
||||
"minecraft:set_custom_data" => {
|
||||
let tag = match &m["tag"] {
|
||||
Value::String(snbt) => horizon_world::nbt::parse_snbt(snbt)
|
||||
.map(|(t, _)| t)
|
||||
.unwrap_or(Tag::Compound(Default::default())),
|
||||
v => horizon_client::scoreboard::json_to_tag(v),
|
||||
};
|
||||
edit_components(&mut stack, |c| {
|
||||
let mut data = match c.get(&"minecraft:custom_data".into()) {
|
||||
Some(t @ Tag::Compound(_)) => t.clone(),
|
||||
_ => Tag::Compound(Default::default()),
|
||||
};
|
||||
merge_compound(&mut data, &tag);
|
||||
c.insert("minecraft:custom_data".into(), data);
|
||||
});
|
||||
}
|
||||
"minecraft:set_components" => {
|
||||
let patch = m["components"].clone();
|
||||
edit_components(&mut stack, |c| {
|
||||
for (k, v) in patch.as_object().into_iter().flatten() {
|
||||
let (remove, key) = match k.strip_prefix('!') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, k.as_str()),
|
||||
};
|
||||
let key = if key.contains(':') {
|
||||
key.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{key}")
|
||||
};
|
||||
if remove {
|
||||
c.remove(&key.as_str().into());
|
||||
} else {
|
||||
c.insert(
|
||||
key.as_str().into(),
|
||||
horizon_client::scoreboard::json_to_tag(v),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
"minecraft:toggle_tooltips" => {
|
||||
let toggles = m["toggles"].clone();
|
||||
edit_components(&mut stack, |c| {
|
||||
let mut hidden: Vec<String> = c
|
||||
.get(&"minecraft:tooltip_display".into())
|
||||
.and_then(|d| d.get("hidden_components"))
|
||||
.and_then(|l| match l {
|
||||
Tag::List(l) => Some(
|
||||
l.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let hide_tooltip = c
|
||||
.get(&"minecraft:tooltip_display".into())
|
||||
.and_then(|d| d.get("hide_tooltip"))
|
||||
.cloned();
|
||||
for (k, shown) in toggles.as_object().into_iter().flatten() {
|
||||
let key = if k.contains(':') {
|
||||
k.clone()
|
||||
} else {
|
||||
format!("minecraft:{k}")
|
||||
};
|
||||
hidden.retain(|h| *h != key);
|
||||
if shown.as_bool() == Some(false) {
|
||||
hidden.push(key);
|
||||
}
|
||||
}
|
||||
let mut display: Vec<(&str, Tag)> = Vec::new();
|
||||
if let Some(h) = hide_tooltip {
|
||||
display.push(("hide_tooltip", h));
|
||||
}
|
||||
if !hidden.is_empty() {
|
||||
display.push((
|
||||
"hidden_components",
|
||||
Tag::List(
|
||||
hidden
|
||||
.iter()
|
||||
.map(|h| Tag::String(h.as_str().into()))
|
||||
.collect(),
|
||||
),
|
||||
));
|
||||
}
|
||||
c.insert("minecraft:tooltip_display".into(), Tag::compound(display));
|
||||
});
|
||||
}
|
||||
"minecraft:filtered" => {
|
||||
let pass = self.loot_item_filter(&m["item_filter"], &stack);
|
||||
let branch = if pass { &m["on_pass"] } else { &m["on_fail"] };
|
||||
if branch.is_null() {
|
||||
return Some(stack);
|
||||
}
|
||||
return self.apply_item_modifier(
|
||||
branch,
|
||||
Some(stack),
|
||||
rng,
|
||||
this,
|
||||
origin,
|
||||
depth + 1,
|
||||
);
|
||||
}
|
||||
"minecraft:discard" => stack.count = 0,
|
||||
_ => {}
|
||||
}
|
||||
(stack.count > 0).then_some(stack)
|
||||
@@ -447,6 +581,38 @@ impl Game<'_> {
|
||||
_ => stack,
|
||||
}
|
||||
}
|
||||
/// `ItemStack.getMaxStackSize`: the max_stack_size component, else the
|
||||
/// item's.
|
||||
pub(super) fn stack_max_size(&self, s: &ItemStack) -> u32 {
|
||||
if let Some(Tag::Int(n)) = s.data().and_then(|d| d.other("minecraft:max_stack_size")) {
|
||||
return (*n).clamp(1, 99) as u32;
|
||||
}
|
||||
self.res.items.get(&s.item).map_or(64, |i| i.max_stack)
|
||||
}
|
||||
/// `ResourceOrIdArgument.getItemModifier`: an inline modifier (SNBT) or
|
||||
/// a registered one.
|
||||
pub(super) fn item_modifier_arg(&mut self, ctx: &Context, name: &str) -> R<serde_json::Value> {
|
||||
let raw = match ctx.get(name) {
|
||||
Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(),
|
||||
_ => return Err(err("command.failed", &[])),
|
||||
};
|
||||
if raw.starts_with('{') || raw.starts_with('[') {
|
||||
let (tag, _) = horizon_world::nbt::parse_snbt(&raw)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
return Ok(horizon_client::scoreboard::tag_to_json(&tag));
|
||||
}
|
||||
let id = if raw.contains(':') {
|
||||
raw
|
||||
} else {
|
||||
format!("minecraft:{raw}")
|
||||
};
|
||||
self.fns
|
||||
.store
|
||||
.item_modifiers
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.ok_or_else(|| err("argument.item_modifier.unknown", &[&id]))
|
||||
}
|
||||
/// `/item modify (entity|block) <target> <slot> <modifier>`.
|
||||
pub(super) fn cmd_item_modify(&mut self, ctx: &Context) -> R<i32> {
|
||||
self.ensure_datapacks();
|
||||
@@ -454,17 +620,7 @@ impl Game<'_> {
|
||||
let Some(Arg::Str(slot_name)) = ctx.get("slot").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let Some(Arg::Str(id)) = ctx.get("modifier").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let id = if id.contains(':') {
|
||||
id
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let Some(modifier) = self.fns.store.item_modifiers.get(&id).cloned() else {
|
||||
return Err(err("argument.item_modifier.unknown", &[&id]));
|
||||
};
|
||||
let modifier = self.item_modifier_arg(ctx, "modifier")?;
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let view = source.entity.map(|t| self.entity_view_of(t));
|
||||
let seed = std::time::SystemTime::now()
|
||||
@@ -501,7 +657,14 @@ impl Game<'_> {
|
||||
source.pos,
|
||||
0,
|
||||
);
|
||||
if new.as_ref() != Some(¤t) && self.slot_set(slot, new) {
|
||||
// CountingModifier: every slot set counts, changed or not;
|
||||
// ItemStack.limitSize to the (new) max stack size.
|
||||
let new = new.map(|mut s| {
|
||||
let max = self.stack_max_size(&s);
|
||||
s.count = s.count.min(max);
|
||||
s
|
||||
});
|
||||
if self.slot_set(slot, new) {
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
@@ -582,6 +745,28 @@ impl Game<'_> {
|
||||
_ => err("commands.item.source.no_such_slot", &[&source_slots]),
|
||||
});
|
||||
}
|
||||
// ItemCommands.applyModifier on each source stack.
|
||||
if ctx.get("modifier").is_some() {
|
||||
let modifier = self.item_modifier_arg(ctx, "modifier")?;
|
||||
let source = self.command_source.unwrap_or_else(|| self.player_source());
|
||||
let view = source.entity.map(|t| self.entity_view_of(t));
|
||||
let mut rng = horizon_core::random::LegacyRandom::new(0);
|
||||
found = found
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
s.and_then(|s| {
|
||||
self.apply_item_modifier(
|
||||
&modifier,
|
||||
Some(s),
|
||||
&mut rng,
|
||||
view.as_ref(),
|
||||
source.pos,
|
||||
0,
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
// A source with nothing in the slot contributes air.
|
||||
(found, None)
|
||||
};
|
||||
@@ -706,7 +891,7 @@ impl Game<'_> {
|
||||
if let Some(stack) = self.slot_get(&s)
|
||||
&& predicate
|
||||
.as_ref()
|
||||
.is_some_and(|p| self.item_matches(p, &stack.item))
|
||||
.is_some_and(|p| self.stack_matches(p, &stack))
|
||||
{
|
||||
count += stack.count as i32;
|
||||
}
|
||||
@@ -715,3 +900,62 @@ impl Game<'_> {
|
||||
Ok((count > 0, count))
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit a stack's components as their saved compound.
|
||||
fn edit_components(stack: &mut ItemStack, f: impl FnOnce(&mut horizon_world::nbt::Compound)) {
|
||||
let mut c = match horizon_client::item_data::encode_components(stack) {
|
||||
Some(Tag::Compound(c)) => c,
|
||||
_ => horizon_world::nbt::Compound::new(),
|
||||
};
|
||||
f(&mut c);
|
||||
let tag = Tag::Compound(c);
|
||||
let (damage, extra) = horizon_client::item_data::decode_components(Some(&tag));
|
||||
stack.damage = damage;
|
||||
stack.extra = extra;
|
||||
stack.tidy();
|
||||
}
|
||||
/// `CompoundTag.merge`: nested compounds merge, other values replace.
|
||||
fn merge_compound(into: &mut Tag, from: &Tag) {
|
||||
let (Tag::Compound(a), Tag::Compound(b)) = (into, from) else {
|
||||
return;
|
||||
};
|
||||
for (k, v) in b {
|
||||
match (a.get_mut(k), v) {
|
||||
(Some(existing @ Tag::Compound(_)), Tag::Compound(_)) => merge_compound(existing, v),
|
||||
_ => {
|
||||
a.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ListOperation.apply` (`mode`: replace_all, replace_section, insert,
|
||||
/// append) with a 256-entry limit.
|
||||
fn list_operation(m: &serde_json::Value, old: Vec<Tag>, new: Vec<Tag>) -> Vec<Tag> {
|
||||
let offset = m["offset"].as_u64().unwrap_or(0) as usize;
|
||||
let mut out = match m["mode"].as_str().unwrap_or("") {
|
||||
"replace_all" => new,
|
||||
"insert" => {
|
||||
let at = offset.min(old.len());
|
||||
let mut out = old[..at].to_vec();
|
||||
out.extend(new);
|
||||
out.extend_from_slice(&old[at..]);
|
||||
out
|
||||
}
|
||||
"replace_section" => {
|
||||
let at = offset.min(old.len());
|
||||
let size = m["size"].as_u64().map_or(new.len(), |s| s as usize);
|
||||
let mut out = old[..at].to_vec();
|
||||
out.extend(new);
|
||||
let end = (at + size).min(old.len());
|
||||
out.extend_from_slice(&old[end..]);
|
||||
out
|
||||
}
|
||||
_ => {
|
||||
let mut out = old;
|
||||
out.extend(new);
|
||||
out
|
||||
}
|
||||
};
|
||||
out.truncate(256);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -70,20 +70,129 @@ impl Game<'_> {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `BlockPosArgument.getLoadedBlockPos(pos)`, or the source's block.
|
||||
fn place_pos(&self, ctx: &Context, name: &str) -> R<[i32; 3]> {
|
||||
if ctx.get(name).is_some() {
|
||||
return self.block_pos_arg(ctx, name);
|
||||
}
|
||||
Ok(self.source_position().map(|v| v.floor() as i32))
|
||||
}
|
||||
/// `PlaceCommand.checkLoaded`: every chunk of the inclusive range.
|
||||
fn place_check_loaded(&self, min: [i32; 2], max: [i32; 2]) -> R<()> {
|
||||
let elsewhere = self.command_source.is_some_and(|s| s.elsewhere);
|
||||
for cx in min[0]..=max[0] {
|
||||
for cz in min[1]..=max[1] {
|
||||
if elsewhere || !self.world.chunks.contains_key(&(cx, cz)) {
|
||||
return Err(err("argument.pos.unloaded", &[]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `PlaceCommand.placeFeature`, `placeJigsaw` and `placeStructure`.
|
||||
pub(super) fn cmd_place_generated(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
match id {
|
||||
"place.feature" => {
|
||||
let raw = match ctx.get("feature") {
|
||||
Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(),
|
||||
_ => return Ok(0),
|
||||
};
|
||||
let pos = self.place_pos(ctx, "pos")?;
|
||||
let (cx, cz) = (pos[0] >> 4, pos[2] >> 4);
|
||||
self.place_check_loaded([cx - 1, cz - 1], [cx + 1, cz + 1])?;
|
||||
// Inline features are not built by the live feature registry.
|
||||
if raw.starts_with('{') {
|
||||
return Err(err("command.failed", &[]));
|
||||
}
|
||||
let name = if raw.contains(':') {
|
||||
raw
|
||||
} else {
|
||||
format!("minecraft:{raw}")
|
||||
};
|
||||
let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]);
|
||||
let placed = self
|
||||
.with_level(|b, level, ticks| b.place_feature(level, ticks, &name, at))
|
||||
.ok_or_else(|| err("command.failed", &[]))?;
|
||||
self.process_level_events()
|
||||
.map_err(|_| err("command.failed", &[]))?;
|
||||
if !placed {
|
||||
return Err(err("commands.place.feature.failed", &[]));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.place.feature.success",
|
||||
&[Text::literal(name), num(pos[0]), num(pos[1]), num(pos[2])],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"place.jigsaw" => {
|
||||
let Some(Arg::Resource(pool)) = ctx.get("pool").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
if !self
|
||||
.ui
|
||||
.registries
|
||||
.ids("minecraft:worldgen/template_pool")
|
||||
.contains(&pool)
|
||||
{
|
||||
return Err(err("commands.place.jigsaw.invalid", &[&pool]));
|
||||
}
|
||||
let target = match ctx.get("target") {
|
||||
Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(),
|
||||
_ => return Ok(0),
|
||||
};
|
||||
let max_depth = match ctx.get("max_depth") {
|
||||
Some(Arg::Int(n)) => *n,
|
||||
_ => return Ok(0),
|
||||
};
|
||||
let pos = self.place_pos(ctx, "position")?;
|
||||
self.place_check_loaded([pos[0] >> 4, pos[2] >> 4], [pos[0] >> 4, pos[2] >> 4])?;
|
||||
let terrain = self
|
||||
.end
|
||||
.locator()
|
||||
.ok_or_else(|| err("command.failed", &[]))?;
|
||||
let query = horizon_world::worldgen::generator::JigsawQuery {
|
||||
pool: &pool,
|
||||
target: &target,
|
||||
max_depth,
|
||||
position: pos,
|
||||
};
|
||||
let placed = self.with_level(|b, level, ticks| {
|
||||
b.place_jigsaw(level, ticks, pos, || terrain.jigsaw_pieces(&query))
|
||||
});
|
||||
self.process_level_events()
|
||||
.map_err(|_| err("command.failed", &[]))?;
|
||||
if !placed {
|
||||
return Err(err("commands.place.jigsaw.failed", &[]));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.place.jigsaw.success",
|
||||
&[num(pos[0]), num(pos[1]), num(pos[2])],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
_ => {
|
||||
let Some(Arg::Resource(structure)) = ctx.get("structure").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
if !self
|
||||
.ui
|
||||
.registries
|
||||
.ids("minecraft:worldgen/structure")
|
||||
.contains(&structure)
|
||||
{
|
||||
return Err(err("commands.place.structure.invalid", &[&structure]));
|
||||
}
|
||||
self.place_pos(ctx, "pos")?;
|
||||
// Structure.generate is not wired to the live level.
|
||||
Err(err("command.failed", &[]))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn cmd_place(&mut self, ctx: &Context) -> R<i32> {
|
||||
let Some(Arg::Resource(id)) = ctx.get("template").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let pos = if ctx.get("pos").is_some() {
|
||||
self.block_pos_arg(ctx, "pos")?
|
||||
} else {
|
||||
let p = self.source_position();
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
]
|
||||
};
|
||||
let pos = self.place_pos(ctx, "pos")?;
|
||||
let rotation = match ctx.get("rotation") {
|
||||
Some(Arg::Str(r)) => Rotation::from_name(r).unwrap_or(Rotation::None),
|
||||
_ => Rotation::None,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
use super::{Arg, Context, Game, R, Target, err, items::Owner};
|
||||
use horizon_client::{
|
||||
chunk::{HEIGHT, MIN_Y},
|
||||
command::CommandError,
|
||||
items::ItemStack,
|
||||
scoreboard_cmd::{Holder, Tracker},
|
||||
text::Text,
|
||||
@@ -146,18 +147,14 @@ impl Game<'_> {
|
||||
// ---- /fillbiome ----------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_fillbiome(&mut self, ctx: &Context) -> R<i32> {
|
||||
let (Some(Arg::Resource(biome)), from, to) = (
|
||||
ctx.get("biome").cloned(),
|
||||
self.coords(ctx, "from"),
|
||||
self.coords(ctx, "to"),
|
||||
) else {
|
||||
let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (Some(from), Some(to)) = (from, to) else {
|
||||
return Ok(0);
|
||||
};
|
||||
let (src_pos, src_rot) = (self.source_position(), self.source_rotation());
|
||||
let (a, b) = (from.block(src_pos, src_rot), to.block(src_pos, src_rot));
|
||||
// BlockPosArgument.getLoadedBlockPos on both corners first.
|
||||
let (a, b) = (
|
||||
self.block_pos_arg(ctx, "from")?,
|
||||
self.block_pos_arg(ctx, "to")?,
|
||||
);
|
||||
// Quantize to biome cells (`QuartPos`), then work with the box.
|
||||
let q = |v: i32| (v >> 2) << 2;
|
||||
let lo = [
|
||||
@@ -433,11 +430,20 @@ impl Game<'_> {
|
||||
|
||||
fn tool_stack(&mut self, ctx: &Context) -> R<Option<ItemStack>> {
|
||||
if let Some(Arg::Item(p)) = ctx.get("tool") {
|
||||
let (damage, extra) = match p
|
||||
.components
|
||||
.as_deref()
|
||||
.map(horizon_client::item_data::command_components)
|
||||
{
|
||||
Some(Ok(tag)) => horizon_client::item_data::decode_components(Some(&tag)),
|
||||
Some(Err(e)) => return Err(CommandError::new(Text::literal(e))),
|
||||
None => (0, None),
|
||||
};
|
||||
return Ok(Some(ItemStack {
|
||||
item: p.id.as_str().into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
damage,
|
||||
extra,
|
||||
}));
|
||||
}
|
||||
let entity = self
|
||||
@@ -461,19 +467,41 @@ impl Game<'_> {
|
||||
let Some(Arg::Resource(table)) = ctx.get("loot_table").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
if !self.res.items.has_loot_table(&table) {
|
||||
return Err(err("argument.resource_or_id.failed_to_parse", &[&table]));
|
||||
}
|
||||
let held = if id == "loot.fish" {
|
||||
self.tool_stack(ctx)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let drops =
|
||||
self.res
|
||||
// An inline table (ResourceOrIdArgument): no random sequence.
|
||||
if table.starts_with('{') {
|
||||
let (tag, _) = horizon_world::nbt::parse_snbt(&table)
|
||||
.map_err(|e| err("argument.nbt.invalid", &[&e]))?;
|
||||
let json = horizon_client::scoreboard::tag_to_json(&tag);
|
||||
let drops = self
|
||||
.res
|
||||
.items
|
||||
.loot_table(&table, false, held.as_ref(), &mut self.world.random);
|
||||
(drops, None)
|
||||
.inline_loot_table(&json, &mut self.world.random);
|
||||
(drops, None)
|
||||
} else {
|
||||
if !self.res.items.has_loot_table(&table) {
|
||||
return Err(err("argument.resource_or_id.failed_to_parse", &[&table]));
|
||||
}
|
||||
let held = if id == "loot.fish" {
|
||||
self.tool_stack(ctx)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let drops = match self.res.items.loot_sequence(&table) {
|
||||
Some(seq) => {
|
||||
let random = self.rand_sequences.get(&seq, self.level.seed);
|
||||
self.res
|
||||
.items
|
||||
.loot_table(&table, false, held.as_ref(), random)
|
||||
}
|
||||
None => self.res.items.loot_table(
|
||||
&table,
|
||||
false,
|
||||
held.as_ref(),
|
||||
&mut self.world.random,
|
||||
),
|
||||
};
|
||||
(drops, None)
|
||||
}
|
||||
}
|
||||
"loot.kill" => {
|
||||
let targets = self.entities(ctx, "target", false)?;
|
||||
@@ -493,12 +521,20 @@ impl Game<'_> {
|
||||
None | Some(Some(Target::Player))
|
||||
);
|
||||
let held = self.slot_get(&super::items::Slot::Inv(self.selected));
|
||||
let drops = self.res.items.entity_drops(
|
||||
&ty,
|
||||
by_player,
|
||||
held.as_ref(),
|
||||
&mut self.world.random,
|
||||
);
|
||||
let drops = match self.res.items.loot_sequence(&table) {
|
||||
Some(seq) => {
|
||||
let random = self.rand_sequences.get(&seq, self.level.seed);
|
||||
self.res
|
||||
.items
|
||||
.entity_drops(&ty, by_player, held.as_ref(), random)
|
||||
}
|
||||
None => self.res.items.entity_drops(
|
||||
&ty,
|
||||
by_player,
|
||||
held.as_ref(),
|
||||
&mut self.world.random,
|
||||
),
|
||||
};
|
||||
(drops, Some(table))
|
||||
}
|
||||
_ => {
|
||||
@@ -511,12 +547,23 @@ impl Game<'_> {
|
||||
return Err(err("commands.drop.no_loot_table.block", &[&name]));
|
||||
}
|
||||
let tool = self.tool_stack(ctx)?;
|
||||
let drops = self.res.items.block_drops(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
tool.as_ref(),
|
||||
&mut self.world.random,
|
||||
);
|
||||
let drops = match self.res.items.loot_sequence(&table) {
|
||||
Some(seq) => {
|
||||
let random = self.rand_sequences.get(&seq, self.level.seed);
|
||||
self.res.items.block_drops(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
tool.as_ref(),
|
||||
random,
|
||||
)
|
||||
}
|
||||
None => self.res.items.block_drops(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
tool.as_ref(),
|
||||
&mut self.world.random,
|
||||
),
|
||||
};
|
||||
(drops, Some(table))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,6 +11,37 @@ impl Game<'_> {
|
||||
};
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
|
||||
// NbtContents.resolve: the path's values in the entity, block or
|
||||
// storage data, rich-styled (or plain, or interpreted), ", "-joined.
|
||||
let nbt_values = std::cell::RefCell::new(Vec::new());
|
||||
{
|
||||
let mut collect = |o: &serde_json::Map<String, serde_json::Value>| {
|
||||
if o.contains_key("nbt") {
|
||||
nbt_values.borrow_mut().push(o.clone());
|
||||
}
|
||||
};
|
||||
fn walk(
|
||||
v: &serde_json::Value,
|
||||
f: &mut dyn FnMut(&serde_json::Map<String, serde_json::Value>),
|
||||
) {
|
||||
match v {
|
||||
serde_json::Value::Object(o) => {
|
||||
f(o);
|
||||
for (_, x) in o {
|
||||
walk(x, f);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(a) => a.iter().for_each(|x| walk(x, f)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
walk(&value, &mut collect);
|
||||
}
|
||||
let mut resolved: Vec<(serde_json::Map<String, serde_json::Value>, Text)> = Vec::new();
|
||||
for o in nbt_values.into_inner() {
|
||||
let t = self.resolve_nbt_component(&o);
|
||||
resolved.push((o, t));
|
||||
}
|
||||
let mut resolve = |raw: &str| -> Text {
|
||||
let mut reader = horizon_client::command::Reader::new(raw);
|
||||
let entities = horizon_client::command::args::ArgType::Entity {
|
||||
@@ -30,7 +61,79 @@ impl Game<'_> {
|
||||
}
|
||||
out
|
||||
};
|
||||
Ok(horizon_client::component::to_text(&value, &mut resolve))
|
||||
Ok(horizon_client::component::to_text_with(
|
||||
&value,
|
||||
&mut resolve,
|
||||
&mut |o| {
|
||||
resolved
|
||||
.iter()
|
||||
.find(|(k, _)| k == o)
|
||||
.map(|(_, t)| t.clone())
|
||||
},
|
||||
))
|
||||
}
|
||||
/// The text of an `nbt` component.
|
||||
fn resolve_nbt_component(&mut self, o: &serde_json::Map<String, serde_json::Value>) -> Text {
|
||||
use horizon_world::nbt::Tag;
|
||||
let path = o.get("nbt").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let mut sources: Vec<Tag> = Vec::new();
|
||||
if let Some(sel) = o.get("entity").and_then(|v| v.as_str()) {
|
||||
let mut reader = horizon_client::command::Reader::new(sel);
|
||||
let ty = horizon_client::command::args::ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
};
|
||||
if let Ok(Arg::Entity(s)) = ty.parse(&mut reader, &self.ui.registries) {
|
||||
for t in self.select(&s) {
|
||||
if let Ok(tag) = self.data_of(&super::data::DataRef::Entity(t)) {
|
||||
sources.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = o.get("storage").and_then(|v| v.as_str()) {
|
||||
let id = if id.contains(':') {
|
||||
id.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
sources.push(self.score.storage.get(&id));
|
||||
} else if let Some(pos) = o.get("block").and_then(|v| v.as_str()) {
|
||||
let p: Vec<i32> = pos
|
||||
.split_whitespace()
|
||||
.filter_map(|v| v.parse().ok())
|
||||
.collect();
|
||||
if let [x, y, z] = p[..]
|
||||
&& let Ok(tag) = self.data_of(&super::data::DataRef::Block([x, y, z]))
|
||||
{
|
||||
sources.push(tag);
|
||||
}
|
||||
}
|
||||
let Ok(compiled) = horizon_client::nbt_path::NbtPath::parse(path) else {
|
||||
return Text::empty();
|
||||
};
|
||||
let plain = o.get("plain").and_then(|v| v.as_bool()) == Some(true);
|
||||
let interpret = o.get("interpret").and_then(|v| v.as_bool()) == Some(true);
|
||||
let mut out = Text::empty();
|
||||
let mut first = true;
|
||||
for data in &sources {
|
||||
for tag in compiled.get(data).unwrap_or_default() {
|
||||
if !first {
|
||||
out.push(Text::literal(", "));
|
||||
}
|
||||
first = false;
|
||||
let piece = if interpret {
|
||||
horizon_client::scoreboard::comp_text(&horizon_client::scoreboard::tag_to_json(
|
||||
&tag,
|
||||
))
|
||||
} else if plain {
|
||||
Text::literal(horizon_client::snbt::pretty(&tag).plain())
|
||||
} else {
|
||||
horizon_client::snbt::pretty(&tag)
|
||||
};
|
||||
out.push(piece);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn player_targets(&mut self, ctx: &Context) -> R<usize> {
|
||||
// Only the local player can receive messages and titles.
|
||||
@@ -67,10 +170,10 @@ impl Game<'_> {
|
||||
} else {
|
||||
let text = self.component_arg(ctx, "title")?;
|
||||
if ctx.has("subtitle") {
|
||||
self.titles.subtitle = Some(text);
|
||||
self.titles.set_subtitle(text);
|
||||
"show.subtitle"
|
||||
} else if ctx.has("actionbar") {
|
||||
self.titles.set_overlay(text);
|
||||
self.titles.set_overlay(text, false);
|
||||
"show.actionbar"
|
||||
} else {
|
||||
self.titles.set_title(text);
|
||||
|
||||
@@ -31,7 +31,41 @@ impl Game<'_> {
|
||||
// ---- /recipe -----------------------------------------------------------
|
||||
|
||||
/// Every `minecraft:` recipe that `/recipe` can give (non-special ones).
|
||||
/// `Recipe.display().size()`.
|
||||
fn recipe_display_count(&self, id: &str) -> i32 {
|
||||
let path = self.options.resources.join(format!(
|
||||
"data/minecraft/recipe/{}.json",
|
||||
id.trim_start_matches("minecraft:")
|
||||
));
|
||||
let Some(v) = std::fs::read(path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
else {
|
||||
return 1;
|
||||
};
|
||||
if v["type"].as_str() != Some("minecraft:crafting_transmute") {
|
||||
return 1;
|
||||
}
|
||||
// TransmuteRecipe: material_count defaults to exactly 1; open
|
||||
// bounds are 1 and 8.
|
||||
let (min, max) = match &v["material_count"] {
|
||||
serde_json::Value::Null => (1, 1),
|
||||
serde_json::Value::Number(n) => {
|
||||
let n = n.as_i64().unwrap_or(1);
|
||||
(n, n)
|
||||
}
|
||||
b => (
|
||||
b["min"].as_i64().unwrap_or(1),
|
||||
b["max"].as_i64().unwrap_or(8),
|
||||
),
|
||||
};
|
||||
(max - min + 1).max(0) as i32
|
||||
}
|
||||
pub(super) fn learnable_recipes(&self) -> Vec<String> {
|
||||
// RecipeManager's learnable (non-special) recipes, as exported.
|
||||
if !self.ui.registries.learnable_recipes.is_empty() {
|
||||
return self.ui.registries.learnable_recipes.clone();
|
||||
}
|
||||
let dir = self.options.resources.join("data/minecraft/recipe");
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
@@ -72,14 +106,27 @@ impl Game<'_> {
|
||||
let mut tracker = Tracker::default();
|
||||
for &t in &targets {
|
||||
let h = holder(self.target_name(t));
|
||||
// ServerRecipeBook.addRecipes/removeRecipes count recipe book
|
||||
// displays (a transmute recipe has one per material count).
|
||||
let mut n = 0;
|
||||
let mut unlocked = Vec::new();
|
||||
for r in &recipes {
|
||||
let changed = if give {
|
||||
self.adv.recipes.insert(r.clone())
|
||||
} else {
|
||||
self.adv.recipes.remove(r)
|
||||
};
|
||||
n += i32::from(changed);
|
||||
if changed {
|
||||
n += self.recipe_display_count(r);
|
||||
if give {
|
||||
unlocked.push(r.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in unlocked {
|
||||
self.trigger("minecraft:recipe_unlocked", |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
tracker.track(&h, n);
|
||||
}
|
||||
@@ -254,6 +301,8 @@ impl Game<'_> {
|
||||
m.ai.swing_time = -1;
|
||||
}
|
||||
}
|
||||
// An armor stand is a LivingEntity: it swings (invisibly).
|
||||
Target::Stand(_) => {}
|
||||
_ => continue,
|
||||
}
|
||||
let h = holder(self.target_name(t));
|
||||
@@ -490,6 +539,27 @@ impl Game<'_> {
|
||||
Some(Arg::Int(c)) => *c,
|
||||
_ => 0,
|
||||
};
|
||||
// ParticleCommand.sendParticles: the viewers it reached, each within
|
||||
// 32 blocks (512 with `force`) of the particle's block centre.
|
||||
let viewers = if ctx.get("viewers").is_some() {
|
||||
self.entities(ctx, "viewers", true)?
|
||||
} else {
|
||||
vec![Target::Player]
|
||||
};
|
||||
let limit = if ctx.has("force") { 512.0 } else { 32.0 };
|
||||
let reached = viewers
|
||||
.iter()
|
||||
.filter(|&&t| {
|
||||
self.target_position(t).is_some_and(|p| {
|
||||
let c = p.map(|v| v.floor() + 0.5);
|
||||
(c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2)
|
||||
< limit * limit
|
||||
})
|
||||
})
|
||||
.count() as i32;
|
||||
if reached == 0 {
|
||||
return Err(err("commands.particle.failed", &[]));
|
||||
}
|
||||
// `ServerLevel.sendParticles`: no count means one particle with the delta as velocity.
|
||||
if count <= 0 {
|
||||
self.particles.create(&options, pos, delta);
|
||||
@@ -513,7 +583,7 @@ impl Game<'_> {
|
||||
"commands.particle.success",
|
||||
&[Text::literal(name.to_owned())],
|
||||
));
|
||||
Ok(count.max(1))
|
||||
Ok(reached)
|
||||
}
|
||||
|
||||
// ---- /attribute ---------------------------------------------------------------------
|
||||
@@ -623,9 +693,13 @@ impl Game<'_> {
|
||||
.has_modifier(Some(key), &modifier_id)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(err(
|
||||
return Err(text_error(
|
||||
"commands.attribute.failed.modifier_already_present",
|
||||
&[&modifier_id, &description.plain(), &name.plain()],
|
||||
&[
|
||||
Text::literal(modifier_id.clone()),
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
],
|
||||
));
|
||||
}
|
||||
let op = ctx
|
||||
@@ -648,9 +722,13 @@ impl Game<'_> {
|
||||
.has_modifier(Some(key), &modifier_id)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(err(
|
||||
return Err(text_error(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
&[
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
Text::literal(modifier_id.clone()),
|
||||
],
|
||||
));
|
||||
}
|
||||
let _ =
|
||||
@@ -678,9 +756,13 @@ impl Game<'_> {
|
||||
.ok()
|
||||
.flatten();
|
||||
let Some(v) = found else {
|
||||
return Err(err(
|
||||
return Err(text_error(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
&[
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
Text::literal(modifier_id.clone()),
|
||||
],
|
||||
));
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
@@ -696,6 +778,26 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Target::Mob(_) | Target::Stand(_)
|
||||
if !(matches!(target, Target::Mob(_))
|
||||
&& matches!(
|
||||
short.as_str(),
|
||||
"max_health" | "movement_speed" | "attack_damage"
|
||||
)) =>
|
||||
{
|
||||
let op = ctx
|
||||
.literals
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "add_value".into());
|
||||
self.generic_attribute(
|
||||
target,
|
||||
id,
|
||||
&attribute,
|
||||
(&name, &description),
|
||||
(value_arg, scale, &modifier_id, &op),
|
||||
)
|
||||
}
|
||||
Target::Mob(mob_id) => {
|
||||
let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) else {
|
||||
return Ok(0);
|
||||
@@ -755,16 +857,177 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(err(
|
||||
_ => Err(text_error(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[&description.plain(), &name.plain(), &modifier_id],
|
||||
&[
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
Text::literal(modifier_id.clone()),
|
||||
],
|
||||
)),
|
||||
}
|
||||
}
|
||||
_ => Err(err("commands.attribute.failed.entity", &[&name.plain()])),
|
||||
_ => Err(text_error(
|
||||
"commands.attribute.failed.entity",
|
||||
std::slice::from_ref(&name),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute map of a living entity whose attributes Horizon does
|
||||
/// not model, created from its type's defaults on first use.
|
||||
pub(in crate::game) fn generic_attributes(
|
||||
&mut self,
|
||||
t: Target,
|
||||
) -> Option<&mut horizon_world::attributes::entity::EntityAttributes> {
|
||||
if !self.cmds.attributes.contains_key(&t) {
|
||||
let ty = self.target_type(t);
|
||||
let map = self.motion.attributes.create(&ty)?;
|
||||
self.cmds.attributes.insert(t, map);
|
||||
}
|
||||
self.cmds.attributes.get_mut(&t)
|
||||
}
|
||||
/// AttributeCommand on a living entity through its generic attribute map.
|
||||
fn generic_attribute(
|
||||
&mut self,
|
||||
target: Target,
|
||||
id: &str,
|
||||
attribute: &str,
|
||||
(name, description): (&Text, &Text),
|
||||
(value_arg, scale, modifier_id, op): (f64, f64, &str, &str),
|
||||
) -> R<i32> {
|
||||
use horizon_world::attributes::{Modifier, Operation};
|
||||
let no_attribute = || {
|
||||
text_error(
|
||||
"commands.attribute.failed.no_attribute",
|
||||
&[name.clone(), description.clone()],
|
||||
)
|
||||
};
|
||||
let no_modifier = || {
|
||||
text_error(
|
||||
"commands.attribute.failed.no_modifier",
|
||||
&[
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
Text::literal(modifier_id),
|
||||
],
|
||||
)
|
||||
};
|
||||
let catalog = self.motion.attributes.clone();
|
||||
let key = catalog.id(attribute).ok_or_else(no_attribute)?;
|
||||
let map = self.generic_attributes(target).ok_or_else(no_attribute)?;
|
||||
if !map.has(key) {
|
||||
return Err(no_attribute());
|
||||
}
|
||||
let (message, args, result) = match id {
|
||||
"attribute.get" | "attribute.base.get" => {
|
||||
let v = if id == "attribute.get" {
|
||||
map.value(key).map_err(|_| no_attribute())?
|
||||
} else {
|
||||
map.base_value(key).map_err(|_| no_attribute())?
|
||||
};
|
||||
let k = if id == "attribute.get" {
|
||||
"commands.attribute.value.get.success"
|
||||
} else {
|
||||
"commands.attribute.base_value.get.success"
|
||||
};
|
||||
(
|
||||
k,
|
||||
vec![description.clone(), name.clone(), java_double_text(v)],
|
||||
(v * scale) as i32,
|
||||
)
|
||||
}
|
||||
"attribute.base.set" => {
|
||||
map.edit(key, |a, o| {
|
||||
let _ = a.set_base_value(value_arg, o);
|
||||
});
|
||||
(
|
||||
"commands.attribute.base_value.set.success",
|
||||
vec![
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
java_double_text(value_arg),
|
||||
],
|
||||
1,
|
||||
)
|
||||
}
|
||||
"attribute.base.reset" => {
|
||||
map.reset_base(key);
|
||||
let v = map.base_value(key).unwrap_or(0.0);
|
||||
(
|
||||
"commands.attribute.base_value.reset.success",
|
||||
vec![description.clone(), name.clone(), java_double_text(v)],
|
||||
1,
|
||||
)
|
||||
}
|
||||
"attribute.modifier.add" => {
|
||||
if map.has_modifier(key, modifier_id) {
|
||||
return Err(text_error(
|
||||
"commands.attribute.failed.modifier_already_present",
|
||||
&[
|
||||
Text::literal(modifier_id),
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
],
|
||||
));
|
||||
}
|
||||
let operation = match op {
|
||||
"add_multiplied_base" => Operation::AddMultipliedBase,
|
||||
"add_multiplied_total" => Operation::AddMultipliedTotal,
|
||||
_ => Operation::AddValue,
|
||||
};
|
||||
let m =
|
||||
Modifier::new(modifier_id, value_arg, operation).map_err(|_| no_attribute())?;
|
||||
map.edit(key, |a, o| {
|
||||
let _ = a.add_permanent(m, o);
|
||||
});
|
||||
(
|
||||
"commands.attribute.modifier.add.success",
|
||||
vec![
|
||||
Text::literal(modifier_id),
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
],
|
||||
1,
|
||||
)
|
||||
}
|
||||
"attribute.modifier.remove" => {
|
||||
if !map.has_modifier(key, modifier_id) {
|
||||
return Err(no_modifier());
|
||||
}
|
||||
map.edit(key, |a, o| {
|
||||
let _ = a.remove(modifier_id, o);
|
||||
});
|
||||
(
|
||||
"commands.attribute.modifier.remove.success",
|
||||
vec![
|
||||
Text::literal(modifier_id),
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
],
|
||||
1,
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let v = map
|
||||
.modifier_value(key, modifier_id)
|
||||
.map_err(|_| no_modifier())?;
|
||||
(
|
||||
"commands.attribute.modifier.value.get.success",
|
||||
vec![
|
||||
Text::literal(modifier_id),
|
||||
description.clone(),
|
||||
name.clone(),
|
||||
java_double_text(v),
|
||||
],
|
||||
(v * scale) as i32,
|
||||
)
|
||||
}
|
||||
};
|
||||
self.feedback(Text::translate(message, &args));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// ---- /ride ----------------------------------------------------------------------------
|
||||
|
||||
pub(super) fn cmd_ride(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
@@ -864,145 +1127,232 @@ impl Game<'_> {
|
||||
if targets.is_empty() {
|
||||
return Err(err("argument.entity.notfound.entity", &[]));
|
||||
}
|
||||
// Units: each entity, or each team together with `respectTeams`.
|
||||
let mut units: Vec<Vec<Target>> = Vec::new();
|
||||
let mut teams: Vec<(String, usize)> = Vec::new();
|
||||
for &t in &targets {
|
||||
let team = if respect {
|
||||
self.holder_name(t)
|
||||
.and_then(|h| self.score.board.players_team(&h).map(|x| x.name.clone()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match team {
|
||||
Some(name) => match teams.iter().find(|(n, _)| *n == name) {
|
||||
Some((_, i)) => units[*i].push(t),
|
||||
None => {
|
||||
teams.push((name, units.len()));
|
||||
units.push(vec![t]);
|
||||
}
|
||||
},
|
||||
None => units.push(vec![t]),
|
||||
// SpreadPlayersCommand: one position per entity, or per team (every
|
||||
// non-player and team-less player sharing one) with respectTeams.
|
||||
let team_of = |g: &mut Self, t: Target| -> Option<String> {
|
||||
if t != Target::Player {
|
||||
return None;
|
||||
}
|
||||
g.holder_name(t)
|
||||
.and_then(|h| g.score.board.players_team(&h).map(|x| x.name.clone()))
|
||||
};
|
||||
let count = if respect {
|
||||
let mut seen: Vec<Option<String>> = Vec::new();
|
||||
for &t in &targets {
|
||||
let team = team_of(self, t);
|
||||
if !seen.contains(&team) {
|
||||
seen.push(team);
|
||||
}
|
||||
}
|
||||
seen.len()
|
||||
} else {
|
||||
targets.len()
|
||||
};
|
||||
let centre_f = [centre[0] as f32, centre[2] as f32];
|
||||
let (cx, cz) = (f64::from(centre_f[0]), f64::from(centre_f[1]));
|
||||
let (min_x, max_x) = (cx - range, cx + range);
|
||||
let (min_z, max_z) = (cz - range, cz + range);
|
||||
// Mth.nextDouble.
|
||||
let next = |g: &mut Self, lo: f64, hi: f64| {
|
||||
if lo >= hi {
|
||||
lo
|
||||
} else {
|
||||
g.world.random.next_double() * (hi - lo) + lo
|
||||
}
|
||||
};
|
||||
let mut points: Vec<[f64; 2]> = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let x = next(self, min_x, max_x);
|
||||
let z = next(self, min_z, max_z);
|
||||
points.push([x, z]);
|
||||
}
|
||||
let (min_x, max_x) = (centre[0] - range, centre[0] + range);
|
||||
let (min_z, max_z) = (centre[2] - range, centre[2] + range);
|
||||
let mut points: Vec<[f64; 2]> = units
|
||||
.iter()
|
||||
.map(|_| {
|
||||
let r = &mut self.world.random;
|
||||
[
|
||||
min_x + r.next_double() * (max_x - min_x),
|
||||
min_z + r.next_double() * (max_z - min_z),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let n = points.len();
|
||||
let mut ok = false;
|
||||
for _ in 0..10_000 {
|
||||
let mut moved = false;
|
||||
let mut crowded = 0;
|
||||
for i in 0..n {
|
||||
let mut push = [0.0, 0.0];
|
||||
let mut near = 0;
|
||||
for j in 0..n {
|
||||
let mut collisions = true;
|
||||
let mut min_distance = f64::from(f32::MAX);
|
||||
let mut iteration = 0;
|
||||
while iteration < 10_000 && collisions {
|
||||
collisions = false;
|
||||
min_distance = f64::from(f32::MAX);
|
||||
for i in 0..points.len() {
|
||||
let mut neighbours = 0;
|
||||
let mut avg = [0.0f64, 0.0f64];
|
||||
for j in 0..points.len() {
|
||||
if i == j {
|
||||
continue;
|
||||
}
|
||||
let (dx, dz) = (points[j][0] - points[i][0], points[j][1] - points[i][1]);
|
||||
let d = (dx * dx + dz * dz).sqrt();
|
||||
if d < spread {
|
||||
near += 1;
|
||||
if d > 1.0e-6 {
|
||||
push[0] -= dx / d;
|
||||
push[1] -= dz / d;
|
||||
} else {
|
||||
let r = &mut self.world.random;
|
||||
push[0] += r.next_double() - 0.5;
|
||||
push[1] += r.next_double() - 0.5;
|
||||
}
|
||||
let (dx, dz) = (points[i][0] - points[j][0], points[i][1] - points[j][1]);
|
||||
let dist = (dx * dx + dz * dz).sqrt();
|
||||
min_distance = min_distance.min(dist);
|
||||
if dist < spread {
|
||||
neighbours += 1;
|
||||
avg[0] += points[j][0] - points[i][0];
|
||||
avg[1] += points[j][1] - points[i][1];
|
||||
}
|
||||
}
|
||||
if near > 0 {
|
||||
crowded += 1;
|
||||
let len = (push[0] * push[0] + push[1] * push[1]).sqrt().max(1.0e-6);
|
||||
points[i][0] += push[0] / len;
|
||||
points[i][1] += push[1] / len;
|
||||
moved = true;
|
||||
if neighbours > 0 {
|
||||
avg[0] /= f64::from(neighbours);
|
||||
avg[1] /= f64::from(neighbours);
|
||||
let length = (avg[0] * avg[0] + avg[1] * avg[1]).sqrt();
|
||||
if length > 0.0 {
|
||||
points[i][0] -= avg[0] / length;
|
||||
points[i][1] -= avg[1] / length;
|
||||
} else {
|
||||
points[i][0] = next(self, min_x, max_x);
|
||||
points[i][1] = next(self, min_z, max_z);
|
||||
}
|
||||
collisions = true;
|
||||
}
|
||||
let p = &mut points[i];
|
||||
let before = *p;
|
||||
p[0] = if p[0] < min_x {
|
||||
min_x
|
||||
} else if p[0] > max_x {
|
||||
max_x
|
||||
} else {
|
||||
p[0]
|
||||
};
|
||||
p[1] = if p[1] < min_z {
|
||||
min_z
|
||||
} else if p[1] > max_z {
|
||||
max_z
|
||||
} else {
|
||||
p[1]
|
||||
};
|
||||
if before != *p {
|
||||
collisions = true;
|
||||
}
|
||||
let before = points[i];
|
||||
points[i][0] = points[i][0].clamp(min_x, max_x);
|
||||
points[i][1] = points[i][1].clamp(min_z, max_z);
|
||||
moved |= before != points[i];
|
||||
}
|
||||
if !moved || crowded == 0 {
|
||||
ok = true;
|
||||
break;
|
||||
if !collisions {
|
||||
for i in 0..points.len() {
|
||||
if !self.spread_safe(points[i], max_y) {
|
||||
points[i][0] = next(self, min_x, max_x);
|
||||
points[i][1] = next(self, min_z, max_z);
|
||||
collisions = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
iteration += 1;
|
||||
}
|
||||
if !ok {
|
||||
let key = if teams.is_empty() {
|
||||
"commands.spreadplayers.failed.entities"
|
||||
} else {
|
||||
if min_distance == f64::from(f32::MAX) {
|
||||
min_distance = 0.0;
|
||||
}
|
||||
let float = |v: f32| Text::literal(horizon_client::snbt::java_float(v));
|
||||
if iteration >= 10_000 {
|
||||
let key = if respect {
|
||||
"commands.spreadplayers.failed.teams"
|
||||
} else {
|
||||
"commands.spreadplayers.failed.entities"
|
||||
};
|
||||
return Err(err(
|
||||
return Err(text_error(
|
||||
key,
|
||||
&[
|
||||
&n,
|
||||
&format!("{:.2}", centre[0]),
|
||||
&format!("{:.2}", centre[2]),
|
||||
&format!("{:.2}", spread),
|
||||
num(points.len()),
|
||||
float(centre_f[0]),
|
||||
float(centre_f[1]),
|
||||
Text::literal(format!("{min_distance:.2}")),
|
||||
],
|
||||
));
|
||||
}
|
||||
// Stand each unit on the ground under `max_y`.
|
||||
// setPlayerPositions.
|
||||
let mut total = 0.0;
|
||||
for (unit, p) in units.iter().zip(&points) {
|
||||
let (bx, bz) = (p[0].floor() as i32, p[1].floor() as i32);
|
||||
let mut y = None;
|
||||
for yy in (horizon_client::chunk::MIN_Y
|
||||
..max_y.min(horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT))
|
||||
.rev()
|
||||
{
|
||||
let solid = |dy: i32| {
|
||||
self.res
|
||||
.facts
|
||||
.get(self.world.block(bx, yy + dy, bz))
|
||||
.full_collision
|
||||
};
|
||||
if solid(-1) && !solid(0) && !solid(1) {
|
||||
y = Some(yy);
|
||||
break;
|
||||
let mut index = 0;
|
||||
let mut team_points: Vec<(Option<String>, usize)> = Vec::new();
|
||||
for &t in &targets {
|
||||
let i = if respect {
|
||||
let team = team_of(self, t);
|
||||
match team_points.iter().find(|(k, _)| *k == team) {
|
||||
Some((_, i)) => *i,
|
||||
None => {
|
||||
team_points.push((team, index));
|
||||
index += 1;
|
||||
index - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
let y = y.unwrap_or(max_y);
|
||||
for &t in unit {
|
||||
self.teleport_to(
|
||||
t,
|
||||
[f64::from(bx) + 0.5, f64::from(y), f64::from(bz) + 0.5],
|
||||
None,
|
||||
);
|
||||
}
|
||||
let (dx, dz) = (p[0] - centre[0], p[1] - centre[2]);
|
||||
total += (dx * dx + dz * dz).sqrt();
|
||||
} else {
|
||||
index += 1;
|
||||
index - 1
|
||||
};
|
||||
let p = points[i];
|
||||
let y = self.spread_spawn_y(p, max_y);
|
||||
self.teleport_to(
|
||||
t,
|
||||
[p[0].floor() + 0.5, f64::from(y), p[1].floor() + 0.5],
|
||||
None,
|
||||
);
|
||||
let closest = points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| *j != i)
|
||||
.map(|(_, q)| ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt())
|
||||
.fold(f64::MAX, f64::min);
|
||||
total += closest;
|
||||
}
|
||||
let average = if n == 0 { 0.0 } else { total / n as f64 };
|
||||
let key = if teams.is_empty() {
|
||||
"commands.spreadplayers.success.entities"
|
||||
let average = if targets.len() < 2 {
|
||||
0.0
|
||||
} else {
|
||||
total / targets.len() as f64
|
||||
};
|
||||
let key = if respect {
|
||||
"commands.spreadplayers.success.teams"
|
||||
} else {
|
||||
"commands.spreadplayers.success.entities"
|
||||
};
|
||||
self.feedback(Text::translate(
|
||||
key,
|
||||
&[
|
||||
num(n),
|
||||
Text::literal(format!("{:.2}", centre[0])),
|
||||
Text::literal(format!("{:.2}", centre[2])),
|
||||
num(points.len()),
|
||||
float(centre_f[0]),
|
||||
float(centre_f[1]),
|
||||
Text::literal(format!("{average:.2}")),
|
||||
],
|
||||
));
|
||||
Ok(n as i32)
|
||||
Ok(points.len() as i32)
|
||||
}
|
||||
/// `SpreadPlayersCommand.Position.getSpawnY`.
|
||||
fn spread_spawn_y(&self, p: [f64; 2], max_y: i32) -> i32 {
|
||||
let (x, z) = (p[0].floor() as i32, p[1].floor() as i32);
|
||||
let air = |y: i32| {
|
||||
let name: &str = &self.res.facts.get(self.world.block(x, y, z)).name;
|
||||
matches!(
|
||||
name,
|
||||
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
|
||||
)
|
||||
};
|
||||
let mut y = max_y + 1;
|
||||
let mut air2 = air(y);
|
||||
y -= 1;
|
||||
let mut air1 = air(y);
|
||||
while y > horizon_client::chunk::MIN_Y {
|
||||
y -= 1;
|
||||
let current = air(y);
|
||||
if !current && air1 && air2 {
|
||||
return y + 1;
|
||||
}
|
||||
air2 = air1;
|
||||
air1 = current;
|
||||
}
|
||||
max_y + 1
|
||||
}
|
||||
/// `SpreadPlayersCommand.Position.isSafe`.
|
||||
fn spread_safe(&self, p: [f64; 2], max_y: i32) -> bool {
|
||||
let y = self.spread_spawn_y(p, max_y) - 1;
|
||||
let (x, z) = (p[0].floor() as i32, p[1].floor() as i32);
|
||||
let name = self.res.facts.get(self.world.block(x, y, z)).name.clone();
|
||||
let liquid = matches!(&*name, "minecraft:water" | "minecraft:lava");
|
||||
let teleportable = self
|
||||
.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("entities_can_teleport_to")
|
||||
.or_else(|| {
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:entities_can_teleport_to")
|
||||
})
|
||||
.is_some_and(|set| {
|
||||
set.contains(&*name) || set.contains(name.trim_start_matches("minecraft:"))
|
||||
});
|
||||
y < max_y && !liquid && teleportable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ impl Game<'_> {
|
||||
m.extra.scratch[3] -= 1;
|
||||
}
|
||||
// The visited positions fade after 6000 ticks.
|
||||
if m.extra.ints[2] > 0 && m.age >= m.extra.ints[2] {
|
||||
if m.extra.ints[2] > 0 && m.age as i32 >= m.extra.ints[2] {
|
||||
m.extra.positions.clear();
|
||||
m.extra.ints[2] = 0;
|
||||
}
|
||||
@@ -141,9 +141,11 @@ impl Game<'_> {
|
||||
if next == -2 {
|
||||
return false;
|
||||
}
|
||||
let interval = |m: &mut Mob| 504_000 + i64::from(m.random.next_int_bound(48_001).unwrap_or(0));
|
||||
// updateWeathering draws from the level random.
|
||||
let r = &mut self.world.random;
|
||||
let mut interval = || 504_000 + i64::from(r.next_int_bound(48_001).unwrap_or(0));
|
||||
if next == -1 {
|
||||
m.extra.vector[0] = (now + interval(m)) as f64;
|
||||
m.extra.vector[0] = (now + interval()) as f64;
|
||||
return false;
|
||||
}
|
||||
let fully = m.extra.variant >= 3;
|
||||
@@ -153,7 +155,7 @@ impl Game<'_> {
|
||||
m.extra.vector[0] = if new >= 3 {
|
||||
0.0
|
||||
} else {
|
||||
(next + interval(m)) as f64
|
||||
(next + interval()) as f64
|
||||
};
|
||||
}
|
||||
if fully && self.golem_can_turn_to_statue(m) {
|
||||
@@ -177,8 +179,9 @@ impl Game<'_> {
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
// The pose comes from the golem's own random (`this.random.nextInt(0, 4)`).
|
||||
let pose = ["standing", "sitting", "running", "star"]
|
||||
[self.world.random.next_int_bound(4).unwrap_or(0) as usize];
|
||||
[m.random.next_int_bound(4).unwrap_or(0) as usize];
|
||||
// Direction.fromYRot.
|
||||
let facing = ["south", "west", "north", "east"]
|
||||
[((f64::from(m.yaw) / 90.0 + 0.5).floor() as i32 & 3) as usize];
|
||||
@@ -186,7 +189,7 @@ impl Game<'_> {
|
||||
name: "minecraft:oxidized_copper_golem_statue".into(),
|
||||
properties: [
|
||||
("facing".to_string(), facing.to_string()),
|
||||
("pose".to_string(), pose.to_string()),
|
||||
("copper_golem_pose".to_string(), pose.to_string()),
|
||||
("waterlogged".to_string(), "false".to_string()),
|
||||
]
|
||||
.into(),
|
||||
@@ -212,15 +215,18 @@ impl Game<'_> {
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
/// `dropPreservedEquipment`: the carried stack and the antenna.
|
||||
/// `Mob.dropPreservedEquipment`: the guaranteed drops in `EquipmentSlot`
|
||||
/// order, the carried stack (main hand) then the antenna flower (saddle),
|
||||
/// each `spawnAtLocation` at the golem's feet.
|
||||
pub(super) fn golem_drop_equipment(&mut self, m: &mut Mob) {
|
||||
let at = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
let at = m.position;
|
||||
if let Some(stack) = held(m).cloned() {
|
||||
set_held(m, None);
|
||||
self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10);
|
||||
self.spawn_at_location(at, 0.0, stack);
|
||||
}
|
||||
if let Some(antenna) = m.extra.legs.take() {
|
||||
self.spawn_item(ItemStack::new(&antenna, 1), at, [0.0, 0.2, 0.0], 10);
|
||||
if let Some(antenna) = m.saddle_item() {
|
||||
m.set_saddle(None);
|
||||
self.spawn_at_location(at, 0.0, antenna);
|
||||
}
|
||||
}
|
||||
// ---- containers -------------------------------------------------------
|
||||
@@ -252,7 +258,8 @@ impl Game<'_> {
|
||||
fn golem_chest_blocked(&self, keys: &[Key]) -> bool {
|
||||
keys.iter().any(|k| {
|
||||
let above = self.world.block(k.0, k.1 + 1, k.2);
|
||||
self.behaviours.facts(above).flags & horizon_world::level::data::state_flags::CONDUCTOR
|
||||
self.res.behaviours.facts(above).flags
|
||||
& horizon_world::level::data::state_flags::CONDUCTOR
|
||||
!= 0
|
||||
})
|
||||
}
|
||||
@@ -273,7 +280,11 @@ impl Game<'_> {
|
||||
None
|
||||
}
|
||||
fn golem_max_stack(&self, stack: &ItemStack) -> u32 {
|
||||
self.res.items.get(&stack.item).map_or(64, |i| i.max_stack).max(1)
|
||||
self.res
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.map_or(64, |i| i.max_stack)
|
||||
.max(1)
|
||||
}
|
||||
/// `pickupItemFromContainer`: up to 16 of the first non-empty slot.
|
||||
fn golem_pick_up(&mut self, keys: &[Key]) -> Option<ItemStack> {
|
||||
@@ -362,7 +373,10 @@ impl Game<'_> {
|
||||
let Some(h) = m.extra.home else { return false };
|
||||
let key = (h[0], h[1], h[2]);
|
||||
let valid = self.golem_wanted_block(m, key)
|
||||
&& matches!(self.world.block_entities.get(&key), Some(BlockEntity::Chest(_)))
|
||||
&& matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Chest(_))
|
||||
)
|
||||
&& !self.golem_chest_blocked(&self.golem_container(key));
|
||||
if !valid {
|
||||
return false;
|
||||
@@ -389,7 +403,11 @@ impl Game<'_> {
|
||||
f64::from(n.y) + m.kind.height / 2.0,
|
||||
f64::from(n.z) + 0.5,
|
||||
],
|
||||
None => [m.position.x, m.position.y + m.kind.height / 2.0, m.position.z],
|
||||
None => [
|
||||
m.position.x,
|
||||
m.position.y + m.kind.height / 2.0,
|
||||
m.position.z,
|
||||
],
|
||||
};
|
||||
let reach = golem_within(m, self.golem_range(m), from, h);
|
||||
(path.is_none() && !reach) || reach
|
||||
@@ -446,7 +464,7 @@ impl Game<'_> {
|
||||
}
|
||||
m.extra.positions.retain(|p| p[1] >= UNREACHABLE);
|
||||
m.extra.positions.extend(list);
|
||||
m.extra.ints[2] = m.age + MEMORY_TICKS;
|
||||
m.extra.ints[2] = m.age as i32 + MEMORY_TICKS;
|
||||
}
|
||||
fn golem_mark_unreachable(&mut self, m: &mut Mob, h: [i32; 3]) {
|
||||
m.extra.positions.retain(|p| *p != h);
|
||||
@@ -454,11 +472,16 @@ impl Game<'_> {
|
||||
if !m.extra.positions.contains(&marked) {
|
||||
m.extra.positions.push(marked);
|
||||
}
|
||||
let count = m.extra.positions.iter().filter(|p| p[1] >= UNREACHABLE).count();
|
||||
let count = m
|
||||
.extra
|
||||
.positions
|
||||
.iter()
|
||||
.filter(|p| p[1] >= UNREACHABLE)
|
||||
.count();
|
||||
if count > 50 {
|
||||
self.golem_enter_cooldown(m);
|
||||
} else {
|
||||
m.extra.ints[2] = m.age + MEMORY_TICKS;
|
||||
m.extra.ints[2] = m.age as i32 + MEMORY_TICKS;
|
||||
}
|
||||
}
|
||||
fn golem_stop_targeting(&mut self, m: &mut Mob) {
|
||||
@@ -495,7 +518,9 @@ impl Game<'_> {
|
||||
}
|
||||
fn golem_chest_sound(&mut self, key: Key, open: bool) {
|
||||
let name = self.golem_block_name(key);
|
||||
let base = name.trim_start_matches("minecraft:").trim_start_matches("waxed_");
|
||||
let base = name
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_start_matches("waxed_");
|
||||
let kind = if base.starts_with("weathered") {
|
||||
"copper_chest_weathered"
|
||||
} else if base.starts_with("oxidized") {
|
||||
@@ -508,8 +533,12 @@ impl Game<'_> {
|
||||
let side = if open { "open" } else { "close" };
|
||||
let at = chest_center([key.0, key.1, key.2]);
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play(&format!("minecraft:block.{kind}.{side}"), Some(at), 0.5, pitch);
|
||||
self.audio.play(
|
||||
&format!("minecraft:block.{kind}.{side}"),
|
||||
Some(at),
|
||||
0.5,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
fn golem_on_queuing(&mut self, m: &mut Mob) {
|
||||
let Some(h) = m.extra.home else { return };
|
||||
@@ -601,7 +630,8 @@ impl Game<'_> {
|
||||
&& let Some(sound) = sound
|
||||
{
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
self.audio.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
|
||||
self.audio
|
||||
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
|
||||
}
|
||||
if ticks == 60 {
|
||||
self.golem_release(m);
|
||||
@@ -626,7 +656,9 @@ impl Game<'_> {
|
||||
.any(|s| held(m).is_some_and(|h| h.item == s.item))
|
||||
{
|
||||
// putDownItem.
|
||||
let stack = held(m).cloned().unwrap_or_else(|| ItemStack::new("minecraft:air", 0));
|
||||
let stack = held(m)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:air", 0));
|
||||
let left = self.golem_put_down(&keys, stack);
|
||||
let emptied = left.is_none();
|
||||
set_held(m, left);
|
||||
@@ -657,25 +689,39 @@ impl Game<'_> {
|
||||
return false;
|
||||
};
|
||||
set_held(&mut self.mobs[index], None);
|
||||
// BehaviorUtils.throwItem: from 0.3 below the golem's eyes towards
|
||||
// the player's feet at 0.3 blocks a tick, default pickup delay.
|
||||
let p = self.player.as_ref().map(|p| p.position);
|
||||
let from = [at[0], at[1] + 0.9, at[2]];
|
||||
let eye = f64::from(self.mobs[index].eye_height());
|
||||
let from = [at[0], at[1] + eye - f64::from(0.3f32), at[2]];
|
||||
let v = p.map_or([0.0; 3], |p| {
|
||||
let d = [p.x - from[0], p.y + 1.0 - from[1], p.z - from[2]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
|
||||
[d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3]
|
||||
let d = [p.x - at[0], p.y - at[1], p.z - at[2]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if len < 1.0e-5 {
|
||||
return [0.0; 3];
|
||||
}
|
||||
let k = f64::from(0.3f32);
|
||||
[d[0] / len * k, d[1] / len * k, d[2] / len * k]
|
||||
});
|
||||
self.spawn_item(h, from, v, 40);
|
||||
self.spawn_item(h, from, v, 10);
|
||||
return true;
|
||||
}
|
||||
let name = item;
|
||||
let is_axe = name.ends_with("_axe");
|
||||
let waxed = self.mobs[index].extra.vector[0] as i64 == -2;
|
||||
if name == "minecraft:shears" && self.golem_shearable(index) {
|
||||
let antenna = self.mobs[index].extra.legs.take();
|
||||
// CopperGolem.shear: the sound, the antenna slot emptied (an
|
||||
// unequip) and the flower dropped 1.5 up.
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.shear", Some(at), 1.0, 1.0);
|
||||
let antenna = self.mobs[index].saddle_item();
|
||||
self.mobs[index].set_saddle(None);
|
||||
let id = self.mobs[index].id;
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None);
|
||||
self.post_game_event("minecraft:unequip", at, ctx);
|
||||
if let Some(a) = antenna {
|
||||
self.spawn_item(ItemStack::new(&a, 1), [at[0], at[1] + 1.5, at[2]], [0.0, 0.2, 0.0], 10);
|
||||
let p = self.mobs[index].position;
|
||||
self.spawn_at_location(p, 1.5, a);
|
||||
}
|
||||
self.damage_held_tool();
|
||||
return true;
|
||||
@@ -705,13 +751,14 @@ impl Game<'_> {
|
||||
}
|
||||
false
|
||||
}
|
||||
fn golem_shearable(&self, index: usize) -> bool {
|
||||
self.mobs[index].extra.legs.as_deref().is_some_and(|a| {
|
||||
/// `readyForShearing`: the antenna holds a flower shears take.
|
||||
pub(super) fn golem_shearable(&self, index: usize) -> bool {
|
||||
self.mobs[index].saddle_item().is_some_and(|a| {
|
||||
self.res
|
||||
.items
|
||||
.item_tags
|
||||
.get("minecraft:shearable_from_copper_golem")
|
||||
.is_some_and(|t| t.contains(a))
|
||||
.is_some_and(|t| t.contains(&*a.item))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,14 @@ fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
pushable: m.pushable(),
|
||||
category: m.category(),
|
||||
potential_job: horizon_client::mobs::villager_brain::potential_job_site(m),
|
||||
meeting: (m.species() == Species::Villager)
|
||||
.then_some(m.extra.meeting)
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
@@ -166,6 +174,7 @@ impl Game<'_> {
|
||||
yaw: self.yaw,
|
||||
hero: self.potions.effects.get("hero_of_the_village").is_some(),
|
||||
uuid: self.level.player_uuid.unwrap_or_default(),
|
||||
allies: std::sync::Arc::new(self.player_allies()),
|
||||
})
|
||||
}
|
||||
/// Biome facts at a position for finalizeSpawn and variant rules.
|
||||
@@ -365,6 +374,8 @@ impl Game<'_> {
|
||||
mob_griefing: self.ui.rules.bool("mob_griefing"),
|
||||
end: self.dim == Dim::End,
|
||||
world_seed: self.level.seed,
|
||||
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
|
||||
teams: self.mob_teams(),
|
||||
difficulty: self.local_difficulty(
|
||||
self.player
|
||||
.as_ref()
|
||||
@@ -445,6 +456,7 @@ impl Game<'_> {
|
||||
{
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
let mut scratch = self.world.random.clone();
|
||||
let mut pushes = Vec::new();
|
||||
mobs.retain_mut(|m| {
|
||||
if !w
|
||||
.world
|
||||
@@ -452,13 +464,18 @@ impl Game<'_> {
|
||||
{
|
||||
return !m.hostile() || m.persistent;
|
||||
}
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
let keep = m.tick(&w, &mut scratch, &mut events);
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
if !keep && !m.alive() && !m.removed {
|
||||
dead.push(m.clone());
|
||||
}
|
||||
keep
|
||||
});
|
||||
push_apart(&mut mobs);
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
}
|
||||
self.mobs.append(&mut mobs);
|
||||
self.sync_riders();
|
||||
@@ -513,6 +530,10 @@ impl Game<'_> {
|
||||
self.villager_murdered(m, by_player);
|
||||
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
self.drop_death_loot(&mut dying, by_player, consumed, pos);
|
||||
if m.species() == Species::CopperGolem {
|
||||
// CopperGolem.dropEquipment: the preserved equipment too.
|
||||
self.golem_drop_equipment(&mut dying);
|
||||
}
|
||||
if m.species() == Species::SulfurCube {
|
||||
self.split_sulfur_cube(m);
|
||||
}
|
||||
@@ -627,6 +648,17 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{name}"), Some(at), volume, pitch)
|
||||
}
|
||||
MobEvent::LevelEventSound {
|
||||
sound,
|
||||
at,
|
||||
volume,
|
||||
spread,
|
||||
} => {
|
||||
let r = &mut self.world.random;
|
||||
let pitch = (r.next_float() - r.next_float()) * spread + 1.0;
|
||||
self.audio
|
||||
.play(&format!("minecraft:{sound}"), Some(at), volume, pitch)
|
||||
}
|
||||
MobEvent::SoundId(name, at, volume, pitch) => {
|
||||
self.audio.play(&name, Some(at), volume, pitch)
|
||||
}
|
||||
@@ -667,18 +699,21 @@ impl Game<'_> {
|
||||
MobEvent::Shoot(..) => {}
|
||||
MobEvent::Explode(at, radius) => {
|
||||
// The exploding mob causes the damage (Creeper.explodeCreeper).
|
||||
if let Some(id) = self
|
||||
let source_mob = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0
|
||||
})
|
||||
.map(|m| m.id)
|
||||
.next()
|
||||
{
|
||||
.next();
|
||||
if let Some(id) = source_mob {
|
||||
self.note_attacker("minecraft:explosion", id);
|
||||
}
|
||||
self.explode(at, radius)?
|
||||
self.combat.explosion_source = source_mob;
|
||||
let result = self.explode(at, radius);
|
||||
self.combat.explosion_source = None;
|
||||
result?
|
||||
}
|
||||
MobEvent::AttackMob {
|
||||
target,
|
||||
@@ -729,6 +764,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
},
|
||||
MobEvent::Gift { target, item } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target)
|
||||
&& m.saddle_item().is_none()
|
||||
{
|
||||
m.set_saddle(Some(ItemStack::new(item, 1)));
|
||||
}
|
||||
}
|
||||
MobEvent::HurtSelf { mob, kind, amount } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.damage(amount, horizon_client::mobs::Damage::of(kind));
|
||||
@@ -792,11 +834,12 @@ impl Game<'_> {
|
||||
let old = self.world.block(pos[0], pos[1], pos[2]);
|
||||
self.destroy_particles(pos, old);
|
||||
if drop {
|
||||
let drops = self.res.items.block_drops(
|
||||
let drops = self.res.items.block_drops_in(
|
||||
self.res.assets.registry,
|
||||
old,
|
||||
None,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for d in drops {
|
||||
self.pop_resource(pos, d);
|
||||
@@ -1701,6 +1744,10 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
if self.interact_copper_golem(index, &item) {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
// AbstractHorse.mobInteract: feed, equip or ride.
|
||||
if self.interact_mount(index, &item) {
|
||||
self.swing_arm();
|
||||
@@ -2384,6 +2431,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
|
||||
K::InWall => "minecraft:in_wall",
|
||||
K::Thorns => "minecraft:thorns",
|
||||
K::SonicBoom => "minecraft:sonic_boom",
|
||||
K::OutOfWorld => "minecraft:out_of_world",
|
||||
}
|
||||
}
|
||||
/// A Horizon item stack as a loot stack (id, count, damage, enchantments).
|
||||
@@ -2421,42 +2469,6 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack {
|
||||
}
|
||||
item
|
||||
}
|
||||
/// Entity.push between overlapping mobs (LivingEntity.pushEntities).
|
||||
fn push_apart(mobs: &mut [Mob]) {
|
||||
let n = mobs.len();
|
||||
for i in 0..n {
|
||||
if !mobs[i].alive() {
|
||||
continue;
|
||||
}
|
||||
let bi = mobs[i].bounds();
|
||||
for j in (i + 1)..n {
|
||||
if !mobs[j].alive() || !bi.intersects(mobs[j].bounds()) {
|
||||
continue;
|
||||
}
|
||||
// A rider and its vehicle do not push each other.
|
||||
if mobs[i].extra.mount == Some(mobs[j].id) || mobs[j].extra.mount == Some(mobs[i].id) {
|
||||
continue;
|
||||
}
|
||||
let (dx, dz) = (
|
||||
mobs[j].position.x - mobs[i].position.x,
|
||||
mobs[j].position.z - mobs[i].position.z,
|
||||
);
|
||||
let mut dd = dx.abs().max(dz.abs());
|
||||
if dd >= 0.01 {
|
||||
dd = dd.sqrt();
|
||||
let (mut xa, mut za) = (dx / dd, dz / dd);
|
||||
let inv = (1.0 / dd).min(1.0);
|
||||
xa *= inv * 0.05;
|
||||
za *= inv * 0.05;
|
||||
mobs[i].velocity.x -= xa;
|
||||
mobs[i].velocity.z -= za;
|
||||
mobs[j].velocity.x += xa;
|
||||
mobs[j].velocity.z += za;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The rest of `NetherPortalBlock.randomTick` after a won roll: with a
|
||||
/// player close enough for spawning, a zombified piglin spawns on the block
|
||||
|
||||
@@ -13,6 +13,7 @@ use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
gamerules::Value as RuleValue,
|
||||
item_data::{canon_stack, parse_stack},
|
||||
items::ItemStack,
|
||||
mobs::{Mob, Species},
|
||||
projectiles::ProjectileKind,
|
||||
world::World,
|
||||
@@ -179,14 +180,7 @@ impl Game<'_> {
|
||||
);
|
||||
let slot = item[3].as_u64().unwrap_or(0) as usize;
|
||||
let stack = parse_stack(item[4].as_str().unwrap_or("-"))?;
|
||||
if let Some(cell) = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_mut(&p)
|
||||
.and_then(|e| e.slots_mut().get_mut(slot))
|
||||
{
|
||||
*cell = stack;
|
||||
}
|
||||
self.fixture_fill(p, slot, stack);
|
||||
}
|
||||
let mut targets = Vec::new();
|
||||
for e in case["entities"].as_array().into_iter().flatten() {
|
||||
@@ -225,7 +219,11 @@ impl Game<'_> {
|
||||
pos[2].as_i64().unwrap_or(0) as i32,
|
||||
);
|
||||
let state = self.world.block(origin.x, origin.y, origin.z);
|
||||
self.dispense_from(origin, state)?;
|
||||
if let Some(op) = case.get("remove") {
|
||||
self.fixture_remove(origin, op)?;
|
||||
} else {
|
||||
self.dispense_from(origin, state)?;
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default();
|
||||
@@ -241,7 +239,11 @@ impl Game<'_> {
|
||||
containers.sort_unstable();
|
||||
for p in containers {
|
||||
let entity = &self.world.block_entities[&p];
|
||||
for (i, slot) in entity.slots().iter().enumerate() {
|
||||
let single = match entity {
|
||||
BlockEntity::Jukebox(j) => std::slice::from_ref(&j.record),
|
||||
_ => entity.slots(),
|
||||
};
|
||||
for (i, slot) in single.iter().enumerate() {
|
||||
if let Some(stack) = slot {
|
||||
out.push(format!(
|
||||
"inv {},{},{} {i} {}",
|
||||
@@ -266,6 +268,112 @@ impl Game<'_> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A stack in a block entity's slot: a container's, a jukebox's record, a
|
||||
/// lectern's book, or the items of a block entity Horizon keeps as saved.
|
||||
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
|
||||
let jukebox =
|
||||
&*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox";
|
||||
match self.world.block_entities.get_mut(&p) {
|
||||
Some(BlockEntity::Jukebox(j)) => j.record = stack,
|
||||
Some(BlockEntity::Lectern(l)) => l.book = stack,
|
||||
Some(e) => {
|
||||
if let Some(cell) = e.slots_mut().get_mut(slot) {
|
||||
*cell = stack;
|
||||
}
|
||||
}
|
||||
None if jukebox => {
|
||||
// JukeboxBlockEntity holding its record (setSongItemWithoutPlaying).
|
||||
self.world.block_entities.insert(
|
||||
p,
|
||||
BlockEntity::Jukebox(horizon_client::containers::Jukebox {
|
||||
record: stack,
|
||||
ticks: 0,
|
||||
playing: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
None => self.fixture_fill_saved(p, slot, stack),
|
||||
}
|
||||
}
|
||||
/// The saved block entity of a campfire, decorated pot, chiseled
|
||||
/// bookshelf or shelf, as a loaded world keeps it.
|
||||
fn fixture_fill_saved(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
|
||||
use horizon_world::nbt::Tag;
|
||||
let name = self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(p.0, p.1, p.2))
|
||||
.name
|
||||
.clone();
|
||||
let id = match name.strip_prefix("minecraft:").unwrap_or(&name) {
|
||||
"campfire" | "soul_campfire" => "minecraft:campfire",
|
||||
"decorated_pot" => "minecraft:decorated_pot",
|
||||
"chiseled_bookshelf" => "minecraft:chiseled_bookshelf",
|
||||
n if n.ends_with("_shelf") => "minecraft:shelf",
|
||||
_ => return,
|
||||
};
|
||||
let Some(chunk) = self.world.chunks.get_mut(&(p.0 >> 4, p.2 >> 4)) else {
|
||||
return;
|
||||
};
|
||||
let chunk = Arc::make_mut(chunk);
|
||||
let saved = Arc::make_mut(chunk.saved.get_or_insert_with(Default::default));
|
||||
let at = |t: &Tag| {
|
||||
t.get("x") == Some(&Tag::Int(p.0))
|
||||
&& t.get("y") == Some(&Tag::Int(p.1))
|
||||
&& t.get("z") == Some(&Tag::Int(p.2))
|
||||
};
|
||||
let index = match saved.block_entities.iter().position(at) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
saved.block_entities.push(Tag::compound([
|
||||
("id", Tag::String(id.into())),
|
||||
("x", Tag::Int(p.0)),
|
||||
("y", Tag::Int(p.1)),
|
||||
("z", Tag::Int(p.2)),
|
||||
]));
|
||||
saved.block_entities.len() - 1
|
||||
}
|
||||
};
|
||||
let Tag::Compound(map) = &mut saved.block_entities[index] else {
|
||||
return;
|
||||
};
|
||||
let Some(stack) = stack else { return };
|
||||
if id == "minecraft:decorated_pot" {
|
||||
map.insert("item".into(), horizon_client::save::item_to_nbt(&stack));
|
||||
return;
|
||||
}
|
||||
let mut item = horizon_client::save::item_to_nbt(&stack);
|
||||
if let Tag::Compound(c) = &mut item {
|
||||
c.insert("Slot".into(), Tag::Byte(slot as i8));
|
||||
}
|
||||
match map
|
||||
.entry("Items".into())
|
||||
.or_insert_with(|| Tag::List(Vec::new()))
|
||||
{
|
||||
Tag::List(list) => list.push(item),
|
||||
other => *other = Tag::List(vec![item]),
|
||||
}
|
||||
}
|
||||
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block.
|
||||
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> {
|
||||
match op["op"].as_str().unwrap_or("") {
|
||||
"set" => {
|
||||
let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32);
|
||||
let flags = op["flags"].as_i64().unwrap_or(3) as i32;
|
||||
self.with_level(|b, level, ticks| b.set_block(level, ticks, origin, state, flags));
|
||||
}
|
||||
"destroy" => {
|
||||
let drop = op["drop"].as_bool().unwrap_or(true);
|
||||
self.with_level(|b, level, ticks| b.destroy_block(level, ticks, origin, drop));
|
||||
}
|
||||
"remove" => {
|
||||
self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false));
|
||||
}
|
||||
other => return Err(format!("unknown removal {other}").into()),
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
|
||||
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
|
||||
fn fixture_target(&mut self, e: &Value) -> Result<Target> {
|
||||
let kind = e["type"].as_str().unwrap_or("minecraft:pig");
|
||||
@@ -391,13 +499,17 @@ impl Game<'_> {
|
||||
let _ = write!(line, " {name}={item}x1");
|
||||
}
|
||||
}
|
||||
let ready = match s {
|
||||
Species::Sheep => Some(!x.sheared && !m.is_baby()),
|
||||
Species::Mooshroom => Some(!m.is_baby()),
|
||||
Species::Bogged => Some(!x.sheared),
|
||||
Species::SnowGolem => Some(!x.sheared),
|
||||
_ => None,
|
||||
};
|
||||
let ready =
|
||||
match s {
|
||||
Species::Sheep => Some(!x.sheared && !m.is_baby()),
|
||||
Species::Mooshroom => Some(!m.is_baby()),
|
||||
Species::Bogged => Some(!x.sheared),
|
||||
Species::SnowGolem => Some(!x.sheared),
|
||||
Species::CopperGolem => Some(self.golem_shearable(
|
||||
self.mobs.iter().position(|o| o.id == id).unwrap_or(0),
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(r) = ready {
|
||||
line.push_str(if r { " ready" } else { " unready" });
|
||||
}
|
||||
@@ -502,6 +614,15 @@ impl Game<'_> {
|
||||
let (p, v) = (b.position, b.velocity);
|
||||
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
|
||||
}
|
||||
for o in &self.orbs {
|
||||
let (p, v) = (o.position, o.velocity);
|
||||
out.push(line(
|
||||
"minecraft:experience_orb",
|
||||
[p.x, p.y, p.z],
|
||||
[v.x, v.y, v.z],
|
||||
"",
|
||||
));
|
||||
}
|
||||
for c in &self.carts {
|
||||
let (p, v) = (c.position, c.velocity);
|
||||
out.push(line(c.kind.id(), [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
|
||||
|
||||
@@ -1706,7 +1706,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Entity.spawnAtLocation(level, stack, offset)`: an item at the entity's
|
||||
/// feet plus the offset, moving as `new ItemEntity` makes it.
|
||||
fn spawn_at_location(&mut self, at: Vec3, y_offset: f64, stack: ItemStack) -> [f64; 3] {
|
||||
pub(super) fn spawn_at_location(
|
||||
&mut self,
|
||||
at: Vec3,
|
||||
y_offset: f64,
|
||||
stack: ItemStack,
|
||||
) -> [f64; 3] {
|
||||
let v = new_item_motion();
|
||||
self.spawn_item(stack, [at.x, at.y + y_offset, at.z], v, 10);
|
||||
v
|
||||
@@ -1842,6 +1847,20 @@ impl Game<'_> {
|
||||
self.spawn_at_location(at, eye, stack);
|
||||
}
|
||||
}
|
||||
// CopperGolem.shear: the antenna's flower drops 1.5 up.
|
||||
Species::CopperGolem if self.golem_shearable(i) => {
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.shear", sound_at, 1.0, 1.0);
|
||||
let antenna = self.mobs[i].saddle_item();
|
||||
let id = self.mobs[i].id;
|
||||
// setItemSlot(EQUIPMENT_SLOT_ANTENNA, EMPTY): an unequip.
|
||||
self.mobs[i].set_saddle(None);
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Mob(id)), None);
|
||||
self.post_game_event("minecraft:unequip", [at.x, at.y, at.z], ctx);
|
||||
if let Some(antenna) = antenna {
|
||||
self.spawn_at_location(at, 1.5, antenna);
|
||||
}
|
||||
}
|
||||
Species::Mooshroom if !m.is_baby() => {
|
||||
let variant = if m.extra.variant == 1 { "brown" } else { "red" };
|
||||
let height = f64::from(m.height());
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
//! exit portal, the egg and the next gateway; and its rendering and boss bar.
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
hud::HudBatch,
|
||||
hud_layout, hud_overlays,
|
||||
mesher::Vertex,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
@@ -1839,30 +1841,30 @@ impl Game<'_> {
|
||||
});
|
||||
self.breath_clouds.append(&mut clouds);
|
||||
}
|
||||
/// The boss bar (`BossHealthOverlay`): name and the pink progress bar.
|
||||
pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) {
|
||||
let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End);
|
||||
let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
|
||||
self.draw_raid_bar(batch, y);
|
||||
let Some(d) = dragon else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let x = (batch.width / 2.0 - 91.0).floor();
|
||||
let y = 12.0;
|
||||
batch.sprite(atlas, "gui/sprites/boss_bar/pink_background", x, y);
|
||||
let progress = (d.health / MAX_HEALTH).clamp(0.0, 1.0);
|
||||
batch.sprite_part(atlas, "gui/sprites/boss_bar/pink_progress", x, y, progress);
|
||||
let name = self.translate("entity.minecraft.ender_dragon", "Ender Dragon");
|
||||
let w = HudBatch::text_width(atlas, &name);
|
||||
batch.text(
|
||||
atlas,
|
||||
&name,
|
||||
(batch.width / 2.0 - w / 2.0).floor(),
|
||||
y - 9.0,
|
||||
rgba(255, 255, 255, 255),
|
||||
true,
|
||||
/// `BossHealthOverlay`: the dragon's pink bar, then the withers', the
|
||||
/// raids' and the custom bars, in that order.
|
||||
pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) {
|
||||
let mut bars = Vec::new();
|
||||
if let Some(d) = self.dragon.as_ref().filter(|_| self.dim == Dim::End) {
|
||||
bars.push(hud_overlays::BossBar {
|
||||
name: Text::literal(
|
||||
self.translate("entity.minecraft.ender_dragon", "Ender Dragon"),
|
||||
),
|
||||
progress: (d.health / MAX_HEALTH).clamp(0.0, 1.0),
|
||||
color: 0,
|
||||
overlay: 0,
|
||||
});
|
||||
}
|
||||
self.wither_bars(&mut bars);
|
||||
self.raid_bars(&mut bars);
|
||||
self.custom_bossbars(&mut bars);
|
||||
let draws = hud_overlays::boss_overlay(
|
||||
batch.width as i32,
|
||||
batch.height as i32,
|
||||
&bars,
|
||||
&self.res.atlas.font,
|
||||
);
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
/// `music.dragon` while the boss bar plays music.
|
||||
pub(super) fn boss_music(&self) -> bool {
|
||||
|
||||
@@ -37,10 +37,6 @@ pub(super) struct EndState {
|
||||
job: Option<GatewayJob>,
|
||||
/// Ticks until the player can use a gateway again (TheEndGatewayBlockEntity cooldown).
|
||||
gateway_cooldown: u32,
|
||||
/// End portal and gateway blocks per loaded chunk (true = gateway), for rendering.
|
||||
portals: HashMap<(i32, i32), Vec<([i32; 3], bool)>>,
|
||||
/// Chunks left to scan for portal blocks in the current round.
|
||||
scan: Vec<(i32, i32)>,
|
||||
/// The Overworld generator, for stronghold positions (ServerLevel.findNearestMapStructure).
|
||||
locator: std::sync::Mutex<Option<Arc<VanillaTerrain>>>,
|
||||
/// Thrown eyes of ender in flight.
|
||||
@@ -132,11 +128,6 @@ impl EyeOfEnder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Chunks scanned for portal blocks per tick.
|
||||
const SCAN_PER_TICK: usize = 6;
|
||||
/// Radius (chunks) around the player in which portal blocks are rendered.
|
||||
const PORTAL_RADIUS: i32 = 10;
|
||||
|
||||
impl Game<'_> {
|
||||
/// The environment attributes of the current dimension.
|
||||
pub(super) fn dim_environment(&self) -> &Environment {
|
||||
@@ -295,7 +286,6 @@ impl Game<'_> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
self.rescan_portals_around(c, 1);
|
||||
// Global LevelEvent 1038: END_PORTAL_SPAWN.
|
||||
self.audio
|
||||
.play("minecraft:block.end_portal.spawn", None, 1.0, 1.0);
|
||||
@@ -350,7 +340,6 @@ impl Game<'_> {
|
||||
self.tick_fight();
|
||||
self.tick_dragon_fireballs();
|
||||
}
|
||||
self.scan_portals();
|
||||
self.tick_eyes();
|
||||
if self.dim == Dim::End {
|
||||
self.end.flash.tick(self.world.game_time);
|
||||
@@ -645,7 +634,6 @@ impl Game<'_> {
|
||||
let id = registry.resolve(&state)?;
|
||||
self.level_set([origin[0] + d[0], origin[1] + 2, origin[2] + d[1]], id)?;
|
||||
}
|
||||
self.rescan_portals_around(origin, 4);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -669,7 +657,6 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.rescan_portals_around(origin, 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -887,214 +874,10 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scan a few loaded chunks per tick for End portal and gateway blocks.
|
||||
fn scan_portals(&mut self) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (pcx, pcz) = (
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
);
|
||||
let chunks = &self.world.chunks;
|
||||
self.end.portals.retain(|k, _| chunks.contains_key(k));
|
||||
if self.end.scan.is_empty() {
|
||||
let mut queue: Vec<(i32, i32)> = chunks
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|&(x, z)| {
|
||||
(x - pcx).abs() <= PORTAL_RADIUS && (z - pcz).abs() <= PORTAL_RADIUS
|
||||
})
|
||||
.collect();
|
||||
// Nearest last: they are popped first.
|
||||
queue.sort_by_key(|&(x, z)| std::cmp::Reverse((x - pcx).pow(2) + (z - pcz).pow(2)));
|
||||
self.end.scan = queue;
|
||||
}
|
||||
for _ in 0..SCAN_PER_TICK {
|
||||
let Some((cx, cz)) = self.end.scan.pop() else {
|
||||
break;
|
||||
};
|
||||
self.scan_portal_chunk(cx, cz);
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_portal_chunk(&mut self, cx: i32, cz: i32) {
|
||||
let registry = self.res.assets.registry;
|
||||
let (Some(portal), Some(gateway)) = (
|
||||
registry.default_state("minecraft:end_portal"),
|
||||
registry.default_state("minecraft:end_gateway"),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let (portal, gateway) = (portal.0 as u16, gateway.0 as u16);
|
||||
let Some(chunk) = self.world.chunks.get(&(cx, cz)) else {
|
||||
self.end.portals.remove(&(cx, cz));
|
||||
return;
|
||||
};
|
||||
let mut found = Vec::new();
|
||||
for (s, section) in chunk.sections.iter().enumerate() {
|
||||
if !section
|
||||
.blocks
|
||||
.maybe_has(|v| v == u32::from(portal) || v == u32::from(gateway))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut blocks = Box::new([0u16; 4096]);
|
||||
section.unpack(&mut blocks);
|
||||
for (i, &b) in blocks.iter().enumerate() {
|
||||
if b == portal || b == gateway {
|
||||
let y = horizon_client::chunk::MIN_Y + s as i32 * 16 + (i >> 8) as i32;
|
||||
found.push((
|
||||
[
|
||||
cx * 16 + (i & 15) as i32,
|
||||
y,
|
||||
cz * 16 + ((i >> 4) & 15) as i32,
|
||||
],
|
||||
b == gateway,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if found.is_empty() {
|
||||
self.end.portals.remove(&(cx, cz));
|
||||
} else {
|
||||
self.end.portals.insert((cx, cz), found);
|
||||
}
|
||||
}
|
||||
|
||||
fn rescan_portals_around(&mut self, p: [i32; 3], r: i32) {
|
||||
for cz in (p[2] - r) >> 4..=(p[2] + r) >> 4 {
|
||||
for cx in (p[0] - r) >> 4..=(p[0] + r) >> 4 {
|
||||
self.scan_portal_chunk(cx, cz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End portal and gateway surfaces (TheEndPortalRenderer: the starfield
|
||||
/// approximated by end_portal.png in world space, unanimated) and the End
|
||||
/// crystals on the spikes, as camera-relative entity geometry.
|
||||
/// The End crystals on the spikes and thrown eyes of ender, as
|
||||
/// camera-relative entity geometry (End portals and gateways are block
|
||||
/// entities).
|
||||
pub(super) fn end_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
|
||||
let atlas = &self.res.atlas;
|
||||
if let Some(r) = atlas.sprites.get("entity/end_portal/end_portal").copied() {
|
||||
let full = (15 * 16) | ((15 * 16) << 8);
|
||||
// Each block shows a quarter of the texture so neighbours join up.
|
||||
let quarter = |a: i32, b: i32| {
|
||||
let (fa, fb) = (a.rem_euclid(4) as f32 / 4.0, b.rem_euclid(4) as f32 / 4.0);
|
||||
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
|
||||
(
|
||||
r.u0 + du * fa,
|
||||
r.u0 + du * (fa + 0.25),
|
||||
r.v0 + dv * fb,
|
||||
r.v0 + dv * (fb + 0.25),
|
||||
)
|
||||
};
|
||||
for blocks in self.end.portals.values() {
|
||||
for &(p, gateway) in blocks {
|
||||
let base = glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))
|
||||
- camera;
|
||||
if base.length_squared() > 160.0 * 160.0 {
|
||||
continue;
|
||||
}
|
||||
let b = base.as_vec3();
|
||||
// Portal: top face at 12/16 and bottom at 6/16; gateway: the whole cube.
|
||||
let (y0, y1) = if gateway { (0.0, 1.0) } else { (0.375, 0.75) };
|
||||
let color = if gateway { 0xFFE0_E0A0 } else { 0xFFD0_E070 };
|
||||
let mut quad =
|
||||
|corners: [glam::Vec3; 4], (u0, u1, v0, v1): (f32, f32, f32, f32)| {
|
||||
let uv = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
|
||||
for (c, uv) in corners.into_iter().zip(uv) {
|
||||
out.push(Vertex {
|
||||
pos: (b + c).to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
color,
|
||||
light: full,
|
||||
});
|
||||
}
|
||||
};
|
||||
let v = glam::Vec3::new;
|
||||
let open = |d: [i32; 3]| {
|
||||
let n = [p[0] + d[0], p[1] + d[1], p[2] + d[2]];
|
||||
!self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(n[0], n[1], n[2]))
|
||||
.solid_render
|
||||
};
|
||||
let uv_xz = quarter(p[0], p[2]);
|
||||
if !gateway || open([0, 1, 0]) {
|
||||
quad(
|
||||
[
|
||||
v(0.0, y1, 0.0),
|
||||
v(1.0, y1, 0.0),
|
||||
v(1.0, y1, 1.0),
|
||||
v(0.0, y1, 1.0),
|
||||
],
|
||||
uv_xz,
|
||||
);
|
||||
}
|
||||
if !gateway || open([0, -1, 0]) {
|
||||
quad(
|
||||
[
|
||||
v(0.0, y0, 0.0),
|
||||
v(1.0, y0, 0.0),
|
||||
v(1.0, y0, 1.0),
|
||||
v(0.0, y0, 1.0),
|
||||
],
|
||||
uv_xz,
|
||||
);
|
||||
}
|
||||
if gateway {
|
||||
let uv_x = quarter(p[2], p[1]);
|
||||
let uv_z = quarter(p[0], p[1]);
|
||||
if open([-1, 0, 0]) {
|
||||
quad(
|
||||
[
|
||||
v(0.0, 0.0, 0.0),
|
||||
v(0.0, 0.0, 1.0),
|
||||
v(0.0, 1.0, 1.0),
|
||||
v(0.0, 1.0, 0.0),
|
||||
],
|
||||
uv_x,
|
||||
);
|
||||
}
|
||||
if open([1, 0, 0]) {
|
||||
quad(
|
||||
[
|
||||
v(1.0, 0.0, 0.0),
|
||||
v(1.0, 0.0, 1.0),
|
||||
v(1.0, 1.0, 1.0),
|
||||
v(1.0, 1.0, 0.0),
|
||||
],
|
||||
uv_x,
|
||||
);
|
||||
}
|
||||
if open([0, 0, -1]) {
|
||||
quad(
|
||||
[
|
||||
v(0.0, 0.0, 0.0),
|
||||
v(1.0, 0.0, 0.0),
|
||||
v(1.0, 1.0, 0.0),
|
||||
v(0.0, 1.0, 0.0),
|
||||
],
|
||||
uv_z,
|
||||
);
|
||||
}
|
||||
if open([0, 0, 1]) {
|
||||
quad(
|
||||
[
|
||||
v(0.0, 0.0, 1.0),
|
||||
v(1.0, 0.0, 1.0),
|
||||
v(1.0, 1.0, 1.0),
|
||||
v(0.0, 1.0, 1.0),
|
||||
],
|
||||
uv_z,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.dim == Dim::End {
|
||||
self.end_crystal_geometry(camera, out);
|
||||
}
|
||||
|
||||
@@ -191,6 +191,15 @@ impl Game<'_> {
|
||||
[d[0] / l, d[1] / l, d[2] / l]
|
||||
}
|
||||
};
|
||||
// `source.doTeamsAllowDamage(entity)`: the exploding mob spares its
|
||||
// team mates when its team has no friendly fire (they are still pushed).
|
||||
let exploding = self.combat.explosion_source;
|
||||
let teams_allow = |g: &Self, victim: Option<&horizon_client::scoreboard::Team>| {
|
||||
exploding.is_none_or(|id| {
|
||||
horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim)
|
||||
})
|
||||
};
|
||||
let player_hurtable = teams_allow(self, self.player_team());
|
||||
// Player.
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let feet = [p.position.x, p.position.y, p.position.z];
|
||||
@@ -217,7 +226,7 @@ impl Game<'_> {
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:explosion")
|
||||
{
|
||||
// Creative players are invulnerable to explosions.
|
||||
if !creative {
|
||||
if !creative && player_hurtable {
|
||||
hurt = p
|
||||
.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false);
|
||||
@@ -236,6 +245,7 @@ impl Game<'_> {
|
||||
// Mobs.
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
for m in mobs.iter_mut().filter(|m| m.alive()) {
|
||||
let hurtable = teams_allow(self, self.mob_team(m.id));
|
||||
let feet = [m.position.x, m.position.y, m.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist > 1.0 {
|
||||
@@ -253,7 +263,7 @@ impl Game<'_> {
|
||||
attacker: None,
|
||||
from: Some(center),
|
||||
};
|
||||
if !m.damage(damage(dist, exposure), source) {
|
||||
if hurtable && !m.damage(damage(dist, exposure), source) {
|
||||
continue;
|
||||
}
|
||||
let dir = direction(eye);
|
||||
@@ -390,17 +400,30 @@ impl Game<'_> {
|
||||
}
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
let is_tnt = &*name == "minecraft:tnt";
|
||||
// Block.onExplosionHit: the drops copy from the block entity, which
|
||||
// then spills its contents as the block turns to air.
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
|
||||
let custom = self.world.block_names.get(&key).cloned();
|
||||
self.pending.record(pos, &entity, &name, custom);
|
||||
} else if let Some(tag) = super::spill::saved_entity(&self.world, pos) {
|
||||
self.pending.record_saved(pos, &tag);
|
||||
}
|
||||
if !is_tnt {
|
||||
let drops = self.res.items.block_drops(
|
||||
let dynamic = self.pending.dynamic(pos);
|
||||
let drops = self.res.items.block_drops_full(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&dynamic,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for stack in drops {
|
||||
for mut stack in drops {
|
||||
if &*stack.item == "minecraft:air" || stack.count == 0 {
|
||||
continue;
|
||||
}
|
||||
self.pending.attach(pos, &mut stack);
|
||||
// survives_explosion / explosion_decay: 1 / radius per stack.
|
||||
if interaction == BlockInteraction::DestroyWithDecay
|
||||
&& self.world.random.next_float() > 1.0 / radius
|
||||
@@ -410,17 +433,8 @@ impl Game<'_> {
|
||||
add_or_append_stack(stacks, stack, pos);
|
||||
}
|
||||
}
|
||||
let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
|
||||
let name = self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(pos[0], pos[1], pos[2]))
|
||||
.name
|
||||
.clone();
|
||||
self.pending.clear(pos);
|
||||
self.level_set(pos, self.world.air)?;
|
||||
if let Some(entity) = contents {
|
||||
self.release_contents(pos, entity, &name);
|
||||
}
|
||||
if is_tnt {
|
||||
self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use horizon_client::{
|
||||
BobState, CameraFluid, FovPlayer, HurtBob, UseItem, bob_matrix, field_of_view_modifier,
|
||||
},
|
||||
fog::{FogType, fog_type},
|
||||
hud::{HudBatch, rgba},
|
||||
hud::HudBatch,
|
||||
hud_layout, hud_overlays,
|
||||
};
|
||||
|
||||
/// `Abilities.walkingSpeed`.
|
||||
@@ -145,26 +146,20 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:item.spyglass.stop_using", at, 1.0, 1.0);
|
||||
}
|
||||
/// `Hud.extractCameraOverlays`: the scope, its size easing from 0.5 to
|
||||
/// 1.125 at half a step per tick of frame time.
|
||||
/// `Hud.extractCameraOverlays`: the spyglass scope, its size easing
|
||||
/// towards 1.125 by half the frame's game ticks and reset to 0.5 while
|
||||
/// not scoping in first person.
|
||||
pub(super) fn draw_spyglass(&mut self, batch: &mut HudBatch) {
|
||||
self.scope_scale += 0.5 * self.frame_ticks * (1.125 - self.scope_scale);
|
||||
if !self.camera_type.first_person() {
|
||||
return;
|
||||
}
|
||||
if !self.scoping() {
|
||||
self.scope_scale = 0.5;
|
||||
return;
|
||||
}
|
||||
self.scope_scale += (1.125 - self.scope_scale) * (0.5 * self.frame_ticks).min(1.0);
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let src = w.min(h);
|
||||
let ratio = (w / src).min(h / src) * self.scope_scale;
|
||||
let (sw, sh) = ((src * ratio).floor(), (src * ratio).floor());
|
||||
let (left, top) = (((w - sw) / 2.0).floor(), ((h - sh) / 2.0).floor());
|
||||
let (right, bottom) = (left + sw, top + sh);
|
||||
batch.sprite_scaled(atlas, "misc/spyglass_scope", left, top, sw, sh, u32::MAX);
|
||||
let black = rgba(0, 0, 0, 255);
|
||||
batch.fill(atlas, 0.0, bottom, w, h - bottom, black);
|
||||
batch.fill(atlas, 0.0, 0.0, w, top, black);
|
||||
batch.fill(atlas, 0.0, top, left, bottom - top, black);
|
||||
batch.fill(atlas, right, top, w - right, bottom - top, black);
|
||||
let draws =
|
||||
hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale);
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,11 +94,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
fn rebuild_store(&mut self) {
|
||||
let packs: Vec<&DataPack> = self
|
||||
.fns
|
||||
.enabled
|
||||
.iter()
|
||||
.filter_map(|id| self.fns.packs.iter().find(|p| &p.id == id))
|
||||
// The built-in pack first (lowest priority), unless disabled.
|
||||
let vanilla = DataPack::builtin(&self.options.resources);
|
||||
let packs: Vec<&DataPack> = (!self.cmds.vanilla_disabled)
|
||||
.then_some(&vanilla)
|
||||
.into_iter()
|
||||
.chain(
|
||||
self.fns
|
||||
.enabled
|
||||
.iter()
|
||||
.filter_map(|id| self.fns.packs.iter().find(|p| &p.id == id)),
|
||||
)
|
||||
.collect();
|
||||
let store = DataStore::load(&packs);
|
||||
for (id, e) in &store.errors {
|
||||
@@ -298,9 +304,10 @@ impl Game<'_> {
|
||||
pub(in crate::game) fn functions_named(&mut self, name: &str) -> R<Vec<Function>> {
|
||||
self.ensure_datapacks();
|
||||
match name.strip_prefix('#') {
|
||||
// ServerFunctionLibrary.getTag: an unknown tag is empty.
|
||||
Some(tag) => {
|
||||
if !self.fns.store.function_tags.contains_key(tag) {
|
||||
return Err(err("arguments.function.tag.unknown", &[&tag]));
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(self
|
||||
.fns
|
||||
@@ -347,7 +354,8 @@ impl Game<'_> {
|
||||
};
|
||||
let functions = self.functions_named(&name)?;
|
||||
if functions.is_empty() {
|
||||
return Err(err("commands.function.scheduled.no_functions", &[&name]));
|
||||
let id = name.trim_start_matches('#');
|
||||
return Err(err("commands.function.scheduled.no_functions", &[&id]));
|
||||
}
|
||||
let args = if ctx.has("with") {
|
||||
let r = self.data_ref_named(ctx, 0, "source")?;
|
||||
@@ -470,12 +478,8 @@ impl Game<'_> {
|
||||
let replace = !ctx.has("append");
|
||||
let tick_time = self.world.game_time + i64::from(time);
|
||||
let schedule_id = match name.strip_prefix('#') {
|
||||
Some(tag) => {
|
||||
if !self.fns.store.function_tags.contains_key(tag) {
|
||||
return Err(err("arguments.function.tag.unknown", &[&tag]));
|
||||
}
|
||||
name.clone()
|
||||
}
|
||||
// An unknown tag is empty, and scheduling it is allowed.
|
||||
Some(_) => name.clone(),
|
||||
None => {
|
||||
let Some(f) = self.fns.store.functions.get(&name) else {
|
||||
return Err(err("arguments.function.unknown", &[&name]));
|
||||
@@ -519,11 +523,14 @@ impl Game<'_> {
|
||||
self.sync_function_registries();
|
||||
Ok((tick_time.rem_euclid(i64::from(i32::MAX))) as i32)
|
||||
}
|
||||
/// ReloadCommand: the message, then the (asynchronous) reload; returns 0.
|
||||
pub(super) fn cmd_reload(&mut self) -> R<i32> {
|
||||
self.reload_datapacks(true);
|
||||
self.feedback(Text::translate("commands.reload.success", &[]));
|
||||
Ok(1)
|
||||
self.reload_datapacks(true);
|
||||
Ok(0)
|
||||
}
|
||||
/// `PackLocationInfo.createChatLink`: the id decorated with its source
|
||||
/// (`pack.nameAndSource`, grey) in brackets, green when enabled.
|
||||
fn pack_link(&self, id: &str, enabled: bool) -> Text {
|
||||
let hint = if enabled { "disable" } else { "enable" };
|
||||
let style = text::Style {
|
||||
@@ -541,7 +548,27 @@ impl Game<'_> {
|
||||
hover: Some(Box::new(Text::literal(format!("{id}\n{description}")))),
|
||||
..style
|
||||
};
|
||||
bracketed(Text::literal(id).with_style(&style))
|
||||
let source = if id == "vanilla" {
|
||||
"pack.source.builtin"
|
||||
} else if FEATURE_PACKS.iter().any(|(p, _)| *p == id) {
|
||||
"pack.source.feature"
|
||||
} else {
|
||||
"pack.source.world"
|
||||
};
|
||||
let name = Text::translate(
|
||||
"pack.nameAndSource",
|
||||
&[Text::literal(id), Text::translate(source, &[])],
|
||||
)
|
||||
.with_color(text::GRAY);
|
||||
bracketed(name).with_style(&style)
|
||||
}
|
||||
/// The selected packs, lowest priority first.
|
||||
fn selected_packs(&self) -> Vec<String> {
|
||||
let vanilla = (!self.cmds.vanilla_disabled).then(|| "vanilla".to_owned());
|
||||
vanilla
|
||||
.into_iter()
|
||||
.chain(self.fns.enabled.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
pub(super) fn cmd_datapack(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.ensure_datapacks();
|
||||
@@ -549,34 +576,37 @@ impl Game<'_> {
|
||||
Some(Arg::Str(n)) => Some(n.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let enabled_ids: Vec<String> = std::iter::once("vanilla".to_owned())
|
||||
.chain(self.fns.enabled.iter().cloned())
|
||||
.collect();
|
||||
let available: Vec<String> = self
|
||||
.fns
|
||||
.packs
|
||||
.iter()
|
||||
.map(|p| p.id.clone())
|
||||
.filter(|p| !enabled_ids.contains(p))
|
||||
let selected = self.selected_packs();
|
||||
// Feature packs need features this world lacks: never available.
|
||||
let available: Vec<String> = std::iter::once("vanilla".to_owned())
|
||||
.chain(self.fns.packs.iter().map(|p| p.id.clone()))
|
||||
.filter(|p| !selected.contains(p))
|
||||
.collect();
|
||||
let known = |g: &Self, n: &str| {
|
||||
n == "vanilla"
|
||||
|| FEATURE_PACKS.iter().any(|(p, _)| *p == n)
|
||||
|| g.fns.packs.iter().any(|p| p.id == n)
|
||||
};
|
||||
match id {
|
||||
"datapack.list" => {
|
||||
let want_enabled = ctx.has("enabled") || (!ctx.has("available"));
|
||||
let want_available = ctx.has("available") || (!ctx.has("enabled"));
|
||||
let mut total = 0;
|
||||
if want_enabled {
|
||||
let links: Vec<Text> = enabled_ids
|
||||
.iter()
|
||||
.map(|p| self.pack_link(p, true))
|
||||
.collect();
|
||||
total += links.len();
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.list.enabled.success",
|
||||
&[
|
||||
Text::literal(links.len().to_string()),
|
||||
horizon_client::scoreboard_cmd::format_list(links),
|
||||
],
|
||||
));
|
||||
if selected.is_empty() {
|
||||
self.feedback(Text::translate("commands.datapack.list.enabled.none", &[]));
|
||||
} else {
|
||||
let links: Vec<Text> =
|
||||
selected.iter().map(|p| self.pack_link(p, true)).collect();
|
||||
total += links.len();
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.list.enabled.success",
|
||||
&[
|
||||
Text::literal(links.len().to_string()),
|
||||
horizon_client::scoreboard_cmd::format_list(links),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
if want_available {
|
||||
if available.is_empty() {
|
||||
@@ -601,57 +631,71 @@ impl Game<'_> {
|
||||
}
|
||||
"datapack.enable" => {
|
||||
let name = name.unwrap_or_default();
|
||||
if !self.fns.packs.iter().any(|p| p.id == name) && name != "vanilla" {
|
||||
if !known(self, &name) {
|
||||
return Err(err("commands.datapack.unknown", &[&name]));
|
||||
}
|
||||
if enabled_ids.contains(&name) {
|
||||
if selected.contains(&name) {
|
||||
return Err(err("commands.datapack.enable.failed", &[&name]));
|
||||
}
|
||||
let existing = match ctx.get("existing") {
|
||||
Some(Arg::Str(e)) => Some(e.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let position = if ctx.has("first") {
|
||||
0
|
||||
} else if let Some(e) = &existing {
|
||||
let Some(i) = self.fns.enabled.iter().position(|p| p == e) else {
|
||||
return Err(err("commands.datapack.unknown", &[e]));
|
||||
};
|
||||
if ctx.has("before") { i } else { i + 1 }
|
||||
if let Some((_, flag)) = FEATURE_PACKS.iter().find(|(p, _)| *p == name) {
|
||||
return Err(err(
|
||||
"commands.datapack.enable.failed.no_flags",
|
||||
&[&name, flag],
|
||||
));
|
||||
}
|
||||
if name == "vanilla" {
|
||||
self.cmds.vanilla_disabled = false;
|
||||
} else {
|
||||
self.fns.enabled.len()
|
||||
};
|
||||
self.fns.enabled.insert(position, name.clone());
|
||||
let existing = match ctx.get("existing") {
|
||||
Some(Arg::Str(e)) => Some(e.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let position = if ctx.has("first") {
|
||||
0
|
||||
} else if let Some(e) = &existing {
|
||||
let Some(i) = self.fns.enabled.iter().position(|p| p == e) else {
|
||||
return Err(err("commands.datapack.unknown", &[e]));
|
||||
};
|
||||
if ctx.has("before") { i } else { i + 1 }
|
||||
} else {
|
||||
self.fns.enabled.len()
|
||||
};
|
||||
self.fns.enabled.insert(position, name.clone());
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.modify.enable",
|
||||
&[self.pack_link(&name, true)],
|
||||
));
|
||||
self.apply_pack_change();
|
||||
Ok(self.fns.enabled.len() as i32)
|
||||
Ok(self.selected_packs().len() as i32)
|
||||
}
|
||||
_ => {
|
||||
let name = name.unwrap_or_default();
|
||||
if !self.fns.packs.iter().any(|p| p.id == name) && name != "vanilla" {
|
||||
if !known(self, &name) {
|
||||
return Err(err("commands.datapack.unknown", &[&name]));
|
||||
}
|
||||
let Some(i) = self.fns.enabled.iter().position(|p| p == &name) else {
|
||||
if !selected.contains(&name) {
|
||||
return Err(err("commands.datapack.disable.failed", &[&name]));
|
||||
};
|
||||
self.fns.enabled.remove(i);
|
||||
}
|
||||
if name == "vanilla" {
|
||||
self.cmds.vanilla_disabled = true;
|
||||
} else {
|
||||
self.fns.enabled.retain(|p| p != &name);
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.modify.disable",
|
||||
&[self.pack_link(&name, false)],
|
||||
&[self.pack_link(&name, true)],
|
||||
));
|
||||
self.apply_pack_change();
|
||||
Ok(self.fns.enabled.len() as i32)
|
||||
Ok(self.selected_packs().len() as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ReloadCommand.reloadPacks`: no message of its own.
|
||||
fn apply_pack_change(&mut self) {
|
||||
self.save_datapack_settings();
|
||||
self.rebuild_store();
|
||||
self.fns.load_pending = true;
|
||||
self.feedback(Text::translate("commands.reload.success", &[]));
|
||||
}
|
||||
|
||||
// ---- predicates -------------------------------------------------------------------
|
||||
@@ -667,3 +711,11 @@ impl Game<'_> {
|
||||
Ok(self.conditions_hold(&json, view.as_ref(), source.pos))
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in feature packs and the feature flag each needs (none of them
|
||||
/// enabled in a world created without experiments).
|
||||
const FEATURE_PACKS: &[(&str, &str)] = &[
|
||||
("minecart_improvements", "minecraft:minecart_improvements"),
|
||||
("redstone_experiments", "minecraft:redstone_experiments"),
|
||||
("trade_rebalance", "minecraft:trade_rebalance"),
|
||||
];
|
||||
|
||||
@@ -33,6 +33,11 @@ impl Game<'_> {
|
||||
let was_spectator = self.spectator();
|
||||
self.mode = mode;
|
||||
self.creative = mode == GameMode::Creative;
|
||||
// GameType.updatePlayerAbilities applies at once.
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.invulnerable = mode == GameMode::Creative || mode == GameMode::Spectator;
|
||||
p.may_fly = p.invulnerable;
|
||||
}
|
||||
if mode == GameMode::Spectator {
|
||||
self.mining = None;
|
||||
self.using = None;
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! golem. Players placing the pumpkin and dispensers share it.
|
||||
use super::Game;
|
||||
use horizon_client::Result;
|
||||
use horizon_world::chunk::BlockState;
|
||||
|
||||
impl Game<'_> {
|
||||
fn golem_block(&self, p: [i32; 3]) -> &str {
|
||||
@@ -49,9 +48,20 @@ impl Game<'_> {
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `CarvedPumpkinBlock.canSpawnGolem`.
|
||||
/// `CarvedPumpkinBlock.canSpawnGolem`: a snow or iron golem base, or a
|
||||
/// copper block (`#minecraft:copper`) below.
|
||||
pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool {
|
||||
self.find_golem(head).is_some()
|
||||
self.find_golem(head).is_some() || self.copper_golem_base(head)
|
||||
}
|
||||
/// The copper golem pattern ("^", "#"): a block of `#minecraft:copper` under the head.
|
||||
fn copper_golem_base(&self, head: [i32; 3]) -> bool {
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let name = self.golem_block(below);
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get("minecraft:copper")
|
||||
.is_some_and(|t| t.contains(name))
|
||||
}
|
||||
/// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed.
|
||||
pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> {
|
||||
@@ -71,9 +81,9 @@ impl Game<'_> {
|
||||
self.create_triggered(kind, at, 0.0);
|
||||
self.update_pattern_blocks(&blocks)
|
||||
}
|
||||
/// Whether placing a golem head at `head` completes a snow or iron golem.
|
||||
/// Whether placing a golem head at `head` completes a golem.
|
||||
pub(super) fn completes_golem(&self, head: [i32; 3]) -> bool {
|
||||
self.find_golem(head).is_some()
|
||||
self.find_golem(head).is_some() || self.copper_golem_base(head)
|
||||
}
|
||||
/// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or
|
||||
/// wither has no spawn finalization and draws nothing from the level.
|
||||
@@ -124,57 +134,67 @@ impl Game<'_> {
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
/// A pumpkin on a copper block: the block turns into the matching copper
|
||||
/// chest (facing the pumpkin's way) and a copper golem appears where the
|
||||
/// pumpkin was (`CarvedPumpkinBlock.spawnGolemInWorld` with
|
||||
/// `CopperChestBlock.getFromCopperBlock`).
|
||||
/// The copper golem (`CarvedPumpkinBlock.trySpawnGolem`, after the snow
|
||||
/// and iron golems): both blocks clear, the golem appears where the
|
||||
/// pumpkin was, the copper block becomes the matching copper chest facing
|
||||
/// the pumpkin's way (`replaceCopperBlockWithChest`, flags 2) and the
|
||||
/// golem takes the block's weathering (`CopperGolem.spawn`).
|
||||
fn try_spawn_copper_golem(&mut self, head: [i32; 3]) -> Result<()> {
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let registry = self.res.assets.registry;
|
||||
let name = self.golem_block(below).to_string();
|
||||
let Some(base) = name.strip_prefix("minecraft:") else {
|
||||
return Ok(());
|
||||
};
|
||||
let waxed = base.strip_prefix("waxed_").unwrap_or(base);
|
||||
if !matches!(
|
||||
waxed,
|
||||
"copper_block" | "exposed_copper" | "weathered_copper" | "oxidized_copper"
|
||||
) {
|
||||
if !self.copper_golem_base(head) {
|
||||
return Ok(());
|
||||
}
|
||||
let chest = format!(
|
||||
"minecraft:{}_chest",
|
||||
base.strip_suffix("_block").unwrap_or(base)
|
||||
);
|
||||
let below = [head[0], head[1] - 1, head[2]];
|
||||
let copper = self.world.block(below[0], below[1], below[2]);
|
||||
let pumpkin = self.world.block(head[0], head[1], head[2]);
|
||||
let registry = self.res.assets.registry;
|
||||
let facing = registry
|
||||
.state(pumpkin)
|
||||
.and_then(|s| s.properties.get("facing").cloned())
|
||||
.unwrap_or_else(|| "north".into());
|
||||
let chest_state = BlockState {
|
||||
name: chest.clone(),
|
||||
properties: [
|
||||
("facing".to_string(), facing),
|
||||
("type".to_string(), "single".to_string()),
|
||||
("waterlogged".to_string(), "false".to_string()),
|
||||
]
|
||||
.into(),
|
||||
};
|
||||
let Some(chest_id) = registry
|
||||
.id(&chest_state)
|
||||
.or_else(|| registry.default_state(&chest))
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
self.destroy_particles(head, pumpkin);
|
||||
self.level_set(head, self.world.air)?;
|
||||
self.level_set(below, chest_id)?;
|
||||
// getWeatherStateFromPattern: waxed blocks weather like their unwaxed form.
|
||||
let base = self
|
||||
.golem_block(below)
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_start_matches("waxed_");
|
||||
let weather = ["exposed", "weathered", "oxidized"]
|
||||
.iter()
|
||||
.position(|w| base.starts_with(w))
|
||||
.map_or(0, |i| i as u8 + 1);
|
||||
let cells = [head, below];
|
||||
self.clear_pattern_blocks(&cells)?;
|
||||
let at = [
|
||||
f64::from(head[0]) + 0.5,
|
||||
f64::from(head[1]) + 0.05,
|
||||
f64::from(head[2]) + 0.5,
|
||||
];
|
||||
let _ = self.spawn_mob("minecraft:copper_golem", at, false);
|
||||
Ok(())
|
||||
let id = self.create_triggered("minecraft:copper_golem", at, 0.0);
|
||||
self.update_pattern_blocks(&cells)?;
|
||||
let direction = match facing.as_str() {
|
||||
"south" => horizon_core::geometry::Direction::South,
|
||||
"west" => horizon_core::geometry::Direction::West,
|
||||
"east" => horizon_core::geometry::Direction::East,
|
||||
_ => horizon_core::geometry::Direction::North,
|
||||
};
|
||||
let pos = horizon_core::position::BlockPos::new(below[0], below[1], below[2]);
|
||||
let chest = self.with_level(|b, level, ticks| {
|
||||
b.copper_chest_from_block(level, ticks, copper, direction, pos)
|
||||
});
|
||||
if let Some(chest) = chest {
|
||||
self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, chest, 2));
|
||||
if let Some(entity) =
|
||||
horizon_client::containers::BlockEntity::for_block(&self.res.facts.get(chest).name)
|
||||
{
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((below[0], below[1], below[2]), entity);
|
||||
}
|
||||
}
|
||||
if let Some(m) = id.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id)) {
|
||||
m.extra.variant = weather;
|
||||
let p = [m.position.x, m.position.y, m.position.z];
|
||||
self.audio
|
||||
.play("minecraft:entity.copper_golem.spawn", Some(p), 1.0, 1.0);
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,8 +104,7 @@ impl Game<'_> {
|
||||
let description =
|
||||
horizon_client::component::to_text(&s.description, &mut |k| Text::literal(k));
|
||||
self.titles
|
||||
.set_overlay(Text::translate("record.nowPlaying", &[description]));
|
||||
self.titles.overlay_animated = true;
|
||||
.set_overlay(Text::translate("record.nowPlaying", &[description]), true);
|
||||
self.update_song_volumes();
|
||||
}
|
||||
fn stop_song(&mut self, pos: [i32; 3]) {
|
||||
@@ -126,16 +125,13 @@ impl Game<'_> {
|
||||
};
|
||||
self.stop_song(pos);
|
||||
if let Some(record) = record {
|
||||
let r = &mut self.world.random;
|
||||
// offsetRandomXZ(random, 0.7)
|
||||
let dx = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0;
|
||||
let dz = f64::from(r.next_float() * 2.0 - 1.0) * 0.7 / 2.0;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5 + dx,
|
||||
f64::from(pos[1]) + 1.01,
|
||||
f64::from(pos[2]) + 0.5 + dz,
|
||||
];
|
||||
self.spawn_item(record, at, [0.0, 0.0, 0.0], 10);
|
||||
// atLowerCornerWithOffset(pos, 0.5, 1.01, 0.5).offsetRandomXZ(random, 0.7);
|
||||
// `new ItemEntity` moves it with its own random.
|
||||
let at = horizon_world::level::removal::jukebox_pop_position(
|
||||
&mut self.world.random,
|
||||
horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
);
|
||||
self.spawn_item(record, at, super::dispenser::new_item_motion(), 10);
|
||||
}
|
||||
self.set_has_record(pos, false);
|
||||
self.jukebox_changed(pos);
|
||||
|
||||
@@ -332,6 +332,16 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> {
|
||||
self.lan_start(settings)?;
|
||||
let port = self.lan.as_ref().map_or(0, |l| l.settings.port);
|
||||
self.system_message(Text::translate(
|
||||
"menu.multiplayerOptions.publish.started.lan",
|
||||
&[Text::literal(port.to_string())],
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
/// IntegratedServer.publishServer without the screen's announcement.
|
||||
pub(super) fn lan_start(&mut self, settings: LanSettings) -> Result<()> {
|
||||
if self.lan.is_some() || self.remote.is_some() || self.title.is_some() {
|
||||
return Err("already open".into());
|
||||
}
|
||||
@@ -407,10 +417,6 @@ impl Game<'_> {
|
||||
mob_state: HashMap::new(),
|
||||
});
|
||||
self.audio.capture = Some(Vec::new());
|
||||
self.system_message(Text::translate(
|
||||
"menu.multiplayerOptions.publish.started.lan",
|
||||
&[Text::literal(port.to_string())],
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -525,7 +525,12 @@ impl Game<'_> {
|
||||
let lines = self.as_guest(host, conn, |g| {
|
||||
g.chat_capture = Some(Vec::new());
|
||||
g.run_command(&command);
|
||||
g.chat_capture.take().unwrap_or_default()
|
||||
g.chat_capture
|
||||
.take()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(horizon_client::text::Text::plain)
|
||||
.collect::<Vec<String>>()
|
||||
});
|
||||
for line in lines.unwrap_or_default() {
|
||||
host.hub.send_to(
|
||||
@@ -551,7 +556,7 @@ impl Game<'_> {
|
||||
};
|
||||
let skip = usize::from(text.starts_with('/'));
|
||||
let command = &text[skip..];
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::game_dispatcher();
|
||||
let level = std::mem::replace(&mut self.ui.registries.permission, permission);
|
||||
let parse = d.parse(command, &self.ui.registries);
|
||||
let ((start, end), suggestions) = d.suggestions(&parse, command.len(), &self.ui.registries);
|
||||
|
||||
@@ -241,7 +241,7 @@ impl Game<'_> {
|
||||
}
|
||||
if o.parsed_port().is_none() {
|
||||
let t = Text::translate(
|
||||
"lanServer.port.invalid.new",
|
||||
"lanServer.port.invalid",
|
||||
&[Text::literal("1024"), Text::literal("65535")],
|
||||
);
|
||||
let first = t.clone();
|
||||
|
||||
@@ -1255,6 +1255,7 @@ impl Game<'_> {
|
||||
texts: None,
|
||||
partial: 0.0,
|
||||
game_time: self.world.game_time,
|
||||
max_y: self.dim.max_y(),
|
||||
world: &self.world,
|
||||
sprites: &self.res.atlas.sprites,
|
||||
nether: self.dim == super::Dim::Nether,
|
||||
|
||||
@@ -466,23 +466,11 @@ impl Game<'_> {
|
||||
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
|
||||
horizon_client::hud_layout::paint(batch, atlas, &draws);
|
||||
if m.extra.saddled {
|
||||
let x = (w / 2 - 91) as f32;
|
||||
let y = (h - 29) as f32;
|
||||
batch.sprite(atlas, "gui/sprites/hud/jump_bar_background", x, y);
|
||||
if self.mount.jump_ticks < 0 {
|
||||
batch.sprite(atlas, "gui/sprites/hud/jump_bar_cooldown", x, y);
|
||||
} else {
|
||||
let filled = (self.mount.jump_scale * 183.0).floor();
|
||||
if filled > 0.0 {
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
"gui/sprites/hud/jump_bar_progress",
|
||||
x,
|
||||
y,
|
||||
filled / 182.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
// JumpableVehicleBar: the cooldown shows while the jump recharges.
|
||||
let cooldown = i32::from(self.mount.jump_ticks < 0);
|
||||
let draws =
|
||||
horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale);
|
||||
horizon_client::hud_layout::paint(batch, atlas, &draws);
|
||||
}
|
||||
(hearts, m.extra.saddled)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Custom names: `NameTagItem.interactLivingEntity` and the name tag
|
||||
//! (`EntityRenderer.submitNameTag`): above the head, facing the camera,
|
||||
//! on a translucent black background, shown when the name is visible or the
|
||||
//! mob is under the crosshair within 64 blocks.
|
||||
//! mob is under the crosshair within 64 blocks, as its team's name tag
|
||||
//! visibility allows, in the team's colours, with its score in the
|
||||
//! objective displayed below names.
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::mesher::Vertex;
|
||||
use horizon_client::{mesher::Vertex, save::uuid_text, scoreboard as sb, text::Text};
|
||||
|
||||
impl Game<'_> {
|
||||
/// A named name tag names the mob under the crosshair.
|
||||
@@ -26,17 +28,37 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// `Entity.belowNameDisplay`: the mob's score in the objective shown below
|
||||
/// names, then a space and the objective's name.
|
||||
fn below_name_text(&self, id: u32) -> Option<Text> {
|
||||
let board = &self.score.board;
|
||||
let objective = board.display_objective(sb::SLOT_BELOW_NAME)?;
|
||||
let uuid = self.persist.uuids.get(&id)?;
|
||||
let score = board.score(&uuid_text(*uuid), &objective.name)?;
|
||||
// numberFormatOrDefault(StyledFormat.NO_STYLE).
|
||||
let format = score
|
||||
.number_format
|
||||
.clone()
|
||||
.or_else(|| objective.number_format.clone())
|
||||
.unwrap_or(sb::NumberFormat::Styled(serde_json::json!({})));
|
||||
let mut t = Text::empty();
|
||||
t.push(format.format(score.value));
|
||||
t.push(Text::literal(" "));
|
||||
t.push(objective.display_text());
|
||||
Some(t)
|
||||
}
|
||||
pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
let target = self.mob_hit().map(|(i, _)| self.mobs[i].id);
|
||||
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
|
||||
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
|
||||
let up = right.cross(forward).normalize_or_zero();
|
||||
let white = self.res.atlas.font.white();
|
||||
let viewer = self.player_team();
|
||||
for m in &self.mobs {
|
||||
let Some(name) = m.custom_name.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if !(m.name_visible || Some(m.id) == target) || !m.alive() {
|
||||
if !m.alive() {
|
||||
continue;
|
||||
}
|
||||
let p = glam::DVec3::new(
|
||||
@@ -44,19 +66,48 @@ impl Game<'_> {
|
||||
m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5,
|
||||
m.previous.z + (m.position.z - m.previous.z) * alpha,
|
||||
);
|
||||
if p.distance_squared(camera) >= 64.0 * 64.0 {
|
||||
// The name tag distance (64) is measured to the entity.
|
||||
let distance_sqr =
|
||||
glam::DVec3::new(m.position.x, m.position.y, m.position.z).distance_squared(camera);
|
||||
if distance_sqr >= 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
let o = (p - camera).as_vec3();
|
||||
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
|
||||
// Text space: x right, y down (scale 0.025, -0.025).
|
||||
let at = |x: f32, y: f32| o + r * x - u * y;
|
||||
let width: f32 = name
|
||||
.chars()
|
||||
.map(|c| self.res.atlas.glyph(c).map_or(6.0, |g| g.1))
|
||||
.sum();
|
||||
let x0 = -(width / 2.0).trunc();
|
||||
let y0 = if name == "deadmau5" { -10.0 } else { 0.0 };
|
||||
let team = self.mob_team(m.id);
|
||||
// LivingEntityRenderer.shouldShowName (team rules included), then
|
||||
// MobRenderer: a visible name, or the mob under the crosshair.
|
||||
let invisible = sb::invisible_to(
|
||||
team,
|
||||
viewer,
|
||||
self.spectator(),
|
||||
m.has_effect("minecraft:invisibility"),
|
||||
);
|
||||
let view = sb::NameView {
|
||||
discrete: false,
|
||||
distance_sqr,
|
||||
invisible_to_viewer: invisible,
|
||||
hud_hidden: self.ui.hide_gui,
|
||||
is_camera: false,
|
||||
is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)),
|
||||
};
|
||||
if !sb::name_shown(team, viewer, view) || !(m.name_visible || Some(m.id) == target) {
|
||||
continue;
|
||||
}
|
||||
// getDisplayName: the custom name in the team's prefix, suffix and colour.
|
||||
let shown = match team {
|
||||
Some(t) => t.formatted_name(Text::literal(name)),
|
||||
None => Text::literal(name),
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
// EntityRenderer.extractNameTags: the score shows within the
|
||||
// below-name distance (10), under the name.
|
||||
let mut lift = 0.0;
|
||||
if distance_sqr < 10.0 * 10.0
|
||||
&& let Some(score) = self.below_name_text(m.id)
|
||||
{
|
||||
lines.push((score, 0.0));
|
||||
lift = f64::from(9.0f32 * 1.15 * 0.025);
|
||||
}
|
||||
lines.push((shown, lift));
|
||||
let l = self.world.light(
|
||||
m.position.x.floor() as i32,
|
||||
(m.position.y + f64::from(m.height())).floor() as i32,
|
||||
@@ -64,48 +115,77 @@ impl Game<'_> {
|
||||
);
|
||||
let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
|
||||
let away = forward.as_vec3() * 0.002;
|
||||
// `background`: unlit (vertex colour only) and a hair behind the text.
|
||||
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| {
|
||||
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
|
||||
let uvs = [
|
||||
[uv[0], uv[3]],
|
||||
[uv[2], uv[3]],
|
||||
[uv[2], uv[1]],
|
||||
[uv[0], uv[1]],
|
||||
];
|
||||
for ((x, y), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO })
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: if background { 2 } else { 0 },
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
};
|
||||
// Background: Options.getBackgroundOpacity(0.25) black.
|
||||
quad(
|
||||
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
0x40_00_00_00,
|
||||
true,
|
||||
);
|
||||
let mut x = x0;
|
||||
for ch in name.chars() {
|
||||
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
for (text, lift) in lines {
|
||||
let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3();
|
||||
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
|
||||
// Text space: x right, y down (scale 0.025, -0.025).
|
||||
let at = |x: f32, y: f32| o + r * x - u * y;
|
||||
let chars: Vec<(char, u32)> = text
|
||||
.spans
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
|
||||
// RGBA8, alpha in the top byte.
|
||||
let color = 0xFF00_0000
|
||||
| ((rgb & 0xFF) << 16)
|
||||
| (rgb & 0xFF00)
|
||||
| ((rgb >> 16) & 0xFF);
|
||||
s.text.chars().map(move |c| (c, color))
|
||||
})
|
||||
.collect();
|
||||
let width: f32 = chars
|
||||
.iter()
|
||||
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
|
||||
.sum();
|
||||
let x0 = -(width / 2.0).trunc();
|
||||
let y0 = if text.plain() == "deadmau5" {
|
||||
-10.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if ch != ' ' {
|
||||
quad(
|
||||
[x, y0, x + 8.0, y0 + 8.0],
|
||||
[g.u0, g.v0, g.u1, g.v1],
|
||||
0xFFFF_FFFF,
|
||||
false,
|
||||
);
|
||||
// `background`: unlit (vertex colour only) and a hair behind the text.
|
||||
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| {
|
||||
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
|
||||
let uvs = [
|
||||
[uv[0], uv[3]],
|
||||
[uv[2], uv[3]],
|
||||
[uv[2], uv[1]],
|
||||
[uv[0], uv[1]],
|
||||
];
|
||||
for ((x, y), uv) in corners.into_iter().zip(uvs) {
|
||||
out.push(Vertex {
|
||||
pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO })
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: if background { 2 } else { 0 },
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
};
|
||||
// Background: Options.getBackgroundOpacity(0.25) black.
|
||||
quad(
|
||||
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
0x40_00_00_00,
|
||||
true,
|
||||
);
|
||||
let mut x = x0;
|
||||
for (ch, color) in chars {
|
||||
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
quad(
|
||||
[x, y0, x + 8.0, y0 + 8.0],
|
||||
[g.u0, g.v0, g.u1, g.v1],
|
||||
color,
|
||||
false,
|
||||
);
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,6 +284,9 @@ impl Game<'_> {
|
||||
_ if self.res.mob_types.contains_key(&kind) => {
|
||||
self.load_mob(tag, None);
|
||||
}
|
||||
_ if !kind.is_empty() && entity_nbt::position(&tag).is_some() => {
|
||||
self.load_other(tag, &kind);
|
||||
}
|
||||
_ => self.persist.unknown.entry(key).or_default().push(tag),
|
||||
}
|
||||
}
|
||||
@@ -356,6 +359,62 @@ impl Game<'_> {
|
||||
}
|
||||
Some(id)
|
||||
}
|
||||
/// An entity of a type Horizon does not simulate, kept as its compound.
|
||||
fn load_other(&mut self, tag: Tag, kind: &str) -> Option<u32> {
|
||||
let position = entity_nbt::position(&tag)?;
|
||||
let rotation = match tag.get("Rotation") {
|
||||
Some(Tag::List(l)) => {
|
||||
let f = |i: usize| match l.get(i) {
|
||||
Some(Tag::Float(v)) => f32::from_bits(*v),
|
||||
_ => 0.0,
|
||||
};
|
||||
[f(0), f(1)]
|
||||
}
|
||||
_ => [0.0, 0.0],
|
||||
};
|
||||
self.next_entity += 1;
|
||||
let id = self.next_entity;
|
||||
let uuid = entity_nbt::uuid(&tag);
|
||||
self.remember(id, uuid, tag);
|
||||
self.others.push(super::commands::OtherEntity {
|
||||
id,
|
||||
kind: kind.to_owned(),
|
||||
position,
|
||||
yaw: rotation[0],
|
||||
pitch: rotation[1],
|
||||
});
|
||||
Some(id)
|
||||
}
|
||||
/// The compound of an entity Horizon does not simulate, with its current
|
||||
/// position, rotation and UUID.
|
||||
pub(super) fn other_to_nbt(&self, o: &super::commands::OtherEntity, uuid: [i32; 4]) -> Tag {
|
||||
let mut tag = self
|
||||
.persist
|
||||
.raw
|
||||
.get(&o.id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Tag::Compound(Default::default()));
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.insert("id".into(), Tag::String(o.kind.as_str().into()));
|
||||
c.insert(
|
||||
"Pos".into(),
|
||||
Tag::List(
|
||||
[o.position.x, o.position.y, o.position.z]
|
||||
.map(|v| Tag::Double(v.to_bits()))
|
||||
.to_vec(),
|
||||
),
|
||||
);
|
||||
c.insert(
|
||||
"Rotation".into(),
|
||||
Tag::List(vec![
|
||||
Tag::Float(o.yaw.to_bits()),
|
||||
Tag::Float(o.pitch.to_bits()),
|
||||
]),
|
||||
);
|
||||
c.insert("UUID".into(), Tag::IntArray(uuid.to_vec()));
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// The root of a stack of riders (`Entity.getRootVehicle`).
|
||||
fn mob_root(&self, mut i: usize) -> usize {
|
||||
for _ in 0..8 {
|
||||
@@ -393,6 +452,10 @@ impl Game<'_> {
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// The compound an entity was loaded with (and commands have edited).
|
||||
pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> {
|
||||
self.persist.raw.get(&id)
|
||||
}
|
||||
fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) {
|
||||
if let Some(u) = uuid {
|
||||
self.persist.uuids.insert(id, u);
|
||||
@@ -627,6 +690,18 @@ impl Game<'_> {
|
||||
out.entry(chunk_of(at)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for o in &self.others {
|
||||
if keys.contains(&chunk_of(o.position)) {
|
||||
let uuid = self
|
||||
.persist
|
||||
.uuids
|
||||
.get(&o.id)
|
||||
.copied()
|
||||
.unwrap_or_else(random_uuid);
|
||||
let tag = self.other_to_nbt(o, uuid);
|
||||
out.entry(chunk_of(o.position)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for key in keys {
|
||||
let unknown = if remove {
|
||||
self.persist.unknown.remove(key)
|
||||
@@ -659,6 +734,13 @@ impl Game<'_> {
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.others.retain(|o| {
|
||||
let keep = !gone(o.position);
|
||||
if !keep {
|
||||
removed.push(o.id);
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.armor_stands.retain(|a| {
|
||||
let keep = !gone(a.position);
|
||||
if !keep {
|
||||
@@ -733,6 +815,7 @@ impl Game<'_> {
|
||||
.chain(self.armor_stands.iter().map(|e| e.id))
|
||||
.chain(self.item_frames.iter().map(|e| e.id))
|
||||
.chain(self.paintings.iter().map(|e| e.id))
|
||||
.chain(self.others.iter().map(|e| e.id))
|
||||
.collect();
|
||||
self.persist.uuids.retain(|id, _| alive.contains(id));
|
||||
self.persist.raw.retain(|id, _| alive.contains(id));
|
||||
|
||||
@@ -6,7 +6,8 @@ use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
brewing,
|
||||
effects::{EffectAction, EffectInstance, PlayerEffects},
|
||||
hud::{HudBatch, rgba},
|
||||
hud::HudBatch,
|
||||
hud_layout, hud_overlays,
|
||||
items::ItemStack,
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
@@ -563,52 +564,26 @@ impl Game<'_> {
|
||||
if self.screen != Screen::Playing || self.potions.effects.list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut list: Vec<&EffectInstance> = self.potions.effects.list.iter().collect();
|
||||
let color = |e: &EffectInstance| brewing::effect(e.id).map_or(0, |d| d.color);
|
||||
list.sort_by(|a, b| {
|
||||
(a.ambient, a.duration == -1, a.duration, color(a))
|
||||
.cmp(&(b.ambient, b.duration == -1, b.duration, color(b)))
|
||||
.reverse()
|
||||
});
|
||||
let (mut good, mut bad) = (0, 0);
|
||||
let atlas = &self.res.atlas;
|
||||
for e in list {
|
||||
let beneficial =
|
||||
brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial);
|
||||
let mut x = batch.width;
|
||||
let mut y = 1.0;
|
||||
if beneficial {
|
||||
good += 1;
|
||||
x -= 25.0 * good as f32;
|
||||
} else {
|
||||
bad += 1;
|
||||
x -= 25.0 * bad as f32;
|
||||
y += 26.0;
|
||||
}
|
||||
let mut alpha = 1.0f32;
|
||||
if e.ambient {
|
||||
batch.sprite(atlas, "gui/sprites/hud/effect_background_ambient", x, y);
|
||||
} else {
|
||||
batch.sprite(atlas, "gui/sprites/hud/effect_background", x, y);
|
||||
if e.duration != -1 && e.duration <= 200 {
|
||||
let d = e.duration as f32;
|
||||
let used = 10.0 - (e.duration / 20) as f32;
|
||||
alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5)
|
||||
+ (d * std::f32::consts::PI / 5.0).cos()
|
||||
* (used / 10.0 * 0.25).clamp(0.0, 0.25))
|
||||
.clamp(0.0, 1.0);
|
||||
let icons: Vec<hud_overlays::EffectIcon> = self
|
||||
.potions
|
||||
.effects
|
||||
.list
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let def = brewing::effect(e.id);
|
||||
hud_overlays::EffectIcon {
|
||||
id: e.id.to_owned(),
|
||||
beneficial: def.is_some_and(|d| d.category == brewing::Category::Beneficial),
|
||||
color: def.map_or(0, |d| d.color as i32),
|
||||
ambient: e.ambient,
|
||||
duration: e.duration,
|
||||
// Horizon keeps no showIcon flag: every effect shows its icon.
|
||||
show_icon: true,
|
||||
}
|
||||
}
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
&format!("mob_effect/{}", e.id),
|
||||
x + 3.0,
|
||||
y + 3.0,
|
||||
18.0,
|
||||
18.0,
|
||||
rgba(255, 255, 255, (alpha * 255.0) as u8),
|
||||
);
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let draws = hud_overlays::effects(batch.width as i32, false, &icons);
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
/// Effects saved in level.dat (`Player.active_effects`).
|
||||
pub(super) fn restore_effects(&mut self) {
|
||||
|
||||
@@ -4,9 +4,10 @@ use super::{Dim, Game};
|
||||
use horizon_client::mobs::villager as mobs_villager;
|
||||
use horizon_client::{
|
||||
effects::EffectInstance,
|
||||
hud::{HudBatch, rgba},
|
||||
hud_overlays,
|
||||
mobs::{Mob, Species, data, raider},
|
||||
raid::{self, Action, BarName, RaidLevel, RaiderInfo, RaiderType, Raids, Spawn},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -746,31 +747,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The raid boss bars (`BossHealthOverlay`): a red notched bar with the
|
||||
/// raid's title. Returns the next free row.
|
||||
pub(super) fn draw_raid_bar(&self, batch: &mut HudBatch, mut y: f32) -> f32 {
|
||||
let atlas = &self.res.atlas;
|
||||
/// The raid boss bars: red and notched in tens, with the raid's title.
|
||||
pub(super) fn raid_bars(&self, bars: &mut Vec<hud_overlays::BossBar>) {
|
||||
for raid in self.raiding.raids.map.values() {
|
||||
if !raid.bar.visible || !raid.bar.player || raid.is_stopped() {
|
||||
continue;
|
||||
}
|
||||
let x = (batch.width / 2.0 - 91.0).floor();
|
||||
batch.sprite(atlas, "gui/sprites/boss_bar/red_background", x, y);
|
||||
batch.sprite(atlas, "gui/sprites/boss_bar/notched_10_background", x, y);
|
||||
let p = raid.bar.progress;
|
||||
// Mth.lerpDiscrete(progress, 0, 182).
|
||||
let width = (p * 181.0).floor() as i32 + i32::from(p > 0.0);
|
||||
if width > 0 {
|
||||
let fraction = width as f32 / 182.0;
|
||||
batch.sprite_part(atlas, "gui/sprites/boss_bar/red_progress", x, y, fraction);
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
"gui/sprites/boss_bar/notched_10_progress",
|
||||
x,
|
||||
y,
|
||||
fraction,
|
||||
);
|
||||
}
|
||||
let title = self.translate("event.minecraft.raid", "Raid");
|
||||
let name = match raid.bar.name {
|
||||
BarName::Raid => title,
|
||||
@@ -789,18 +771,13 @@ impl Game<'_> {
|
||||
self.translate("event.minecraft.raid.defeat.full", "Raid - Defeat")
|
||||
}
|
||||
};
|
||||
let w = HudBatch::text_width(atlas, &name);
|
||||
batch.text(
|
||||
atlas,
|
||||
&name,
|
||||
(batch.width / 2.0 - w / 2.0).floor(),
|
||||
y - 9.0,
|
||||
rgba(255, 255, 255, 255),
|
||||
true,
|
||||
);
|
||||
y += 19.0;
|
||||
bars.push(hud_overlays::BossBar {
|
||||
name: Text::literal(name),
|
||||
progress: raid.bar.progress,
|
||||
color: 2,
|
||||
overlay: 2,
|
||||
});
|
||||
}
|
||||
y
|
||||
}
|
||||
/// A firework a villager launches to celebrate (`CelebrateVillagersSurvivedRaid`).
|
||||
pub(super) fn villager_firework(&mut self, at: [f64; 3], color: usize, flight: u8) {
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//! campfire smoke and rain splashes (`ClientLevel.tickWeatherEffects`).
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog};
|
||||
use horizon_client::screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness};
|
||||
use horizon_client::{
|
||||
animate_tick::{AnimateContext, animate_tick, campfire_particles},
|
||||
biome::Biomes,
|
||||
@@ -11,6 +10,10 @@ use horizon_client::{
|
||||
particles::{ParticleLevel, ParticleOptions, ParticleType},
|
||||
world::World,
|
||||
};
|
||||
use horizon_client::{
|
||||
hud_overlays,
|
||||
screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness},
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
|
||||
/// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one.
|
||||
@@ -140,12 +143,33 @@ impl Game<'_> {
|
||||
fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water;
|
||||
let water =
|
||||
(in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch));
|
||||
let camera_overlays = match &self.armor[0] {
|
||||
Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => {
|
||||
vec!["misc/pumpkinblur".to_owned()]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
// Hud.extractCameraOverlays; the spyglass scope (and its easing) is
|
||||
// drawn on the HUD by draw_spyglass.
|
||||
let fx = &self.res.screen_fx;
|
||||
let overlays = hud_overlays::CameraOverlays {
|
||||
vignette: self
|
||||
.settings
|
||||
.vignette
|
||||
.then_some((fx.vignette_brightness, 0.0)),
|
||||
first_person: self.camera_type.first_person(),
|
||||
scoping: self.scoping(),
|
||||
game_time_delta: 0.0,
|
||||
equipment: match &self.armor[0] {
|
||||
Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => {
|
||||
vec!["misc/pumpkinblur".to_owned()]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
},
|
||||
ticks_frozen: 0,
|
||||
percent_frozen: 0.0,
|
||||
partial,
|
||||
portal: [fx.o_portal, fx.portal],
|
||||
nausea: 0.0,
|
||||
screen_effect_scale: 1.0,
|
||||
};
|
||||
let mut scope = self.scope_scale;
|
||||
let gui_overlays =
|
||||
hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope);
|
||||
self.res.screen_fx.build(&ScreenInputs {
|
||||
sprites: &self.res.atlas.sprites,
|
||||
aspect: size[0] as f32 / size[1].max(1) as f32,
|
||||
@@ -153,10 +177,7 @@ impl Game<'_> {
|
||||
block_overlay,
|
||||
water,
|
||||
on_fire: false,
|
||||
camera_overlays,
|
||||
frozen: 0.0,
|
||||
vignette: true,
|
||||
border_warning: None,
|
||||
gui_overlays: &gui_overlays,
|
||||
})
|
||||
}
|
||||
/// `Lightmap.getBrightness(getMaxLocalRawBrightness(eye))`.
|
||||
|
||||
@@ -8,9 +8,10 @@ use horizon_client::{
|
||||
Context,
|
||||
args::{IntRange, Selector},
|
||||
},
|
||||
hud::{HudBatch, rgba},
|
||||
hud::HudBatch,
|
||||
hud_layout, hud_overlays,
|
||||
save::{self, uuid_from_text, uuid_text},
|
||||
scoreboard::{self as sb, Comp, NumberFormat, Scoreboard, literal},
|
||||
scoreboard::{self as sb, Comp, Scoreboard, literal},
|
||||
scoreboard_cmd::{self, Env, Holder},
|
||||
text::Text,
|
||||
};
|
||||
@@ -20,7 +21,8 @@ use std::collections::HashSet;
|
||||
/// What `ServerPlayer` last recorded for the criteria that follow the player.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recorded {
|
||||
health: Option<i32>,
|
||||
/// `lastRecordedHealthAndAbsorption` (compared as a float).
|
||||
health_and_absorption: Option<f32>,
|
||||
food: Option<i32>,
|
||||
air: Option<i32>,
|
||||
armor: Option<i32>,
|
||||
@@ -166,9 +168,16 @@ impl Game<'_> {
|
||||
/// `Entity.getTags` (the `Tags` list of the saved entity).
|
||||
pub(super) fn tags_of(&self, t: Target) -> Vec<String> {
|
||||
let raw = match t {
|
||||
Target::Mob(id) | Target::Item(id) => self.persist.raw.get(&id),
|
||||
Target::Mob(id)
|
||||
| Target::Item(id)
|
||||
| Target::Stand(id)
|
||||
| Target::Frame(id)
|
||||
| Target::Painting(id)
|
||||
| Target::Boat(id)
|
||||
| Target::Cart(id)
|
||||
| Target::Other(id) => self.persist.raw.get(&id),
|
||||
Target::Player => self.level.player_extra.as_ref(),
|
||||
_ => None,
|
||||
Target::Orb(_) | Target::Arrow(_) => None,
|
||||
};
|
||||
match raw.and_then(|r| r.get("Tags")) {
|
||||
Some(Tag::List(l)) => l
|
||||
@@ -306,18 +315,29 @@ impl Game<'_> {
|
||||
});
|
||||
}
|
||||
}
|
||||
let display = self.player_display_comp();
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
let health = (p.health.health() + p.health.absorption()).ceil() as i32;
|
||||
let health_and_absorption = p.health.health() + p.health.absorption();
|
||||
let food = p.health.food.food;
|
||||
// getArmorValue: the armor attribute rounded down.
|
||||
let armor = p
|
||||
.attribute("minecraft:armor")
|
||||
.or_else(|_| p.attribute("armor"))
|
||||
.unwrap_or(0.0)
|
||||
.ceil() as i32;
|
||||
.floor() as i32;
|
||||
let rec = &mut self.score.recorded;
|
||||
let board = &mut self.score.board;
|
||||
if rec.health_and_absorption != Some(health_and_absorption) {
|
||||
rec.health_and_absorption = Some(health_and_absorption);
|
||||
let value = health_and_absorption.ceil() as i32;
|
||||
board.for_all_objectives_with(
|
||||
sb::CRITERIA_HEALTH,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
|_| value,
|
||||
);
|
||||
}
|
||||
for (criteria, last, value) in [
|
||||
(sb::CRITERIA_HEALTH, &mut rec.health, health),
|
||||
(sb::CRITERIA_FOOD, &mut rec.food, food),
|
||||
// The air supply is full unless the player is drowning.
|
||||
(sb::CRITERIA_AIR, &mut rec.air, 300),
|
||||
@@ -327,7 +347,12 @@ impl Game<'_> {
|
||||
] {
|
||||
if *last != Some(value) {
|
||||
*last = Some(value);
|
||||
board.for_all_objectives(criteria, PLAYER_NAME, |_| value);
|
||||
board.for_all_objectives_with(
|
||||
criteria,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
|_| value,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -338,29 +363,39 @@ impl Game<'_> {
|
||||
}
|
||||
/// `ServerPlayer.die`: the death count.
|
||||
pub(super) fn score_player_died(&mut self) {
|
||||
let display = self.player_display_comp();
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| {
|
||||
v.wrapping_add(1)
|
||||
});
|
||||
// A respawned player has everything to record again.
|
||||
self.score.recorded = Recorded::default();
|
||||
}
|
||||
/// `ServerPlayer.awardKillScore`: total kills and the team kill counts.
|
||||
pub(super) fn score_player_killed(&mut self, victim: Target) {
|
||||
let victim_name = self.holder_name(victim);
|
||||
let display = self.player_display_comp();
|
||||
let board = &mut self.score.board;
|
||||
board.for_all_objectives(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
let inc = |v: i32| v.wrapping_add(1);
|
||||
board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc);
|
||||
if victim == Target::Player {
|
||||
board.for_all_objectives(sb::CRITERIA_PLAYER_KILLS, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(
|
||||
sb::CRITERIA_PLAYER_KILLS,
|
||||
PLAYER_NAME,
|
||||
Some(&display),
|
||||
inc,
|
||||
);
|
||||
}
|
||||
let color_of =
|
||||
|board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone());
|
||||
if let Some(victim_name) = victim_name {
|
||||
if let Some(color) = color_of(board, &victim_name) {
|
||||
let criteria = format!("teamkill.{color}");
|
||||
board.for_all_objectives(&criteria, PLAYER_NAME, |v| v + 1);
|
||||
board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc);
|
||||
}
|
||||
if let Some(color) = color_of(board, PLAYER_NAME) {
|
||||
let criteria = format!("killedByTeam.{color}");
|
||||
board.for_all_objectives(&criteria, &victim_name, |v| v + 1);
|
||||
board.for_all_objectives(&criteria, &victim_name, inc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,9 +404,62 @@ impl Game<'_> {
|
||||
let Some(uuid) = self.persist.uuids.get(&id).copied() else {
|
||||
return;
|
||||
};
|
||||
let name = uuid_text(uuid);
|
||||
self.score.board.reset_all(&name);
|
||||
self.score.board.remove_from_team(&name);
|
||||
self.score.board.entity_removed(&uuid_text(uuid));
|
||||
}
|
||||
|
||||
// ---- teams in gameplay -----------------------------------------------------
|
||||
|
||||
/// `Entity.getTeam` of a mob (a mob joins a team by its UUID).
|
||||
pub(super) fn mob_team(&self, id: u32) -> Option<&sb::Team> {
|
||||
let uuid = self.persist.uuids.get(&id)?;
|
||||
self.score.board.players_team(&uuid_text(*uuid))
|
||||
}
|
||||
pub(super) fn player_team(&self) -> Option<&sb::Team> {
|
||||
self.score.board.players_team(PLAYER_NAME)
|
||||
}
|
||||
/// The teams of the player and of the mobs on one (empty without teams).
|
||||
pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams {
|
||||
let board = &self.score.board;
|
||||
if board.teams.is_empty() {
|
||||
return Default::default();
|
||||
}
|
||||
horizon_client::mobs::Teams {
|
||||
player: self.player_team().cloned(),
|
||||
mobs: self
|
||||
.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.filter_map(|(id, uuid)| {
|
||||
Some((*id, board.players_team(&uuid_text(*uuid))?.clone()))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
/// The mobs on the player's team (`isAlliedTo`).
|
||||
pub(super) fn player_allies(&self) -> HashSet<u32> {
|
||||
let Some(team) = self.player_team() else {
|
||||
return HashSet::new();
|
||||
};
|
||||
self.persist
|
||||
.uuids
|
||||
.iter()
|
||||
.filter(|(_, uuid)| team.players.contains(&uuid_text(**uuid)))
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
}
|
||||
/// `Player.getDisplayName`: the name with the team's prefix, suffix and colour.
|
||||
pub(super) fn player_display_comp(&self) -> Comp {
|
||||
let name = literal(PLAYER_NAME);
|
||||
match self.player_team() {
|
||||
Some(t) => t.formatted_name_comp(&name),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
pub(super) fn player_display_text(&self) -> Text {
|
||||
match self.player_team() {
|
||||
Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)),
|
||||
None => Text::literal(PLAYER_NAME),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- commands ------------------------------------------------------------
|
||||
@@ -478,84 +566,16 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let default_format = NumberFormat::sidebar_default();
|
||||
let format = objective.format_or_default(default_format);
|
||||
let mut entries: Vec<_> = board
|
||||
.list_scores(&objective.name)
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_hidden())
|
||||
.collect();
|
||||
// Highest score first, then names case-insensitively.
|
||||
entries.sort_by(|a, b| {
|
||||
b.value
|
||||
.cmp(&a.value)
|
||||
.then_with(|| a.owner.to_lowercase().cmp(&b.owner.to_lowercase()))
|
||||
});
|
||||
entries.truncate(15);
|
||||
let rows: Vec<(Text, Text, f32)> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let name = match board.players_team(&e.owner) {
|
||||
Some(t) => t.formatted_name(e.owner_name()),
|
||||
None => e.owner_name(),
|
||||
};
|
||||
let score = e.format_value(&format);
|
||||
let width = atlas.font.width_text(&score);
|
||||
(name, score, width)
|
||||
})
|
||||
.collect();
|
||||
let title = objective.display_text();
|
||||
let title_width = atlas.font.width_text(&title);
|
||||
let spacer = atlas.font.width(": ");
|
||||
let mut biggest = title_width;
|
||||
for (name, _, score_width) in &rows {
|
||||
let extra = if *score_width > 0.0 {
|
||||
spacer + score_width
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
biggest = biggest.max(atlas.font.width_text(name) + extra);
|
||||
}
|
||||
let count = rows.len() as f32;
|
||||
let height = count * 9.0;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let bottom = (h / 2.0).trunc() + (height / 3.0).trunc();
|
||||
let left = w - biggest - 3.0;
|
||||
let right = w - 3.0 + 2.0;
|
||||
let body = rgba(0, 0, 0, (0.3 * 255.0) as u8);
|
||||
let header = rgba(0, 0, 0, (0.4 * 255.0) as u8);
|
||||
let top = bottom - count * 9.0;
|
||||
batch.fill(
|
||||
atlas,
|
||||
left - 2.0,
|
||||
top - 9.0 - 1.0,
|
||||
right - (left - 2.0),
|
||||
9.0,
|
||||
header,
|
||||
let draws = hud_overlays::sidebar(
|
||||
batch.width as i32,
|
||||
batch.height as i32,
|
||||
board,
|
||||
objective,
|
||||
&self.res.atlas.font,
|
||||
self.settings.text_background(0.3),
|
||||
self.settings.text_background(0.4),
|
||||
);
|
||||
batch.fill(
|
||||
atlas,
|
||||
left - 2.0,
|
||||
top - 1.0,
|
||||
right - (left - 2.0),
|
||||
bottom - (top - 1.0),
|
||||
body,
|
||||
);
|
||||
let white = rgba(255, 255, 255, 255);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
left + (biggest / 2.0).trunc() - (title_width / 2.0).trunc(),
|
||||
top - 9.0,
|
||||
white,
|
||||
false,
|
||||
);
|
||||
for (i, (name, score, score_width)) in rows.iter().enumerate() {
|
||||
let y = bottom - (count - i as f32) * 9.0;
|
||||
batch.text_styled(atlas, name, left, y, white, false);
|
||||
batch.text_styled(atlas, score, right - score_width, y, white, false);
|
||||
}
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Block entities removed by the block behaviour (`LevelChunk.setBlockState`
|
||||
//! running `BlockEntity.preRemoveSideEffects`) and the resources a destroyed
|
||||
//! block drops (`Block.dropResources`), drawn from the level random at the
|
||||
//! moment vanilla draws them. The item entities they make are added to the
|
||||
//! world as soon as the behaviour returns, within the same tick.
|
||||
use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box};
|
||||
use horizon_client::{
|
||||
containers::{Banner, BlockEntity},
|
||||
items::ItemStack,
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::{
|
||||
level::{
|
||||
LevelEvent,
|
||||
removal::{self, PreRemove},
|
||||
},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What a broken block's entity gives its own dropped item (`copy_components`
|
||||
/// in the block loot tables): a shulker box's contents, a banner's layers, a
|
||||
/// container's custom name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Pending {
|
||||
pub(super) shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
|
||||
pub(super) banner: HashMap<[i32; 3], Banner>,
|
||||
/// The block's item and the custom name.
|
||||
pub(super) names: HashMap<[i32; 3], (String, String)>,
|
||||
/// A decorated pot's sherds (back, left, right, front).
|
||||
pub(super) pot: HashMap<[i32; 3], [Option<ItemStack>; 4]>,
|
||||
}
|
||||
impl Pending {
|
||||
/// Remember what the block entity at `pos` copies into the drops of `block`.
|
||||
pub(super) fn record(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
entity: &BlockEntity,
|
||||
block: &str,
|
||||
name: Option<String>,
|
||||
) {
|
||||
if let BlockEntity::Banner(banner) = entity {
|
||||
self.banner.insert(pos, banner.clone());
|
||||
return;
|
||||
}
|
||||
if let Some(name) = name {
|
||||
self.names.insert(pos, (block.to_owned(), name));
|
||||
}
|
||||
if is_shulker_box(block)
|
||||
&& let BlockEntity::Chest(items) = entity
|
||||
{
|
||||
let kept = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| Some((i as u8, s.clone()?)))
|
||||
.collect();
|
||||
self.shulker.insert(pos, kept);
|
||||
}
|
||||
}
|
||||
/// Copy what was remembered for `pos` into a drop of the block.
|
||||
pub(super) fn attach(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if is_shulker_box(&stack.item)
|
||||
&& let Some(contents) = self.shulker.remove(&pos)
|
||||
&& !contents.is_empty()
|
||||
{
|
||||
stack.data_mut().container = contents;
|
||||
}
|
||||
if self
|
||||
.names
|
||||
.get(&pos)
|
||||
.is_some_and(|(item, _)| **item == *stack.item)
|
||||
&& let Some((_, name)) = self.names.remove(&pos)
|
||||
{
|
||||
stack.data_mut().custom_name = Some(name);
|
||||
}
|
||||
if &*stack.item == "minecraft:decorated_pot" {
|
||||
// The pot's block entity always copies its decorations, empty or not.
|
||||
let sides = self.pot.remove(&pos).unwrap_or_default();
|
||||
stack.data_mut().pot_decorations = Some(Box::new(sides));
|
||||
}
|
||||
if stack.item.ends_with("_banner")
|
||||
&& let Some(Banner { layers, name }) = self.banner.remove(&pos)
|
||||
{
|
||||
let data = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
if name.is_some() {
|
||||
data.custom_name = name;
|
||||
}
|
||||
stack.tidy();
|
||||
}
|
||||
}
|
||||
/// Remember a decorated pot's sherds from its saved block entity.
|
||||
pub(super) fn record_saved(&mut self, pos: [i32; 3], tag: &horizon_world::nbt::Tag) {
|
||||
use horizon_world::nbt::Tag;
|
||||
if tag.get("id") != Some(&Tag::String("minecraft:decorated_pot".into())) {
|
||||
return;
|
||||
}
|
||||
let sherds = tag.get("sherds");
|
||||
let side = |name: &str| match sherds.and_then(|s| s.get(name)) {
|
||||
Some(Tag::String(id)) => Some(ItemStack {
|
||||
item: std::sync::Arc::from(id.to_string_lossy().as_str()),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
}),
|
||||
Some(t) => horizon_client::save::item_from_nbt(t),
|
||||
None => None,
|
||||
};
|
||||
self.pot.insert(
|
||||
pos,
|
||||
[side("back"), side("left"), side("right"), side("front")],
|
||||
);
|
||||
}
|
||||
/// The block entity's dynamic drops: a decorated pot's sherds, left,
|
||||
/// back, front then right (`DecoratedPotBlock.getDrops`).
|
||||
pub(super) fn dynamic(&self, pos: [i32; 3]) -> Vec<ItemStack> {
|
||||
self.pot
|
||||
.get(&pos)
|
||||
.map_or_else(Vec::new, |[back, left, right, front]| {
|
||||
[left, back, front, right]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
pub(super) fn clear(&mut self, pos: [i32; 3]) {
|
||||
self.pot.remove(&pos);
|
||||
self.shulker.remove(&pos);
|
||||
self.banner.remove(&pos);
|
||||
self.names.remove(&pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// An item entity to add: where, its motion (None: `new ItemEntity`'s own
|
||||
/// random motion) and its pickup delay.
|
||||
pub(super) struct Spawn {
|
||||
pub(super) stack: ItemStack,
|
||||
pub(super) pos: [f64; 3],
|
||||
pub(super) motion: Option<[f64; 3]>,
|
||||
pub(super) delay: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Spill {
|
||||
pub(super) spawns: Vec<Spawn>,
|
||||
/// Experience orbs (`ExperienceOrb.award`): where and how much, each
|
||||
/// having drawn its merge id from the level random.
|
||||
pub(super) orbs: Vec<([f64; 3], u32)>,
|
||||
/// Block entities the behaviour removed, for the game's own follow-ups
|
||||
/// (open screens, playing songs).
|
||||
pub(super) removed: Vec<([i32; 3], BlockEntity)>,
|
||||
}
|
||||
|
||||
/// `Block.popResource`: a spot around the block's centre from the level random.
|
||||
pub(super) fn pop_position(
|
||||
random: &mut impl horizon_core::random::RandomSource,
|
||||
pos: [i32; 3],
|
||||
) -> [f64; 3] {
|
||||
let mut offset = || -0.25 + random.next_double() * 0.5;
|
||||
// EntityTypes.ITEM is 0.25 high.
|
||||
let half_height = f64::from(0.25f32) / 2.0;
|
||||
[
|
||||
f64::from(pos[0]) + 0.5 + offset(),
|
||||
f64::from(pos[1]) + 0.5 + offset() - half_height,
|
||||
f64::from(pos[2]) + 0.5 + offset(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The block entity at `pos` Horizon keeps as it was loaded, if any
|
||||
/// (campfires, decorated pots, chiseled bookshelves, shelves).
|
||||
pub(super) fn saved_entity(
|
||||
world: &horizon_client::world::World,
|
||||
pos: [i32; 3],
|
||||
) -> Option<horizon_world::nbt::Tag> {
|
||||
use horizon_world::nbt::Tag;
|
||||
let saved = world
|
||||
.chunks
|
||||
.get(&(pos[0] >> 4, pos[2] >> 4))?
|
||||
.saved
|
||||
.as_ref()?;
|
||||
saved
|
||||
.block_entities
|
||||
.iter()
|
||||
.find(|t| {
|
||||
t.get("x") == Some(&Tag::Int(pos[0]))
|
||||
&& t.get("y") == Some(&Tag::Int(pos[1]))
|
||||
&& t.get("z") == Some(&Tag::Int(pos[2]))
|
||||
})
|
||||
.cloned()
|
||||
}
|
||||
|
||||
impl GameLevel<'_> {
|
||||
/// `Block.popResource(level, pos, stack)` with the broken block's copied components.
|
||||
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
|
||||
self.pending.attach(pos, &mut stack);
|
||||
let at = pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack,
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
/// `Block.popResource(level, pos, new ItemStack(block))`.
|
||||
pub(super) fn pop_block_item(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let item = self.facts.get(state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.pop_resource([pos.x, pos.y, pos.z], ItemStack::new(&item, 1));
|
||||
}
|
||||
}
|
||||
/// An item `atLowerCornerWithOffset(pos, 0.5, 1.01, 0.5).offsetRandomXZ(random,
|
||||
/// 0.7)` with the default pickup delay (`ComposterBlock.extractProduce`).
|
||||
pub(super) fn pop_above(&mut self, pos: BlockPos, item: std::sync::Arc<str>) {
|
||||
let at = removal::jukebox_pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: ItemStack::new(&item, 1),
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
/// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot
|
||||
/// (from its random sequence, else the level random), with what its block
|
||||
/// entity copies into it, popped at once.
|
||||
pub(super) fn drop_resources_now(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
let at = [pos.x, pos.y, pos.z];
|
||||
if let Some(entity) = self.world.block_entities.get(&key) {
|
||||
let entity = entity.clone();
|
||||
let name = self.world.block_names.get(&key).cloned();
|
||||
let block = self.facts.get(state).name.clone();
|
||||
self.pending.record(at, &entity, &block, name);
|
||||
} else if let Some(tag) = saved_entity(self.world, [pos.x, pos.y, pos.z]) {
|
||||
self.pending.record_saved(at, &tag);
|
||||
}
|
||||
let dynamic = self.pending.dynamic(at);
|
||||
let drops = match self.items.block_loot_sequence(self.registry, state) {
|
||||
Some(sequence) => {
|
||||
let random = self.rand_sequences.get(&sequence, self.seed);
|
||||
self.items
|
||||
.block_drops_with(self.registry, state, None, &dynamic, random)
|
||||
}
|
||||
None => self.items.block_drops_with(
|
||||
self.registry,
|
||||
state,
|
||||
None,
|
||||
&dynamic,
|
||||
&mut self.world.random,
|
||||
),
|
||||
};
|
||||
for stack in drops {
|
||||
if &*stack.item != "minecraft:air" && stack.count > 0 {
|
||||
self.pop_resource(at, stack);
|
||||
}
|
||||
}
|
||||
self.pending.clear(at);
|
||||
// BlockBehaviour.spawnAfterBreak with no tool: ores, sculk and spawners
|
||||
// award experience at the block's centre.
|
||||
let name = self.facts.get(state).name.clone();
|
||||
if let Some(xp) = removal::break_experience(&mut self.world.random, &name)
|
||||
&& self.rules.block_drops
|
||||
{
|
||||
let centre = [
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y) + 0.5,
|
||||
f64::from(pos.z) + 0.5,
|
||||
];
|
||||
self.award_orbs(centre, xp);
|
||||
}
|
||||
}
|
||||
/// `ExperienceOrb.award`: orbs of the largest sizes, each drawing the id
|
||||
/// `tryMergeToExisting` compares from the level random.
|
||||
pub(super) fn award_orbs(&mut self, at: [f64; 3], mut amount: u32) {
|
||||
while amount > 0 {
|
||||
let value = removal::orb_value(amount);
|
||||
amount -= value;
|
||||
let _merge_id = self.world.random.next_int_bound(40);
|
||||
self.spill.orbs.push((at, value));
|
||||
}
|
||||
}
|
||||
/// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block
|
||||
/// entity of `old` at `pos`. A block entity Horizon never created reads as
|
||||
/// vanilla's fresh one: an empty container still draws a spot per slot.
|
||||
pub(super) fn remove_entity(
|
||||
&mut self,
|
||||
pos: BlockPos,
|
||||
old: BlockStateId,
|
||||
side_effects: bool,
|
||||
) -> u8 {
|
||||
let key = (pos.x, pos.y, pos.z);
|
||||
if self.remove_saved_entity(pos, old, side_effects) {
|
||||
return 0;
|
||||
}
|
||||
// Sculk blocks and creaking hearts notice their removal on their own tick.
|
||||
if matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Sculk(_) | BlockEntity::CreakingHeart(_))
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
let entity = self.world.block_entities.remove(&key);
|
||||
self.world.block_names.remove(&key);
|
||||
let name = self.facts.get(old).name.clone();
|
||||
let kind = removal::pre_remove(&name);
|
||||
let mut neighbour_updates = 0;
|
||||
if side_effects {
|
||||
match kind {
|
||||
PreRemove::Contents { slots, .. } => {
|
||||
let items = entity.as_ref().map_or(&[][..], BlockEntity::slots);
|
||||
for slot in 0..slots {
|
||||
let stack = items.get(slot).cloned().flatten();
|
||||
self.drop_item_stack(pos, stack);
|
||||
}
|
||||
}
|
||||
PreRemove::Campfire => {
|
||||
for _ in 0..4 {
|
||||
self.drop_item_stack(pos, None);
|
||||
}
|
||||
}
|
||||
PreRemove::Jukebox => {
|
||||
// popOutTheItem: removeTheItem stops a playing song (its
|
||||
// events and a neighbour update), the record pops, and
|
||||
// onSongChanged updates the neighbours again.
|
||||
if let Some(BlockEntity::Jukebox(j)) = &entity
|
||||
&& let Some(record) = j.record.clone()
|
||||
{
|
||||
if j.playing {
|
||||
self.jukebox_stopped(pos, old);
|
||||
neighbour_updates += 1;
|
||||
}
|
||||
let at = removal::jukebox_pop_position(&mut self.world.random, pos);
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: record,
|
||||
pos: at,
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
neighbour_updates += 1;
|
||||
}
|
||||
}
|
||||
PreRemove::Lectern => {
|
||||
let props = self.registry.state(old).map(|s| &s.properties);
|
||||
let has_book = props
|
||||
.and_then(|p| p.get("has_book"))
|
||||
.is_some_and(|v| v == "true");
|
||||
let step = match props.and_then(|p| p.get("facing")).map(String::as_str) {
|
||||
Some("north") => [0, -1],
|
||||
Some("south") => [0, 1],
|
||||
Some("west") => [-1, 0],
|
||||
_ => [1, 0],
|
||||
};
|
||||
if has_book
|
||||
&& let Some(BlockEntity::Lectern(l)) = &entity
|
||||
&& let Some(book) = l.book.clone()
|
||||
{
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: book,
|
||||
pos: removal::lectern_book_position(pos, step),
|
||||
motion: None,
|
||||
delay: 10,
|
||||
});
|
||||
}
|
||||
}
|
||||
PreRemove::ShulkerBox
|
||||
| PreRemove::SculkShrieker
|
||||
| PreRemove::CreakingHeart
|
||||
| PreRemove::Beacon
|
||||
| PreRemove::Nothing => {}
|
||||
}
|
||||
}
|
||||
// BlockEntity.setRemoved: a jukebox always reports its song stopping,
|
||||
// a beacon plays its deactivation.
|
||||
match kind {
|
||||
PreRemove::Jukebox => self.jukebox_stopped(pos, old),
|
||||
PreRemove::Beacon => self.events.push(LevelEvent::Sound {
|
||||
pos,
|
||||
sound: "minecraft:block.beacon.deactivate".into(),
|
||||
volume: 1.0,
|
||||
pitch: 1.0,
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(entity) = entity {
|
||||
self.spill.removed.push(([pos.x, pos.y, pos.z], entity));
|
||||
}
|
||||
neighbour_updates
|
||||
}
|
||||
/// The jukebox's `JUKEBOX_STOP_PLAY` game event and level event 1011.
|
||||
fn jukebox_stopped(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
self.events.push(LevelEvent::GameEvent {
|
||||
pos,
|
||||
event: "minecraft:jukebox_stop_play",
|
||||
state: Some(state),
|
||||
});
|
||||
self.events.push(LevelEvent::LevelEvent {
|
||||
id: 1011,
|
||||
pos,
|
||||
data: 0,
|
||||
});
|
||||
}
|
||||
/// A block entity Horizon keeps as it was loaded (campfires, decorated
|
||||
/// pots, chiseled bookshelves, shelves): its items spill as vanilla's do.
|
||||
fn remove_saved_entity(
|
||||
&mut self,
|
||||
pos: BlockPos,
|
||||
old: BlockStateId,
|
||||
side_effects: bool,
|
||||
) -> bool {
|
||||
use horizon_world::nbt::Tag;
|
||||
let chunk_key = (pos.x >> 4, pos.z >> 4);
|
||||
let at = |t: &Tag| {
|
||||
let int = |k: &str| match t.get(k) {
|
||||
Some(Tag::Int(v)) => Some(*v),
|
||||
_ => None,
|
||||
};
|
||||
int("x") == Some(pos.x) && int("y") == Some(pos.y) && int("z") == Some(pos.z)
|
||||
};
|
||||
let Some(chunk) = self.world.chunks.get_mut(&chunk_key) else {
|
||||
return false;
|
||||
};
|
||||
let Some(saved) = chunk.saved.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let Some(index) = saved.block_entities.iter().position(at) else {
|
||||
return false;
|
||||
};
|
||||
let chunk = std::sync::Arc::make_mut(chunk);
|
||||
let Some(saved) = chunk.saved.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let tag = std::sync::Arc::make_mut(saved).block_entities.remove(index);
|
||||
if !side_effects {
|
||||
return true;
|
||||
}
|
||||
let name = self.facts.get(old).name.clone();
|
||||
let items = match removal::pre_remove(&name) {
|
||||
PreRemove::Contents { slots, .. } if &*name == "minecraft:decorated_pot" => {
|
||||
let mut items = vec![None; slots];
|
||||
items[0] = tag
|
||||
.get("item")
|
||||
.and_then(horizon_client::save::item_from_nbt);
|
||||
items
|
||||
}
|
||||
PreRemove::Contents { slots, .. } => {
|
||||
horizon_client::save::decode_items(tag.get("Items"), slots)
|
||||
}
|
||||
PreRemove::Campfire => horizon_client::save::decode_items(tag.get("Items"), 4),
|
||||
_ => return true,
|
||||
};
|
||||
for stack in items {
|
||||
self.drop_item_stack(pos, stack);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `Containers.dropItemStack` of one slot (an empty one still draws its spot).
|
||||
fn drop_item_stack(&mut self, pos: BlockPos, stack: Option<ItemStack>) {
|
||||
let count = stack.as_ref().map_or(0, |s| s.count);
|
||||
for piece in removal::drop_item_stack(&mut self.world.random, pos, count) {
|
||||
let Some(stack) = &stack else { break };
|
||||
self.spill.spawns.push(Spawn {
|
||||
stack: ItemStack {
|
||||
count: piece.count,
|
||||
..stack.clone()
|
||||
},
|
||||
pos: piece.pos,
|
||||
motion: Some(piece.motion),
|
||||
delay: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Add the item entities the block behaviour spawned and follow up on the
|
||||
/// block entities it removed.
|
||||
pub(super) fn flush_spill(&mut self) {
|
||||
if self.spill.spawns.is_empty()
|
||||
&& self.spill.removed.is_empty()
|
||||
&& self.spill.orbs.is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let spill = std::mem::take(&mut self.spill);
|
||||
for s in spill.spawns {
|
||||
let motion = s.motion.unwrap_or_else(new_item_motion);
|
||||
self.spawn_item(s.stack, s.pos, motion, s.delay);
|
||||
}
|
||||
for (at, value) in spill.orbs {
|
||||
self.add_orb(at, value);
|
||||
}
|
||||
for (pos, entity) in spill.removed {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
if matches!(entity, BlockEntity::Jukebox(_)) {
|
||||
self.jukebox_removed(pos);
|
||||
}
|
||||
if self.container == Some(key) {
|
||||
self.container_opener_event(key, false);
|
||||
self.container = None;
|
||||
self.screen = Screen::Playing;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,58 +8,6 @@ pub(super) fn is_shulker_box(name: &str) -> bool {
|
||||
name.ends_with("shulker_box")
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// Block-entity contents on removal: shulker boxes keep theirs for the
|
||||
/// dropped box (`copy_components`), other containers spill them.
|
||||
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
|
||||
if let Some(name) = self
|
||||
.world
|
||||
.block_names
|
||||
.remove(&(pos[0], pos[1], pos[2]))
|
||||
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
|
||||
{
|
||||
self.pending_names.insert(pos, (block.to_owned(), name));
|
||||
}
|
||||
if let BlockEntity::Banner(banner) = entity {
|
||||
self.pending_banner.insert(pos, banner);
|
||||
return;
|
||||
}
|
||||
if is_shulker_box(block) {
|
||||
if let BlockEntity::Chest(items) = entity {
|
||||
let kept = items
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| Some((i as u8, s?)))
|
||||
.collect();
|
||||
self.pending_shulker.insert(pos, kept);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for stack in entity.contents() {
|
||||
self.pop_resource(pos, stack);
|
||||
}
|
||||
}
|
||||
/// The contents a shulker box dropped at `pos` carries.
|
||||
pub(super) fn attach_shulker_contents(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if !is_shulker_box(&stack.item) {
|
||||
return;
|
||||
}
|
||||
if let Some(contents) = self.pending_shulker.remove(&pos)
|
||||
&& !contents.is_empty()
|
||||
{
|
||||
stack.data_mut().container = contents;
|
||||
}
|
||||
}
|
||||
/// The custom name a broken container drops with (`copy_components`).
|
||||
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
|
||||
if self
|
||||
.pending_names
|
||||
.get(&pos)
|
||||
.is_some_and(|(item, _)| **item == *stack.item)
|
||||
&& let Some((_, name)) = self.pending_names.remove(&pos)
|
||||
{
|
||||
stack.data_mut().custom_name = Some(name);
|
||||
}
|
||||
}
|
||||
/// A placed container takes the item's custom name.
|
||||
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
|
||||
@@ -1,52 +1,58 @@
|
||||
//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): sounds the
|
||||
//! audio engine plays feed it, the HUD draws it.
|
||||
//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): the sound
|
||||
//! engine reports the sounds it plays while the overlay listens, the HUD
|
||||
//! renders it (which starts or stops the listening as the "Show Subtitles"
|
||||
//! option says).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::HudBatch,
|
||||
subtitles::{self, SubtitleOverlay},
|
||||
hud_layout,
|
||||
hud_overlays::{SubtitleFrame, SubtitleOverlay, now_ms},
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SubtitleState {
|
||||
overlay: SubtitleOverlay,
|
||||
listening: bool,
|
||||
overlay: RefCell<SubtitleOverlay>,
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// Feed the sounds played since the last tick to the overlay while the
|
||||
/// `showSubtitles` option is on.
|
||||
/// Feed the sounds the engine reported since the last tick
|
||||
/// (`SoundEventListener.onPlaySound`) while the overlay listens.
|
||||
pub(super) fn tick_subtitles(&mut self) {
|
||||
let on = self.settings.show_subtitles;
|
||||
self.audio.record_heard = on;
|
||||
if !on {
|
||||
if self.subtitles.listening {
|
||||
self.subtitles.listening = false;
|
||||
self.subtitles.overlay.clear();
|
||||
}
|
||||
self.audio.take_heard();
|
||||
let mut overlay = self.subtitles.overlay.borrow_mut();
|
||||
let listening = overlay.listening();
|
||||
self.audio.record_heard = listening;
|
||||
let heard = self.audio.take_heard();
|
||||
if !listening {
|
||||
return;
|
||||
}
|
||||
self.subtitles.listening = true;
|
||||
let now = subtitles::now_ms();
|
||||
let listener = self.audio.listener;
|
||||
for heard in self.audio.take_heard() {
|
||||
self.subtitles.overlay.on_play(&heard, listener, now);
|
||||
let now = now_ms();
|
||||
for h in heard {
|
||||
let at = h.at.unwrap_or(self.audio.listener);
|
||||
overlay.on_play(Some(&h.subtitle), at, h.range, h.looping, now);
|
||||
}
|
||||
self.subtitles
|
||||
.overlay
|
||||
.purge(f64::from(self.settings.notification_display_time), now);
|
||||
}
|
||||
pub(super) fn draw_subtitles(&self, batch: &mut HudBatch) {
|
||||
if !self.settings.show_subtitles {
|
||||
// Hud.extractRenderState: hidden with the rest of the HUD (F1).
|
||||
if self.ui.hide_gui {
|
||||
return;
|
||||
}
|
||||
self.subtitles.overlay.draw(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
self.audio.listener,
|
||||
self.yaw,
|
||||
self.pitch,
|
||||
f64::from(self.settings.notification_display_time),
|
||||
subtitles::now_ms(),
|
||||
);
|
||||
let v = &self.view;
|
||||
let frame = SubtitleFrame {
|
||||
show: self.settings.show_subtitles,
|
||||
position: v.position,
|
||||
forward: v.forwards.map(f64::from),
|
||||
up: v.up.map(f64::from),
|
||||
multiplier: f64::from(self.settings.notification_display_time),
|
||||
background: self.settings.text_background(0.8),
|
||||
width: batch.width as i32,
|
||||
height: batch.height as i32,
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
let draws = self
|
||||
.subtitles
|
||||
.overlay
|
||||
.borrow_mut()
|
||||
.extract(&frame, &atlas.font, now_ms());
|
||||
hud_layout::paint(batch, atlas, &draws);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,169 +1,69 @@
|
||||
//! Titles, subtitles and the action bar (`Gui.setTitle`, `setSubtitle`,
|
||||
//! `setTimes`, `setOverlayMessage`, `extractTitle`, `extractOverlayMessage`).
|
||||
//! Titles, the action bar and the selected item name: the state and layout
|
||||
//! live in `hud_overlays` (`Titles`, `ToolHighlight`); this feeds and draws them.
|
||||
use super::Game;
|
||||
pub(super) use horizon_client::hud_overlays::Titles;
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
text::Text,
|
||||
hud::HudBatch,
|
||||
hud_layout,
|
||||
hud_overlays::HeldName,
|
||||
text::{self, Text},
|
||||
};
|
||||
|
||||
pub(super) struct Titles {
|
||||
pub title: Option<Text>,
|
||||
pub subtitle: Option<Text>,
|
||||
pub time: i32,
|
||||
pub fade_in: i32,
|
||||
pub stay: i32,
|
||||
pub fade_out: i32,
|
||||
pub overlay: Option<Text>,
|
||||
pub overlay_time: i32,
|
||||
/// `animateOverlayMessageColor`: the "Now Playing" rainbow.
|
||||
pub overlay_animated: bool,
|
||||
}
|
||||
impl Default for Titles {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: None,
|
||||
subtitle: None,
|
||||
time: 0,
|
||||
fade_in: 10,
|
||||
stay: 70,
|
||||
fade_out: 20,
|
||||
overlay: None,
|
||||
overlay_time: 0,
|
||||
overlay_animated: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Titles {
|
||||
pub fn set_title(&mut self, title: Text) {
|
||||
self.title = Some(title);
|
||||
self.time = self.fade_in + self.stay + self.fade_out;
|
||||
}
|
||||
pub fn set_times(&mut self, fade_in: i32, stay: i32, fade_out: i32) {
|
||||
if fade_in >= 0 {
|
||||
self.fade_in = fade_in;
|
||||
}
|
||||
if stay >= 0 {
|
||||
self.stay = stay;
|
||||
}
|
||||
if fade_out >= 0 {
|
||||
self.fade_out = fade_out;
|
||||
}
|
||||
if self.time > 0 {
|
||||
self.time = self.fade_in + self.stay + self.fade_out;
|
||||
}
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.title = None;
|
||||
self.subtitle = None;
|
||||
self.time = 0;
|
||||
}
|
||||
pub fn reset_times(&mut self) {
|
||||
(self.fade_in, self.stay, self.fade_out) = (10, 70, 20);
|
||||
}
|
||||
pub fn set_overlay(&mut self, text: Text) {
|
||||
self.overlay = Some(text);
|
||||
self.overlay_time = 60;
|
||||
self.overlay_animated = false;
|
||||
}
|
||||
/// Gui.tick.
|
||||
pub fn tick(&mut self) {
|
||||
if self.overlay_time > 0 {
|
||||
self.overlay_time -= 1;
|
||||
}
|
||||
if self.time > 0 {
|
||||
self.time -= 1;
|
||||
if self.time <= 0 {
|
||||
self.title = None;
|
||||
self.subtitle = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `Hud.extractOverlayMessage` and `extractTitle`.
|
||||
pub(super) fn draw_titles(&self, batch: &mut HudBatch) {
|
||||
let t = &self.titles;
|
||||
let (w, h) = (batch.width as i32, batch.height as i32);
|
||||
let partial = self.clock.fraction() as f32;
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
if let Some(text) = &t.overlay
|
||||
&& t.overlay_time > 0
|
||||
{
|
||||
let ticks = t.overlay_time as f32 - partial;
|
||||
let alpha = ((ticks * 255.0 / 20.0) as i32).min(255);
|
||||
if alpha > 0 {
|
||||
let width = atlas.font.width_text(text);
|
||||
let color = if t.overlay_animated {
|
||||
let [r, g, b] = hsv_to_rgb(ticks / 50.0, 0.7, 0.6);
|
||||
rgba(r, g, b, alpha as u8)
|
||||
} else {
|
||||
rgba(255, 255, 255, alpha as u8)
|
||||
};
|
||||
batch.text_posed(
|
||||
atlas,
|
||||
text,
|
||||
[-(width / 2.0).trunc(), -4.0],
|
||||
color,
|
||||
1.0,
|
||||
[(w / 2.0).trunc(), (h - 68.0).trunc()],
|
||||
);
|
||||
}
|
||||
let background = self.settings.text_background(0.0);
|
||||
let font = &self.res.atlas.font;
|
||||
let mut draws = self.titles.overlay_message(w, h, partial, font, background);
|
||||
draws.extend(self.titles.title(w, h, partial, font, background));
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
/// The selected stack as `Hud.tick` compares it for the name highlight.
|
||||
fn held_name(&self) -> Option<HeldName> {
|
||||
let stack = self.inventory.get(self.selected)?.as_ref()?;
|
||||
let custom = stack.custom_name();
|
||||
// ItemStack.getRarity: enchanting raises common and uncommon to rare
|
||||
// and rare to epic.
|
||||
let mut rarity = self.item_rarity(&stack.item);
|
||||
if !stack.enchantments().is_empty() {
|
||||
rarity = match rarity.as_str() {
|
||||
"common" | "uncommon" => "rare".into(),
|
||||
"rare" => "epic".into(),
|
||||
_ => rarity,
|
||||
};
|
||||
}
|
||||
let Some(title) = &t.title else { return };
|
||||
if t.time <= 0 {
|
||||
return;
|
||||
}
|
||||
let ticks = t.time as f32 - partial;
|
||||
let mut alpha = 255;
|
||||
if t.time > t.fade_out + t.stay {
|
||||
let time = (t.fade_in + t.stay + t.fade_out) as f32 - ticks;
|
||||
alpha = (time * 255.0 / t.fade_in.max(1) as f32) as i32;
|
||||
}
|
||||
if t.time <= t.fade_out {
|
||||
alpha = (ticks * 255.0 / t.fade_out.max(1) as f32) as i32;
|
||||
}
|
||||
let alpha = alpha.clamp(0, 255);
|
||||
if alpha == 0 {
|
||||
return;
|
||||
}
|
||||
let color = rgba(255, 255, 255, alpha as u8);
|
||||
let origin = [(w / 2.0).trunc(), (h / 2.0).trunc()];
|
||||
let width = atlas.font.width_text(title);
|
||||
batch.text_posed(
|
||||
atlas,
|
||||
title,
|
||||
[-(width / 2.0).trunc(), -10.0],
|
||||
color,
|
||||
4.0,
|
||||
origin,
|
||||
Some(HeldName {
|
||||
item: stack.item.to_string(),
|
||||
hover_name: Text::literal(
|
||||
custom.map_or_else(|| self.res.names.item(&stack.item), str::to_owned),
|
||||
),
|
||||
rarity_color: match rarity.as_str() {
|
||||
"uncommon" => text::YELLOW,
|
||||
"rare" => text::AQUA,
|
||||
"epic" => text::LIGHT_PURPLE,
|
||||
_ => text::WHITE,
|
||||
},
|
||||
custom_name: custom.is_some(),
|
||||
})
|
||||
}
|
||||
/// The title, action bar and selected-item parts of `Hud.tick`.
|
||||
pub(super) fn tick_hud(&mut self) {
|
||||
self.titles.tick();
|
||||
let held = self.held_name();
|
||||
self.tool_highlight
|
||||
.tick(held, f64::from(self.settings.notification_display_time));
|
||||
}
|
||||
/// `Hud.extractSelectedItemName`.
|
||||
pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, can_hurt: bool) {
|
||||
let draws = self.tool_highlight.draw(
|
||||
batch.width as i32,
|
||||
batch.height as i32,
|
||||
can_hurt,
|
||||
&self.res.atlas.font,
|
||||
self.settings.text_background(0.0),
|
||||
);
|
||||
if let Some(sub) = &t.subtitle {
|
||||
let width = atlas.font.width_text(sub);
|
||||
batch.text_posed(
|
||||
atlas,
|
||||
sub,
|
||||
[-(width / 2.0).trunc(), 5.0],
|
||||
color,
|
||||
2.0,
|
||||
origin,
|
||||
);
|
||||
}
|
||||
hud_layout::paint(batch, &self.res.atlas, &draws);
|
||||
}
|
||||
}
|
||||
/// `Mth.hsvToRgb`.
|
||||
fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [u8; 3] {
|
||||
let h = (hue * 6.0) as i32 % 6;
|
||||
let f = hue * 6.0 - (hue * 6.0).floor();
|
||||
let p = value * (1.0 - saturation);
|
||||
let q = value * (1.0 - f * saturation);
|
||||
let t = value * (1.0 - (1.0 - f) * saturation);
|
||||
let (r, g, b) = match h {
|
||||
0 => (value, t, p),
|
||||
1 => (q, value, p),
|
||||
2 => (p, value, t),
|
||||
3 => (p, q, value),
|
||||
4 => (t, p, value),
|
||||
_ => (value, p, q),
|
||||
};
|
||||
let c = |v: f32| (v * 255.0).clamp(0.0, 255.0) as u8;
|
||||
[c(r), c(g), c(b)]
|
||||
}
|
||||
|
||||
@@ -184,8 +184,10 @@ impl Game<'_> {
|
||||
mob: Some(m.id),
|
||||
name: m.custom_name.clone(),
|
||||
};
|
||||
// setTradingPlayer: a wandering trader stands still while trading.
|
||||
self.mobs[index].extra.flag2 = species == Species::WanderingTrader;
|
||||
// setTradingPlayer: a wandering trader stands still while trading, a
|
||||
// villager's brain follows and looks at the player
|
||||
// (LookAndFollowTradingPlayerSink).
|
||||
self.mobs[index].extra.flag2 = true;
|
||||
self.open_merchant_state(state);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
//! its boss bar, and its skulls hitting and exploding.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
hud_overlays,
|
||||
mobs::{Damage, DamageKind, Species, Who},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
text::Text,
|
||||
};
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -69,12 +70,11 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The wither boss bars (purple, below the dragon's), within range.
|
||||
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 {
|
||||
/// The wither boss bars (purple), within range.
|
||||
pub(super) fn wither_bars(&self, bars: &mut Vec<hud_overlays::BossBar>) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return y;
|
||||
return;
|
||||
};
|
||||
let atlas = &self.res.atlas;
|
||||
for m in self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -83,36 +83,22 @@ impl Game<'_> {
|
||||
if m.position.distance_squared(p.position) > 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
let x = (batch.width / 2.0 - 91.0).floor();
|
||||
let progress = if m.extra.counter > 0 {
|
||||
1.0 - m.extra.counter as f32 / horizon_client::mobs::wither::INVULNERABLE as f32
|
||||
} else {
|
||||
(m.health / m.attrs.max_health).clamp(0.0, 1.0)
|
||||
};
|
||||
batch.sprite(atlas, "gui/sprites/boss_bar/purple_background", x, y);
|
||||
batch.sprite_part(
|
||||
atlas,
|
||||
"gui/sprites/boss_bar/purple_progress",
|
||||
x,
|
||||
y,
|
||||
progress,
|
||||
);
|
||||
let name = m
|
||||
.custom_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| self.translate("entity.minecraft.wither", "Wither"));
|
||||
let w = HudBatch::text_width(atlas, &name);
|
||||
batch.text(
|
||||
atlas,
|
||||
&name,
|
||||
(batch.width / 2.0 - w / 2.0).floor(),
|
||||
y - 9.0,
|
||||
rgba(255, 255, 255, 255),
|
||||
true,
|
||||
);
|
||||
y += 19.0;
|
||||
bars.push(hud_overlays::BossBar {
|
||||
name: Text::literal(name),
|
||||
progress,
|
||||
color: 5,
|
||||
overlay: 0,
|
||||
});
|
||||
}
|
||||
y
|
||||
}
|
||||
pub(super) fn wither_near(&self) -> bool {
|
||||
self.player.as_ref().is_some_and(|p| {
|
||||
|
||||
@@ -26,6 +26,10 @@ struct Globals {
|
||||
sun: [f32; 4],
|
||||
/// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), w: unused.
|
||||
fog_ends: [f32; 4],
|
||||
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png.
|
||||
end_portal_sprites: [[f32; 4]; 2],
|
||||
/// x: vanilla's `GameTime` uniform; yzw unused.
|
||||
time: [f32; 4],
|
||||
}
|
||||
pub type SectionKey = (i32, i32, i32);
|
||||
struct SectionGpu {
|
||||
@@ -77,6 +81,11 @@ pub struct Frame<'a> {
|
||||
/// Full-screen camera effects drawn over the world and hand, under the HUD.
|
||||
pub screen: &'a [crate::screen_effects::ScreenQuad],
|
||||
pub game_time: f32,
|
||||
/// `GlobalSettingsUniform` GameTime: (game time % 24000 + partial tick) / 24000.
|
||||
pub shader_game_time: f32,
|
||||
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png
|
||||
/// (`rendertype_end_portal`'s Sampler0 and Sampler1).
|
||||
pub end_portal_sprites: [[f32; 4]; 2],
|
||||
pub ticks: u64,
|
||||
/// The darkness effect on the lightmap: the brightness it takes off the
|
||||
/// gamma option and the pulsing scale subtracted from the light.
|
||||
@@ -1281,6 +1290,8 @@ impl Renderer {
|
||||
if frame.dark_disc { 1.0 } else { 0.0 },
|
||||
0.0,
|
||||
],
|
||||
end_portal_sprites: frame.end_portal_sprites,
|
||||
time: [frame.shader_game_time, 0.0, 0.0, 0.0],
|
||||
};
|
||||
self.queue
|
||||
.write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));
|
||||
|
||||
@@ -1,26 +1,109 @@
|
||||
//! Layout of vanilla's `Hud` decorations as draw calls (`GuiGraphicsExtractor`
|
||||
//! blits and text): the hotbar with its selection, off-hand slot, items and
|
||||
//! Layout of vanilla's `Hud` as draw calls (`GuiGraphicsExtractor` blits,
|
||||
//! fills and text): the hotbar with its selection, off-hand slot, items and
|
||||
//! attack indicator, the crosshair, armour, hearts, food, air bubbles, mount
|
||||
//! hearts and the experience bar and level. Computed without drawing so the
|
||||
//! parity fixture can compare them with the vanilla client.
|
||||
//! hearts and the experience bar, plus the draw-call types and colour
|
||||
//! helpers the other layouts share (`hud_overlays`, `chat`). Computed without
|
||||
//! drawing so the parity fixture can compare them with the vanilla client.
|
||||
use crate::{font::Font, text::Text};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// A `Matrix3x2fStack` operation applied to a copy of the current pose.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum PoseOp {
|
||||
Translate(f32, f32),
|
||||
Scale(f32, f32),
|
||||
}
|
||||
|
||||
/// A JOML `Matrix3x2f` as `[m00, m01, m10, m11, m20, m21]`.
|
||||
pub type Pose = [f32; 6];
|
||||
pub const IDENTITY: Pose = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// Applies `op` like JOML's `translate` / `scale` (same float order).
|
||||
pub fn pose_apply(m: &mut Pose, op: PoseOp) {
|
||||
match op {
|
||||
PoseOp::Translate(x, y) => {
|
||||
m[4] += m[0] * x + m[2] * y;
|
||||
m[5] += m[1] * x + m[3] * y;
|
||||
}
|
||||
PoseOp::Scale(x, y) => {
|
||||
m[0] *= x;
|
||||
m[1] *= x;
|
||||
m[2] *= y;
|
||||
m[3] *= y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The render pipeline of a texture blit.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Blend {
|
||||
/// `GUI_TEXTURED`.
|
||||
Textured,
|
||||
/// `VIGNETTE`: `dst * (1 - src)`.
|
||||
Vignette,
|
||||
/// `GUI_NAUSEA_OVERLAY`: additive.
|
||||
Nausea,
|
||||
}
|
||||
impl Blend {
|
||||
pub fn pipeline(self) -> &'static str {
|
||||
match self {
|
||||
Blend::Textured => "pipeline/gui_textured",
|
||||
Blend::Vignette => "pipeline/vignette",
|
||||
Blend::Nausea => "pipeline/gui_nausea_overlay",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `GuiGraphicsExtractor` call.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GuiDraw {
|
||||
/// `blitSprite(sprite, x, y, w, h)`; `region` = (spriteW, spriteH, u, v)
|
||||
/// for the partial overload.
|
||||
/// `blitSprite(sprite, x, y, w, h, color)`; `region` = (spriteW,
|
||||
/// spriteH, u, v) for the partial overload.
|
||||
Sprite {
|
||||
sprite: &'static str,
|
||||
sprite: Cow<'static, str>,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
region: Option<[i32; 4]>,
|
||||
color: u32,
|
||||
},
|
||||
/// `blitSprite(pipeline, TextureAtlasSprite, ...)` with a block atlas
|
||||
/// sprite (the nether portal overlay).
|
||||
AtlasSprite {
|
||||
sprite: Cow<'static, str>,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
color: u32,
|
||||
},
|
||||
/// `blit(pipeline, texture, x, y, u, v, w, h, srcW, srcH, texW, texH,
|
||||
/// color)`; `texture` is the path under `textures/` without `.png`.
|
||||
Blit {
|
||||
texture: Cow<'static, str>,
|
||||
blend: Blend,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
uv: [f32; 2],
|
||||
src: [i32; 2],
|
||||
tex: [i32; 2],
|
||||
color: u32,
|
||||
},
|
||||
/// `fill(x0, y0, x1, y1, color)` with the corners sorted.
|
||||
Fill {
|
||||
x0: i32,
|
||||
y0: i32,
|
||||
x1: i32,
|
||||
y1: i32,
|
||||
color: u32,
|
||||
},
|
||||
/// `text(font, text, x, y, argb, dropShadow)`.
|
||||
Text {
|
||||
text: String,
|
||||
text: Text,
|
||||
x: i32,
|
||||
y: i32,
|
||||
color: u32,
|
||||
@@ -36,17 +119,134 @@ pub enum GuiDraw {
|
||||
scale: [f32; 2],
|
||||
pivot: [f32; 2],
|
||||
},
|
||||
/// `pose().pushMatrix()` followed by `ops`.
|
||||
Push(Vec<PoseOp>),
|
||||
/// `pose().popMatrix()`.
|
||||
Pop,
|
||||
}
|
||||
|
||||
pub const WHITE: u32 = 0xFFFF_FFFF;
|
||||
|
||||
fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
|
||||
GuiDraw::Sprite {
|
||||
sprite,
|
||||
sprite: Cow::Borrowed(sprite),
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
region: None,
|
||||
color: WHITE,
|
||||
}
|
||||
}
|
||||
fn region(
|
||||
sprite: &'static str,
|
||||
size: [i32; 2],
|
||||
uv: [i32; 2],
|
||||
at: [i32; 2],
|
||||
w: i32,
|
||||
h: i32,
|
||||
) -> GuiDraw {
|
||||
GuiDraw::Sprite {
|
||||
sprite: Cow::Borrowed(sprite),
|
||||
x: at[0],
|
||||
y: at[1],
|
||||
w,
|
||||
h,
|
||||
region: Some([size[0], size[1], uv[0], uv[1]]),
|
||||
color: WHITE,
|
||||
}
|
||||
}
|
||||
/// `graphics.fill`: the corners are sorted.
|
||||
pub fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: u32) -> GuiDraw {
|
||||
GuiDraw::Fill {
|
||||
x0: x0.min(x1),
|
||||
y0: y0.min(y1),
|
||||
x1: x0.max(x1),
|
||||
y1: y0.max(y1),
|
||||
color,
|
||||
}
|
||||
}
|
||||
/// `graphics.text`: dropped when fully transparent.
|
||||
fn text(out: &mut Vec<GuiDraw>, text: Text, x: i32, y: i32, color: u32, shadow: bool) {
|
||||
if color >> 24 != 0 {
|
||||
out.push(GuiDraw::Text {
|
||||
text,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `Options.getBackgroundColor(float)`: `chat_only` = `backgroundForChatOnly`.
|
||||
pub fn background_color(chat_only: bool, opacity: f64, default: f32) -> u32 {
|
||||
let a = if chat_only { default } else { opacity as f32 };
|
||||
color_from_float(a, 0.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
/// `Mth.floor`.
|
||||
pub fn floor(x: f32) -> i32 {
|
||||
let i = x as i32;
|
||||
if x < i as f32 { i - 1 } else { i }
|
||||
}
|
||||
/// `Mth.ceil`.
|
||||
pub fn ceil(x: f32) -> i32 {
|
||||
let i = x as i32;
|
||||
if x > i as f32 { i + 1 } else { i }
|
||||
}
|
||||
/// `ARGB.as8BitChannel`.
|
||||
pub fn as8(v: f32) -> u32 {
|
||||
floor(v * 255.0) as u32
|
||||
}
|
||||
/// `ARGB.white(float)`.
|
||||
pub fn white(alpha: f32) -> u32 {
|
||||
(as8(alpha) << 24) | 0xFF_FFFF
|
||||
}
|
||||
/// `ARGB.colorFromFloat`.
|
||||
pub fn color_from_float(a: f32, r: f32, g: f32, b: f32) -> u32 {
|
||||
argb(as8(a), as8(r), as8(g), as8(b))
|
||||
}
|
||||
/// `ARGB.color(a, r, g, b)`.
|
||||
pub fn argb(a: u32, r: u32, g: u32, b: u32) -> u32 {
|
||||
(a & 255) << 24 | (r & 255) << 16 | (g & 255) << 8 | (b & 255)
|
||||
}
|
||||
/// `ARGB.multiply`.
|
||||
pub fn multiply(l: u32, r: u32) -> u32 {
|
||||
if l == WHITE {
|
||||
return r;
|
||||
}
|
||||
if r == WHITE {
|
||||
return l;
|
||||
}
|
||||
let c = |s: u32| ((l >> s) & 255) * ((r >> s) & 255) / 255;
|
||||
argb(c(24), c(16), c(8), c(0))
|
||||
}
|
||||
/// `Mth.lerpDiscrete`.
|
||||
pub fn lerp_discrete(alpha: f32, p0: i32, p1: i32) -> i32 {
|
||||
p0 + floor(alpha * (p1 - p0 - 1) as f32) + i32::from(alpha > 0.0)
|
||||
}
|
||||
/// `Mth.hsvToArgb`.
|
||||
pub fn hsv_to_argb(hue: f32, saturation: f32, value: f32, alpha: u32) -> u32 {
|
||||
let h = (hue * 6.0) as i32 % 6;
|
||||
let f = hue * 6.0 - h as f32;
|
||||
let p = value * (1.0 - saturation);
|
||||
let q = value * (1.0 - f * saturation);
|
||||
let t = value * (1.0 - (1.0 - f) * saturation);
|
||||
let (r, g, b) = match h {
|
||||
0 => (value, t, p),
|
||||
1 => (q, value, p),
|
||||
2 => (p, value, t),
|
||||
3 => (p, q, value),
|
||||
4 => (t, p, value),
|
||||
_ => (value, p, q),
|
||||
};
|
||||
let c = |v: f32| ((v * 255.0) as i32).clamp(0, 255) as u32;
|
||||
argb(alpha, c(r), c(g), c(b))
|
||||
}
|
||||
/// `Font.width` of styled text.
|
||||
pub fn width(font: &Font, t: &Text) -> i32 {
|
||||
font.width_text(t) as i32
|
||||
}
|
||||
|
||||
/// `Hud.extractItemHotbar` inputs.
|
||||
pub struct HotbarInputs {
|
||||
@@ -153,14 +353,14 @@ pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec<GuiDraw> {
|
||||
18,
|
||||
18,
|
||||
));
|
||||
out.push(GuiDraw::Sprite {
|
||||
sprite: "hud/hotbar_attack_indicator_progress",
|
||||
x,
|
||||
y: y + 18 - progress,
|
||||
w: 18,
|
||||
h: progress,
|
||||
region: Some([18, 18, 0, 18 - progress]),
|
||||
});
|
||||
out.push(region(
|
||||
"hud/hotbar_attack_indicator_progress",
|
||||
[18, 18],
|
||||
[0, 18 - progress],
|
||||
[x, y + 18 - progress],
|
||||
18,
|
||||
progress,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -183,14 +383,14 @@ pub fn crosshair(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw
|
||||
16,
|
||||
4,
|
||||
));
|
||||
out.push(GuiDraw::Sprite {
|
||||
sprite: "hud/crosshair_attack_indicator_progress",
|
||||
x,
|
||||
y,
|
||||
w: progress,
|
||||
h: 4,
|
||||
region: Some([16, 4, 0, 0]),
|
||||
});
|
||||
out.push(region(
|
||||
"hud/crosshair_attack_indicator_progress",
|
||||
[16, 4],
|
||||
[0, 0],
|
||||
[x, y],
|
||||
progress,
|
||||
4,
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -212,14 +412,14 @@ pub fn experience(
|
||||
let filled = (progress * 183.0) as i32;
|
||||
out.push(sprite("hud/experience_bar_background", left, top, 182, 5));
|
||||
if filled > 0 {
|
||||
out.push(GuiDraw::Sprite {
|
||||
sprite: "hud/experience_bar_progress",
|
||||
x: left,
|
||||
y: top,
|
||||
w: filled,
|
||||
h: 5,
|
||||
region: Some([182, 5, 0, 0]),
|
||||
});
|
||||
out.push(region(
|
||||
"hud/experience_bar_progress",
|
||||
[182, 5],
|
||||
[0, 0],
|
||||
[left, top],
|
||||
filled,
|
||||
5,
|
||||
));
|
||||
}
|
||||
}
|
||||
if level > 0 {
|
||||
@@ -227,21 +427,16 @@ pub fn experience(
|
||||
let x = (w - width(&text)) / 2;
|
||||
let y = h - 24 - 9 - 2;
|
||||
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
|
||||
out.push(GuiDraw::Text {
|
||||
text: text.clone(),
|
||||
x: x + dx,
|
||||
y: y + dy,
|
||||
color: 0xFF00_0000,
|
||||
shadow: false,
|
||||
});
|
||||
self::text(
|
||||
&mut out,
|
||||
Text::literal(&text),
|
||||
x + dx,
|
||||
y + dy,
|
||||
0xFF00_0000,
|
||||
false,
|
||||
);
|
||||
}
|
||||
out.push(GuiDraw::Text {
|
||||
text,
|
||||
x,
|
||||
y,
|
||||
color: 0xFF80_FF20,
|
||||
shadow: false,
|
||||
});
|
||||
self::text(&mut out, Text::literal(text), x, y, 0xFF80_FF20, false);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -394,12 +589,6 @@ fn heart(
|
||||
table[usize::from(hardcore) * 4 + usize::from(half) * 2 + usize::from(blink)]
|
||||
}
|
||||
|
||||
fn ceil(x: f32) -> i32 {
|
||||
// Mth.ceil.
|
||||
let i = x as i32;
|
||||
if x > i as f32 { i + 1 } else { i }
|
||||
}
|
||||
|
||||
impl HealthHud {
|
||||
/// `Hud.extractPlayerHealth` for a screen of `w` x `h` GUI pixels.
|
||||
pub fn layout(&mut self, i: &HealthInputs, w: i32, h: i32) -> Vec<GuiDraw> {
|
||||
@@ -554,10 +743,14 @@ impl HealthHud {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the sprite and text calls with the HUD batch; items are left to the
|
||||
/// caller (they need the item renderer).
|
||||
/// Draws the calls with the HUD batch under their poses; items are left to
|
||||
/// the caller (they need the item renderer) and so are the vignette and
|
||||
/// nausea blits (their blending needs the screen-effect pipeline).
|
||||
pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, draws: &[GuiDraw]) {
|
||||
let mut stack = vec![IDENTITY];
|
||||
for d in draws {
|
||||
let start = batch.vertices.len();
|
||||
let pose = *stack.last().unwrap_or(&IDENTITY);
|
||||
match d {
|
||||
GuiDraw::Sprite {
|
||||
sprite,
|
||||
@@ -566,6 +759,7 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
|
||||
w,
|
||||
h,
|
||||
region,
|
||||
color,
|
||||
} => {
|
||||
let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied()
|
||||
else {
|
||||
@@ -580,7 +774,66 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
|
||||
r.u0 = u0;
|
||||
r.v0 = v0;
|
||||
}
|
||||
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, u32::MAX);
|
||||
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
|
||||
}
|
||||
GuiDraw::AtlasSprite {
|
||||
sprite,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color,
|
||||
} => {
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
sprite,
|
||||
*x as f32,
|
||||
*y as f32,
|
||||
*w as f32,
|
||||
*h as f32,
|
||||
abgr(*color),
|
||||
);
|
||||
}
|
||||
GuiDraw::Blit {
|
||||
texture,
|
||||
blend: Blend::Textured,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
uv,
|
||||
src,
|
||||
tex,
|
||||
color,
|
||||
} => {
|
||||
let Some(mut r) = atlas.sprites.get(texture.as_ref()).copied() else {
|
||||
continue;
|
||||
};
|
||||
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
|
||||
let u0 = r.u0 + du * uv[0] / tex[0] as f32;
|
||||
let v0 = r.v0 + dv * uv[1] / tex[1] as f32;
|
||||
r.u1 = r.u0 + du * (uv[0] + src[0] as f32) / tex[0] as f32;
|
||||
r.v1 = r.v0 + dv * (uv[1] + src[1] as f32) / tex[1] as f32;
|
||||
r.u0 = u0;
|
||||
r.v0 = v0;
|
||||
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
|
||||
}
|
||||
GuiDraw::Blit { .. } | GuiDraw::Item { .. } => {}
|
||||
GuiDraw::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => {
|
||||
batch.fill(
|
||||
atlas,
|
||||
*x0 as f32,
|
||||
*y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
abgr(*color),
|
||||
);
|
||||
}
|
||||
GuiDraw::Text {
|
||||
text,
|
||||
@@ -589,11 +842,35 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
|
||||
color,
|
||||
shadow,
|
||||
} => {
|
||||
let [a, r, g, b] = color.to_be_bytes();
|
||||
let rgba = crate::hud::rgba(r, g, b, a);
|
||||
batch.text(atlas, text, *x as f32, *y as f32, rgba, *shadow);
|
||||
batch.text_styled(atlas, text, *x as f32, *y as f32, abgr(*color), *shadow);
|
||||
}
|
||||
GuiDraw::Push(ops) => {
|
||||
let mut m = pose;
|
||||
for op in ops {
|
||||
pose_apply(&mut m, *op);
|
||||
}
|
||||
stack.push(m);
|
||||
}
|
||||
GuiDraw::Pop => {
|
||||
if stack.len() > 1 {
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
if pose != IDENTITY {
|
||||
for v in &mut batch.vertices[start..] {
|
||||
let [x, y] = v.pos;
|
||||
v.pos = [
|
||||
pose[0] * x + pose[2] * y + pose[4],
|
||||
pose[1] * x + pose[3] * y + pose[5],
|
||||
];
|
||||
}
|
||||
GuiDraw::Item { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An ARGB colour as the HUD batch's packed RGBA.
|
||||
pub fn abgr(color: u32) -> u32 {
|
||||
let [a, r, g, b] = color.to_be_bytes();
|
||||
crate::hud::rgba(r, g, b, a)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -56,6 +56,48 @@ pub struct StackData {
|
||||
pub stew_effects: Vec<(Arc<str>, i32)>,
|
||||
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
|
||||
pub map_post_processing: Option<u8>,
|
||||
/// Components Horizon does not model (lore, custom data, item name,
|
||||
/// max stack size...), kept as their saved values in key order.
|
||||
pub other: Vec<(String, Tag)>,
|
||||
}
|
||||
/// The components `components_tag` writes from modelled fields.
|
||||
const MODELLED: &[&str] = &[
|
||||
"minecraft:banner_patterns",
|
||||
"minecraft:base_color",
|
||||
"minecraft:bundle_contents",
|
||||
"minecraft:charged_projectiles",
|
||||
"minecraft:container",
|
||||
"minecraft:custom_name",
|
||||
"minecraft:damage",
|
||||
"minecraft:dyed_color",
|
||||
"minecraft:enchantments",
|
||||
"minecraft:firework_explosion",
|
||||
"minecraft:fireworks",
|
||||
"minecraft:map_id",
|
||||
"minecraft:map_post_processing",
|
||||
"minecraft:ominous_bottle_amplifier",
|
||||
"minecraft:pot_decorations",
|
||||
"minecraft:potion_contents",
|
||||
"minecraft:repair_cost",
|
||||
"minecraft:stored_enchantments",
|
||||
"minecraft:suspicious_stew_effects",
|
||||
"minecraft:trim",
|
||||
"minecraft:writable_book_content",
|
||||
"minecraft:written_book_content",
|
||||
];
|
||||
impl StackData {
|
||||
/// An unmodelled component's saved value.
|
||||
pub fn other(&self, id: &str) -> Option<&Tag> {
|
||||
self.other.iter().find(|(k, _)| k == id).map(|(_, v)| v)
|
||||
}
|
||||
/// Set (or with None remove) an unmodelled component.
|
||||
pub fn set_other(&mut self, id: &str, value: Option<Tag>) {
|
||||
self.other.retain(|(k, _)| k != id);
|
||||
if let Some(v) = value {
|
||||
self.other.push((id.to_owned(), v));
|
||||
self.other.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
|
||||
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
|
||||
@@ -596,7 +638,17 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
entries.push(("minecraft:container", Tag::List(slots)));
|
||||
}
|
||||
}
|
||||
(!entries.is_empty()).then(|| Tag::compound(entries))
|
||||
let mut out: horizon_world::nbt::Compound = entries
|
||||
.into_iter()
|
||||
.map(|(k, v)| (JavaString::from(k), v))
|
||||
.collect();
|
||||
if let Some(d) = data {
|
||||
for (k, v) in &d.other {
|
||||
out.entry(JavaString::from(k.as_str()))
|
||||
.or_insert_with(|| v.clone());
|
||||
}
|
||||
}
|
||||
(!out.is_empty()).then_some(Tag::Compound(out))
|
||||
}
|
||||
/// Damage and extra components from a stack's `components` compound.
|
||||
pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData>>) {
|
||||
@@ -729,7 +781,23 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
|
||||
Arc::from(t.get("pattern").and_then(string)?.as_str()),
|
||||
))
|
||||
}),
|
||||
other: Vec::new(),
|
||||
};
|
||||
let mut data = data;
|
||||
if let Tag::Compound(map) = c {
|
||||
for (k, v) in map {
|
||||
let key = k.to_string_lossy();
|
||||
let ominous_part = data.ominous_banner
|
||||
&& matches!(
|
||||
key.as_str(),
|
||||
"minecraft:item_name" | "minecraft:rarity" | "minecraft:tooltip_display"
|
||||
);
|
||||
if !MODELLED.contains(&key.as_str()) && !ominous_part {
|
||||
data.other.push((key, v.clone()));
|
||||
}
|
||||
}
|
||||
data.other.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
}
|
||||
(damage, (!data.is_empty()).then(|| Box::new(data)))
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! tool mining rules and block loot tables (`LootTable`/`LootPool` semantics
|
||||
//! for the condition, entry and modifier types used by block drops).
|
||||
use crate::{Result, blocks::BlockFacts};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
@@ -158,6 +158,8 @@ pub struct ItemStack {
|
||||
/// Components beyond count and damage (see `item_data`); None when default.
|
||||
pub extra: Option<Box<crate::item_data::StackData>>,
|
||||
}
|
||||
/// Item ids standing for a loot table's `minecraft:dynamic` entries.
|
||||
const DYNAMIC: &str = "#dynamic:";
|
||||
pub struct Items {
|
||||
pub items: HashMap<Arc<str>, ItemInfo>,
|
||||
pub order: Vec<Arc<str>>,
|
||||
@@ -526,6 +528,22 @@ impl Items {
|
||||
pub fn has_loot_table(&self, id: &str) -> bool {
|
||||
self.loot.contains_key(id)
|
||||
}
|
||||
/// `LootTable.getRandomItems` of an inline table.
|
||||
pub fn inline_loot_table<R: RandomSource>(
|
||||
&self,
|
||||
table: &Value,
|
||||
random: &mut R,
|
||||
) -> Vec<ItemStack> {
|
||||
let empty = BTreeMap::new();
|
||||
let ctx = LootContext {
|
||||
items: self,
|
||||
block: "",
|
||||
properties: &empty,
|
||||
held: None,
|
||||
killed_by_player: false,
|
||||
};
|
||||
ctx.evaluate(table, random)
|
||||
}
|
||||
/// The server random sequence the block's loot table draws from.
|
||||
pub fn block_loot_sequence(
|
||||
&self,
|
||||
@@ -541,12 +559,71 @@ impl Items {
|
||||
.or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}")))
|
||||
}
|
||||
/// Evaluate the block's loot table for a player break without explosions.
|
||||
pub fn block_drops(
|
||||
pub fn block_drops<R: RandomSource>(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut R,
|
||||
) -> Vec<ItemStack> {
|
||||
self.block_drops_in(registry, state, held, random, None)
|
||||
}
|
||||
/// `block_drops` drawing from the table's random sequence when it has one
|
||||
/// (`sequences`: the world's sequences and seed), as BlockState.getDrops.
|
||||
pub fn block_drops_in<R: RandomSource>(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut R,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
self.block_drops_full(registry, state, held, &[], random, sequences)
|
||||
}
|
||||
/// `block_drops` with the block entity's dynamic drops (`LootParams.withDynamicDrop`:
|
||||
/// a decorated pot's sherds) in place of the `minecraft:dynamic` entries.
|
||||
pub fn block_drops_with(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
dynamic: &[ItemStack],
|
||||
random: &mut impl RandomSource,
|
||||
) -> Vec<ItemStack> {
|
||||
self.block_drops_full(registry, state, held, dynamic, random, None)
|
||||
}
|
||||
/// `block_drops_in` with dynamic drops.
|
||||
pub fn block_drops_full(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
dynamic: &[ItemStack],
|
||||
random: &mut impl RandomSource,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
let drops = self.block_drops_raw(registry, state, held, random, sequences);
|
||||
if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) {
|
||||
return drops;
|
||||
}
|
||||
drops
|
||||
.into_iter()
|
||||
.flat_map(|d| {
|
||||
if d.item.starts_with(DYNAMIC) {
|
||||
dynamic.to_vec()
|
||||
} else {
|
||||
vec![d]
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn block_drops_raw(
|
||||
&self,
|
||||
registry: &BlockRegistry,
|
||||
state: BlockStateId,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut impl RandomSource,
|
||||
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
|
||||
) -> Vec<ItemStack> {
|
||||
let Some(block) = registry.state(state) else {
|
||||
return vec![];
|
||||
@@ -564,6 +641,21 @@ impl Items {
|
||||
let Some(table) = table else {
|
||||
return vec![];
|
||||
};
|
||||
// LootTable.getRandomItems draws from the table's random sequence.
|
||||
if let (Some(seq), Some(sequences)) = (
|
||||
table.get("random_sequence").and_then(Value::as_str),
|
||||
sequences,
|
||||
) {
|
||||
let random = sequences.0.get(seq, sequences.1);
|
||||
let ctx = LootContext {
|
||||
items: self,
|
||||
block: &block.name,
|
||||
properties: &block.properties,
|
||||
held,
|
||||
killed_by_player: false,
|
||||
};
|
||||
return ctx.evaluate(table, random);
|
||||
}
|
||||
let ctx = LootContext {
|
||||
items: self,
|
||||
block: &block.name,
|
||||
@@ -575,12 +667,12 @@ impl Items {
|
||||
}
|
||||
/// Evaluate an entity's loot table (`minecraft:entities/<name>`).
|
||||
/// Evaluate any loot table by id (e.g. `minecraft:gameplay/chicken_lay`).
|
||||
pub fn loot_table(
|
||||
pub fn loot_table<R: RandomSource>(
|
||||
&self,
|
||||
id: &str,
|
||||
killed_by_player: bool,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut LegacyRandom,
|
||||
random: &mut R,
|
||||
) -> Vec<ItemStack> {
|
||||
let Some(table) = self.loot.get(id) else {
|
||||
return vec![];
|
||||
@@ -623,12 +715,12 @@ impl Items {
|
||||
};
|
||||
ctx.evaluate(table, random)
|
||||
}
|
||||
pub fn entity_drops(
|
||||
pub fn entity_drops<R: RandomSource>(
|
||||
&self,
|
||||
entity: &str,
|
||||
killed_by_player: bool,
|
||||
held: Option<&ItemStack>,
|
||||
random: &mut LegacyRandom,
|
||||
random: &mut R,
|
||||
) -> Vec<ItemStack> {
|
||||
let name = entity.trim_start_matches("minecraft:");
|
||||
let Some(table) = self.loot.get(&format!("minecraft:entities/{name}")) else {
|
||||
@@ -646,7 +738,7 @@ impl Items {
|
||||
}
|
||||
}
|
||||
impl LootContext<'_> {
|
||||
fn evaluate(&self, table: &Value, random: &mut impl RandomSource) -> Vec<ItemStack> {
|
||||
fn evaluate<R: RandomSource>(&self, table: &Value, random: &mut R) -> Vec<ItemStack> {
|
||||
let ctx = self;
|
||||
let mut out = Vec::new();
|
||||
for pool in table["pools"].as_array().into_iter().flatten() {
|
||||
@@ -686,7 +778,7 @@ impl LootContext<'_> {
|
||||
fn enchantment_level(&self, id: &str) -> u32 {
|
||||
self.held.map_or(0, |h| h.enchantment_level(id))
|
||||
}
|
||||
fn number(&self, v: &Value, random: &mut impl RandomSource) -> f32 {
|
||||
fn number<R: RandomSource>(&self, v: &Value, random: &mut R) -> f32 {
|
||||
match v {
|
||||
Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32,
|
||||
Value::Object(o) => match o
|
||||
@@ -717,7 +809,7 @@ impl LootContext<'_> {
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
fn int_number(&self, v: &Value, random: &mut impl RandomSource) -> i32 {
|
||||
fn int_number<R: RandomSource>(&self, v: &Value, random: &mut R) -> i32 {
|
||||
if let Value::Object(o) = v
|
||||
&& o.get("type")
|
||||
.and_then(Value::as_str)
|
||||
@@ -734,7 +826,7 @@ impl LootContext<'_> {
|
||||
}
|
||||
self.number(v, random).round() as i32
|
||||
}
|
||||
fn condition(&self, c: &Value, random: &mut impl RandomSource) -> bool {
|
||||
fn condition<R: RandomSource>(&self, c: &Value, random: &mut R) -> bool {
|
||||
let (kind, c) = match c {
|
||||
Value::String(s) => (s.as_str(), &Value::Null),
|
||||
Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c),
|
||||
@@ -843,7 +935,7 @@ impl LootContext<'_> {
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
fn conditions(&self, o: &Value, random: &mut impl RandomSource) -> bool {
|
||||
fn conditions<R: RandomSource>(&self, o: &Value, random: &mut R) -> bool {
|
||||
if let Some(c) = o.get("condition")
|
||||
&& !self.condition(c, random)
|
||||
{
|
||||
@@ -856,10 +948,10 @@ impl LootContext<'_> {
|
||||
.all(|c| self.condition(c, random))
|
||||
}
|
||||
/// Expand entries; returns whether an entry succeeded (for alternatives).
|
||||
fn expand(
|
||||
fn expand<R: RandomSource>(
|
||||
&self,
|
||||
e: &Value,
|
||||
random: &mut impl RandomSource,
|
||||
random: &mut R,
|
||||
out: &mut Vec<(i32, ItemStack, Value)>,
|
||||
) -> bool {
|
||||
if !self.conditions(e, random) {
|
||||
@@ -901,6 +993,21 @@ impl LootContext<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
// DynamicLoot: what the block entity adds (a cracked decorated
|
||||
// pot's sherds), filled in by `block_drops_with`.
|
||||
"minecraft:dynamic" => {
|
||||
out.push((
|
||||
e["weight"].as_i64().unwrap_or(1) as i32,
|
||||
ItemStack {
|
||||
item: Arc::from(format!("{DYNAMIC}{}", e["name"].as_str().unwrap_or(""))),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
Value::Null,
|
||||
));
|
||||
true
|
||||
}
|
||||
"minecraft:empty" => {
|
||||
out.push((
|
||||
e["weight"].as_i64().unwrap_or(1) as i32,
|
||||
@@ -917,10 +1024,10 @@ impl LootContext<'_> {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn choose(
|
||||
fn choose<R: RandomSource>(
|
||||
&self,
|
||||
entries: &[Value],
|
||||
random: &mut impl RandomSource,
|
||||
random: &mut R,
|
||||
produced: &mut Vec<ItemStack>,
|
||||
) {
|
||||
let mut candidates = Vec::new();
|
||||
@@ -949,7 +1056,7 @@ impl LootContext<'_> {
|
||||
self.modifiers(&modifiers, &mut stack, random);
|
||||
produced.push(stack);
|
||||
}
|
||||
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut impl RandomSource) {
|
||||
fn modifiers<R: RandomSource>(&self, m: &Value, stack: &mut ItemStack, random: &mut R) {
|
||||
let list: Vec<&Value> = match m {
|
||||
Value::Array(a) => a.iter().collect(),
|
||||
Value::Object(_) => vec![m],
|
||||
@@ -1029,6 +1136,7 @@ impl LootContext<'_> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::LegacyRandom;
|
||||
use serde_json::json;
|
||||
|
||||
fn ctx<'a>(
|
||||
|
||||
@@ -39,6 +39,30 @@ impl ResourceSource for std::path::PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// DeprecatedTranslationsInfo.applyToMap: drop removed keys, then move each
|
||||
/// renamed key's text to its new key (a missing old key removes the new one).
|
||||
pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
|
||||
let Ok(info) = serde_json::from_slice::<serde_json::Value>(json) else {
|
||||
return;
|
||||
};
|
||||
for key in info["removed"].as_array().into_iter().flatten() {
|
||||
if let Some(k) = key.as_str() {
|
||||
map.remove(k);
|
||||
}
|
||||
}
|
||||
for (from, to) in info["renamed"].as_object().into_iter().flatten() {
|
||||
let Some(to) = to.as_str() else { continue };
|
||||
match map.remove(from) {
|
||||
Some(value) => {
|
||||
map.insert(to.to_owned(), value);
|
||||
}
|
||||
None => {
|
||||
map.remove(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
|
||||
Self {
|
||||
@@ -64,6 +88,14 @@ impl Language {
|
||||
}
|
||||
}
|
||||
}
|
||||
// DeprecatedTranslationsInfo.loadFromDefaultResource().applyToMap: the
|
||||
// game's own deprecated.json, not a resource pack's.
|
||||
if let Some(bytes) = sources
|
||||
.iter()
|
||||
.find_map(|s| s.read("assets/minecraft/lang/deprecated.json"))
|
||||
{
|
||||
apply_deprecated(&mut map, &bytes);
|
||||
}
|
||||
Self {
|
||||
code: code.to_owned(),
|
||||
map,
|
||||
|
||||
@@ -6,11 +6,13 @@ pub mod ambience;
|
||||
pub mod animate_tick;
|
||||
pub mod assets;
|
||||
pub mod atlas_sources;
|
||||
pub mod attack_strength;
|
||||
pub mod attribute_updates;
|
||||
pub mod audio;
|
||||
pub mod auto_jump;
|
||||
pub mod banner;
|
||||
pub mod biome;
|
||||
pub mod block_entity_anim;
|
||||
pub mod block_entity_nbt;
|
||||
pub mod block_entity_render;
|
||||
pub mod block_transform;
|
||||
@@ -37,6 +39,7 @@ pub mod enchant;
|
||||
pub mod entities;
|
||||
pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod fastutil_order;
|
||||
pub mod fog;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
@@ -45,6 +48,7 @@ pub mod gossip;
|
||||
pub mod health;
|
||||
pub mod hud;
|
||||
pub mod hud_layout;
|
||||
pub mod hud_overlays;
|
||||
pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod item_data;
|
||||
@@ -96,7 +100,6 @@ pub mod stations;
|
||||
pub mod stopwatches;
|
||||
pub mod streaming;
|
||||
pub mod structure_blocks;
|
||||
pub mod subtitles;
|
||||
pub mod testgen;
|
||||
pub mod text;
|
||||
pub mod title;
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod breeze;
|
||||
pub mod camel;
|
||||
pub mod caravan;
|
||||
pub mod control;
|
||||
pub mod copper_golem;
|
||||
pub mod creaking;
|
||||
pub mod cube;
|
||||
pub mod data;
|
||||
@@ -56,6 +57,7 @@ pub mod trader;
|
||||
pub mod undead;
|
||||
pub mod vex;
|
||||
pub mod villager;
|
||||
pub mod villager_brain;
|
||||
pub mod warden;
|
||||
pub mod witch;
|
||||
pub mod wither;
|
||||
@@ -359,6 +361,8 @@ pub enum DamageKind {
|
||||
InWall,
|
||||
Thorns,
|
||||
SonicBoom,
|
||||
/// `fell_out_of_world`: below the world's floor.
|
||||
OutOfWorld,
|
||||
}
|
||||
/// A damage source: its type, the attacking entity and where it came from.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -414,6 +418,7 @@ impl Damage {
|
||||
| DamageKind::InWall
|
||||
| DamageKind::Generic
|
||||
| DamageKind::SonicBoom
|
||||
| DamageKind::OutOfWorld
|
||||
)
|
||||
}
|
||||
pub fn is_fire(&self) -> bool {
|
||||
@@ -436,6 +441,7 @@ impl Damage {
|
||||
| DamageKind::Cactus
|
||||
| DamageKind::Generic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::OutOfWorld
|
||||
)
|
||||
}
|
||||
pub fn is_projectile(&self) -> bool {
|
||||
@@ -591,6 +597,9 @@ pub struct Mob {
|
||||
pub ai: Box<ai::Ai>,
|
||||
pub extra: Extra,
|
||||
pub fluids: living::Fluids,
|
||||
/// Entity.wasEyeInWater: the eyes were in water before this tick's fluid
|
||||
/// update (`isUnderWater` reads it).
|
||||
pub was_eye_in_water: bool,
|
||||
pub no_gravity: bool,
|
||||
/// `NoAI`: no goals and no movement.
|
||||
pub no_ai: bool,
|
||||
@@ -620,8 +629,23 @@ pub struct Mob {
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum MobEvent {
|
||||
Sound(&'static str, [f64; 3], f32, f32),
|
||||
/// `OfferFlowerGoal.stop`: the item goes to the target's antenna (saddle)
|
||||
/// slot if it is empty, as a guaranteed drop.
|
||||
Gift {
|
||||
target: u32,
|
||||
item: &'static str,
|
||||
},
|
||||
/// A sound event id that is not a static string (variant sounds).
|
||||
SoundId(String, [f64; 3], f32, f32),
|
||||
/// A level event's sound (`levelEvent`/`globalLevelEvent`): the client
|
||||
/// plays it with its own random pitch spread (`(a - b) * spread + 1`),
|
||||
/// nothing is drawn from the mob.
|
||||
LevelEventSound {
|
||||
sound: &'static str,
|
||||
at: [f64; 3],
|
||||
volume: f32,
|
||||
spread: f32,
|
||||
},
|
||||
AttackPlayer(f32, [f64; 3]),
|
||||
/// Damage of a given type to the player (guardian lasers, thorns).
|
||||
DamagePlayer {
|
||||
@@ -876,6 +900,60 @@ pub struct Seen {
|
||||
pub active_raid: bool,
|
||||
/// A villager's reputation of the player (`getPlayerReputation`).
|
||||
pub player_rep: i32,
|
||||
/// `isPushable` and pushed by others (`Entity.push(Entity)` moves it).
|
||||
pub pushable: bool,
|
||||
/// `MobCategory` (`monster`, `creature`, ...).
|
||||
pub category: &'static str,
|
||||
/// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`.
|
||||
pub potential_job: Option<[i32; 3]>,
|
||||
pub meeting: Option<[i32; 3]>,
|
||||
/// A villager's profession (index into `render::PROFESSIONS`) and experience.
|
||||
pub profession: u8,
|
||||
pub xp: i32,
|
||||
}
|
||||
impl Mob {
|
||||
/// `EntityType.getCategory`'s name.
|
||||
pub fn category(&self) -> &'static str {
|
||||
match self.kind.category.as_str() {
|
||||
"monster" => "monster",
|
||||
"creature" => "creature",
|
||||
"ambient" => "ambient",
|
||||
"axolotls" => "axolotls",
|
||||
"underground_water_creature" => "underground_water_creature",
|
||||
"water_creature" => "water_creature",
|
||||
"water_ambient" => "water_ambient",
|
||||
_ => "misc",
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later
|
||||
/// moves with it this tick. Takes the `Push` events aimed at mobs out of
|
||||
/// `events[from..]` into `pending`, which the caller adds to each mob's
|
||||
/// velocity before its tick (and to every mob once all have ticked).
|
||||
pub fn take_mob_pushes(events: &mut Vec<MobEvent>, from: usize, pending: &mut Vec<(u32, Vec3)>) {
|
||||
let mut i = from;
|
||||
while i < events.len() {
|
||||
if let MobEvent::Push {
|
||||
target: Who::Mob(id),
|
||||
velocity,
|
||||
} = events[i]
|
||||
{
|
||||
pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2])));
|
||||
events.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Adds the pending pushes aimed at `m` to its velocity, in push order.
|
||||
pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) {
|
||||
pending.retain(|(id, v)| {
|
||||
if *id != m.id {
|
||||
return true;
|
||||
}
|
||||
m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z);
|
||||
false
|
||||
});
|
||||
}
|
||||
/// The player as mobs see it.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -904,6 +982,9 @@ pub struct PlayerView {
|
||||
pub hero: bool,
|
||||
/// The player's UUID (villagers' gossip is keyed by it).
|
||||
pub uuid: [i32; 4],
|
||||
/// The mobs on the player's team (`isAlliedTo`): combat targeting
|
||||
/// leaves the player alone.
|
||||
pub allies: std::sync::Arc<std::collections::HashSet<u32>>,
|
||||
}
|
||||
pub struct MobWorld<'a> {
|
||||
pub world: &'a World,
|
||||
@@ -929,6 +1010,24 @@ pub struct MobWorld<'a> {
|
||||
pub end: bool,
|
||||
/// The world seed (slime chunks).
|
||||
pub world_seed: i64,
|
||||
/// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world).
|
||||
pub sea_level: i32,
|
||||
/// The scoreboard teams of the player and the mobs (collision rules).
|
||||
pub teams: Teams,
|
||||
}
|
||||
/// `Entity.getTeam` of the player and of the mobs on a team.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Teams {
|
||||
pub player: Option<crate::scoreboard::Team>,
|
||||
pub mobs: HashMap<u32, crate::scoreboard::Team>,
|
||||
}
|
||||
impl Teams {
|
||||
pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> {
|
||||
match who {
|
||||
Who::Player => self.player.as_ref(),
|
||||
Who::Mob(id) => self.mobs.get(&id),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
|
||||
@@ -972,6 +1071,7 @@ impl Mob {
|
||||
ai: Box::default(),
|
||||
extra: Extra::default(),
|
||||
fluids: living::Fluids::default(),
|
||||
was_eye_in_water: false,
|
||||
no_gravity: false,
|
||||
no_ai: false,
|
||||
silent: false,
|
||||
@@ -1164,10 +1264,10 @@ impl Mob {
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
_random: &mut LegacyRandom,
|
||||
level_random: &mut LegacyRandom,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) -> bool {
|
||||
ai::tick(self, w, events)
|
||||
ai::tick(self, w, level_random, events)
|
||||
}
|
||||
pub fn distance_to(&self, p: [f64; 3]) -> f64 {
|
||||
let d = [
|
||||
@@ -1315,8 +1415,10 @@ impl Mob {
|
||||
/// Wear (or take off) a saddle stack, keeping its components.
|
||||
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
|
||||
self.extra.saddled = saddle.is_some();
|
||||
// A plain saddle is implied by `saddled`; anything else (a copper
|
||||
// golem's antenna flower) is kept as it is.
|
||||
self.extra.saddle_stack = saddle
|
||||
.map(|s| crate::items::ItemStack { count: 1, ..s })
|
||||
.filter(|s| s.damage != 0 || s.extra.is_some());
|
||||
.filter(|s| s.damage != 0 || s.extra.is_some() || &*s.item != "minecraft:saddle");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ use super::{
|
||||
undead,
|
||||
};
|
||||
use crate::blocks::Fluid;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ai {
|
||||
@@ -125,7 +128,7 @@ pub fn family(s: Species) -> Family {
|
||||
S::Witch => Family::Witch,
|
||||
S::Wolf | S::Cat => Family::Tame,
|
||||
S::Blaze | S::Ghast => Family::Nether,
|
||||
S::IronGolem | S::SnowGolem => Family::Golem,
|
||||
S::IronGolem | S::SnowGolem | S::CopperGolem => Family::Golem,
|
||||
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => Family::Illager,
|
||||
S::Vex => Family::Vex,
|
||||
S::Ravager => Family::Ravager,
|
||||
@@ -158,6 +161,8 @@ pub fn family(s: Species) -> Family {
|
||||
}
|
||||
}
|
||||
pub fn register(m: &mut Mob) {
|
||||
// Raider subclasses call super.registerGoals() first.
|
||||
super::raider::register(m);
|
||||
match family(m.species()) {
|
||||
Family::Farm => farm::register(m),
|
||||
Family::Undead => undead::register(m),
|
||||
@@ -171,6 +176,7 @@ pub fn register(m: &mut Mob) {
|
||||
Family::Nether if m.species() == Species::Ghast => super::nether::register_ghast(m),
|
||||
Family::Nether => super::nether::register_blaze(m),
|
||||
Family::Golem if m.species() == Species::IronGolem => super::golem::register_iron(m),
|
||||
Family::Golem if m.species() == Species::CopperGolem => super::copper_golem::register(m),
|
||||
Family::Golem => super::golem::register_snow(m),
|
||||
Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m),
|
||||
Family::Illager if m.species() == Species::Evoker => super::illager::register_evoker(m),
|
||||
@@ -201,7 +207,6 @@ pub fn register(m: &mut Mob) {
|
||||
Family::Creaking => super::creaking::register(m),
|
||||
Family::Nautilus => super::nautilus::register(m),
|
||||
}
|
||||
super::raider::register(m);
|
||||
}
|
||||
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
|
||||
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
@@ -220,6 +225,9 @@ fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
/// Move controls implemented by the species (MoveKind::Custom).
|
||||
pub fn custom_move_control(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if m.species() == Species::Drowned {
|
||||
return undead::drowned_move_control(m, w);
|
||||
}
|
||||
if m.species() == Species::Ghast {
|
||||
return super::nether::ghast_move_control(m, w);
|
||||
}
|
||||
@@ -263,8 +271,54 @@ fn generic(m: &mut Mob) {
|
||||
g.add(7, RandomLookAround::default());
|
||||
}
|
||||
}
|
||||
/// Subclasses of `net.minecraft.world.entity.monster.Monster`.
|
||||
pub fn is_monster(s: Species) -> bool {
|
||||
use Species as S;
|
||||
matches!(
|
||||
s,
|
||||
S::Zombie
|
||||
| S::Husk
|
||||
| S::Drowned
|
||||
| S::ZombieVillager
|
||||
| S::ZombifiedPiglin
|
||||
| S::Giant
|
||||
| S::Skeleton
|
||||
| S::Stray
|
||||
| S::Bogged
|
||||
| S::Parched
|
||||
| S::WitherSkeleton
|
||||
| S::Creeper
|
||||
| S::Spider
|
||||
| S::CaveSpider
|
||||
| S::Enderman
|
||||
| S::Endermite
|
||||
| S::Silverfish
|
||||
| S::Witch
|
||||
| S::Pillager
|
||||
| S::Vindicator
|
||||
| S::Evoker
|
||||
| S::Illusioner
|
||||
| S::Ravager
|
||||
| S::Vex
|
||||
| S::Piglin
|
||||
| S::PiglinBrute
|
||||
| S::Zoglin
|
||||
| S::Blaze
|
||||
| S::Guardian
|
||||
| S::ElderGuardian
|
||||
| S::Breeze
|
||||
| S::Creaking
|
||||
| S::Warden
|
||||
| S::Wither
|
||||
)
|
||||
}
|
||||
/// One full entity tick. Returns false when the mob is gone.
|
||||
pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
pub fn tick(
|
||||
m: &mut Mob,
|
||||
w: &MobWorld,
|
||||
level_random: &mut LegacyRandom,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) -> bool {
|
||||
if m.removed {
|
||||
return false;
|
||||
}
|
||||
@@ -299,7 +353,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
return false;
|
||||
}
|
||||
if !m.no_ai {
|
||||
ai_step(m, w, events);
|
||||
ai_step(m, w, level_random, events);
|
||||
}
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick
|
||||
if m.alive() {
|
||||
@@ -309,7 +363,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
m.update_walk_animation();
|
||||
m.anim.end_tick(m.ai.swinging);
|
||||
tick_swing(m);
|
||||
m.position.y > -128.0
|
||||
true
|
||||
}
|
||||
/// LivingEntity.updateSwingTime (6-tick swing duration).
|
||||
fn tick_swing(m: &mut Mob) {
|
||||
@@ -326,6 +380,7 @@ fn tick_swing(m: &mut Mob) {
|
||||
}
|
||||
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
|
||||
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.was_eye_in_water = m.fluids.eye_in_water;
|
||||
m.fluids = w.fluids(m.bounds(), m.eye_y());
|
||||
if m.fluids.in_water {
|
||||
m.fall_distance = 0.0;
|
||||
@@ -354,6 +409,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.fire_ticks -= 1;
|
||||
}
|
||||
}
|
||||
// Entity.checkBelowWorld: LivingEntity.onBelowWorld hurts 4 a tick.
|
||||
if m.position.y < f64::from(crate::chunk::MIN_Y - 64) {
|
||||
m.damage(4.0, Damage::of(DamageKind::OutOfWorld));
|
||||
}
|
||||
if m.alive() {
|
||||
// LivingEntity.baseTick: suffocation inside full blocks.
|
||||
let (ex, ey, ez) = (
|
||||
@@ -489,7 +548,20 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
}
|
||||
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
|
||||
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &mut Vec<MobEvent>) {
|
||||
// Witch.aiStep runs before super.aiStep().
|
||||
if m.species() == Species::Witch {
|
||||
let far = m
|
||||
.target_info(w)
|
||||
.is_some_and(|t| t.position.distance_squared(m.position) > 121.0);
|
||||
super::witch::ai_step(m, events, far);
|
||||
}
|
||||
// Monster.aiStep: updateNoActionTime (Raider: always +2).
|
||||
if is_monster(m.species())
|
||||
&& (super::raider::is_raider(m.species()) || super::hostile::mob_brightness(m, w) > 0.5)
|
||||
{
|
||||
m.ai.no_action_time += 2;
|
||||
}
|
||||
if super::creaking::is_creaking(m) {
|
||||
super::creaking::update(m, w, events);
|
||||
}
|
||||
@@ -506,10 +578,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.ai.zza *= 0.98;
|
||||
// LivingEntity.isImmobile: no goals or input (a biting, stunned or
|
||||
// roaring ravager).
|
||||
let immobile = m.species() == Species::Ravager && super::ravager::immobile(m)
|
||||
|| super::villager::sleeping(m);
|
||||
let immobile = m.species() == Species::Ravager && super::ravager::immobile(m);
|
||||
if m.alive() && !immobile {
|
||||
server_ai_step(m, w, events);
|
||||
server_ai_step(m, w, level_random, events);
|
||||
} else {
|
||||
m.ai.jumping = false;
|
||||
m.ai.xxa = 0.0;
|
||||
@@ -522,6 +593,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
f64::from(m.ai.zza),
|
||||
);
|
||||
m.travel(w, input, events);
|
||||
push_entities(m, w, events);
|
||||
// Spider.tick: climbing while pressed against a wall.
|
||||
if m.kind.flags.climber {
|
||||
m.climbing = m.horizontal_collision;
|
||||
@@ -558,6 +630,85 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
species_ai_step(m, w, events);
|
||||
}
|
||||
impl Mob {
|
||||
/// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`):
|
||||
/// bats and shulkers are never moved by others.
|
||||
pub fn pushable(&self) -> bool {
|
||||
self.alive()
|
||||
&& !matches!(self.species(), Species::Bat | Species::Shulker)
|
||||
&& !(self.kind.flags.climber && self.climbing)
|
||||
&& !(self.species() == Species::Creaking && !super::creaking::can_move(self))
|
||||
}
|
||||
}
|
||||
/// LivingEntity.onClimbable for the pusher (Spider.onClimbable: climbing a wall).
|
||||
fn on_climbable(m: &Mob, w: &MobWorld) -> bool {
|
||||
if m.kind.flags.climber {
|
||||
return m.climbing;
|
||||
}
|
||||
let (x, y, z) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
w.has_tag("minecraft:climbable", w.block_name(x, y, z))
|
||||
}
|
||||
/// LivingEntity.pushEntities: every pushable entity overlapping the box is
|
||||
/// pushed apart from this one (`doPush(e)` = `e.push(this)`); pushes of other
|
||||
/// mobs are `Push` events their tick picks up.
|
||||
fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if m.species() == Species::Bat {
|
||||
return;
|
||||
}
|
||||
let bounds = m.bounds();
|
||||
// The pusher's own isPushable, checked by `e.push(this)` before moving it.
|
||||
let self_pushable = m.alive()
|
||||
&& m.species() != Species::Shulker
|
||||
&& !on_climbable(m, w)
|
||||
&& !(m.species() == Species::Creaking && !super::creaking::can_move(m));
|
||||
let mut targets: Vec<(Who, Vec3)> = Vec::new();
|
||||
if let Some(p) = &w.player
|
||||
&& p.alive
|
||||
&& !p.spectator
|
||||
&& p.bounds.intersects(bounds)
|
||||
{
|
||||
targets.push((Who::Player, p.position));
|
||||
}
|
||||
for o in w.others {
|
||||
if o.id != m.id && o.alive && o.pushable && o.bounds.intersects(bounds) {
|
||||
targets.push((Who::Mob(o.id), o.position));
|
||||
}
|
||||
}
|
||||
// EntitySelector.pushableBy(this): the teams' collision rules.
|
||||
let own = w.teams.of(Who::Mob(m.id));
|
||||
targets.retain(|(who, _)| crate::scoreboard::pushable_by(own, w.teams.of(*who), true));
|
||||
// Cramming (maxEntityCramming 24).
|
||||
if targets.len() > 23 {
|
||||
let _ = m.random.next_int_bound(4);
|
||||
}
|
||||
for (who, at) in targets {
|
||||
// Entity.push(Entity) with `this` the other entity.
|
||||
let (mut xa, mut za) = (m.position.x - at.x, m.position.z - at.z);
|
||||
let mut dd = xa.abs().max(za.abs());
|
||||
if dd < f64::from(0.01_f32) {
|
||||
continue;
|
||||
}
|
||||
dd = dd.sqrt();
|
||||
xa /= dd;
|
||||
za /= dd;
|
||||
let pow = (1.0 / dd).min(1.0);
|
||||
xa *= pow;
|
||||
za *= pow;
|
||||
xa *= f64::from(0.05_f32);
|
||||
za *= f64::from(0.05_f32);
|
||||
events.push(MobEvent::Push {
|
||||
target: who,
|
||||
velocity: [-xa, 0.0, -za],
|
||||
});
|
||||
if self_pushable {
|
||||
m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if !w.daylight || w.nether {
|
||||
return false;
|
||||
@@ -572,7 +723,12 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
br > 0.5 && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 && !wet && w.can_see_sky(x, y, z)
|
||||
}
|
||||
/// Mob.serverAiStep
|
||||
fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
fn server_ai_step(
|
||||
m: &mut Mob,
|
||||
w: &MobWorld,
|
||||
level_random: &mut LegacyRandom,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) {
|
||||
m.ai.no_action_time += 1;
|
||||
// A creaking looked at stands still.
|
||||
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
|
||||
@@ -601,6 +757,11 @@ fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.ai.targets = targets;
|
||||
m.ai.goals = goals;
|
||||
m.nav_tick(w);
|
||||
if m.species() == Species::Villager {
|
||||
// Villager.customServerAiStep: the brain, then the raid sound roll.
|
||||
super::villager_brain::tick(m, w, level_random, events);
|
||||
let _ = m.random.next_int_bound(100);
|
||||
}
|
||||
{
|
||||
let mut cx = Cx { w, events };
|
||||
custom_server_ai_step(m, &mut cx);
|
||||
@@ -626,6 +787,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
Species::Blaze => super::nether::blaze_server_ai_step(m, cx),
|
||||
Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx),
|
||||
Species::Warden => super::warden::server_ai_step(m, cx),
|
||||
Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events),
|
||||
// SpellcasterIllager.customServerAiStep.
|
||||
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
|
||||
_ => {}
|
||||
@@ -636,12 +798,6 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
aquatic::ai_step(m, w, events);
|
||||
}
|
||||
match m.species() {
|
||||
Species::Witch => {
|
||||
let far = m
|
||||
.target_info(w)
|
||||
.is_some_and(|t| t.position.distance_squared(m.position) > 121.0);
|
||||
super::witch::ai_step(m, events, far)
|
||||
}
|
||||
Species::Enderman => super::enderman::ai_step(m, w, events),
|
||||
Species::Wolf => super::tame::ai_step(m, w, events),
|
||||
Species::Cat => super::tame::cat_ai_step(m, events),
|
||||
@@ -672,6 +828,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
super::shulker::ai_step(m, w, events);
|
||||
}
|
||||
Species::SnowGolem => super::golem::snow_ai_step(m, w, events),
|
||||
Species::CopperGolem => super::copper_golem::ai_step(m, w, events),
|
||||
Species::Slime | Species::MagmaCube => super::cube::ai_step(m, w, events),
|
||||
Species::SulfurCube => {
|
||||
super::cube::ai_step(m, w, events);
|
||||
@@ -939,13 +1096,15 @@ pub fn ate(m: &mut Mob) {
|
||||
}
|
||||
/// Species-specific travel (fish, squid, dolphins swim with their own rules).
|
||||
pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) -> bool {
|
||||
if m.species() == Species::Drowned {
|
||||
return undead::drowned_travel(m, w, input, events);
|
||||
}
|
||||
match family(m.species()) {
|
||||
Family::Aquatic => aquatic::travel(m, w, input, events),
|
||||
Family::Guardian => super::guardian::travel(m, w, input, events),
|
||||
// Shulkers never move on their own.
|
||||
Family::Shulker => true,
|
||||
Family::Vex => super::vex::travel(m),
|
||||
Family::Villager => super::villager::travel(m),
|
||||
Family::Nautilus => super::nautilus::travel(m, w, input, events),
|
||||
_ => false,
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ pub enum Anim {
|
||||
Villager,
|
||||
IronGolem,
|
||||
SnowGolem,
|
||||
CopperGolem,
|
||||
Illager,
|
||||
Piglin,
|
||||
ZombifiedPiglin,
|
||||
@@ -462,6 +463,7 @@ pub fn setup(
|
||||
Anim::Camel => super::camel::anim(m, s, p, w_anims),
|
||||
Anim::Breeze => super::breeze::anim(m, s, p, w_anims),
|
||||
Anim::Sniffer => super::sniffer::anim(m, s, p, w_anims),
|
||||
Anim::CopperGolem => super::copper_golem::anim(m, s, p, w_anims),
|
||||
Anim::HappyGhast => super::happy_ghast::anim(m, s, p),
|
||||
Anim::Nautilus => super::nautilus::anim(m, s, p, w_anims),
|
||||
Anim::Llama => super::llama::anim(m, s, p),
|
||||
|
||||
@@ -330,7 +330,12 @@ fn tick_shoot(m: &mut Mob, cx: &mut Cx) {
|
||||
Some(Who::Mob(m.id)),
|
||||
);
|
||||
// 5 - 4 * difficulty at normal.
|
||||
p.shoot(&mut m.random, [xd, yd, zd], 0.7, -3.0);
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd, zd],
|
||||
0.7,
|
||||
-3.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
cx.events
|
||||
.push(MobEvent::Sound("entity.breeze.shoot", m.center(), 1.5, 1.0));
|
||||
|
||||
@@ -230,7 +230,7 @@ impl Mob {
|
||||
self.ai.speed = speed;
|
||||
self.ai.zza = speed;
|
||||
}
|
||||
fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) {
|
||||
pub(crate) fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) {
|
||||
match self.ai.mov.operation {
|
||||
Operation::Strafe => {
|
||||
let speed = self.ai.mov.speed_modifier as f32 * attr_speed as f32;
|
||||
|
||||
@@ -14,8 +14,8 @@ use std::collections::HashMap;
|
||||
|
||||
// Copper golem state: `variant` the weathering (0 unaffected .. 3 oxidized),
|
||||
// `variant3` the `CopperGolemState`, `main_hand` with `ints[1]` the carried
|
||||
// stack, `legs` the antenna block, `egg_time` the next weathering tick (-1
|
||||
// unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest
|
||||
// stack, the saddle slot the antenna (`EQUIPMENT_SLOT_ANTENNA`), `vector[0]`
|
||||
// the next weathering tick (-1 unset, -2 waxed), `ints[0]` the idle animation start tick, `home` the chest
|
||||
// being served with `positions` the visited chests, `point` where it walks,
|
||||
// `scratch` = [transport phase, ticks since reaching the target, interaction
|
||||
// state, transport cooldown ticks]. AnimationState slots: idle (0), getting an
|
||||
@@ -32,7 +32,8 @@ pub fn register(m: &mut Mob) {
|
||||
m.ai.nav.required_path_length = 48.0;
|
||||
m.ai.nav.can_open_doors = true;
|
||||
m.persistent = true;
|
||||
m.extra.egg_time = -1;
|
||||
// nextWeatheringTick starts unset (-1); waxed is -2.
|
||||
m.extra.vector[0] = -1.0;
|
||||
m.extra.scratch[3] = 60 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Panic::new(1.5));
|
||||
@@ -44,7 +45,10 @@ pub fn register(m: &mut Mob) {
|
||||
pub fn texture(m: &Mob) -> String {
|
||||
match m.extra.variant {
|
||||
0 => "entity/copper_golem/copper_golem".into(),
|
||||
n => format!("entity/copper_golem/copper_golem_{}", WEATHER[n.min(3) as usize]),
|
||||
n => format!(
|
||||
"entity/copper_golem/copper_golem_{}",
|
||||
WEATHER[n.min(3) as usize]
|
||||
),
|
||||
}
|
||||
}
|
||||
pub fn eye_texture(m: &Mob) -> String {
|
||||
@@ -101,8 +105,12 @@ impl Goal for Serve {
|
||||
]);
|
||||
match m.extra.point {
|
||||
Some(p) => {
|
||||
if m.ai.nav.is_done() || m.age % 10 == 0 {
|
||||
let block = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
|
||||
if m.ai.nav.is_done() || m.age.is_multiple_of(10) {
|
||||
let block = [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
];
|
||||
let path = m.create_path_to(cx.w, block, 0);
|
||||
m.nav_move_to_path(path, 1.0);
|
||||
}
|
||||
@@ -179,12 +187,13 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
match state {
|
||||
IDLE => {
|
||||
interaction(st, 0);
|
||||
if m.extra.ints[0] == m.age {
|
||||
let tick = m.age as i32;
|
||||
if m.extra.ints[0] == tick {
|
||||
st[0].start(age);
|
||||
} else if m.extra.ints[0] == 0 {
|
||||
m.extra.ints[0] = m.age + 200 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
m.extra.ints[0] = tick + 200 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
}
|
||||
if m.age == m.extra.ints[0] + 10 {
|
||||
if tick == m.extra.ints[0] + 10 {
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
events.push(MobEvent::Sound(sound(m, "spin"), at, 1.0, 1.0));
|
||||
m.extra.ints[0] = 0;
|
||||
|
||||
@@ -315,6 +315,38 @@ impl Mob {
|
||||
m.land_up_out_of_solid(w, p)
|
||||
})
|
||||
}
|
||||
/// LandRandomPos.getPos(mob, h, v, scorer): the best of ten by `score`.
|
||||
pub fn land_random_pos_scored(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
h: i32,
|
||||
v: i32,
|
||||
score: impl Fn([i32; 3]) -> f64,
|
||||
) -> Option<[f64; 3]> {
|
||||
let mut best: Option<[i32; 3]> = None;
|
||||
let mut best_weight = f64::NEG_INFINITY;
|
||||
for _ in 0..10 {
|
||||
let d = self.random_direction(h, v);
|
||||
let p = self.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !self.stable_destination(w, p) {
|
||||
continue;
|
||||
}
|
||||
if let Some(p) = self.land_up_out_of_solid(w, p) {
|
||||
let v = score(p);
|
||||
if v > best_weight {
|
||||
best_weight = v;
|
||||
best = Some(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|p| {
|
||||
[
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]),
|
||||
f64::from(p[2]) + 0.5,
|
||||
]
|
||||
})
|
||||
}
|
||||
/// LandRandomPos.getPosAway
|
||||
pub fn land_random_pos_away(
|
||||
&mut self,
|
||||
@@ -397,9 +429,23 @@ impl Mob {
|
||||
/// creative, within range scaled by visibility, optionally visible.
|
||||
pub fn can_target_player(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
if !p.alive || p.creative {
|
||||
// TargetingConditions.isCombat: never an ally.
|
||||
if p.creative || p.allies.contains(&self.id) {
|
||||
return false;
|
||||
}
|
||||
self.player_in_range(w, range, check_sight)
|
||||
}
|
||||
/// TargetingConditions.forNonCombat().range(range).test for the player
|
||||
/// (seen by anyone, within range scaled by visibility, in sight).
|
||||
pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool {
|
||||
self.player_in_range(w, range, true)
|
||||
}
|
||||
fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
if !p.alive || p.spectator {
|
||||
return false;
|
||||
}
|
||||
// LivingEntity.getVisibilityPercent
|
||||
let mut visibility = 1.0;
|
||||
if p.sneaking {
|
||||
visibility *= 0.8;
|
||||
@@ -572,6 +618,15 @@ impl Stroll {
|
||||
}
|
||||
impl Goal for Stroll {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
if self.water_avoiding.is_some() {
|
||||
"Stroll"
|
||||
} else if self.swim {
|
||||
"RandomSwimming"
|
||||
} else {
|
||||
"RandomStroll"
|
||||
}
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
@@ -635,6 +690,11 @@ pub struct LookAtPlayer {
|
||||
pub range: f32,
|
||||
pub probability: f32,
|
||||
pub only_horizontal: bool,
|
||||
/// `LookAtPlayerGoal(Mob.class, ...)`: the nearest mob, not the player.
|
||||
pub mobs: bool,
|
||||
/// InteractGoal: LOOK and MOVE.
|
||||
pub interact: bool,
|
||||
look_at: Option<Who>,
|
||||
look_time: i32,
|
||||
}
|
||||
impl LookAtPlayer {
|
||||
@@ -643,45 +703,110 @@ impl LookAtPlayer {
|
||||
range,
|
||||
probability: 0.02,
|
||||
only_horizontal: false,
|
||||
mobs: false,
|
||||
interact: false,
|
||||
look_at: None,
|
||||
look_time: 0,
|
||||
}
|
||||
}
|
||||
/// `LookAtPlayerGoal(this, Mob.class, range)`.
|
||||
pub fn mobs(range: f32) -> Self {
|
||||
Self {
|
||||
mobs: true,
|
||||
..Self::new(range)
|
||||
}
|
||||
}
|
||||
/// `InteractGoal(this, Player.class, range, probability)`.
|
||||
pub fn interact(range: f32, probability: f32) -> Self {
|
||||
Self {
|
||||
interact: true,
|
||||
..Self::new(range).probability(probability)
|
||||
}
|
||||
}
|
||||
pub fn probability(mut self, p: f32) -> Self {
|
||||
self.probability = p;
|
||||
self
|
||||
}
|
||||
/// The goal's look target, alive, with its position and eye height.
|
||||
fn look_target(&self, w: &MobWorld) -> Option<(Vec3, f64)> {
|
||||
match self.look_at? {
|
||||
Who::Player => w
|
||||
.player
|
||||
.as_ref()
|
||||
.filter(|p| p.alive)
|
||||
.map(|p| (p.position, p.eye[1])),
|
||||
Who::Mob(id) => w
|
||||
.seen(id)
|
||||
.filter(|s| s.alive)
|
||||
.map(|s| (s.position, s.eye_y)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for LookAtPlayer {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
LOOK
|
||||
if self.interact { LOOK | MOVE } else { LOOK }
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
if self.interact {
|
||||
"InteractGoal"
|
||||
} else {
|
||||
"LookAtPlayer"
|
||||
}
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.random.next_float() >= self.probability {
|
||||
return false;
|
||||
}
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
p.alive && m.distance_sqr(p.position) <= f64::from(self.range * self.range)
|
||||
self.look_at = None;
|
||||
let range = f64::from(self.range);
|
||||
if !self.mobs {
|
||||
// level.getNearestPlayer(forNonCombat().range(lookDistance)).
|
||||
if m.can_see_player(cx.w, range) {
|
||||
self.look_at = Some(Who::Player);
|
||||
}
|
||||
return self.look_at.is_some();
|
||||
}
|
||||
// level.getNearestEntity(mobs in the box inflated by (range, 3, range)).
|
||||
let area = m.bounds().inflate(Vec3::new(range, 3.0, range));
|
||||
let id = m.id;
|
||||
let at = Vec3::new(m.position.x, m.eye_y(), m.position.z);
|
||||
let candidates: Vec<(u32, Vec3)> =
|
||||
cx.w.others
|
||||
.iter()
|
||||
.filter(|s| s.id != id && s.alive && s.bounds.intersects(area))
|
||||
.map(|s| (s.id, s.position))
|
||||
.collect();
|
||||
let mut best: Option<(u32, f64)> = None;
|
||||
for (cid, pos) in candidates {
|
||||
let reach = range.max(2.0);
|
||||
if m.distance_sqr(pos) > reach * reach || !m.sees(cx.w, Who::Mob(cid)) {
|
||||
continue;
|
||||
}
|
||||
let d = pos.distance_squared(at);
|
||||
if best.is_none_or(|(_, b)| d < b) {
|
||||
best = Some((cid, d));
|
||||
}
|
||||
}
|
||||
self.look_at = best.map(|(cid, _)| Who::Mob(cid));
|
||||
self.look_at.is_some()
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
p.alive
|
||||
&& m.distance_sqr(p.position) <= f64::from(self.range * self.range)
|
||||
&& self.look_time > 0
|
||||
let Some((pos, _)) = self.look_target(cx.w) else {
|
||||
return false;
|
||||
};
|
||||
m.distance_sqr(pos) <= f64::from(self.range * self.range) && self.look_time > 0
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
self.look_time = reduced(40 + m.random.next_int_bound(40).unwrap_or(0));
|
||||
}
|
||||
fn stop(&mut self, _: &mut Mob, _: &mut Cx) {
|
||||
self.look_at = None;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(p) = &cx.w.player
|
||||
&& p.alive
|
||||
{
|
||||
let y = if self.only_horizontal {
|
||||
m.eye_y()
|
||||
} else {
|
||||
p.eye[1]
|
||||
};
|
||||
m.look_at([p.position.x, y, p.position.z]);
|
||||
if let Some((pos, eye)) = self.look_target(cx.w) {
|
||||
let y = if self.only_horizontal { m.eye_y() } else { eye };
|
||||
m.look_at([pos.x, y, pos.z]);
|
||||
self.look_time -= 1;
|
||||
}
|
||||
}
|
||||
@@ -918,8 +1043,13 @@ pub struct NearestTarget {
|
||||
pub must_see: bool,
|
||||
pub must_reach: bool,
|
||||
pub interval: i32,
|
||||
/// Extra condition on the attacker (e.g. spiders only at night).
|
||||
/// Extra condition on the attacker, checked after the random interval.
|
||||
pub when: Option<fn(&Mob, &MobWorld) -> bool>,
|
||||
/// A condition checked before anything else, by subclasses overriding
|
||||
/// `canUse` (SpiderTargetGoal: only in the dark).
|
||||
pub gate: Option<fn(&Mob, &MobWorld) -> bool>,
|
||||
/// The vanilla class name of a subclass (`Goal::name`).
|
||||
pub label: Option<&'static str>,
|
||||
found: Option<Who>,
|
||||
target_goal: TargetState,
|
||||
}
|
||||
@@ -947,6 +1077,8 @@ impl NearestTarget {
|
||||
must_reach: false,
|
||||
interval: reduced(10),
|
||||
when: None,
|
||||
gate: None,
|
||||
label: None,
|
||||
found: None,
|
||||
target_goal: TargetState {
|
||||
unseen_memory: 60,
|
||||
@@ -977,6 +1109,15 @@ impl NearestTarget {
|
||||
self.when = Some(f);
|
||||
self
|
||||
}
|
||||
pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self {
|
||||
self.gate = Some(f);
|
||||
self
|
||||
}
|
||||
/// A subclass's name, e.g. `NearestAttackableWitchTargetGoal`.
|
||||
pub fn named(mut self, label: &'static str) -> Self {
|
||||
self.label = Some(label);
|
||||
self
|
||||
}
|
||||
}
|
||||
/// TargetGoal.canContinueToUse
|
||||
pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
@@ -1005,10 +1146,18 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m
|
||||
}
|
||||
impl Goal for NearestTarget {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
self.label.unwrap_or("NearestTarget")
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if let Some(f) = self.gate
|
||||
&& !f(m, cx.w)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if self.interval > 0 && m.random.next_int_bound(self.interval).unwrap_or(1) != 0 {
|
||||
return false;
|
||||
}
|
||||
@@ -1828,7 +1977,7 @@ impl MoveToBlock {
|
||||
self.find_nearest(m, w, valid)
|
||||
}
|
||||
/// `MoveToBlockGoal.findNearestBlock`: rings outward, alternating heights.
|
||||
fn find_nearest(
|
||||
pub fn find_nearest(
|
||||
&mut self,
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
@@ -1881,6 +2030,10 @@ impl MoveToBlock {
|
||||
}
|
||||
/// `MoveToBlockGoal.tick` (accepted distance 1 from the block above).
|
||||
pub fn tick(&mut self, m: &mut Mob, w: &MobWorld) {
|
||||
self.tick_within(m, w, 1.0);
|
||||
}
|
||||
/// `MoveToBlockGoal.tick` with the goal's `acceptedDistance`.
|
||||
pub fn tick_within(&mut self, m: &mut Mob, w: &MobWorld, accepted: f64) {
|
||||
let t = [
|
||||
f64::from(self.block[0]) + 0.5,
|
||||
f64::from(self.block[1] + 1) + 0.5,
|
||||
@@ -1889,7 +2042,7 @@ impl MoveToBlock {
|
||||
let d2 = (m.position.x - t[0]).powi(2)
|
||||
+ (m.position.y - t[1]).powi(2)
|
||||
+ (m.position.z - t[2]).powi(2);
|
||||
if d2 >= 1.0 {
|
||||
if d2 >= accepted * accepted {
|
||||
self.reached = false;
|
||||
self.try_ticks += 1;
|
||||
if self.try_ticks % 40 == 0 {
|
||||
|
||||
@@ -142,9 +142,10 @@ impl Goal for OfferFlower {
|
||||
if !cx.w.daylight || m.random.next_int_bound(8000).unwrap_or(1) != 0 {
|
||||
return false;
|
||||
}
|
||||
// The nearest of #candidate_for_iron_golem_gift: villagers and copper golems.
|
||||
self.villager =
|
||||
cx.w.nearby(m.position, 6.0, |s| {
|
||||
s.species == Species::Villager && s.alive
|
||||
matches!(s.species, Species::Villager | Species::CopperGolem) && s.alive
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.next();
|
||||
@@ -157,8 +158,30 @@ impl Goal for OfferFlower {
|
||||
self.ticks = 400;
|
||||
m.extra.counter = 400;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.counter = 0;
|
||||
// A copper golem the offer ran out beside takes the poppy on its
|
||||
// antenna (#accepts_iron_golem_gift) when it has none.
|
||||
if self.ticks == 0
|
||||
&& let Some(v) = self.villager.and_then(|v| cx.w.seen(v))
|
||||
&& v.species == Species::CopperGolem
|
||||
{
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let (vlo, vhi) = (v.bounds.min_position(), v.bounds.max_position());
|
||||
if lo.x - 6.0 < vhi.x
|
||||
&& hi.x + 6.0 > vlo.x
|
||||
&& lo.y - 2.0 < vhi.y
|
||||
&& hi.y + 2.0 > vlo.y
|
||||
&& lo.z - 6.0 < vhi.z
|
||||
&& hi.z + 6.0 > vlo.z
|
||||
{
|
||||
cx.events.push(MobEvent::Gift {
|
||||
target: v.id,
|
||||
item: "minecraft:poppy",
|
||||
});
|
||||
}
|
||||
}
|
||||
self.villager = None;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
@@ -284,7 +307,12 @@ fn snowball_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
let yo = (xd * xd + zd * zd).sqrt() * 0.2;
|
||||
let mut p = Projectile::new(ProjectileKind::Snowball, start, Some(Who::Mob(m.id)));
|
||||
// rangedAttackUncertainty: 14 - 4 * difficulty (normal: 6).
|
||||
p.shoot(&mut m.random, [xd, yd + yo - start.y, zd], 1.6, 6.0);
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd + yo - start.y, zd],
|
||||
1.6,
|
||||
6.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 0.4 / (m.random.next_float() * 0.4 + 0.8);
|
||||
cx.events.push(MobEvent::Sound(
|
||||
|
||||
@@ -47,10 +47,10 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(6, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
m.ai.targets
|
||||
.add(2, NearestTarget::player(true).when(dark_enough));
|
||||
.add(2, NearestTarget::player(true).gate(dark_enough));
|
||||
m.ai.targets.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::IronGolem], true).when(dark_enough),
|
||||
NearestTarget::species(&[S::IronGolem], true).gate(dark_enough),
|
||||
);
|
||||
m.ai.nav.kind = super::nav::NavKind::WallClimber;
|
||||
}
|
||||
|
||||
@@ -48,20 +48,35 @@ fn targets(m: &mut Mob, villagers_seen: bool) {
|
||||
m.ai.targets
|
||||
.add(3, NearestTarget::species(&[Species::IronGolem], true));
|
||||
}
|
||||
/// `AvoidEntityGoal<>(this, Creaking.class, 8.0F, walk, sprint)`.
|
||||
fn avoid_creaking(walk: f64, sprint: f64) -> super::goals::AvoidEntity {
|
||||
super::goals::AvoidEntity::new(
|
||||
super::goals::Avoid::Species(vec![Species::Creaking]),
|
||||
8.0,
|
||||
walk,
|
||||
sprint,
|
||||
)
|
||||
}
|
||||
pub fn register_pillager(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(1, avoid_creaking(1.0, 1.2));
|
||||
g.add(2, super::raider::HoldGroundAttack::new(10.0));
|
||||
g.add(3, CrossbowAttack::new(1.0, 8.0));
|
||||
g.add(8, Stroll::new(0.6));
|
||||
g.add(9, LookAtPlayer::new(15.0));
|
||||
g.add(9, LookAtPlayer::new(15.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::mobs(15.0));
|
||||
targets(m, false);
|
||||
}
|
||||
pub fn register_vindicator(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(1, avoid_creaking(1.0, 1.2));
|
||||
g.add(4, super::raider::HoldGroundAttack::new(10.0));
|
||||
g.add(5, MeleeAttack::new(1.0, false));
|
||||
g.add(8, Stroll::new(0.6));
|
||||
g.add(9, LookAtPlayer::new(3.0));
|
||||
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
targets(m, true);
|
||||
// VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks anything.
|
||||
m.ai.targets.add(
|
||||
@@ -82,11 +97,13 @@ pub fn register_evoker(m: &mut Mob) {
|
||||
2,
|
||||
super::goals::AvoidEntity::new(super::goals::Avoid::Player, 8.0, 0.6, 1.0),
|
||||
);
|
||||
g.add(3, avoid_creaking(0.6, 1.0));
|
||||
g.add(4, UseSpell::new(Spell::Vexes));
|
||||
g.add(5, UseSpell::new(Spell::Fangs));
|
||||
g.add(6, UseSpell::new(Spell::Wololo));
|
||||
g.add(8, Stroll::new(0.6));
|
||||
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
targets(m, false);
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -526,7 +543,12 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
|
||||
);
|
||||
p.bonus = super::gear::arrow_bonus(m);
|
||||
// rangedAttackUncertainty at normal difficulty: 14 - 2 * 4.
|
||||
p.shoot(&mut m.random, [dx, dy, dz], 1.6, 6.0);
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[dx, dy, dz],
|
||||
1.6,
|
||||
6.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 1.0 / (m.random.next_float() * 0.5 + 1.8) + 0.53;
|
||||
cx.events.push(MobEvent::Sound(
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(6, BowAttack::new(0.5, 20, 15.0));
|
||||
g.add(8, Stroll::new(0.6));
|
||||
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::new(8.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
hurt.ignore = vec![
|
||||
Species::Pillager,
|
||||
|
||||
@@ -86,10 +86,34 @@ impl MobWorld<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fx, fz) = ((lo.x + hi.x) / 2.0, (lo.z + hi.z) / 2.0);
|
||||
let ey = eye_y.floor() as i32;
|
||||
let (fluid, h) = self.fluid_height(fx.floor() as i32, ey, fz.floor() as i32);
|
||||
out.eye_in_water = fluid == Fluid::Water && eye_y < f64::from(ey) + h + 0.111_111_11;
|
||||
// EntityFluidInteraction.update: the eyes are in a fluid block of
|
||||
// the box in the entity's column, between its bottom and its height
|
||||
// for the camera.
|
||||
let (ex, ez) = (
|
||||
((lo.x + hi.x) / 2.0).floor() as i32,
|
||||
((lo.z + hi.z) / 2.0).floor() as i32,
|
||||
);
|
||||
for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) {
|
||||
let (fluid, h) = self.fluid_height(ex, y, ez);
|
||||
if fluid != Fluid::Water || f64::from(y) + h < lo.y || eye_y < f64::from(y) {
|
||||
continue;
|
||||
}
|
||||
let state = self.world.block(ex, y, ez);
|
||||
let source = self
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("level"))
|
||||
.is_none_or(|l| l == "0");
|
||||
let above = self.facts.get(self.world.block(ex, y + 1, ez));
|
||||
let camera = if source && above.sturdy_full & 1 != 0 {
|
||||
1.0
|
||||
} else {
|
||||
h
|
||||
};
|
||||
if eye_y <= f64::from(y) + camera {
|
||||
out.eye_in_water = true;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn no_collision(&self, b: Aabb) -> bool {
|
||||
@@ -108,6 +132,10 @@ impl Mob {
|
||||
/// slime size scaling.
|
||||
/// `EntityDimensions` (float width, height and eye height) widened to double.
|
||||
pub fn dims(&self) -> (f64, f64, f64) {
|
||||
// LivingEntity.SLEEPING_DIMENSIONS.
|
||||
if super::villager::sleeping(self) {
|
||||
return (f64::from(0.2_f32), f64::from(0.2_f32), f64::from(0.2_f32));
|
||||
}
|
||||
let k = &self.kind;
|
||||
let (mut w, mut h, mut e) = (k.width as f32, k.height as f32, k.eye_height as f32);
|
||||
// Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81.
|
||||
@@ -362,8 +390,13 @@ impl Mob {
|
||||
fn flying_speed(&self) -> f32 {
|
||||
0.02
|
||||
}
|
||||
/// Entity.getGravity: none while isNoGravity.
|
||||
fn gravity(&self) -> f64 {
|
||||
self.kind.gravity
|
||||
if self.no_gravity {
|
||||
0.0
|
||||
} else {
|
||||
self.kind.gravity
|
||||
}
|
||||
}
|
||||
/// LivingEntity.travel.
|
||||
pub fn travel(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
@@ -474,7 +507,11 @@ impl Mob {
|
||||
if self.horizontal_collision && self.kind.flags.climber {
|
||||
m.y = 0.2;
|
||||
}
|
||||
m = Vec3::new(m.x * f64::from(slow), m.y * 0.8, m.z * f64::from(slow));
|
||||
m = Vec3::new(
|
||||
m.x * f64::from(slow),
|
||||
m.y * f64::from(0.8_f32),
|
||||
m.z * f64::from(slow),
|
||||
);
|
||||
self.velocity = fluid_falling(gravity, falling, m);
|
||||
} else {
|
||||
self.move_relative(0.02, input);
|
||||
@@ -482,7 +519,7 @@ impl Mob {
|
||||
if self.fluids.lava <= self.fluid_jump_threshold() {
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.5,
|
||||
self.velocity.y * 0.8,
|
||||
self.velocity.y * f64::from(0.8_f32),
|
||||
self.velocity.z * 0.5,
|
||||
);
|
||||
self.velocity = fluid_falling(gravity, falling, self.velocity);
|
||||
@@ -502,11 +539,11 @@ impl Mob {
|
||||
if self.horizontal_collision
|
||||
&& w.no_collision(self.bounds().move_by(Vec3::new(
|
||||
m.x,
|
||||
m.y + 0.6 - self.position.y + old_y,
|
||||
m.y + f64::from(0.6_f32) - self.position.y + old_y,
|
||||
m.z,
|
||||
)))
|
||||
{
|
||||
self.velocity.y = 0.3;
|
||||
self.velocity.y = f64::from(0.3_f32);
|
||||
}
|
||||
}
|
||||
/// The jump part of LivingEntity.aiStep.
|
||||
|
||||
@@ -174,7 +174,12 @@ fn spit(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
let zd = t.position.z - m.position.z;
|
||||
let yo = (xd * xd + zd * zd).sqrt() * f64::from(0.2_f32);
|
||||
let mut p = Projectile::new(ProjectileKind::LlamaSpit, start, Some(Who::Mob(m.id)));
|
||||
p.shoot(&mut m.random, [xd, yd + yo, zd], 1.5, 10.0);
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd + yo, zd],
|
||||
1.5,
|
||||
10.0,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2;
|
||||
cx.events.push(MobEvent::Sound(
|
||||
|
||||
@@ -267,6 +267,17 @@ impl Mob {
|
||||
let max = self.max_path_length();
|
||||
self.create_path_raw(w, &[p], reach, max)
|
||||
}
|
||||
/// PathNavigation.createPath(Set<BlockPos>, reach): the nearest of
|
||||
/// several targets, without the ground surface search.
|
||||
pub fn create_path_to_any(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
targets: &[[i32; 3]],
|
||||
reach: i32,
|
||||
) -> Option<Path> {
|
||||
let max = self.max_path_length();
|
||||
self.create_path_raw(w, targets, reach, max)
|
||||
}
|
||||
/// PathNavigation.createPath(Entity, reach).
|
||||
pub fn create_path_to_entity(
|
||||
&mut self,
|
||||
|
||||
@@ -80,24 +80,18 @@ pub fn is_captain(m: &Mob) -> bool {
|
||||
m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader)
|
||||
}
|
||||
|
||||
/// `PatrollingMonster.registerGoals` then `Raider.registerGoals`: the goals
|
||||
/// every raider registers before its own.
|
||||
pub fn register(m: &mut Mob) {
|
||||
if !is_raider(m.species()) {
|
||||
return;
|
||||
}
|
||||
m.extra.raider = Some(Box::default());
|
||||
let species = m.species();
|
||||
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
|
||||
m.ai.goals.add(1, ObtainBanner);
|
||||
m.ai.goals.add(3, PathfindToRaid);
|
||||
m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0));
|
||||
m.ai.goals.add(5, Celebration);
|
||||
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
|
||||
// The illagers hold their ground in a patrol (Witch and Ravager do not).
|
||||
if matches!(species, Species::Pillager | Species::Vindicator) {
|
||||
m.ai.goals.add(
|
||||
if species == Species::Pillager { 2 } else { 4 },
|
||||
HoldGroundAttack::new(10.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Raid.getOminousBannerInstance`.
|
||||
|
||||
@@ -21,6 +21,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(4, MeleeAttack::new(1.0, true));
|
||||
g.add(5, Stroll::avoiding_water(0.4));
|
||||
g.add(6, LookAtPlayer::new(6.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
hurt.ignore = vec![
|
||||
Species::Pillager,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user