Merge branch 'parity/rendering-gaps' into parity-base
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
<a href="https://github.com/ludovic111/horizon/actions/workflows/ci.yml"><img src="https://github.com/ludovic111/horizon/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>
|
||||
<img src="https://img.shields.io/badge/Minecraft-Java%2026.3-5D9C3F" alt="Minecraft Java 26.3">
|
||||
<img src="https://img.shields.io/badge/Rust-stable-B7410E?logo=rust&logoColor=white" alt="Rust">
|
||||
<img src="https://img.shields.io/badge/vanilla%20parity-88%25-F0795A" alt="Vanilla parity 88%">
|
||||
<img src="https://img.shields.io/badge/vanilla%20parity-89%25-F0795A" alt="Vanilla parity 89%">
|
||||
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-2A2470" alt="Linux, macOS and Windows">
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3B2F7E" alt="MIT license"></a>
|
||||
</p>
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
A Rust rewrite of Minecraft: Java Edition 26.3 that aims for one-to-one vanilla parity, checked against the game itself with differential tests.
|
||||
|
||||
**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 88% (see [Project status](#project-status)).
|
||||
**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 89% (see [Project status](#project-status)).
|
||||
|
||||
> Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3.
|
||||
|
||||
@@ -113,7 +113,7 @@ The client starts on the title screen. Command-line options (`--world`, `--seed`
|
||||
|
||||
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
|
||||
|
||||
### Java parity: 88%
|
||||
### Java parity: 89%
|
||||
|
||||
Each subsystem scores 0 (absent), 0.25 (started, not playable), 0.5 (playable,
|
||||
major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete
|
||||
@@ -130,7 +130,7 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
|
||||
| Network protocol and multiplayer | 0.75 | Joins vanilla servers and opens worlds to LAN; server.properties, eula.txt and the user lists match vanilla, but there is no dedicated server mode and LAN hosting is not tested against a vanilla client |
|
||||
| Chunk storage and palettes | 1 | None: client and saves share paletted containers, identical to vanilla over 266 scenarios |
|
||||
| Section meshing | 1 | None: 112 scenes and over a million quads identical to vanilla |
|
||||
| Rendering | 0.75 | Entity models, block entity renderers (400 cases, End portals and gateways included) and their animations (256 cases), the HUD overlays (2,200 states), the player list, subtitles and the world border match vanilla; the recipe book's drawing and the banner preview are not compared, and End gateways show no beam in game |
|
||||
| Rendering | 1 | None: entity models, block entity renderers (407 cases, End portals, gateways and the loom's banner preview included) and their animations (296 cases, End gateway beams included), the HUD overlays (2,200 states), the recipe book (600 states), the player list, subtitles and the world border match vanilla |
|
||||
| Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included |
|
||||
| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla |
|
||||
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded |
|
||||
|
||||
@@ -8,9 +8,10 @@ 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,
|
||||
EndGateway, PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot,
|
||||
direction_index,
|
||||
},
|
||||
block_entity_render::BlockEntityRenderer,
|
||||
block_entity_render::{BlockEntityRenderer, gateway_beam},
|
||||
blocks::{BlockFacts, Fluid},
|
||||
items::Items,
|
||||
};
|
||||
@@ -188,6 +189,14 @@ fn main() -> Result<()> {
|
||||
let facing = prop(&block, "facing")
|
||||
.and_then(direction_index)
|
||||
.unwrap_or(1);
|
||||
// End gateways: the saved age, the level's height range and the
|
||||
// integrated server's copy.
|
||||
let initial = EndGateway {
|
||||
age: case["age"].as_i64().unwrap_or(0),
|
||||
teleport_cooldown: 0,
|
||||
};
|
||||
let max_y = int(&case["level"][0]) + int(&case["level"][1]) - 1;
|
||||
let mut server = initial;
|
||||
let mut text = String::new();
|
||||
for step in case["steps"].as_array().into_iter().flatten() {
|
||||
let time = step["time"].as_i64().unwrap_or(0);
|
||||
@@ -445,6 +454,36 @@ fn main() -> Result<()> {
|
||||
f(progress),
|
||||
style
|
||||
);
|
||||
} else if name == "minecraft:end_gateway" {
|
||||
let client = anims.gateways.entry(pos).or_insert(initial);
|
||||
if step["enter"].as_bool() == Some(true) && server.enter() {
|
||||
log.push_str(" blockEvent 1 0");
|
||||
client.trigger_event(1, 0);
|
||||
}
|
||||
if server.portal_tick() {
|
||||
log.push_str(" blockEvent 1 0");
|
||||
client.trigger_event(1, 0);
|
||||
}
|
||||
if let Some((e0, e1)) = event {
|
||||
let handled = client.trigger_event(e0, e1);
|
||||
let _ = write!(log, " event {handled}");
|
||||
}
|
||||
client.tick();
|
||||
let g = *client;
|
||||
let a = anims.block_anim(pos, time, partial, Default::default());
|
||||
let b = gateway_beam(a.gateway, partial, max_y, time);
|
||||
let _ = write!(
|
||||
text,
|
||||
"{} {} server {} {} render {} {} {:x} {}",
|
||||
g.age,
|
||||
g.teleport_cooldown,
|
||||
server.age,
|
||||
server.teleport_cooldown,
|
||||
b.height,
|
||||
f(b.scale),
|
||||
b.color,
|
||||
f(b.animation_time)
|
||||
);
|
||||
} else {
|
||||
text = format!("unsupported {block}");
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use horizon_client::{
|
||||
},
|
||||
chunk::{Chunk, Light},
|
||||
hud::{HudAtlas, Rect},
|
||||
item_render::{ItemRenderer, gui},
|
||||
signs::{DYE_TEXT, SignData, SignText},
|
||||
world::World,
|
||||
};
|
||||
@@ -119,6 +120,7 @@ fn main() -> Result<()> {
|
||||
let renderer = BlockEntityRenderer::load(root, registry)?;
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let banners = Banners::load(root);
|
||||
let items = ItemRenderer::load(root)?;
|
||||
let (sprites, names, grid) = fake_sprites(textures)?;
|
||||
let air = registry.default_state("minecraft:air").ok_or("no air")?;
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
@@ -128,6 +130,43 @@ fn main() -> Result<()> {
|
||||
{
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let block = case["block"].as_str().unwrap_or_default();
|
||||
if let Some(loom) = case.get("loom") {
|
||||
// The loom's result preview, as LoomScreen draws it at (0, 0).
|
||||
let layers: Vec<(String, String)> = loom["patterns"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|p| {
|
||||
(
|
||||
banners.banner_texture(p[0].as_str().unwrap_or_default()),
|
||||
p[1].as_str().unwrap_or_default().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let base = loom["base"].as_str().unwrap_or_default();
|
||||
let flat = gui::items_flat_lights();
|
||||
let quads: Vec<Value> =
|
||||
gui::banner_result_quads(&items, &sprites, 0.0, 0.0, base, &layers)
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let (cu, cv) = ((q.uv[0][0] / 2.0).floor(), (q.uv[0][1] / 2.0).floor());
|
||||
let texture = names
|
||||
.get(cu as usize + cv as usize * grid)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let v: Vec<Value> = (0..4)
|
||||
.map(|k| {
|
||||
let p = q.pos[k];
|
||||
json!([p.x, p.y, p.z, q.uv[k][0] - cu * 2.0, q.uv[k][1] - cv * 2.0])
|
||||
})
|
||||
.collect();
|
||||
// Full bright (15728880).
|
||||
json!({"texture": texture, "v": v, "color": gui::lit_color(q, flat), "light": 0xF0F0})
|
||||
})
|
||||
.collect();
|
||||
writeln!(out, "{}", json!({"quads": quads, "texts": []}))?;
|
||||
continue;
|
||||
}
|
||||
if block == "minecraft:beacon" {
|
||||
// BeaconRenderer: the beam sections from the case, as Horizon's beacon keeps them.
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0);
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//! The recipe book's drawing, for tools/test_recipe_book_render_parity.py:
|
||||
//! reads one JSON case per line (book type, GUI size, tabs, search box,
|
||||
//! filter, recipe collections and page, overlay, ghost slots, cycling index,
|
||||
//! mouse) and writes the calls `horizon_client::recipe_book_screen` makes,
|
||||
//! in the oracle's JSON form.
|
||||
//!
|
||||
//! usage: recipe_book_render_fixture RESOURCES CASES OUTPUT
|
||||
use horizon_client::{
|
||||
crafting::Recipes,
|
||||
hud::{HudAtlas, HudBatch},
|
||||
items::{ItemStack, Items},
|
||||
lang,
|
||||
recipe_book::{Book, BookType, Entry},
|
||||
recipe_book_screen::{
|
||||
ButtonView, Call, GhostView, ItemCall, OverlayRecipe, OverlayView, Run, Screen, Search,
|
||||
TabView, draw, overlay_cells, overlay_origin,
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fmt::Write as _, fs, path::Path};
|
||||
|
||||
fn runs(r: &[Run]) -> Value {
|
||||
Value::Array(
|
||||
r.iter()
|
||||
.map(|r| json!([r.text, r.color, r.italic]))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
fn round(v: f32) -> f32 {
|
||||
(v * 1e4).round() / 1e4
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT";
|
||||
let root = Path::new(args.get(1).ok_or(usage)?);
|
||||
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let book = Book::build(&recipes, &items);
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let root_buf = root.to_path_buf();
|
||||
lang::set(lang::Language::load(&[&root_buf], lang::DEFAULT));
|
||||
let translate = |key: &str| lang::get(key);
|
||||
let text_width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
|
||||
let mut out = String::new();
|
||||
for line in cases.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
|
||||
let kind = match case["type"].as_str().unwrap_or_default() {
|
||||
"crafting" => BookType::Crafting,
|
||||
"furnace" => BookType::Furnace,
|
||||
"blast_furnace" => BookType::BlastFurnace,
|
||||
_ => BookType::Smoker,
|
||||
};
|
||||
let filtering = case["filtering"].as_bool().unwrap_or(false);
|
||||
let tab_list = kind.tabs();
|
||||
let tabs: Vec<TabView> = case["tabs"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|t| {
|
||||
let (a, b) = tab_list[t["tab"].as_u64().unwrap_or(0) as usize].icons();
|
||||
TabView {
|
||||
icons: (a.to_owned(), b.map(str::to_owned)),
|
||||
selected: t["selected"].as_bool().unwrap_or(false),
|
||||
anim: t["anim"].as_f64().unwrap_or(0.0) as f32,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let s = &case["search"];
|
||||
let search = Search {
|
||||
value: s["value"].as_str().unwrap_or_default().to_owned(),
|
||||
cursor: s["cursor"].as_u64().unwrap_or(0) as usize,
|
||||
highlight: s["highlight"].as_u64().unwrap_or(0) as usize,
|
||||
display: s["display"].as_u64().unwrap_or(0) as usize,
|
||||
focused: s["focused"].as_bool().unwrap_or(false),
|
||||
blink_ms: s["blink"].as_u64().unwrap_or(0),
|
||||
};
|
||||
// Each collection's recipes and craftable flags.
|
||||
let collections: Vec<Vec<(&Entry, bool)>> = case["collections"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| {
|
||||
c["recipes"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| Some((book.entry(r[0].as_str()?)?, r[1].as_bool()?)))
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let page = case["page"].as_u64().unwrap_or(0) as usize;
|
||||
let pages = collections.len().div_ceil(20);
|
||||
let anims = case["buttonAnims"].as_array().cloned().unwrap_or_default();
|
||||
let shown = &collections[(20 * page).min(collections.len())..];
|
||||
let buttons: Vec<ButtonView> = shown
|
||||
.iter()
|
||||
.take(20)
|
||||
.enumerate()
|
||||
.map(|(i, c)| ButtonView {
|
||||
has_craftable: c.iter().any(|e| e.1),
|
||||
entries: c
|
||||
.iter()
|
||||
.filter(|e| e.1 || !filtering)
|
||||
.map(|e| vec![e.0.result.clone()])
|
||||
.collect(),
|
||||
anim: anims.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32,
|
||||
})
|
||||
.collect();
|
||||
let (xo, yo) = Screen {
|
||||
book: kind,
|
||||
width: int(&case["width"]),
|
||||
height: int(&case["height"]),
|
||||
narrow: case["narrow"].as_bool().unwrap_or(false),
|
||||
mouse: (0, 0),
|
||||
index: 0,
|
||||
filtering,
|
||||
search: &search,
|
||||
tabs: &[],
|
||||
buttons: &[],
|
||||
page,
|
||||
pages,
|
||||
overlay: None,
|
||||
ghost: None,
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
}
|
||||
.origin();
|
||||
let overlay = case["overlay"].as_u64().map(|i| {
|
||||
let i = i as usize;
|
||||
let c = &shown[i];
|
||||
let mut recipes: Vec<OverlayRecipe> = c
|
||||
.iter()
|
||||
.filter(|e| e.1)
|
||||
.map(|e| OverlayRecipe {
|
||||
craftable: true,
|
||||
cells: overlay_cells(&book, e.0),
|
||||
})
|
||||
.collect();
|
||||
if !filtering {
|
||||
recipes.extend(c.iter().filter(|e| !e.1).map(|e| OverlayRecipe {
|
||||
craftable: false,
|
||||
cells: overlay_cells(&book, e.0),
|
||||
}));
|
||||
}
|
||||
let (x, y) = overlay_origin(
|
||||
xo + 11 + 25 * (i as i32 % 5),
|
||||
yo + 31 + 25 * (i as i32 / 5),
|
||||
recipes.len(),
|
||||
xo,
|
||||
yo,
|
||||
);
|
||||
OverlayView { x, y, recipes }
|
||||
});
|
||||
let ghosts: Vec<GhostView> = case["ghost"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|g| GhostView {
|
||||
x: int(&g["x"]),
|
||||
y: int(&g["y"]),
|
||||
result: g["result"].as_bool().unwrap_or(false),
|
||||
items: g["items"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|i| ItemStack::new(i, 1))
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
let screen = Screen {
|
||||
book: kind,
|
||||
width: int(&case["width"]),
|
||||
height: int(&case["height"]),
|
||||
narrow: case["narrow"].as_bool().unwrap_or(false),
|
||||
mouse: (int(&case["mouse"][0]), int(&case["mouse"][1])),
|
||||
index: case["index"].as_u64().unwrap_or(0) as usize,
|
||||
filtering,
|
||||
search: &search,
|
||||
tabs: &tabs,
|
||||
buttons: &buttons,
|
||||
page,
|
||||
pages,
|
||||
overlay: overlay.as_ref(),
|
||||
ghost: case.get("ghost").map(|_| {
|
||||
(
|
||||
int(&case["left"]),
|
||||
int(&case["top"]),
|
||||
case["big"].as_bool().unwrap_or(false),
|
||||
ghosts.as_slice(),
|
||||
)
|
||||
}),
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
};
|
||||
let draws: Vec<Value> = draw(&screen)
|
||||
.into_iter()
|
||||
.filter_map(|d| {
|
||||
let m: Vec<f32> = d.pose.iter().map(|v| round(*v)).collect();
|
||||
let mut o = match d.call {
|
||||
Call::Blit {
|
||||
texture,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
u,
|
||||
v,
|
||||
tw,
|
||||
th,
|
||||
} => json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h,
|
||||
"u": u, "v": v, "tw": tw, "th": th}),
|
||||
Call::Sprite { id, x, y, w, h } => {
|
||||
json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h})
|
||||
}
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}),
|
||||
Call::Highlight { x0, y0, x1, y1 } => {
|
||||
json!({"t": "highlight", "x0": x0, "y0": y0, "x1": x1, "y1": y1})
|
||||
}
|
||||
Call::Text {
|
||||
runs: r,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => json!({"t": "text", "runs": runs(&r), "x": x, "y": y, "color": color, "shadow": shadow}),
|
||||
Call::Item { call, stack, x, y } => {
|
||||
if stack.count == 0 || &*stack.item == "minecraft:air" {
|
||||
return None;
|
||||
}
|
||||
let t = match call {
|
||||
ItemCall::Item => "item",
|
||||
ItemCall::Fake => "fake",
|
||||
ItemCall::Decorations => "decorations",
|
||||
};
|
||||
json!({"t": t, "id": &*stack.item, "count": stack.count, "x": x, "y": y})
|
||||
}
|
||||
Call::Tooltip(lines) => {
|
||||
json!({"t": "tooltip", "lines": lines.iter().map(|l| runs(l)).collect::<Vec<_>>()})
|
||||
}
|
||||
Call::ItemTooltip { stack, more } => {
|
||||
json!({"t": "item_tooltip", "id": &*stack.item, "more": more})
|
||||
}
|
||||
Call::Stratum => json!({"t": "stratum"}),
|
||||
};
|
||||
o["m"] = json!(m);
|
||||
Some(o)
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(out, "{}", json!({ "draws": draws }));
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -725,6 +725,55 @@ impl PotWobble {
|
||||
}
|
||||
}
|
||||
|
||||
/// `TheEndGatewayBlockEntity` fields the beam reads.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct EndGateway {
|
||||
pub age: i64,
|
||||
pub teleport_cooldown: i32,
|
||||
}
|
||||
impl EndGateway {
|
||||
/// `beamAnimationTick` (the client ticker).
|
||||
pub fn tick(&mut self) {
|
||||
self.age = self.age.wrapping_add(1);
|
||||
if self.teleport_cooldown > 0 {
|
||||
self.teleport_cooldown -= 1;
|
||||
}
|
||||
}
|
||||
/// `portalTick` on the server copy: whether it called `triggerCooldown`,
|
||||
/// whose block event 1 reaches the client copy.
|
||||
pub fn portal_tick(&mut self) -> bool {
|
||||
let cooling = self.teleport_cooldown > 0;
|
||||
self.age = self.age.wrapping_add(1);
|
||||
if cooling {
|
||||
self.teleport_cooldown -= 1;
|
||||
false
|
||||
} else if self.age % 2400 == 0 {
|
||||
self.teleport_cooldown = 40;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// `EndGatewayBlock.entityInside` on the server copy: an entity that can
|
||||
/// use the portal starts the cooldown unless it is already running.
|
||||
pub fn enter(&mut self) -> bool {
|
||||
if self.teleport_cooldown > 0 {
|
||||
return false;
|
||||
}
|
||||
self.teleport_cooldown = 40;
|
||||
true
|
||||
}
|
||||
/// `triggerEvent`: event 1 starts the 40 tick cooldown.
|
||||
pub fn trigger_event(&mut self, event: i32, _data: i32) -> bool {
|
||||
if event == 1 {
|
||||
self.teleport_cooldown = 40;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
@@ -746,6 +795,8 @@ pub enum Ticker {
|
||||
powered: bool,
|
||||
},
|
||||
Pot,
|
||||
/// `TheEndGatewayBlockEntity.beamAnimationTick`.
|
||||
Gateway,
|
||||
}
|
||||
|
||||
/// The [`Ticker`] of a block state, by block name and property lookup.
|
||||
@@ -764,6 +815,7 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option<String>) -> Option<Ticke
|
||||
"bell" => Ticker::Bell,
|
||||
"conduit" => Ticker::Conduit,
|
||||
"decorated_pot" => Ticker::Pot,
|
||||
"end_gateway" => Ticker::Gateway,
|
||||
"dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull {
|
||||
powered: prop("powered").as_deref() == Some("true"),
|
||||
},
|
||||
@@ -789,6 +841,9 @@ pub struct BlockEntityAnims {
|
||||
pub conduits: HashMap<[i32; 3], Conduit>,
|
||||
pub skulls: HashMap<[i32; 3], Skull>,
|
||||
pub pots: HashMap<[i32; 3], PotWobble>,
|
||||
pub gateways: HashMap<[i32; 3], EndGateway>,
|
||||
/// The integrated server's copies of the gateways (`portalTick`).
|
||||
pub gateway_servers: HashMap<[i32; 3], EndGateway>,
|
||||
/// The client level's random (conduit particles).
|
||||
pub random: LegacyRandom,
|
||||
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
|
||||
@@ -805,6 +860,8 @@ impl Default for BlockEntityAnims {
|
||||
conduits: HashMap::new(),
|
||||
skulls: HashMap::new(),
|
||||
pots: HashMap::new(),
|
||||
gateways: HashMap::new(),
|
||||
gateway_servers: HashMap::new(),
|
||||
random: LegacyRandom::new(0x6c6576656c),
|
||||
kinds: Vec::new(),
|
||||
}
|
||||
@@ -839,6 +896,8 @@ impl BlockEntityAnims {
|
||||
self.skulls
|
||||
.retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. })));
|
||||
self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot));
|
||||
self.gateways
|
||||
.retain(|p, _| is(p, |t| *t == Ticker::Gateway));
|
||||
}
|
||||
/// Drops the state of positions whose block entity is gone.
|
||||
pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) {
|
||||
@@ -849,6 +908,8 @@ impl BlockEntityAnims {
|
||||
self.conduits.retain(|p, _| keep(*p));
|
||||
self.skulls.retain(|p, _| keep(*p));
|
||||
self.pots.retain(|p, _| keep(*p));
|
||||
self.gateways.retain(|p, _| keep(*p));
|
||||
self.gateway_servers.retain(|p, _| keep(*p));
|
||||
}
|
||||
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
|
||||
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
|
||||
@@ -867,9 +928,11 @@ impl BlockEntityAnims {
|
||||
) -> 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),
|
||||
// Gateways not ticked yet render settled (no beam).
|
||||
gateway: self
|
||||
.gateways
|
||||
.get(&pos)
|
||||
.map_or((i64::MAX, 0), |g| (g.age, g.teleport_cooldown)),
|
||||
..BlockAnim::default()
|
||||
};
|
||||
if let Some(b) = self.books.get(&pos) {
|
||||
|
||||
@@ -1292,44 +1292,24 @@ impl BlockEntityRenderer {
|
||||
}
|
||||
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,
|
||||
);
|
||||
}
|
||||
let b = gateway_beam(anim.gateway, scene.partial, scene.max_y, scene.game_time);
|
||||
if b.height > 0
|
||||
&& let Some(s) = sprite("entity/end_portal/end_gateway_beam")
|
||||
{
|
||||
beam(
|
||||
base,
|
||||
BeamShape {
|
||||
scale: b.scale,
|
||||
time: b.animation_time,
|
||||
start: -b.height,
|
||||
height: b.height * 2,
|
||||
color: b.color,
|
||||
solid_radius: 0.15,
|
||||
glow_radius: 0.175,
|
||||
},
|
||||
s,
|
||||
out,
|
||||
);
|
||||
}
|
||||
// AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace.
|
||||
let faces: Vec<Direction> = Direction::ALL
|
||||
@@ -1618,6 +1598,43 @@ impl BeamPart {
|
||||
}
|
||||
}
|
||||
|
||||
/// `EndGatewayRenderState`'s beam fields (zero when there is no beam).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct GatewayBeam {
|
||||
pub height: i32,
|
||||
pub scale: f32,
|
||||
pub color: u32,
|
||||
pub animation_time: f32,
|
||||
}
|
||||
|
||||
/// `TheEndGatewayRenderer.extractRenderState` from the block entity's age and
|
||||
/// teleport cooldown, at `partial`, for a level whose top is `max_y`.
|
||||
pub fn gateway_beam(
|
||||
(age, cooldown): (i64, i32),
|
||||
partial: f32,
|
||||
max_y: i32,
|
||||
game_time: i64,
|
||||
) -> GatewayBeam {
|
||||
let spawning = age < 200;
|
||||
if !spawning && cooldown <= 0 {
|
||||
return GatewayBeam::default();
|
||||
}
|
||||
let percent = if spawning {
|
||||
((age as f32 + partial) / 200.0).clamp(0.0, 1.0)
|
||||
} else {
|
||||
1.0 - ((cooldown as f32 - partial) / 40.0).clamp(0.0, 1.0)
|
||||
};
|
||||
let distance = if spawning { f64::from(max_y) } else { 50.0 };
|
||||
let scale = trig::sin(f64::from(percent * PI));
|
||||
GatewayBeam {
|
||||
height: (f64::from(scale) * distance).floor() as i32,
|
||||
scale,
|
||||
// DyeColor.MAGENTA / PURPLE getTextureDiffuseColor.
|
||||
color: if spawning { 0xFFC7_4EBD } else { 0xFF89_32B8 },
|
||||
animation_time: game_time.rem_euclid(40) as f32 + partial,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
@@ -24,17 +24,26 @@ const FIREWORK_COLORS: [u32; 16] = [
|
||||
11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019,
|
||||
];
|
||||
|
||||
/// A set of accepted items (expanded from an item, list or tag).
|
||||
/// A set of accepted items (expanded from an item, list or tag), and the
|
||||
/// items in its `HolderSet` order (`Ingredient.display`'s `TagSlotDisplay`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Ingredient(pub HashSet<String>);
|
||||
pub struct Ingredient(pub HashSet<String>, pub Vec<String>);
|
||||
impl Ingredient {
|
||||
/// The items of a list, in order.
|
||||
pub fn of(items: Vec<String>) -> Self {
|
||||
Self(items.iter().cloned().collect(), items)
|
||||
}
|
||||
fn parse(v: &Value, items: &Items) -> Option<Self> {
|
||||
let mut set = HashSet::new();
|
||||
let mut list: Vec<String> = Vec::new();
|
||||
let mut add = |s: &str| {
|
||||
if let Some(tag) = s.strip_prefix('#') {
|
||||
set.extend(items.item_tags.get(tag).into_iter().flatten().cloned());
|
||||
} else {
|
||||
set.insert(s.to_owned());
|
||||
let more: Vec<String> = match s.strip_prefix('#') {
|
||||
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
|
||||
None => vec![s.to_owned()],
|
||||
};
|
||||
for i in more {
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
};
|
||||
match v {
|
||||
@@ -50,7 +59,7 @@ impl Ingredient {
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
(!set.is_empty()).then_some(Self(set))
|
||||
(!list.is_empty()).then(|| Self::of(list))
|
||||
}
|
||||
pub fn test(&self, stack: &ItemStack) -> bool {
|
||||
self.0.contains(&*stack.item)
|
||||
@@ -1525,7 +1534,7 @@ mod tests {
|
||||
use crate::banner::BannerLayer;
|
||||
|
||||
fn ingredient(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn patterned(item: &str) -> ItemStack {
|
||||
let mut s = ItemStack::new(item, 1);
|
||||
|
||||
@@ -2930,6 +2930,10 @@ 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);
|
||||
self.draw_item_decorations(batch, stack, x, y);
|
||||
}
|
||||
/// `GuiGraphicsExtractor.itemDecorations`: the count and damage bar.
|
||||
fn draw_item_decorations(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
|
||||
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
||||
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
|
||||
let max_damage = self
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
//! [`Game::block_anim`] and [`Game::chest_lid`].
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
|
||||
block_entity_render::BlockAnim,
|
||||
collisions::{SceneCollisions, no_collision_empty},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
save::number,
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use std::collections::HashMap;
|
||||
@@ -44,6 +45,14 @@ impl Game<'_> {
|
||||
.or_default()
|
||||
.trigger_event(a, b, time, || gathered);
|
||||
}
|
||||
Some(Ticker::Gateway) => {
|
||||
let initial = self.gateway_loaded(pos);
|
||||
self.be_anims
|
||||
.gateways
|
||||
.entry(pos)
|
||||
.or_insert(initial)
|
||||
.trigger_event(a, b);
|
||||
}
|
||||
Some(Ticker::Pot) => {
|
||||
self.be_anims
|
||||
.pots
|
||||
@@ -276,9 +285,58 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Ticker::Pot => {}
|
||||
Ticker::Gateway => {
|
||||
// The server copy's portalTick runs first; its block event
|
||||
// reaches the client copy before the client ticks it.
|
||||
let initial = self.gateway_loaded(pos);
|
||||
let anims = &mut self.be_anims;
|
||||
let server = anims.gateway_servers.entry(pos).or_insert(initial);
|
||||
let triggered = server.portal_tick();
|
||||
let client = anims.gateways.entry(pos).or_insert(initial);
|
||||
if triggered {
|
||||
client.trigger_event(1, 0);
|
||||
}
|
||||
client.tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
|
||||
/// `pos` let the entity in (`triggerCooldown`, with its block event).
|
||||
pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool {
|
||||
let initial = self.gateway_loaded(pos);
|
||||
let entered = self
|
||||
.be_anims
|
||||
.gateway_servers
|
||||
.entry(pos)
|
||||
.or_insert(initial)
|
||||
.enter();
|
||||
if entered {
|
||||
self.block_entity_event(pos, 1, 0);
|
||||
}
|
||||
entered
|
||||
}
|
||||
/// The End gateway at `pos` as its chunk was loaded: `Age` from the saved
|
||||
/// block entity (`getUpdateTag`), or a new gateway.
|
||||
fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway {
|
||||
let age = self
|
||||
.world
|
||||
.chunks
|
||||
.get(&(pos[0] >> 4, pos[2] >> 4))
|
||||
.and_then(|c| c.saved.as_deref())
|
||||
.and_then(|saved| {
|
||||
saved.block_entities.iter().find(|t| {
|
||||
[t.get("x"), t.get("y"), t.get("z")]
|
||||
.map(number)
|
||||
.eq(&pos.map(|v| Some(i64::from(v))))
|
||||
})
|
||||
})
|
||||
.and_then(|t| number(t.get("Age")));
|
||||
EndGateway {
|
||||
age: age.unwrap_or(0),
|
||||
teleport_cooldown: 0,
|
||||
}
|
||||
}
|
||||
/// 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
|
||||
|
||||
@@ -405,6 +405,7 @@ impl Game<'_> {
|
||||
}
|
||||
} else if let Some(g) = gateway
|
||||
&& self.end.gateway_cooldown == 0
|
||||
&& self.gateway_enter(g)
|
||||
{
|
||||
self.enter_gateway(g)?;
|
||||
}
|
||||
|
||||
@@ -44,24 +44,6 @@ const BUTTON: f32 = 14.0;
|
||||
fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool {
|
||||
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
|
||||
}
|
||||
/// A sub-rectangle of a sprite given in texels.
|
||||
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
|
||||
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
|
||||
Rect {
|
||||
u0: r.u0 + x * du,
|
||||
v0: r.v0 + y * dv,
|
||||
u1: r.u0 + (x + w) * du,
|
||||
v1: r.v0 + (y + h) * dv,
|
||||
w: w as u32,
|
||||
h: h as u32,
|
||||
}
|
||||
}
|
||||
/// A dye's tint as a HUD vertex colour.
|
||||
pub(super) fn dye_color(name: &str) -> u32 {
|
||||
let c = banner::dye_rgb(name);
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `LoomScreen.containerChanged`: the error flag, whether the pattern
|
||||
/// buttons show (only when an input changed), and the scroller reset.
|
||||
@@ -182,30 +164,30 @@ impl Game<'_> {
|
||||
l.start_row = l.row_for(l.scroll);
|
||||
}
|
||||
}
|
||||
/// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1))
|
||||
/// drawn flat: the cloth, the base colour and every layer.
|
||||
pub(super) fn draw_flag(
|
||||
/// `GuiGraphicsExtractor.bannerPattern`: the banner flag model with its
|
||||
/// layers in a 20x40 picture in picture at `(x, y)`.
|
||||
fn draw_banner_result(
|
||||
&self,
|
||||
batch: &mut HudBatch,
|
||||
rect: [f32; 4],
|
||||
x: f32,
|
||||
y: f32,
|
||||
base: &str,
|
||||
layers: &[BannerLayer],
|
||||
) {
|
||||
let banners = &self.res.stations.banners;
|
||||
let mut paint = |name: &str, color: u32| {
|
||||
if let Some(r) = self.res.atlas.sprites.get(name).copied() {
|
||||
let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]);
|
||||
batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color);
|
||||
}
|
||||
};
|
||||
paint("entity/banner/banner_base", u32::MAX);
|
||||
paint("entity/banner/base", dye_color(base));
|
||||
for layer in layers.iter().take(16) {
|
||||
paint(
|
||||
&banners.banner_texture(&layer.pattern),
|
||||
dye_color(&layer.color),
|
||||
);
|
||||
}
|
||||
let layers: Vec<(String, String)> = layers
|
||||
.iter()
|
||||
.map(|l| (banners.banner_texture(&l.pattern), l.color.to_string()))
|
||||
.collect();
|
||||
horizon_client::item_render::gui::draw_banner_result(
|
||||
&self.res.item_renderer,
|
||||
&self.res.atlas.sprites,
|
||||
batch,
|
||||
x,
|
||||
y,
|
||||
base,
|
||||
&layers,
|
||||
);
|
||||
}
|
||||
/// Paints `screen_layout` calls at the menu origin (ox, oy): the container
|
||||
/// background and the dimmed world are drawn by the caller.
|
||||
@@ -256,19 +238,8 @@ impl Game<'_> {
|
||||
layers,
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
} => self.draw_flag(
|
||||
batch,
|
||||
[
|
||||
ox + *x0 as f32,
|
||||
oy + *y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
],
|
||||
base,
|
||||
layers,
|
||||
),
|
||||
..
|
||||
} => self.draw_banner_result(batch, ox + *x0 as f32, oy + *y0 as f32, base, layers),
|
||||
ScreenDraw::Tooltip { key } => {
|
||||
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
|
||||
}
|
||||
|
||||
@@ -95,6 +95,16 @@ impl Game<'_> {
|
||||
extras.fluid_ticks.clear();
|
||||
}
|
||||
extras.last_update = time;
|
||||
// TheEndGatewayBlockEntity saves its Age (the server copy's).
|
||||
for tag in &mut extras.block_entities {
|
||||
let pos = [tag.get("x"), tag.get("y"), tag.get("z")]
|
||||
.map(|v| horizon_client::save::number(v).unwrap_or(0) as i32);
|
||||
if let Some(g) = self.be_anims.gateway_servers.get(&pos)
|
||||
&& let Some(age) = tag.get_mut("Age")
|
||||
{
|
||||
*age = horizon_world::nbt::Tag::Long(g.age);
|
||||
}
|
||||
}
|
||||
if let Some(t) = self.world.inhabited.get(&(chunk.x, chunk.z)) {
|
||||
extras
|
||||
.root
|
||||
|
||||
@@ -11,6 +11,11 @@ use horizon_client::{
|
||||
items::ItemStack,
|
||||
menu::place::{PostPlace, Stacked},
|
||||
recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab},
|
||||
recipe_book_screen::{
|
||||
self as screen, ButtonView, Call, Drawn, GhostView, ItemCall, OverlayRecipe, OverlayView,
|
||||
Screen as Layout, Search, TabView,
|
||||
},
|
||||
text::{Style, Text},
|
||||
ui::EditBox,
|
||||
};
|
||||
use std::{
|
||||
@@ -444,9 +449,12 @@ impl Game<'_> {
|
||||
|
||||
// ---- geometry ----
|
||||
|
||||
/// `RecipeBookComponent.getXOrigin` / `getYOrigin` (`widthTooNarrow`
|
||||
/// centres the book over the menu).
|
||||
fn book_origin(&self, batch: &HudBatch) -> (f32, f32) {
|
||||
let offset = if batch.width < NARROW { 0.0 } else { 86.0 };
|
||||
(
|
||||
((batch.width - WIDTH) / 2.0).floor() - 86.0,
|
||||
((batch.width - WIDTH) / 2.0).floor() - offset,
|
||||
((batch.height - HEIGHT) / 2.0).floor(),
|
||||
)
|
||||
}
|
||||
@@ -623,25 +631,9 @@ impl Game<'_> {
|
||||
let mut entries: Vec<(usize, bool)> =
|
||||
button.entries.iter().copied().filter(|e| e.1).collect();
|
||||
entries.extend(button.entries.iter().copied().filter(|e| !e.1));
|
||||
let total = entries.len();
|
||||
let maxrow = if total <= 16 { 4 } else { 5 };
|
||||
let rows = total.div_ceil(maxrow);
|
||||
let (mut x, mut y) = (bx, by);
|
||||
let (center_x, center_y) = (xo + WIDTH / 2.0, yo + 13.0 + HEIGHT / 2.0);
|
||||
let right = x + (total.min(maxrow) * 25) as f32;
|
||||
let max_left = center_x + 50.0;
|
||||
if right > max_left {
|
||||
x -= 25.0 * ((right - max_left) / 25.0).floor();
|
||||
}
|
||||
let bottom = y + rows as f32 * 25.0;
|
||||
let max_bottom = center_y + 50.0;
|
||||
if bottom > max_bottom {
|
||||
y -= 25.0 * ((bottom - max_bottom) / 25.0).ceil();
|
||||
}
|
||||
let max_top = center_y - 100.0;
|
||||
if y < max_top {
|
||||
y -= 25.0 * ((y - max_top) / 25.0).ceil();
|
||||
}
|
||||
let (x, y) =
|
||||
screen::overlay_origin(bx as i32, by as i32, entries.len(), xo as i32, yo as i32);
|
||||
let (x, y) = (x as f32, y as f32);
|
||||
self.recipe_ui.overlay = Some(Overlay { x, y, entries });
|
||||
}
|
||||
|
||||
@@ -821,359 +813,293 @@ impl Game<'_> {
|
||||
use winit::keyboard::KeyCode;
|
||||
self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight)
|
||||
}
|
||||
/// `GhostSlots.extractRenderState`, among the container's slots.
|
||||
fn draw_ghost(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
if self.recipe_ui.ghost.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Ghosts show only while their slots are empty.
|
||||
let (ox, oy) = self.inventory_origin(batch);
|
||||
let step = self.swap_index();
|
||||
let big_result = book_type != BookType::Crafting || self.craft_size == 3;
|
||||
let ghosts: Vec<(usize, ItemStack, bool)> = self
|
||||
let ghosts: Vec<GhostView> = self
|
||||
.recipe_ui
|
||||
.ghost
|
||||
.iter()
|
||||
.filter(|g| !g.items.is_empty())
|
||||
.map(|g| (g.slot, g.items[step % g.items.len()].clone(), g.result))
|
||||
.map(|g| {
|
||||
let (sx, sy) = self.slot_position(g.slot);
|
||||
GhostView {
|
||||
x: sx as i32,
|
||||
y: sy as i32,
|
||||
items: g.items.clone(),
|
||||
result: g.result,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for (slot, stack, result) in ghosts {
|
||||
let (sx, sy) = self.slot_position(slot);
|
||||
let (x, y) = (ox + sx, oy + sy);
|
||||
let atlas = &self.res.atlas;
|
||||
let red = rgba(255, 0, 0, 0x30);
|
||||
if result && big_result {
|
||||
batch.fill(atlas, x - 4.0, y - 4.0, 24.0, 24.0, red);
|
||||
} else {
|
||||
batch.fill(atlas, x, y, 16.0, 16.0, red);
|
||||
}
|
||||
self.draw_item(batch, &stack, x, y);
|
||||
batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 0x30));
|
||||
}
|
||||
let calls = screen::ghost(self.swap_index(), ox as i32, oy as i32, big_result, &ghosts);
|
||||
self.paint_book(batch, &calls);
|
||||
}
|
||||
/// `RecipeBookComponent.extractRenderState` and `extractTooltip`, laid
|
||||
/// out by `horizon_client::recipe_book_screen`.
|
||||
fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
let (xo, yo) = self.book_origin(batch);
|
||||
let cursor = self.cursor;
|
||||
let atlas_name = "gui/recipe_book";
|
||||
// Background: the 147x166 page at (1, 1) of the texture.
|
||||
if let Some(r) = self.res.atlas.sprites.get(atlas_name).copied() {
|
||||
batch.rect_uv(
|
||||
xo,
|
||||
yo,
|
||||
WIDTH,
|
||||
HEIGHT,
|
||||
sub_rect(r, [1.0, 1.0, WIDTH, HEIGHT]),
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
// Search box.
|
||||
if let Some(search) = self.recipe_ui.search.as_mut() {
|
||||
search.x = xo + 25.0;
|
||||
search.y = yo + 13.0;
|
||||
search.draw(batch, &self.res.atlas, None);
|
||||
if search.value.is_empty() && !search.focused {
|
||||
let hint = self
|
||||
.res
|
||||
.stations
|
||||
.enchantments
|
||||
.translate("gui.recipebook.search_hint")
|
||||
.unwrap_or("Search...")
|
||||
.to_owned();
|
||||
batch.text(
|
||||
&self.res.atlas,
|
||||
&hint,
|
||||
search.text_x(),
|
||||
search.text_y(),
|
||||
rgba(170, 170, 170, 255),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Tabs.
|
||||
let tabs = self.recipe_ui.view.tabs.clone();
|
||||
let current = self
|
||||
.recipe_ui
|
||||
.tab
|
||||
.filter(|t| tabs.contains(t))
|
||||
.unwrap_or(Tab::Search);
|
||||
let frame = self.frame_ticks;
|
||||
for (n, tab) in tabs.iter().enumerate() {
|
||||
let (x, y) = self.tab_pos(xo, yo, n);
|
||||
let selected = *tab == current;
|
||||
let name = if selected { "tab_selected" } else { "tab" };
|
||||
let sx = if selected { x - 2.0 } else { x };
|
||||
let start = batch.vertices.len();
|
||||
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
|
||||
let (a, b) = tab.icons();
|
||||
let shift = if selected { -2.0 } else { 0.0 };
|
||||
match b {
|
||||
Some(b) => {
|
||||
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
|
||||
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
|
||||
let atlas = &self.res.atlas;
|
||||
let search = match self.recipe_ui.search.as_mut() {
|
||||
Some(edit) => {
|
||||
// The box's place, for clicks and typing.
|
||||
edit.x = xo + 25.0;
|
||||
edit.y = yo + 13.0;
|
||||
let (display, blink_ms) = edit.view_state(atlas);
|
||||
Search {
|
||||
value: edit.value.clone(),
|
||||
cursor: edit.cursor,
|
||||
highlight: edit.highlight,
|
||||
display,
|
||||
focused: edit.focused,
|
||||
blink_ms,
|
||||
}
|
||||
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
|
||||
}
|
||||
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
|
||||
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
|
||||
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
|
||||
entry.1 -= frame;
|
||||
None => Search::default(),
|
||||
};
|
||||
let ui = &self.recipe_ui;
|
||||
let current = ui
|
||||
.tab
|
||||
.filter(|t| ui.view.tabs.contains(t))
|
||||
.unwrap_or(Tab::Search);
|
||||
let tabs: Vec<TabView> = ui
|
||||
.view
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|tab| {
|
||||
let (a, b) = tab.icons();
|
||||
TabView {
|
||||
icons: (a.to_owned(), b.map(str::to_owned)),
|
||||
selected: *tab == current,
|
||||
anim: ui
|
||||
.tab_anim
|
||||
.iter()
|
||||
.find(|e| e.0 == *tab)
|
||||
.map_or(0.0, |e| e.1),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let pages = ui.view.buttons.len().div_ceil(20);
|
||||
let first = ui.page * 20;
|
||||
let (buttons, overlay) = match ui.book.as_ref() {
|
||||
Some(book) => {
|
||||
let buttons: Vec<ButtonView> = ui
|
||||
.view
|
||||
.buttons
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(first)
|
||||
.take(20)
|
||||
.map(|(n, b)| ButtonView {
|
||||
has_craftable: b.craftable(),
|
||||
entries: b
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| vec![book.entries[e.0].result.clone()])
|
||||
.collect(),
|
||||
anim: ui
|
||||
.button_anim
|
||||
.iter()
|
||||
.find(|e| e.0 == n)
|
||||
.map_or(0.0, |e| e.1),
|
||||
})
|
||||
.collect();
|
||||
let overlay = ui.overlay.as_ref().map(|o| OverlayView {
|
||||
x: o.x as i32,
|
||||
y: o.y as i32,
|
||||
recipes: o
|
||||
.entries
|
||||
.iter()
|
||||
.map(|&(i, craftable)| OverlayRecipe {
|
||||
craftable,
|
||||
cells: screen::overlay_cells(book, &book.entries[i]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
(buttons, overlay)
|
||||
}
|
||||
None => (Vec::new(), None),
|
||||
};
|
||||
let translate = |key: &str| self.translate(key, key);
|
||||
let text_width = |s: &str| HudBatch::text_width(atlas, s) as i32;
|
||||
let layout = Layout {
|
||||
book: book_type,
|
||||
width: batch.width as i32,
|
||||
height: batch.height as i32,
|
||||
narrow: batch.width < NARROW,
|
||||
mouse: (cursor.0.floor() as i32, cursor.1.floor() as i32),
|
||||
index: self.swap_index(),
|
||||
filtering: self.book_filtering(book_type),
|
||||
search: &search,
|
||||
tabs: &tabs,
|
||||
buttons: &buttons,
|
||||
page: ui.page,
|
||||
pages,
|
||||
overlay: overlay.as_ref(),
|
||||
ghost: None,
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
};
|
||||
let calls = screen::draw(&layout);
|
||||
let tooltip = self.paint_book(batch, &calls);
|
||||
// The squeeze animations run down with the frames.
|
||||
let frame = self.frame_ticks;
|
||||
for e in &mut self.recipe_ui.tab_anim {
|
||||
e.1 -= frame;
|
||||
}
|
||||
for e in &mut self.recipe_ui.button_anim {
|
||||
e.1 -= frame;
|
||||
}
|
||||
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
|
||||
// Craftable filter.
|
||||
let filtering = self.book_filtering(book_type);
|
||||
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
|
||||
let prefix = if book_type == BookType::Crafting {
|
||||
""
|
||||
} else {
|
||||
"furnace_"
|
||||
};
|
||||
let state = if filtering {
|
||||
"filter_enabled"
|
||||
} else {
|
||||
"filter_disabled"
|
||||
};
|
||||
let name = format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" });
|
||||
batch.sprite(&self.res.atlas, &sprite(&name), xo + 110.0, yo + 12.0);
|
||||
// Recipe buttons.
|
||||
let buttons = self.recipe_ui.view.buttons.clone();
|
||||
let pages = buttons.len().div_ceil(20);
|
||||
let step = self.swap_index();
|
||||
let first = self.recipe_ui.page * 20;
|
||||
let mut tooltip: Option<Vec<(String, u32)>> = None;
|
||||
let overlay_open = self.recipe_ui.overlay.is_some();
|
||||
for n in 0..20 {
|
||||
let Some(button) = buttons.get(first + n) else {
|
||||
break;
|
||||
};
|
||||
let (x, y) = Self::button_pos(xo, yo, n);
|
||||
let anim_start = batch.vertices.len();
|
||||
let many = button.entries.len() > 1;
|
||||
let name = match (button.craftable(), many) {
|
||||
(true, true) => "slot_many_craftable",
|
||||
(true, false) => "slot_craftable",
|
||||
(false, true) => "slot_many_uncraftable",
|
||||
(false, false) => "slot_uncraftable",
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), x, y);
|
||||
let shown = button.entries[step % button.entries.len()].0;
|
||||
let Some(stack) = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map(|b| ItemStack::new(&b.entries[shown].result.item, 1))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let same_result = button.entries.iter().all(|e| {
|
||||
self.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.is_some_and(|b| b.entries[e.0].result.item == b.entries[shown].result.item)
|
||||
});
|
||||
let mut offset = 4.0;
|
||||
if many && same_result {
|
||||
self.draw_item_plain(batch, &stack, x + offset + 1.0, y + offset + 1.0);
|
||||
offset -= 1.0;
|
||||
}
|
||||
self.draw_item_plain(batch, &stack, x + offset, y + offset);
|
||||
if let Some(entry) = self
|
||||
.recipe_ui
|
||||
.button_anim
|
||||
.iter_mut()
|
||||
.find(|e| e.0 == first + n)
|
||||
{
|
||||
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
|
||||
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
|
||||
entry.1 -= self.frame_ticks;
|
||||
}
|
||||
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
|
||||
let mut lines = self.stack_tooltip(&stack);
|
||||
if many {
|
||||
lines.push((
|
||||
self.translate("gui.recipebook.moreRecipes", "Right Click for More"),
|
||||
u32::MAX,
|
||||
));
|
||||
}
|
||||
tooltip = Some(lines);
|
||||
}
|
||||
}
|
||||
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
|
||||
// Page arrows and number.
|
||||
if pages > 1 {
|
||||
let page_text = self
|
||||
.translate("gui.recipebook.page", "%s/%s")
|
||||
.replacen("%s", &(self.recipe_ui.page + 1).to_string(), 1)
|
||||
.replacen("%s", &pages.to_string(), 1);
|
||||
let w = HudBatch::text_width(&self.res.atlas, &page_text);
|
||||
batch.text(
|
||||
&self.res.atlas,
|
||||
&page_text,
|
||||
xo - (w / 2.0).floor() + 73.0,
|
||||
yo + 141.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
if self.recipe_ui.page + 1 < pages {
|
||||
let hover = inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0);
|
||||
let name = if hover {
|
||||
"page_forward_highlighted"
|
||||
} else {
|
||||
"page_forward"
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), xo + 93.0, yo + 137.0);
|
||||
if hover {
|
||||
tooltip = Some(vec![(
|
||||
self.translate("gui.recipebook.next_page", "Next Page"),
|
||||
u32::MAX,
|
||||
)]);
|
||||
}
|
||||
}
|
||||
if self.recipe_ui.page > 0 {
|
||||
let hover = inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0);
|
||||
let name = if hover {
|
||||
"page_backward_highlighted"
|
||||
} else {
|
||||
"page_backward"
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), xo + 38.0, yo + 137.0);
|
||||
if hover {
|
||||
tooltip = Some(vec![(
|
||||
self.translate("gui.recipebook.previous_page", "Previous Page"),
|
||||
u32::MAX,
|
||||
)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) {
|
||||
let key = if !filtering {
|
||||
"gui.recipebook.toggleRecipes.all"
|
||||
} else {
|
||||
match book_type {
|
||||
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
|
||||
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
|
||||
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
|
||||
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
|
||||
}
|
||||
};
|
||||
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
|
||||
}
|
||||
self.draw_overlay(batch, book_type);
|
||||
if let Some(lines) = tooltip {
|
||||
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
|
||||
}
|
||||
}
|
||||
/// An item without count or bars (`GuiGraphics.fakeItem`).
|
||||
fn draw_item_plain(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
damage: 0,
|
||||
..stack.clone()
|
||||
};
|
||||
self.draw_item(batch, &one, x, y);
|
||||
}
|
||||
fn draw_overlay(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
let Some(overlay) = self.recipe_ui.overlay.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (ox, oy, entries) = (overlay.x, overlay.y, overlay.entries.clone());
|
||||
let maxrow = if entries.len() <= 16 { 4 } else { 5 };
|
||||
let width = entries.len().min(maxrow) as f32 * 25.0 + 8.0;
|
||||
let height = entries.len().div_ceil(maxrow) as f32 * 25.0 + 8.0;
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
&sprite("overlay_recipe"),
|
||||
ox,
|
||||
oy,
|
||||
width,
|
||||
height,
|
||||
u32::MAX,
|
||||
);
|
||||
let cursor = self.cursor;
|
||||
let step = self.swap_index();
|
||||
let (gw, gh) = if book_type == BookType::Crafting {
|
||||
(3, 3)
|
||||
} else {
|
||||
(1, 1)
|
||||
};
|
||||
for (n, (index, craftable)) in entries.into_iter().enumerate() {
|
||||
let x = ox + 4.0 + 25.0 * (n % maxrow) as f32;
|
||||
let y = oy + 5.0 + 25.0 * (n / maxrow) as f32;
|
||||
let hover = inside(cursor, x, y, 24.0, 24.0);
|
||||
let family = if book_type == BookType::Crafting {
|
||||
"crafting"
|
||||
} else {
|
||||
"furnace"
|
||||
};
|
||||
let state = if craftable { "" } else { "_disabled" };
|
||||
let name = format!(
|
||||
"{family}_overlay{state}{}",
|
||||
if hover { "_highlighted" } else { "" }
|
||||
);
|
||||
batch.sprite(&self.res.atlas, &sprite(&name), x, y);
|
||||
let Some(entry) = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map(|b| b.entries[index].clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// The recipe's layout in miniature, ingredients at 3/8 scale.
|
||||
let mut cells: Vec<(f32, f32, ItemStack)> = Vec::new();
|
||||
if let Some(book) = self.recipe_ui.book.as_ref() {
|
||||
let requirements = entry.requirements();
|
||||
match &entry.display {
|
||||
Display::Furnace(ingredient) => {
|
||||
let items = book.items_of(ingredient);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((3.0 + 7.0, 3.0 + 7.0, ItemStack::new(item, 1)));
|
||||
}
|
||||
}
|
||||
Display::Shaped { .. } => {
|
||||
for (ingredient, grid_index) in entry.grid_cells(gw, gh) {
|
||||
if let Some(i) = ingredient {
|
||||
let items = book.items_of(requirements[i]);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((
|
||||
3.0 + (grid_index % 3) as f32 * 7.0,
|
||||
3.0 + (grid_index / 3) as f32 * 7.0,
|
||||
ItemStack::new(item, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Display::Shapeless(list) => {
|
||||
for (i, ingredient) in list.iter().enumerate() {
|
||||
let items = book.items_of(ingredient);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((
|
||||
3.0 + (i % 3) as f32 * 7.0,
|
||||
3.0 + (i / 3) as f32 * 7.0,
|
||||
ItemStack::new(item, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
/// Paints recipe book calls; returns the first tooltip set (vanilla keeps
|
||||
/// the first one a frame asks for).
|
||||
fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option<Vec<(String, u32)>> {
|
||||
let mut tooltip: Option<Vec<(String, u32)>> = None;
|
||||
for d in calls {
|
||||
let start = batch.vertices.len();
|
||||
let atlas = &self.res.atlas;
|
||||
match &d.call {
|
||||
Call::Blit {
|
||||
x, y, w, h, u, v, ..
|
||||
} => {
|
||||
if let Some(r) = atlas.sprites.get("gui/recipe_book").copied() {
|
||||
let (w, h) = (*w as f32, *h as f32);
|
||||
batch.rect_uv(
|
||||
*x as f32,
|
||||
*y as f32,
|
||||
w,
|
||||
h,
|
||||
sub_rect(r, [*u, *v, w, h]),
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::Sprite { id, x, y, w, h } => {
|
||||
let name = format!("gui/sprites/{id}");
|
||||
let native = atlas
|
||||
.sprites
|
||||
.get(&name)
|
||||
.is_some_and(|r| r.w as i32 == *w && r.h as i32 == *h);
|
||||
if native {
|
||||
batch.sprite(atlas, &name, *x as f32, *y as f32);
|
||||
} else {
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
atlas,
|
||||
&name,
|
||||
*x as f32,
|
||||
*y as f32,
|
||||
*w as f32,
|
||||
*h as f32,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => batch.fill(
|
||||
atlas,
|
||||
*x0 as f32,
|
||||
*y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
argb(*color),
|
||||
),
|
||||
Call::Highlight { x0, y0, x1, y1 } => {
|
||||
let (a, b) = (*x0.min(x1), *x0.max(x1));
|
||||
batch.fill(
|
||||
atlas,
|
||||
a as f32,
|
||||
*y0 as f32,
|
||||
(b - a) as f32,
|
||||
(y1 - y0) as f32,
|
||||
rgba(0, 0, 255, 128),
|
||||
);
|
||||
}
|
||||
Call::Text {
|
||||
runs,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => {
|
||||
let mut x = *x as f32;
|
||||
for r in runs {
|
||||
let style = Style {
|
||||
color: (r.color >= 0).then_some(r.color as u32),
|
||||
italic: r.italic.then_some(true),
|
||||
..Style::default()
|
||||
};
|
||||
let t = Text::styled(r.text.clone(), style);
|
||||
batch.text_styled(atlas, &t, x, *y as f32, argb(*color), *shadow);
|
||||
x += atlas.font.width_text(&t);
|
||||
}
|
||||
}
|
||||
Call::Item { call, stack, x, y } => match call {
|
||||
ItemCall::Item | ItemCall::Fake => {
|
||||
self.draw_item_model(batch, stack, *x as f32, *y as f32)
|
||||
}
|
||||
ItemCall::Decorations => {
|
||||
self.draw_item_decorations(batch, stack, *x as f32, *y as f32)
|
||||
}
|
||||
},
|
||||
Call::Tooltip(lines) => {
|
||||
if tooltip.is_none() {
|
||||
tooltip = Some(
|
||||
lines
|
||||
.iter()
|
||||
.map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::ItemTooltip { stack, more } => {
|
||||
if tooltip.is_none() {
|
||||
let mut lines = self.stack_tooltip(stack);
|
||||
if *more {
|
||||
lines.push((
|
||||
self.translate(
|
||||
"gui.recipebook.moreRecipes",
|
||||
"Right Click for More",
|
||||
),
|
||||
u32::MAX,
|
||||
));
|
||||
}
|
||||
tooltip = Some(lines);
|
||||
}
|
||||
}
|
||||
Call::Stratum => {}
|
||||
}
|
||||
for (cx, cy, stack) in cells {
|
||||
// Draw at the origin, then shrink around the cell centre.
|
||||
let start = batch.vertices.len();
|
||||
self.draw_item_plain(batch, &stack, 0.0, 0.0);
|
||||
let (px, py) = (x + 2.0 + cx, y + 2.0 + cy);
|
||||
if d.pose != screen::IDENTITY {
|
||||
let m = d.pose;
|
||||
for v in &mut batch.vertices[start..] {
|
||||
v.pos = [px + (v.pos[0] - 8.0) * 0.375, py + (v.pos[1] - 8.0) * 0.375];
|
||||
let [x, y] = v.pos;
|
||||
v.pos = [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
|
||||
}
|
||||
}
|
||||
}
|
||||
tooltip
|
||||
}
|
||||
}
|
||||
|
||||
/// An ARGB colour as a HUD vertex colour.
|
||||
fn argb(c: i32) -> u32 {
|
||||
let c = c as u32;
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8)
|
||||
}
|
||||
|
||||
/// A sub-rectangle of a sprite given in texels.
|
||||
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
|
||||
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
|
||||
|
||||
@@ -89,7 +89,7 @@ fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec<Point> {
|
||||
}
|
||||
|
||||
/// RGBA vertex colour of a lit quad: `minecraft_mix_light` on the tint.
|
||||
fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 {
|
||||
pub fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 {
|
||||
let light = crate::block_entity_render::diffuse(q.normal, lights);
|
||||
let [a, r, g, b] = q.color.to_be_bytes();
|
||||
let c = |v: u8| (f32::from(v) * light) as u8;
|
||||
@@ -155,6 +155,28 @@ pub fn draw(
|
||||
} else {
|
||||
items_flat_lights()
|
||||
};
|
||||
let rect = if state.oversized_in_gui {
|
||||
[
|
||||
f32::NEG_INFINITY,
|
||||
f32::NEG_INFINITY,
|
||||
f32::INFINITY,
|
||||
f32::INFINITY,
|
||||
]
|
||||
} else {
|
||||
[x, y, x + 16.0, y + 16.0]
|
||||
};
|
||||
draw_quads(&quads, lights, batch, rect, time);
|
||||
}
|
||||
|
||||
/// Lights, culls, sorts far to near and clips `quads` (GUI positions) to
|
||||
/// `rect`.
|
||||
fn draw_quads(
|
||||
quads: &[ItemQuad],
|
||||
lights: (Vec3, Vec3),
|
||||
batch: &mut HudBatch,
|
||||
rect: [f32; 4],
|
||||
time: f32,
|
||||
) {
|
||||
// Back-face culling: front faces wind counter-clockwise on screen with y up.
|
||||
let mut visible: Vec<(f32, usize)> = quads
|
||||
.iter()
|
||||
@@ -173,16 +195,6 @@ pub fn draw(
|
||||
.collect();
|
||||
// Far to near; the depth buffer of the item atlas, approximated per quad.
|
||||
visible.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let rect = if state.oversized_in_gui {
|
||||
[
|
||||
f32::NEG_INFINITY,
|
||||
f32::NEG_INFINITY,
|
||||
f32::INFINITY,
|
||||
f32::INFINITY,
|
||||
]
|
||||
} else {
|
||||
[x, y, x + 16.0, y + 16.0]
|
||||
};
|
||||
for (_, i) in visible {
|
||||
let q = &quads[i];
|
||||
let points: [Point; 4] = std::array::from_fn(|k| Point {
|
||||
@@ -206,6 +218,65 @@ pub fn draw(
|
||||
}
|
||||
}
|
||||
|
||||
/// `PictureInPictureRenderer.prepare` for the loom's 20x40 result rectangle
|
||||
/// at `(x0, y0)` (`translate(w / 2, h)`, `scale(16, 16, -16)`, one texel per
|
||||
/// GUI pixel), then `GuiBannerResultRenderer.renderToTexture`'s
|
||||
/// `translate(0, 0.25, 0)`.
|
||||
pub fn banner_result_pose(x0: f32, y0: f32) -> Mat4 {
|
||||
Mat4::from_translation(Vec3::new(x0 + 10.0, y0 + 40.0, 0.0))
|
||||
* Mat4::from_scale(Vec3::new(16.0, 16.0, -16.0))
|
||||
* Mat4::from_translation(Vec3::new(0.0, 0.25, 0.0))
|
||||
}
|
||||
|
||||
/// The quads of `GuiGraphicsExtractor.bannerPattern` (the loom's result
|
||||
/// preview) at `(x0, y0)`: base dye and `(texture, dye)` layers.
|
||||
pub fn banner_result_quads(
|
||||
renderer: &ItemRenderer,
|
||||
sprites: &HashMap<String, Rect>,
|
||||
x0: f32,
|
||||
y0: f32,
|
||||
base: &str,
|
||||
layers: &[(String, String)],
|
||||
) -> Vec<ItemQuad> {
|
||||
let mut quads = Vec::new();
|
||||
super::special::submit_banner_result(
|
||||
renderer,
|
||||
banner_result_pose(x0, y0),
|
||||
base,
|
||||
layers,
|
||||
sprites,
|
||||
&mut quads,
|
||||
);
|
||||
// The winding normal flips with the pose's mirrored axis; PoseStack's
|
||||
// normal matrix only takes the scale's signs, so the lit normal is the
|
||||
// opposite one.
|
||||
for q in &mut quads {
|
||||
q.normal = -q.normal;
|
||||
}
|
||||
quads
|
||||
}
|
||||
|
||||
/// Draws the loom's result preview: the picture in picture is lit with
|
||||
/// `Lighting.Entry.ITEMS_FLAT` and holds only its 20x40 rectangle.
|
||||
pub fn draw_banner_result(
|
||||
renderer: &ItemRenderer,
|
||||
sprites: &HashMap<String, Rect>,
|
||||
batch: &mut HudBatch,
|
||||
x0: f32,
|
||||
y0: f32,
|
||||
base: &str,
|
||||
layers: &[(String, String)],
|
||||
) {
|
||||
let quads = banner_result_quads(renderer, sprites, x0, y0, base, layers);
|
||||
draw_quads(
|
||||
&quads,
|
||||
items_flat_lights(),
|
||||
batch,
|
||||
[x0, y0, x0 + 20.0, y0 + 40.0],
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -379,6 +379,33 @@ fn pot_sides(v: &Value) -> [Option<String>; 4] {
|
||||
}
|
||||
}
|
||||
|
||||
/// `GuiBannerResultRenderer.renderToTexture` under `pose`: the standing
|
||||
/// banner flag (`BannerFlagModel.setupAnim(0)`) in the banner base texture,
|
||||
/// then `BannerRenderer.submitPatterns` (the base colour and up to 16 layers
|
||||
/// of `(texture, dye)`).
|
||||
pub(super) fn submit_banner_result(
|
||||
renderer: &ItemRenderer,
|
||||
pose: Mat4,
|
||||
base: &str,
|
||||
layers: &[(String, String)],
|
||||
sprites: &HashMap<String, Rect>,
|
||||
sink: &mut dyn ItemSink,
|
||||
) {
|
||||
let Some(flag) = renderer.part("standing_banner_flag") else {
|
||||
return;
|
||||
};
|
||||
let mut part = |texture: &str, color: u32| {
|
||||
if let Some(r) = sprites.get(texture).copied() {
|
||||
draw(flag, "root", pose, &flag_pose, r, color, Foil::None, sink);
|
||||
}
|
||||
};
|
||||
part("entity/banner/banner_base", argb(-1));
|
||||
part("entity/banner/base", dye(base));
|
||||
for (texture, color) in layers.iter().take(16) {
|
||||
part(texture, dye(color));
|
||||
}
|
||||
}
|
||||
|
||||
/// `SpecialModelRenderer.submit`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn submit(
|
||||
|
||||
@@ -166,6 +166,9 @@ pub struct Items {
|
||||
/// Block tag name (without '#') -> member block names.
|
||||
pub block_tags: HashMap<String, HashSet<String>>,
|
||||
pub item_tags: HashMap<String, HashSet<String>>,
|
||||
/// Item tags in vanilla's order (`TagLoader`: file order, nested tags in
|
||||
/// place, first occurrence kept), the order `TagSlotDisplay` resolves.
|
||||
pub item_tag_order: HashMap<String, Vec<String>>,
|
||||
loot: HashMap<String, Value>,
|
||||
/// The `jukebox_song` registry.
|
||||
pub songs: HashMap<String, Song>,
|
||||
@@ -216,6 +219,13 @@ fn load_songs(root: &Path) -> HashMap<String, Song> {
|
||||
songs
|
||||
}
|
||||
pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
|
||||
Ok(load_tag_lists(root, kind)?
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k, v.into_iter().collect()))
|
||||
.collect())
|
||||
}
|
||||
/// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`).
|
||||
pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result<HashMap<String, Vec<String>>> {
|
||||
let dir = root.join(format!("data/minecraft/tags/{kind}"));
|
||||
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
|
||||
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
|
||||
@@ -246,29 +256,24 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
|
||||
if dir.exists() {
|
||||
walk(&dir, &dir, &mut raw)?;
|
||||
}
|
||||
fn resolve(
|
||||
name: &str,
|
||||
raw: &HashMap<String, Vec<String>>,
|
||||
out: &mut HashSet<String>,
|
||||
depth: u32,
|
||||
) {
|
||||
fn resolve(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut Vec<String>, depth: u32) {
|
||||
if depth > 32 {
|
||||
return;
|
||||
}
|
||||
for v in raw.get(name).into_iter().flatten() {
|
||||
if let Some(tag) = v.strip_prefix('#') {
|
||||
resolve(tag, raw, out, depth + 1);
|
||||
} else {
|
||||
out.insert(v.clone());
|
||||
} else if !out.contains(v) {
|
||||
out.push(v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(raw
|
||||
.keys()
|
||||
.map(|k| {
|
||||
let mut set = HashSet::new();
|
||||
resolve(k, &raw, &mut set, 0);
|
||||
(k.clone(), set)
|
||||
let mut list = Vec::new();
|
||||
resolve(k, &raw, &mut list, 0);
|
||||
(k.clone(), list)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -456,6 +461,7 @@ impl Items {
|
||||
order,
|
||||
block_tags: load_tags(root, "block")?,
|
||||
item_tags: load_tags(root, "item")?,
|
||||
item_tag_order: load_tag_lists(root, "item")?,
|
||||
loot,
|
||||
songs: load_songs(root),
|
||||
})
|
||||
@@ -470,6 +476,7 @@ impl Items {
|
||||
order: Vec::new(),
|
||||
block_tags: load_tags(root, "block")?,
|
||||
item_tags: load_tags(root, "item")?,
|
||||
item_tag_order: load_tag_lists(root, "item")?,
|
||||
loot: HashMap::new(),
|
||||
songs: HashMap::new(),
|
||||
})
|
||||
@@ -481,6 +488,10 @@ impl Items {
|
||||
items: HashMap::new(),
|
||||
order: Vec::new(),
|
||||
block_tags: HashMap::new(),
|
||||
item_tag_order: item_tags
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.iter().cloned().collect()))
|
||||
.collect(),
|
||||
item_tags,
|
||||
loot: HashMap::new(),
|
||||
songs: HashMap::new(),
|
||||
|
||||
@@ -85,6 +85,7 @@ pub mod projectiles;
|
||||
pub mod raid;
|
||||
pub mod random_sequences;
|
||||
pub mod recipe_book;
|
||||
pub mod recipe_book_screen;
|
||||
pub mod save;
|
||||
pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
|
||||
@@ -639,7 +639,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn have(items: &[(&str, i32)]) -> Stacked {
|
||||
let mut s = Stacked::default();
|
||||
|
||||
@@ -405,11 +405,10 @@ impl Book {
|
||||
pub fn entry(&self, id: &str) -> Option<&Entry> {
|
||||
self.entries.iter().find(|e| e.id == id)
|
||||
}
|
||||
/// `ingredient`'s items in registry order (the cycling order of ghost slots).
|
||||
/// `ingredient`'s items as its display resolves them (the cycling order
|
||||
/// of ghost slots and the overlay).
|
||||
pub fn items_of(&self, ingredient: &Ingredient) -> Vec<String> {
|
||||
let mut items: Vec<String> = ingredient.0.iter().cloned().collect();
|
||||
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
|
||||
items
|
||||
ingredient.1.clone()
|
||||
}
|
||||
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
|
||||
/// `FullTextSearchTree`): without a colon the text must occur in a
|
||||
@@ -714,7 +713,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
#[test]
|
||||
fn small_recipes_are_centred_in_the_grid() {
|
||||
|
||||
@@ -0,0 +1,734 @@
|
||||
//! The recipe book's drawing (`RecipeBookComponent.extractRenderState`,
|
||||
//! `extractTooltip` and `GhostSlots.extractRenderState`) as the list of GUI
|
||||
//! calls vanilla's widgets make: the background, the search `EditBox`, the
|
||||
//! `RecipeBookTabButton`s, the craftable filter `CycleButton`, the
|
||||
//! `RecipeBookPage` with its `RecipeButton`s, page number and arrows, the
|
||||
//! `OverlayRecipeComponent` and the ghost slots, each with the pose it is
|
||||
//! drawn under. The game paints them; the render parity harness compares them.
|
||||
use crate::{
|
||||
items::ItemStack,
|
||||
recipe_book::{Book, BookType, Display, Entry},
|
||||
};
|
||||
|
||||
/// A styled run of text: its characters, colour (`-1` for the call's own) and italics.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Run {
|
||||
pub text: String,
|
||||
pub color: i32,
|
||||
pub italic: bool,
|
||||
}
|
||||
impl Run {
|
||||
pub fn plain(text: impl Into<String>) -> Self {
|
||||
Run {
|
||||
text: text.into(),
|
||||
color: -1,
|
||||
italic: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an item is drawn: `GuiGraphicsExtractor.item`, `fakeItem` or `itemDecorations`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ItemCall {
|
||||
Item,
|
||||
Fake,
|
||||
Decorations,
|
||||
}
|
||||
|
||||
/// One GUI call.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Call {
|
||||
/// `blit` of a texture region (the book's background).
|
||||
Blit {
|
||||
texture: &'static str,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
u: f32,
|
||||
v: f32,
|
||||
tw: i32,
|
||||
th: i32,
|
||||
},
|
||||
/// `blitSprite`, the id without its namespace.
|
||||
Sprite {
|
||||
id: String,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
},
|
||||
Fill {
|
||||
x0: i32,
|
||||
y0: i32,
|
||||
x1: i32,
|
||||
y1: i32,
|
||||
color: i32,
|
||||
},
|
||||
/// `textHighlight` (the search box's selection).
|
||||
Highlight { x0: i32, y0: i32, x1: i32, y1: i32 },
|
||||
Text {
|
||||
runs: Vec<Run>,
|
||||
x: i32,
|
||||
y: i32,
|
||||
color: i32,
|
||||
shadow: bool,
|
||||
},
|
||||
Item {
|
||||
call: ItemCall,
|
||||
stack: ItemStack,
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
/// A widget's tooltip lines.
|
||||
Tooltip(Vec<Vec<Run>>),
|
||||
/// The hovered recipe button's tooltip: its display stack's own tooltip,
|
||||
/// then "Right Click for More" when it has several recipes.
|
||||
ItemTooltip { stack: ItemStack, more: bool },
|
||||
/// `nextStratum`.
|
||||
Stratum,
|
||||
}
|
||||
|
||||
/// A call and the pose (`Matrix3x2f` m00, m01, m10, m11, m20, m21) it is made under.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drawn {
|
||||
pub call: Call,
|
||||
pub pose: [f32; 6],
|
||||
}
|
||||
|
||||
pub const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// JOML `Matrix3x2f.translate`.
|
||||
fn translate(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
|
||||
[
|
||||
m[0],
|
||||
m[1],
|
||||
m[2],
|
||||
m[3],
|
||||
m[0] * x + m[2] * y + m[4],
|
||||
m[1] * x + m[3] * y + m[5],
|
||||
]
|
||||
}
|
||||
/// JOML `Matrix3x2f.scale`.
|
||||
fn scale(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
|
||||
[m[0] * x, m[1] * x, m[2] * y, m[3] * y, m[4], m[5]]
|
||||
}
|
||||
|
||||
/// The search box (`EditBox` fields).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Search {
|
||||
pub value: String,
|
||||
/// Cursor, selection end and first shown character, in characters.
|
||||
pub cursor: usize,
|
||||
pub highlight: usize,
|
||||
pub display: usize,
|
||||
pub focused: bool,
|
||||
/// Milliseconds since the box was focused (`TextCursorUtils.isCursorVisible`).
|
||||
pub blink_ms: u64,
|
||||
}
|
||||
|
||||
/// A visible tab, in order: its icons, whether selected, its squeeze time left.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TabView {
|
||||
pub icons: (String, Option<String>),
|
||||
pub selected: bool,
|
||||
pub anim: f32,
|
||||
}
|
||||
|
||||
/// A recipe button: its collection has a craftable recipe; the display
|
||||
/// stacks of each selected recipe; the squeeze time left.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ButtonView {
|
||||
pub has_craftable: bool,
|
||||
pub entries: Vec<Vec<ItemStack>>,
|
||||
pub anim: f32,
|
||||
}
|
||||
|
||||
/// A recipe of the overlay: craftable, and its ingredient cells (grid
|
||||
/// x, y and the stacks the cell cycles through).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OverlayRecipe {
|
||||
pub craftable: bool,
|
||||
pub cells: Vec<(i32, i32, Vec<ItemStack>)>,
|
||||
}
|
||||
|
||||
/// The alternatives overlay of a button, at the corner [`overlay_origin`] gives.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OverlayView {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
/// Craftable recipes first.
|
||||
pub recipes: Vec<OverlayRecipe>,
|
||||
}
|
||||
|
||||
/// A ghost slot: its position in the menu, the stacks it cycles through,
|
||||
/// and whether it is the result slot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GhostView {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub items: Vec<ItemStack>,
|
||||
pub result: bool,
|
||||
}
|
||||
|
||||
/// What the recipe book shows.
|
||||
pub struct Screen<'a> {
|
||||
pub book: BookType,
|
||||
/// GUI size and `widthTooNarrow`.
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub narrow: bool,
|
||||
pub mouse: (i32, i32),
|
||||
/// `slotSelectTime.currentIndex()`.
|
||||
pub index: usize,
|
||||
pub filtering: bool,
|
||||
pub search: &'a Search,
|
||||
pub tabs: &'a [TabView],
|
||||
/// The current page's buttons.
|
||||
pub buttons: &'a [ButtonView],
|
||||
pub page: usize,
|
||||
pub pages: usize,
|
||||
pub overlay: Option<&'a OverlayView>,
|
||||
/// The container's corner, whether its result slot is big, and the ghost slots.
|
||||
pub ghost: Option<(i32, i32, bool, &'a [GhostView])>,
|
||||
/// Translations.
|
||||
pub translate: &'a dyn Fn(&str) -> String,
|
||||
/// `Font.width`.
|
||||
pub text_width: &'a dyn Fn(&str) -> i32,
|
||||
}
|
||||
|
||||
impl Screen<'_> {
|
||||
/// `RecipeBookComponent.getXOrigin` and `getYOrigin`.
|
||||
pub fn origin(&self) -> (i32, i32) {
|
||||
let offset = if self.narrow { 0 } else { 86 };
|
||||
((self.width - 147) / 2 - offset, (self.height - 166) / 2)
|
||||
}
|
||||
fn hovered(&self, x: i32, y: i32, w: i32, h: i32) -> bool {
|
||||
let (mx, my) = self.mouse;
|
||||
mx >= x && my >= y && mx < x + w && my < y + h
|
||||
}
|
||||
/// `Font.plainSubstrByWidth`.
|
||||
fn substr_by_width<'s>(&self, s: &'s str, max: i32) -> &'s str {
|
||||
let mut end = 0;
|
||||
for (i, c) in s.char_indices() {
|
||||
if (self.text_width)(&s[..i + c.len_utf8()]) > max {
|
||||
break;
|
||||
}
|
||||
end = i + c.len_utf8();
|
||||
}
|
||||
&s[..end]
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe book's calls, in vanilla's order.
|
||||
pub fn draw(s: &Screen) -> Vec<Drawn> {
|
||||
let mut out = Vec::new();
|
||||
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
|
||||
let (xo, yo) = s.origin();
|
||||
put(
|
||||
Call::Blit {
|
||||
texture: "textures/gui/recipe_book.png",
|
||||
x: xo,
|
||||
y: yo,
|
||||
w: 147,
|
||||
h: 166,
|
||||
u: 1.0,
|
||||
v: 1.0,
|
||||
tw: 256,
|
||||
th: 256,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
search_box(s, xo + 25, yo + 13, &mut put);
|
||||
// updateTabs.
|
||||
let offset = if s.narrow { 0 } else { 86 };
|
||||
let tab_x = (s.width - 147) / 2 - offset - 30;
|
||||
let tab_y = (s.height - 166) / 2 + 3;
|
||||
for (n, tab) in s.tabs.iter().enumerate() {
|
||||
let (x, y) = (tab_x, tab_y + 27 * n as i32);
|
||||
let mut pose = IDENTITY;
|
||||
if tab.anim > 0.0 {
|
||||
let squeeze = squeeze(tab.anim);
|
||||
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
|
||||
pose = translate(scale(translate(pose, cx, cy), 1.0, squeeze), -cx, -cy);
|
||||
}
|
||||
let sprite = if tab.selected {
|
||||
"recipe_book/tab_selected"
|
||||
} else {
|
||||
"recipe_book/tab"
|
||||
};
|
||||
let left = if tab.selected { -2 } else { 0 };
|
||||
put(sprite_call(sprite, x + left, y, 35, 27), pose);
|
||||
let fake = |id: &str, x: i32| Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: ItemStack::new(id, 1),
|
||||
x,
|
||||
y: y + 5,
|
||||
};
|
||||
match &tab.icons.1 {
|
||||
Some(second) => {
|
||||
put(fake(&tab.icons.0, x + 3 + left), pose);
|
||||
put(fake(second, x + 14 + left), pose);
|
||||
}
|
||||
None => put(fake(&tab.icons.0, x + 9 + left), pose),
|
||||
}
|
||||
}
|
||||
// The craftable filter.
|
||||
let (fx, fy) = (xo + 110, yo + 12);
|
||||
let hover = s.hovered(fx, fy, 26, 16);
|
||||
let prefix = if s.book == BookType::Crafting {
|
||||
"recipe_book/"
|
||||
} else {
|
||||
"recipe_book/furnace_"
|
||||
};
|
||||
let state = if s.filtering {
|
||||
"filter_enabled"
|
||||
} else {
|
||||
"filter_disabled"
|
||||
};
|
||||
put(
|
||||
sprite_call(
|
||||
&format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" }),
|
||||
fx,
|
||||
fy,
|
||||
26,
|
||||
16,
|
||||
),
|
||||
IDENTITY,
|
||||
);
|
||||
if hover {
|
||||
let key = if !s.filtering {
|
||||
"gui.recipebook.toggleRecipes.all"
|
||||
} else {
|
||||
match s.book {
|
||||
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
|
||||
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
|
||||
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
|
||||
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
|
||||
}
|
||||
};
|
||||
put(
|
||||
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
// RecipeBookPage.extractRenderState.
|
||||
if s.pages > 1 {
|
||||
let text = (s.translate)("gui.recipebook.page")
|
||||
.replacen("%s", &(s.page + 1).to_string(), 1)
|
||||
.replacen("%s", &s.pages.to_string(), 1);
|
||||
let w = (s.text_width)(&text);
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run::plain(text)],
|
||||
x: xo - w / 2 + 73,
|
||||
y: yo + 141,
|
||||
color: -1,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
let mut hovered = None;
|
||||
for (i, b) in s.buttons.iter().enumerate().take(20) {
|
||||
let (x, y) = (xo + 11 + 25 * (i as i32 % 5), yo + 31 + 25 * (i as i32 / 5));
|
||||
let many = b.entries.len() > 1;
|
||||
let sprite = match (b.has_craftable, many) {
|
||||
(true, true) => "recipe_book/slot_many_craftable",
|
||||
(true, false) => "recipe_book/slot_craftable",
|
||||
(false, true) => "recipe_book/slot_many_uncraftable",
|
||||
(false, false) => "recipe_book/slot_uncraftable",
|
||||
};
|
||||
let mut pose = IDENTITY;
|
||||
if b.anim > 0.0 {
|
||||
let squeeze = squeeze(b.anim);
|
||||
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
|
||||
pose = translate(scale(translate(pose, cx, cy), squeeze, squeeze), -cx, -cy);
|
||||
}
|
||||
put(sprite_call(sprite, x, y, 25, 25), pose);
|
||||
let stack = display_stack(&b.entries, s.index);
|
||||
let mut offset = 4;
|
||||
if many && same_result_display(&b.entries) {
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Item,
|
||||
stack: stack.clone(),
|
||||
x: x + offset + 1,
|
||||
y: y + offset + 1,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
offset -= 1;
|
||||
}
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: stack.clone(),
|
||||
x: x + offset,
|
||||
y: y + offset,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
if s.hovered(x, y, 25, 25) {
|
||||
hovered = Some((stack, many));
|
||||
}
|
||||
}
|
||||
let arrows = [
|
||||
(
|
||||
s.pages > 1 && s.page + 1 < s.pages,
|
||||
xo + 93,
|
||||
"recipe_book/page_forward",
|
||||
"gui.recipebook.next_page",
|
||||
),
|
||||
(
|
||||
s.pages > 1 && s.page > 0,
|
||||
xo + 38,
|
||||
"recipe_book/page_backward",
|
||||
"gui.recipebook.previous_page",
|
||||
),
|
||||
];
|
||||
for (visible, x, sprite, key) in arrows {
|
||||
if !visible {
|
||||
continue;
|
||||
}
|
||||
let hover = s.hovered(x, yo + 137, 12, 17);
|
||||
let id = if hover {
|
||||
format!("{sprite}_highlighted")
|
||||
} else {
|
||||
sprite.to_owned()
|
||||
};
|
||||
put(sprite_call(&id, x, yo + 137, 12, 17), IDENTITY);
|
||||
if hover {
|
||||
put(
|
||||
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
}
|
||||
put(Call::Stratum, IDENTITY);
|
||||
if let Some(o) = s.overlay {
|
||||
overlay(s, o, &mut put);
|
||||
}
|
||||
// RecipeBookPage.extractTooltip.
|
||||
if let Some((stack, more)) = hovered
|
||||
&& s.overlay.is_none()
|
||||
{
|
||||
put(Call::ItemTooltip { stack, more }, IDENTITY);
|
||||
}
|
||||
if let Some((left, top, big, ghosts)) = s.ghost {
|
||||
out.extend(ghost(s.index, left, top, big, ghosts));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `GhostSlots.extractRenderState` for a container whose corner is `(left, top)`.
|
||||
pub fn ghost(index: usize, left: i32, top: i32, big: bool, ghosts: &[GhostView]) -> Vec<Drawn> {
|
||||
let mut out = Vec::new();
|
||||
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
|
||||
let pose = translate(IDENTITY, left as f32, top as f32);
|
||||
for g in ghosts.iter().filter(|g| !g.items.is_empty()) {
|
||||
let (x, y) = (g.x, g.y);
|
||||
if g.result && big {
|
||||
put(fill(x - 4, y - 4, x + 20, y + 20, 822_018_048), pose);
|
||||
} else {
|
||||
put(fill(x, y, x + 16, y + 16, 822_018_048), pose);
|
||||
}
|
||||
let stack = g.items[index % g.items.len()].clone();
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: stack.clone(),
|
||||
x,
|
||||
y,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
put(fill(x, y, x + 16, y + 16, 822_083_583), pose);
|
||||
if g.result {
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Decorations,
|
||||
stack,
|
||||
x,
|
||||
y,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `1 + 0.1 sin(t / 15 * PI)`, the squeeze of new recipes' buttons and tabs.
|
||||
fn squeeze(time: f32) -> f32 {
|
||||
1.0 + 0.1 * f64::from(time / 15.0 * std::f32::consts::PI).sin() as f32
|
||||
}
|
||||
|
||||
fn sprite_call(id: &str, x: i32, y: i32, w: i32, h: i32) -> Call {
|
||||
Call::Sprite {
|
||||
id: id.to_owned(),
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
}
|
||||
}
|
||||
fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: i32) -> Call {
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeButton.getDisplayStack`.
|
||||
fn display_stack(entries: &[Vec<ItemStack>], index: usize) -> ItemStack {
|
||||
let n = entries.len().max(1);
|
||||
let (offset, entry) = (index / n, index % n);
|
||||
match entries.get(entry) {
|
||||
Some(items) if !items.is_empty() => items[offset % items.len()].clone(),
|
||||
_ => ItemStack::new("minecraft:air", 0),
|
||||
}
|
||||
}
|
||||
/// `RecipeButton.allRecipesHaveSameResultDisplay`.
|
||||
fn same_result_display(entries: &[Vec<ItemStack>]) -> bool {
|
||||
let mut items = entries.iter().flatten();
|
||||
let Some(first) = items.next() else {
|
||||
return true;
|
||||
};
|
||||
items.all(|s| first.same_item_same_components(s))
|
||||
}
|
||||
|
||||
/// `EditBox.extractWidgetRenderState` for the recipe book's search box.
|
||||
fn search_box(s: &Screen, x: i32, y: i32, put: &mut impl FnMut(Call, [f32; 6])) {
|
||||
let b = s.search;
|
||||
let (w, h) = (81, 9 + 5);
|
||||
let sprite = if b.focused {
|
||||
"widget/text_field_highlighted"
|
||||
} else {
|
||||
"widget/text_field"
|
||||
};
|
||||
put(sprite_call(sprite, x, y, w, h), IDENTITY);
|
||||
let (text_x, text_y) = (x + 4, y + (h - 8) / 2);
|
||||
let color = -1;
|
||||
let chars: Vec<char> = b.value.chars().collect();
|
||||
let tail: String = chars[b.display.min(chars.len())..].iter().collect();
|
||||
let displayed = s.substr_by_width(&tail, w - 8).to_owned();
|
||||
let shown = displayed.chars().count();
|
||||
let rel_cursor = b.cursor as i64 - b.display as i64;
|
||||
let on_screen = rel_cursor >= 0 && rel_cursor <= shown as i64;
|
||||
let visible = b.focused && (b.blink_ms / 300).is_multiple_of(2) && on_screen;
|
||||
let mut draw_x = text_x;
|
||||
let rel_highlight = (b.highlight as i64 - b.display as i64).clamp(0, shown as i64) as usize;
|
||||
let prefix = |n: usize| displayed.chars().take(n).collect::<String>();
|
||||
if !displayed.is_empty() {
|
||||
let half = if on_screen {
|
||||
prefix(rel_cursor as usize)
|
||||
} else {
|
||||
displayed.clone()
|
||||
};
|
||||
let width = (s.text_width)(&half);
|
||||
put(
|
||||
Call::Text {
|
||||
runs: runs_of(half),
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
draw_x += width + 1;
|
||||
}
|
||||
let insert = b.cursor < chars.len() || chars.len() >= 50;
|
||||
let mut cursor_x = draw_x;
|
||||
if !on_screen {
|
||||
cursor_x = if rel_cursor > 0 { text_x + w } else { text_x };
|
||||
} else if insert {
|
||||
cursor_x -= 1;
|
||||
draw_x -= 1;
|
||||
}
|
||||
if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown {
|
||||
let rest: String = displayed.chars().skip(rel_cursor as usize).collect();
|
||||
put(
|
||||
Call::Text {
|
||||
runs: runs_of(rest),
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if displayed.is_empty() && !b.focused {
|
||||
// SEARCH_HINT: gray, italic.
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run {
|
||||
text: (s.translate)("gui.recipebook.search_hint"),
|
||||
color: 0xAAAAAA,
|
||||
italic: true,
|
||||
}],
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if rel_highlight as i64 != rel_cursor {
|
||||
let highlight_x = text_x + (s.text_width)(&prefix(rel_highlight));
|
||||
put(
|
||||
Call::Highlight {
|
||||
x0: cursor_x.min(x + w),
|
||||
y0: text_y - 1,
|
||||
x1: (highlight_x - 1).min(x + w),
|
||||
y1: text_y + 1 + 9,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if visible {
|
||||
if insert {
|
||||
put(
|
||||
fill(cursor_x, text_y - 1, cursor_x + 1, text_y + 10, color),
|
||||
IDENTITY,
|
||||
);
|
||||
} else {
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run::plain("_")],
|
||||
x: cursor_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn runs_of(text: String) -> Vec<Run> {
|
||||
if text.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![Run::plain(text)]
|
||||
}
|
||||
}
|
||||
|
||||
/// `OverlayRecipeComponent.init`'s corner for `total` recipes opened from the
|
||||
/// button at `(button_x, button_y)` of the book at `(xo, yo)`.
|
||||
pub fn overlay_origin(button_x: i32, button_y: i32, total: usize, xo: i32, yo: i32) -> (i32, i32) {
|
||||
let total = total as i32;
|
||||
let max_row = if total <= 16 { 4 } else { 5 };
|
||||
let rows = (total as f32 / max_row as f32).ceil() as i32;
|
||||
let (mut x, mut y) = (button_x, button_y);
|
||||
let width = 25.0f32;
|
||||
let (center_x, center_y) = (xo + 147 / 2, yo + 13 + 166 / 2);
|
||||
let right = (x + total.min(max_row) * 25) as f32;
|
||||
let max_left = (center_x + 50) as f32;
|
||||
if right > max_left {
|
||||
x = (x as f32 - width * ((right - max_left) / width) as i32 as f32) as i32;
|
||||
}
|
||||
let bottom = (y + rows * 25) as f32;
|
||||
let max_bottom = (center_y + 50) as f32;
|
||||
if bottom > max_bottom {
|
||||
y = (y as f32 - width * ((bottom - max_bottom) / width).ceil()) as i32;
|
||||
}
|
||||
let top = y as f32;
|
||||
let max_top = (center_y - 100) as f32;
|
||||
if top < max_top {
|
||||
y = (y as f32 - width * ((top - max_top) / width).ceil()) as i32;
|
||||
}
|
||||
(x, y)
|
||||
}
|
||||
|
||||
/// `OverlayRecipeComponent.extractRenderState`.
|
||||
fn overlay(s: &Screen, o: &OverlayView, put: &mut impl FnMut(Call, [f32; 6])) {
|
||||
let total = o.recipes.len() as i32;
|
||||
let max_row = if total <= 16 { 4 } else { 5 };
|
||||
let (x, y) = (o.x, o.y);
|
||||
let columns = total.min(max_row);
|
||||
let height = (total as f32 / max_row as f32).ceil() as i32;
|
||||
put(
|
||||
sprite_call(
|
||||
"recipe_book/overlay_recipe",
|
||||
x,
|
||||
y,
|
||||
columns * 25 + 8,
|
||||
height * 25 + 8,
|
||||
),
|
||||
IDENTITY,
|
||||
);
|
||||
let family = if s.book == BookType::Crafting {
|
||||
"crafting"
|
||||
} else {
|
||||
"furnace"
|
||||
};
|
||||
for (i, r) in o.recipes.iter().enumerate() {
|
||||
let i = i as i32;
|
||||
let (bx, by) = (x + 4 + 25 * (i % max_row), y + 5 + 25 * (i / max_row));
|
||||
let hover = s.hovered(bx, by, 24, 24);
|
||||
let id = format!(
|
||||
"recipe_book/{family}_overlay{}{}",
|
||||
if r.craftable { "" } else { "_disabled" },
|
||||
if hover { "_highlighted" } else { "" }
|
||||
);
|
||||
put(sprite_call(&id, bx, by, 24, 24), IDENTITY);
|
||||
let (gx, gy) = ((bx + 2) as f32, (by + 2) as f32);
|
||||
for (cx, cy, items) in &r.cells {
|
||||
let pose = translate(
|
||||
scale(
|
||||
translate(IDENTITY, gx + (3 + cx * 7) as f32, gy + (3 + cy * 7) as f32),
|
||||
0.375,
|
||||
0.375,
|
||||
),
|
||||
-8.0,
|
||||
-8.0,
|
||||
);
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Item,
|
||||
stack: items[s.index % items.len()].clone(),
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ingredient cells a recipe shows in the overlay
|
||||
/// (`OverlayCraftingRecipeButton` / `OverlaySmeltingRecipeButton.calculateIngredientsPositions`).
|
||||
pub fn overlay_cells(book: &Book, entry: &Entry) -> Vec<(i32, i32, Vec<ItemStack>)> {
|
||||
let stacks = |ingredient| -> Vec<ItemStack> {
|
||||
book.items_of(ingredient)
|
||||
.iter()
|
||||
.map(|i| ItemStack::new(i, 1))
|
||||
.collect()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
match &entry.display {
|
||||
Display::Furnace(i) => out.push((1, 1, stacks(i))),
|
||||
Display::Shaped { .. } => {
|
||||
let requirements = entry.requirements();
|
||||
for (ingredient, grid) in entry.grid_cells(3, 3) {
|
||||
if let Some(i) = ingredient {
|
||||
out.push((grid as i32 % 3, grid as i32 / 3, stacks(requirements[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
Display::Shapeless(list) => {
|
||||
for (i, ingredient) in list.iter().enumerate() {
|
||||
out.push((i as i32 % 3, i as i32 / 3, stacks(ingredient)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.retain(|c| !c.2.is_empty());
|
||||
out
|
||||
}
|
||||
@@ -53,7 +53,7 @@ pub(crate) fn text(tag: Option<&Tag>) -> Option<String> {
|
||||
}
|
||||
}
|
||||
/// Any numeric tag as i64 (vanilla's `getIntOr` etc. accept every number type).
|
||||
pub(crate) fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
pub fn number(tag: Option<&Tag>) -> Option<i64> {
|
||||
Some(match tag? {
|
||||
Tag::Byte(v) => i64::from(*v),
|
||||
Tag::Short(v) => i64::from(*v),
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashSet, fs, path::Path, sync::Arc};
|
||||
use std::{fs, path::Path, sync::Arc};
|
||||
|
||||
/// Everything the workstation menus read, loaded once with the resources.
|
||||
pub struct StationData {
|
||||
@@ -457,7 +457,7 @@ pub struct StationRecipes {
|
||||
pub trim_materials: Vec<(String, String)>,
|
||||
}
|
||||
fn ingredient(v: &Value, items: &Items) -> Ingredient {
|
||||
let mut set = HashSet::new();
|
||||
let mut list: Vec<String> = Vec::new();
|
||||
for s in match v {
|
||||
Value::String(s) => vec![s.clone()],
|
||||
Value::Array(a) => a
|
||||
@@ -466,14 +466,17 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient {
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
} {
|
||||
match s.strip_prefix('#') {
|
||||
Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()),
|
||||
None => {
|
||||
set.insert(s);
|
||||
let more = match s.strip_prefix('#') {
|
||||
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
|
||||
None => vec![s],
|
||||
};
|
||||
for i in more {
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ingredient(set)
|
||||
Ingredient::of(list)
|
||||
}
|
||||
impl StationRecipes {
|
||||
pub fn load(root: &Path, items: &Items) -> Self {
|
||||
|
||||
@@ -701,6 +701,12 @@ impl EditBox {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The first shown character after scrolling to the cursor, and the
|
||||
/// milliseconds since the field was focused (the cursor's blink).
|
||||
pub fn view_state(&mut self, atlas: &HudAtlas) -> (usize, u64) {
|
||||
self.layout(atlas);
|
||||
(self.display, self.focused_at.elapsed().as_millis() as u64)
|
||||
}
|
||||
/// Draw the field; `format` styles the visible text (command colouring).
|
||||
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
|
||||
self.layout(atlas);
|
||||
|
||||
+15
-4
@@ -1418,11 +1418,22 @@ vanilla's own classes, and the game uses that code:
|
||||
`CrafterScreen`'s decorations as draw calls the game paints;
|
||||
`tools/test_screen_layout_parity.py` runs vanilla's screens on stand-in
|
||||
menus and compares 1,600 call lists.
|
||||
- **The book's drawing.** `recipe_book_screen` lays out
|
||||
`RecipeBookComponent`'s background, search `EditBox`, tab buttons, filter
|
||||
`CycleButton`, the page of `RecipeButton`s with its number and arrows, the
|
||||
`OverlayRecipeComponent`, the tooltips and `GhostSlots` as GUI calls with
|
||||
their poses (squeeze animations, the overlay's 3/8 scale items); the game
|
||||
paints them. `tools/test_recipe_book_render_parity.py` builds vanilla's
|
||||
widgets for 600 states (`VanillaRecipeBookScreenOracle`) and compares every
|
||||
call. Ingredients cycle in their `HolderSet` order (tags in `TagLoader` order).
|
||||
- **The loom's banner preview.** `item_render::gui::draw_banner_result` draws
|
||||
`GuiBannerResultRenderer`'s flag model and layers in the 20x40 picture in
|
||||
picture, lit with `ITEMS_FLAT`; the block entity render harness compares its
|
||||
quads under the picture-in-picture pose.
|
||||
|
||||
Not compared yet: the recipe book's own drawing (tabs, buttons, the overlay
|
||||
and ghost slots) and its text search, the banner preview's 3D flag (drawn as
|
||||
the flat front face), furnaces awarding their recipes and experience when
|
||||
their output is taken, and the limited crafting game rule.
|
||||
Not compared yet: the recipe book's text search, furnaces awarding their
|
||||
recipes and experience when their output is taken, and the limited crafting
|
||||
game rule.
|
||||
|
||||
## Player list and world border rendering
|
||||
|
||||
|
||||
@@ -33,13 +33,15 @@ import net.minecraft.world.phys.*;
|
||||
/**
|
||||
* Original oracle for the client-ticked animation state of chests and ender
|
||||
* chests (ChestLidController), enchanting table books, shulker boxes, bells,
|
||||
* conduits, skulls and decorated pots. Each case builds the real
|
||||
* conduits, skulls, decorated pots and End gateways. Each case builds the real
|
||||
* vanilla block entity on a stand-in client level (scripted blocks, entities,
|
||||
* game time and a seeded LegacyRandomSource), then per step applies the
|
||||
* scripted block event (triggerEvent), runs the block entity's own client
|
||||
* ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM
|
||||
* reseeded, ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick,
|
||||
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none)
|
||||
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation,
|
||||
* TheEndGatewayBlockEntity.beamAnimationTick after the server copy's portalTick
|
||||
* on a server-side stand-in; pots have none)
|
||||
* and runs the real renderer's extractRenderState at the step's partial tick.
|
||||
* It prints the block entity's fields, the level calls the tick made
|
||||
* (neighbour updates, entity queries, sounds, particles) and the render state.
|
||||
@@ -100,6 +102,9 @@ public final class VanillaBlockEntityAnimOracle {
|
||||
static final class World extends Level {
|
||||
World() { super(null, null, null, null, false, false, 0L, 0); }
|
||||
long time;
|
||||
boolean server;
|
||||
int minY, height;
|
||||
BlockEntity serverCopyOf;
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
List<Mob> mobs = new ArrayList<>();
|
||||
List<Player> gamers = new ArrayList<>();
|
||||
@@ -108,7 +113,16 @@ public final class VanillaBlockEntityAnimOracle {
|
||||
StringBuilder log = new StringBuilder();
|
||||
|
||||
@Override public long getGameTime() { return time; }
|
||||
@Override public boolean isClientSide() { return true; }
|
||||
@Override public boolean isClientSide() { return !server; }
|
||||
@Override public int getMinY() { return minY; }
|
||||
@Override public int getHeight() { return height; }
|
||||
@Override public void blockEvent(BlockPos p, Block block, int b0, int b1) {
|
||||
// The integrated server's block event reaching the client copy.
|
||||
log.append(" blockEvent ").append(b0).append(' ').append(b1);
|
||||
serverCopyOf.triggerEvent(b0, b1);
|
||||
}
|
||||
@Override public void blockEntityChanged(BlockPos p) {}
|
||||
@Override public void updateNeighbourForOutputSignal(BlockPos p, Block block) {}
|
||||
@Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); }
|
||||
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
|
||||
@Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; }
|
||||
@@ -236,6 +250,22 @@ public final class VanillaBlockEntityAnimOracle {
|
||||
if (c.has("target") && be instanceof ConduitBlockEntity) {
|
||||
put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world)));
|
||||
}
|
||||
World serverWorld = null;
|
||||
TheEndGatewayBlockEntity serverGateway = null;
|
||||
if (be instanceof TheEndGatewayBlockEntity g) {
|
||||
var level = c.getAsJsonArray("level");
|
||||
world.minY = level.get(0).getAsInt();
|
||||
world.height = level.get(1).getAsInt();
|
||||
field(TheEndGatewayBlockEntity.class, "age").setLong(g, c.get("age").getAsLong());
|
||||
serverWorld = make(World.class);
|
||||
serverWorld.server = true;
|
||||
serverWorld.blocks = world.blocks;
|
||||
serverWorld.log = world.log;
|
||||
serverWorld.serverCopyOf = g;
|
||||
serverGateway = (TheEndGatewayBlockEntity) ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
|
||||
serverGateway.setLevel(serverWorld);
|
||||
field(TheEndGatewayBlockEntity.class, "age").setLong(serverGateway, c.get("age").getAsLong());
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (var stepElement : c.getAsJsonArray("steps")) {
|
||||
var step = stepElement.getAsJsonObject();
|
||||
@@ -251,6 +281,14 @@ public final class VanillaBlockEntityAnimOracle {
|
||||
world.gamers.clear();
|
||||
for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject()));
|
||||
}
|
||||
if (serverGateway != null) {
|
||||
serverWorld.time = world.time;
|
||||
// ServerLevel.tick: entities (EndGatewayBlock.entityInside), then block entities.
|
||||
if (step.has("enter") && !serverGateway.isCoolingDown()) {
|
||||
TheEndGatewayBlockEntity.triggerCooldown(serverWorld, pos, state, serverGateway);
|
||||
}
|
||||
TheEndGatewayBlockEntity.portalTick(serverWorld, pos, state, serverGateway);
|
||||
}
|
||||
if (step.has("event")) {
|
||||
var ev = step.getAsJsonArray("event");
|
||||
boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt());
|
||||
@@ -327,6 +365,15 @@ public final class VanillaBlockEntityAnimOracle {
|
||||
make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null);
|
||||
fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle
|
||||
+ " render " + f(r.wobbleProgress) + " " + r.wobbleStyle;
|
||||
} else if (be instanceof TheEndGatewayBlockEntity g) {
|
||||
TheEndGatewayBlockEntity.beamAnimationTick(world, pos, state, g);
|
||||
var r = make(TheEndGatewayRenderer.class).createRenderState();
|
||||
make(TheEndGatewayRenderer.class).extractRenderState(g, r, partial, Vec3.ZERO, null);
|
||||
fields = field(TheEndGatewayBlockEntity.class, "age").getLong(g)
|
||||
+ " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(g)
|
||||
+ " server " + field(TheEndGatewayBlockEntity.class, "age").getLong(serverGateway)
|
||||
+ " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(serverGateway)
|
||||
+ " render " + r.height + " " + f(r.scale) + " " + Integer.toHexString(r.color) + " " + f(r.animationTime);
|
||||
} else {
|
||||
throw new IllegalArgumentException("no animation for " + be);
|
||||
}
|
||||
|
||||
+41
-8
@@ -11,6 +11,9 @@ import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.model.Model;
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
import net.minecraft.client.model.geom.LayerDefinitions;
|
||||
import net.minecraft.client.model.object.banner.BannerFlagModel;
|
||||
import net.minecraft.client.renderer.Sheets;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.minecraft.client.renderer.SubmitNodeCollector;
|
||||
import net.minecraft.client.renderer.blockentity.*;
|
||||
import net.minecraft.client.renderer.blockentity.state.*;
|
||||
@@ -333,17 +336,39 @@ public final class VanillaBlockEntityRenderOracle {
|
||||
}
|
||||
be.setLevel(level);
|
||||
} else if (be instanceof BannerBlockEntity && c.has("patterns")) {
|
||||
var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder();
|
||||
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
|
||||
for (var e : c.getAsJsonArray("patterns")) {
|
||||
var p = e.getAsJsonArray();
|
||||
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
|
||||
builder.add(holder, dye(p.get(1).getAsString()));
|
||||
}
|
||||
field(BannerBlockEntity.class, "patterns").set(be, builder.build());
|
||||
field(BannerBlockEntity.class, "patterns").set(be, patterns(c.getAsJsonArray("patterns")));
|
||||
}
|
||||
}
|
||||
|
||||
/** [[pattern id, dye], ...] as BannerPatternLayers. */
|
||||
static BannerPatternLayers patterns(JsonArray list) {
|
||||
var builder = new BannerPatternLayers.Builder();
|
||||
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
|
||||
for (var e : list) {
|
||||
var p = e.getAsJsonArray();
|
||||
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
|
||||
builder.add(holder, dye(p.get(1).getAsString()));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* LoomScreen's result preview (GuiGraphicsExtractor.bannerPattern): the
|
||||
* picture-in-picture pose of PictureInPictureRenderer.prepare for its 20x40
|
||||
* rectangle at GUI scale 1 (translate(w / 2, h), scale(16, 16, -16)), then
|
||||
* GuiBannerResultRenderer.renderToTexture without its lighting setup
|
||||
* (Lighting.Entry.ITEMS_FLAT, applied by the harness).
|
||||
*/
|
||||
static void loomResult(JsonObject loom, BannerFlagModel flag, SpriteGetter sprites, SubmitNodeCollector collector) {
|
||||
var pose = new PoseStack();
|
||||
pose.translate(20 / 2.0F, 40.0F, 0.0F);
|
||||
pose.scale(16.0F, 16.0F, -16.0F);
|
||||
pose.translate(0.0F, 0.25F, 0.0F);
|
||||
collector.submitModel(flag, 0.0F, pose, 15728880, OverlayTexture.NO_OVERLAY, -1, Sheets.BANNER_BASE, sprites, 0);
|
||||
BannerRenderer.submitPatterns(sprites, pose, collector, 15728880, OverlayTexture.NO_OVERLAY, flag, 0.0F, true,
|
||||
dye(loom.get("base").getAsString()), patterns(loom.getAsJsonArray("patterns")));
|
||||
}
|
||||
|
||||
/** Render-state values vanilla reads from the level (absent here). */
|
||||
static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) {
|
||||
if (rs instanceof ChestRenderState chest) {
|
||||
@@ -381,6 +406,7 @@ public final class VanillaBlockEntityRenderOracle {
|
||||
var items = new net.minecraft.client.renderer.item.ItemModelResolver(null);
|
||||
var context = new BlockEntityRendererProvider.Context(null, null, items, null, models, font, sprites, null);
|
||||
Map<Object, BlockEntityRenderer> renderers = (Map) BlockEntityRenderers.createEntityRenderers(context);
|
||||
var loomFlag = new BannerFlagModel(models.bakeLayer(net.minecraft.client.model.geom.ModelLayers.STANDING_BANNER_FLAG));
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
@@ -389,6 +415,13 @@ public final class VanillaBlockEntityRenderOracle {
|
||||
var result = new JsonObject();
|
||||
result.add("case", c);
|
||||
try {
|
||||
if (c.has("loom")) {
|
||||
var submits = new JsonArray();
|
||||
loomResult(c.getAsJsonObject("loom"), loomFlag, sprites, collector(submits));
|
||||
result.add("submits", submits);
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
continue;
|
||||
}
|
||||
BlockState state = parseState(c.get("block").getAsString());
|
||||
var p = c.getAsJsonArray("pos");
|
||||
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.ClientRecipeBook;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.CycleButton;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.components.WidgetSprites;
|
||||
import net.minecraft.client.gui.components.WidgetTooltipHolder;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
|
||||
import net.minecraft.client.gui.screens.recipebook.*;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.RenderPipelines;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.CommonComponents;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.context.ContextMap;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.inventory.tooltip.TooltipComponent;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.item.crafting.display.RecipeDisplayEntry;
|
||||
import net.minecraft.world.item.crafting.display.RecipeDisplayId;
|
||||
import net.minecraft.world.item.crafting.display.SlotDisplay;
|
||||
import net.minecraft.world.item.crafting.display.SlotDisplayContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.joml.Matrix3x2fStack;
|
||||
|
||||
/**
|
||||
* Original oracle for the recipe book's drawing (RecipeBookComponent.extractRenderState,
|
||||
* its tooltips and GhostSlots.extractRenderState): the background, the real
|
||||
* search EditBox, RecipeBookTabButtons, the craftable filter CycleButton, a
|
||||
* RecipeBookPage of RecipeButtons over real RecipeCollections with its page
|
||||
* arrows and number, the OverlayRecipeComponent of a button and ghost slots,
|
||||
* each built as RecipeBookComponent.initVisuals and RecipeBookPage.init build
|
||||
* them, with the state the case gives (tab and button animations, the cycling
|
||||
* index, the search box, the mouse). Every GuiGraphicsExtractor call is recorded
|
||||
* with its pose. The hovered button's tooltip is recorded as its display stack
|
||||
* (RecipeButton.getTooltipText adds the item's own tooltip, compared elsewhere).
|
||||
*/
|
||||
public final class VanillaRecipeBookScreenOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T alloc(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> owner, String name) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
|
||||
Class<?> t = f.getType();
|
||||
String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject";
|
||||
Class<?> param = t.isPrimitive() ? t : Object.class;
|
||||
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
|
||||
}
|
||||
|
||||
static float round(float v) { return Math.round(v * 1e4f) / 1e4f; }
|
||||
|
||||
/** A text's styled runs: [text, rgb or -1, italic]. */
|
||||
static JsonArray runs(FormattedCharSequence s) {
|
||||
var out = new JsonArray();
|
||||
StringBuilder text = new StringBuilder();
|
||||
int[] style = {Integer.MIN_VALUE, 0};
|
||||
s.accept((i, st, cp) -> {
|
||||
int color = st.getColor() == null ? -1 : st.getColor().getValue();
|
||||
int italic = st.isItalic() ? 1 : 0;
|
||||
if (text.length() > 0 && (color != style[0] || italic != style[1])) {
|
||||
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
|
||||
text.setLength(0);
|
||||
}
|
||||
style[0] = color; style[1] = italic;
|
||||
text.appendCodePoint(cp);
|
||||
return true;
|
||||
});
|
||||
if (text.length() > 0) {
|
||||
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String id(ItemStack s) { return s.isEmpty() ? "minecraft:air" : s.getItem().builtInRegistryHolder().key().identifier().toString(); }
|
||||
|
||||
/** Records every GuiGraphicsExtractor call with the pose it was made under. */
|
||||
public static final class Capture extends GuiGraphicsExtractor {
|
||||
JsonArray draws = new JsonArray();
|
||||
Matrix3x2fStack stack = new Matrix3x2fStack(16);
|
||||
private Capture() { super(null, null, 0, 0); }
|
||||
@Override public Matrix3x2fStack pose() { return stack; }
|
||||
@Override public void nextStratum() { add("stratum"); }
|
||||
@Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { }
|
||||
@Override public boolean containsPointInScissor(int x, int y) { return true; }
|
||||
JsonObject add(String type) {
|
||||
var o = new JsonObject();
|
||||
o.addProperty("t", type);
|
||||
var m = new JsonArray();
|
||||
for (float v : new float[] {stack.m00(), stack.m01(), stack.m10(), stack.m11(), stack.m20(), stack.m21()}) m.add(round(v));
|
||||
o.add("m", m);
|
||||
draws.add(o);
|
||||
return o;
|
||||
}
|
||||
@Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) {
|
||||
var o = add("fill");
|
||||
o.addProperty("x0", Math.min(x0, x1)); o.addProperty("y0", Math.min(y0, y1));
|
||||
o.addProperty("x1", Math.max(x0, x1)); o.addProperty("y1", Math.max(y0, y1));
|
||||
o.addProperty("color", color);
|
||||
}
|
||||
@Override public void textHighlight(int x0, int y0, int x1, int y1, boolean invert) {
|
||||
var o = add("highlight");
|
||||
o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1);
|
||||
}
|
||||
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) {
|
||||
var o = add("sprite");
|
||||
o.addProperty("id", id.getPath());
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
|
||||
}
|
||||
@Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) {
|
||||
var o = add("blit");
|
||||
o.addProperty("texture", texture.getPath());
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
|
||||
o.addProperty("u", u); o.addProperty("v", v); o.addProperty("tw", texW); o.addProperty("th", texH);
|
||||
}
|
||||
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
|
||||
var o = add("text");
|
||||
o.add("runs", runs(str));
|
||||
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
|
||||
}
|
||||
@Override public void text(Font font, String str, int x, int y, int color, boolean shadow) {
|
||||
if (str != null) text(font, FormattedCharSequence.forward(str, net.minecraft.network.chat.Style.EMPTY), x, y, color, shadow);
|
||||
}
|
||||
void item(String kind, ItemStack s, int x, int y) {
|
||||
if (s.isEmpty()) return;
|
||||
var o = add(kind);
|
||||
o.addProperty("id", id(s)); o.addProperty("count", s.getCount());
|
||||
o.addProperty("x", x); o.addProperty("y", y);
|
||||
}
|
||||
@Override public void item(ItemStack s, int x, int y) { item("item", s, x, y); }
|
||||
@Override public void item(ItemStack s, int x, int y, int seed) { item("item", s, x, y); }
|
||||
@Override public void fakeItem(ItemStack s, int x, int y) { item("fake", s, x, y); }
|
||||
@Override public void fakeItem(ItemStack s, int x, int y, int seed) { item("fake", s, x, y); }
|
||||
@Override public void itemDecorations(Font font, ItemStack s, int x, int y, String count) { item("decorations", s, x, y); }
|
||||
@Override public void setTooltipForNextFrame(Font font, List<FormattedCharSequence> lines, Optional<TooltipComponent> image,
|
||||
ClientTooltipPositioner positioner, int x, int y, boolean replace, Identifier style) {
|
||||
var o = add("tooltip");
|
||||
var a = new JsonArray();
|
||||
for (var l : lines) a.add(runs(l));
|
||||
o.add("lines", a);
|
||||
}
|
||||
}
|
||||
|
||||
/** The window's text input area, which a focused EditBox moves: not tracked here. */
|
||||
static final class NoTextInput extends com.mojang.blaze3d.platform.TextInputManager {
|
||||
NoTextInput() { super(null); }
|
||||
@Override public void setTextInputArea(int x0, int y0, int x1, int y1) { }
|
||||
}
|
||||
|
||||
static List<RecipeDisplayEntry> displays(RecipeManager recipes, String id) {
|
||||
List<RecipeDisplayEntry> out = new ArrayList<>();
|
||||
recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A collection of the given recipes' displays; `craftable` lists the recipes the inventory can craft. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static RecipeCollection collection(RecipeManager recipes, JsonObject b) throws Exception {
|
||||
List<RecipeDisplayEntry> entries = new ArrayList<>();
|
||||
Set<RecipeDisplayId> craftable = (Set<RecipeDisplayId>) new HashSet<RecipeDisplayId>();
|
||||
for (var r : b.getAsJsonArray("recipes")) {
|
||||
var a = r.getAsJsonArray();
|
||||
for (var e : displays(recipes, a.get(0).getAsString())) {
|
||||
entries.add(e);
|
||||
if (a.get(1).getAsBoolean()) craftable.add(e.id());
|
||||
}
|
||||
}
|
||||
var c = new RecipeCollection(entries);
|
||||
((Set<RecipeDisplayId>) field(RecipeCollection.class, "selected").get(c)).addAll(entries.stream().map(RecipeDisplayEntry::id).toList());
|
||||
((Set<RecipeDisplayId>) field(RecipeCollection.class, "craftable").get(c)).addAll(craftable);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** The widget's tooltip shows on this frame when hovered (its delay has passed). */
|
||||
static void settled(Object widget) throws Exception {
|
||||
var holder = (WidgetTooltipHolder) field(net.minecraft.client.gui.components.AbstractWidget.class, "tooltip").get(widget);
|
||||
put(holder, WidgetTooltipHolder.class, "wasDisplayed", true);
|
||||
put(holder, WidgetTooltipHolder.class, "displayStartTime", Util.getMillis() - 1000L);
|
||||
}
|
||||
|
||||
static JsonArray run(JsonObject c, Minecraft mc, RecipeManager recipes) throws Exception {
|
||||
var g = alloc(Capture.class);
|
||||
g.draws = new JsonArray();
|
||||
g.stack = new Matrix3x2fStack(16);
|
||||
String type = c.get("type").getAsString();
|
||||
boolean furnace = !type.equals("crafting");
|
||||
int width = c.get("width").getAsInt(), height = c.get("height").getAsInt();
|
||||
int xOffset = c.get("narrow").getAsBoolean() ? 0 : 86;
|
||||
int xo = (width - 147) / 2 - xOffset, yo = (height - 166) / 2;
|
||||
int mx = c.getAsJsonArray("mouse").get(0).getAsInt(), my = c.getAsJsonArray("mouse").get(1).getAsInt();
|
||||
int index = c.get("index").getAsInt();
|
||||
SlotSelectTime time = () -> index;
|
||||
boolean filtering = c.get("filtering").getAsBoolean();
|
||||
// RecipeBookComponent.extractRenderState.
|
||||
g.blit(RenderPipelines.GUI_TEXTURED, (Identifier) field(RecipeBookComponent.class, "RECIPE_BOOK_LOCATION").get(null), xo, yo, 1.0F, 1.0F, 147, 166, 256, 256);
|
||||
var s = c.getAsJsonObject("search");
|
||||
var search = new EditBox(mc.font, xo + 25, yo + 13, 81, 9 + 5, Component.translatable("itemGroup.search"));
|
||||
search.setMaxLength(50);
|
||||
search.setVisible(true);
|
||||
search.setTextColor(-1);
|
||||
search.setValue(s.get("value").getAsString());
|
||||
search.setHint((Component) field(RecipeBookComponent.class, "SEARCH_HINT").get(null));
|
||||
put(search, net.minecraft.client.gui.components.AbstractWidget.class, "focused", s.get("focused").getAsBoolean());
|
||||
put(search, EditBox.class, "displayPos", s.get("display").getAsInt());
|
||||
put(search, EditBox.class, "cursorPos", s.get("cursor").getAsInt());
|
||||
put(search, EditBox.class, "highlightPos", s.get("highlight").getAsInt());
|
||||
put(search, EditBox.class, "focusedTime", Util.getMillis() - s.get("blink").getAsLong());
|
||||
search.extractRenderState(g, mx, my, 1.0F);
|
||||
Class<?> tabOwner = switch (type) {
|
||||
case "crafting" -> CraftingRecipeBookComponent.class;
|
||||
case "furnace" -> net.minecraft.client.gui.screens.inventory.FurnaceScreen.class;
|
||||
case "blast_furnace" -> net.minecraft.client.gui.screens.inventory.BlastFurnaceScreen.class;
|
||||
default -> net.minecraft.client.gui.screens.inventory.SmokerScreen.class;
|
||||
};
|
||||
@SuppressWarnings("unchecked")
|
||||
var infos = (List<RecipeBookComponent.TabInfo>) field(tabOwner, "TABS").get(null);
|
||||
// updateTabs: the visible tabs in order.
|
||||
int n = 0;
|
||||
for (var t : c.getAsJsonArray("tabs")) {
|
||||
var tab = t.getAsJsonObject();
|
||||
var button = new RecipeBookTabButton(0, 0, infos.get(tab.get("tab").getAsInt()), b -> {});
|
||||
button.setPosition((width - 147) / 2 - xOffset - 30, (height - 166) / 2 + 3 + 27 * n++);
|
||||
if (tab.get("selected").getAsBoolean()) button.select();
|
||||
put(button, RecipeBookTabButton.class, "animationTime", tab.get("anim").getAsFloat());
|
||||
button.extractRenderState(g, mx, my, 1.0F);
|
||||
}
|
||||
RecipeBookComponent<?> component = furnace ? alloc(FurnaceRecipeBookComponent.class) : alloc(CraftingRecipeBookComponent.class);
|
||||
Method name = RecipeBookComponent.class.getDeclaredMethod("getRecipeFilterName");
|
||||
name.setAccessible(true);
|
||||
Method sprites = RecipeBookComponent.class.getDeclaredMethod("getFilterButtonTextures");
|
||||
sprites.setAccessible(true);
|
||||
if (furnace) put(component, FurnaceRecipeBookComponent.class, "recipeFilterName", Component.translatable(switch (type) {
|
||||
case "furnace" -> "gui.recipebook.toggleRecipes.smeltable";
|
||||
case "blast_furnace" -> "gui.recipebook.toggleRecipes.blastable";
|
||||
default -> "gui.recipebook.toggleRecipes.smokable";
|
||||
}));
|
||||
Component filterName = (Component) name.invoke(component);
|
||||
WidgetSprites filterSprites = (WidgetSprites) sprites.invoke(component);
|
||||
Component all = (Component) field(RecipeBookComponent.class, "ALL_RECIPES_TOOLTIP").get(null);
|
||||
var filter = CycleButton.booleanBuilder(filterName, all, filtering)
|
||||
.withTooltip(f -> f ? Tooltip.create(filterName) : Tooltip.create(all))
|
||||
.withSprite((b, f) -> filterSprites.get(f, b.isHoveredOrFocused()))
|
||||
.displayState(CycleButton.DisplayState.HIDE)
|
||||
.create(xo + 110, yo + 12, 26, 16, CommonComponents.EMPTY, (b, v) -> {});
|
||||
settled(filter);
|
||||
filter.extractRenderState(g, mx, my, 1.0F);
|
||||
// RecipeBookPage.init and updateCollections.
|
||||
var page = new RecipeBookPage(null, time, furnace);
|
||||
page.init(mc, xo, yo);
|
||||
List<RecipeCollection> collections = new ArrayList<>();
|
||||
for (var b : c.getAsJsonArray("collections")) collections.add(collection(recipes, b.getAsJsonObject()));
|
||||
put(page, RecipeBookPage.class, "currentPage", c.get("page").getAsInt());
|
||||
page.updateCollections(collections, false, filtering);
|
||||
@SuppressWarnings("unchecked")
|
||||
var buttons = (List<RecipeButton>) field(RecipeBookPage.class, "buttons").get(page);
|
||||
var anims = c.getAsJsonArray("buttonAnims");
|
||||
for (int i = 0; i < anims.size(); i++) put(buttons.get(i), RecipeButton.class, "animationTime", anims.get(i).getAsFloat());
|
||||
for (String arrow : new String[] {"forwardButton", "backButton"}) settled(field(RecipeBookPage.class, arrow).get(page));
|
||||
var overlay = (OverlayRecipeComponent) field(RecipeBookPage.class, "overlay").get(page);
|
||||
if (c.has("overlay")) {
|
||||
// RecipeBookPage.mouseClicked: right click on a button.
|
||||
var button = buttons.get(c.get("overlay").getAsInt());
|
||||
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
|
||||
overlay.init(button.getCollection(), context, filtering, button.getX(), button.getY(), xo + 147 / 2, yo + 13 + 166 / 2, button.getWidth());
|
||||
}
|
||||
page.extractRenderState(g, xo, yo, mx, my, 1.0F);
|
||||
// RecipeBookPage.extractTooltip.
|
||||
var hovered = (RecipeButton) field(RecipeBookPage.class, "hoveredButton").get(page);
|
||||
if (hovered != null && !overlay.isVisible()) {
|
||||
var o = g.add("item_tooltip");
|
||||
o.addProperty("id", id(hovered.getDisplayStack()));
|
||||
o.addProperty("more", !hovered.isOnlyOption());
|
||||
}
|
||||
// GhostSlots.extractRenderState.
|
||||
if (c.has("ghost")) {
|
||||
var ghost = new GhostSlots(time);
|
||||
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
|
||||
var container = new SimpleContainer(16);
|
||||
int i = 0;
|
||||
for (var e : c.getAsJsonArray("ghost")) {
|
||||
var gs = e.getAsJsonObject();
|
||||
var slot = new Slot(container, i++, gs.get("x").getAsInt(), gs.get("y").getAsInt());
|
||||
List<SlotDisplay> items = new ArrayList<>();
|
||||
for (var it : gs.getAsJsonArray("items")) items.add(new SlotDisplay.ItemStackSlotDisplay(new net.minecraft.world.item.ItemStackTemplate(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue(Identifier.parse(it.getAsString())))));
|
||||
SlotDisplay display = new SlotDisplay.Composite(items);
|
||||
Method set = GhostSlots.class.getDeclaredMethod(gs.get("result").getAsBoolean() ? "setResult" : "setInput", Slot.class, ContextMap.class, SlotDisplay.class);
|
||||
set.setAccessible(true);
|
||||
set.invoke(ghost, slot, context, display);
|
||||
}
|
||||
g.pose().pushMatrix();
|
||||
g.pose().translate(c.get("left").getAsInt(), c.get("top").getAsInt());
|
||||
ghost.extractRenderState(g, mc, c.get("big").getAsBoolean());
|
||||
g.pose().popMatrix();
|
||||
}
|
||||
return g.draws;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
unsafeField.setAccessible(true);
|
||||
unsafe = unsafeField.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
RecipeManager recipes = new RecipeManager(ParityData.lookup);
|
||||
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
|
||||
// A stand-in client: its font, a level for the slot display context, a player's book.
|
||||
Minecraft mc = alloc(Minecraft.class);
|
||||
put(mc, Minecraft.class, "font", ParityFont.create(ParityFont.resources()));
|
||||
var level = alloc(ClientLevel.class);
|
||||
put(level, Level.class, "registryAccess", ParityData.access);
|
||||
put(mc, Minecraft.class, "level", level);
|
||||
var player = alloc(LocalPlayer.class);
|
||||
put(player, LocalPlayer.class, "recipeBook", new ClientRecipeBook());
|
||||
put(mc, Minecraft.class, "player", player);
|
||||
put(mc, Minecraft.class, "lastInputType", net.minecraft.client.InputType.MOUSE);
|
||||
put(mc, Minecraft.class, "textInputManager", new NoTextInput());
|
||||
field(Minecraft.class, "instance").set(null, mc);
|
||||
var gson = new Gson();
|
||||
var out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
if (line.isBlank()) continue;
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
var result = new JsonObject();
|
||||
try {
|
||||
result.add("draws", run(c, mc, recipes));
|
||||
} catch (Throwable error) {
|
||||
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result.addProperty("error", sw.toString().lines().limit(8).reduce("", (a, b) -> a + b + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla
|
||||
block entity (chest, trapped/copper chest and the other half of a double chest,
|
||||
ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head,
|
||||
decorated pot)
|
||||
decorated pot, End gateway with the integrated server's copy ticking beside it)
|
||||
on a stand-in client level, then per scripted step applies the block event
|
||||
(triggerEvent), runs the entity's own client ticker and the renderer's
|
||||
extractRenderState, printing the fields, the level calls the tick made
|
||||
@@ -162,6 +162,21 @@ def cases():
|
||||
step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])]
|
||||
steps.append(step)
|
||||
add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps)
|
||||
# End gateways: the server copy's portalTick (triggerCooldown every 2400
|
||||
# ticks, entities entering) sends block event 1 to the client copy, whose
|
||||
# beamAnimationTick and TheEndGatewayRenderer draw the beam; saved ages
|
||||
# from new to long settled, both level heights.
|
||||
for i in range(40):
|
||||
age = rng.choice([0, 0, 150, 2390, 4790, rng.randint(200, 10 ** 6), 2399 + 2400 * rng.randint(1, 50)])
|
||||
steps = []
|
||||
for t in times(rng.randint(20, 90), gaps=(1, 1, 1, 2)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
if rng.random() < 0.06:
|
||||
step['enter'] = True
|
||||
if rng.random() < 0.04:
|
||||
step['event'] = [rng.choice([1, 2, 0]), rng.choice([0, 3])]
|
||||
steps.append(step)
|
||||
add('gateway', 'minecraft:end_gateway', steps, age=age, level=rng.choice([[0, 256], [-64, 384]]))
|
||||
# Chests and ender chests: open counts from block event 1 (both halves of
|
||||
# a double chest), other events ignored; the neighbour a double half
|
||||
# connects to may be its other half or not (wrong block, type, facing).
|
||||
|
||||
@@ -72,6 +72,11 @@ def cases():
|
||||
add(f'minecraft:{color}_wall_banner[facing={f}]',
|
||||
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))])
|
||||
add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)])
|
||||
# The loom's result preview (GuiBannerResultRenderer in a 20x40 picture in
|
||||
# picture, lit with Lighting.Entry.ITEMS_FLAT): up to the loom's six layers, and 17.
|
||||
for n in [0, 1, 2, 3, 6, 6, 17]:
|
||||
out.append({'block': 'loom_result', 'loom': {'base': rng.choice(DYES),
|
||||
'patterns': [[rng.choice(patterns), rng.choice(DYES)] for _ in range(n)]}})
|
||||
for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head',
|
||||
'piglin_head', 'player_head']:
|
||||
wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head')
|
||||
@@ -147,15 +152,26 @@ def lights():
|
||||
return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7])
|
||||
|
||||
|
||||
def items_flat_lights():
|
||||
"""Lighting.Entry.ITEMS_FLAT: rotationY(-PI/8).rotateX(3PI/4) of the diffuse lights."""
|
||||
def rotate(v):
|
||||
a, b = -math.pi / 8, math.pi * 3 / 4
|
||||
x, y, z = v
|
||||
y, z = y * math.cos(b) - z * math.sin(b), y * math.sin(b) + z * math.cos(b)
|
||||
return [x * math.cos(a) + z * math.sin(a), y, -x * math.sin(a) + z * math.cos(a)]
|
||||
return tuple(rotate(l) for l in lights())
|
||||
|
||||
|
||||
L0, L1 = lights()
|
||||
FLAT = items_flat_lights()
|
||||
|
||||
|
||||
def mix(normal):
|
||||
def mix(normal, lit=(L0, L1)):
|
||||
d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal)))
|
||||
return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4)
|
||||
return min(1.0, (d(lit[0]) + d(lit[1])) * 0.6 + 0.4)
|
||||
|
||||
|
||||
def vanilla_quads(submits):
|
||||
def vanilla_quads(submits, lit=(L0, L1)):
|
||||
quads, other = [], []
|
||||
for s in submits:
|
||||
custom = s['type'] == 'submitCustomGeometry'
|
||||
@@ -167,7 +183,7 @@ def vanilla_quads(submits):
|
||||
q = verts[i:i + 4]
|
||||
tint = q[0][3] & 0xFFFFFFFF
|
||||
# Custom geometry (beacon beams) is unlit; models get the entity shader's mix light.
|
||||
b = 1.0 if custom else mix(q[0][8:11])
|
||||
b = 1.0 if custom else mix(q[0][8:11], lit)
|
||||
ch = lambda shift: int(((tint >> shift) & 255) * b)
|
||||
quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q],
|
||||
'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7],
|
||||
@@ -206,7 +222,7 @@ def pair(vq, rq):
|
||||
|
||||
def compare_case(v, r, tol):
|
||||
problems = []
|
||||
vq, other = vanilla_quads(v['submits'])
|
||||
vq, other = vanilla_quads(v['submits'], FLAT if 'loom' in v['case'] else (L0, L1))
|
||||
for s in other:
|
||||
if s['type'] == 'submitText':
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the recipe book's drawing with the vanilla client's.
|
||||
|
||||
Each case opens a book type (the inventory's or a crafting table's crafting
|
||||
book, the furnace, blast furnace or smoker) at a GUI size, with its visible
|
||||
tabs (one selected, some in their new-recipe squeeze), the search box (text,
|
||||
cursor, selection, focus and cursor blink), the craftable filter, a page of
|
||||
recipe collections (real recipes, some craftable, some buttons squeezing),
|
||||
the alternatives overlay of one button, ghost slots, the cycling index and
|
||||
the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's
|
||||
widgets for that state as RecipeBookComponent.initVisuals and
|
||||
RecipeBookPage.init do and records every GuiGraphicsExtractor call of their
|
||||
extractRenderState, the tooltips and GhostSlots.extractRenderState, with its
|
||||
pose; examples/recipe_book_render_fixture lays out the same state with
|
||||
horizon_client::recipe_book_screen, which the game paints. The call lists
|
||||
must agree.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
try:
|
||||
from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import test_model_baking_parity as baking
|
||||
import test_rust_parity as base
|
||||
|
||||
TABS = {'crafting': 5, 'furnace': 4, 'blast_furnace': 3, 'smoker': 2}
|
||||
TYPES = {'crafting': ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless'), 'furnace': ('minecraft:smelting',),
|
||||
'blast_furnace': ('minecraft:blasting',), 'smoker': ('minecraft:smoking',)}
|
||||
WORDS = ['', '', 'a', 'stone', 'iron ingot', 'oak', 'zzz', 'red', 'a very long search text that overflows']
|
||||
|
||||
|
||||
def recipes_by_type():
|
||||
out = {k: [] for k in TYPES}
|
||||
for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')):
|
||||
kind = json.loads(path.read_text()).get('type')
|
||||
for k, types in TYPES.items():
|
||||
if kind in types:
|
||||
out[k].append('minecraft:' + path.stem)
|
||||
return out
|
||||
|
||||
|
||||
def cases(count, seed):
|
||||
rng = random.Random(seed)
|
||||
by_type = recipes_by_type()
|
||||
items = sorted(i for i in json.loads((lib.RESOURCES / 'items.json').read_text()) if i != 'minecraft:air')
|
||||
out = []
|
||||
for n in range(count):
|
||||
kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5]
|
||||
width, height = rng.choice([(427, 240), (480, 270), (640, 360), (320, 240), (378, 260), (854, 480)])
|
||||
narrow = width < 379
|
||||
xo = (width - 147) // 2 - (0 if narrow else 86)
|
||||
yo = (height - 166) // 2
|
||||
tabs = [0] + sorted(rng.sample(range(1, TABS[kind]), rng.randint(0, TABS[kind] - 1)))
|
||||
selected = rng.choice(tabs)
|
||||
tab_list = [{'tab': t, 'selected': t == selected, 'anim': rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)])}
|
||||
for t in tabs]
|
||||
total = rng.choice([0, 1, 5, 19, 20, 21, 47, 80])
|
||||
pages = (total + 19) // 20
|
||||
page = rng.randrange(pages) if pages else 0
|
||||
filtering = rng.random() < 0.4
|
||||
collections = []
|
||||
for _ in range(total):
|
||||
group = rng.sample(by_type[kind], rng.choice([1, 1, 1, 2, 3, 6]))
|
||||
recipes = [[r, rng.random() < 0.4] for r in group]
|
||||
if filtering and not any(c for _, c in recipes):
|
||||
recipes[0][1] = True
|
||||
collections.append({'recipes': recipes})
|
||||
on_page = max(0, min(20, total - 20 * page))
|
||||
value = rng.choice(WORDS)
|
||||
cursor = rng.randint(0, len(value))
|
||||
highlight = rng.choice([cursor, rng.randint(0, len(value))])
|
||||
search = {'value': value, 'cursor': cursor, 'highlight': highlight,
|
||||
'display': rng.choice([0, 0, min(cursor, rng.randint(0, len(value)))]), 'focused': rng.random() < 0.5,
|
||||
'blink': rng.choice([0, 150, 450, 700])}
|
||||
targets = [(xo + 11 + 25 * (i % 5) + rng.randint(0, 24), yo + 31 + 25 * (i // 5) + rng.randint(0, 24)) for i in range(on_page)]
|
||||
targets += [(xo + 115, yo + 20), (xo + 95, yo + 140), (xo + 40, yo + 140), (xo + 30, yo + 18), (xo - 20, yo + 40),
|
||||
(rng.randint(0, width), rng.randint(0, height))]
|
||||
case = {'type': kind, 'grid': 2 if rng.random() < 0.5 else 3, 'width': width, 'height': height, 'narrow': narrow,
|
||||
'mouse': list(rng.choice(targets)), 'index': rng.choice([0, 0, 1, 2, 5, 13, 60]), 'filtering': filtering,
|
||||
'tabs': tab_list, 'search': search, 'collections': collections, 'page': page,
|
||||
'buttonAnims': [rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)]) for _ in range(on_page)]}
|
||||
multi = [i for i in range(on_page) if sum(1 for _, c in collections[20 * page + i]['recipes'] if c or not filtering) > 1]
|
||||
if multi and rng.random() < 0.4:
|
||||
case['overlay'] = rng.choice(multi)
|
||||
if rng.random() < 0.4:
|
||||
left, top = (width - 176) // 2, (height - 166) // 2
|
||||
slots = [(124, 35, True)] + [(30 + 18 * (i % 3), 17 + 18 * (i // 3), False) for i in range(9)]
|
||||
if kind != 'crafting':
|
||||
slots = [(116, 35, True), (56, 17, False)]
|
||||
case.update({'left': left, 'top': top, 'big': rng.random() < 0.7,
|
||||
'ghost': [{'x': x, 'y': y, 'result': r, 'items': rng.sample(items, rng.choice([1, 1, 2, 4]))}
|
||||
for x, y, r in rng.sample(slots, rng.randint(1, len(slots)))]})
|
||||
out.append(case)
|
||||
return out
|
||||
|
||||
|
||||
def same(a, b):
|
||||
"""Calls agree: every field exactly, poses within float printing."""
|
||||
if a is None or b is None or set(a) != set(b):
|
||||
return False
|
||||
return all(all(abs(x - y) <= 1e-3 for x, y in zip(a[k], b[k])) if k == 'm' else a[k] == b[k] for k in a)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=29)
|
||||
parser.add_argument('--cases', type=int, default=600)
|
||||
parser.add_argument('--limit', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
work = lib.work_dir('recipe-book-render-parity')
|
||||
classes = work / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
|
||||
done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps,
|
||||
'-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'ParityFont', 'VanillaRecipeBookScreenOracle'))],
|
||||
capture_output=True, text=True)
|
||||
if done.returncode:
|
||||
print(done.stderr[-4000:])
|
||||
sys.exit('javac failed')
|
||||
chosen = cases(args.cases, args.seed)
|
||||
inputs = work / 'cases.jsonl'
|
||||
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookScreenOracle',
|
||||
str(inputs), str(work / 'vanilla.jsonl')], capture_output=True, text=True)
|
||||
if run.returncode:
|
||||
print(run.stderr[-4000:])
|
||||
sys.exit('oracle failed')
|
||||
lib.cargo_example('horizon-client', 'recipe_book_render_fixture', lib.RESOURCES, inputs, work / 'rust.jsonl')
|
||||
vanilla = [json.loads(l) for l in (work / 'vanilla.jsonl').read_text().splitlines()]
|
||||
rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
|
||||
errors, failures, passed = {}, {}, 0
|
||||
for case, v, r in zip(chosen, vanilla, rust):
|
||||
if 'error' in v:
|
||||
errors.setdefault(case['type'], v['error'])
|
||||
continue
|
||||
a, b = v['draws'], r['draws']
|
||||
bad = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or not same(a[i], b[i])), None)
|
||||
if bad is None:
|
||||
passed += 1
|
||||
else:
|
||||
failures.setdefault(case['type'], []).append((case, bad, a[bad] if bad < len(a) else None, b[bad] if bad < len(b) else None))
|
||||
for kind, error in sorted(errors.items()):
|
||||
print(f'ORACLE ERROR {kind}: {error[:1500]}')
|
||||
for kind, items in sorted(failures.items()):
|
||||
print(f'MISMATCH {kind}: {len(items)} cases')
|
||||
for case, i, x, y in items[:args.limit]:
|
||||
brief = {k: v for k, v in case.items() if k not in ('collections',)}
|
||||
print(f' {json.dumps(brief)[:700]}')
|
||||
print(f' call {i}: vanilla {json.dumps(x)}')
|
||||
print(f' call {i}: horizon {json.dumps(y)}')
|
||||
print(f'{passed}/{len(chosen)} cases match')
|
||||
if errors or failures:
|
||||
sys.exit(1)
|
||||
print('recipe book render parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user