Skip to main content

yog_book/
renderer.rs

1//! Book renderer — ties together yog-ui layout, yog-gfx GPU pipeline,
2//! SVG icon rasterization, and custom font rendering.
3
4use std::collections::HashMap;
5use yog_gfx::{GfxContext, gl, core::{DrawMode, DataType, blend}};
6use yog_ui::{widget, FlexDir, Align, UiRoot};
7
8use crate::{Book, BookPage};
9use crate::state::BookViewState;
10use crate::theme::BookTheme;
11use crate::font::{BookFontRegistry, FontAtlas};
12use crate::svg;
13
14// Patchouli-compatible book texture layout (512×256 sprite sheet).
15// UV coordinates are in pixels on a 512×256 sheet.
16// The full open-book background occupies 272×180 at UV (0,0).
17pub const BOOK_TEX_W: f32   = 512.0;
18pub const BOOK_TEX_H: f32   = 256.0;
19// Open-book dimensions in texture-space
20pub const BK_W: f32         = 272.0;
21pub const BK_H: f32         = 180.0;
22// Per-page dimensions and offsets (in book-local coords)
23pub const PAGE_W: f32       = 116.0;
24pub const PAGE_H: f32       = 156.0;
25pub const TOP_PAD: f32      = 18.0;   // vertical space above page text area
26pub const LEFT_X: f32       = 15.0;   // left page X inside book
27pub const RIGHT_X: f32      = 141.0;  // right page X inside book
28// Separator strip UV origin on the sprite sheet
29pub const SEP_U: f32        = 140.0;
30pub const SEP_V: f32        = 180.0;
31pub const SEP_W: f32        = 110.0;
32pub const SEP_H: f32        = 3.0;
33
34// ── Vertex for the custom 2D shader (pos + uv + color) ───────────────────────
35
36#[repr(C)]
37#[derive(Copy, Clone)]
38struct Vert { x: f32, y: f32, u: f32, v: f32, r: f32, g: f32, b: f32, a: f32 }
39
40fn rgba_f(c: u32) -> (f32, f32, f32, f32) {
41    let a = ((c >> 24) & 0xFF) as f32 / 255.0;
42    let r = ((c >> 16) & 0xFF) as f32 / 255.0;
43    let g = ((c >>  8) & 0xFF) as f32 / 255.0;
44    let b = ( c        & 0xFF) as f32 / 255.0;
45    (r, g, b, a)
46}
47
48fn quad(verts: &mut Vec<Vert>, x: f32, y: f32, w: f32, h: f32,
49        u0: f32, v0: f32, u1: f32, v1: f32, color: u32) {
50    let (r, g, b, a) = rgba_f(color);
51    let p = [
52        Vert { x,        y,        u: u0, v: v0, r, g, b, a },
53        Vert { x: x+w,   y,        u: u1, v: v0, r, g, b, a },
54        Vert { x,        y: y+h,   u: u0, v: v1, r, g, b, a },
55        Vert { x: x+w,   y: y+h,   u: u1, v: v1, r, g, b, a },
56    ];
57    // two triangles: 0,1,2  1,3,2
58    verts.extend_from_slice(&[p[0], p[1], p[2], p[1], p[3], p[2]]);
59}
60
61// ── GLSL shaders ─────────────────────────────────────────────────────────────
62
63const VERT: &str = r#"
64#version 330 core
65layout(location = 0) in vec2 aPos;
66layout(location = 1) in vec2 aUv;
67layout(location = 2) in vec4 aCol;
68out vec2 fUv;
69out vec4 fCol;
70uniform vec2 uScreen;
71void main() {
72    fUv  = aUv;
73    fCol = aCol;
74    vec2 ndc = aPos / uScreen * 2.0 - vec2(1.0);
75    gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
76}
77"#;
78
79const FRAG: &str = r#"
80#version 330 core
81in vec2 fUv;
82in vec4 fCol;
83out vec4 outColor;
84uniform sampler2D uTex;
85uniform int uMode;  // 0 = solid color, 1 = RGBA texture, 2 = alpha-only (font)
86void main() {
87    if (uMode == 0) {
88        outColor = fCol;
89    } else if (uMode == 1) {
90        outColor = texture(uTex, fUv) * fCol;
91    } else {
92        float alpha = texture(uTex, fUv).a;
93        outColor = vec4(fCol.rgb, fCol.a * alpha);
94    }
95}
96"#;
97
98// ── Embedded textures ─────────────────────────────────────────────────────────
99
100static BOOK_PNG:     &[u8] = include_bytes!("../assets/book_brown.png");
101static CRAFTING_PNG: &[u8] = include_bytes!("../assets/crafting.png");
102
103fn decode_png(data: &[u8]) -> Option<(Vec<u8>, u32, u32)> {
104    use png::Decoder;
105    let decoder = Decoder::new(std::io::Cursor::new(data));
106    let mut reader = decoder.read_info().ok()?;
107    let mut buf = vec![0u8; reader.output_buffer_size()];
108    let info = reader.next_frame(&mut buf).ok()?;
109    let rgba = match info.color_type {
110        png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
111        png::ColorType::Rgb  => {
112            let rgb = &buf[..info.buffer_size()];
113            let mut out = Vec::with_capacity(rgb.len() / 3 * 4);
114            for px in rgb.chunks(3) { out.extend_from_slice(px); out.push(255); }
115            out
116        }
117        _ => return None,
118    };
119    Some((rgba, info.width, info.height))
120}
121
122// ── GL resource cache ─────────────────────────────────────────────────────────
123
124struct BookGl {
125    prog:         gl::ShaderProgram,
126    vao:          gl::VertexArray,
127    vbo:          gl::Buffer,
128    book_tex:     Option<(gl::Texture, u32, u32)>,
129    crafting_tex: Option<(gl::Texture, u32, u32)>,
130    svg_tex:      HashMap<u64, (gl::Texture, u32, u32)>,
131    font_atlas:   HashMap<u64, (gl::Texture, FontAtlas)>,
132    /// item id → resolved MC texture handle (0 = no texture found).
133    mc_item_tex:  HashMap<String, u32>,
134}
135
136impl BookGl {
137    fn init(ctx: &GfxContext) -> Option<Self> {
138        let prog = ctx.create_shader(VERT, FRAG).ok()?;
139        let vbo  = ctx.create_buffer();
140        let vao  = ctx.create_vao();
141
142        const STRIDE: u32 = 32; // 8 × f32
143        vao.attrib(ctx, &vbo, 0, 2, DataType::F32, false, STRIDE, 0);  // pos
144        vao.attrib(ctx, &vbo, 1, 2, DataType::F32, false, STRIDE, 8);  // uv
145        vao.attrib(ctx, &vbo, 2, 4, DataType::F32, false, STRIDE, 16); // col
146
147        let load = |data: &[u8]| decode_png(data).map(|(rgba, w, h)| {
148            let tex = ctx.create_texture_rgba(w, h, &rgba, true);
149            (tex, w, h)
150        });
151        let book_tex     = load(BOOK_PNG);
152        let crafting_tex = load(CRAFTING_PNG);
153
154        Some(BookGl { prog, vao, vbo, book_tex, crafting_tex,
155                      svg_tex: HashMap::new(), font_atlas: HashMap::new(),
156                      mc_item_tex: HashMap::new() })
157    }
158
159    fn svg_tex(&mut self, ctx: &GfxContext, hash: u64, data: &str, w: u32, h: u32)
160        -> Option<&(gl::Texture, u32, u32)>
161    {
162        if !self.svg_tex.contains_key(&hash) {
163            let pixels = svg::rasterize(data, w, h)?;
164            let tex = ctx.create_texture_rgba(w, h, &pixels, true);
165            self.svg_tex.insert(hash, (tex, w, h));
166        }
167        self.svg_tex.get(&hash)
168    }
169
170    fn flush(&self, ctx: &GfxContext, verts: &[Vert]) {
171        if verts.is_empty() { return; }
172        unsafe { self.vbo.upload(ctx, verts, true); }
173        ctx.draw_arrays(&self.vao, &self.prog, DrawMode::Triangles, 0, verts.len() as u32);
174    }
175}
176
177// ── Draw helpers ──────────────────────────────────────────────────────────────
178
179impl BookGl {
180    fn begin_frame(&self, ctx: &GfxContext, sw: f32, sh: f32) {
181        ctx.set_blend(true, blend::SRC_ALPHA, blend::ONE_MINUS_SRC_ALPHA);
182        ctx.set_depth(false, false);
183        self.prog.uniform_2f(ctx, "uScreen", sw, sh);
184        self.prog.uniform_1i(ctx, "uTex", 0);
185    }
186
187    /// Blit a subrect of a sprite sheet at an arbitrary screen position.
188    fn draw_book_sprite(&self, ctx: &GfxContext, spr: &BgSprite) {
189        let sheet = match spr.sheet {
190            SpriteSheet::Book     => &self.book_tex,
191            SpriteSheet::Crafting => &self.crafting_tex,
192        };
193        let Some((tex, tw, th)) = sheet else { return };
194        let u0 = spr.u  / *tw as f32;
195        let v0 = spr.v  / *th as f32;
196        let u1 = (spr.u + spr.uw) / *tw as f32;
197        let v1 = (spr.v + spr.uh) / *th as f32;
198        self.prog.uniform_1i(ctx, "uMode", 1);
199        ctx.bind_texture(0, tex);
200        let mut v = Vec::with_capacity(6);
201        quad(&mut v, spr.x, spr.y, spr.w, spr.h, u0, v0, u1, v1, 0xFF_FFFFFF);
202        self.flush(ctx, &v);
203    }
204
205    /// Blit the open-book background from the embedded book texture.
206    fn draw_book_bg(&self, ctx: &GfxContext, bx: f32, by: f32, bw: f32, bh: f32) {
207        let Some((tex, tw, th)) = &self.book_tex else { return };
208        let su = BK_W / *tw as f32;
209        let sv = BK_H / *th as f32;
210        self.prog.uniform_1i(ctx, "uMode", 1);
211        ctx.bind_texture(0, tex);
212        let mut v = Vec::with_capacity(6);
213        quad(&mut v, bx, by, bw, bh, 0.0, 0.0, su, sv, 0xFF_FFFFFF);
214        self.flush(ctx, &v);
215    }
216
217    /// Resolve an item id to an MC texture handle, trying item/ then block/
218    /// texture paths (block items have no flat item texture). Cached.
219    fn resolve_item_tex(&mut self, ctx: &GfxContext, item_id: &str) -> u32 {
220        if let Some(&h) = self.mc_item_tex.get(item_id) { return h; }
221        let (ns, path) = item_id.split_once(':').unwrap_or(("minecraft", item_id));
222        let candidates: Vec<String> = if path.starts_with("textures/") {
223            vec![format!("{ns}:{}.png", path.trim_end_matches(".png"))]
224        } else {
225            // Plain item name — "item/ruby_block" and "ruby_block" both resolve
226            // through the same chain (block items have no flat item texture).
227            let name = path.trim_start_matches("item/").trim_start_matches("block/");
228            vec![
229                format!("{ns}:textures/item/{name}.png"),
230                format!("{ns}:textures/block/{name}.png"),
231                format!("{ns}:textures/block/{name}_front.png"),
232                format!("{ns}:textures/block/{name}_top.png"),
233                format!("{ns}:textures/block/{name}_side.png"),
234            ]
235        };
236        let mut handle = 0u32;
237        for c in &candidates {
238            let t = ctx.texture_from_mc(c);
239            if t.handle != 0 { handle = t.handle; break; }
240        }
241        self.mc_item_tex.insert(item_id.to_owned(), handle);
242        handle
243    }
244
245    /// Draw a 16×16-style item icon from an MC-managed texture.
246    fn draw_mc_item(&mut self, ctx: &GfxContext, item_id: &str, x: f32, y: f32, w: f32, h: f32) {
247        let handle = self.resolve_item_tex(ctx, item_id);
248        if handle == 0 { return; }
249        self.prog.uniform_1i(ctx, "uMode", 1);
250        ctx.bind_texture(0, &gl::Texture { handle });
251        let mut v = Vec::with_capacity(6);
252        quad(&mut v, x, y, w, h, 0.0, 0.0, 1.0, 1.0, 0xFF_FFFFFF);
253        self.flush(ctx, &v);
254    }
255
256    fn draw_svg(&mut self, ctx: &GfxContext, data: &str, x: f32, y: f32, w: f32, h: f32) {
257        let hash = svg::svg_hash(data);
258        let tw = w as u32; let th = h as u32;
259        if let Some(&(tex, _, _)) = self.svg_tex(ctx, hash, data, tw, th) {
260            self.prog.uniform_1i(ctx, "uMode", 1);
261            ctx.bind_texture(0, &tex);
262            let mut v = Vec::with_capacity(6);
263            quad(&mut v, x, y, w, h, 0.0, 0.0, 1.0, 1.0, 0xFF_FFFFFF);
264            self.flush(ctx, &v);
265        }
266    }
267
268    fn draw_text_custom(&mut self, ctx: &GfxContext, ttf: &[u8], size_px: f32,
269                        text: &str, mut x: f32, y: f32, color: u32) {
270        let hash = font_hash(ttf);
271        if !self.font_atlas.contains_key(&hash) {
272            if let Some(atlas) = FontAtlas::build(ttf, size_px) {
273                let tex = ctx.create_texture_rgba(
274                    atlas.atlas_size, atlas.atlas_size, &atlas.pixels, true);
275                self.font_atlas.insert(hash, (tex, atlas));
276            }
277        }
278        // Get raw pointers so the borrow of self.font_atlas ends before we call
279        // self.prog / self.flush, which also borrow fields of self.
280        let ptrs = self.font_atlas.get(&hash)
281            .map(|(t, a)| (t as *const gl::Texture, a as *const FontAtlas));
282        if let Some((tex_ptr, atlas_ptr)) = ptrs {
283            // SAFETY: we hold &mut self; font_atlas is not mutated below.
284            let tex   = unsafe { &*tex_ptr   };
285            let atlas = unsafe { &*atlas_ptr };
286            self.prog.uniform_1i(ctx, "uMode", 2);
287            ctx.bind_texture(0, tex);
288            let baseline = y + size_px;
289            let mut verts = Vec::new();
290            for ch in text.chars() {
291                if let Some(g) = atlas.glyphs.get(&ch) {
292                    if g.width > 0 {
293                        let gx = x + g.xoff;
294                        let gy = baseline - g.yoff - g.height as f32;
295                        quad(&mut verts, gx, gy, g.width as f32, g.height as f32,
296                             g.u0, g.v0, g.u1, g.v1, color);
297                    }
298                    x += g.advance;
299                }
300            }
301            self.flush(ctx, &verts);
302        }
303    }
304}
305
306fn font_hash(data: &[u8]) -> u64 {
307    use std::hash::{Hash, Hasher};
308    let mut h = std::collections::hash_map::DefaultHasher::new();
309    data.hash(&mut h);
310    h.finish()
311}
312
313// ── Background sprite (texture blit, drawn before yog-ui) ────────────────────
314
315#[derive(Clone, Copy, PartialEq)]
316pub(crate) enum SpriteSheet { Book, Crafting }
317
318/// A subrect blit from one of the embedded sprite sheets, drawn before yog-ui.
319#[derive(Clone)]
320pub(crate) struct BgSprite {
321    pub sheet: SpriteSheet,
322    /// Source rect in pixels on the sheet.
323    pub u: f32, pub v: f32, pub uw: f32, pub uh: f32,
324    /// Destination on screen.
325    pub x: f32, pub y: f32, pub w: f32, pub h: f32,
326}
327
328// ── Pending overlay draw commands ─────────────────────────────────────────────
329
330#[derive(Clone)]
331pub(crate) enum OverlayCmd {
332    Svg    { data: String, x: f32, y: f32, w: f32, h: f32 },
333    Text   { text: String, font: crate::font::BookFont, x: f32, y: f32, color: u32 },
334    /// MC default-font text rendered via draw2d (e.g. nameplate title/subtitle).
335    McText { text: String, x: f32, y: f32, color: u32 },
336    /// Item icon rendered through our GL pipeline from an MC-managed texture.
337    McItem { item_id: String, x: f32, y: f32, w: f32, h: f32 },
338}
339
340// ── Recipe visuals (parsed from registered recipe JSON) ───────────────────────
341
342#[derive(Clone)]
343pub(crate) enum RecipeVis {
344    Shaped    { grid: Vec<Option<String>>, width: usize, output: String, count: u32 },
345    Shapeless { ingredients: Vec<String>, output: String, count: u32 },
346    Smelting  { input: String, output: String },
347}
348
349fn parse_recipe(json: &str) -> Option<RecipeVis> {
350    let v: serde_json::Value = serde_json::from_str(json).ok()?;
351    match v.get("type")?.as_str()? {
352        "minecraft:crafting_shaped" => {
353            let pattern: Vec<&str> = v.get("pattern")?.as_array()?
354                .iter().filter_map(|p| p.as_str()).collect();
355            let width = pattern.iter().map(|r| r.chars().count()).max()?.max(1);
356            let key = v.get("key")?.as_object()?;
357            let mut grid = Vec::new();
358            for row in &pattern {
359                let mut chars: Vec<char> = row.chars().collect();
360                chars.resize(width, ' ');
361                for ch in chars {
362                    grid.push(key.get(&ch.to_string())
363                        .and_then(|k| k.get("item")).and_then(|i| i.as_str())
364                        .map(str::to_owned));
365                }
366            }
367            let result = v.get("result")?;
368            Some(RecipeVis::Shaped {
369                grid, width,
370                output: result.get("item")?.as_str()?.to_owned(),
371                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
372            })
373        }
374        "minecraft:crafting_shapeless" => {
375            let ingredients = v.get("ingredients")?.as_array()?.iter()
376                .filter_map(|i| i.get("item").and_then(|x| x.as_str()).map(str::to_owned))
377                .collect();
378            let result = v.get("result")?;
379            Some(RecipeVis::Shapeless {
380                ingredients,
381                output: result.get("item")?.as_str()?.to_owned(),
382                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
383            })
384        }
385        "minecraft:smelting" | "minecraft:blasting"
386        | "minecraft:smoking" | "minecraft:campfire_cooking" => {
387            Some(RecipeVis::Smelting {
388                input:  v.get("ingredient")?.get("item")?.as_str()?.to_owned(),
389                output: v.get("result")?.as_str()?.to_owned(),
390            })
391        }
392        _ => None,
393    }
394}
395
396/// "yog:ruby_block" → "Ruby Block" (fallback display name from an item id).
397fn pretty_item_name(id: &str) -> String {
398    let name = id.rsplit(':').next().unwrap_or(id);
399    name.split('_')
400        .map(|w| {
401            let mut c = w.chars();
402            match c.next() {
403                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
404                None    => String::new(),
405            }
406        })
407        .collect::<Vec<_>>()
408        .join(" ")
409}
410
411// ── BookRenderer ──────────────────────────────────────────────────────────────
412
413pub struct BookRenderer {
414    pub book:  Book,
415    pub state: BookViewState,
416    pub theme: BookTheme,
417    fonts:        BookFontRegistry,
418    recipes:      HashMap<String, RecipeVis>,
419    gl:           Option<BookGl>,
420    pub ui:       Option<UiRoot>,
421    bg_sprites:   Vec<BgSprite>,
422    overlays:     Vec<OverlayCmd>,
423    dirty:   bool,
424    last_sw: f32,
425    last_sh: f32,
426}
427
428impl BookRenderer {
429    pub fn new(book: Book) -> Self {
430        let theme = BookTheme::default().with_nameplate(&book.nameplate_color);
431        Self {
432            book,
433            state: BookViewState::default(),
434            theme,
435            fonts: BookFontRegistry::default(),
436            recipes: HashMap::new(),
437            gl: None,
438            ui: None,
439            bg_sprites: Vec::new(),
440            overlays: Vec::new(),
441            dirty: true,
442            last_sw: 0.0,
443            last_sh: 0.0,
444        }
445    }
446
447    pub fn handle_event(&mut self, ev: &str) {
448        if self.state.handle(ev, &self.book) {
449            self.dirty = true;
450        }
451    }
452
453    /// Register a custom TTF/OTF font for use in `BookPage::CustomText`.
454    pub fn register_font(&mut self, id: impl Into<String>, ttf: Vec<u8>) {
455        self.fonts.register(id, ttf);
456    }
457
458    /// Register a recipe (vanilla recipe JSON) so Crafting/Smelting pages can
459    /// render it visually. Unknown recipe types are ignored.
460    pub fn add_recipe(&mut self, id: impl Into<String>, json: &str) {
461        if let Some(vis) = parse_recipe(json) {
462            self.recipes.insert(id.into(), vis);
463            self.dirty = true;
464        }
465    }
466
467    pub fn render(&mut self, ctx: &GfxContext, sw: f32, sh: f32) {
468        // Lazy GL init.
469        if self.gl.is_none() {
470            self.gl = BookGl::init(ctx);
471        }
472
473        // Render at Patchouli-native size (272×180 GUI pixels). Scale DOWN only
474        // if the screen is smaller; never scale up (MC font is designed for 1×).
475        let scale = ((sw - 16.0) / BK_W).min((sh - 16.0) / BK_H).min(1.0).max(0.4);
476        let bw = BK_W * scale;
477        let bh = BK_H * scale;
478        let bx = (sw - bw) / 2.0;
479        let by = (sh - bh) / 2.0;
480
481        // Rebuild widget tree if dirty or screen resized.
482        if self.dirty || sw != self.last_sw || sh != self.last_sh {
483            let (root, bg_sprites, overlays) = build_ui(&self.book, &self.state, &self.theme, &self.recipes, sw, sh, bx, by, bw, bh);
484            self.ui = Some(root);
485            self.bg_sprites = bg_sprites;
486            self.overlays = overlays;
487            self.dirty = false;
488            self.last_sw = sw;
489            self.last_sh = sh;
490        }
491
492        // 1. Draw book background texture first.
493        if let Some(gl) = &mut self.gl {
494            gl.begin_frame(ctx, sw, sh);
495            gl.draw_book_bg(ctx, bx, by, bw, bh);
496        }
497
498        // 1b. Background sprites (nameplate banner, separator lines) from book texture.
499        if let Some(gl) = &mut self.gl {
500            for spr in &self.bg_sprites {
501                gl.draw_book_sprite(ctx, spr);
502            }
503        }
504
505        // 2. yog-ui: text, buttons, icons (transparent BG — texture is already there).
506        if let Some(ui) = &mut self.ui {
507            if ui.needs_layout { ui.layout(sw, sh); }
508            ui.render(ctx);
509        }
510
511        // 3. Custom GL overlays (SVG icons, custom font text).
512        if let Some(gl) = &mut self.gl {
513            gl.begin_frame(ctx, sw, sh);
514            for ov in self.overlays.clone() {
515                match ov {
516                    OverlayCmd::Svg  { data, x, y, w, h } =>
517                        gl.draw_svg(ctx, &data, x, y, w, h),
518                    OverlayCmd::Text { text, font, x, y, color } => {
519                        if let Some(ttf) = self.fonts.get(&font.font_id) {
520                            gl.draw_text_custom(ctx, ttf, font.size_px, &text, x, y, color);
521                        }
522                    }
523                    OverlayCmd::McText { text, x, y, color } => {
524                        ctx.draw2d().text(&text, x, y, color, false);
525                    }
526                    OverlayCmd::McItem { item_id, x, y, w, h } => {
527                        gl.draw_mc_item(ctx, &item_id, x, y, w, h);
528                    }
529                }
530            }
531        }
532    }
533}
534
535// ── UI builder ────────────────────────────────────────────────────────────────
536
537/// Book label: MC font, no drop-shadow (Patchouli draws book text shadowless).
538fn lbl(text: impl Into<String>) -> widget::Widget { widget::label(text).shadow(false) }
539/// Book button: no drop-shadow.
540fn btn(text: impl Into<String>) -> widget::Widget { widget::button(text).shadow(false) }
541
542/// Build the yog-ui widget tree + bg sprites + overlay commands for the current book state.
543/// `bx/by/bw/bh` are the screen-space book rect (same values used to blit the bg texture).
544fn build_ui(book: &Book, state: &BookViewState, theme: &BookTheme,
545             recipes: &HashMap<String, RecipeVis>,
546             sw: f32, sh: f32,
547             bx: f32, by: f32, bw: f32, bh: f32) -> (UiRoot, Vec<BgSprite>, Vec<OverlayCmd>) {
548    let _ = (sw, sh);
549    let mut bg_sprites: Vec<BgSprite> = Vec::new();
550    let mut overlays:   Vec<OverlayCmd> = Vec::new();
551
552    // Scale from Patchouli's fixed BK_W×BK_H coordinate space → actual bw×bh.
553    let sx = bw / BK_W;
554    let sy = bh / BK_H;
555
556    // In book-local: left page starts at x=LEFT_X, right at RIGHT_X, both y=TOP_PAD.
557    let pw = PAGE_W * sx;
558    let ph = PAGE_H * sy;
559    let spine_gap = (RIGHT_X - LEFT_X - PAGE_W) * sx; // ≈10px scaled
560
561    // Content x/y in screen space (for SVG overlay positioning).
562    let lx = bx + LEFT_X  * sx;
563    let rx = bx + RIGHT_X * sx;
564    let py = by + TOP_PAD  * sy;
565
566    // Separator x offset within a page: centered = PAGE_W/2 - SEP_W/2 = 58-55 = 3.
567    let sep_cx = (PAGE_W / 2.0 - SEP_W / 2.0) * sx; // = 3*sx
568
569    if state.at_home {
570        // Nameplate banner: book-local (-8, 12) from LEFT_PAGE_X, size 140×31.
571        bg_sprites.push(BgSprite {
572            sheet: SpriteSheet::Book,
573            u: 0.0, v: 180.0, uw: 140.0, uh: 31.0,
574            x: bx + (LEFT_X - 8.0) * sx,
575            y: by + 12.0 * sy,
576            w: 140.0 * sx,
577            h: 31.0 * sy,
578        });
579        // Separator below "Categories" header on right page (y=12 page-local), centered.
580        bg_sprites.push(BgSprite {
581            sheet: SpriteSheet::Book,
582            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
583            x: rx + sep_cx,
584            y: by + (TOP_PAD + 12.0) * sy,
585            w: SEP_W * sx,
586            h: (SEP_H * sy).max(1.0),
587        });
588    } else {
589        // Entry view: separator on right page below category name (y=12 page-local).
590        bg_sprites.push(BgSprite {
591            sheet: SpriteSheet::Book,
592            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
593            x: rx + sep_cx,
594            y: by + (TOP_PAD + 12.0) * sy,
595            w: SEP_W * sx,
596            h: (SEP_H * sy).max(1.0),
597        });
598    }
599
600    let (left_page, right_page) = if state.at_home {
601        let l = build_landing_left(book, theme, pw, ph, lx, py, sx, sy, bx, by, &mut overlays);
602        let r = build_categories_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
603        (l, r)
604    } else {
605        let l = build_entry_left(book, state, theme, recipes, pw, ph, lx, py, sx, sy, sep_cx, &mut bg_sprites, &mut overlays);
606        let r = build_entries_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
607        (l, r)
608    };
609
610    // Root row spans the full book width.
611    // padding-left = LEFT_X*sx offsets both pages from the left cover edge.
612    // padding-top  = TOP_PAD*sy offsets from the header banner.
613    // spine_gap spacer sits between the two pages.
614    let root_widget = widget::panel(FlexDir::Row)
615        .w(bw).h(bh)
616        .padding(TOP_PAD * sy, 0.0, 0.0, LEFT_X * sx)
617        .child(left_page)
618        .child(widget::spacer().w(spine_gap))  // spine gap
619        .child(right_page);
620
621    // Outer shell: positions the book on screen via a full-screen transparent Row.
622    // We use a Column + Row arrangement to apply top/left offsets without margin support.
623    let outer = widget::panel(FlexDir::Column)
624        .w(bw).h(bh)
625        .child(root_widget);
626
627    // Screen-level container: positions book at (bx, by).
628    // bx offset via padding, by offset via padding-top.
629    // Note: layout computes from (0,0), so we pass bx/by into the UiRoot manually
630    // by wrapping in a full-screen panel with the right padding.
631    let screen_root = widget::panel(FlexDir::Row)
632        .padding(by, 0.0, 0.0, bx)
633        .child(outer);
634
635    let ui = UiRoot::new(&book.id, screen_root);
636    (ui, bg_sprites, overlays)
637}
638
639// ── Left page: landing (home view) ───────────────────────────────────────────
640
641fn build_landing_left(
642    book: &Book, theme: &BookTheme,
643    page_w: f32, page_h: f32,
644    _lx: f32, _py: f32,
645    sx: f32, sy: f32,
646    bx: f32, by: f32,
647    overlays: &mut Vec<OverlayCmd>,
648) -> widget::Widget {
649    // Patchouli: title at book-local (13, 16), subtitle at (24, 24).
650    // These overlap the nameplate sprite which is above/within the page top.
651    overlays.push(OverlayCmd::McText {
652        text: book.name.clone(),
653        x: bx + 13.0 * sx,
654        y: by + 16.0 * sy,
655        color: theme.nameplate,
656    });
657    if let Some(author) = &book.author {
658        overlays.push(OverlayCmd::McText {
659            text: format!("by {}", author),
660            x: bx + 24.0 * sx,
661            y: by + 24.0 * sy,
662            color: theme.nameplate,
663        });
664    }
665
666    // Widget content: landing text + entry count.
667    // Landing text starts at page-local y=25 (= book-local y=43).
668    // We push it down with top padding = 25*sy.
669    let mut col = widget::panel(FlexDir::Column)
670        .w(page_w).h(page_h)
671        .padding(25.0 * sy, 6.0, 4.0, 4.0)
672        .gap(0.0);
673
674    for para in book.landing_text.split('\n') {
675        if para.is_empty() {
676            col = col.child(widget::spacer().h(4.0 * sy));
677        } else {
678            col = col.child(lbl(para).color(theme.text));
679        }
680    }
681
682    let total = book.entries.len();
683    col = col.child(widget::spacer().flex(1.0));
684    col = col.child(
685        lbl(format!("{} entries", total))
686            .color(theme.nav).h(9.0 * sy).align(Align::Center)
687    );
688    col
689}
690
691// ── Right page: category list (home view) ────────────────────────────────────
692
693fn build_categories_right(
694    book: &Book, state: &BookViewState, theme: &BookTheme,
695    page_w: f32, page_h: f32,
696    rx: f32, py: f32,
697    sx: f32, sy: f32,
698    overlays: &mut Vec<OverlayCmd>,
699) -> widget::Widget {
700    // Patchouli right-page layout (landing):
701    //   "Categories" header at page-local y=0, centered
702    //   Separator at page-local y=12 (drawn as bg sprite, not here)
703    //   4-column 24×24 icon grid starting at page-local (10, 25)
704    let cell_w = 24.0 * sx;
705    let cell_h = 24.0 * sy;
706    let grid_pad_left = 10.0 * sx;
707    let header_h = 9.0 * sy;
708
709    let mut col = widget::panel(FlexDir::Column)
710        .w(page_w).h(page_h)
711        .padding(0.0, 4.0, 4.0, 0.0)
712        .gap(0.0);
713
714    col = col.child(
715        lbl("Categories").color(theme.divider).h(header_h).align(Align::Center)
716    );
717    // Gap covering the separator region up to grid start (page-local y=25).
718    col = col.child(widget::spacer().h(25.0 * sy - header_h));
719
720    // 4-column icon grid; icons drawn as GL overlays at exact Patchouli positions.
721    let cats = &book.categories;
722    let icon_s = 16.0 * sx.min(sy);
723    let mut row_i = 0usize;
724    loop {
725        let row_start = row_i * 4;
726        if row_start >= cats.len() { break; }
727        let mut row = widget::panel(FlexDir::Row)
728            .h(cell_h)
729            .gap(0.0)
730            .padding(0.0, 0.0, 0.0, grid_pad_left);
731        for col_i in 0..4 {
732            let idx = row_start + col_i;
733            if idx >= cats.len() { break; }
734            let cat = &cats[idx];
735            let selected = !state.at_home && idx == state.cat;
736            let bg = if selected { theme.nav_selected_bg } else { 0 };
737
738            if let Some(icon_id) = &cat.icon {
739                overlays.push(OverlayCmd::McItem {
740                    item_id: icon_id.clone(),
741                    x: rx + (10.0 + col_i as f32 * 24.0 + 4.0) * sx,
742                    y: py + (25.0 + row_i as f32 * 24.0 + 4.0) * sy,
743                    w: icon_s, h: icon_s,
744                });
745            }
746            let cell = widget::panel(FlexDir::Column)
747                .w(cell_w).h(cell_h).bg(bg)
748                .on_click(format!("cat:{}", idx))
749                .id(format!("book_cat_{}", idx));
750            row = row.child(cell);
751        }
752        col = col.child(row);
753        row_i += 1;
754    }
755    col
756}
757
758// ── Left page: entry content (entry view) ────────────────────────────────────
759
760fn build_entry_left(
761    book: &Book, state: &BookViewState, theme: &BookTheme,
762    recipes: &HashMap<String, RecipeVis>,
763    page_w: f32, page_h: f32,
764    ox: f32, oy: f32,
765    sx: f32, sy: f32,
766    sep_cx: f32,
767    bg_sprites: &mut Vec<BgSprite>,
768    overlays: &mut Vec<OverlayCmd>,
769) -> widget::Widget {
770    let entry      = state.current_entry(book);
771    let page       = entry.and_then(|e| e.pages.get(state.page));
772    let page_count = state.page_count(book);
773    let title_text = entry.map(|e| e.name.as_str()).unwrap_or("");
774
775    // Patchouli PageText page 0:
776    //   title centered at page-local (PAGE_W/2, 0)
777    //   separator at page-local (0, 12)  → centered ≡ sep_cx offset
778    //   text body at page-local (0, 22)
779    let title_h  = 9.0 * sy;
780    let sep_h_px = (SEP_H * sy).max(1.0);
781    let sep_y    = oy + 12.0 * sy;
782    let body_oy  = oy + 22.0 * sy;
783
784    bg_sprites.push(BgSprite {
785        sheet: SpriteSheet::Book,
786        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
787        x: ox + sep_cx, y: sep_y,
788        w: SEP_W * sx, h: sep_h_px,
789    });
790
791    let page_label = format!("{}/{}", state.page + 1, page_count);
792    let nav = widget::panel(FlexDir::Row)
793        .h(12.0 * sy).gap(4.0)
794        .padding(0.0, 2.0, 0.0, 2.0)
795        .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
796            .on_click("prev_page").id("prev_page"))
797        .child(lbl(&page_label).color(theme.nav).flex(1.0).align(Align::Center))
798        .child(btn("⌂").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
799            .on_click("home").id("book_home"))
800        .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
801            .on_click("next_page").id("next_page"));
802
803    let page_body = build_page(page, state.page, theme, recipes, bg_sprites, overlays, ox, body_oy, sx, sy);
804
805    widget::panel(FlexDir::Column)
806        .w(page_w).h(page_h)
807        .padding(0.0, 6.0, 4.0, 4.0)
808        .gap(0.0)
809        .child(lbl(title_text).color(theme.title).h(title_h).align(Align::Center))
810        .child(widget::spacer().h((12.0 - 9.0) * sy))  // gap: title end → sep start
811        .child(widget::spacer().h(sep_h_px))             // height occupied by sep sprite
812        .child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy)) // gap: sep end → body
813        .child(page_body)
814        .child(nav)
815}
816
817// ── Right page: entry list for selected category (entry view) ─────────────────
818
819fn build_entries_right(
820    book: &Book, state: &BookViewState, theme: &BookTheme,
821    page_w: f32, page_h: f32, rx: f32, py: f32,
822    sx: f32, sy: f32,
823    overlays: &mut Vec<OverlayCmd>,
824) -> widget::Widget {
825    let entries  = state.entries_visible(book);
826    let cat_name = book.categories.get(state.cat).map(|c| c.name.as_str()).unwrap_or("Entries");
827    let spread_count = state.list_spread_count(book);
828
829    // Patchouli GuiBookEntryList layout (right page):
830    //   category name at page-local y=0, centered
831    //   separator at page-local y=12 (drawn as bg sprite in build_ui)
832    //   entries start at page-local y=20, each h=11
833    let header_h   = 9.0 * sy;
834    let row_h      = 11.0 * sy;
835    let icon_size  = 8.0 * sx.min(sy);
836
837    let mut col = widget::panel(FlexDir::Column)
838        .w(page_w).h(page_h)
839        .padding(0.0, 4.0, 4.0, 0.0)
840        .gap(0.0);
841
842    col = col.child(lbl(cat_name).color(theme.divider).h(header_h).align(Align::Center));
843    // sep region: y=9..15 (sep h=3), then gap to entries start at y=20
844    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));    // gap to sep
845    col = col.child(widget::spacer().h((SEP_H * sy).max(1.0))); // sep height
846    col = col.child(widget::spacer().h((20.0 - 12.0 - SEP_H) * sy)); // gap to entries
847
848    let abs_start = state.list_spread_start();
849    for (i, entry) in entries.iter().enumerate() {
850        let abs_i    = abs_start + i;
851        let selected = abs_i == state.entry;
852        let bg    = if selected { theme.nav_selected_bg } else { 0 };
853        let color = if selected { theme.nav_selected } else { theme.nav };
854
855        // Icon at page-local (1, 20 + i*11 + 1), 8×8 (Patchouli renders entry
856        // icons at 0.5× scale).
857        if let Some(icon_id) = &entry.icon {
858            overlays.push(OverlayCmd::McItem {
859                item_id: icon_id.clone(),
860                x: rx + 1.0 * sx,
861                y: py + (20.0 + i as f32 * 11.0 + 1.0) * sy,
862                w: icon_size, h: icon_size,
863            });
864        }
865
866        let mut row = widget::panel(FlexDir::Row)
867            .h(row_h).gap(2.0).bg(bg)
868            .on_click(format!("entry:{}", abs_i))
869            .id(format!("book_entry_{}", abs_i))
870            .padding(1.0, 2.0, 1.0, 2.0);
871
872        row = row.child(widget::spacer().w(icon_size + 2.0));
873        row = row.child(lbl(&entry.name).color(color).flex(1.0));
874        col = col.child(row);
875    }
876
877    if spread_count > 1 {
878        col = col.child(widget::spacer().flex(1.0));
879        let spread_label = format!("{}/{}", state.list_spread + 1, spread_count);
880        col = col.child(
881            widget::panel(FlexDir::Row).h(12.0 * sy).gap(2.0)
882                .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
883                    .on_click("prev_list").id("prev_list"))
884                .child(lbl(&spread_label).color(theme.nav)
885                    .flex(1.0).align(Align::Center))
886                .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
887                    .on_click("next_list").id("next_list"))
888        );
889    }
890    col
891}
892
893/// Draw a Patchouli-style crafting recipe: title, 100×62 grid background
894/// (UV 0,0 on the crafting sheet), 3×N ingredient icons, output item.
895/// `rx0`/`ry` are body-local recipe origin; `ox`/`oy` the body screen origin.
896#[allow(clippy::too_many_arguments)]
897fn draw_crafting_grid(
898    theme: &BookTheme,
899    bg_sprites: &mut Vec<BgSprite>,
900    overlays: &mut Vec<OverlayCmd>,
901    col: &mut widget::Widget,
902    grid: &[Option<String>], width: usize,
903    output: &str, count: u32, shapeless: bool,
904    ox: f32, oy: f32, rx0: f32, ry: f32, sx: f32, sy: f32,
905) {
906    let mut c = std::mem::replace(col, widget::panel(FlexDir::Column));
907    c = c.child(lbl(pretty_item_name(output)).color(theme.title)
908        .h(10.0 * sy).align(Align::Center));
909
910    // Grid background: blit at (rx0-2, ry-2) size 100×62, UV(0,0).
911    bg_sprites.push(BgSprite {
912        sheet: SpriteSheet::Crafting,
913        u: 0.0, v: 0.0, uw: 100.0, uh: 62.0,
914        x: ox + (rx0 - 2.0) * sx, y: oy + (ry - 2.0) * sy,
915        w: 100.0 * sx, h: 62.0 * sy,
916    });
917    // Shapeless marker: UV(0,64) 11×11 at (rx0+62, ry+2).
918    if shapeless {
919        bg_sprites.push(BgSprite {
920            sheet: SpriteSheet::Crafting,
921            u: 0.0, v: 64.0, uw: 11.0, uh: 11.0,
922            x: ox + (rx0 + 62.0) * sx, y: oy + (ry + 2.0) * sy,
923            w: 11.0 * sx, h: 11.0 * sy,
924        });
925    }
926
927    let icon_s = 16.0 * sx.min(sy);
928    let width = width.max(1);
929    for (i, slot) in grid.iter().enumerate() {
930        if let Some(item) = slot {
931            overlays.push(OverlayCmd::McItem {
932                item_id: item.clone(),
933                x: ox + (rx0 + 3.0 + (i % width) as f32 * 19.0) * sx,
934                y: oy + (ry  + 3.0 + (i / width) as f32 * 19.0) * sy,
935                w: icon_s, h: icon_s,
936            });
937        }
938    }
939    // Output item at (rx0+79, ry+22); stack count below it when > 1.
940    overlays.push(OverlayCmd::McItem {
941        item_id: output.to_owned(),
942        x: ox + (rx0 + 79.0) * sx, y: oy + (ry + 22.0) * sy,
943        w: icon_s, h: icon_s,
944    });
945    if count > 1 {
946        overlays.push(OverlayCmd::McText {
947            text: format!("x{}", count),
948            x: ox + (rx0 + 81.0) * sx, y: oy + (ry + 40.0) * sy,
949            color: theme.title,
950        });
951    }
952
953    // Spacer from title end (10) to below the grid (ry+62+4).
954    c = c.child(widget::spacer().h((ry + 62.0 + 4.0 - 10.0) * sy));
955    *col = c;
956}
957
958// ── Page content builder ──────────────────────────────────────────────────────
959
960/// Build the content widget for a single page.
961/// `ox/oy` = screen top-left of the page body area.
962/// `sx/sy` = book-local-to-screen scale factors.
963fn build_page(
964    page: Option<&BookPage>,
965    page_num: usize,
966    theme: &BookTheme,
967    recipes: &HashMap<String, RecipeVis>,
968    bg_sprites: &mut Vec<BgSprite>,
969    overlays: &mut Vec<OverlayCmd>,
970    ox: f32, oy: f32,
971    sx: f32, sy: f32,
972) -> widget::Widget {
973    let mut col = widget::panel(FlexDir::Column).flex(1.0).gap(4.0);
974
975    let Some(page) = page else {
976        return col.child(lbl("No entries yet.").color(theme.nav));
977    };
978
979    match page {
980        BookPage::Text { text, title } => {
981            // On non-first pages, show an optional section title + separator.
982            if page_num > 0 {
983                if let Some(t) = title {
984                    let sep_h_px = (SEP_H * sy).max(1.0);
985                    let title_h  = 9.0 * sy;
986                    col = col.child(lbl(t.as_str()).color(theme.title)
987                        .h(title_h).align(Align::Center));
988                    // sep at y=12 page-local, centered
989                    bg_sprites.push(BgSprite {
990                        sheet: SpriteSheet::Book,
991                        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
992                        x: ox + (PAGE_W / 2.0 - SEP_W / 2.0) * sx,
993                        y: oy + 12.0 * sy,
994                        w: SEP_W * sx, h: sep_h_px,
995                    });
996                    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));
997                    col = col.child(widget::spacer().h(sep_h_px));
998                    col = col.child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy));
999                }
1000            }
1001            for para in text.split('\n') {
1002                col = col.child(lbl(para).color(theme.text));
1003            }
1004        }
1005
1006        BookPage::Spotlight { item, title, text } => {
1007            // Patchouli PageSpotlight (page-body-local coordinates):
1008            //   title at y=0 centered, item frame at (PAGE_W/2-33, 10) 66×26
1009            //   (UV 0,102 on the 128×256 crafting sheet), item at (PAGE_W/2-8, 15),
1010            //   text at y=40.
1011            bg_sprites.push(BgSprite {
1012                sheet: SpriteSheet::Crafting,
1013                u: 0.0, v: 102.0, uw: 66.0, uh: 26.0,
1014                x: ox + (PAGE_W / 2.0 - 33.0) * sx,
1015                y: oy + 10.0 * sy,
1016                w: 66.0 * sx, h: 26.0 * sy,
1017            });
1018
1019            let item_name = title.as_deref()
1020                .or(item.name.as_deref())
1021                .unwrap_or(item.id.as_str());
1022            col = col.child(lbl(item_name).color(theme.title)
1023                .h(10.0 * sy).align(Align::Center));
1024
1025            let icon_s = 16.0 * sx.min(sy);
1026            overlays.push(OverlayCmd::McItem {
1027                item_id: item.id.clone(),
1028                x: ox + (PAGE_W / 2.0 - 8.0) * sx,
1029                y: oy + 15.0 * sy,
1030                w: icon_s, h: icon_s,
1031            });
1032
1033            // Spacer from title end (y=10) to text start (y=40).
1034            col = col.child(widget::spacer().h(30.0 * sy));
1035
1036            if let Some(t) = text {
1037                col = col.child(lbl(t.as_str()).color(theme.text));
1038            }
1039        }
1040
1041        BookPage::Crafting { recipe_id, text } => {
1042            // Patchouli PageCrafting: recipe origin at page-local
1043            // (PAGE_W/2-49, 4); we place it in body-local coords below a title.
1044            let rx0 = PAGE_W / 2.0 - 49.0; // = 9
1045            let ry  = 12.0;                // body-local recipe y (title occupies 0..10)
1046            match recipes.get(recipe_id.as_str()) {
1047                Some(RecipeVis::Shaped { grid, width, output, count })  => {
1048                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1049                        grid, *width, output, *count, false, ox, oy, rx0, ry, sx, sy);
1050                }
1051                Some(RecipeVis::Shapeless { ingredients, output, count }) => {
1052                    let grid: Vec<Option<String>> =
1053                        ingredients.iter().cloned().map(Some).collect();
1054                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1055                        &grid, 3, output, *count, true, ox, oy, rx0, ry, sx, sy);
1056                }
1057                _ => {
1058                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1059                        .color(theme.nav));
1060                }
1061            }
1062            if let Some(t) = text {
1063                col = col.child(lbl(t.as_str()).color(theme.text));
1064            }
1065        }
1066
1067        BookPage::Smelting { recipe_id, text } => {
1068            // Patchouli PageSmelting: bg UV(11,71) 96×24, input at +4,+4,
1069            // output at +76,+4.
1070            let rx0 = PAGE_W / 2.0 - 49.0;
1071            let ry  = 12.0;
1072            match recipes.get(recipe_id.as_str()) {
1073                Some(RecipeVis::Smelting { input, output }) => {
1074                    col = col.child(lbl(pretty_item_name(output)).color(theme.title)
1075                        .h(10.0 * sy).align(Align::Center));
1076                    bg_sprites.push(BgSprite {
1077                        sheet: SpriteSheet::Crafting,
1078                        u: 11.0, v: 71.0, uw: 96.0, uh: 24.0,
1079                        x: ox + rx0 * sx, y: oy + ry * sy,
1080                        w: 96.0 * sx, h: 24.0 * sy,
1081                    });
1082                    let icon_s = 16.0 * sx.min(sy);
1083                    overlays.push(OverlayCmd::McItem {
1084                        item_id: input.clone(),
1085                        x: ox + (rx0 + 4.0) * sx, y: oy + (ry + 4.0) * sy,
1086                        w: icon_s, h: icon_s,
1087                    });
1088                    overlays.push(OverlayCmd::McItem {
1089                        item_id: output.clone(),
1090                        x: ox + (rx0 + 76.0) * sx, y: oy + (ry + 4.0) * sy,
1091                        w: icon_s, h: icon_s,
1092                    });
1093                    // Spacer from title end (10) to below the furnace strip (ry+24+4).
1094                    col = col.child(widget::spacer().h((ry + 24.0 + 4.0 - 10.0) * sy));
1095                }
1096                _ => {
1097                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1098                        .color(theme.nav));
1099                }
1100            }
1101            if let Some(t) = text {
1102                col = col.child(lbl(t.as_str()).color(theme.text));
1103            }
1104        }
1105
1106        BookPage::Image { texture, title, text, .. } => {
1107            if let Some(t) = title {
1108                col = col.child(lbl(t.as_str()).color(theme.title));
1109            }
1110            col = col.child(widget::mc_image(texture, 80.0, 80.0));
1111            if let Some(t) = text {
1112                col = col.child(lbl(t.as_str()).color(theme.text));
1113            }
1114        }
1115
1116        BookPage::Svg { data, title, text } => {
1117            if let Some(t) = title {
1118                col = col.child(lbl(t.as_str()).color(theme.title));
1119            }
1120            overlays.push(OverlayCmd::Svg { data: data.clone(), x: ox, y: oy, w: 64.0, h: 64.0 });
1121            col = col.child(widget::spacer().h(68.0));
1122            if let Some(t) = text {
1123                col = col.child(lbl(t.as_str()).color(theme.text));
1124            }
1125        }
1126
1127        BookPage::CustomText { text, font, color } => {
1128            overlays.push(OverlayCmd::Text {
1129                text: text.clone(), font: font.clone(), x: ox, y: oy, color: *color,
1130            });
1131            col = col.child(widget::spacer().h(font.size_px * 1.5));
1132        }
1133
1134        BookPage::Relations { entries, text } => {
1135            if let Some(t) = text {
1136                col = col.child(lbl(t.as_str()).color(theme.text));
1137            }
1138            col = col.child(lbl("See also:").color(theme.title));
1139            for e in entries {
1140                col = col.child(lbl(format!("• {}", e)).color(theme.nav));
1141            }
1142        }
1143
1144        BookPage::Entity { entity_type, name, text } => {
1145            let display = name.as_deref().unwrap_or(entity_type.as_str());
1146            col = col.child(lbl(display).color(theme.title));
1147            if let Some(t) = text {
1148                col = col.child(lbl(t.as_str()).color(theme.text));
1149            }
1150        }
1151
1152        BookPage::Pattern { op_id, input, output, text, .. } => {
1153            col = col.child(lbl(op_id.as_str()).color(theme.title));
1154            col = col.child(
1155                lbl(format!("{} → {}", input, output)).color(theme.nav)
1156            );
1157            if !text.is_empty() {
1158                col = col.child(lbl(text.as_str()).color(theme.text));
1159            }
1160        }
1161
1162        BookPage::Empty => {}
1163    }
1164
1165    col
1166}