Skip to main content

takumi_core/
geometry.rs

1//! Transform geometry helpers shared across backends.
2
3use std::ops::{Add, Sub};
4
5use kurbo::PathSeg;
6#[cfg(feature = "svg")]
7use tiny_skia::PathSegment;
8use tiny_skia::{Path, PathBuilder as TinyPathBuilder};
9use xxhash_rust::xxh3::Xxh3;
10
11use crate::{layout_unit::LayoutUnit, style::Affine};
12
13/// The smallest difference between two layout values a browser can tell apart:
14/// Blink stores layout in 1/64px fixed point, so anything closer is one value
15/// there.
16/// <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/geometry/layout_unit.h>
17pub(crate) const LAYOUT_UNIT_EPSILON: f32 = 1.0 / 64.0;
18
19/// A 2D point.
20#[derive(Debug, Clone, Copy, PartialEq, Default)]
21pub struct Point<T> {
22  /// Horizontal coordinate.
23  pub x: T,
24  /// Vertical coordinate.
25  pub y: T,
26}
27
28impl<T> Point<T> {
29  /// Creates a point from its coordinates.
30  pub const fn new(x: T, y: T) -> Self {
31    Self { x, y }
32  }
33
34  /// A point with both coordinates `value`.
35  pub(crate) fn all(value: T) -> Self
36  where
37    T: Copy,
38  {
39    Self { x: value, y: value }
40  }
41
42  /// Maps both coordinates through `f`.
43  pub fn map<R>(self, f: impl Fn(T) -> R) -> Point<R> {
44    Point {
45      x: f(self.x),
46      y: f(self.y),
47    }
48  }
49}
50
51impl Point<f32> {
52  /// The origin.
53  pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
54}
55
56impl<U, T: Add<U>> Add<Point<U>> for Point<T> {
57  type Output = Point<<T as Add<U>>::Output>;
58
59  fn add(self, rhs: Point<U>) -> Self::Output {
60    Point {
61      x: self.x + rhs.x,
62      y: self.y + rhs.y,
63    }
64  }
65}
66
67impl<U, T: Sub<U>> Sub<Point<U>> for Point<T> {
68  type Output = Point<<T as Sub<U>>::Output>;
69
70  fn sub(self, rhs: Point<U>) -> Self::Output {
71    Point {
72      x: self.x - rhs.x,
73      y: self.y - rhs.y,
74    }
75  }
76}
77
78/// A 2D size.
79#[derive(Debug, Clone, Copy, PartialEq, Default)]
80pub struct Size<T> {
81  /// Width.
82  pub width: T,
83  /// Height.
84  pub height: T,
85}
86
87impl<T> Size<T> {
88  /// Creates a size from its dimensions.
89  pub const fn new(width: T, height: T) -> Self {
90    Self { width, height }
91  }
92
93  /// A size with both dimensions `value`.
94  pub(crate) fn all(value: T) -> Self
95  where
96    T: Copy,
97  {
98    Self {
99      width: value,
100      height: value,
101    }
102  }
103
104  /// Maps both dimensions through `f`.
105  pub fn map<R>(self, f: impl Fn(T) -> R) -> Size<R> {
106    Size {
107      width: f(self.width),
108      height: f(self.height),
109    }
110  }
111
112  /// Combines this size with `other` dimension-wise through `f`.
113  pub fn zip_map<O, R>(self, other: Size<O>, f: impl Fn(T, O) -> R) -> Size<R> {
114    Size {
115      width: f(self.width, other.width),
116      height: f(self.height, other.height),
117    }
118  }
119}
120
121impl Size<f32> {
122  /// A zero size.
123  pub const ZERO: Self = Self {
124    width: 0.0,
125    height: 0.0,
126  };
127
128  /// Whether both dimensions are finite and above zero.
129  pub fn has_area(self) -> bool {
130    self.width.is_finite() && self.height.is_finite() && self.width > 0.0 && self.height > 0.0
131  }
132
133  /// Shrinks by `inset` on each edge, clamped to zero.
134  pub fn inset(self, inset: Rect<f32>) -> Self {
135    Size {
136      width: (self.width - inset.left - inset.right).max(0.0),
137      height: (self.height - inset.top - inset.bottom).max(0.0),
138    }
139  }
140}
141
142impl<U, T: Add<U>> Add<Size<U>> for Size<T> {
143  type Output = Size<<T as Add<U>>::Output>;
144
145  fn add(self, rhs: Size<U>) -> Self::Output {
146    Size {
147      width: self.width + rhs.width,
148      height: self.height + rhs.height,
149    }
150  }
151}
152
153impl<U, T: Sub<U>> Sub<Size<U>> for Size<T> {
154  type Output = Size<<T as Sub<U>>::Output>;
155
156  fn sub(self, rhs: Size<U>) -> Self::Output {
157    Size {
158      width: self.width - rhs.width,
159      height: self.height - rhs.height,
160    }
161  }
162}
163
164impl Size<Option<f32>> {
165  /// A size with both dimensions unset.
166  pub const NONE: Self = Self {
167    width: None,
168    height: None,
169  };
170}
171
172/// A 2D rect defined by its four edges.
173#[derive(Debug, Clone, Copy, PartialEq, Default)]
174pub struct Rect<T> {
175  /// Left edge.
176  pub left: T,
177  /// Right edge.
178  pub right: T,
179  /// Top edge.
180  pub top: T,
181  /// Bottom edge.
182  pub bottom: T,
183}
184
185impl<T> Rect<T> {
186  /// A rect with all four edges `value`.
187  pub(crate) fn all(value: T) -> Self
188  where
189    T: Copy,
190  {
191    Self {
192      left: value,
193      right: value,
194      top: value,
195      bottom: value,
196    }
197  }
198
199  /// Maps all four edges through `f`.
200  pub fn map<R>(self, f: impl Fn(T) -> R) -> Rect<R> {
201    Rect {
202      left: f(self.left),
203      right: f(self.right),
204      top: f(self.top),
205      bottom: f(self.bottom),
206    }
207  }
208}
209
210impl<T: Add<Output = T> + Copy> Rect<T> {
211  /// Sum of the left and right edges.
212  pub fn horizontal(self) -> T {
213    self.left + self.right
214  }
215
216  /// Sum of the top and bottom edges.
217  pub fn vertical(self) -> T {
218    self.top + self.bottom
219  }
220}
221
222impl Rect<f32> {
223  /// A zero rect.
224  pub const ZERO: Self = Self {
225    left: 0.0,
226    right: 0.0,
227    top: 0.0,
228    bottom: 0.0,
229  };
230
231  /// The top-left corner as a point.
232  pub fn top_left(self) -> Point<f32> {
233    Point {
234      x: self.left,
235      y: self.top,
236    }
237  }
238
239  /// Per-side `self - rhs`, clamped to zero.
240  pub(crate) fn saturating_sub(self, rhs: Self) -> Self {
241    Rect {
242      top: (self.top - rhs.top).max(0.0),
243      right: (self.right - rhs.right).max(0.0),
244      bottom: (self.bottom - rhs.bottom).max(0.0),
245      left: (self.left - rhs.left).max(0.0),
246    }
247  }
248}
249
250#[cfg(feature = "svg-raster")]
251impl Rect<f32> {
252  /// The pixels the rect covers under `transform`, none unless they have area: the floor of the
253  /// origin and the ceiling of the size, as tiny-skia's `NonZeroRect::to_int_rect` rounds.
254  pub(crate) fn pixel_bounds(&self, transform: Affine) -> Option<Rect<i32>> {
255    let bounds = self.transformed(transform).filter(Self::has_area)?;
256    let (left, top) = (bounds.left.floor() as i32, bounds.top.floor() as i32);
257
258    Some(Rect {
259      left,
260      top,
261      right: left.checked_add((bounds.width().ceil() as i32).max(1))?,
262      bottom: top.checked_add((bounds.height().ceil() as i32).max(1))?,
263    })
264  }
265}
266
267#[cfg(feature = "svg-raster")]
268impl Rect<i32> {
269  /// The rect at `x`, `y` of `width` by `height` pixels.
270  pub(crate) fn from_size(x: i32, y: i32, width: u32, height: u32) -> Self {
271    Self {
272      left: x,
273      top: y,
274      right: x.saturating_add_unsigned(width),
275      bottom: y.saturating_add_unsigned(height),
276    }
277  }
278
279  pub(crate) fn width(&self) -> u32 {
280    self.right.abs_diff(self.left)
281  }
282
283  pub(crate) fn height(&self) -> u32 {
284    self.bottom.abs_diff(self.top)
285  }
286
287  /// The pixels both rects cover, none when there are none.
288  pub(crate) fn intersection(&self, other: &Self) -> Option<Self> {
289    let rect = Self {
290      left: self.left.max(other.left),
291      top: self.top.max(other.top),
292      right: self.right.min(other.right),
293      bottom: self.bottom.min(other.bottom),
294    };
295
296    (rect.left < rect.right && rect.top < rect.bottom).then_some(rect)
297  }
298
299  /// The rect moved by `dx` and `dy`.
300  pub(crate) fn translated(&self, dx: i32, dy: i32) -> Self {
301    Self {
302      left: self.left.saturating_add(dx),
303      top: self.top.saturating_add(dy),
304      right: self.right.saturating_add(dx),
305      bottom: self.bottom.saturating_add(dy),
306    }
307  }
308}
309
310#[cfg(feature = "svg")]
311impl Rect<f32> {
312  /// The rect between the edges, none unless it is finite and not inverted.
313  pub(crate) fn from_ltrb(left: f32, top: f32, right: f32, bottom: f32) -> Option<Self> {
314    let rect = Self {
315      left,
316      right,
317      top,
318      bottom,
319    };
320    let finite = [left, right, top, bottom, rect.width(), rect.height()]
321      .iter()
322      .all(|value| value.is_finite());
323
324    (finite && left <= right && top <= bottom).then_some(rect)
325  }
326
327  /// The rect at `x`, `y` of `width` by `height`, none unless it is finite and not inverted.
328  pub(crate) fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Option<Self> {
329    Self::from_ltrb(x, y, width + x, height + y)
330  }
331
332  /// [`Self::from_xywh`], but with both dimensions above zero.
333  pub(crate) fn positive_from_xywh(x: f32, y: f32, width: f32, height: f32) -> Option<Self> {
334    Self::from_xywh(x, y, width, height).filter(Self::has_area)
335  }
336
337  pub(crate) fn x(&self) -> f32 {
338    self.left
339  }
340
341  pub(crate) fn y(&self) -> f32 {
342    self.top
343  }
344
345  pub(crate) fn width(&self) -> f32 {
346    self.right - self.left
347  }
348
349  pub(crate) fn height(&self) -> f32 {
350    self.bottom - self.top
351  }
352
353  /// Whether the rect has both dimensions above zero.
354  pub(crate) fn has_area(&self) -> bool {
355    self.left < self.right && self.top < self.bottom
356  }
357
358  /// The smallest rect holding both.
359  pub(crate) fn union(&self, other: &Self) -> Self {
360    Self {
361      left: self.left.min(other.left),
362      right: self.right.max(other.right),
363      top: self.top.min(other.top),
364      bottom: self.bottom.max(other.bottom),
365    }
366  }
367
368  /// The bounds of the rect under `transform`, none when they are not finite.
369  pub(crate) fn transformed(&self, transform: Affine) -> Option<Self> {
370    let (left, top, right, bottom) = transformed_rect_extents(
371      self.top_left(),
372      Size::new(self.width(), self.height()),
373      transform,
374    )?;
375
376    Self::from_ltrb(left, top, right, bottom)
377  }
378
379  /// The edges as bits, to key a cache by the rect.
380  pub(crate) fn to_bits(self) -> [u32; 4] {
381    [self.left, self.top, self.right, self.bottom].map(f32::to_bits)
382  }
383
384  /// The rect with its coordinates read as fractions of `bbox`.
385  pub(crate) fn in_bounding_box(&self, bbox: &Self) -> Option<Self> {
386    Self::positive_from_xywh(
387      self.x() * bbox.width() + bbox.x(),
388      self.y() * bbox.height() + bbox.y(),
389      self.width() * bbox.width(),
390      self.height() * bbox.height(),
391    )
392  }
393
394  /// The transform that maps the unit square onto the rect.
395  pub(crate) fn unit_square_transform(&self) -> Affine {
396    Affine {
397      a: self.width(),
398      b: 0.0,
399      c: 0.0,
400      d: self.height(),
401      x: self.x(),
402      y: self.y(),
403    }
404  }
405}
406
407#[cfg(feature = "svg")]
408impl Size<f32> {
409  /// The size scaled to fit inside `target` keeping its ratio, or to cover it when `expand`, after
410  /// tiny-skia's `Size::scale_to` and `Size::expand_to`.
411  pub(crate) fn fitted_to(self, target: Self, expand: bool) -> Self {
412    let width = target.height * self.width / self.height;
413    let fits_height = if expand {
414      width <= target.width
415    } else {
416      width >= target.width
417    };
418
419    if fits_height {
420      Self::new(target.width, target.width * self.height / self.width)
421    } else {
422      Self::new(width, target.height)
423    }
424  }
425}
426
427/// The computed box geometry of a laid-out node, as backends read it.
428#[derive(Debug, Clone, Copy, PartialEq, Default)]
429pub struct ComputedLayout {
430  /// Top-left corner relative to the parent's content box.
431  pub location: Point<f32>,
432  /// Border-box width and height.
433  pub size: Size<f32>,
434  /// Border widths per side.
435  pub border: Rect<f32>,
436  /// Padding widths per side.
437  pub padding: Rect<f32>,
438}
439
440impl ComputedLayout {
441  /// A layout of `size` at `location`, with `border` and `padding` widths.
442  pub fn new(location: Point<f32>, size: Size<f32>, border: Rect<f32>, padding: Rect<f32>) -> Self {
443    Self {
444      location,
445      size,
446      border,
447      padding,
448    }
449  }
450
451  /// Content-box width: border-box width minus padding and border on both sides.
452  pub fn content_box_width(&self) -> f32 {
453    self.size.width - self.padding.left - self.padding.right - self.border.left - self.border.right
454  }
455
456  /// Content-box height: border-box height minus padding and border on both sides.
457  pub fn content_box_height(&self) -> f32 {
458    self.size.height - self.padding.top - self.padding.bottom - self.border.top - self.border.bottom
459  }
460
461  /// Padding-box width: border-box width minus the border on both sides.
462  pub fn padding_box_width(&self) -> f32 {
463    self.size.width - self.border.left - self.border.right
464  }
465
466  /// Padding-box height: border-box height minus the border on both sides.
467  pub fn padding_box_height(&self) -> f32 {
468    self.size.height - self.border.top - self.border.bottom
469  }
470
471  /// Content-box size.
472  pub fn content_box_size(&self) -> Size<f32> {
473    Size {
474      width: self.content_box_width(),
475      height: self.content_box_height(),
476    }
477  }
478
479  /// Offset of the content-box top-left from the border-box top-left, i.e. the left/top border plus
480  /// padding.
481  pub fn content_box_offset(&self) -> Point<f32> {
482    Point::new(
483      self.border.left + self.padding.left,
484      self.border.top + self.padding.top,
485    )
486  }
487}
488
489/// Opaque identifier for a node within a computed layout tree.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub struct NodeId(usize);
492
493impl NodeId {
494  /// The root of any layout tree; construction always assigns it index 0.
495  pub const ROOT: Self = Self(0);
496
497  /// The node at `index` in its layout tree.
498  pub(crate) const fn new(index: usize) -> Self {
499    Self(index)
500  }
501}
502
503impl From<NodeId> for usize {
504  fn from(id: NodeId) -> Self {
505    id.0
506  }
507}
508
509impl From<NodeId> for u64 {
510  fn from(id: NodeId) -> Self {
511    id.0 as u64
512  }
513}
514
515/// How much space is available along one axis during layout.
516#[derive(Debug, Clone, Copy, PartialEq)]
517pub enum AvailableSpace {
518  /// A definite amount of space, in pixels.
519  Definite(f32),
520  /// Indefinite space; the node should size to its minimum content.
521  MinContent,
522  /// Indefinite space; the node should size to its maximum content.
523  MaxContent,
524}
525
526impl AvailableSpace {
527  /// The space in layout units, none where indefinite.
528  pub(crate) fn definite(self) -> Option<LayoutUnit> {
529    match self {
530      Self::Definite(size) => Some(LayoutUnit::from_float(size)),
531      Self::MinContent | Self::MaxContent => None,
532    }
533  }
534}
535
536/// One command of a resolved outline path, in device space.
537#[derive(Debug, Clone, Copy, PartialEq)]
538pub enum PathCommand {
539  /// Starts a new subpath at the given point.
540  MoveTo(Point<f32>),
541  /// Draws a line to the given point.
542  LineTo(Point<f32>),
543  /// Draws a quadratic Bezier curve through the control point to the end point.
544  QuadTo(Point<f32>, Point<f32>),
545  /// Draws a cubic Bezier curve through the two control points to the end point.
546  CubicTo(Point<f32>, Point<f32>, Point<f32>),
547  /// Closes the current subpath.
548  Close,
549}
550
551impl PathCommand {
552  /// `paths` as a tiny-skia path; none for one with no segments.
553  pub fn build_path(paths: &[Self]) -> Option<Path> {
554    let mut builder = TinyPathBuilder::new();
555
556    for command in paths {
557      match command {
558        Self::MoveTo(point) => builder.move_to(point.x, point.y),
559        Self::LineTo(point) => builder.line_to(point.x, point.y),
560        Self::QuadTo(p1, p2) => builder.quad_to(p1.x, p1.y, p2.x, p2.y),
561        Self::CubicTo(p1, p2, p3) => {
562          builder.cubic_to(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
563        }
564        Self::Close => builder.close(),
565      }
566    }
567
568    builder.finish()
569  }
570
571  /// The closed rectangle at `x`, `y` of `width` by `height`.
572  #[cfg(feature = "svg")]
573  pub(crate) fn rectangle(x: f32, y: f32, width: f32, height: f32) -> Vec<Self> {
574    vec![
575      Self::MoveTo(Point::new(x, y)),
576      Self::LineTo(Point::new(x + width, y)),
577      Self::LineTo(Point::new(x + width, y + height)),
578      Self::LineTo(Point::new(x, y + height)),
579      Self::Close,
580    ]
581  }
582
583  /// The commands of a tiny-skia path.
584  #[cfg(feature = "svg")]
585  pub(crate) fn from_path(path: &Path) -> Vec<Self> {
586    let point = |point: tiny_skia::Point| Point::new(point.x, point.y);
587
588    path
589      .segments()
590      .map(|segment| match segment {
591        PathSegment::MoveTo(to) => Self::MoveTo(point(to)),
592        PathSegment::LineTo(to) => Self::LineTo(point(to)),
593        PathSegment::QuadTo(control, to) => Self::QuadTo(point(control), point(to)),
594        PathSegment::CubicTo(first, second, to) => {
595          Self::CubicTo(point(first), point(second), point(to))
596        }
597        PathSegment::Close => Self::Close,
598      })
599      .collect()
600  }
601
602  /// `paths` as tiny-skia's path builder normalizes them. None for commands that draw nothing.
603  #[cfg(feature = "svg")]
604  pub(crate) fn normalize(paths: &[Self]) -> Option<NormalizedPath> {
605    let path = Self::build_path(paths)?;
606    let edges = |bounds: tiny_skia::Rect| Rect {
607      left: bounds.left(),
608      right: bounds.right(),
609      top: bounds.top(),
610      bottom: bounds.bottom(),
611    };
612
613    Some(NormalizedPath {
614      commands: Self::from_path(&path),
615      bounds: edges(path.compute_tight_bounds()?),
616      control_bounds: edges(path.bounds()),
617    })
618  }
619
620  /// A digest of `paths`, which the same commands always give.
621  pub fn digest(paths: &[Self]) -> u64 {
622    let mut h = Xxh3::new();
623    let point = |h: &mut Xxh3, p: &Point<f32>| {
624      h.update(&p.x.to_le_bytes());
625      h.update(&p.y.to_le_bytes());
626    };
627
628    for cmd in paths {
629      match cmd {
630        Self::MoveTo(p) => {
631          h.update(&[0u8]);
632          point(&mut h, p);
633        }
634        Self::LineTo(p) => {
635          h.update(&[1u8]);
636          point(&mut h, p);
637        }
638        Self::QuadTo(p1, p2) => {
639          h.update(&[2u8]);
640          point(&mut h, p1);
641          point(&mut h, p2);
642        }
643        Self::CubicTo(p1, p2, p3) => {
644          h.update(&[3u8]);
645          point(&mut h, p1);
646          point(&mut h, p2);
647          point(&mut h, p3);
648        }
649        Self::Close => {
650          h.update(&[4u8]);
651        }
652      }
653    }
654    h.digest()
655  }
656
657  /// The command with its points mapped through `transform`.
658  #[cfg(feature = "svg")]
659  pub(crate) fn transformed(self, transform: Affine) -> Self {
660    self.map_points(|point| {
661      let (x, y) = transform.transform_point(point.x, point.y);
662
663      Point::new(x, y)
664    })
665  }
666
667  /// Maps every point the command carries through `f`.
668  pub fn map_points(self, mut f: impl FnMut(Point<f32>) -> Point<f32>) -> Self {
669    match self {
670      Self::MoveTo(point) => Self::MoveTo(f(point)),
671      Self::LineTo(point) => Self::LineTo(f(point)),
672      Self::QuadTo(control, point) => Self::QuadTo(f(control), f(point)),
673      Self::CubicTo(control1, control2, point) => Self::CubicTo(f(control1), f(control2), f(point)),
674      Self::Close => Self::Close,
675    }
676  }
677}
678
679/// A path as tiny-skia's builder normalizes it, with its bounds.
680#[cfg(feature = "svg")]
681pub(crate) struct NormalizedPath {
682  pub(crate) commands: Vec<PathCommand>,
683  /// The tight bounds of the outline.
684  pub(crate) bounds: Rect<f32>,
685  /// The bounds of the points, control points included.
686  pub(crate) control_bounds: Rect<f32>,
687}
688
689/// Push-style sugar over a [`PathCommand`] list, shared by the geometry and rasterization path
690/// builders.
691pub trait PathBuilder {
692  /// Starts a new subpath at the given point.
693  fn move_to(&mut self, point: (f32, f32));
694  /// Draws a line to the given point.
695  fn line_to(&mut self, point: (f32, f32));
696  /// Draws a cubic Bezier curve through the two control points to the end point.
697  fn curve_to(&mut self, p1: (f32, f32), p2: (f32, f32), p3: (f32, f32));
698  /// Closes the current subpath.
699  fn close(&mut self);
700}
701
702impl PathBuilder for Vec<PathCommand> {
703  fn move_to(&mut self, point: (f32, f32)) {
704    self.push(PathCommand::MoveTo(Point::new(point.0, point.1)));
705  }
706
707  fn line_to(&mut self, point: (f32, f32)) {
708    self.push(PathCommand::LineTo(Point::new(point.0, point.1)));
709  }
710
711  fn curve_to(&mut self, p1: (f32, f32), p2: (f32, f32), p3: (f32, f32)) {
712    self.push(PathCommand::CubicTo(
713      Point::new(p1.0, p1.1),
714      Point::new(p2.0, p2.1),
715      Point::new(p3.0, p3.1),
716    ));
717  }
718
719  fn close(&mut self) {
720    self.push(PathCommand::Close);
721  }
722}
723
724/// Transforms a rect's four corners and returns the axis-aligned `(min_x, min_y, max_x, max_y)`
725/// extents, or `None` if any corner is non-finite.
726pub fn transformed_rect_extents(
727  origin: Point<f32>,
728  size: Size<f32>,
729  transform: Affine,
730) -> Option<(f32, f32, f32, f32)> {
731  let corners = [
732    transform.transform_point(origin.x, origin.y),
733    transform.transform_point(origin.x + size.width, origin.y),
734    transform.transform_point(origin.x, origin.y + size.height),
735    transform.transform_point(origin.x + size.width, origin.y + size.height),
736  ];
737
738  let mut min_x = f32::INFINITY;
739  let mut min_y = f32::INFINITY;
740  let mut max_x = f32::NEG_INFINITY;
741  let mut max_y = f32::NEG_INFINITY;
742  for (x, y) in corners {
743    min_x = min_x.min(x);
744    min_y = min_y.min(y);
745    max_x = max_x.max(x);
746    max_y = max_y.max(y);
747  }
748
749  if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
750    return None;
751  }
752
753  Some((min_x, min_y, max_x, max_y))
754}
755
756/// Pixel-space placement of a rasterized surface: a glyph mask, a shadow, a filtered layer.
757#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
758pub struct Placement {
759  /// Left offset in pixels.
760  pub left: i32,
761  /// Top offset in pixels.
762  pub top: i32,
763  /// Width in pixels.
764  pub width: u32,
765  /// Height in pixels.
766  pub height: u32,
767}
768
769impl Placement {
770  /// Right edge, exclusive.
771  pub fn right(self) -> i32 {
772    self.left + self.width as i32
773  }
774
775  /// Bottom edge, exclusive.
776  pub fn bottom(self) -> i32 {
777    self.top + self.height as i32
778  }
779
780  /// Builds a placement from edges, or `None` when they enclose no pixels.
781  pub fn from_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Option<Self> {
782    if left >= right || top >= bottom {
783      return None;
784    }
785
786    Some(Self {
787      left,
788      top,
789      width: (right - left) as u32,
790      height: (bottom - top) as u32,
791    })
792  }
793
794  /// Moves the placement without resizing it.
795  pub fn translate(self, dx: i32, dy: i32) -> Self {
796    Self {
797      left: self.left + dx,
798      top: self.top + dy,
799      ..self
800    }
801  }
802
803  /// Grows the placement by `padding` on every side.
804  pub fn inflate(self, padding: i32) -> Option<Self> {
805    Self::from_bounds(
806      self.left - padding,
807      self.top - padding,
808      self.right() + padding,
809      self.bottom() + padding,
810    )
811  }
812
813  /// Intersects the placement with a `size`-sized surface at the origin.
814  pub fn clamp_to(self, size: Size<u32>) -> Option<Self> {
815    Self::from_bounds(
816      self.left.clamp(0, size.width as i32),
817      self.top.clamp(0, size.height as i32),
818      self.right().clamp(0, size.width as i32),
819      self.bottom().clamp(0, size.height as i32),
820    )
821  }
822}
823
824/// The finest share of a segment's control polygon its length is measured to. kurbo's root search
825/// takes about `log2(length / accuracy)` steps and shifts a `u64` by that count, so a finer accuracy
826/// on a long segment overflows, as it did for a fuzzer's path quintillions of pixels long. This
827/// stays above what `f64` resolves at that length anyway.
828const ARCLEN_PRECISION_LIMIT: f64 = 1.0 / (1u64 << 50) as f64;
829
830/// How closely to measure the length of `segment`: `finest`, or `relative` of its control polygon
831/// when that is coarser, so that a long segment costs no more than a short one. `relative` below
832/// [`ARCLEN_PRECISION_LIMIT`] measures as finely as `f64` allows.
833pub(crate) fn arclen_accuracy(segment: PathSeg, finest: f64, relative: f64) -> f64 {
834  let polygon = match segment {
835    PathSeg::Line(line) => line.p0.distance(line.p1),
836    PathSeg::Quad(quad) => quad.p0.distance(quad.p1) + quad.p1.distance(quad.p2),
837    PathSeg::Cubic(cubic) => {
838      cubic.p0.distance(cubic.p1) + cubic.p1.distance(cubic.p2) + cubic.p2.distance(cubic.p3)
839    }
840  };
841
842  (polygon * relative.max(ARCLEN_PRECISION_LIMIT)).max(finest)
843}