Merge remote-tracking branch 'origin/t3/achieve-full-parity' into parity/warden-sculk
# Conflicts: # crates/horizon-client/src/game.rs # crates/horizon-client/src/game/creatures.rs
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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| {
|
||||
@@ -485,16 +537,38 @@ fn main() -> horizon_client::Result<()> {
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
for m in &mut mobs {
|
||||
#[allow(unused_mut)] // filled only with the rng-trace feature
|
||||
let mut traces: Vec<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 +582,18 @@ fn main() -> horizon_client::Result<()> {
|
||||
);
|
||||
} else if let MobEvent::SoundId(name, _, volume, pitch) = e {
|
||||
let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch));
|
||||
} else if player_hurt(player.as_ref(), e) {
|
||||
// The oracle's survival player, healed and made hurtable every tick,
|
||||
// takes the damage (LivingEntity.playHurtSound).
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{t} sound minecraft:entity.player.hurt 3f800000 3f800000"
|
||||
);
|
||||
}
|
||||
}
|
||||
for line in traces {
|
||||
let _ = writeln!(out, "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fs::write(&args[2], out)?;
|
||||
|
||||
@@ -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) {
|
||||
@@ -1579,7 +1710,8 @@ impl ArgType {
|
||||
if block {
|
||||
parse_coord_int(reader)
|
||||
} else {
|
||||
parse_coord_double(reader, false)
|
||||
// Vec2Argument.vec2(): integers are centred on the block.
|
||||
parse_coord_double(reader, true)
|
||||
}
|
||||
};
|
||||
let x = one(reader)?;
|
||||
@@ -1741,6 +1873,9 @@ impl ArgType {
|
||||
}
|
||||
ArgType::StrEnum(values, _) => builder.suggest_matching(values.iter().copied()),
|
||||
ArgType::HexColor => builder.suggest_matching(["F00", "FF0000"]),
|
||||
ArgType::ResourceSelector(registry) => {
|
||||
suggest_resources(builder, reg.ids(registry), "")
|
||||
}
|
||||
ArgType::GameProfile => {
|
||||
let players = reg.players.clone();
|
||||
super::selector::suggest(builder, reg, &|b| {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
@@ -1118,6 +1120,25 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
|
||||
{
|
||||
put(&mut tag, "Health", Tag::Float(20f32.to_bits()));
|
||||
}
|
||||
// LivingEntity.addAdditionalSaveData and ArmorStand's own fields.
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
for (key, value) in [
|
||||
("HurtTime", Tag::Short(0)),
|
||||
("DeathTime", Tag::Short(0)),
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
("current_impulse_context_reset_grace_time", Tag::Int(0)),
|
||||
("attributes", Tag::List(Vec::new())),
|
||||
(
|
||||
"Brain",
|
||||
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
|
||||
),
|
||||
("DisabledSlots", Tag::Int(0)),
|
||||
("Pose", Tag::Compound(Compound::new())),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Iteration order of fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! addressing with linear probing, backward-shift deletion and rehashing at
|
||||
//! the load factor), for the vanilla collections whose order commands show:
|
||||
//! the scoreboard's objectives and teams.
|
||||
|
||||
/// The keys of an open hash map in their table slots.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OpenOrder {
|
||||
keys: Vec<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`.
|
||||
fn java_hash(s: &str) -> i32 {
|
||||
s.encode_utf16()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
|
||||
}
|
||||
/// `HashCommon.mix`.
|
||||
fn mix(x: i32) -> usize {
|
||||
let h = (x as u32).wrapping_mul(0x9E37_79B9);
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
/// `HashCommon.arraySize`.
|
||||
fn array_size(expected: usize, f: f32) -> usize {
|
||||
let wanted = (expected as f64 / f64::from(f)).ceil() as usize;
|
||||
wanted.max(2).next_power_of_two()
|
||||
}
|
||||
impl OpenOrder {
|
||||
pub fn new(expected: usize, load: f32) -> Self {
|
||||
let n = array_size(expected, load);
|
||||
Self {
|
||||
keys: vec![None; n],
|
||||
size: 0,
|
||||
min_n: n,
|
||||
load,
|
||||
}
|
||||
}
|
||||
fn max_fill(&self) -> usize {
|
||||
((self.keys.len() as f64 * f64::from(self.load)).ceil() as usize).min(self.keys.len() - 1)
|
||||
}
|
||||
fn slot(&self, key: &str) -> usize {
|
||||
mix(java_hash(key)) & (self.keys.len() - 1)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key.to_owned());
|
||||
self.size += 1;
|
||||
if self.size >= self.max_fill() {
|
||||
self.rehash(array_size(self.size + 1, self.load));
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
loop {
|
||||
match &self.keys[pos] {
|
||||
None => return,
|
||||
Some(k) if k == key => break,
|
||||
Some(_) => pos = (pos + 1) & mask,
|
||||
}
|
||||
}
|
||||
self.size -= 1;
|
||||
self.shift_keys(pos);
|
||||
let n = self.keys.len();
|
||||
if n > self.min_n && self.size < self.max_fill() / 4 && n > 16 {
|
||||
self.rehash(n / 2);
|
||||
}
|
||||
}
|
||||
fn shift_keys(&mut self, mut pos: usize) {
|
||||
let mask = self.keys.len() - 1;
|
||||
loop {
|
||||
let last = pos;
|
||||
pos = (last + 1) & mask;
|
||||
loop {
|
||||
let Some(curr) = self.keys[pos].clone() else {
|
||||
self.keys[last] = None;
|
||||
return;
|
||||
};
|
||||
let slot = self.slot(&curr);
|
||||
let stop = if last <= pos {
|
||||
last >= slot || slot > pos
|
||||
} else {
|
||||
last >= slot && slot > pos
|
||||
};
|
||||
if stop {
|
||||
self.keys[last] = Some(curr);
|
||||
break;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rehash(&mut self, new_n: usize) {
|
||||
let old = std::mem::replace(&mut self.keys, vec![None; new_n]);
|
||||
let mask = new_n - 1;
|
||||
for key in old.into_iter().rev().flatten() {
|
||||
let mut pos = mix(java_hash(&key)) & mask;
|
||||
while self.keys[pos].is_some() {
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key);
|
||||
}
|
||||
}
|
||||
/// The iteration order (`keySet().iterator()`: from the last slot down).
|
||||
pub fn keys(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().rev().flatten().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_and_order() {
|
||||
assert_eq!(
|
||||
java_hash("harness"),
|
||||
"harness"
|
||||
.chars()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))
|
||||
);
|
||||
let mut o = OpenOrder::new(16, 0.5);
|
||||
for k in ["harness", "harness_h"] {
|
||||
o.insert(k);
|
||||
}
|
||||
let keys: Vec<&str> = o.keys().collect();
|
||||
assert_eq!(keys.len(), 2);
|
||||
o.remove("harness");
|
||||
assert_eq!(o.keys().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
for i in 0..40 {
|
||||
o.insert(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.keys().count(), 41);
|
||||
for i in 0..40 {
|
||||
o.remove(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.keys().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -6,6 +6,7 @@ mod allays;
|
||||
mod armor_stands;
|
||||
mod banners;
|
||||
mod beacon;
|
||||
mod block_entity_anims;
|
||||
mod blockctl;
|
||||
mod boats;
|
||||
mod books;
|
||||
@@ -14,6 +15,7 @@ mod breezes;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod combat;
|
||||
mod command_harness;
|
||||
mod commands;
|
||||
mod control;
|
||||
mod creaking;
|
||||
@@ -110,7 +112,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,
|
||||
@@ -615,7 +617,8 @@ struct Game<'a> {
|
||||
last_hurt_by_player: HashSet<u32>,
|
||||
/// Mobs whose death (`LivingEntity.die`) has been handled.
|
||||
died: 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.
|
||||
@@ -638,6 +641,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>,
|
||||
@@ -682,6 +687,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,
|
||||
@@ -741,7 +748,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,
|
||||
@@ -784,6 +793,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 {
|
||||
@@ -1613,6 +1629,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 { .. } => {}
|
||||
@@ -1637,6 +1656,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,
|
||||
@@ -1649,9 +1669,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],
|
||||
@@ -1888,6 +1911,7 @@ impl Game<'_> {
|
||||
let name = facts.name.clone();
|
||||
self.release_contents(pos, entity, &name);
|
||||
if self.container == Some((pos[0], pos[1], pos[2])) {
|
||||
self.container_opener_event((pos[0], pos[1], pos[2]), false);
|
||||
self.container = None;
|
||||
self.screen = Screen::Playing;
|
||||
}
|
||||
@@ -2528,6 +2552,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);
|
||||
@@ -2625,7 +2651,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);
|
||||
@@ -2735,7 +2761,7 @@ impl Game<'_> {
|
||||
self.tick_effects();
|
||||
self.tick_burning();
|
||||
self.tick_using();
|
||||
self.titles.tick();
|
||||
self.tick_hud();
|
||||
if running {
|
||||
self.tick_paintings();
|
||||
self.tick_item_frames();
|
||||
@@ -2778,17 +2804,10 @@ impl Game<'_> {
|
||||
self.tick_sculk_blocks()?;
|
||||
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 {
|
||||
@@ -2883,26 +2902,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);
|
||||
@@ -2970,8 +2993,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);
|
||||
@@ -3041,6 +3068,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
|
||||
@@ -3142,12 +3172,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),
|
||||
@@ -3499,6 +3523,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],
|
||||
@@ -4144,14 +4169,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)
|
||||
@@ -4167,10 +4186,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,
|
||||
@@ -4632,20 +4652,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
|
||||
@@ -5030,6 +5036,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;
|
||||
@@ -7118,6 +7129,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(),
|
||||
@@ -8075,7 +8094,11 @@ pub fn run() -> Result<()> {
|
||||
attack_ticks: 100,
|
||||
last_hurt_by_player: HashSet::new(),
|
||||
died: 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),
|
||||
@@ -8088,6 +8111,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(),
|
||||
@@ -8123,6 +8147,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),
|
||||
@@ -8166,6 +8191,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(),
|
||||
@@ -8215,6 +8241,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| {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
@@ -1355,12 +1515,14 @@ impl Game<'_> {
|
||||
return Err(err("commands.setblock.failed", &[]));
|
||||
}
|
||||
if ctx.has("destroy") && current != self.world.air {
|
||||
let creative = self.creative;
|
||||
self.creative = false;
|
||||
let _ = self.break_block(pos);
|
||||
self.creative = creative;
|
||||
self.destroy_block_dropping(pos)?;
|
||||
}
|
||||
if !self.place_state(pos, state, ctx.has("strict"))? {
|
||||
let placed = self.place_state(pos, state, ctx.has("strict"))?;
|
||||
let loaded = match &b.nbt {
|
||||
Some(nbt) => self.load_block_entity_nbt(pos, nbt),
|
||||
None => false,
|
||||
};
|
||||
if !placed && !loaded {
|
||||
return Err(err("commands.setblock.failed", &[]));
|
||||
}
|
||||
self.feedback(Text::tr(
|
||||
@@ -1369,6 +1531,64 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
/// `Level.destroyBlock(pos, true)`: the block's drops without a tool or
|
||||
/// breaker (its loot table, contents of a container), then air.
|
||||
pub(super) fn destroy_block_dropping(&mut self, pos: [i32; 3]) -> R<()> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
self.destroy_particles(pos, state);
|
||||
self.jukebox_removed(pos);
|
||||
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
self.release_contents(pos, entity, &name);
|
||||
}
|
||||
let drops = self.res.items.block_drops_in(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for d in drops {
|
||||
if &*d.item != "minecraft:air" {
|
||||
self.pop_resource(pos, d);
|
||||
}
|
||||
}
|
||||
let air = self.world.air;
|
||||
self.place_state(pos, air, false)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The block entity part of `BlockInput.place`: load the block entity
|
||||
/// from the argument's tag; true when its saved data changed.
|
||||
pub(super) fn load_block_entity_nbt(&mut self, pos: [i32; 3], nbt: &str) -> bool {
|
||||
use horizon_world::nbt::Tag;
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let Some(e) = self.world.block_entities.get(&key) else {
|
||||
return false;
|
||||
};
|
||||
let name = self.data_block_name(pos);
|
||||
let before = horizon_client::save::encode_block_entity(key, e, &name);
|
||||
let Ok((mut tag, _)) = horizon_world::nbt::parse_snbt(nbt) else {
|
||||
return false;
|
||||
};
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
for k in ["id", "x", "y", "z"] {
|
||||
if let Some(v) = before.get(k) {
|
||||
c.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else {
|
||||
return false;
|
||||
};
|
||||
let after = horizon_client::save::encode_block_entity(key, &new, &name);
|
||||
if after == before {
|
||||
return false;
|
||||
}
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], state);
|
||||
true
|
||||
}
|
||||
fn cmd_fill(&mut self, ctx: &Context) -> R<i32> {
|
||||
let a = self.block_pos_arg(ctx, "from")?;
|
||||
let b = self.block_pos_arg(ctx, "to")?;
|
||||
@@ -1418,10 +1638,7 @@ impl Game<'_> {
|
||||
|| z == max[2];
|
||||
let mut affected = false;
|
||||
if destroy && current != air {
|
||||
let creative = self.creative;
|
||||
self.creative = false;
|
||||
let _ = self.break_block([x, y, z]);
|
||||
self.creative = creative;
|
||||
self.destroy_block_dropping([x, y, z])?;
|
||||
affected = true;
|
||||
}
|
||||
let target = if (outline || hollow) && !edge {
|
||||
@@ -1497,21 +1714,29 @@ impl Game<'_> {
|
||||
dest[2] + z - min[2],
|
||||
],
|
||||
s,
|
||||
self.world.block_entities.get(&(x, y, z)).cloned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if moving {
|
||||
for (from, _, _) in &copies {
|
||||
for (from, _, _, _) in &copies {
|
||||
self.place_state(*from, air, true)?;
|
||||
}
|
||||
}
|
||||
let strict = ctx.has("strict");
|
||||
// CloneCommands.clone sets every destination to a barrier first, so
|
||||
// each copied state but a barrier counts as placed.
|
||||
let barrier = self.res.assets.registry.default_state("minecraft:barrier");
|
||||
let mut count = 0;
|
||||
for (_, to, s) in copies {
|
||||
if self.place_state(to, s, strict)? {
|
||||
for (_, to, s, entity) in copies {
|
||||
self.place_state(to, s, strict)?;
|
||||
if Some(s) != barrier {
|
||||
count += 1;
|
||||
}
|
||||
if let Some(e) = entity {
|
||||
self.world.block_entities.insert((to[0], to[1], to[2]), e);
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return Err(err("commands.clone.failed", &[]));
|
||||
@@ -1758,7 +1983,7 @@ impl Game<'_> {
|
||||
if self.ui.difficulty == i {
|
||||
return Err(CommandError::new(Text::translate(
|
||||
"commands.difficulty.failure",
|
||||
&[Text::literal(DIFFICULTIES[i as usize])],
|
||||
&[name(i)],
|
||||
)));
|
||||
}
|
||||
self.ui.difficulty = i;
|
||||
@@ -1808,7 +2033,7 @@ impl Game<'_> {
|
||||
dim,
|
||||
];
|
||||
let key = if targets.len() == 1 {
|
||||
args.push(Text::literal(PLAYER_NAME));
|
||||
args.push(self.target_name(targets[0]));
|
||||
"commands.spawnpoint.success.single"
|
||||
} else {
|
||||
args.push(Text::literal(targets.len().to_string()));
|
||||
@@ -1828,9 +2053,6 @@ impl Game<'_> {
|
||||
p[2].floor() as i32,
|
||||
]
|
||||
};
|
||||
if self.dim != Dim::Overworld {
|
||||
return Err(err("commands.setworldspawn.failure.not_overworld", &[]));
|
||||
}
|
||||
let rot = match ctx.get("rotation") {
|
||||
Some(Arg::Coords(c)) => c.rotation(self.source_rotation()),
|
||||
_ => [0.0, 0.0],
|
||||
@@ -1865,6 +2087,89 @@ impl Game<'_> {
|
||||
}
|
||||
predicate.id == item
|
||||
}
|
||||
/// `ItemPredicateArgument`: the item test and its `[...]` component
|
||||
/// tests (presence, `=` equality, `!` negation, `|` alternatives).
|
||||
pub(super) fn stack_matches(&self, predicate: &ItemInput, stack: &ItemStack) -> bool {
|
||||
if !self.item_matches(predicate, &stack.item) {
|
||||
return false;
|
||||
}
|
||||
let Some(tests) = predicate.components.as_deref() else {
|
||||
return true;
|
||||
};
|
||||
let inner = tests
|
||||
.trim()
|
||||
.strip_prefix('[')
|
||||
.and_then(|t| t.strip_suffix(']'))
|
||||
.unwrap_or("");
|
||||
let components = match horizon_client::item_data::encode_components(stack) {
|
||||
Some(horizon_world::nbt::Tag::Compound(c)) => c,
|
||||
_ => Default::default(),
|
||||
};
|
||||
let test = |term: &str| -> bool {
|
||||
let term = term.trim();
|
||||
let (negated, term) = match term.strip_prefix('!') {
|
||||
Some(t) => (true, t.trim()),
|
||||
None => (false, term),
|
||||
};
|
||||
let split = term.find(['=', '~']).unwrap_or(term.len());
|
||||
let id = term[..split].trim();
|
||||
let id = if id.contains(':') {
|
||||
id.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
};
|
||||
let present = components.get(&id.as_str().into());
|
||||
let result = match term[split..].chars().next() {
|
||||
Some('=') => {
|
||||
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
|
||||
.ok()
|
||||
.map(|(t, _)| t);
|
||||
match (present, value) {
|
||||
(Some(have), Some(want)) => {
|
||||
horizon_client::nbt_path::compare_nbt(&want, Some(have))
|
||||
&& horizon_client::nbt_path::compare_nbt(have, Some(&want))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
Some('~') => {
|
||||
// Sub-predicates: `count` and component predicates.
|
||||
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
|
||||
.ok()
|
||||
.map(|(t, _)| t);
|
||||
match (id.as_str(), value) {
|
||||
("minecraft:count", Some(v)) => {
|
||||
let n = i64::from(stack.count);
|
||||
match &v {
|
||||
horizon_world::nbt::Tag::Compound(_) => {
|
||||
let get = |k: &str| match v.get(k) {
|
||||
Some(horizon_world::nbt::Tag::Int(i)) => {
|
||||
Some(i64::from(*i))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
get("min").is_none_or(|m| n >= m)
|
||||
&& get("max").is_none_or(|m| n <= m)
|
||||
}
|
||||
horizon_world::nbt::Tag::Int(i) => n == i64::from(*i),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(_, Some(v)) => present.is_some_and(|have| {
|
||||
horizon_client::nbt_path::compare_nbt(&v, Some(have))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => present.is_some(),
|
||||
};
|
||||
result != negated
|
||||
};
|
||||
split_top_level(inner, ',')
|
||||
.iter()
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.all(|term| split_top_level(term, '|').iter().any(|alt| test(alt)))
|
||||
}
|
||||
fn cmd_clear(&mut self, ctx: &Context) -> R<i32> {
|
||||
let targets = if ctx.get("targets").is_some() {
|
||||
self.entities(ctx, "targets", true)?
|
||||
@@ -1885,19 +2190,30 @@ impl Game<'_> {
|
||||
// Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried.
|
||||
let mut removed = 0i32;
|
||||
let mut budget = if max < 0 { i32::MAX } else { max };
|
||||
let all = |g: &Self| -> Vec<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 +2231,6 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if predicate.tag {
|
||||
// Tag predicates: match against item tags.
|
||||
let pred = predicate.clone();
|
||||
let mut budget = if max < 0 { i32::MAX } else { max };
|
||||
let items: Vec<(usize, String, u32)> = self
|
||||
.inventory
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count)))
|
||||
.collect();
|
||||
for (i, item, count) in items {
|
||||
if !self.item_matches(&pred, &item) {
|
||||
continue;
|
||||
}
|
||||
let take = if counting {
|
||||
count as i32
|
||||
} else {
|
||||
(count as i32).min(budget)
|
||||
};
|
||||
removed += take;
|
||||
if !counting && let Some(s) = self.inventory[i].as_mut() {
|
||||
budget -= take;
|
||||
s.count -= take as u32;
|
||||
if s.count == 0 {
|
||||
self.inventory[i] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if removed == 0 {
|
||||
return Err(if targets.len() == 1 {
|
||||
CommandError::new(Text::translate(
|
||||
@@ -1964,35 +2251,179 @@ impl Game<'_> {
|
||||
));
|
||||
Ok(removed)
|
||||
}
|
||||
/// `PoiTypes`: the point of interest type of a block state.
|
||||
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
|
||||
let s = self.res.assets.registry.state(state)?;
|
||||
let name = s.name.strip_prefix("minecraft:")?;
|
||||
Some(match name {
|
||||
"blast_furnace" => "minecraft:armorer",
|
||||
"smoker" => "minecraft:butcher",
|
||||
"cartography_table" => "minecraft:cartographer",
|
||||
"brewing_stand" => "minecraft:cleric",
|
||||
"composter" => "minecraft:farmer",
|
||||
"barrel" => "minecraft:fisherman",
|
||||
"fletching_table" => "minecraft:fletcher",
|
||||
"cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => {
|
||||
"minecraft:leatherworker"
|
||||
}
|
||||
"lectern" => "minecraft:librarian",
|
||||
"stonecutter" => "minecraft:mason",
|
||||
"loom" => "minecraft:shepherd",
|
||||
"smithing_table" => "minecraft:toolsmith",
|
||||
"grindstone" => "minecraft:weaponsmith",
|
||||
"bell" => "minecraft:meeting",
|
||||
"beehive" => "minecraft:beehive",
|
||||
"bee_nest" => "minecraft:bee_nest",
|
||||
"nether_portal" => "minecraft:nether_portal",
|
||||
"lodestone" => "minecraft:lodestone",
|
||||
"test_instance_block" => "minecraft:test_instance",
|
||||
n if n.ends_with("_bed") => {
|
||||
if s.properties.get("part").map(String::as_str) != Some("head") {
|
||||
return None;
|
||||
}
|
||||
"minecraft:home"
|
||||
}
|
||||
n if n.ends_with("lightning_rod") => "minecraft:lightning_rod",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within
|
||||
/// 256 blocks of the source, over the loaded chunks.
|
||||
fn cmd_locate_poi(&mut self, ctx: &Context) -> R<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 +2433,11 @@ impl Game<'_> {
|
||||
suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let distance = d2.sqrt().floor() as i32;
|
||||
self.system_message(Text::translate(
|
||||
let distance = (d2 as f32).sqrt().floor() as i32;
|
||||
self.feedback(Text::translate(
|
||||
"commands.locate.biome.success",
|
||||
&[
|
||||
Text::literal(biome),
|
||||
Text::literal(shown),
|
||||
link,
|
||||
Text::literal(distance.to_string()),
|
||||
],
|
||||
@@ -2064,6 +2495,10 @@ impl Game<'_> {
|
||||
}
|
||||
/// The structures of a `worldgen/structure` tag, nested tags expanded.
|
||||
pub(super) fn structure_tag(&self, tag: &str) -> Vec<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 +2510,7 @@ impl Game<'_> {
|
||||
let file = self
|
||||
.options
|
||||
.resources
|
||||
.join(format!("data/{ns}/tags/worldgen/structure/{path}.json"));
|
||||
.join(format!("data/{ns}/tags/{registry}/{path}.json"));
|
||||
let Ok(v) = std::fs::read(file)
|
||||
.map_err(|_| ())
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).map_err(|_| ()))
|
||||
@@ -2126,6 +2561,9 @@ impl Game<'_> {
|
||||
.italic()
|
||||
}
|
||||
};
|
||||
if let Some(capture) = self.chat_capture.as_mut() {
|
||||
capture.push(line.clone());
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
self.ui
|
||||
.chat
|
||||
@@ -2165,3 +2603,33 @@ impl Game<'_> {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Split at a separator outside brackets, braces and quotes.
|
||||
fn split_top_level(s: &str, sep: char) -> Vec<&str> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quote, mut escaped, mut start) = (0i32, None::<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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<'_> {
|
||||
@@ -365,6 +373,7 @@ 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 },
|
||||
difficulty: self.local_difficulty(
|
||||
self.player
|
||||
.as_ref()
|
||||
@@ -466,6 +475,7 @@ impl Game<'_> {
|
||||
// The level random, lent to the mobs (brain behaviours draw from
|
||||
// it) and taken back after their ticks.
|
||||
let mut scratch = self.world.random.clone();
|
||||
let mut pushes = Vec::new();
|
||||
mobs.retain_mut(|m| {
|
||||
if !w
|
||||
.world
|
||||
@@ -473,7 +483,10 @@ 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);
|
||||
// Killed during its own tick (drowning, burning, falling...).
|
||||
if !m.alive() && !m.removed && died.insert(m.id) {
|
||||
dead.push(m.clone());
|
||||
@@ -483,7 +496,9 @@ impl Game<'_> {
|
||||
}
|
||||
keep
|
||||
});
|
||||
push_apart(&mut mobs);
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
level_random = scratch;
|
||||
}
|
||||
self.world.random = level_random;
|
||||
@@ -655,6 +670,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)
|
||||
}
|
||||
@@ -820,11 +846,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);
|
||||
@@ -2418,6 +2445,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).
|
||||
@@ -2455,42 +2483,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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -391,11 +391,12 @@ impl Game<'_> {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
let is_tnt = &*name == "minecraft:tnt";
|
||||
if !is_tnt {
|
||||
let drops = self.res.items.block_drops(
|
||||
let drops = self.res.items.block_drops_in(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&mut self.world.random,
|
||||
Some((&mut self.rand_sequences, self.level.seed)),
|
||||
);
|
||||
for stack in drops {
|
||||
if &*stack.item == "minecraft:air" || stack.count == 0 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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]) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -166,9 +167,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
|
||||
@@ -478,84 +486,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,899 @@
|
||||
//! The `Hud` overlays laid out as [`GuiDraw`] calls like
|
||||
//! [`crate::hud_layout`]: status effect icons (`extractEffects`), titles and
|
||||
//! the action bar (`extractTitle`, `extractOverlayMessage` and the title
|
||||
//! timers of `Hud.tick`), the selected item name (`extractSelectedItemName`
|
||||
//! and its `toolHighlightTimer`), boss bars (`BossHealthOverlay`), the jump
|
||||
//! bar (`JumpableVehicleBar`), the scoreboard sidebar, item decorations
|
||||
//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays and the
|
||||
//! sleep overlay.
|
||||
use crate::{
|
||||
font::Font,
|
||||
hud_layout::{
|
||||
Blend, GuiDraw, PoseOp, color_from_float, fill, hsv_to_argb, multiply, white, width,
|
||||
},
|
||||
text::{Style, Text},
|
||||
};
|
||||
use std::{borrow::Cow, cmp::Ordering};
|
||||
|
||||
/// `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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `graphics.textWithBackdrop`; `background` is `Options.getBackgroundColor(0.0F)`.
|
||||
pub fn text_with_backdrop(
|
||||
out: &mut Vec<GuiDraw>,
|
||||
t: Text,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
color: u32,
|
||||
background: u32,
|
||||
) {
|
||||
if background != 0 {
|
||||
out.push(fill(
|
||||
x - 2,
|
||||
y - 2,
|
||||
x + w + 2,
|
||||
y + 9 + 2,
|
||||
multiply(background, color),
|
||||
));
|
||||
}
|
||||
text(out, t, x, y, color, true);
|
||||
}
|
||||
|
||||
/// `Arrays.sort(T[], Comparator)` for the short arrays the HUD sorts: Java's
|
||||
/// TimSort below `MIN_MERGE` (a natural run, then binary insertion), which
|
||||
/// matters when the comparator is not a total order. Longer arrays fall back
|
||||
/// to a stable sort.
|
||||
pub fn java_sort<T>(a: &mut [T], cmp: impl Fn(&T, &T) -> Ordering) {
|
||||
let n = a.len();
|
||||
if n < 2 {
|
||||
return;
|
||||
}
|
||||
if n >= 32 {
|
||||
a.sort_by(cmp);
|
||||
return;
|
||||
}
|
||||
// countRunAndMakeAscending.
|
||||
let mut run = 2;
|
||||
if cmp(&a[1], &a[0]) == Ordering::Less {
|
||||
while run < n && cmp(&a[run], &a[run - 1]) == Ordering::Less {
|
||||
run += 1;
|
||||
}
|
||||
a[..run].reverse();
|
||||
} else {
|
||||
while run < n && cmp(&a[run], &a[run - 1]) != Ordering::Less {
|
||||
run += 1;
|
||||
}
|
||||
}
|
||||
// binarySort.
|
||||
for start in run..n {
|
||||
let (mut left, mut right) = (0, start);
|
||||
while left < right {
|
||||
let mid = (left + right) / 2;
|
||||
if cmp(&a[start], &a[mid]) == Ordering::Less {
|
||||
right = mid;
|
||||
} else {
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
a[left..=start].rotate_right(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `MobEffectInstance` as `extractEffects` sees it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EffectIcon {
|
||||
/// The effect id without namespace (`speed`): the sprite is `mob_effect/<id>`.
|
||||
pub id: String,
|
||||
/// `MobEffect.isBeneficial`.
|
||||
pub beneficial: bool,
|
||||
/// `MobEffect.getColor`.
|
||||
pub color: i32,
|
||||
pub ambient: bool,
|
||||
/// Remaining ticks, -1 for infinite.
|
||||
pub duration: i32,
|
||||
pub show_icon: bool,
|
||||
}
|
||||
|
||||
/// `MobEffectInstance.compareTo`.
|
||||
fn compare_effects(a: &EffectIcon, o: &EffectIcon) -> Ordering {
|
||||
if (a.duration <= 32147 || o.duration <= 32147) && !(a.ambient && o.ambient) {
|
||||
a.ambient
|
||||
.cmp(&o.ambient)
|
||||
.then((a.duration == -1).cmp(&(o.duration == -1)))
|
||||
.then(a.duration.cmp(&o.duration))
|
||||
.then(a.color.cmp(&o.color))
|
||||
} else {
|
||||
a.ambient.cmp(&o.ambient).then(a.color.cmp(&o.color))
|
||||
}
|
||||
}
|
||||
|
||||
/// `Hud.extractEffects`: `effects` in `getActiveEffects` order; `demo` moves
|
||||
/// the icons below the demo timer.
|
||||
pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let mut sorted: Vec<&EffectIcon> = effects.iter().collect();
|
||||
// Ordering.natural().reverse().sortedCopy.
|
||||
java_sort(&mut sorted, |a, b| compare_effects(b, a));
|
||||
let (mut beneficial, mut harmful) = (0, 0);
|
||||
for e in sorted.into_iter().filter(|e| e.show_icon) {
|
||||
let mut x = w;
|
||||
let mut y = 1 + if demo { 15 } else { 0 };
|
||||
if e.beneficial {
|
||||
beneficial += 1;
|
||||
x -= 25 * beneficial;
|
||||
} else {
|
||||
harmful += 1;
|
||||
x -= 25 * harmful;
|
||||
y += 26;
|
||||
}
|
||||
let mut alpha = 1.0f32;
|
||||
let background = if e.ambient {
|
||||
"hud/effect_background_ambient"
|
||||
} else {
|
||||
if e.duration != -1 && e.duration <= 200 {
|
||||
let remaining = e.duration;
|
||||
let used = 10 - remaining / 20;
|
||||
alpha = (remaining as f32 / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5)
|
||||
+ horizon_core::geometry::trig::cos(f64::from(
|
||||
remaining as f32 * std::f32::consts::PI / 5.0,
|
||||
)) * (used as f32 / 10.0 * 0.25).clamp(0.0, 0.25);
|
||||
alpha = alpha.clamp(0.0, 1.0);
|
||||
}
|
||||
"hud/effect_background"
|
||||
};
|
||||
out.push(GuiDraw::Sprite {
|
||||
sprite: Cow::Borrowed(background),
|
||||
x,
|
||||
y,
|
||||
w: 24,
|
||||
h: 24,
|
||||
region: None,
|
||||
color: crate::hud_layout::WHITE,
|
||||
});
|
||||
out.push(GuiDraw::Sprite {
|
||||
sprite: Cow::Owned(format!("mob_effect/{}", e.id)),
|
||||
x: x + 3,
|
||||
y: y + 3,
|
||||
w: 18,
|
||||
h: 18,
|
||||
region: None,
|
||||
color: white(alpha),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the
|
||||
/// fade times and `overlayMessageString` / `overlayMessageTime`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub 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 {
|
||||
/// `setTitle`.
|
||||
pub fn set_title(&mut self, title: Text) {
|
||||
self.title = Some(title);
|
||||
self.time = self.fade_in + self.stay + self.fade_out;
|
||||
}
|
||||
/// `setSubtitle`.
|
||||
pub fn set_subtitle(&mut self, subtitle: Text) {
|
||||
self.subtitle = Some(subtitle);
|
||||
}
|
||||
/// `setTimes`: negative values keep the current time.
|
||||
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;
|
||||
}
|
||||
}
|
||||
/// `clearTitles`.
|
||||
pub fn clear(&mut self) {
|
||||
self.title = None;
|
||||
self.subtitle = None;
|
||||
self.time = 0;
|
||||
}
|
||||
/// `resetTitleTimes`.
|
||||
pub fn reset_times(&mut self) {
|
||||
(self.fade_in, self.stay, self.fade_out) = (10, 70, 20);
|
||||
}
|
||||
/// `setOverlayMessage`.
|
||||
pub fn set_overlay(&mut self, text: Text, animate: bool) {
|
||||
self.overlay = Some(text);
|
||||
self.overlay_time = 60;
|
||||
self.overlay_animated = animate;
|
||||
}
|
||||
/// The title and action bar part of `Hud.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Hud.extractOverlayMessage`.
|
||||
pub fn overlay_message(
|
||||
&self,
|
||||
w: i32,
|
||||
h: i32,
|
||||
partial: f32,
|
||||
font: &Font,
|
||||
background: u32,
|
||||
) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let Some(message) = &self.overlay else {
|
||||
return out;
|
||||
};
|
||||
if self.overlay_time <= 0 {
|
||||
return out;
|
||||
}
|
||||
let t = self.overlay_time as f32 - partial;
|
||||
let alpha = ((t * 255.0 / 20.0) as i32).min(255);
|
||||
if alpha > 0 {
|
||||
out.push(GuiDraw::Push(vec![PoseOp::Translate(
|
||||
(w / 2) as f32,
|
||||
(h - 68) as f32,
|
||||
)]));
|
||||
let color = if self.overlay_animated {
|
||||
hsv_to_argb(t / 50.0, 0.7, 0.6, alpha as u32)
|
||||
} else {
|
||||
crate::hud_layout::argb(alpha as u32, 255, 255, 255)
|
||||
};
|
||||
let width = width(font, message);
|
||||
text_with_backdrop(
|
||||
&mut out,
|
||||
message.clone(),
|
||||
-width / 2,
|
||||
-4,
|
||||
width,
|
||||
color,
|
||||
background,
|
||||
);
|
||||
out.push(GuiDraw::Pop);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `Hud.extractTitle`.
|
||||
pub fn title(
|
||||
&self,
|
||||
w: i32,
|
||||
h: i32,
|
||||
partial: f32,
|
||||
font: &Font,
|
||||
background: u32,
|
||||
) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let Some(title) = &self.title else {
|
||||
return out;
|
||||
};
|
||||
if self.time <= 0 {
|
||||
return out;
|
||||
}
|
||||
let t = self.time as f32 - partial;
|
||||
let mut alpha = 255;
|
||||
if self.time > self.fade_out + self.stay {
|
||||
let time = (self.fade_in + self.stay + self.fade_out) as f32 - t;
|
||||
alpha = (time * 255.0 / self.fade_in as f32) as i32;
|
||||
}
|
||||
if self.time <= self.fade_out {
|
||||
alpha = (t * 255.0 / self.fade_out as f32) as i32;
|
||||
}
|
||||
let alpha = alpha.clamp(0, 255);
|
||||
if alpha > 0 {
|
||||
out.push(GuiDraw::Push(vec![PoseOp::Translate(
|
||||
(w / 2) as f32,
|
||||
(h / 2) as f32,
|
||||
)]));
|
||||
out.push(GuiDraw::Push(vec![PoseOp::Scale(4.0, 4.0)]));
|
||||
let title_width = width(font, title);
|
||||
let color = crate::hud_layout::argb(alpha as u32, 255, 255, 255);
|
||||
text_with_backdrop(
|
||||
&mut out,
|
||||
title.clone(),
|
||||
-title_width / 2,
|
||||
-10,
|
||||
title_width,
|
||||
color,
|
||||
background,
|
||||
);
|
||||
out.push(GuiDraw::Pop);
|
||||
if let Some(subtitle) = &self.subtitle {
|
||||
out.push(GuiDraw::Push(vec![PoseOp::Scale(2.0, 2.0)]));
|
||||
let subtitle_width = width(font, subtitle);
|
||||
text_with_backdrop(
|
||||
&mut out,
|
||||
subtitle.clone(),
|
||||
-subtitle_width / 2,
|
||||
5,
|
||||
subtitle_width,
|
||||
color,
|
||||
background,
|
||||
);
|
||||
out.push(GuiDraw::Pop);
|
||||
}
|
||||
out.push(GuiDraw::Pop);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected item as `Hud.tick` compares it: its item id and hover name.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct HeldName {
|
||||
pub item: String,
|
||||
/// `ItemStack.getHoverName`.
|
||||
pub hover_name: Text,
|
||||
/// `getRarity().color()`.
|
||||
pub rarity_color: u32,
|
||||
/// The stack has `CUSTOM_NAME`.
|
||||
pub custom_name: bool,
|
||||
}
|
||||
|
||||
/// `Hud.toolHighlightTimer` and `lastToolHighlight`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ToolHighlight {
|
||||
pub timer: i32,
|
||||
pub last: Option<HeldName>,
|
||||
}
|
||||
impl ToolHighlight {
|
||||
/// The selected-item part of `Hud.tick`; `display_time` is the
|
||||
/// `notificationDisplayTime` option.
|
||||
pub fn tick(&mut self, selected: Option<HeldName>, display_time: f64) {
|
||||
match &selected {
|
||||
None => self.timer = 0,
|
||||
Some(s) => {
|
||||
let changed = self
|
||||
.last
|
||||
.as_ref()
|
||||
.is_none_or(|l| l.item != s.item || l.hover_name != s.hover_name);
|
||||
if changed {
|
||||
self.timer = (40.0 * display_time) as i32;
|
||||
} else if self.timer > 0 {
|
||||
self.timer -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.last = selected;
|
||||
}
|
||||
/// `Hud.extractSelectedItemName`; `can_hurt` is
|
||||
/// `gameMode.canHurtPlayer()` (survival and adventure).
|
||||
pub fn draw(
|
||||
&self,
|
||||
w: i32,
|
||||
h: i32,
|
||||
can_hurt: bool,
|
||||
font: &Font,
|
||||
background: u32,
|
||||
) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let Some(last) = &self.last else {
|
||||
return out;
|
||||
};
|
||||
if self.timer <= 0 {
|
||||
return out;
|
||||
}
|
||||
let mut name = last.hover_name.clone().with_color(last.rarity_color);
|
||||
if last.custom_name {
|
||||
name = name.with_style(&Style {
|
||||
italic: Some(true),
|
||||
..Style::default()
|
||||
});
|
||||
}
|
||||
let str_width = width(font, &name);
|
||||
let x = (w - str_width) / 2;
|
||||
let mut y = h - 59;
|
||||
if !can_hurt {
|
||||
y += 14;
|
||||
}
|
||||
let alpha = ((self.timer as f32 * 256.0 / 10.0) as i32).min(255);
|
||||
if alpha > 0 {
|
||||
let color = crate::hud_layout::argb(alpha as u32, 255, 255, 255);
|
||||
text_with_backdrop(&mut out, name, x, y, str_width, color, background);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// One `LerpingBossEvent` as `BossHealthOverlay` draws it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BossBar {
|
||||
pub name: Text,
|
||||
/// `getProgress()` (the lerped value).
|
||||
pub progress: f32,
|
||||
/// `BossBarColor` ordinal: pink, blue, red, green, yellow, purple, white.
|
||||
pub color: usize,
|
||||
/// `BossBarOverlay` ordinal: progress, notched_6, _10, _12, _20.
|
||||
pub overlay: usize,
|
||||
}
|
||||
const BOSS_COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"];
|
||||
const BOSS_OVERLAYS: [&str; 5] = [
|
||||
"progress",
|
||||
"notched_6",
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
];
|
||||
|
||||
/// `BossHealthOverlay.extractRenderState`: the bars in event order, 19 pixels
|
||||
/// apart from y = 12 until a third of the screen height.
|
||||
pub fn boss_overlay(w: i32, h: i32, bars: &[BossBar], font: &Font) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
let mut y_offset = 12;
|
||||
for bar in bars {
|
||||
let x_left = w / 2 - 91;
|
||||
let part = |out: &mut Vec<GuiDraw>, width: i32, kind: &str| {
|
||||
let sprite = |name: String| GuiDraw::Sprite {
|
||||
sprite: Cow::Owned(format!("boss_bar/{name}_{kind}")),
|
||||
x: x_left,
|
||||
y: y_offset,
|
||||
w: width,
|
||||
h: 5,
|
||||
region: Some([182, 5, 0, 0]),
|
||||
color: crate::hud_layout::WHITE,
|
||||
};
|
||||
out.push(sprite(BOSS_COLORS[bar.color].to_owned()));
|
||||
if bar.overlay != 0 {
|
||||
out.push(sprite(BOSS_OVERLAYS[bar.overlay].to_owned()));
|
||||
}
|
||||
};
|
||||
part(&mut out, 182, "background");
|
||||
let progress = crate::hud_layout::lerp_discrete(bar.progress, 0, 182);
|
||||
if progress > 0 {
|
||||
part(&mut out, progress, "progress");
|
||||
}
|
||||
let width = width(font, &bar.name);
|
||||
text(
|
||||
&mut out,
|
||||
bar.name.clone(),
|
||||
w / 2 - width / 2,
|
||||
y_offset - 9,
|
||||
crate::hud_layout::WHITE,
|
||||
true,
|
||||
);
|
||||
y_offset += 10 + 9;
|
||||
if y_offset >= h / 3 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `JumpableVehicleBar.extractBackground`: `cooldown` is the mount's jump
|
||||
/// cooldown and `scale` the player's `getJumpRidingScale()`.
|
||||
pub fn jump_bar(w: i32, h: i32, cooldown: i32, scale: f32) -> Vec<GuiDraw> {
|
||||
let (left, top) = ((w - 182) / 2, h - 24 - 5);
|
||||
let sprite = |name: &'static str, width: i32, region: Option<[i32; 4]>| GuiDraw::Sprite {
|
||||
sprite: Cow::Borrowed(name),
|
||||
x: left,
|
||||
y: top,
|
||||
w: width,
|
||||
h: 5,
|
||||
region,
|
||||
color: crate::hud_layout::WHITE,
|
||||
};
|
||||
let mut out = vec![sprite("hud/jump_bar_background", 182, None)];
|
||||
if cooldown > 0 {
|
||||
out.push(sprite("hud/jump_bar_cooldown", 182, None));
|
||||
} else {
|
||||
let progress = crate::hud_layout::lerp_discrete(scale, 0, 182);
|
||||
if progress > 0 {
|
||||
out.push(sprite(
|
||||
"hud/jump_bar_progress",
|
||||
progress,
|
||||
Some([182, 5, 0, 0]),
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `String.CASE_INSENSITIVE_ORDER` over UTF-16 code units.
|
||||
pub fn compare_ignore_case(a: &str, b: &str) -> Ordering {
|
||||
fn single(mut it: impl Iterator<Item = char>, c: char) -> char {
|
||||
match (it.next(), it.next()) {
|
||||
(Some(m), None) => m,
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
let unit = |u: u16| char::from_u32(u32::from(u));
|
||||
let (x, y): (Vec<u16>, Vec<u16>) = (a.encode_utf16().collect(), b.encode_utf16().collect());
|
||||
for (&p, &q) in x.iter().zip(&y) {
|
||||
if p == q {
|
||||
continue;
|
||||
}
|
||||
let (Some(c1), Some(c2)) = (unit(p), unit(q)) else {
|
||||
return p.cmp(&q);
|
||||
};
|
||||
let (u1, u2) = (single(c1.to_uppercase(), c1), single(c2.to_uppercase(), c2));
|
||||
if u1 != u2 {
|
||||
let (l1, l2) = (single(u1.to_lowercase(), u1), single(u2.to_lowercase(), u2));
|
||||
if l1 != l2 {
|
||||
return (l1 as u32).cmp(&(l2 as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
x.len().cmp(&y.len())
|
||||
}
|
||||
|
||||
/// `Hud.displayScoreboardSidebar` for `objective`; `background` and
|
||||
/// `header` are `Options.getBackgroundColor(0.3F)` and `(0.4F)`.
|
||||
pub fn sidebar(
|
||||
w: i32,
|
||||
h: i32,
|
||||
board: &crate::scoreboard::Scoreboard,
|
||||
objective: &crate::scoreboard::Objective,
|
||||
font: &Font,
|
||||
background: u32,
|
||||
header: u32,
|
||||
) -> Vec<GuiDraw> {
|
||||
use crate::scoreboard::NumberFormat;
|
||||
let format = objective.format_or_default(NumberFormat::sidebar_default());
|
||||
let mut entries: Vec<_> = board
|
||||
.list_scores(&objective.name)
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_hidden())
|
||||
.collect();
|
||||
// SCORE_DISPLAY_ORDER: highest value first, then owners case-insensitively.
|
||||
java_sort(&mut entries, |a, b| {
|
||||
b.value
|
||||
.cmp(&a.value)
|
||||
.then_with(|| compare_ignore_case(&a.owner, &b.owner))
|
||||
});
|
||||
entries.truncate(15);
|
||||
let rows: Vec<(Text, Text, i32)> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let name = match board.players_team(&e.owner) {
|
||||
Some(team) => team.formatted_name(e.owner_name()),
|
||||
None => e.owner_name(),
|
||||
};
|
||||
let score = e.format_value(&format);
|
||||
let score_width = width(font, &score);
|
||||
(name, score, score_width)
|
||||
})
|
||||
.collect();
|
||||
let title = objective.display_text();
|
||||
let title_width = width(font, &title);
|
||||
let spacer = font.width(": ") as i32;
|
||||
let mut biggest = title_width;
|
||||
for (name, _, score_width) in &rows {
|
||||
let extra = if *score_width > 0 {
|
||||
spacer + score_width
|
||||
} else {
|
||||
0
|
||||
};
|
||||
biggest = biggest.max(width(font, name) + extra);
|
||||
}
|
||||
let count = rows.len() as i32;
|
||||
let height = count * 9;
|
||||
let bottom = h / 2 + height / 3;
|
||||
let left = w - biggest - 3;
|
||||
let right = w - 3 + 2;
|
||||
let header_y = bottom - count * 9;
|
||||
let mut out = vec![
|
||||
fill(left - 2, header_y - 9 - 1, right, header_y - 1, header),
|
||||
fill(left - 2, header_y - 1, right, bottom, background),
|
||||
];
|
||||
let white = crate::hud_layout::WHITE;
|
||||
text(
|
||||
&mut out,
|
||||
title,
|
||||
left + biggest / 2 - title_width / 2,
|
||||
header_y - 9,
|
||||
white,
|
||||
false,
|
||||
);
|
||||
for (i, (name, score, score_width)) in rows.into_iter().enumerate() {
|
||||
let y = bottom - (count - i as i32) * 9;
|
||||
text(&mut out, name, left, y, white, false);
|
||||
text(&mut out, score, right - score_width, y, white, false);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `GuiGraphicsExtractor.itemDecorations` draws over a stack.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ItemDecorations {
|
||||
pub count: u32,
|
||||
/// The text shown instead of the count, if any.
|
||||
pub count_text: Option<String>,
|
||||
/// `isBarVisible`: `getBarWidth` and `getBarColor` (RGB).
|
||||
pub bar: Option<(i32, u32)>,
|
||||
/// `ItemCooldowns.getCooldownPercent` of the stack.
|
||||
pub cooldown: f32,
|
||||
}
|
||||
|
||||
/// `Item.getBarWidth` and `getBarColor` for a damaged stack (`isDamaged`).
|
||||
pub fn damage_bar(damage: i32, max_damage: i32) -> Option<(i32, u32)> {
|
||||
if max_damage <= 0 || damage <= 0 {
|
||||
return None;
|
||||
}
|
||||
let width = (13.0 - damage as f32 * 13.0 / max_damage as f32)
|
||||
.round()
|
||||
.clamp(0.0, 13.0) as i32;
|
||||
let health = ((max_damage as f32 - damage as f32) / max_damage as f32).max(0.0);
|
||||
Some((width, hsv_to_argb(health / 3.0, 1.0, 1.0, 0)))
|
||||
}
|
||||
|
||||
/// `GuiGraphicsExtractor.itemDecorations` for a non-empty stack at (x, y):
|
||||
/// the durability bar, the cooldown shade and the count.
|
||||
pub fn item_decorations(x: i32, y: i32, d: &ItemDecorations, font: &Font) -> Vec<GuiDraw> {
|
||||
let mut out = vec![GuiDraw::Push(Vec::new())];
|
||||
if let Some((width, color)) = d.bar {
|
||||
let (left, top) = (x + 2, y + 13);
|
||||
out.push(fill(left, top, left + 13, top + 2, 0xFF00_0000));
|
||||
out.push(fill(left, top, left + width, top + 1, color | 0xFF00_0000));
|
||||
}
|
||||
if d.cooldown > 0.0 {
|
||||
let top = y + crate::hud_layout::floor(16.0 * (1.0 - d.cooldown));
|
||||
let bottom = top + crate::hud_layout::ceil(16.0 * d.cooldown);
|
||||
out.push(fill(x, top, x + 16, bottom, 0x7FFF_FFFF));
|
||||
}
|
||||
if d.count != 1 || d.count_text.is_some() {
|
||||
let amount = d.count_text.clone().unwrap_or_else(|| d.count.to_string());
|
||||
let w = font.width(&amount) as i32;
|
||||
text(
|
||||
&mut out,
|
||||
Text::literal(amount),
|
||||
x + 19 - 2 - w,
|
||||
y + 6 + 3,
|
||||
crate::hud_layout::WHITE,
|
||||
true,
|
||||
);
|
||||
}
|
||||
out.push(GuiDraw::Pop);
|
||||
out
|
||||
}
|
||||
|
||||
/// A full-screen `graphics.blit` of `textures/<texture>.png`.
|
||||
fn screen_blit(
|
||||
w: i32,
|
||||
h: i32,
|
||||
texture: impl Into<Cow<'static, str>>,
|
||||
blend: Blend,
|
||||
color: u32,
|
||||
) -> GuiDraw {
|
||||
GuiDraw::Blit {
|
||||
texture: texture.into(),
|
||||
blend,
|
||||
x: 0,
|
||||
y: 0,
|
||||
w,
|
||||
h,
|
||||
uv: [0.0, 0.0],
|
||||
src: [w, h],
|
||||
tex: [w, h],
|
||||
color,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Hud.extractVignette`: `brightness` is `vignetteBrightness` and
|
||||
/// `border_warning` the world border warning strength (0 when far).
|
||||
pub fn vignette(w: i32, h: i32, brightness: f32, border_warning: f32) -> GuiDraw {
|
||||
let brightness = brightness.clamp(0.0, 1.0);
|
||||
let color = if border_warning > 0.0 {
|
||||
let warning = border_warning.clamp(0.0, 1.0);
|
||||
let red = brightness * (1.0 - warning);
|
||||
let green_blue = brightness + (1.0 - brightness) * warning;
|
||||
color_from_float(1.0, red, green_blue, green_blue)
|
||||
} else {
|
||||
color_from_float(1.0, brightness, brightness, brightness)
|
||||
};
|
||||
screen_blit(w, h, "misc/vignette", Blend::Vignette, color)
|
||||
}
|
||||
|
||||
/// The border warning strength of `extractVignette` for a camera
|
||||
/// `distance` from a border with `warning_blocks`, `warning_time`, its
|
||||
/// `lerp_speed` and how far its size still has to move.
|
||||
pub fn border_warning(
|
||||
distance: f32,
|
||||
warning_blocks: i32,
|
||||
warning_time: i32,
|
||||
lerp_speed: f64,
|
||||
size_left: f64,
|
||||
) -> f32 {
|
||||
let moving = (lerp_speed * f64::from(warning_time)).min(size_left.abs());
|
||||
let warning_distance = f64::from(warning_blocks).max(moving);
|
||||
if f64::from(distance) < warning_distance {
|
||||
1.0 - (f64::from(distance) / warning_distance) as f32
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// `Hud.extractSpyglassOverlay`.
|
||||
pub fn spyglass(w: i32, h: i32, scale: f32) -> Vec<GuiDraw> {
|
||||
let src = w.min(h) as f32;
|
||||
let ratio = (w as f32 / src).min(h as f32 / src) * scale;
|
||||
let width = crate::hud_layout::floor(src * ratio);
|
||||
let height = crate::hud_layout::floor(src * ratio);
|
||||
let left = (w - width) / 2;
|
||||
let top = (h - height) / 2;
|
||||
let (right, bottom) = (left + width, top + height);
|
||||
vec![
|
||||
GuiDraw::Blit {
|
||||
texture: Cow::Borrowed("misc/spyglass_scope"),
|
||||
blend: Blend::Textured,
|
||||
x: left,
|
||||
y: top,
|
||||
w: width,
|
||||
h: height,
|
||||
uv: [0.0, 0.0],
|
||||
src: [width, height],
|
||||
tex: [width, height],
|
||||
color: crate::hud_layout::WHITE,
|
||||
},
|
||||
fill(0, bottom, w, h, 0xFF00_0000),
|
||||
fill(0, 0, w, top, 0xFF00_0000),
|
||||
fill(0, top, left, bottom, 0xFF00_0000),
|
||||
fill(right, top, w, bottom, 0xFF00_0000),
|
||||
]
|
||||
}
|
||||
|
||||
/// `Hud.extractPortalOverlay`: the nether portal block sprite over the screen.
|
||||
pub fn portal_overlay(w: i32, h: i32, mut alpha: f32) -> GuiDraw {
|
||||
if alpha < 1.0 {
|
||||
alpha *= alpha;
|
||||
alpha *= alpha;
|
||||
alpha = alpha * 0.8 + 0.2;
|
||||
}
|
||||
GuiDraw::AtlasSprite {
|
||||
sprite: Cow::Borrowed("block/nether_portal"),
|
||||
x: 0,
|
||||
y: 0,
|
||||
w,
|
||||
h,
|
||||
color: white(alpha),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Hud.extractConfusionOverlay`: the nausea swirl scaled about the centre.
|
||||
pub fn confusion_overlay(w: i32, h: i32, strength: f32) -> Vec<GuiDraw> {
|
||||
let size = 2.0 + strength * (1.0 - 2.0);
|
||||
let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
|
||||
vec![
|
||||
GuiDraw::Push(vec![
|
||||
PoseOp::Translate(cx, cy),
|
||||
PoseOp::Scale(size, size),
|
||||
PoseOp::Translate(-cx, -cy),
|
||||
]),
|
||||
screen_blit(
|
||||
w,
|
||||
h,
|
||||
"misc/nausea",
|
||||
Blend::Nausea,
|
||||
color_from_float(1.0, 0.2 * strength, 0.4 * strength, 0.2 * strength),
|
||||
),
|
||||
GuiDraw::Pop,
|
||||
]
|
||||
}
|
||||
|
||||
/// What `Hud.extractCameraOverlays` reads.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CameraOverlays {
|
||||
/// `Options.vignette`: `vignetteBrightness` and the border warning strength.
|
||||
pub vignette: Option<(f32, f32)>,
|
||||
pub first_person: bool,
|
||||
/// `LocalPlayer.isScoping`.
|
||||
pub scoping: bool,
|
||||
/// `DeltaTracker.getGameTimeDeltaTicks`.
|
||||
pub game_time_delta: f32,
|
||||
/// `Equippable.cameraOverlay` textures (`misc/pumpkinblur`) of the worn
|
||||
/// items in `EquipmentSlot` order.
|
||||
pub equipment: Vec<String>,
|
||||
/// `getTicksFrozen` and `getPercentFrozen`.
|
||||
pub ticks_frozen: i32,
|
||||
pub percent_frozen: f32,
|
||||
/// The partial tick and `oPortalEffectIntensity` / `portalEffectIntensity`.
|
||||
pub partial: f32,
|
||||
pub portal: [f32; 2],
|
||||
/// `getEffectBlendFactor(NAUSEA, partial)` and `Options.screenEffectScale`.
|
||||
pub nausea: f32,
|
||||
pub screen_effect_scale: f32,
|
||||
}
|
||||
|
||||
/// `Hud.extractCameraOverlays`, easing `scope_scale` (`Hud.scopeScale`).
|
||||
pub fn camera_overlays(w: i32, h: i32, i: &CameraOverlays, scope_scale: &mut f32) -> Vec<GuiDraw> {
|
||||
let mut out = Vec::new();
|
||||
if let Some((brightness, warning)) = i.vignette {
|
||||
out.push(vignette(w, h, brightness, warning));
|
||||
}
|
||||
*scope_scale += 0.5 * i.game_time_delta * (1.125 - *scope_scale);
|
||||
if i.first_person {
|
||||
if i.scoping {
|
||||
out.extend(spyglass(w, h, *scope_scale));
|
||||
} else {
|
||||
*scope_scale = 0.5;
|
||||
for texture in &i.equipment {
|
||||
out.push(screen_blit(
|
||||
w,
|
||||
h,
|
||||
texture.clone(),
|
||||
Blend::Textured,
|
||||
crate::hud_layout::WHITE,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if i.ticks_frozen > 0 {
|
||||
out.push(screen_blit(
|
||||
w,
|
||||
h,
|
||||
"misc/powder_snow_outline",
|
||||
Blend::Textured,
|
||||
white(i.percent_frozen),
|
||||
));
|
||||
}
|
||||
let portal = i.portal[0] + i.partial * (i.portal[1] - i.portal[0]);
|
||||
if portal > 0.0 {
|
||||
out.push(portal_overlay(w, h, portal));
|
||||
} else if i.nausea > 0.0 && i.screen_effect_scale < 1.0 {
|
||||
out.extend(confusion_overlay(
|
||||
w,
|
||||
h,
|
||||
i.nausea * (1.0 - i.screen_effect_scale),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `Hud.extractSleepOverlay`.
|
||||
pub fn sleep_overlay(w: i32, h: i32, sleep_timer: i32) -> Vec<GuiDraw> {
|
||||
if sleep_timer <= 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let timer = sleep_timer as f32;
|
||||
let mut amount = timer / 100.0;
|
||||
if amount > 1.0 {
|
||||
amount = 1.0 - (timer - 100.0) / 10.0;
|
||||
}
|
||||
let color = (((220.0 * amount) as i32) << 24) as u32 | 0x10_1020;
|
||||
vec![fill(0, 0, w, h, color)]
|
||||
}
|
||||
@@ -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::{
|
||||
@@ -526,6 +526,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 +557,24 @@ 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 impl RandomSource,
|
||||
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> {
|
||||
let Some(block) = registry.state(state) else {
|
||||
return vec![];
|
||||
@@ -564,6 +592,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 +618,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 +666,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 +689,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 +729,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 +760,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 +777,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 +886,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 +899,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) {
|
||||
@@ -917,10 +960,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 +992,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 +1072,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;
|
||||
|
||||
@@ -56,6 +56,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 +360,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 +417,7 @@ impl Damage {
|
||||
| DamageKind::InWall
|
||||
| DamageKind::Generic
|
||||
| DamageKind::SonicBoom
|
||||
| DamageKind::OutOfWorld
|
||||
)
|
||||
}
|
||||
pub fn is_fire(&self) -> bool {
|
||||
@@ -436,6 +440,7 @@ impl Damage {
|
||||
| DamageKind::Cactus
|
||||
| DamageKind::Generic
|
||||
| DamageKind::InWall
|
||||
| DamageKind::OutOfWorld
|
||||
)
|
||||
}
|
||||
pub fn is_projectile(&self) -> bool {
|
||||
@@ -591,6 +596,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,
|
||||
@@ -622,6 +630,15 @@ pub enum MobEvent {
|
||||
Sound(&'static str, [f64; 3], f32, f32),
|
||||
/// 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 +893,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)]
|
||||
@@ -929,6 +1000,8 @@ 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,
|
||||
}
|
||||
impl Mob {
|
||||
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
|
||||
@@ -972,6 +1045,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 +1238,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 = [
|
||||
|
||||
@@ -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 {
|
||||
@@ -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),
|
||||
@@ -201,7 +206,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 +224,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 +270,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 +352,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 +362,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 +379,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 +408,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 +547,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 +577,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 +592,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 +629,82 @@ 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));
|
||||
}
|
||||
}
|
||||
// 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 +719,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 +753,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 +783,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 +794,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),
|
||||
@@ -939,13 +1091,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,
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,22 @@ 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 {
|
||||
if p.creative {
|
||||
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 +617,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 +689,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 +702,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 +1042,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 +1076,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 +1108,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 +1145,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 +1976,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 +2029,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 +2041,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 {
|
||||
|
||||
@@ -284,7 +284,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,
|
||||
|
||||
@@ -586,7 +586,7 @@ impl SpawnLevel for super::MobWorld<'_> {
|
||||
self.thundering
|
||||
}
|
||||
fn sea_level(&self) -> i32 {
|
||||
if self.nether { 32 } else { 63 }
|
||||
self.sea_level
|
||||
}
|
||||
fn world_surface(&self, x: i32, z: i32) -> i32 {
|
||||
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;
|
||||
|
||||
@@ -220,10 +220,15 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
// AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on
|
||||
// registration).
|
||||
// AbstractSkeleton.populateDefaultEquipmentSlots: armour, then a bow.
|
||||
S::Skeleton | S::Stray | S::Bogged | S::Parched => {
|
||||
populate_armor(m, difficulty);
|
||||
m.extra.main_hand = Some("minecraft:bow".into());
|
||||
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
|
||||
}
|
||||
// WitherSkeleton.populateDefaultEquipmentSlots: a stone sword only.
|
||||
S::WitherSkeleton => {
|
||||
m.extra.main_hand = Some("minecraft:stone_sword".into());
|
||||
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
|
||||
}
|
||||
S::Pillager => {
|
||||
|
||||
@@ -44,10 +44,10 @@ pub fn register(m: &mut Mob) {
|
||||
for (species, distance) in [
|
||||
(Species::Zombie, 8.0),
|
||||
(Species::Evoker, 12.0),
|
||||
(Species::Illusioner, 12.0),
|
||||
(Species::Vindicator, 8.0),
|
||||
(Species::Vex, 8.0),
|
||||
(Species::Pillager, 15.0),
|
||||
(Species::Illusioner, 12.0),
|
||||
(Species::Zoglin, 10.0),
|
||||
] {
|
||||
// `Zombie.class` covers the zombie family.
|
||||
@@ -78,8 +78,8 @@ pub fn register(m: &mut Mob) {
|
||||
);
|
||||
g.add(4, MoveTowardsRestriction::new(0.35));
|
||||
g.add(8, Stroll::avoiding_water(0.35));
|
||||
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::new(8.0));
|
||||
g.add(9, LookAtPlayer::interact(3.0, 1.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
}
|
||||
fn invisible(m: &Mob) -> bool {
|
||||
m.extra.effects.iter().any(|e| e.0 == INVISIBILITY)
|
||||
|
||||
@@ -15,6 +15,7 @@ pub fn register(m: &mut Mob) {
|
||||
match m.species() {
|
||||
S::Zombie | S::Husk | S::ZombieVillager => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(4, AttackTurtleEgg::default());
|
||||
g.add(8, LookAtPlayer::new(8.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
g.add(3, MeleeAttack::new(1.0, false).zombie());
|
||||
@@ -55,24 +56,53 @@ pub fn register(m: &mut Mob) {
|
||||
);
|
||||
}
|
||||
S::Drowned => {
|
||||
// Zombie.registerGoals, then Drowned.addBehaviourGoals.
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, DrownedGoToWater::default());
|
||||
g.add(2, MeleeAttack::new(1.0, false).zombie());
|
||||
g.add(5, Stroll::new(1.0));
|
||||
g.add(4, AttackTurtleEgg::default());
|
||||
g.add(8, LookAtPlayer::new(8.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
g.add(1, DrownedGoToWater::default());
|
||||
g.add(
|
||||
2,
|
||||
DrownedTridentAttack(super::witch::RangedAttack::new(
|
||||
1.0,
|
||||
40,
|
||||
40,
|
||||
10.0,
|
||||
drowned_throw,
|
||||
)),
|
||||
);
|
||||
g.add(2, DrownedAttack(MeleeAttack::new(1.0, false).zombie()));
|
||||
g.add(
|
||||
5,
|
||||
DrownedGoToBeach(super::goals::MoveToBlock::new(1.0, 8, 2)),
|
||||
);
|
||||
g.add(6, DrownedSwimUp { stuck: false });
|
||||
g.add(7, Stroll::new(1.0));
|
||||
let t = &mut m.ai.targets;
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
let mut hurt = HurtByTarget::new().alert().ignoring(&[S::Drowned]);
|
||||
hurt.alert_except = vec![S::ZombifiedPiglin];
|
||||
t.add(1, hurt);
|
||||
t.add(2, NearestTarget::player(false).when(drowned_can_attack));
|
||||
t.add(2, NearestTarget::player(true).when(drowned_can_attack));
|
||||
t.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::Villager, S::WanderingTrader], false),
|
||||
);
|
||||
t.add(3, NearestTarget::species(&[S::IronGolem], true));
|
||||
t.add(3, NearestTarget::species(&[S::Axolotl], true).interval(10));
|
||||
t.add(3, NearestTarget::species(&[S::Axolotl], true));
|
||||
t.add(
|
||||
5,
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby),
|
||||
true,
|
||||
)
|
||||
.interval(10),
|
||||
);
|
||||
// DrownedMoveControl, AmphibiousPathNavigation, no water malus.
|
||||
m.ai.mov.kind = super::control::MoveKind::Custom;
|
||||
m.ai.nav.kind = super::nav::NavKind::Amphibious;
|
||||
m.ai.nav.can_float = false;
|
||||
m.set_malus(super::path::PathType::Water, 0.0);
|
||||
}
|
||||
S::Skeleton | S::Stray | S::Bogged | S::Parched | S::WitherSkeleton => {
|
||||
let species = m.species();
|
||||
@@ -103,30 +133,280 @@ pub fn register(m: &mut Mob) {
|
||||
3,
|
||||
NearestTarget::species(&[S::Piglin, S::PiglinBrute], true),
|
||||
);
|
||||
m.extra.main_hand = Some("minecraft:stone_sword".into());
|
||||
m.ai.goals.add(4, MeleeAttack::new(1.2, false));
|
||||
} else {
|
||||
m.extra.main_hand = Some("minecraft:bow".into());
|
||||
let interval = if matches!(m.species(), S::Bogged | S::Parched) {
|
||||
70
|
||||
} else {
|
||||
40
|
||||
};
|
||||
m.ai.goals.add(4, BowAttack::new(1.0, interval, 15.0));
|
||||
}
|
||||
// The AbstractSkeleton constructor's reassessWeaponGoal, after
|
||||
// registerGoals; the weapon itself comes with finalizeSpawn.
|
||||
let interval = if matches!(species, S::Bogged | S::Parched) {
|
||||
70
|
||||
} else {
|
||||
40
|
||||
};
|
||||
m.ai.goals.add(4, SkeletonWeapon::new(interval));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn drowned_can_attack(m: &Mob, w: &super::MobWorld) -> bool {
|
||||
// Drowned.okTarget: at night or when the target is in water.
|
||||
/// Drowned.okTarget: at night, or when the target is in water.
|
||||
fn drowned_can_attack(_m: &Mob, w: &super::MobWorld) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
let (x, y, z) = (
|
||||
p.position.x.floor() as i32,
|
||||
p.position.y.floor() as i32,
|
||||
p.position.z.floor() as i32,
|
||||
!w.daylight || in_water_at(w, p.position)
|
||||
}
|
||||
/// The target's isInWater, from the water at its feet.
|
||||
fn in_water_at(w: &super::MobWorld, p: Vec3) -> bool {
|
||||
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
|
||||
w.fluid(x, y, z) == crate::blocks::Fluid::Water
|
||||
}
|
||||
/// Drowned.okTarget for the current target.
|
||||
fn drowned_ok_target(m: &Mob, w: &super::MobWorld) -> bool {
|
||||
m.target_info(w)
|
||||
.is_some_and(|t| !w.daylight || in_water_at(w, t.position))
|
||||
}
|
||||
// Drowned state: `flag` wantsToSwim (target in water), `flag2` searchingForLand.
|
||||
/// Drowned.wantsToSwim
|
||||
pub fn drowned_wants_to_swim(m: &Mob, w: &super::MobWorld) -> bool {
|
||||
m.extra.flag2 || m.target_info(w).is_some_and(|t| in_water_at(w, t.position))
|
||||
}
|
||||
/// Drowned.DrownedMoveControl
|
||||
pub fn drowned_move_control(m: &mut Mob, w: &super::MobWorld) {
|
||||
let target = m.target_info(w);
|
||||
if drowned_wants_to_swim(m, w) && m.fluids.in_water {
|
||||
if target.is_some_and(|t| t.position.y > m.position.y) || m.extra.flag2 {
|
||||
m.velocity = Vec3::new(m.velocity.x, m.velocity.y + 0.002, m.velocity.z);
|
||||
}
|
||||
if m.ai.mov.operation != super::control::Operation::MoveTo || m.ai.nav.is_done() {
|
||||
m.set_speed(0.0);
|
||||
return;
|
||||
}
|
||||
let [wx, wy, wz] = m.ai.mov.wanted;
|
||||
let (xd, mut yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z);
|
||||
let dd = (xd * xd + yd * yd + zd * zd).sqrt();
|
||||
yd /= dd;
|
||||
let y_rot = horizon_core::geometry::trig::atan2_degrees(zd, xd) - 90.0;
|
||||
m.yaw = super::control::rotlerp(m.yaw, y_rot, 90.0);
|
||||
m.body_yaw = m.yaw;
|
||||
let target_speed = (m.ai.mov.speed_modifier * m.movement_speed()) as f32;
|
||||
let speed = m.ai.speed + 0.125 * (target_speed - m.ai.speed);
|
||||
m.set_speed(speed);
|
||||
let s = f64::from(speed);
|
||||
m.velocity = Vec3::new(
|
||||
m.velocity.x + s * xd * 0.005,
|
||||
m.velocity.y + s * yd * 0.1,
|
||||
m.velocity.z + s * zd * 0.005,
|
||||
);
|
||||
} else {
|
||||
if !m.on_ground {
|
||||
m.velocity = Vec3::new(m.velocity.x, m.velocity.y - 0.008, m.velocity.z);
|
||||
}
|
||||
let speed = m.movement_speed();
|
||||
m.ground_move_tick(w, speed);
|
||||
}
|
||||
}
|
||||
/// Drowned.travelInWater: swimming under water slowly when it wants to.
|
||||
pub fn drowned_travel(
|
||||
m: &mut Mob,
|
||||
w: &super::MobWorld,
|
||||
input: Vec3,
|
||||
events: &mut Vec<MobEvent>,
|
||||
) -> bool {
|
||||
// isUnderWater: wasEyeInWater && isInWater.
|
||||
if !(m.was_eye_in_water && m.fluids.in_water && drowned_wants_to_swim(m, w)) {
|
||||
return false;
|
||||
}
|
||||
m.move_relative(0.01, input);
|
||||
m.do_move(w, events);
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
true
|
||||
}
|
||||
/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents
|
||||
/// exist: an arrow-like shot with the trident's damage.
|
||||
fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
let Some(t) = cx.w.target_info(who) else {
|
||||
return;
|
||||
};
|
||||
let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z);
|
||||
let xd = t.position.x - m.position.x;
|
||||
let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y;
|
||||
let zd = t.position.z - m.position.z;
|
||||
let dist = (xd * xd + zd * zd).sqrt();
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: 8.0,
|
||||
critical: false,
|
||||
effect: None,
|
||||
},
|
||||
start,
|
||||
Some(Who::Mob(m.id)),
|
||||
);
|
||||
!w.daylight || w.fluid(x, y, z) == crate::blocks::Fluid::Water || m.fluids.in_water
|
||||
p.shoot(
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd + dist * f64::from(0.2_f32), zd],
|
||||
1.6,
|
||||
(14 - 2 * 4) as f32,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 1.0 / (m.random.next_float() * 0.4 + 0.8);
|
||||
cx.events.push(MobEvent::Sound(
|
||||
"entity.drowned.shoot",
|
||||
m.center(),
|
||||
1.0,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
/// Drowned.DrownedTridentAttackGoal: the ranged goal while holding a trident.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DrownedTridentAttack(super::witch::RangedAttack);
|
||||
impl Goal for DrownedTridentAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"DrownedTridentAttackGoal"
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_use(m, cx) && m.extra.main_hand.as_deref() == Some("minecraft:trident")
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.start(m, cx);
|
||||
m.ai.aggressive = true;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx);
|
||||
m.ai.aggressive = false;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
self.0.every_tick()
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// Drowned.DrownedAttackGoal: ZombieAttackGoal on a target it may attack.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DrownedAttack(MeleeAttack);
|
||||
impl Goal for DrownedAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"DrownedAttackGoal"
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_use(m, cx) && drowned_ok_target(m, cx.w)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx) && drowned_ok_target(m, cx.w)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
self.0.every_tick()
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// Drowned.DrownedGoToBeachGoal: at night, swim near the surface to a
|
||||
/// standable block with air above.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DrownedGoToBeach(super::goals::MoveToBlock);
|
||||
fn beach_target(w: &super::MobWorld, p: [i32; 3]) -> bool {
|
||||
let empty = |y: i32| {
|
||||
let state = w.world.block(p[0], y, p[2]);
|
||||
w.facts.is_air(state) && w.facts.get(state).fluid == crate::blocks::Fluid::None
|
||||
};
|
||||
// BlockState.entityCanStandOn: a full top face.
|
||||
empty(p[1] + 1)
|
||||
&& empty(p[1] + 2)
|
||||
&& w.facts.get(w.world.block(p[0], p[1], p[2])).sturdy_full & (1 << 1) != 0
|
||||
}
|
||||
impl Goal for DrownedGoToBeach {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | super::goals::JUMP
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"DrownedGoToBeachGoal"
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
// MoveToBlockGoal.canUse, then the drowned's conditions.
|
||||
if self.0.next_start > 0 {
|
||||
self.0.next_start -= 1;
|
||||
return false;
|
||||
}
|
||||
self.0.next_start = super::goals::reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
|
||||
self.0.find_nearest(m, cx.w, beach_target)
|
||||
&& !cx.w.daylight
|
||||
&& m.fluids.in_water
|
||||
&& m.position.y >= f64::from(cx.w.sea_level - 3)
|
||||
}
|
||||
fn can_continue(&mut self, _m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(cx.w, beach_target)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.flag2 = false;
|
||||
self.0.start(m, cx.w);
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.tick(m, cx.w);
|
||||
}
|
||||
}
|
||||
/// Drowned.DrownedSwimUpGoal: at night, deep in water, head for the surface.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DrownedSwimUp {
|
||||
stuck: bool,
|
||||
}
|
||||
impl Goal for DrownedSwimUp {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"DrownedSwimUpGoal"
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
!cx.w.daylight && m.fluids.in_water && m.position.y < f64::from(cx.w.sea_level - 2)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx) && !self.stuck
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.extra.flag2 = true;
|
||||
self.stuck = false;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.extra.flag2 = false;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let sea = f64::from(cx.w.sea_level);
|
||||
if m.position.y < sea - 1.0 && (m.ai.nav.is_done() || drowned_close_to_next_pos(m)) {
|
||||
let to = [m.position.x, sea - 1.0, m.position.z];
|
||||
match m.default_random_pos_towards(cx.w, 4, 8, to, std::f64::consts::FRAC_PI_2) {
|
||||
None => self.stuck = true,
|
||||
Some(p) => {
|
||||
m.nav_move_to(cx.w, p, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Drowned.closeToNextPos: within two blocks of the path's target.
|
||||
fn drowned_close_to_next_pos(m: &Mob) -> bool {
|
||||
m.ai.nav.path.as_ref().is_some_and(|p| {
|
||||
let t = p.target;
|
||||
m.distance_sqr(Vec3::new(f64::from(t[0]), f64::from(t[1]), f64::from(t[2]))) < 4.0
|
||||
})
|
||||
}
|
||||
/// Zombie drowning conversion (Zombie.DrowningTracker) and husk -> zombie.
|
||||
/// `ZombifiedPiglin.customServerAiStep`: faster and loud while angry,
|
||||
@@ -236,25 +516,82 @@ pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.counter = -1;
|
||||
}
|
||||
}
|
||||
if m.species() == Species::Drowned {
|
||||
// Drowned.updateSwimming / travel: swim when the target is in water.
|
||||
let wants =
|
||||
m.ai.target
|
||||
.and_then(|t| cx.w.target_info(t))
|
||||
.is_some_and(|t| {
|
||||
let (x, y, z) = (
|
||||
t.position.x.floor() as i32,
|
||||
t.position.y.floor() as i32,
|
||||
t.position.z.floor() as i32,
|
||||
);
|
||||
cx.w.fluid(x, y, z) == crate::blocks::Fluid::Water
|
||||
});
|
||||
m.extra.flag = wants;
|
||||
if m.fluids.in_water && wants {
|
||||
m.ai.nav.kind = super::nav::NavKind::Water { breach: false };
|
||||
} else if m.ai.nav.kind != super::nav::NavKind::Ground {
|
||||
m.ai.nav.kind = super::nav::NavKind::Ground;
|
||||
m.ai.nav.stop();
|
||||
}
|
||||
/// `AbstractSkeleton.reassessWeaponGoal`'s goal: the bow goal while holding a
|
||||
/// bow, otherwise the melee goal (the anonymous `AbstractSkeleton$1`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkeletonWeapon {
|
||||
bow: BowAttack,
|
||||
melee: MeleeAttack,
|
||||
use_bow: bool,
|
||||
}
|
||||
impl SkeletonWeapon {
|
||||
pub fn new(bow_interval: i32) -> Self {
|
||||
Self {
|
||||
bow: BowAttack::new(1.0, bow_interval, 15.0),
|
||||
melee: MeleeAttack::new(1.2, false),
|
||||
use_bow: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for SkeletonWeapon {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
if self.use_bow {
|
||||
"BowAttack"
|
||||
} else {
|
||||
"AbstractSkeleton$1"
|
||||
}
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
if self.use_bow {
|
||||
self.bow.every_tick()
|
||||
} else {
|
||||
self.melee.every_tick()
|
||||
}
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
// The goal registered for the weapon in hand.
|
||||
self.use_bow = holding_bow(m);
|
||||
if self.use_bow {
|
||||
self.bow.can_use(m, cx)
|
||||
} else {
|
||||
self.melee.can_use(m, cx)
|
||||
}
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
// Changing weapons removes the running goal.
|
||||
if self.use_bow != holding_bow(m) {
|
||||
return false;
|
||||
}
|
||||
if self.use_bow {
|
||||
self.bow.can_continue(m, cx)
|
||||
} else {
|
||||
self.melee.can_continue(m, cx)
|
||||
}
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if self.use_bow {
|
||||
self.bow.start(m, cx)
|
||||
} else {
|
||||
self.melee.start(m, cx)
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if self.use_bow {
|
||||
self.bow.stop(m, cx)
|
||||
} else {
|
||||
self.melee.stop(m, cx)
|
||||
}
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if self.use_bow {
|
||||
self.bow.tick(m, cx)
|
||||
} else {
|
||||
self.melee.tick(m, cx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,7 +738,8 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) {
|
||||
let zd = t.position.z - m.position.z;
|
||||
let dist = (xd * xd + zd * zd).sqrt();
|
||||
// AbstractArrow.setBaseDamageFromMob: power * 2 + triangle(difficulty * 0.11, 0.57425).
|
||||
let base = f64::from(power) * 2.0 + m.random.triangle(2.0 * 0.11, 0.574_25);
|
||||
let mut arrow_random = crate::projectiles::own_random(m);
|
||||
let base = f64::from(power) * 2.0 + arrow_random.triangle(2.0 * 0.11, 0.574_25);
|
||||
let effect = match m.species() {
|
||||
Species::Stray => Some(("minecraft:slowness", 600)),
|
||||
Species::Bogged => Some(("minecraft:poison", 100)),
|
||||
@@ -419,7 +757,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) {
|
||||
);
|
||||
p.bonus = super::gear::arrow_bonus(m);
|
||||
p.shoot(
|
||||
&mut m.random,
|
||||
&mut arrow_random,
|
||||
[xd, yd + dist * 0.2, zd],
|
||||
1.6,
|
||||
(14 - 2 * 4) as f32,
|
||||
@@ -476,3 +814,148 @@ impl Goal for DrownedGoToWater {
|
||||
m.nav_move_to(cx.w, self.wanted, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Zombie.ZombieAttackTurtleEggGoal` (a `RemoveBlockGoal` on turtle eggs):
|
||||
/// walk to a turtle egg within 24 blocks and trample it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AttackTurtleEgg {
|
||||
base: super::goals::MoveToBlock,
|
||||
since_reached: i32,
|
||||
}
|
||||
impl Default for AttackTurtleEgg {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
base: super::goals::MoveToBlock::new(1.0, 24, 3),
|
||||
since_reached: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// RemoveBlockGoal.isValidTarget: the block with two air blocks above, in a loaded chunk.
|
||||
fn turtle_egg_target(w: &super::MobWorld, p: [i32; 3]) -> bool {
|
||||
w.world.loaded(p[0], p[2])
|
||||
&& w.block_name(p[0], p[1], p[2]) == "minecraft:turtle_egg"
|
||||
&& w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2]))
|
||||
&& w.facts.is_air(w.world.block(p[0], p[1] + 2, p[2]))
|
||||
}
|
||||
impl Goal for AttackTurtleEgg {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | super::goals::JUMP
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// RemoveBlockGoal.canUse
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !cx.w.mob_griefing {
|
||||
return false;
|
||||
}
|
||||
if self.base.next_start > 0 {
|
||||
self.base.next_start -= 1;
|
||||
return false;
|
||||
}
|
||||
if self.base.find_nearest(m, cx.w, turtle_egg_target) {
|
||||
self.base.next_start = super::goals::reduced(20);
|
||||
return true;
|
||||
}
|
||||
// MoveToBlockGoal.nextStartTick
|
||||
self.base.next_start =
|
||||
super::goals::reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
|
||||
false
|
||||
}
|
||||
fn can_continue(&mut self, _m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.base.can_continue(cx.w, turtle_egg_target)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.base.start(m, cx.w);
|
||||
self.since_reached = 0;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.fall_distance = 1.0;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.base.tick_within(m, cx.w, 1.14);
|
||||
let at = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
let egg = |p: [i32; 3]| cx.w.block_name(p[0], p[1], p[2]) == "minecraft:turtle_egg";
|
||||
let eat = [
|
||||
at,
|
||||
[at[0], at[1] - 1, at[2]],
|
||||
[at[0] - 1, at[1], at[2]],
|
||||
[at[0] + 1, at[1], at[2]],
|
||||
[at[0], at[1], at[2] - 1],
|
||||
[at[0], at[1], at[2] + 1],
|
||||
[at[0], at[1] - 2, at[2]],
|
||||
]
|
||||
.into_iter()
|
||||
.find(|p| egg(*p));
|
||||
let Some(eat) = eat.filter(|_| self.base.reached) else {
|
||||
return;
|
||||
};
|
||||
let center = [
|
||||
f64::from(eat[0]) + 0.5,
|
||||
f64::from(eat[1]) + 0.7,
|
||||
f64::from(eat[2]) + 0.5,
|
||||
];
|
||||
if self.since_reached > 0 {
|
||||
m.velocity.y = 0.3;
|
||||
// The egg crumb particles' spread.
|
||||
for _ in 0..3 {
|
||||
m.random.next_float();
|
||||
}
|
||||
cx.events.push(MobEvent::Particles {
|
||||
kind: "item_egg",
|
||||
at: center,
|
||||
count: 3,
|
||||
});
|
||||
}
|
||||
if self.since_reached % 2 == 0 {
|
||||
m.velocity.y = -0.3;
|
||||
if self.since_reached % 6 == 0 {
|
||||
let pitch = 0.9 + m.random.next_float() * 0.2;
|
||||
let b = self.base.block;
|
||||
cx.events.push(MobEvent::Sound(
|
||||
"entity.zombie.destroy_egg",
|
||||
[
|
||||
f64::from(b[0]) + 0.5,
|
||||
f64::from(b[1]) + 0.5,
|
||||
f64::from(b[2]) + 0.5,
|
||||
],
|
||||
0.5,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.since_reached > 60 {
|
||||
cx.events.push(MobEvent::BreakBlock {
|
||||
pos: eat,
|
||||
drop: false,
|
||||
});
|
||||
for _ in 0..20 {
|
||||
m.random.next_gaussian();
|
||||
m.random.next_gaussian();
|
||||
m.random.next_gaussian();
|
||||
}
|
||||
cx.events.push(MobEvent::Particles {
|
||||
kind: "poof",
|
||||
at: [center[0], f64::from(eat[1]), center[2]],
|
||||
count: 20,
|
||||
});
|
||||
// The break sound's pitch draws from the level random.
|
||||
cx.events.push(MobEvent::Sound(
|
||||
"block.turtle_egg.break",
|
||||
[
|
||||
f64::from(eat[0]) + 0.5,
|
||||
f64::from(eat[1]) + 0.5,
|
||||
f64::from(eat[2]) + 0.5,
|
||||
],
|
||||
0.7,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
self.since_reached += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(4, Charge);
|
||||
g.add(8, RandomMove);
|
||||
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
|
||||
g.add(10, LookAtPlayer::mobs(8.0));
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
hurt.ignore = vec![
|
||||
Species::Pillager,
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
//! Villagers (`Villager` and its brain packages, as goals): taking the
|
||||
//! profession of a free job site nearby (`AcquirePoi` with
|
||||
//! `AssignProfessionFromJobSite`), losing a fresh profession when the site
|
||||
//! goes (`ResetProfession`), claiming a bed and a bell, the daily schedule
|
||||
//! (work and restock at the job site, meet at the bell, sleep in the bed),
|
||||
//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake.
|
||||
//! Villagers (`Villager`): professions, sleeping, the unhappy head shake,
|
||||
//! food, gossip and the raid state. Their AI is the brain in
|
||||
//! `villager_brain`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
anim::{Poses, State},
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround,
|
||||
Stroll, goal_clone,
|
||||
},
|
||||
};
|
||||
use crate::items::ItemStack;
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::{collections::HashMap, f32::consts::PI};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
// Villager state: `variant` type, `variant2` profession (index into
|
||||
// `render::PROFESSIONS`), `variant3` level, `home` the claimed job site,
|
||||
@@ -50,187 +43,12 @@ pub fn register(m: &mut Mob) {
|
||||
if m.extra.variant3 == 0 {
|
||||
m.extra.variant3 = 1;
|
||||
}
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
// VillagerHostilesSensor: zombies within 8 blocks, illagers further.
|
||||
let zombies = vec![
|
||||
Species::Zombie,
|
||||
Species::ZombieVillager,
|
||||
Species::Husk,
|
||||
Species::Drowned,
|
||||
Species::Vex,
|
||||
];
|
||||
let raiders = vec![
|
||||
Species::Pillager,
|
||||
Species::Vindicator,
|
||||
Species::Evoker,
|
||||
Species::Illusioner,
|
||||
Species::Ravager,
|
||||
Species::Zoglin,
|
||||
];
|
||||
g.add(
|
||||
1,
|
||||
AvoidEntity::new(Avoid::Species(zombies), 8.0, 0.75, 0.75),
|
||||
);
|
||||
g.add(
|
||||
1,
|
||||
AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75),
|
||||
);
|
||||
g.add(1, Panic::new(0.75));
|
||||
g.add(2, RaidBehavior::default());
|
||||
g.add(3, Social::default());
|
||||
g.add(0, GolemCall);
|
||||
g.add(3, GiftToHero::default());
|
||||
g.add(3, JobSite::default());
|
||||
g.add(3, AcquireHome::default());
|
||||
g.add(4, Schedule::default());
|
||||
g.add(5, Stroll::avoiding_water(0.5));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
g.add(7, RandomLookAround::default());
|
||||
// Villager's constructor: its brain does everything, it has no goals.
|
||||
m.ai.nav.can_open_doors = true;
|
||||
m.ai.nav.can_float = true;
|
||||
m.ai.nav.required_path_length = 48.0;
|
||||
}
|
||||
|
||||
/// `AcquirePoi` for job sites with `AssignProfessionFromJobSite`: walk to the
|
||||
/// nearest unclaimed job site and take its profession once within 2 blocks.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct JobSite {
|
||||
target: Option<[i32; 3]>,
|
||||
next_search: i32,
|
||||
ticks: i32,
|
||||
}
|
||||
fn claimed(w: &MobWorld, me: u32, p: [i32; 3]) -> bool {
|
||||
w.others
|
||||
.iter()
|
||||
.any(|s| s.id != me && s.alive && s.job == Some(p))
|
||||
}
|
||||
fn job_seeker(m: &Mob) -> bool {
|
||||
!m.is_baby() && m.extra.home.is_none() && m.extra.variant2 != NITWIT
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Poi {
|
||||
Job(u8),
|
||||
Bed,
|
||||
Bell,
|
||||
}
|
||||
fn poi_at(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option<Poi> {
|
||||
let name = &w.facts.get(state).name;
|
||||
if name.as_ref() == "minecraft:bell" {
|
||||
return Some(Poi::Bell);
|
||||
}
|
||||
if name.ends_with("_bed") {
|
||||
let s = w.registry.state(state)?;
|
||||
let free = s.properties.get("part").map(String::as_str) == Some("head")
|
||||
&& s.properties.get("occupied").map(String::as_str) != Some("true");
|
||||
return free.then_some(Poi::Bed);
|
||||
}
|
||||
job_site_profession(name).map(Poi::Job)
|
||||
}
|
||||
/// `PoiManager.findClosest` (`AcquirePoi.SCAN_RANGE` 48 blocks across, 8
|
||||
/// up and down): the nearest position whose POI passes `want`.
|
||||
fn scan(m: &Mob, w: &MobWorld, want: impl Fn(Poi, [i32; 3]) -> bool) -> Option<[i32; 3]> {
|
||||
let (bx, by, bz) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
let mut known: HashMap<u32, Option<Poi>> = HashMap::new();
|
||||
let mut best: Option<(i32, [i32; 3])> = None;
|
||||
for y in by - 8..=by + 8 {
|
||||
for z in bz - 48..=bz + 48 {
|
||||
for x in bx - 48..=bx + 48 {
|
||||
let state = w.world.block(x, y, z);
|
||||
if w.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
let poi = *known.entry(state.0).or_insert_with(|| poi_at(w, state));
|
||||
let Some(poi) = poi else { continue };
|
||||
let d = (x - bx).pow(2) + (y - by).pow(2) + (z - bz).pow(2);
|
||||
if best.is_none_or(|(b, _)| d < b) && want(poi, [x, y, z]) {
|
||||
best = Some((d, [x, y, z]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, p)| p)
|
||||
}
|
||||
/// The nearest free job site (a profession's own one once employed).
|
||||
fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
|
||||
scan(m, w, |poi, p| match poi {
|
||||
Poi::Job(profession) => {
|
||||
(m.extra.variant2 == NONE || profession == m.extra.variant2) && !claimed(w, m.id, p)
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
impl Goal for JobSite {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !job_seeker(m) {
|
||||
return false;
|
||||
}
|
||||
if self.next_search > 0 {
|
||||
self.next_search -= 1;
|
||||
return false;
|
||||
}
|
||||
// AcquirePoi's scan pacing: 20 to 40 ticks between scans.
|
||||
self.next_search = 20 + m.random.next_int_bound(20).unwrap_or(0);
|
||||
self.target = find_site(m, cx.w);
|
||||
self.target.is_some()
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
job_seeker(m)
|
||||
&& self.ticks < 1200
|
||||
&& self.target.is_some_and(|p| {
|
||||
job_site_profession(cx.w.block_name(p[0], p[1], p[2])).is_some()
|
||||
&& !claimed(cx.w, m.id, p)
|
||||
})
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks = 0;
|
||||
if let Some(p) = self.target {
|
||||
let path = m.create_path_to(cx.w, p, 1);
|
||||
m.nav_move_to_path(path, 0.5);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
self.target = None;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks += 1;
|
||||
let Some(p) = self.target else { return };
|
||||
let c = [
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]) + 0.5,
|
||||
f64::from(p[2]) + 0.5,
|
||||
];
|
||||
if m.position
|
||||
.distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2]))
|
||||
< 4.0
|
||||
{
|
||||
take_job(m, p, cx.w, cx.events);
|
||||
return;
|
||||
}
|
||||
if m.ai.nav.is_done() && self.ticks % 40 == 0 {
|
||||
let path = m.create_path_to(cx.w, p, 1);
|
||||
m.nav_move_to_path(path, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `AssignProfessionFromJobSite`: claim the site, take its profession if
|
||||
/// unemployed, and show the happy particles (entity event 14).
|
||||
fn take_job(m: &mut Mob, p: [i32; 3], w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.extra.home = Some(p);
|
||||
if m.extra.variant2 == NONE
|
||||
&& let Some(profession) = job_site_profession(w.block_name(p[0], p[1], p[2]))
|
||||
{
|
||||
m.extra.variant2 = profession;
|
||||
m.extra.trade = None;
|
||||
}
|
||||
particles_around(m, "happy_villager", events);
|
||||
}
|
||||
/// `LivingEntity.addParticlesAroundSelf`: five particles about the body.
|
||||
pub fn particles_around(m: &mut Mob, kind: &'static str, events: &mut Vec<MobEvent>) {
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
@@ -253,8 +71,11 @@ pub enum Activity {
|
||||
Rest,
|
||||
}
|
||||
pub fn activity(m: &Mob, day_time: i64) -> Activity {
|
||||
activity_at(m.is_baby(), day_time)
|
||||
}
|
||||
pub fn activity_at(baby: bool, day_time: i64) -> Activity {
|
||||
let t = day_time.rem_euclid(24000);
|
||||
if m.is_baby() {
|
||||
if baby {
|
||||
match t {
|
||||
10..3000 | 6000..10000 => Activity::Idle,
|
||||
3000..6000 | 10000..12000 => Activity::Play,
|
||||
@@ -269,192 +90,13 @@ pub fn activity(m: &Mob, day_time: i64) -> Activity {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn center(p: [i32; 3]) -> [f64; 3] {
|
||||
[
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]) + 0.5,
|
||||
f64::from(p[2]) + 0.5,
|
||||
]
|
||||
}
|
||||
fn distance(m: &Mob, p: [i32; 3]) -> f64 {
|
||||
let c = center(p);
|
||||
m.position
|
||||
.distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2]))
|
||||
.sqrt()
|
||||
}
|
||||
/// `AcquirePoi` for `HOME` (a free bed head) and `MEETING` (a bell), with
|
||||
/// the happy particles on success; failed scans back off.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct AcquireHome {
|
||||
next_search: i32,
|
||||
}
|
||||
impl Goal for AcquireHome {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.extra.bed.is_some() && m.extra.meeting.is_some() {
|
||||
return false;
|
||||
}
|
||||
if self.next_search > 0 {
|
||||
self.next_search -= 1;
|
||||
return false;
|
||||
}
|
||||
let w = cx.w;
|
||||
let mut found = false;
|
||||
if m.extra.bed.is_none()
|
||||
&& let Some(p) = scan(m, w, |poi, p| {
|
||||
poi == Poi::Bed
|
||||
&& !w
|
||||
.others
|
||||
.iter()
|
||||
.any(|s| s.id != m.id && s.alive && s.bed == Some(p))
|
||||
})
|
||||
{
|
||||
m.extra.bed = Some(p);
|
||||
found = true;
|
||||
}
|
||||
if m.extra.meeting.is_none()
|
||||
&& !m.is_baby()
|
||||
&& let Some(p) = scan(m, w, |poi, _| poi == Poi::Bell)
|
||||
{
|
||||
m.extra.meeting = Some(p);
|
||||
found = true;
|
||||
}
|
||||
if found {
|
||||
particles_around(m, "happy_villager", cx.events);
|
||||
}
|
||||
self.next_search = if found {
|
||||
20 + m.random.next_int_bound(20).unwrap_or(0)
|
||||
} else {
|
||||
200 + m.random.next_int_bound(200).unwrap_or(0)
|
||||
};
|
||||
false
|
||||
}
|
||||
}
|
||||
/// The schedule's walk targets (`SetWalkTargetFromBlockMemory`,
|
||||
/// `StrollToPoi`, `StrollAroundPoi`), `WorkAtPoi` with restocking, and
|
||||
/// `SleepInBed`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Schedule {
|
||||
cooldown: i32,
|
||||
target: Option<[f64; 3]>,
|
||||
to_site: bool,
|
||||
last_work: i64,
|
||||
ticks: i32,
|
||||
}
|
||||
impl Schedule {
|
||||
fn anchor(m: &Mob, a: Activity) -> Option<([i32; 3], f64)> {
|
||||
match a {
|
||||
Activity::Work if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT => {
|
||||
m.extra.home.map(|p| (p, 9.0))
|
||||
}
|
||||
Activity::Meet => m.extra.meeting.map(|p| (p, 6.0)),
|
||||
Activity::Rest => m.extra.bed.map(|p| (p, 1.0)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for Schedule {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if sleeping(m) {
|
||||
return false;
|
||||
}
|
||||
if self.cooldown > 0 {
|
||||
self.cooldown -= 1;
|
||||
return false;
|
||||
}
|
||||
let a = activity(m, cx.w.day_time);
|
||||
let Some((p, close)) = Self::anchor(m, a) else {
|
||||
return false;
|
||||
};
|
||||
self.to_site = false;
|
||||
let c = center(p);
|
||||
self.target = if a == Activity::Rest || distance(m, p) > close {
|
||||
self.to_site = true;
|
||||
Some(c)
|
||||
} else if m.random.next_int_bound(2).unwrap_or(0) == 0 && a == Activity::Work {
|
||||
// StrollToPoi / WorkAtPoi.
|
||||
self.to_site = true;
|
||||
Some(c)
|
||||
} else {
|
||||
// StrollAroundPoi: somewhere near the site.
|
||||
let r = &mut m.random;
|
||||
let spread = if a == Activity::Meet { 6 } else { 4 };
|
||||
let mut d = || f64::from(r.next_int_bound(2 * spread + 1).unwrap_or(0) - spread);
|
||||
Some([c[0] + d(), c[1], c[2] + d()])
|
||||
};
|
||||
self.cooldown = 40 + m.random.next_int_bound(80).unwrap_or(0);
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.ticks < 400
|
||||
&& !sleeping(m)
|
||||
&& Self::anchor(m, activity(m, cx.w.day_time)).is_some()
|
||||
&& !(m.ai.nav.is_done() && self.ticks > 20)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks = 0;
|
||||
if let Some(t) = self.target {
|
||||
m.nav_move_to(cx.w, t, 0.5);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks += 1;
|
||||
let a = activity(m, cx.w.day_time);
|
||||
let Some((p, _)) = Self::anchor(m, a) else {
|
||||
return;
|
||||
};
|
||||
if !self.to_site {
|
||||
return;
|
||||
}
|
||||
match a {
|
||||
Activity::Work if distance(m, p) < 1.73 => {
|
||||
// WorkAtPoi: every 300 ticks at most, half the time.
|
||||
let now = cx.w.game_time;
|
||||
m.look_at(center(p));
|
||||
if now - self.last_work >= 300 && m.random.next_int_bound(2).unwrap_or(1) == 0 {
|
||||
self.last_work = now;
|
||||
work(m, cx.w, cx.events);
|
||||
}
|
||||
m.nav_stop();
|
||||
}
|
||||
Activity::Rest if distance(m, p) < 2.0 => start_sleeping(m, p, cx.w),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `WorkAtPoi.start`: the profession's work sound, and a restock when due.
|
||||
fn work(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15];
|
||||
events.push(MobEvent::SoundId(
|
||||
format!("minecraft:entity.villager.work_{profession}"),
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
let day = w.day_time.div_euclid(24000);
|
||||
if let Some(t) = m.extra.trade.as_mut()
|
||||
&& t.should_restock(w.game_time, day)
|
||||
{
|
||||
t.restock(w.game_time);
|
||||
}
|
||||
}
|
||||
pub fn sleeping(m: &Mob) -> bool {
|
||||
matches!(m.species(), Species::Villager | Species::WanderingTrader) && m.extra.ints[1] != 0
|
||||
}
|
||||
/// `LivingEntity.startSleeping`: lie in the bed (`setPosToBed`).
|
||||
fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
|
||||
pub fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) -> bool {
|
||||
if w.prop(p[0], p[1], p[2], "occupied") == Some("true") {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
m.extra.ints[1] = match w.prop(p[0], p[1], p[2], "facing") {
|
||||
Some("north") => 1,
|
||||
@@ -470,6 +112,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
|
||||
f64::from(p[1]) + 0.6875,
|
||||
f64::from(p[2]) + 0.5,
|
||||
);
|
||||
true
|
||||
}
|
||||
/// `LivingEntity.stopSleeping` with `BedBlock.findStandUpPosition`: beside
|
||||
/// the bed where there is room, else on top of it.
|
||||
@@ -499,14 +142,6 @@ pub fn stop_sleeping(m: &mut Mob, w: &MobWorld) {
|
||||
}
|
||||
m.position.y = f64::from(p[1]) + 0.5625;
|
||||
}
|
||||
/// While asleep the villager stays in the bed.
|
||||
pub fn travel(m: &mut Mob) -> bool {
|
||||
if !sleeping(m) {
|
||||
return false;
|
||||
}
|
||||
m.velocity = horizon_core::geometry::Vec3::ZERO;
|
||||
true
|
||||
}
|
||||
/// `LivingEntityRenderer.sleepDirectionToRotation` and the bed's direction
|
||||
/// (the body is shifted back from the pillow by the standing eye height).
|
||||
pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> {
|
||||
@@ -518,69 +153,24 @@ pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> {
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `Villager.tick` / brain upkeep: the unhappy counter, and
|
||||
/// `ResetProfession` / job site loss when the site's block is gone.
|
||||
/// `Villager.tick`: the unhappy counter and the gossip decay; a sleeper
|
||||
/// hurt or without its bed wakes up (`LivingEntity.hurtServer`,
|
||||
/// `LivingEntity.checkBedExists`). The brain does the rest.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
if m.extra.ints[0] > 0 {
|
||||
m.extra.ints[0] -= 1;
|
||||
}
|
||||
if m.species() == Species::Villager {
|
||||
let now = w.game_time;
|
||||
let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0
|
||||
&& w.others.iter().any(|s| {
|
||||
s.species == Species::IronGolem
|
||||
&& s.alive
|
||||
&& (s.position.x - m.position.x).abs() <= 16.0
|
||||
&& (s.position.y - m.position.y).abs() <= 16.0
|
||||
&& (s.position.z - m.position.z).abs() <= 16.0
|
||||
});
|
||||
let e = ext_mut(m);
|
||||
// Villager.maybeDecayGossip and the GolemSensor (every 200 ticks).
|
||||
e.maybe_decay(now);
|
||||
if seen_golem {
|
||||
e.golem_until = now + 599;
|
||||
}
|
||||
ext_mut(m).maybe_decay(w.game_time);
|
||||
}
|
||||
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
|
||||
if sleeping(m) {
|
||||
let bed_gone = m
|
||||
.extra
|
||||
.bed
|
||||
.is_none_or(|p| !w.block_name(p[0], p[1], p[2]).ends_with("_bed"));
|
||||
if activity(m, w.day_time) != Activity::Rest || m.hurt_time > 0 || bed_gone {
|
||||
if m.hurt_time > 0 || bed_gone {
|
||||
stop_sleeping(m, w);
|
||||
}
|
||||
}
|
||||
// ValidateNearbyPoi for the bed and bell.
|
||||
if m.age.is_multiple_of(20) {
|
||||
let loaded = |p: [i32; 3]| w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4));
|
||||
if let Some(p) = m.extra.bed
|
||||
&& loaded(p)
|
||||
&& !w.block_name(p[0], p[1], p[2]).ends_with("_bed")
|
||||
{
|
||||
m.extra.bed = None;
|
||||
}
|
||||
if let Some(p) = m.extra.meeting
|
||||
&& loaded(p)
|
||||
&& w.block_name(p[0], p[1], p[2]) != "minecraft:bell"
|
||||
{
|
||||
m.extra.meeting = None;
|
||||
}
|
||||
}
|
||||
if m.species() != Species::Villager || !m.age.is_multiple_of(20) {
|
||||
return;
|
||||
}
|
||||
let Some(p) = m.extra.home else { return };
|
||||
if !w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
|
||||
return;
|
||||
}
|
||||
if job_site_profession(w.block_name(p[0], p[1], p[2])).is_none() {
|
||||
m.extra.home = None;
|
||||
let fresh = m.extra.trade.as_ref().is_none_or(|t| t.xp == 0);
|
||||
if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT && fresh && m.extra.variant3 <= 1
|
||||
{
|
||||
m.extra.variant2 = NONE;
|
||||
m.extra.trade = None;
|
||||
super::villager_brain::woken(m, w.game_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -651,6 +241,8 @@ pub struct Ext {
|
||||
pub hurt_seen: i32,
|
||||
/// A zombie villager's cure under way.
|
||||
pub cure: Option<super::zombie_villager::Cure>,
|
||||
/// The villager's brain, built at its first tick.
|
||||
pub brain: Option<Box<super::villager_brain::Brain>>,
|
||||
}
|
||||
pub fn ext(m: &Mob) -> Option<&Ext> {
|
||||
m.extra.villager.as_deref()
|
||||
@@ -658,127 +250,75 @@ pub fn ext(m: &Mob) -> Option<&Ext> {
|
||||
pub fn ext_mut(m: &mut Mob) -> &mut Ext {
|
||||
m.extra.villager.get_or_insert_with(Box::default)
|
||||
}
|
||||
fn raid_status(m: &Mob) -> u8 {
|
||||
/// The raid package the villager follows (`RAID_NONE` ... `RAID_VICTORY`).
|
||||
pub fn raid_status(m: &Mob) -> u8 {
|
||||
ext(m).map_or(RAID_NONE, |e| e.raid)
|
||||
}
|
||||
|
||||
/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at
|
||||
/// home (`LocateHidingPlace`), before one they gather at the bell and ring it
|
||||
/// (`RingBell`), and after a victory they look for the sky to celebrate
|
||||
/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct RaidBehavior {
|
||||
next_move: i32,
|
||||
/// `ServerLevel.getRaidAt(blockPosition)` is a raid.
|
||||
pub fn raid_nearby(m: &Mob) -> bool {
|
||||
ext(m).is_some_and(|e| e.raid != RAID_NONE)
|
||||
}
|
||||
impl Goal for RaidBehavior {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
/// The raid near the villager: `Some(true)` while a wave is on
|
||||
/// (`hasFirstWaveSpawned && !isBetweenWaves`), `Some(false)` otherwise.
|
||||
pub fn raid_state(m: &Mob) -> Option<bool> {
|
||||
match ext(m).map_or(RAID_NONE, |e| e.raid) {
|
||||
RAID_NONE => None,
|
||||
RAID => Some(true),
|
||||
_ => Some(false),
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
|
||||
raid_status(m) != RAID_NONE && !sleeping(m)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
self.next_move = 0;
|
||||
m.nav_stop();
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.next_move -= 1;
|
||||
let p = m.position;
|
||||
match raid_status(m) {
|
||||
RAID => {
|
||||
// LocateHidingPlace(24, 0.7, 1): back to the bed.
|
||||
let Some(home) = m.extra.bed else { return };
|
||||
if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
|
||||
if distance(m, home) <= 24.0 {
|
||||
m.nav_move_to(cx.w, center(home), 0.7);
|
||||
}
|
||||
self.next_move = 40;
|
||||
}
|
||||
}
|
||||
PRE_RAID => {
|
||||
// RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75).
|
||||
let Some(bell) = m.extra.meeting else { return };
|
||||
if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
|
||||
m.nav_move_to(cx.w, center(bell), 0.75);
|
||||
self.next_move = 40;
|
||||
}
|
||||
if distance(m, bell) < 3.0
|
||||
&& m.random.next_float() > 0.95
|
||||
&& cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell"
|
||||
{
|
||||
cx.events.push(MobEvent::SoundId(
|
||||
"minecraft:block.bell.use".into(),
|
||||
center(bell),
|
||||
2.0,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
}
|
||||
RAID_VICTORY => {
|
||||
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
|
||||
if cx.w.can_see_sky(x, y, z) {
|
||||
// CelebrateVillagersSurvivedRaid.tick.
|
||||
if m.random.next_int_bound(100).unwrap_or(1) == 0 {
|
||||
m.voice("entity.villager.celebrate", cx.events);
|
||||
}
|
||||
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
|
||||
let color = m.random.next_int_bound(16).unwrap_or(0) as usize;
|
||||
let flight = m.random.next_int_bound(3).unwrap_or(0) as u8;
|
||||
cx.events.push(MobEvent::Firework {
|
||||
at: [p.x, m.eye_y(), p.z],
|
||||
color,
|
||||
flight,
|
||||
});
|
||||
}
|
||||
m.nav_stop();
|
||||
} else if self.next_move <= 0 || m.ai.nav.is_done() {
|
||||
// MoveToSkySeeingSpot: a random spot with a view of the sky.
|
||||
for _ in 0..5 {
|
||||
if let Some(at) = m.land_random_pos(cx.w, 15, 7)
|
||||
&& cx.w.can_see_sky(
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
)
|
||||
{
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.next_move = 40;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
/// `Villager.getVillagerXp`.
|
||||
pub fn xp(m: &Mob) -> i32 {
|
||||
m.extra.trade.as_ref().map_or(0, |t| t.xp)
|
||||
}
|
||||
/// `Villager.setVillagerData(withProfession)`: a new profession forgets the
|
||||
/// offers.
|
||||
pub fn set_profession(m: &mut Mob, profession: u8) {
|
||||
if m.extra.variant2 != profession {
|
||||
m.extra.variant2 = profession;
|
||||
if let Some(t) = m.extra.trade.as_mut() {
|
||||
t.offers.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `VillagerProfession.workSound`.
|
||||
pub fn work_sound(profession: u8) -> Option<&'static str> {
|
||||
Some(match super::render::PROFESSIONS[profession as usize % 15] {
|
||||
"armorer" => "entity.villager.work_armorer",
|
||||
"butcher" => "entity.villager.work_butcher",
|
||||
"cartographer" => "entity.villager.work_cartographer",
|
||||
"cleric" => "entity.villager.work_cleric",
|
||||
"farmer" => "entity.villager.work_farmer",
|
||||
"fisherman" => "entity.villager.work_fisherman",
|
||||
"fletcher" => "entity.villager.work_fletcher",
|
||||
"leatherworker" => "entity.villager.work_leatherworker",
|
||||
"librarian" => "entity.villager.work_librarian",
|
||||
"mason" => "entity.villager.work_mason",
|
||||
"shepherd" => "entity.villager.work_shepherd",
|
||||
"toolsmith" => "entity.villager.work_toolsmith",
|
||||
"weaponsmith" => "entity.villager.work_weaponsmith",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// A `CropBlock` at `p`.
|
||||
pub fn crop(w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
matches!(
|
||||
w.block_name(p[0], p[1], p[2]),
|
||||
"minecraft:wheat" | "minecraft:carrots" | "minecraft:potatoes" | "minecraft:beetroots"
|
||||
)
|
||||
}
|
||||
/// `CropBlock.isMaxAge` for the block at `p`.
|
||||
pub fn ripe_crop(w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
let max = match w.block_name(p[0], p[1], p[2]) {
|
||||
"minecraft:wheat" | "minecraft:carrots" | "minecraft:potatoes" => "7",
|
||||
"minecraft:beetroots" => "3",
|
||||
_ => return false,
|
||||
};
|
||||
w.prop(p[0], p[1], p[2], "age") == Some(max)
|
||||
}
|
||||
|
||||
/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and
|
||||
/// throws a gift of its profession, every so often.
|
||||
#[derive(Clone, Debug)]
|
||||
struct GiftToHero {
|
||||
until_next: i32,
|
||||
started: i64,
|
||||
given: bool,
|
||||
}
|
||||
impl Default for GiftToHero {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
until_next: 600,
|
||||
started: 0,
|
||||
given: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`).
|
||||
fn gift_table(m: &Mob) -> String {
|
||||
pub fn gift_table(m: &Mob) -> String {
|
||||
if m.is_baby() {
|
||||
return "minecraft:gameplay/hero_of_the_village/baby_gift".into();
|
||||
}
|
||||
@@ -789,66 +329,6 @@ fn gift_table(m: &Mob) -> String {
|
||||
};
|
||||
format!("minecraft:gameplay/hero_of_the_village/{name}_gift")
|
||||
}
|
||||
fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
p.hero
|
||||
&& p.alive
|
||||
&& !p.spectator
|
||||
&& m.position.distance_squared(p.position) <= 16.0 * 16.0
|
||||
&& m.sees(cx.w, Who::Player)
|
||||
}
|
||||
impl Goal for GiftToHero {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !hero_in_view(m, cx) || sleeping(m) {
|
||||
return false;
|
||||
}
|
||||
if self.until_next > 0 {
|
||||
self.until_next -= 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
hero_in_view(m, cx) && !self.given
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.given = false;
|
||||
self.started = cx.w.game_time;
|
||||
if let Some(p) = &cx.w.player {
|
||||
m.look_at(p.eye);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0);
|
||||
m.nav_stop();
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = cx.w.player.clone() else { return };
|
||||
m.look_at(p.eye);
|
||||
let near = m.position.distance_squared(p.position) < 25.0;
|
||||
if near {
|
||||
if cx.w.game_time - self.started > 20 {
|
||||
cx.events.push(MobEvent::ThrowGift {
|
||||
table: gift_table(m),
|
||||
from: [m.position.x, m.eye_y() - 0.3, m.position.z],
|
||||
to: [p.position.x, p.position.y, p.position.z],
|
||||
});
|
||||
self.given = true;
|
||||
}
|
||||
m.nav_stop();
|
||||
} else if m.ai.nav.is_done() {
|
||||
m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Gossip, food, breeding and golems.
|
||||
|
||||
/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`).
|
||||
@@ -1074,191 +554,6 @@ pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while
|
||||
/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap
|
||||
/// gossip and food, and make a baby with a willing partner.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Social {
|
||||
target: Option<u32>,
|
||||
breed: bool,
|
||||
ticks: i32,
|
||||
cooldown: i32,
|
||||
birth_at: i64,
|
||||
}
|
||||
impl Social {
|
||||
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let breedable = can_breed(m);
|
||||
let id = m.id;
|
||||
let nearest =
|
||||
cx.w.nearby(m.position, 8.0, move |s| {
|
||||
s.species == Species::Villager && s.id != id
|
||||
})
|
||||
.filter(|s| m.position.distance_squared(s.position) <= 64.0)
|
||||
.map(|s| (s.id, s.in_love))
|
||||
.collect::<Vec<_>>();
|
||||
let visible: Vec<(u32, bool)> = nearest
|
||||
.into_iter()
|
||||
.filter(|(i, _)| m.sees(cx.w, Who::Mob(*i)))
|
||||
.collect();
|
||||
let Some(&(target, partner_willing)) = visible.first() else {
|
||||
return false;
|
||||
};
|
||||
// RunOne weights: interact 2, breed 1 (when both are willing).
|
||||
let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0;
|
||||
self.target = Some(target);
|
||||
self.breed = breed;
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Goal for Social {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE {
|
||||
return false;
|
||||
}
|
||||
if self.cooldown > 0 {
|
||||
self.cooldown -= 1;
|
||||
return false;
|
||||
}
|
||||
match activity(m, cx.w.day_time) {
|
||||
Activity::Idle => self.pick(m, cx),
|
||||
Activity::Meet => {
|
||||
// SocializeAtBell: one tick in a hundred, near the bell.
|
||||
let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0);
|
||||
near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && {
|
||||
let ok = self.pick(m, cx);
|
||||
self.breed = false;
|
||||
ok
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(t) = self.target else { return false };
|
||||
let Some(s) = cx.w.seen(t) else { return false };
|
||||
if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE {
|
||||
return false;
|
||||
}
|
||||
if self.breed {
|
||||
self.ticks < 350 && can_breed(m) && s.in_love
|
||||
} else {
|
||||
self.ticks < 60
|
||||
}
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks = 0;
|
||||
self.birth_at = 0;
|
||||
if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) {
|
||||
let at = [s.position.x, s.position.y, s.position.z];
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
|
||||
m.nav_stop();
|
||||
self.target = None;
|
||||
self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0);
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks += 1;
|
||||
let Some(t) = self.target else { return };
|
||||
let Some(s) = cx.w.seen(t) else { return };
|
||||
let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y);
|
||||
m.look_at([at[0], eye, at[2]]);
|
||||
if m.position.distance_squared(s.position) > 5.0 {
|
||||
if m.ai.nav.is_done() && self.ticks % 10 == 1 {
|
||||
m.nav_move_to(cx.w, at, 0.5);
|
||||
}
|
||||
return;
|
||||
}
|
||||
m.nav_stop();
|
||||
if !self.breed {
|
||||
cx.events.push(MobEvent::VillagerMeet {
|
||||
mob: m.id,
|
||||
other: t,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let now = cx.w.game_time;
|
||||
if self.birth_at == 0 {
|
||||
self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
|
||||
}
|
||||
if now >= self.birth_at {
|
||||
cx.events.push(MobEvent::VillagerBirth {
|
||||
parent: m.id,
|
||||
partner: t,
|
||||
});
|
||||
self.ticks = 1000;
|
||||
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
|
||||
for p in [m.position, s.position] {
|
||||
cx.events.push(MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at: [p.x, p.y + 1.8, p.z],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem
|
||||
/// every five seconds.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct GolemCall;
|
||||
/// `VillagerHostilesSensor`: how close each hostile must be to scare.
|
||||
fn hostile_range(s: Species) -> f64 {
|
||||
match s {
|
||||
Species::Drowned
|
||||
| Species::Husk
|
||||
| Species::Vex
|
||||
| Species::Zombie
|
||||
| Species::ZombieVillager => 8.0,
|
||||
Species::Evoker | Species::Illusioner | Species::Ravager => 12.0,
|
||||
Species::Pillager => 15.0,
|
||||
Species::Vindicator | Species::Zoglin => 10.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
fn frightened(m: &Mob, cx: &Cx) -> bool {
|
||||
// HURT_BY lasts 100 ticks.
|
||||
let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100;
|
||||
hurt || cx.w.others.iter().any(|s| {
|
||||
s.alive && {
|
||||
let r = hostile_range(s.species);
|
||||
r > 0.0 && s.position.distance_squared(m.position) <= r * r
|
||||
}
|
||||
})
|
||||
}
|
||||
impl Goal for GolemCall {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
!m.is_baby() && frightened(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if cx.w.game_time % 100 == 0 {
|
||||
cx.events.push(MobEvent::GolemCheck {
|
||||
mob: m.id,
|
||||
needed: 3,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,20 +20,57 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(3, LookAtPlayer::new(8.0));
|
||||
g.add(3, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
// NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders.
|
||||
m.ai.targets.add(2, HealRaiders::default());
|
||||
// NearestAttackableWitchTargetGoal: only while not healing raiders.
|
||||
m.ai.targets.add(
|
||||
2,
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| {
|
||||
super::raider::is_raider(s.species) && s.species != Species::Witch
|
||||
}),
|
||||
true,
|
||||
)
|
||||
.interval(1)
|
||||
.when(|m, _| super::raider::has_active_raid(m)),
|
||||
3,
|
||||
NearestTarget::player(true)
|
||||
.interval(10)
|
||||
.gate(|m, _| m.extra.counter2 <= 0)
|
||||
.named("NearestAttackableWitchTargetGoal"),
|
||||
);
|
||||
m.ai.targets
|
||||
.add(3, NearestTarget::player(true).interval(10));
|
||||
}
|
||||
/// `NearestHealableRaiderTargetGoal`: in a raid, target another raider to
|
||||
/// heal, then wait 10 seconds (the cooldown lives in `extra.counter2`).
|
||||
#[derive(Clone, Debug)]
|
||||
struct HealRaiders(NearestTarget);
|
||||
impl Default for HealRaiders {
|
||||
fn default() -> Self {
|
||||
Self(
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| {
|
||||
super::raider::is_raider(s.species) && s.species != Species::Witch
|
||||
}),
|
||||
true,
|
||||
)
|
||||
.interval(0),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Goal for HealRaiders {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.extra.counter2 > 0 || !m.random.next_boolean() {
|
||||
return false;
|
||||
}
|
||||
if !super::raider::has_active_raid(m) {
|
||||
return false;
|
||||
}
|
||||
self.0.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.extra.counter2 = super::goals::reduced(200);
|
||||
self.0.start(m, cx);
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx);
|
||||
}
|
||||
}
|
||||
/// The callback a ranged mob uses to fire (`RangedAttackMob.performRangedAttack`).
|
||||
pub type Fire = fn(&mut Mob, Who, f32, &mut Cx);
|
||||
@@ -123,15 +160,20 @@ impl Goal for RangedAttack {
|
||||
/// Witch.performRangedAttack: harming by default, slowness at range, poison
|
||||
/// on healthy targets, weakness up close.
|
||||
fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
if m.extra.using_item > 0 {
|
||||
// isDrinkingPotion
|
||||
if m.extra.flag {
|
||||
return;
|
||||
}
|
||||
let Some(t) = cx.w.target_info(who) else {
|
||||
return;
|
||||
};
|
||||
let xd = t.position.x - m.position.x;
|
||||
let yd = t.eye_y - 1.1 - m.position.y;
|
||||
let zd = t.position.z - m.position.z;
|
||||
let motion = match who {
|
||||
Who::Player => cx.w.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity),
|
||||
Who::Mob(id) => cx.w.seen(id).map_or(Vec3::ZERO, |s| s.velocity),
|
||||
};
|
||||
let xd = t.position.x + motion.x - m.position.x;
|
||||
let yd = t.eye_y - f64::from(1.1_f32) - m.position.y;
|
||||
let zd = t.position.z + motion.z - m.position.z;
|
||||
let dist = (xd * xd + zd * zd).sqrt();
|
||||
let health = if t.is_player {
|
||||
20.0
|
||||
@@ -180,7 +222,7 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
);
|
||||
// Splash potions throw with gravity 0.05.
|
||||
p.shoot(
|
||||
&mut m.random,
|
||||
&mut crate::projectiles::own_random(m),
|
||||
[xd, yd + dist * 0.2, zd],
|
||||
if dist <= 2.0 { 0.45 } else { 0.75 },
|
||||
8.0,
|
||||
@@ -194,14 +236,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
/// Witch.aiStep: drink water breathing, fire resistance, healing or swiftness.
|
||||
/// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink
|
||||
/// water breathing, fire resistance, healing or swiftness.
|
||||
pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
if m.extra.using_item > 0 {
|
||||
// healRaidersGoal.decrementCooldown (the attack goal's canAttack reads it).
|
||||
m.extra.counter2 -= 1;
|
||||
drink(m, cx_events, target_far);
|
||||
// The angry-witch particles (entity event 15).
|
||||
let _ = m.random.next_float();
|
||||
}
|
||||
fn drink(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
|
||||
if m.extra.flag {
|
||||
// `usingTime-- <= 0`
|
||||
m.extra.using_item -= 1;
|
||||
if m.extra.using_item <= 0 {
|
||||
if m.extra.using_item < 0 {
|
||||
m.extra.using_item = 0;
|
||||
if let Some(potion) = m.extra.main_hand.take() {
|
||||
match potion.as_ref() {
|
||||
|
||||
@@ -111,13 +111,15 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] {
|
||||
/// `performRangedAttack`: a skull from a head toward a point.
|
||||
fn shoot(m: &mut Mob, head: usize, at: [f64; 3], dangerous: bool, events: &mut Vec<MobEvent>) {
|
||||
let h = head_pos(m, head);
|
||||
// Level event 1024: the shoot sound.
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.wither.shoot",
|
||||
h,
|
||||
2.0,
|
||||
(m.random.next_float() - m.random.next_float()) * 0.2 + 1.0,
|
||||
));
|
||||
// Level event 1024: the shoot sound (the client's pitch).
|
||||
if !m.silent {
|
||||
events.push(MobEvent::LevelEventSound {
|
||||
sound: "entity.wither.shoot",
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
volume: 2.0,
|
||||
spread: 0.2,
|
||||
});
|
||||
}
|
||||
let dir = [at[0] - h[0], at[1] - h[1], at[2] - h[2]];
|
||||
let p = Projectile::fireball(
|
||||
ProjectileKind::WitherSkull { dangerous },
|
||||
@@ -135,7 +137,7 @@ pub fn steer(m: &mut Mob) {
|
||||
let mut yd = v.y;
|
||||
if m.position.y < t[1] || !powered(m) && m.position.y < t[1] + 5.0 {
|
||||
yd = yd.max(0.0);
|
||||
yd += 0.3 - yd * 0.6;
|
||||
yd += 0.3 - yd * f64::from(0.6_f32);
|
||||
}
|
||||
v.y = yd;
|
||||
let (dx, dz) = (t[0] - m.position.x, t[2] - m.position.z);
|
||||
@@ -147,7 +149,10 @@ pub fn steer(m: &mut Mob) {
|
||||
}
|
||||
m.velocity = v;
|
||||
if v.x * v.x + v.z * v.z > 0.05 {
|
||||
m.yaw = (v.z.atan2(v.x).to_degrees() as f32) - 90.0;
|
||||
// (float)Mth.atan2(z, x) * (180.0F / (float)Math.PI) - 90.0F
|
||||
m.yaw = (horizon_core::geometry::trig::atan2(v.z, v.x) as f32)
|
||||
* (180.0_f32 / std::f32::consts::PI)
|
||||
- 90.0;
|
||||
}
|
||||
}
|
||||
fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> {
|
||||
@@ -165,14 +170,9 @@ fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> {
|
||||
.map(|s| ([s.position.x, s.position.y, s.position.z], s.eye_y, false)),
|
||||
}
|
||||
}
|
||||
/// `WitherBoss.aiStep` (heads, particles) and `customServerAiStep`.
|
||||
/// `WitherBoss.aiStep` after `super.aiStep()`: the side heads turn, smoke
|
||||
/// rises from the heads (the particle offsets are drawn on the server too).
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
m.extra.point = m
|
||||
.target_info(w)
|
||||
.map(|t| [t.position.x, t.position.y, t.position.z]);
|
||||
// Side heads turn toward their targets, else back to the body.
|
||||
for i in 0..2 {
|
||||
match target_pos(w, m.extra.ints[i]) {
|
||||
@@ -180,22 +180,42 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let h = head_pos(m, i + 1);
|
||||
let (xd, yd, zd) = (p[0] - h[0], eye - h[1], p[2] - h[2]);
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
let x_rot = -(yd.atan2(sd).to_degrees() as f32);
|
||||
let y_rot = horizon_core::geometry::trig::atan2_degrees(zd, xd) - 90.0;
|
||||
let x_rot = -horizon_core::geometry::trig::atan2_degrees(yd, sd);
|
||||
m.anim.v[2 + i] = rotlerp(m.anim.v[2 + i], x_rot, 40.0);
|
||||
m.anim.v[i] = rotlerp(m.anim.v[i], y_rot, 10.0);
|
||||
}
|
||||
None => m.anim.v[i] = rotlerp(m.anim.v[i], m.body_yaw, 10.0),
|
||||
}
|
||||
}
|
||||
let powered = powered(m);
|
||||
for i in 0..3 {
|
||||
let h = head_pos(m, i);
|
||||
for _ in 0..3 {
|
||||
m.random.next_gaussian();
|
||||
}
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "smoke",
|
||||
at: h,
|
||||
count: 0,
|
||||
});
|
||||
// The entity-effect particles roll the level random, not the wither's.
|
||||
let _ = powered;
|
||||
}
|
||||
if m.extra.counter > 0 {
|
||||
for _ in 0..3 {
|
||||
m.random.next_gaussian();
|
||||
m.random.next_float();
|
||||
m.random.next_gaussian();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `WitherBoss.customServerAiStep`: charging, then the side heads' targets
|
||||
/// and volleys, block breaking and healing.
|
||||
pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.extra.point = m
|
||||
.target_info(w)
|
||||
.map(|t| [t.position.x, t.position.y, t.position.z]);
|
||||
if m.extra.counter > 0 {
|
||||
let left = m.extra.counter - 1;
|
||||
if left <= 0 {
|
||||
@@ -203,12 +223,15 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
[m.position.x, m.eye_y(), m.position.z],
|
||||
7.0,
|
||||
));
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.wither.spawn",
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
// Global level event 1023.
|
||||
if !m.silent {
|
||||
events.push(MobEvent::LevelEventSound {
|
||||
sound: "entity.wither.spawn",
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
volume: 1.0,
|
||||
spread: 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
m.extra.counter = left;
|
||||
if m.age.is_multiple_of(10) {
|
||||
@@ -226,11 +249,14 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.extra.ints[2 + k] = age + 10 + m.random.next_int_bound(10).unwrap_or(0);
|
||||
m.extra.ints[4 + k] += 1;
|
||||
if m.extra.ints[4 + k] > 16 {
|
||||
// Mth.nextDouble(random, min, max) = nextDouble * (max - min) + min.
|
||||
let p = m.position;
|
||||
let r = &mut m.random;
|
||||
let mut between = |lo: f64, hi: f64| r.next_double() * (hi - lo) + lo;
|
||||
let at = [
|
||||
m.position.x - 10.0 + r.next_double() * 20.0,
|
||||
m.position.y - 5.0 + r.next_double() * 10.0,
|
||||
m.position.z - 10.0 + r.next_double() * 20.0,
|
||||
between(p.x - 10.0, p.x + 10.0),
|
||||
between(p.y - 5.0, p.y + 5.0),
|
||||
between(p.z - 10.0, p.z + 10.0),
|
||||
];
|
||||
shoot(m, i + 1, at, true, events);
|
||||
m.extra.ints[4 + k] = 0;
|
||||
@@ -307,12 +333,13 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
}
|
||||
if destroyed {
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.wither.break_block",
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
// Level event 1022.
|
||||
events.push(MobEvent::LevelEventSound {
|
||||
sound: "entity.wither.break_block",
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
volume: 1.0,
|
||||
spread: 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,17 @@ use horizon_core::{
|
||||
random::RandomSource,
|
||||
};
|
||||
|
||||
/// A new projectile entity's own random: vanilla seeds every entity's random
|
||||
/// unpredictably, and a projectile's spread (and an arrow's base damage) come
|
||||
/// from it, never from the shooter's random.
|
||||
pub fn own_random(shooter: &crate::mobs::Mob) -> horizon_core::random::LegacyRandom {
|
||||
horizon_core::random::LegacyRandom::new(
|
||||
i64::from(shooter.id).wrapping_mul(0x9E37_79B9)
|
||||
^ i64::from(shooter.age)
|
||||
^ shooter.position.x.to_bits() as i64,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ProjectileKind {
|
||||
/// Arrow with its base damage, critical flag and tipped/stray/bogged effect.
|
||||
|
||||
@@ -1846,8 +1846,16 @@ impl Level {
|
||||
}),
|
||||
),
|
||||
];
|
||||
// Vanilla writes `equipment` even when empty and omits an empty effect list.
|
||||
entries.push(("equipment", Tag::compound(equipment)));
|
||||
// LivingEntity.addAdditionalSaveData omits empty equipment and an empty
|
||||
// effect list. PlayerEquipment.isEmpty also counts the selected hotbar
|
||||
// item, which the codec never writes: holding one saves `equipment: {}`.
|
||||
let holding = self
|
||||
.inventory
|
||||
.iter()
|
||||
.any(|(slot, _, count, _)| i32::from(*slot) == self.selected_slot && *count > 0);
|
||||
if holding || !equipment.is_empty() {
|
||||
entries.push(("equipment", Tag::compound(equipment)));
|
||||
}
|
||||
if self.active_effects.is_empty() {
|
||||
entries.retain(|(key, _)| *key != "active_effects");
|
||||
}
|
||||
@@ -1943,7 +1951,17 @@ impl Level {
|
||||
map.remove(&JavaString::from(key));
|
||||
}
|
||||
}
|
||||
let uuid = *self.player_uuid.get_or_insert_with(random_uuid);
|
||||
// A new world's player has the offline profile id of its name
|
||||
// (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game.
|
||||
let uuid = *self.player_uuid.get_or_insert_with(|| {
|
||||
let u = horizon_protocol::crypto::offline_uuid("Player");
|
||||
[
|
||||
(u >> 96) as u32 as i32,
|
||||
(u >> 64) as u32 as i32,
|
||||
(u >> 32) as u32 as i32,
|
||||
u as u32 as i32,
|
||||
]
|
||||
});
|
||||
// A new world's first spawn point is its world spawn.
|
||||
if self.world_spawn.is_none() {
|
||||
self.world_spawn = self.spawn.map(|s| {
|
||||
|
||||
@@ -578,8 +578,12 @@ impl ScoreEntry {
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Scoreboard {
|
||||
/// In creation order.
|
||||
/// In the iteration order of vanilla's objectivesByName map.
|
||||
pub objectives: Vec<Objective>,
|
||||
/// `objectivesByName` (`Object2ObjectOpenHashMap(16, 0.5)`) and
|
||||
/// `teamsByName` key orders.
|
||||
objective_order: Option<crate::fastutil_order::OpenOrder>,
|
||||
team_order: crate::fastutil_order::OpenOrder,
|
||||
pub scores: BTreeMap<String, BTreeMap<String, Score>>,
|
||||
pub display: BTreeMap<String, String>,
|
||||
pub teams: Vec<Team>,
|
||||
@@ -612,15 +616,45 @@ impl Scoreboard {
|
||||
display_auto_update,
|
||||
number_format,
|
||||
});
|
||||
self.objective_order
|
||||
.get_or_insert_with(|| crate::fastutil_order::OpenOrder::new(16, 0.5))
|
||||
.insert(name);
|
||||
self.sort_objectives();
|
||||
true
|
||||
}
|
||||
/// Objectives and teams in vanilla's hash map iteration order.
|
||||
fn sort_objectives(&mut self) {
|
||||
let order = self
|
||||
.objective_order
|
||||
.get_or_insert_with(|| crate::fastutil_order::OpenOrder::new(16, 0.5));
|
||||
for o in &self.objectives {
|
||||
order.insert(&o.name);
|
||||
}
|
||||
let rank: BTreeMap<&str, usize> = order.keys().enumerate().map(|(i, k)| (k, i)).collect();
|
||||
self.objectives
|
||||
.sort_by_key(|o| rank.get(o.name.as_str()).copied().unwrap_or(usize::MAX));
|
||||
for t in &self.teams {
|
||||
self.team_order.insert(&t.name);
|
||||
}
|
||||
let rank: BTreeMap<&str, usize> = self
|
||||
.team_order
|
||||
.keys()
|
||||
.enumerate()
|
||||
.map(|(i, k)| (k, i))
|
||||
.collect();
|
||||
self.teams
|
||||
.sort_by_key(|t| rank.get(t.name.as_str()).copied().unwrap_or(usize::MAX));
|
||||
}
|
||||
pub fn remove_objective(&mut self, name: &str) {
|
||||
self.objectives.retain(|o| o.name != name);
|
||||
if let Some(order) = self.objective_order.as_mut() {
|
||||
order.remove(name);
|
||||
}
|
||||
self.display.retain(|_, o| o != name);
|
||||
// Scoreboard.removeObjective: holders left without scores stay tracked.
|
||||
for s in self.scores.values_mut() {
|
||||
s.remove(name);
|
||||
}
|
||||
self.scores.retain(|_, s| !s.is_empty());
|
||||
}
|
||||
pub fn display_objective(&self, slot: &str) -> Option<&Objective> {
|
||||
self.objective(self.display.get(slot)?)
|
||||
@@ -739,12 +773,15 @@ impl Scoreboard {
|
||||
pub fn add_team(&mut self, name: &str) -> &mut Team {
|
||||
if self.team(name).is_none() {
|
||||
self.teams.push(Team::new(name));
|
||||
self.team_order.insert(name);
|
||||
self.sort_objectives();
|
||||
}
|
||||
self.team_mut(name).expect("just added")
|
||||
}
|
||||
pub fn remove_team(&mut self, name: &str) {
|
||||
self.team_of.retain(|_, t| t != name);
|
||||
self.teams.retain(|t| t.name != name);
|
||||
self.team_order.remove(name);
|
||||
}
|
||||
pub fn players_team(&self, player: &str) -> Option<&Team> {
|
||||
self.team(self.team_of.get(player)?)
|
||||
@@ -1046,7 +1083,9 @@ mod tests {
|
||||
sb.set_display_objective("sidebar", Some("kills"));
|
||||
sb.remove_objective("kills");
|
||||
assert!(sb.display_objective("sidebar").is_none());
|
||||
assert!(sb.tracked().is_empty());
|
||||
// Scoreboard.removeObjective keeps the holder, now without scores.
|
||||
assert_eq!(sb.tracked(), vec!["Steve".to_owned()]);
|
||||
assert!(sb.holder_scores("Steve").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -908,7 +908,8 @@ fn team(id: &str, ctx: &Context, env: &mut dyn Env) -> CmdResult<i32> {
|
||||
let mut tracker = Tracker::default();
|
||||
for m in &members {
|
||||
let joined = env.sb_mut().add_to_team(&m.name, &name);
|
||||
tracker.track(m, i32::from(joined));
|
||||
// The message reads the display name after the change.
|
||||
tracker.track(&env.named(&m.name), i32::from(joined));
|
||||
}
|
||||
let shown = formatted(env, &name);
|
||||
tracker.send(
|
||||
@@ -934,7 +935,7 @@ fn team(id: &str, ctx: &Context, env: &mut dyn Env) -> CmdResult<i32> {
|
||||
let mut tracker = Tracker::default();
|
||||
for m in &members {
|
||||
let left = env.sb_mut().remove_from_team(&m.name);
|
||||
tracker.track(m, i32::from(left));
|
||||
tracker.track(&env.named(&m.name), i32::from(left));
|
||||
}
|
||||
tracker.send(
|
||||
env,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Full-screen camera effects drawn between the world and the HUD:
|
||||
//! `ScreenEffectRenderer` (in-wall block texture, underwater overlay, fire)
|
||||
//! and the `Hud` camera overlays (vignette, pumpkin blur, powder-snow
|
||||
//! and the full-screen `Hud` camera overlays laid out by
|
||||
//! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow
|
||||
//! outline, nether portal swirl). Positions are clip-space quads; textures
|
||||
//! come from the shared 2D atlas and may repeat.
|
||||
use crate::hud::Rect;
|
||||
use crate::{hud::Rect, hud_layout::GuiDraw};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -40,14 +41,9 @@ pub struct ScreenInputs<'a> {
|
||||
/// Eye in water: (lightmap brightness at the eye, yaw, pitch).
|
||||
pub water: Option<(f32, f32, f32)>,
|
||||
pub on_fire: bool,
|
||||
/// Equipment camera overlays (`Equippable.cameraOverlay`, e.g. `misc/pumpkinblur`).
|
||||
pub camera_overlays: Vec<String>,
|
||||
/// `Player.getPercentFrozen`.
|
||||
pub frozen: f32,
|
||||
/// `Options.vignette`.
|
||||
pub vignette: bool,
|
||||
/// Distance to the world border and its warning distance, when close.
|
||||
pub border_warning: Option<f32>,
|
||||
/// `Hud.extractCameraOverlays` draws: the full-screen blits become
|
||||
/// screen quads (the spyglass, its fills and the nausea swirl do not).
|
||||
pub gui_overlays: &'a [GuiDraw],
|
||||
}
|
||||
|
||||
/// Effect state advanced every tick.
|
||||
@@ -170,43 +166,43 @@ impl ScreenEffects {
|
||||
}),
|
||||
blend,
|
||||
};
|
||||
if input.vignette
|
||||
&& let Some(rect) = sprite("misc/vignette")
|
||||
{
|
||||
let b = self.vignette_brightness.clamp(0.0, 1.0);
|
||||
let color = match input.border_warning {
|
||||
Some(w) if w > 0.0 => {
|
||||
let w = w.clamp(0.0, 1.0);
|
||||
let red = b * (1.0 - w);
|
||||
let gb = b + (1.0 - b) * w;
|
||||
[red, gb, gb, 1.0]
|
||||
let rgba = |c: u32| {
|
||||
let [a, r, g, b] = c.to_be_bytes();
|
||||
[r, g, b, a].map(|v| f32::from(v) / 255.0)
|
||||
};
|
||||
for d in input.gui_overlays {
|
||||
match d {
|
||||
GuiDraw::Blit {
|
||||
texture,
|
||||
blend,
|
||||
x: 0,
|
||||
y: 0,
|
||||
color,
|
||||
..
|
||||
} if *blend != crate::hud_layout::Blend::Nausea
|
||||
&& texture != "misc/spyglass_scope" =>
|
||||
{
|
||||
let blend = if *blend == crate::hud_layout::Blend::Vignette {
|
||||
Blend::Vignette
|
||||
} else {
|
||||
Blend::Alpha
|
||||
};
|
||||
if let Some(rect) = sprite(texture) {
|
||||
out.push(gui(rect, rgba(*color), blend));
|
||||
}
|
||||
}
|
||||
_ => [b, b, b, 1.0],
|
||||
};
|
||||
out.push(gui(rect, color, Blend::Vignette));
|
||||
}
|
||||
for overlay in &input.camera_overlays {
|
||||
if let Some(rect) = sprite(overlay) {
|
||||
out.push(gui(rect, [1.0; 4], Blend::Alpha));
|
||||
GuiDraw::AtlasSprite {
|
||||
sprite: name,
|
||||
color,
|
||||
..
|
||||
} => {
|
||||
if let Some(rect) = sprite(name) {
|
||||
out.push(gui(rect, rgba(*color), Blend::Alpha));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if input.frozen > 0.0
|
||||
&& let Some(rect) = sprite("misc/powder_snow_outline")
|
||||
{
|
||||
out.push(gui(rect, [1.0, 1.0, 1.0, input.frozen], Blend::Alpha));
|
||||
}
|
||||
let portal = self.o_portal + (self.portal - self.o_portal) * input.partial;
|
||||
if portal > 0.0
|
||||
&& let Some(rect) = sprite("block/nether_portal")
|
||||
{
|
||||
let mut a = portal;
|
||||
if a < 1.0 {
|
||||
a *= a;
|
||||
a *= a;
|
||||
a = a * 0.8 + 0.2;
|
||||
}
|
||||
out.push(gui(rect, [1.0, 1.0, 1.0, a], Blend::Alpha));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -254,10 +250,7 @@ mod tests {
|
||||
block_overlay: None,
|
||||
water: Some((1.0, 0.0, 0.0)),
|
||||
on_fire: false,
|
||||
camera_overlays: vec![],
|
||||
frozen: 0.0,
|
||||
vignette: true,
|
||||
border_warning: None,
|
||||
gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)],
|
||||
};
|
||||
let quads = e.build(&input);
|
||||
assert_eq!(quads.len(), 1);
|
||||
|
||||
@@ -475,15 +475,24 @@ impl Settings {
|
||||
}
|
||||
})
|
||||
}
|
||||
/// `Options.getBackgroundColor(float)`: the text backdrop colour, `default`
|
||||
/// opacity unless `backgroundForChatOnly` is off.
|
||||
pub fn text_background(&self, default: f32) -> u32 {
|
||||
crate::hud_layout::background_color(
|
||||
self.file.bool("backgroundForChatOnly"),
|
||||
f64::from(self.text_background_opacity),
|
||||
default,
|
||||
)
|
||||
}
|
||||
pub fn chat_options(&self) -> crate::chat::ChatOptions {
|
||||
crate::chat::ChatOptions {
|
||||
opacity: self.chat_opacity,
|
||||
background_opacity: self.text_background_opacity,
|
||||
scale: self.chat_scale,
|
||||
width: self.chat_width,
|
||||
height_focused: self.chat_height_focused,
|
||||
height_unfocused: self.chat_height_unfocused,
|
||||
line_spacing: self.chat_line_spacing,
|
||||
opacity: f64::from(self.chat_opacity),
|
||||
background_opacity: f64::from(self.text_background_opacity),
|
||||
scale: f64::from(self.chat_scale),
|
||||
width: f64::from(self.chat_width),
|
||||
height_focused: f64::from(self.chat_height_focused),
|
||||
height_unfocused: f64::from(self.chat_height_unfocused),
|
||||
line_spacing: f64::from(self.chat_line_spacing),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,7 +328,7 @@ impl Pretty {
|
||||
"\n"
|
||||
};
|
||||
let n = c.len();
|
||||
for (i, (k, v)) in c.iter().enumerate() {
|
||||
for (i, (k, v)) in java_hash_order(c).into_iter().enumerate() {
|
||||
self.lit(&entry, None);
|
||||
let key = string_of(k);
|
||||
if !key.is_empty()
|
||||
@@ -357,6 +357,91 @@ impl Pretty {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The iteration order of the `HashMap<String, Tag>` a `CompoundTag` holds,
|
||||
/// for a map that grew to its size by insertion: buckets by
|
||||
/// `HashMap.hash(String.hashCode())`, keys sharing a bucket in key order.
|
||||
pub fn java_hash_order(
|
||||
c: &horizon_world::nbt::Compound,
|
||||
) -> Vec<(&horizon_world::nbt::JavaString, &Tag)> {
|
||||
let mut capacity = 16usize;
|
||||
while c.len() > capacity * 3 / 4 {
|
||||
capacity *= 2;
|
||||
}
|
||||
let bucket = |k: &horizon_world::nbt::JavaString| {
|
||||
let h = string_of(k)
|
||||
.encode_utf16()
|
||||
.fold(0u32, |h, ch| h.wrapping_mul(31).wrapping_add(u32::from(ch)));
|
||||
((h ^ (h >> 16)) as usize) & (capacity - 1)
|
||||
};
|
||||
// Keys sharing a bucket iterate in insertion order: the order vanilla's
|
||||
// savers write them, as far as it is known here.
|
||||
const WRITE_ORDER: &[&str] = &[
|
||||
// ItemStack.CODEC.
|
||||
"id",
|
||||
"count",
|
||||
"components",
|
||||
// Entity.saveWithoutId.
|
||||
"Pos",
|
||||
"Motion",
|
||||
"Rotation",
|
||||
"fall_distance",
|
||||
"Fire",
|
||||
"Air",
|
||||
"OnGround",
|
||||
"Invulnerable",
|
||||
"PortalCooldown",
|
||||
"UUID",
|
||||
"CustomName",
|
||||
"CustomNameVisible",
|
||||
"Silent",
|
||||
"NoGravity",
|
||||
"Glowing",
|
||||
"TicksFrozen",
|
||||
"HasVisualFire",
|
||||
"Tags",
|
||||
"data",
|
||||
"Passengers",
|
||||
// LivingEntity.addAdditionalSaveData.
|
||||
"Health",
|
||||
"HurtTime",
|
||||
"DeathTime",
|
||||
"AbsorptionAmount",
|
||||
"current_impulse_context_reset_grace_time",
|
||||
"current_explosion_impact_pos",
|
||||
"attributes",
|
||||
"active_effects",
|
||||
"FallFlying",
|
||||
"sleeping_pos",
|
||||
"Brain",
|
||||
"equipment",
|
||||
// ArmorStand.
|
||||
"Invisible",
|
||||
"Small",
|
||||
"ShowArms",
|
||||
"DisabledSlots",
|
||||
"NoBasePlate",
|
||||
"Marker",
|
||||
"Pose",
|
||||
];
|
||||
// BlockEntity.saveMetadata writes the position after the entity's data.
|
||||
const AFTER: &[&str] = &["x", "y", "z"];
|
||||
let rank = |k: &horizon_world::nbt::JavaString| {
|
||||
let k = string_of(k);
|
||||
WRITE_ORDER
|
||||
.iter()
|
||||
.position(|w| *w == k)
|
||||
.or_else(|| {
|
||||
AFTER
|
||||
.iter()
|
||||
.position(|w| *w == k)
|
||||
.map(|i| WRITE_ORDER.len() + 1 + i)
|
||||
})
|
||||
.unwrap_or(WRITE_ORDER.len())
|
||||
};
|
||||
let mut entries: Vec<_> = c.iter().collect();
|
||||
entries.sort_by_key(|(k, _)| (bucket(k), rank(k)));
|
||||
entries
|
||||
}
|
||||
/// `NbtUtils.toPrettyComponent`: the coloured, unindented form.
|
||||
pub fn pretty(tag: &Tag) -> Text {
|
||||
pretty_indented(tag, "")
|
||||
|
||||
@@ -14,6 +14,10 @@ struct Globals {
|
||||
sun: vec4<f32>,
|
||||
// x: sky fog end, y: cloud fog end, z: dark disc flag
|
||||
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 sprites: texture_2d_array<f32>;
|
||||
|
||||
@@ -91,6 +91,24 @@ impl VanillaTerrain {
|
||||
) -> Option<(String, [i32; 3])> {
|
||||
self.generator.worker().locate(names, from, radius)
|
||||
}
|
||||
/// `/locate biome`: `BiomeSource.findClosestBiome3d`.
|
||||
pub fn find_closest_biome(
|
||||
&self,
|
||||
search: &horizon_world::worldgen::generator::BiomeSearch<'_>,
|
||||
) -> Option<(String, [i32; 3])> {
|
||||
let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let worker = worker.get_or_insert_with(|| self.generator.worker());
|
||||
worker.find_closest_biome(search)
|
||||
}
|
||||
/// `/place jigsaw`: `JigsawPlacement.addPieces`.
|
||||
pub fn jigsaw_pieces(
|
||||
&self,
|
||||
query: &horizon_world::worldgen::generator::JigsawQuery<'_>,
|
||||
) -> Option<horizon_world::worldgen::generator::JigsawPieces> {
|
||||
let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let worker = worker.get_or_insert_with(|| self.generator.worker());
|
||||
worker.jigsaw_pieces(query)
|
||||
}
|
||||
/// Concentric ring positions of a structure set (strongholds), once known.
|
||||
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
||||
self.generator.ring_positions(set)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user