diff --git a/crates/thing-core/src/layout/measure.rs b/crates/thing-core/src/layout/measure.rs index b0a226f..578940a 100644 --- a/crates/thing-core/src/layout/measure.rs +++ b/crates/thing-core/src/layout/measure.rs @@ -41,11 +41,17 @@ pub trait Measure { fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32); } -/// The largest length, in device px or cells, a style or a measure may state. f32 holds whole -/// numbers exactly up to 2^24 (about 1.6e7); past that, edges stop landing on whole pixels and -/// sums of several lengths approach the range where Taffy's arithmetic overflows. A length -/// beyond it is an invalid style value, and a larger measured size is clamped to it. -pub(super) const MAX_DEVICE: f32 = 1e7; +/// The largest length, in device px or cells, a style or a measure may state: 2^21 = 2,097,152. +/// f32 has 24 mantissa bits, so a coordinate below 2^24 is exact to a whole pixel and one below +/// 2^21 keeps 3 fractional bits, 1/8 px. A coordinate is a sum of lengths along an axis: eight +/// maximal siblings still sum below 2^24 (whole-pixel exact), and any run of siblings whose +/// extents sum below 2^21 keeps 1/8 px. A length beyond the bound is an invalid style value and a +/// larger measured size is clamped to it. +pub(super) const MAX_DEVICE: f32 = 2_097_152.0; + +/// The smallest nonzero extent a measure may state: 1/8 px, the precision the length bound +/// leaves. A smaller side is below the resolution layout keeps. +pub(super) const MIN_SIDE: f32 = 0.125; /// The one place logical units become device units and back: `k` device px per logical px /// (1 in Cells). Everything past this adapter, the style map and the solver included, is device. @@ -96,20 +102,22 @@ pub(super) fn measure_leaf( } /// The aspect ratio an Image keeps when stretched, from what its measure says unconstrained -/// (logical px). `Ok(None)` is no extent at all (0x0: nothing known yet). A side that is not -/// finite, negative, past MAX_DEVICE, or only one side zero, or a ratio outside -/// [1/MAX_DEVICE, MAX_DEVICE] (so that ratio times a legal side stays finite and whole-pixel -/// arithmetic holds) is an invalid measure: `Err`. -pub(super) fn intrinsic_ratio(measure: &mut dyn Measure, leaf: &Leaf) -> Result, ()> { +/// (logical px, judged in device px). `Ok(None)` is no extent at all (0x0: nothing known yet). +/// Each side must be 0 or within [MIN_SIDE, MAX_DEVICE] and not just one of them zero; the ratio +/// is then within [MIN_SIDE / MAX_DEVICE, MAX_DEVICE / MIN_SIDE] = [2^-24, 2^24] by derivation, so +/// no second range is checked. Anything else is an invalid measure: `Err`. A side the image takes +/// from its ratio is held under MAX_DEVICE by the image's own max size (see the walk). +pub(super) fn intrinsic_ratio(measure: &mut dyn Measure, leaf: &Leaf, dev: Device) -> Result, ()> { let constraint = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] }; let (w, h) = measure.measure(leaf, constraint); - let legal = |v: f32| v.is_finite() && (0.0..=MAX_DEVICE).contains(&v); + let (w, h) = (dev.px(w), dev.px(h)); + let legal = |v: f32| v == 0.0 || (v.is_finite() && (MIN_SIDE..=MAX_DEVICE).contains(&v)); if !legal(w) || !legal(h) { return Err(()); } - if w == 0.0 && h == 0.0 { - return Ok(None); + match (w == 0.0, h == 0.0) { + (true, true) => Ok(None), + (false, false) => Ok(Some(w / h)), + _ => Err(()), } - let ratio = w / h; - if w > 0.0 && h > 0.0 && (1.0 / MAX_DEVICE..=MAX_DEVICE).contains(&ratio) { Ok(Some(ratio)) } else { Err(()) } } diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index 53fe6eb..dc365da 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -3,7 +3,7 @@ use taffy::{Style, TaffyTree}; use thing_contract::{Node, NodeId, Overflow}; -use super::measure::{Device, Leaf, intrinsic_ratio}; +use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio}; use super::style::{Invalid, box_style, embed_style}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; @@ -102,8 +102,11 @@ impl<'a> Builder<'a, '_> { let mut style = Style::default(); if matches!(leaf, Leaf::Image { .. }) { // A stretched image keeps its shape: the ratio is what the measure says it is unconstrained. + // Whatever its ratio derives, a side of the image stays within the length bound. + let bound = taffy::LengthPercentageAuto::length(MAX_DEVICE); + style.max_size = taffy::Size { width: bound, height: bound }; // An invalid measure leaves the image unconstrained (no ratio, not replaced) and is named. - match intrinsic_ratio(self.measure, &leaf) { + match intrinsic_ratio(self.measure, &leaf, self.dev) { Ok(ratio) => { style.item_is_replaced = true; style.aspect_ratio = ratio; diff --git a/crates/thing-core/tests/layout.rs b/crates/thing-core/tests/layout.rs index 1a0dc23..701949a 100644 --- a/crates/thing-core/tests/layout.rs +++ b/crates/thing-core/tests/layout.rs @@ -636,7 +636,7 @@ fn invalid_image_measures_are_named_and_harmless() { let root = || bx("root", BoxStyle { direction: Direction::Column, size: size2(px(200.0), Dimension::Auto), ..plain() }, vec![picture(), text("sibling", "hi")]); let tree = bind(&mut MemState::new(), &surface_of(root())).unwrap(); let run = |size| layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Image(size)).unwrap(); - for size in [(1e7, 1e-30), (1e-30, 1e7), (0.0, 5.0), (f32::NAN, 1.0), (f32::INFINITY, 1.0), (-1.0, 2.0), (1e8, 1e8)] { + for size in [(1e7, 1e-30), (1e-30, 1e7), (0.0, 5.0), (f32::NAN, 1.0), (f32::INFINITY, 1.0), (-1.0, 2.0), (1e8, 1e8), (1.0, 1e7), (1e-3, 5.0), (3e6, 3e6)] { let laid = run(size); assert_eq!(laid.diagnostics.len(), 1, "{size:?}"); let d = &laid.diagnostics[0]; @@ -749,9 +749,9 @@ fn extreme_values_never_panic() { assert!(laid.diagnostics.iter().all(|d| d.code == Code::StyleValueInvalid && d.node.is_some())); assert!(laid.diagnostics.iter().any(|d| d.node.as_ref().map(|n| n.as_str()) == Some("big-embed"))); // A length at the bound is legal; one past it is not. - let at = lay(bx("root", plain(), vec![bx("c", sized(1e7, 10.0), vec![])]), 800.0, 600.0); + let at = lay(bx("root", plain(), vec![bx("c", sized(2_097_152.0, 10.0), vec![])]), 800.0, 600.0); assert!(at.diagnostics.is_empty()); - let past = lay(bx("root", plain(), vec![bx("c", sized(1e7 + 1.0, 10.0), vec![])]), 800.0, 600.0); + let past = lay(bx("root", plain(), vec![bx("c", sized(2_097_153.0, 10.0), vec![])]), 800.0, 600.0); assert_eq!(past.diagnostics.len(), 1); // The bound is on device pixels: 6e6 logical px at scale 2 is past it. let scaled = lay_with(&mut MemState::new(), bx("root", plain(), vec![bx("c", sized(6e6, 10.0), vec![])]), &pixels(800.0, 600.0, 2.0)); @@ -767,7 +767,51 @@ fn extreme_values_never_panic() { let tree = bind(&mut MemState::new(), &surface_of(bx("root", plain(), vec![text("t", "x"), text("u", "y")]))).unwrap(); let laid = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Huge).unwrap(); assert_eq!(laid.nodes.len(), 3); - assert!(laid.nodes.iter().all(|n| n.rect.w <= 1e7 && n.rect.h <= 1e7), "{laid:?}"); + assert!(laid.nodes.iter().all(|n| n.rect.w <= 2_097_152.0 && n.rect.h <= 2_097_152.0), "{laid:?}"); +} + +#[test] +fn image_measures_never_resize_fixed_siblings() { + struct Image((f32, f32)); + impl Measure for Image { + fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) { + match leaf { + Leaf::Image { .. } => self.0, + _ => (8.0, 16.0), + } + } + } + let picture = || Node::Image(ImageNode { common: common("pic"), catalog: "c".into(), asset: "a".into(), fit: ImageFit::Fill, alt: lit_text("alt") }); + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + // Lengths are log-uniform over the allowed range, [1/8, 2^21], edges included. + let mut length = |next: &mut dyn FnMut() -> u64| { + let unit = (next() % 10_001) as f32 / 10_000.0; + (0.125f32 * (2_097_152.0f32 / 0.125).powf(unit)).clamp(0.125, 2_097_152.0) + }; + for round in 0..400 { + let size = if round % 7 == 0 { (length(&mut next), length(&mut next)) } else { (length(&mut next).min(4096.0), length(&mut next).min(4096.0)) }; + let direction = if round % 2 == 0 { Direction::Column } else { Direction::Row }; + let fixed = BoxStyle { shrink: 0.0, ..sized(30.0, 20.0) }; + let siblings = vec![embed("e1", 16.0, 12.0), picture(), bx("b1", fixed, vec![]), embed("e2", 7.0, 9.0)]; + for root_style in [plain(), sized(800.0, 600.0)] { + let root = bx("root", BoxStyle { direction: direction.clone(), ..root_style }, siblings.clone()); + let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap(); + let laid = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Image(size)).unwrap(); + assert!(laid.diagnostics.is_empty(), "{size:?}"); + for (id, w, h) in [("e1", 16.0, 12.0), ("b1", 30.0, 20.0), ("e2", 7.0, 9.0)] { + let r = rect(&laid, id); + assert_eq!((r.2, r.3), (w, h), "{id} with an image measuring {size:?}, {direction:?}"); + } + let pic = rect(&laid, "pic"); + assert!(pic.2 <= 2_097_152.0 && pic.3 <= 2_097_152.0, "{size:?} {pic:?}"); + } + } } #[test]