diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index aa4a14a58..d844c4e44 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -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 = + 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 = (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); diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 759d6e0da..f6648c43b 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -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)]); } diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index 0000b2613..930524dce 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -89,7 +89,7 @@ fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec { } /// 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, + x0: f32, + y0: f32, + base: &str, + layers: &[(String, String)], +) -> Vec { + 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, + 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::*; diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index fe9f0cfa8..a36b5b118 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -379,6 +379,33 @@ fn pot_sides(v: &Value) -> [Option; 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, + 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( diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java index c7c40a477..1de892a29 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java @@ -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 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()); diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index e4c32ca2a..8d11389fd 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -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