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:
Ludovic Marie
2026-10-12 17:18:11 +02:00
133 changed files with 19187 additions and 2931 deletions
@@ -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);
}
+242 -115
View File
@@ -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)
}
+88 -4
View File
@@ -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)?;