waft_embedder/geometry/geometry.rs
1//! Flutter counterpart: `engine/src/flutter/lib/ui/geometry.dart`.
2
3use std::fmt::{self, Debug};
4use std::ops::{Add, BitAnd, Div, Mul, Neg, Rem, Sub};
5
6use super::lerp::lerp_double_non_null;
7use super::math::clamp_double;
8
9/// An immutable 2D floating-point offset.
10///
11/// Generally speaking, Offsets can be interpreted in two ways:
12///
13/// 1. As representing a point in Cartesian space a specified distance from a
14/// separately-maintained origin. For example, the top-left position of
15/// children in the `RenderBox` protocol is typically represented as an
16/// [`Offset`] from the top left of the parent box.
17///
18/// 2. As a vector that can be applied to coordinates. For example, when painting
19/// a `RenderObject`, the parent is passed an [`Offset`] from the screen's
20/// origin which it can add to the offsets of its children to find the
21/// [`Offset`] from the screen's origin to each of the children.
22///
23/// Because a particular [`Offset`] can be interpreted as one sense at one time
24/// then as the other sense at a later time, the same class is used for both
25/// senses.
26///
27/// See also:
28///
29/// * [`Size`], which represents a vector describing the size of a rectangle.
30#[derive(Clone, Copy, PartialEq)]
31pub struct Offset {
32 dx: f64,
33 dy: f64,
34}
35
36impl Offset {
37 /// Creates an offset. The first argument sets [`dx`](Offset::dx), the
38 /// horizontal component, and the second sets [`dy`](Offset::dy), the
39 /// vertical component.
40 pub const fn new(dx: f64, dy: f64) -> Offset {
41 Offset { dx, dy }
42 }
43
44 /// Creates an offset from its [`direction`](Offset::direction) and
45 /// [`distance`](Offset::distance).
46 ///
47 /// The direction is in radians clockwise from the positive x-axis.
48 ///
49 /// Pass `1.0` for `distance` to create a unit vector.
50 pub fn from_direction(direction: f64, distance: f64) -> Offset {
51 Offset::new(distance * direction.cos(), distance * direction.sin())
52 }
53
54 /// The x component of the offset.
55 ///
56 /// The y component is given by [`dy`](Offset::dy).
57 pub const fn dx(&self) -> f64 {
58 self.dx
59 }
60
61 /// The y component of the offset.
62 ///
63 /// The x component is given by [`dx`](Offset::dx).
64 pub const fn dy(&self) -> f64 {
65 self.dy
66 }
67
68 /// Returns true if either component is [`f64::INFINITY`], and false if both
69 /// are finite (or negative infinity, or NaN).
70 ///
71 /// This is different than comparing for equality with an instance that has
72 /// _both_ components set to [`f64::INFINITY`].
73 ///
74 /// See also:
75 ///
76 /// * [`is_finite`](Offset::is_finite), which is true if both components are
77 /// finite (and not NaN).
78 pub fn is_infinite(&self) -> bool {
79 self.dx >= f64::INFINITY || self.dy >= f64::INFINITY
80 }
81
82 /// Whether both components are finite (neither infinite nor NaN).
83 ///
84 /// See also:
85 ///
86 /// * [`is_infinite`](Offset::is_infinite), which returns true if either
87 /// component is equal to positive infinity.
88 pub fn is_finite(&self) -> bool {
89 self.dx.is_finite() && self.dy.is_finite()
90 }
91
92 /// Less-than operator. Compares an [`Offset`] or [`Size`] to another
93 /// [`Offset`] or [`Size`], and returns true if both the horizontal and
94 /// vertical values of the left-hand-side operand are smaller than the
95 /// horizontal and vertical values of the right-hand-side operand
96 /// respectively. Returns false otherwise.
97 ///
98 /// This is a partial ordering. It is possible for two values to be neither
99 /// less, nor greater than, nor equal to, another.
100 pub fn lt(&self, other: &Offset) -> bool {
101 self.dx < other.dx && self.dy < other.dy
102 }
103
104 /// Less-than-or-equal-to operator. Compares an [`Offset`] or [`Size`] to
105 /// another [`Offset`] or [`Size`], and returns true if both the horizontal
106 /// and vertical values of the left-hand-side operand are smaller than or
107 /// equal to the horizontal and vertical values of the right-hand-side
108 /// operand respectively. Returns false otherwise.
109 ///
110 /// This is a partial ordering. It is possible for two values to be neither
111 /// less, nor greater than, nor equal to, another.
112 pub fn le(&self, other: &Offset) -> bool {
113 self.dx <= other.dx && self.dy <= other.dy
114 }
115
116 /// Greater-than operator. Compares an [`Offset`] or [`Size`] to another
117 /// [`Offset`] or [`Size`], and returns true if both the horizontal and
118 /// vertical values of the left-hand-side operand are bigger than the
119 /// horizontal and vertical values of the right-hand-side operand
120 /// respectively. Returns false otherwise.
121 ///
122 /// This is a partial ordering. It is possible for two values to be neither
123 /// less, nor greater than, nor equal to, another.
124 pub fn gt(&self, other: &Offset) -> bool {
125 self.dx > other.dx && self.dy > other.dy
126 }
127
128 /// Greater-than-or-equal-to operator. Compares an [`Offset`] or [`Size`] to
129 /// another [`Offset`] or [`Size`], and returns true if both the horizontal
130 /// and vertical values of the left-hand-side operand are bigger than or
131 /// equal to the horizontal and vertical values of the right-hand-side
132 /// operand respectively. Returns false otherwise.
133 ///
134 /// This is a partial ordering. It is possible for two values to be neither
135 /// less, nor greater than, nor equal to, another.
136 pub fn ge(&self, other: &Offset) -> bool {
137 self.dx >= other.dx && self.dy >= other.dy
138 }
139
140 /// The magnitude of the offset.
141 ///
142 /// If you need this value to compare it to another [`Offset`]'s distance,
143 /// consider using [`distance_squared`](Offset::distance_squared) instead,
144 /// since it is cheaper to compute.
145 pub fn distance(&self) -> f64 {
146 (self.dx * self.dx + self.dy * self.dy).sqrt()
147 }
148
149 /// The square of the magnitude of the offset.
150 ///
151 /// This is cheaper than computing the [`distance`](Offset::distance) itself.
152 pub fn distance_squared(&self) -> f64 {
153 self.dx * self.dx + self.dy * self.dy
154 }
155
156 /// The angle of this offset as radians clockwise from the positive x-axis,
157 /// in the range -pi to pi, assuming positive values of the x-axis go to the
158 /// right and positive values of the y-axis go down.
159 ///
160 /// Zero means that [`dy`](Offset::dy) is zero and [`dx`](Offset::dx) is zero
161 /// or positive.
162 ///
163 /// Values from zero to pi/2 indicate positive values of [`dx`](Offset::dx)
164 /// and [`dy`](Offset::dy), the bottom-right quadrant.
165 ///
166 /// Values from pi/2 to pi indicate negative values of [`dx`](Offset::dx) and
167 /// positive values of [`dy`](Offset::dy), the bottom-left quadrant.
168 ///
169 /// Values from zero to -pi/2 indicate positive values of [`dx`](Offset::dx)
170 /// and negative values of [`dy`](Offset::dy), the top-right quadrant.
171 ///
172 /// Values from -pi/2 to -pi indicate negative values of [`dx`](Offset::dx)
173 /// and [`dy`](Offset::dy), the top-left quadrant.
174 ///
175 /// When [`dy`](Offset::dy) is zero and [`dx`](Offset::dx) is negative, the
176 /// direction is pi.
177 ///
178 /// When [`dx`](Offset::dx) is zero, direction is pi/2 if [`dy`](Offset::dy)
179 /// is positive and -pi/2 if [`dy`](Offset::dy) is negative.
180 ///
181 /// See also:
182 ///
183 /// * [`distance`](Offset::distance), to compute the magnitude of the
184 /// vector.
185 pub fn direction(&self) -> f64 {
186 self.dy.atan2(self.dx)
187 }
188
189 /// An offset with zero magnitude.
190 ///
191 /// This can be used to represent the origin of a coordinate space.
192 pub const ZERO: Offset = Offset::new(0.0, 0.0);
193
194 /// An offset with infinite x and y components.
195 ///
196 /// See also:
197 ///
198 /// * [`is_infinite`](Offset::is_infinite), which checks whether either
199 /// component is infinite.
200 /// * [`is_finite`](Offset::is_finite), which checks whether both
201 /// components are finite.
202 // This is included for completeness, because [Size.infinite] exists.
203 pub const INFINITE: Offset = Offset::new(f64::INFINITY, f64::INFINITY);
204
205 /// Returns a new offset with the x component scaled by `scale_x` and the y
206 /// component scaled by `scale_y`.
207 ///
208 /// If the two scale arguments are the same, consider using the `*` operator
209 /// instead:
210 ///
211 /// ```
212 /// # use waft_embedder::Offset;
213 /// let a = Offset::new(10.0, 10.0);
214 /// let b = a * 2.0; // same as: a.scale(2.0, 2.0)
215 /// # assert_eq!(b, a.scale(2.0, 2.0));
216 /// ```
217 ///
218 /// If the two arguments are -1, consider using the unary `-` operator
219 /// instead:
220 ///
221 /// ```
222 /// # use waft_embedder::Offset;
223 /// let a = Offset::new(10.0, 10.0);
224 /// let b = -a; // same as: a.scale(-1.0, -1.0)
225 /// # assert_eq!(b, a.scale(-1.0, -1.0));
226 /// ```
227 pub fn scale(&self, scale_x: f64, scale_y: f64) -> Offset {
228 Offset::new(self.dx * scale_x, self.dy * scale_y)
229 }
230
231 /// Returns a new offset with `translate_x` added to the x component and
232 /// `translate_y` added to the y component.
233 ///
234 /// If the arguments come from another [`Offset`], consider using the `+` or
235 /// `-` operators instead:
236 ///
237 /// ```
238 /// # use waft_embedder::Offset;
239 /// let a = Offset::new(10.0, 10.0);
240 /// let b = Offset::new(10.0, 10.0);
241 /// let c = a + b; // same as: a.translate(b.dx(), b.dy())
242 /// let d = a - b; // same as: a.translate(-b.dx(), -b.dy())
243 /// # assert_eq!(c, a.translate(b.dx(), b.dy()));
244 /// # assert_eq!(d, a.translate(-b.dx(), -b.dy()));
245 /// ```
246 pub fn translate(&self, translate_x: f64, translate_y: f64) -> Offset {
247 Offset::new(self.dx + translate_x, self.dy + translate_y)
248 }
249
250 /// Integer (truncating) division operator.
251 ///
252 /// Returns an offset whose coordinates are the coordinates of this offset
253 /// divided by the scalar `operand`, rounded towards zero.
254 pub fn truncating_div(&self, operand: f64) -> Offset {
255 Offset::new((self.dx / operand).trunc(), (self.dy / operand).trunc())
256 }
257
258 /// Linearly interpolate between two offsets.
259 ///
260 /// If either offset is null, this function interpolates from
261 /// [`Offset::ZERO`].
262 ///
263 /// The `t` argument represents position on the timeline, with 0.0 meaning
264 /// that the interpolation has not started, returning `a` (or something
265 /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
266 /// returning `b` (or something equivalent to `b`), and values in between
267 /// meaning that the interpolation is at the relevant point on the timeline
268 /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
269 /// 1.0, so negative values and values greater than 1.0 are valid (and can
270 /// easily be generated by curves such as `Curves.elasticInOut`).
271 ///
272 /// Values for `t` are usually obtained from an `Animation<double>`, such as
273 /// an `AnimationController`.
274 pub fn lerp(a: Option<Offset>, b: Option<Offset>, t: f64) -> Option<Offset> {
275 match (a, b) {
276 (None, None) => None,
277 (Some(a), None) => Some(a * (1.0 - t)),
278 (None, Some(b)) => Some(b * t),
279 (Some(a), Some(b)) => Some(Offset::new(
280 lerp_double_non_null(a.dx, b.dx, t),
281 lerp_double_non_null(a.dy, b.dy, t),
282 )),
283 }
284 }
285}
286
287/// Unary negation operator.
288///
289/// Returns an offset with the coordinates negated.
290///
291/// If the [`Offset`] represents an arrow on a plane, this operator returns the
292/// same arrow but pointing in the reverse direction.
293impl Neg for Offset {
294 type Output = Offset;
295
296 fn neg(self) -> Offset {
297 Offset::new(-self.dx, -self.dy)
298 }
299}
300
301/// Binary subtraction operator.
302///
303/// Returns an offset whose [`dx`](Offset::dx) value is the left-hand-side
304/// operand's [`dx`](Offset::dx) minus the right-hand-side operand's
305/// [`dx`](Offset::dx) and whose [`dy`](Offset::dy) value is the left-hand-side
306/// operand's [`dy`](Offset::dy) minus the right-hand-side operand's
307/// [`dy`](Offset::dy).
308///
309/// See also [`translate`](Offset::translate).
310impl Sub for Offset {
311 type Output = Offset;
312
313 fn sub(self, other: Offset) -> Offset {
314 Offset::new(self.dx - other.dx, self.dy - other.dy)
315 }
316}
317
318/// Binary addition operator.
319///
320/// Returns an offset whose [`dx`](Offset::dx) value is the sum of the
321/// [`dx`](Offset::dx) values of the two operands, and whose [`dy`](Offset::dy)
322/// value is the sum of the [`dy`](Offset::dy) values of the two operands.
323///
324/// See also [`translate`](Offset::translate).
325impl Add for Offset {
326 type Output = Offset;
327
328 fn add(self, other: Offset) -> Offset {
329 Offset::new(self.dx + other.dx, self.dy + other.dy)
330 }
331}
332
333/// Multiplication operator.
334///
335/// Returns an offset whose coordinates are the coordinates of the left-hand-side
336/// operand (an Offset) multiplied by the scalar right-hand-side operand (an
337/// `f64`).
338///
339/// See also [`scale`](Offset::scale).
340impl Mul<f64> for Offset {
341 type Output = Offset;
342
343 fn mul(self, operand: f64) -> Offset {
344 Offset::new(self.dx * operand, self.dy * operand)
345 }
346}
347
348/// Division operator.
349///
350/// Returns an offset whose coordinates are the coordinates of the left-hand-side
351/// operand (an Offset) divided by the scalar right-hand-side operand (an `f64`).
352///
353/// See also [`scale`](Offset::scale).
354impl Div<f64> for Offset {
355 type Output = Offset;
356
357 fn div(self, operand: f64) -> Offset {
358 Offset::new(self.dx / operand, self.dy / operand)
359 }
360}
361
362/// Modulo (remainder) operator.
363///
364/// Returns an offset whose coordinates are the remainder of dividing the
365/// coordinates of the left-hand-side operand (an Offset) by the scalar
366/// right-hand-side operand (an `f64`).
367impl Rem<f64> for Offset {
368 type Output = Offset;
369
370 fn rem(self, operand: f64) -> Offset {
371 Offset::new(self.dx.rem_euclid(operand), self.dy.rem_euclid(operand))
372 }
373}
374
375impl Debug for Offset {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 write!(f, "Offset({:.1}, {:.1})", self.dx, self.dy)
378 }
379}
380
381/// Dart's `Offset.toString`, the same text as [`Debug`].
382impl fmt::Display for Offset {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 Debug::fmt(self, f)
385 }
386}
387
388/// Holds a 2D floating-point size.
389///
390/// You can think of this as an [`Offset`] from the origin.
391#[derive(Clone, Copy, PartialEq)]
392pub struct Size {
393 width: f64,
394 height: f64,
395}
396
397impl Size {
398 /// Creates a [`Size`] with the given [`width`](Size::width) and
399 /// [`height`](Size::height).
400 pub const fn new(width: f64, height: f64) -> Size {
401 Size { width, height }
402 }
403
404 /// Creates a square [`Size`] whose [`width`](Size::width) and
405 /// [`height`](Size::height) are the given dimension.
406 ///
407 /// See also:
408 ///
409 /// * [`from_radius`](Size::from_radius), which is more convenient when the
410 /// available size is the radius of a circle.
411 pub const fn square(dimension: f64) -> Size {
412 Size::new(dimension, dimension)
413 }
414
415 /// Creates a [`Size`] with the given [`width`](Size::width) and an infinite
416 /// [`height`](Size::height).
417 pub const fn from_width(width: f64) -> Size {
418 Size::new(width, f64::INFINITY)
419 }
420
421 /// Creates a [`Size`] with the given [`height`](Size::height) and an
422 /// infinite [`width`](Size::width).
423 pub const fn from_height(height: f64) -> Size {
424 Size::new(f64::INFINITY, height)
425 }
426
427 /// Creates a square [`Size`] whose [`width`](Size::width) and
428 /// [`height`](Size::height) are twice the given dimension.
429 ///
430 /// This is a square that contains a circle with the given radius.
431 ///
432 /// See also:
433 ///
434 /// * [`square`](Size::square), which creates a square with the given
435 /// dimension.
436 pub const fn from_radius(radius: f64) -> Size {
437 Size::new(radius * 2.0, radius * 2.0)
438 }
439
440 /// The horizontal extent of this size.
441 pub const fn width(&self) -> f64 {
442 self.width
443 }
444
445 /// The vertical extent of this size.
446 pub const fn height(&self) -> f64 {
447 self.height
448 }
449
450 /// Returns true if either component is [`f64::INFINITY`], and false if both
451 /// are finite (or negative infinity, or NaN).
452 ///
453 /// This is different than comparing for equality with an instance that has
454 /// _both_ components set to [`f64::INFINITY`].
455 ///
456 /// See also:
457 ///
458 /// * [`is_finite`](Size::is_finite), which is true if both components are
459 /// finite (and not NaN).
460 pub fn is_infinite(&self) -> bool {
461 self.width >= f64::INFINITY || self.height >= f64::INFINITY
462 }
463
464 /// Whether both components are finite (neither infinite nor NaN).
465 ///
466 /// See also:
467 ///
468 /// * [`is_infinite`](Size::is_infinite), which returns true if either
469 /// component is equal to positive infinity.
470 pub fn is_finite(&self) -> bool {
471 self.width.is_finite() && self.height.is_finite()
472 }
473
474 /// Less-than operator. Compares an [`Offset`] or [`Size`] to another
475 /// [`Offset`] or [`Size`], and returns true if both the horizontal and
476 /// vertical values of the left-hand-side operand are smaller than the
477 /// horizontal and vertical values of the right-hand-side operand
478 /// respectively. Returns false otherwise.
479 ///
480 /// This is a partial ordering. It is possible for two values to be neither
481 /// less, nor greater than, nor equal to, another.
482 pub fn lt(&self, other: &Size) -> bool {
483 self.width < other.width && self.height < other.height
484 }
485
486 /// Less-than-or-equal-to operator. Compares an [`Offset`] or [`Size`] to
487 /// another [`Offset`] or [`Size`], and returns true if both the horizontal
488 /// and vertical values of the left-hand-side operand are smaller than or
489 /// equal to the horizontal and vertical values of the right-hand-side
490 /// operand respectively. Returns false otherwise.
491 ///
492 /// This is a partial ordering. It is possible for two values to be neither
493 /// less, nor greater than, nor equal to, another.
494 pub fn le(&self, other: &Size) -> bool {
495 self.width <= other.width && self.height <= other.height
496 }
497
498 /// Greater-than operator. Compares an [`Offset`] or [`Size`] to another
499 /// [`Offset`] or [`Size`], and returns true if both the horizontal and
500 /// vertical values of the left-hand-side operand are bigger than the
501 /// horizontal and vertical values of the right-hand-side operand
502 /// respectively. Returns false otherwise.
503 ///
504 /// This is a partial ordering. It is possible for two values to be neither
505 /// less, nor greater than, nor equal to, another.
506 pub fn gt(&self, other: &Size) -> bool {
507 self.width > other.width && self.height > other.height
508 }
509
510 /// Greater-than-or-equal-to operator. Compares an [`Offset`] or [`Size`] to
511 /// another [`Offset`] or [`Size`], and returns true if both the horizontal
512 /// and vertical values of the left-hand-side operand are bigger than or
513 /// equal to the horizontal and vertical values of the right-hand-side
514 /// operand respectively. Returns false otherwise.
515 ///
516 /// This is a partial ordering. It is possible for two values to be neither
517 /// less, nor greater than, nor equal to, another.
518 pub fn ge(&self, other: &Size) -> bool {
519 self.width >= other.width && self.height >= other.height
520 }
521
522 /// The aspect ratio of this size.
523 ///
524 /// This returns the [`width`](Size::width) divided by the
525 /// [`height`](Size::height).
526 ///
527 /// If the [`width`](Size::width) is zero, the result will be zero. If the
528 /// [`height`](Size::height) is zero (and the [`width`](Size::width) is not),
529 /// the result will be [`f64::INFINITY`] or [`f64::NEG_INFINITY`] as
530 /// determined by the sign of [`width`](Size::width).
531 ///
532 /// See also:
533 ///
534 /// * `AspectRatio`, a widget for giving a child widget a specific aspect
535 /// ratio.
536 /// * `FittedBox`, a widget that (in most modes) attempts to maintain a
537 /// child widget's aspect ratio while changing its size.
538 pub fn aspect_ratio(&self) -> f64 {
539 if self.height != 0.0 {
540 return self.width / self.height;
541 }
542 if self.width > 0.0 {
543 return f64::INFINITY;
544 }
545 if self.width < 0.0 {
546 return f64::NEG_INFINITY;
547 }
548 0.0
549 }
550
551 /// An empty size, one with a zero width and a zero height.
552 pub const ZERO: Size = Size::new(0.0, 0.0);
553
554 /// A size whose [`width`](Size::width) and [`height`](Size::height) are
555 /// infinite.
556 ///
557 /// See also:
558 ///
559 /// * [`is_infinite`](Size::is_infinite), which checks whether either
560 /// dimension is infinite.
561 /// * [`is_finite`](Size::is_finite), which checks whether both dimensions
562 /// are finite.
563 pub const INFINITE: Size = Size::new(f64::INFINITY, f64::INFINITY);
564
565 /// Whether this size encloses a zero area.
566 ///
567 /// Negative areas are considered empty.
568 pub fn is_empty(&self) -> bool {
569 self.width <= 0.0 || self.height <= 0.0
570 }
571
572 /// Integer (truncating) division operator.
573 ///
574 /// Returns a [`Size`] whose dimensions are the dimensions of this size
575 /// divided by the scalar `operand`, rounded towards zero.
576 pub fn truncating_div(&self, operand: f64) -> Size {
577 Size::new(
578 (self.width / operand).trunc(),
579 (self.height / operand).trunc(),
580 )
581 }
582
583 /// The lesser of the magnitudes of the [`width`](Size::width) and the
584 /// [`height`](Size::height).
585 pub fn shortest_side(&self) -> f64 {
586 self.width.abs().min(self.height.abs())
587 }
588
589 /// The greater of the magnitudes of the [`width`](Size::width) and the
590 /// [`height`](Size::height).
591 pub fn longest_side(&self) -> f64 {
592 self.width.abs().max(self.height.abs())
593 }
594
595 /// The offset to the intersection of the top and left edges of the
596 /// rectangle described by the given [`Offset`] (which is interpreted as the
597 /// top-left corner) and this [`Size`].
598 ///
599 /// See also [`Rect::top_left`].
600 pub fn top_left(&self, origin: Offset) -> Offset {
601 origin
602 }
603
604 /// The offset to the center of the top edge of the rectangle described by
605 /// the given offset (which is interpreted as the top-left corner) and this
606 /// size.
607 ///
608 /// See also [`Rect::top_center`].
609 pub fn top_center(&self, origin: Offset) -> Offset {
610 Offset::new(origin.dx() + self.width / 2.0, origin.dy())
611 }
612
613 /// The offset to the intersection of the top and right edges of the
614 /// rectangle described by the given offset (which is interpreted as the
615 /// top-left corner) and this size.
616 ///
617 /// See also [`Rect::top_right`].
618 pub fn top_right(&self, origin: Offset) -> Offset {
619 Offset::new(origin.dx() + self.width, origin.dy())
620 }
621
622 /// The offset to the center of the left edge of the rectangle described by
623 /// the given offset (which is interpreted as the top-left corner) and this
624 /// size.
625 ///
626 /// See also [`Rect::center_left`].
627 pub fn center_left(&self, origin: Offset) -> Offset {
628 Offset::new(origin.dx(), origin.dy() + self.height / 2.0)
629 }
630
631 /// The offset to the point halfway between the left and right and the top
632 /// and bottom edges of the rectangle described by the given offset (which
633 /// is interpreted as the top-left corner) and this size.
634 ///
635 /// See also [`Rect::center`].
636 pub fn center(&self, origin: Offset) -> Offset {
637 Offset::new(
638 origin.dx() + self.width / 2.0,
639 origin.dy() + self.height / 2.0,
640 )
641 }
642
643 /// The offset to the center of the right edge of the rectangle described by
644 /// the given offset (which is interpreted as the top-left corner) and this
645 /// size.
646 ///
647 /// See also [`Rect::center_right`].
648 pub fn center_right(&self, origin: Offset) -> Offset {
649 Offset::new(origin.dx() + self.width, origin.dy() + self.height / 2.0)
650 }
651
652 /// The offset to the intersection of the bottom and left edges of the
653 /// rectangle described by the given offset (which is interpreted as the
654 /// top-left corner) and this size.
655 ///
656 /// See also [`Rect::bottom_left`].
657 pub fn bottom_left(&self, origin: Offset) -> Offset {
658 Offset::new(origin.dx(), origin.dy() + self.height)
659 }
660
661 /// The offset to the center of the bottom edge of the rectangle described
662 /// by the given offset (which is interpreted as the top-left corner) and
663 /// this size.
664 ///
665 /// See also [`Rect::bottom_center`].
666 pub fn bottom_center(&self, origin: Offset) -> Offset {
667 Offset::new(origin.dx() + self.width / 2.0, origin.dy() + self.height)
668 }
669
670 /// The offset to the intersection of the bottom and right edges of the
671 /// rectangle described by the given offset (which is interpreted as the
672 /// top-left corner) and this size.
673 ///
674 /// See also [`Rect::bottom_right`].
675 pub fn bottom_right(&self, origin: Offset) -> Offset {
676 Offset::new(origin.dx() + self.width, origin.dy() + self.height)
677 }
678
679 /// Whether the point specified by the given offset (which is assumed to be
680 /// relative to the top left of the size) lies between the left and right
681 /// and the top and bottom edges of a rectangle of this size.
682 ///
683 /// Rectangles include their top and left edges but exclude their bottom and
684 /// right edges.
685 pub fn contains(&self, offset: Offset) -> bool {
686 offset.dx() >= 0.0
687 && offset.dx() < self.width
688 && offset.dy() >= 0.0
689 && offset.dy() < self.height
690 }
691
692 /// A [`Size`] with the [`width`](Size::width) and [`height`](Size::height)
693 /// swapped.
694 pub fn flipped(&self) -> Size {
695 Size::new(self.height, self.width)
696 }
697
698 /// Linearly interpolate between two sizes.
699 ///
700 /// If either size is null, this function interpolates from [`Size::ZERO`].
701 ///
702 /// The `t` argument represents position on the timeline, with 0.0 meaning
703 /// that the interpolation has not started, returning `a` (or something
704 /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
705 /// returning `b` (or something equivalent to `b`), and values in between
706 /// meaning that the interpolation is at the relevant point on the timeline
707 /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
708 /// 1.0, so negative values and values greater than 1.0 are valid (and can
709 /// easily be generated by curves such as `Curves.elasticInOut`).
710 ///
711 /// Values for `t` are usually obtained from an `Animation<double>`, such as
712 /// an `AnimationController`.
713 pub fn lerp(a: Option<Size>, b: Option<Size>, t: f64) -> Option<Size> {
714 match (a, b) {
715 (None, None) => None,
716 (Some(a), None) => Some(a * (1.0 - t)),
717 (None, Some(b)) => Some(b * t),
718 (Some(a), Some(b)) => Some(Size::new(
719 lerp_double_non_null(a.width, b.width, t),
720 lerp_double_non_null(a.height, b.height, t),
721 )),
722 }
723 }
724}
725
726/// Binary subtraction operator for [`Size`].
727///
728/// Subtracting a [`Size`] from a [`Size`] returns the [`Offset`] that describes
729/// how much bigger the left-hand-side operand is than the right-hand-side
730/// operand. Adding that resulting [`Offset`] to the [`Size`] that was the
731/// right-hand-side operand would return a [`Size`] equal to the [`Size`] that
732/// was the left-hand-side operand. (i.e. if `size_a - size_b -> offset_a`, then
733/// `offset_a + size_b -> size_a`)
734impl Sub<Size> for Size {
735 type Output = Offset;
736
737 fn sub(self, other: Size) -> Offset {
738 Offset::new(self.width - other.width, self.height - other.height)
739 }
740}
741
742/// Subtracting an [`Offset`] from a [`Size`] returns the [`Size`] that is
743/// smaller than the [`Size`] operand by the difference given by the [`Offset`]
744/// operand. In other words, the returned [`Size`] has a [`width`](Size::width)
745/// consisting of the [`width`](Size::width) of the left-hand-side operand minus
746/// the [`Offset::dx`] dimension of the right-hand-side operand, and a
747/// [`height`](Size::height) consisting of the [`height`](Size::height) of the
748/// left-hand-side operand minus the [`Offset::dy`] dimension of the
749/// right-hand-side operand.
750impl Sub<Offset> for Size {
751 type Output = Size;
752
753 fn sub(self, other: Offset) -> Size {
754 Size::new(self.width - other.dx(), self.height - other.dy())
755 }
756}
757
758/// Binary addition operator for adding an [`Offset`] to a [`Size`].
759///
760/// Returns a [`Size`] whose [`width`](Size::width) is the sum of the
761/// [`width`](Size::width) of the left-hand-side operand, a [`Size`], and the
762/// [`Offset::dx`] dimension of the right-hand-side operand, an [`Offset`], and
763/// whose [`height`](Size::height) is the sum of the [`height`](Size::height) of
764/// the left-hand-side operand and the [`Offset::dy`] dimension of the
765/// right-hand-side operand.
766impl Add<Offset> for Size {
767 type Output = Size;
768
769 fn add(self, other: Offset) -> Size {
770 Size::new(self.width + other.dx(), self.height + other.dy())
771 }
772}
773
774/// Multiplication operator.
775///
776/// Returns a [`Size`] whose dimensions are the dimensions of the left-hand-side
777/// operand (a [`Size`]) multiplied by the scalar right-hand-side operand (an
778/// `f64`).
779impl Mul<f64> for Size {
780 type Output = Size;
781
782 fn mul(self, operand: f64) -> Size {
783 Size::new(self.width * operand, self.height * operand)
784 }
785}
786
787/// Division operator.
788///
789/// Returns a [`Size`] whose dimensions are the dimensions of the left-hand-side
790/// operand (a [`Size`]) divided by the scalar right-hand-side operand (an
791/// `f64`).
792impl Div<f64> for Size {
793 type Output = Size;
794
795 fn div(self, operand: f64) -> Size {
796 Size::new(self.width / operand, self.height / operand)
797 }
798}
799
800/// Modulo (remainder) operator.
801///
802/// Returns a [`Size`] whose dimensions are the remainder of dividing the
803/// left-hand-side operand (a [`Size`]) by the scalar right-hand-side operand
804/// (an `f64`).
805impl Rem<f64> for Size {
806 type Output = Size;
807
808 fn rem(self, operand: f64) -> Size {
809 Size::new(
810 self.width.rem_euclid(operand),
811 self.height.rem_euclid(operand),
812 )
813 }
814}
815
816/// Rectangle constructor operator.
817///
818/// Combines an [`Offset`] and a [`Size`] to form a [`Rect`] whose top-left
819/// coordinate is the point given by adding this offset, the left-hand-side
820/// operand, to the origin, and whose size is the right-hand-side operand.
821///
822/// ```
823/// # use waft_embedder::{Offset, Rect, Size};
824/// let my_rect = Offset::ZERO & Size::new(100.0, 100.0);
825/// // same as: Rect::from_ltwh(0.0, 0.0, 100.0, 100.0)
826/// # assert_eq!(my_rect, Rect::from_ltwh(0.0, 0.0, 100.0, 100.0));
827/// ```
828impl BitAnd<Size> for Offset {
829 type Output = Rect;
830
831 fn bitand(self, other: Size) -> Rect {
832 Rect::from_ltwh(self.dx(), self.dy(), other.width, other.height)
833 }
834}
835
836impl Debug for Size {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 write!(f, "Size({:.1}, {:.1})", self.width, self.height)
839 }
840}
841
842/// Dart's `Size.toString`, the same text as [`Debug`].
843impl fmt::Display for Size {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 Debug::fmt(self, f)
846 }
847}
848
849/// An immutable, 2D, axis-aligned, floating-point rectangle whose coordinates
850/// are relative to a given origin.
851///
852/// A Rect can be created with one of its constructors or from an [`Offset`] and
853/// a [`Size`] using the `&` operator:
854///
855/// ```
856/// # use waft_embedder::{Offset, Rect, Size};
857/// let my_rect = Offset::new(1.0, 2.0) & Size::new(3.0, 4.0);
858/// # assert_eq!(my_rect, Rect::from_ltwh(1.0, 2.0, 3.0, 4.0));
859/// ```
860#[derive(Clone, Copy, PartialEq)]
861pub struct Rect {
862 /// The offset of the left edge of this rectangle from the x axis.
863 pub left: f64,
864
865 /// The offset of the top edge of this rectangle from the y axis.
866 pub top: f64,
867
868 /// The offset of the right edge of this rectangle from the x axis.
869 pub right: f64,
870
871 /// The offset of the bottom edge of this rectangle from the y axis.
872 pub bottom: f64,
873}
874
875impl Rect {
876 /// Construct a rectangle from its left, top, right, and bottom edges.
877 pub const fn from_ltrb(left: f64, top: f64, right: f64, bottom: f64) -> Rect {
878 Rect {
879 left,
880 top,
881 right,
882 bottom,
883 }
884 }
885
886 /// Construct a rectangle from its left and top edges, its width, and its
887 /// height.
888 ///
889 /// To construct a [`Rect`] from an [`Offset`] and a [`Size`], you can use
890 /// the rectangle constructor operator `&`. See [`BitAnd`] for [`Offset`].
891 pub const fn from_ltwh(left: f64, top: f64, width: f64, height: f64) -> Rect {
892 Rect::from_ltrb(left, top, left + width, top + height)
893 }
894
895 /// Construct a rectangle that bounds the given circle.
896 ///
897 /// The `center` argument is assumed to be an offset from the origin.
898 pub fn from_circle(center: Offset, radius: f64) -> Rect {
899 Rect::from_center(center, radius * 2.0, radius * 2.0)
900 }
901
902 /// Constructs a rectangle from its center point, width, and height.
903 ///
904 /// The `center` argument is assumed to be an offset from the origin.
905 pub fn from_center(center: Offset, width: f64, height: f64) -> Rect {
906 Rect::from_ltrb(
907 center.dx() - width / 2.0,
908 center.dy() - height / 2.0,
909 center.dx() + width / 2.0,
910 center.dy() + height / 2.0,
911 )
912 }
913
914 /// Construct the smallest rectangle that encloses the given offsets,
915 /// treating them as vectors from the origin.
916 pub fn from_points(a: Offset, b: Offset) -> Rect {
917 Rect::from_ltrb(
918 a.dx().min(b.dx()),
919 a.dy().min(b.dy()),
920 a.dx().max(b.dx()),
921 a.dy().max(b.dy()),
922 )
923 }
924
925 /// The distance between the left and right edges of this rectangle.
926 pub fn width(&self) -> f64 {
927 self.right - self.left
928 }
929
930 /// The distance between the top and bottom edges of this rectangle.
931 pub fn height(&self) -> f64 {
932 self.bottom - self.top
933 }
934
935 /// The distance between the upper-left corner and the lower-right corner of
936 /// this rectangle.
937 pub fn size(&self) -> Size {
938 Size::new(self.width(), self.height())
939 }
940
941 /// Whether any of the dimensions are `NaN`.
942 pub fn has_nan(&self) -> bool {
943 self.left.is_nan() || self.top.is_nan() || self.right.is_nan() || self.bottom.is_nan()
944 }
945
946 /// A rectangle with left, top, right, and bottom edges all at zero.
947 pub const ZERO: Rect = Rect::from_ltrb(0.0, 0.0, 0.0, 0.0);
948
949 const GIANT_SCALAR: f64 = 1.0E+9; // matches kGiantRect from layer.h
950
951 /// A rectangle that covers the entire coordinate space.
952 ///
953 /// This covers the space from -1e9,-1e9 to 1e9,1e9. This is the space over
954 /// which graphics operations are valid.
955 pub const LARGEST: Rect = Rect::from_ltrb(
956 -Rect::GIANT_SCALAR,
957 -Rect::GIANT_SCALAR,
958 Rect::GIANT_SCALAR,
959 Rect::GIANT_SCALAR,
960 );
961
962 /// Whether any of the coordinates of this rectangle are equal to positive
963 /// infinity.
964 // included for consistency with Offset and Size
965 pub fn is_infinite(&self) -> bool {
966 self.left >= f64::INFINITY
967 || self.top >= f64::INFINITY
968 || self.right >= f64::INFINITY
969 || self.bottom >= f64::INFINITY
970 }
971
972 /// Whether all coordinates of this rectangle are finite.
973 pub fn is_finite(&self) -> bool {
974 self.left.is_finite()
975 && self.top.is_finite()
976 && self.right.is_finite()
977 && self.bottom.is_finite()
978 }
979
980 /// Whether this rectangle encloses a non-zero area. Negative areas are
981 /// considered empty.
982 pub fn is_empty(&self) -> bool {
983 self.left >= self.right || self.top >= self.bottom
984 }
985
986 /// Returns a new rectangle translated by the given offset.
987 ///
988 /// To translate a rectangle by separate x and y components rather than by
989 /// an [`Offset`], consider [`translate`](Rect::translate).
990 pub fn shift(&self, offset: Offset) -> Rect {
991 Rect::from_ltrb(
992 self.left + offset.dx(),
993 self.top + offset.dy(),
994 self.right + offset.dx(),
995 self.bottom + offset.dy(),
996 )
997 }
998
999 /// Returns a new rectangle with translateX added to the x components and
1000 /// translateY added to the y components.
1001 ///
1002 /// To translate a rectangle by an [`Offset`] rather than by separate x and
1003 /// y components, consider [`shift`](Rect::shift).
1004 pub fn translate(&self, translate_x: f64, translate_y: f64) -> Rect {
1005 Rect::from_ltrb(
1006 self.left + translate_x,
1007 self.top + translate_y,
1008 self.right + translate_x,
1009 self.bottom + translate_y,
1010 )
1011 }
1012
1013 /// Returns a new rectangle with edges moved outwards by the given delta.
1014 pub fn inflate(&self, delta: f64) -> Rect {
1015 Rect::from_ltrb(
1016 self.left - delta,
1017 self.top - delta,
1018 self.right + delta,
1019 self.bottom + delta,
1020 )
1021 }
1022
1023 /// Returns a new rectangle with edges moved inwards by the given delta.
1024 pub fn deflate(&self, delta: f64) -> Rect {
1025 self.inflate(-delta)
1026 }
1027
1028 /// Returns a new rectangle that is the intersection of the given rectangle
1029 /// and this rectangle. The two rectangles must overlap for this to be
1030 /// meaningful. If the two rectangles do not overlap, then the resulting
1031 /// Rect will have a negative width or height.
1032 pub fn intersect(&self, other: Rect) -> Rect {
1033 Rect::from_ltrb(
1034 self.left.max(other.left),
1035 self.top.max(other.top),
1036 self.right.min(other.right),
1037 self.bottom.min(other.bottom),
1038 )
1039 }
1040
1041 /// Returns a new rectangle which is the bounding box containing this
1042 /// rectangle and the given rectangle.
1043 pub fn expand_to_include(&self, other: Rect) -> Rect {
1044 Rect::from_ltrb(
1045 self.left.min(other.left),
1046 self.top.min(other.top),
1047 self.right.max(other.right),
1048 self.bottom.max(other.bottom),
1049 )
1050 }
1051
1052 /// Whether `other` has a nonzero area of overlap with this rectangle.
1053 pub fn overlaps(&self, other: Rect) -> bool {
1054 if self.right <= other.left || other.right <= self.left {
1055 return false;
1056 }
1057 if self.bottom <= other.top || other.bottom <= self.top {
1058 return false;
1059 }
1060 true
1061 }
1062
1063 /// The lesser of the magnitudes of the [`width`](Rect::width) and the
1064 /// [`height`](Rect::height) of this rectangle.
1065 pub fn shortest_side(&self) -> f64 {
1066 self.width().abs().min(self.height().abs())
1067 }
1068
1069 /// The greater of the magnitudes of the [`width`](Rect::width) and the
1070 /// [`height`](Rect::height) of this rectangle.
1071 pub fn longest_side(&self) -> f64 {
1072 self.width().abs().max(self.height().abs())
1073 }
1074
1075 /// The offset to the intersection of the top and left edges of this
1076 /// rectangle.
1077 ///
1078 /// See also [`Size::top_left`].
1079 pub fn top_left(&self) -> Offset {
1080 Offset::new(self.left, self.top)
1081 }
1082
1083 /// The offset to the center of the top edge of this rectangle.
1084 ///
1085 /// See also [`Size::top_center`].
1086 pub fn top_center(&self) -> Offset {
1087 Offset::new(self.left + self.width() / 2.0, self.top)
1088 }
1089
1090 /// The offset to the intersection of the top and right edges of this
1091 /// rectangle.
1092 ///
1093 /// See also [`Size::top_right`].
1094 pub fn top_right(&self) -> Offset {
1095 Offset::new(self.right, self.top)
1096 }
1097
1098 /// The offset to the center of the left edge of this rectangle.
1099 ///
1100 /// See also [`Size::center_left`].
1101 pub fn center_left(&self) -> Offset {
1102 Offset::new(self.left, self.top + self.height() / 2.0)
1103 }
1104
1105 /// The offset to the point halfway between the left and right and the top
1106 /// and bottom edges of this rectangle.
1107 ///
1108 /// See also [`Size::center`].
1109 pub fn center(&self) -> Offset {
1110 Offset::new(
1111 self.left + self.width() / 2.0,
1112 self.top + self.height() / 2.0,
1113 )
1114 }
1115
1116 /// The offset to the center of the right edge of this rectangle.
1117 ///
1118 /// See also [`Size::center_right`].
1119 pub fn center_right(&self) -> Offset {
1120 Offset::new(self.right, self.top + self.height() / 2.0)
1121 }
1122
1123 /// The offset to the intersection of the bottom and left edges of this
1124 /// rectangle.
1125 ///
1126 /// See also [`Size::bottom_left`].
1127 pub fn bottom_left(&self) -> Offset {
1128 Offset::new(self.left, self.bottom)
1129 }
1130
1131 /// The offset to the center of the bottom edge of this rectangle.
1132 ///
1133 /// See also [`Size::bottom_center`].
1134 pub fn bottom_center(&self) -> Offset {
1135 Offset::new(self.left + self.width() / 2.0, self.bottom)
1136 }
1137
1138 /// The offset to the intersection of the bottom and right edges of this
1139 /// rectangle.
1140 ///
1141 /// See also [`Size::bottom_right`].
1142 pub fn bottom_right(&self) -> Offset {
1143 Offset::new(self.right, self.bottom)
1144 }
1145
1146 /// Whether the point specified by the given offset (which is assumed to be
1147 /// relative to the origin) lies between the left and right and the top and
1148 /// bottom edges of this rectangle.
1149 ///
1150 /// Rectangles include their top and left edges but exclude their bottom and
1151 /// right edges.
1152 pub fn contains(&self, offset: Offset) -> bool {
1153 offset.dx() >= self.left
1154 && offset.dx() < self.right
1155 && offset.dy() >= self.top
1156 && offset.dy() < self.bottom
1157 }
1158
1159 /// Linearly interpolate between two rectangles.
1160 ///
1161 /// If either rect is null, [`Rect::ZERO`] is used as a substitute.
1162 ///
1163 /// The `t` argument represents position on the timeline, with 0.0 meaning
1164 /// that the interpolation has not started, returning `a` (or something
1165 /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
1166 /// returning `b` (or something equivalent to `b`), and values in between
1167 /// meaning that the interpolation is at the relevant point on the timeline
1168 /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
1169 /// 1.0, so negative values and values greater than 1.0 are valid (and can
1170 /// easily be generated by curves such as `Curves.elasticInOut`).
1171 ///
1172 /// Values for `t` are usually obtained from an `Animation<double>`, such as
1173 /// an `AnimationController`.
1174 pub fn lerp(a: Option<Rect>, b: Option<Rect>, t: f64) -> Option<Rect> {
1175 match (a, b) {
1176 (None, None) => None,
1177 (Some(a), None) => {
1178 let k = 1.0 - t;
1179 Some(Rect::from_ltrb(
1180 a.left * k,
1181 a.top * k,
1182 a.right * k,
1183 a.bottom * k,
1184 ))
1185 }
1186 (None, Some(b)) => Some(Rect::from_ltrb(
1187 b.left * t,
1188 b.top * t,
1189 b.right * t,
1190 b.bottom * t,
1191 )),
1192 (Some(a), Some(b)) => Some(Rect::from_ltrb(
1193 lerp_double_non_null(a.left, b.left, t),
1194 lerp_double_non_null(a.top, b.top, t),
1195 lerp_double_non_null(a.right, b.right, t),
1196 lerp_double_non_null(a.bottom, b.bottom, t),
1197 )),
1198 }
1199 }
1200}
1201
1202impl Debug for Rect {
1203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1204 write!(
1205 f,
1206 "Rect.fromLTRB({:.1}, {:.1}, {:.1}, {:.1})",
1207 self.left, self.top, self.right, self.bottom
1208 )
1209 }
1210}
1211
1212/// Dart's `Rect.toString`, the same text as [`Debug`].
1213impl fmt::Display for Rect {
1214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 Debug::fmt(self, f)
1216 }
1217}
1218
1219/// A radius for either circular or elliptical shapes.
1220#[derive(Clone, Copy, PartialEq)]
1221pub struct Radius {
1222 /// The radius value on the horizontal axis.
1223 pub x: f64,
1224
1225 /// The radius value on the vertical axis.
1226 pub y: f64,
1227}
1228
1229impl Radius {
1230 /// Constructs a circular radius. [`x`](Radius::x) and [`y`](Radius::y) will
1231 /// have the same radius value.
1232 pub const fn circular(radius: f64) -> Radius {
1233 Radius::elliptical(radius, radius)
1234 }
1235
1236 /// Constructs an elliptical radius with the given radii.
1237 pub const fn elliptical(x: f64, y: f64) -> Radius {
1238 Radius { x, y }
1239 }
1240
1241 /// A radius with [`x`](Radius::x) and [`y`](Radius::y) values set to zero.
1242 ///
1243 /// You can use [`Radius::ZERO`] with `RRect` or `RSuperellipse` to have
1244 /// right-angle corners.
1245 pub const ZERO: Radius = Radius::circular(0.0);
1246
1247 /// Returns this [`Radius`], with values clamped to the given min and max
1248 /// [`Radius`] values.
1249 ///
1250 /// The `minimum` value defaults to `Radius::circular(f64::NEG_INFINITY)`,
1251 /// and the `maximum` value defaults to `Radius::circular(f64::INFINITY)`.
1252 pub fn clamp(&self, minimum: Option<Radius>, maximum: Option<Radius>) -> Radius {
1253 let minimum = minimum.unwrap_or(Radius::circular(f64::NEG_INFINITY));
1254 let maximum = maximum.unwrap_or(Radius::circular(f64::INFINITY));
1255 Radius::elliptical(
1256 clamp_double(self.x, minimum.x, maximum.x),
1257 clamp_double(self.y, minimum.y, maximum.y),
1258 )
1259 }
1260
1261 /// Returns this [`Radius`], with values clamped to the given min and max
1262 /// values in each dimension.
1263 ///
1264 /// The `minimum_x` and `minimum_y` values default to [`f64::NEG_INFINITY`],
1265 /// and the `maximum_x` and `maximum_y` values default to [`f64::INFINITY`].
1266 pub fn clamp_values(
1267 &self,
1268 minimum_x: Option<f64>,
1269 minimum_y: Option<f64>,
1270 maximum_x: Option<f64>,
1271 maximum_y: Option<f64>,
1272 ) -> Radius {
1273 Radius::elliptical(
1274 clamp_double(
1275 self.x,
1276 minimum_x.unwrap_or(f64::NEG_INFINITY),
1277 maximum_x.unwrap_or(f64::INFINITY),
1278 ),
1279 clamp_double(
1280 self.y,
1281 minimum_y.unwrap_or(f64::NEG_INFINITY),
1282 maximum_y.unwrap_or(f64::INFINITY),
1283 ),
1284 )
1285 }
1286
1287 /// Integer (truncating) division operator.
1288 ///
1289 /// Returns a radius whose coordinates are the coordinates of this radius
1290 /// divided by the scalar `operand`, rounded towards zero.
1291 pub fn truncating_div(&self, operand: f64) -> Radius {
1292 Radius::elliptical((self.x / operand).trunc(), (self.y / operand).trunc())
1293 }
1294
1295 /// Linearly interpolate between two radii.
1296 ///
1297 /// If either is null, this function substitutes [`Radius::ZERO`] instead.
1298 ///
1299 /// The `t` argument represents position on the timeline, with 0.0 meaning
1300 /// that the interpolation has not started, returning `a` (or something
1301 /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
1302 /// returning `b` (or something equivalent to `b`), and values in between
1303 /// meaning that the interpolation is at the relevant point on the timeline
1304 /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
1305 /// 1.0, so negative values and values greater than 1.0 are valid (and can
1306 /// easily be generated by curves such as `Curves.elasticInOut`).
1307 ///
1308 /// Values for `t` are usually obtained from an `Animation<double>`, such as
1309 /// an `AnimationController`.
1310 pub fn lerp(a: Option<Radius>, b: Option<Radius>, t: f64) -> Option<Radius> {
1311 match (a, b) {
1312 (None, None) => None,
1313 (Some(a), None) => {
1314 let k = 1.0 - t;
1315 Some(Radius::elliptical(a.x * k, a.y * k))
1316 }
1317 (None, Some(b)) => Some(Radius::elliptical(b.x * t, b.y * t)),
1318 (Some(a), Some(b)) => Some(Radius::elliptical(
1319 lerp_double_non_null(a.x, b.x, t),
1320 lerp_double_non_null(a.y, b.y, t),
1321 )),
1322 }
1323 }
1324}
1325
1326/// Unary negation operator.
1327///
1328/// Returns a Radius with the distances negated.
1329///
1330/// Radiuses with negative values aren't geometrically meaningful, but could
1331/// occur as part of expressions. For example, negating a radius of one pixel
1332/// and then adding the result to another radius is equivalent to subtracting
1333/// a radius of one pixel from the other.
1334impl Neg for Radius {
1335 type Output = Radius;
1336
1337 fn neg(self) -> Radius {
1338 Radius::elliptical(-self.x, -self.y)
1339 }
1340}
1341
1342/// Binary subtraction operator.
1343///
1344/// Returns a radius whose [`x`](Radius::x) value is the left-hand-side
1345/// operand's [`x`](Radius::x) minus the right-hand-side operand's
1346/// [`x`](Radius::x) and whose [`y`](Radius::y) value is the left-hand-side
1347/// operand's [`y`](Radius::y) minus the right-hand-side operand's
1348/// [`y`](Radius::y).
1349impl Sub for Radius {
1350 type Output = Radius;
1351
1352 fn sub(self, other: Radius) -> Radius {
1353 Radius::elliptical(self.x - other.x, self.y - other.y)
1354 }
1355}
1356
1357/// Binary addition operator.
1358///
1359/// Returns a radius whose [`x`](Radius::x) value is the sum of the
1360/// [`x`](Radius::x) values of the two operands, and whose [`y`](Radius::y)
1361/// value is the sum of the [`y`](Radius::y) values of the two operands.
1362impl Add for Radius {
1363 type Output = Radius;
1364
1365 fn add(self, other: Radius) -> Radius {
1366 Radius::elliptical(self.x + other.x, self.y + other.y)
1367 }
1368}
1369
1370/// Multiplication operator.
1371///
1372/// Returns a radius whose coordinates are the coordinates of the left-hand-side
1373/// operand (a radius) multiplied by the scalar right-hand-side operand (an
1374/// `f64`).
1375impl Mul<f64> for Radius {
1376 type Output = Radius;
1377
1378 fn mul(self, operand: f64) -> Radius {
1379 Radius::elliptical(self.x * operand, self.y * operand)
1380 }
1381}
1382
1383/// Division operator.
1384///
1385/// Returns a radius whose coordinates are the coordinates of the left-hand-side
1386/// operand (a radius) divided by the scalar right-hand-side operand (an `f64`).
1387impl Div<f64> for Radius {
1388 type Output = Radius;
1389
1390 fn div(self, operand: f64) -> Radius {
1391 Radius::elliptical(self.x / operand, self.y / operand)
1392 }
1393}
1394
1395/// Modulo (remainder) operator.
1396///
1397/// Returns a radius whose coordinates are the remainder of dividing the
1398/// coordinates of the left-hand-side operand (a radius) by the scalar
1399/// right-hand-side operand (an `f64`).
1400impl Rem<f64> for Radius {
1401 type Output = Radius;
1402
1403 fn rem(self, operand: f64) -> Radius {
1404 Radius::elliptical(self.x.rem_euclid(operand), self.y.rem_euclid(operand))
1405 }
1406}
1407
1408impl Debug for Radius {
1409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410 if self.x == self.y {
1411 write!(f, "Radius.circular({:.1})", self.x)
1412 } else {
1413 write!(f, "Radius.elliptical({:.1}, {:.1})", self.x, self.y)
1414 }
1415 }
1416}
1417
1418/// Dart's `Radius.toString`, which [`Debug`] already renders.
1419impl fmt::Display for Radius {
1420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421 Debug::fmt(self, f)
1422 }
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427 use super::*;
1428
1429 #[test]
1430 fn an_offset_is_equal_to_another_with_the_same_components() {
1431 assert_eq!(Offset::new(1.0, 2.0), Offset::new(1.0, 2.0));
1432 assert_ne!(Offset::new(1.0, 2.0), Offset::new(2.0, 1.0));
1433 }
1434
1435 #[test]
1436 fn arithmetic_operators_work_component_wise() {
1437 let a = Offset::new(10.0, 20.0);
1438 let b = Offset::new(1.0, 2.0);
1439
1440 assert_eq!(a + b, Offset::new(11.0, 22.0));
1441 assert_eq!(a - b, Offset::new(9.0, 18.0));
1442 assert_eq!(a * 2.0, Offset::new(20.0, 40.0));
1443 assert_eq!(a / 2.0, Offset::new(5.0, 10.0));
1444 assert_eq!(-a, Offset::new(-10.0, -20.0));
1445 assert_eq!(a.scale(2.0, 3.0), Offset::new(20.0, 60.0));
1446 assert_eq!(a.translate(1.0, -1.0), Offset::new(11.0, 19.0));
1447 }
1448
1449 #[test]
1450 fn remainder_follows_dart_and_stays_non_negative() {
1451 assert_eq!(Offset::new(-5.0, 5.0) % 3.0, Offset::new(1.0, 2.0));
1452 assert_eq!(-5.0_f64 % 3.0, -2.0);
1453 }
1454
1455 #[test]
1456 fn truncating_division_rounds_towards_zero() {
1457 assert_eq!(
1458 Offset::new(-5.0, 5.0).truncating_div(3.0),
1459 Offset::new(-1.0, 1.0)
1460 );
1461 }
1462
1463 #[test]
1464 fn distance_and_direction_describe_the_same_vector_as_the_components() {
1465 let offset = Offset::new(3.0, 4.0);
1466 assert_eq!(offset.distance(), 5.0);
1467 assert_eq!(offset.distance_squared(), 25.0);
1468
1469 let rebuilt = Offset::from_direction(offset.direction(), offset.distance());
1470 assert!((rebuilt.dx() - 3.0).abs() < 1e-12);
1471 assert!((rebuilt.dy() - 4.0).abs() < 1e-12);
1472 }
1473
1474 #[test]
1475 fn comparison_is_component_wise_and_only_partial() {
1476 let a = Offset::new(1.0, 2.0);
1477 let b = Offset::new(2.0, 3.0);
1478 assert!(a.lt(&b));
1479 assert!(a.le(&b));
1480 assert!(b.gt(&a));
1481 assert!(b.ge(&a));
1482
1483 let c = Offset::new(1.0, 3.0);
1484 let d = Offset::new(2.0, 2.0);
1485 assert!(!c.lt(&d) && !c.le(&d) && !c.gt(&d) && !c.ge(&d));
1486
1487 let e = Offset::new(1.0, 2.0);
1488 let f = Offset::new(1.0, 3.0);
1489 assert!(e.le(&f));
1490 assert!(!e.lt(&f));
1491 assert_ne!(e, f);
1492 }
1493
1494 #[test]
1495 fn finiteness_asks_about_either_component_or_both() {
1496 assert!(Offset::INFINITE.is_infinite());
1497 assert!(Offset::new(0.0, f64::INFINITY).is_infinite());
1498 assert!(!Offset::new(0.0, f64::NEG_INFINITY).is_infinite());
1499 assert!(!Offset::new(0.0, f64::NAN).is_infinite());
1500
1501 assert!(Offset::ZERO.is_finite());
1502 assert!(!Offset::new(0.0, f64::NAN).is_finite());
1503 }
1504
1505 #[test]
1506 fn lerp_defaults_a_missing_end_to_zero() {
1507 let a = Offset::new(0.0, 10.0);
1508 let b = Offset::new(10.0, 0.0);
1509
1510 assert_eq!(
1511 Offset::lerp(Some(a), Some(b), 0.5),
1512 Some(Offset::new(5.0, 5.0))
1513 );
1514 assert_eq!(
1515 Offset::lerp(Some(a), None, 0.5),
1516 Some(Offset::new(0.0, 5.0))
1517 );
1518 assert_eq!(
1519 Offset::lerp(None, Some(b), 0.5),
1520 Some(Offset::new(5.0, 0.0))
1521 );
1522 assert_eq!(Offset::lerp(None, None, 0.5), None);
1523 }
1524
1525 #[test]
1526 fn debug_matches_flutter_to_string() {
1527 assert_eq!(format!("{:?}", Offset::new(1.0, 2.5)), "Offset(1.0, 2.5)");
1528 }
1529
1530 // engine geometry_test.dart 'Size.aspectRatio'.
1531 #[test]
1532 fn size_aspect_ratio_covers_the_zero_and_infinite_arms() {
1533 assert_eq!(Size::new(0.0, 0.0).aspect_ratio(), 0.0);
1534 assert_eq!(Size::new(-0.0, 0.0).aspect_ratio(), 0.0);
1535 assert_eq!(Size::new(1.0, 0.0).aspect_ratio(), f64::INFINITY);
1536 assert_eq!(Size::new(-1.0, 0.0).aspect_ratio(), f64::NEG_INFINITY);
1537 assert_eq!(Size::new(3.0, 2.0).aspect_ratio(), 1.5);
1538 assert_eq!(Size::new(3.0, -2.0).aspect_ratio(), -1.5);
1539 assert_eq!(Size::new(-3.0, 2.0).aspect_ratio(), -1.5);
1540 assert_eq!(Size::new(0.0, -1.0).aspect_ratio(), -0.0);
1541 }
1542
1543 #[test]
1544 fn size_shortest_and_longest_side_use_magnitudes() {
1545 let size = Size::new(-9.0, 4.0);
1546 assert_eq!(size.shortest_side(), 4.0);
1547 assert_eq!(size.longest_side(), 9.0);
1548 }
1549
1550 #[test]
1551 fn subtracting_sizes_gives_the_offset_between_their_corners() {
1552 let offset: Offset = Size::new(5.0, 7.0) - Size::new(3.0, 2.0);
1553 assert_eq!(offset, Offset::new(2.0, 5.0));
1554
1555 let size: Size = Size::new(5.0, 7.0) - Offset::new(3.0, 2.0);
1556 assert_eq!(size, Size::new(2.0, 5.0));
1557
1558 assert_eq!(
1559 Size::new(5.0, 7.0) + Offset::new(3.0, 2.0),
1560 Size::new(8.0, 9.0)
1561 );
1562 }
1563
1564 #[test]
1565 fn size_comparison_operators_are_component_wise() {
1566 let small = Size::new(1.0, 2.0);
1567 let large = Size::new(3.0, 4.0);
1568 let mixed = Size::new(5.0, 1.0);
1569
1570 assert!(small.lt(&large));
1571 assert!(small.le(&small));
1572 assert!(large.gt(&small));
1573 assert!(!small.lt(&mixed), "only one component is smaller");
1574 assert!(!mixed.gt(&small));
1575 }
1576
1577 #[test]
1578 fn size_lerp_matches_darts_null_arms() {
1579 assert_eq!(Size::lerp(None, None, 0.5), None);
1580 assert_eq!(
1581 Size::lerp(Some(Size::new(4.0, 8.0)), None, 0.25),
1582 Some(Size::new(3.0, 6.0))
1583 );
1584 assert_eq!(
1585 Size::lerp(None, Some(Size::new(4.0, 8.0)), 0.25),
1586 Some(Size::new(1.0, 2.0))
1587 );
1588 assert_eq!(
1589 Size::lerp(Some(Size::ZERO), Some(Size::new(4.0, 8.0)), 0.5),
1590 Some(Size::new(2.0, 4.0))
1591 );
1592 }
1593
1594 #[test]
1595 fn size_contains_includes_top_left_and_excludes_bottom_right() {
1596 let size = Size::new(2.0, 2.0);
1597 assert!(size.contains(Offset::ZERO));
1598 assert!(size.contains(Offset::new(1.9, 1.9)));
1599 assert!(!size.contains(Offset::new(2.0, 1.0)));
1600 assert!(!size.contains(Offset::new(-0.1, 1.0)));
1601 }
1602
1603 // engine geometry_test.dart 'Rect accessors': fromLTRB(1,3,5,7).
1604 #[test]
1605 fn rect_accessors() {
1606 let rect = Rect::from_ltrb(1.0, 3.0, 5.0, 7.0);
1607 assert_eq!(rect.left, 1.0);
1608 assert_eq!(rect.top, 3.0);
1609 assert_eq!(rect.right, 5.0);
1610 assert_eq!(rect.bottom, 7.0);
1611 assert_eq!(rect.width(), 4.0);
1612 assert_eq!(rect.height(), 4.0);
1613 assert_eq!(rect.size(), Size::new(4.0, 4.0));
1614 assert_eq!(rect.center(), Offset::new(3.0, 5.0));
1615 }
1616
1617 // engine geometry_test.dart 'Rect created by width and height'.
1618 #[test]
1619 fn rect_from_ltwh_matches_ltrb() {
1620 assert_eq!(
1621 Rect::from_ltwh(1.0, 3.0, 4.0, 4.0),
1622 Rect::from_ltrb(1.0, 3.0, 5.0, 7.0)
1623 );
1624 }
1625
1626 // engine geometry_test.dart 'Rect created from center': 5x7 about (1, 3),
1627 // plus the NaN case.
1628 #[test]
1629 fn rect_from_center() {
1630 let rect = Rect::from_center(Offset::new(1.0, 3.0), 5.0, 7.0);
1631 assert_eq!(rect, Rect::from_ltrb(-1.5, -0.5, 3.5, 6.5));
1632
1633 let nan = Rect::from_center(Offset::new(f64::NAN, 3.0), 5.0, 7.0);
1634 assert!(nan.has_nan());
1635
1636 assert_eq!(
1637 Rect::from_points(Offset::new(5.0, 7.0), Offset::new(1.0, 3.0)),
1638 Rect::from_ltrb(1.0, 3.0, 5.0, 7.0)
1639 );
1640 }
1641
1642 // engine geometry_test.dart 'Rect.toString'.
1643 #[test]
1644 fn rect_debug_matches_darts_to_string() {
1645 assert_eq!(
1646 format!("{:?}", Rect::from_ltrb(1.0, 3.0, 5.0, 7.0)),
1647 "Rect.fromLTRB(1.0, 3.0, 5.0, 7.0)"
1648 );
1649 assert_eq!(format!("{:?}", Size::new(2.0, 3.0)), "Size(2.0, 3.0)");
1650 }
1651
1652 #[test]
1653 fn an_offset_and_a_size_make_a_rect() {
1654 let from_origin = Offset::ZERO & Size::new(100.0, 100.0);
1655 assert_eq!(from_origin, Rect::from_ltwh(0.0, 0.0, 100.0, 100.0));
1656
1657 let rect = Offset::new(1.0, 2.0) & Size::new(3.0, 4.0);
1658 assert_eq!(rect, Rect::from_ltwh(1.0, 2.0, 3.0, 4.0));
1659 }
1660
1661 #[test]
1662 fn rect_intersect_and_overlaps_agree_on_the_shared_edge() {
1663 let a = Rect::from_ltrb(0.0, 0.0, 10.0, 10.0);
1664 let b = Rect::from_ltrb(5.0, 5.0, 15.0, 15.0);
1665 assert_eq!(a.intersect(b), Rect::from_ltrb(5.0, 5.0, 10.0, 10.0));
1666 assert!(a.overlaps(b));
1667
1668 let touching = Rect::from_ltrb(10.0, 0.0, 20.0, 10.0);
1669 assert!(!a.overlaps(touching), "a shared edge is not an overlap");
1670 assert!(a.intersect(touching).is_empty());
1671
1672 assert_eq!(
1673 a.expand_to_include(touching),
1674 Rect::from_ltrb(0.0, 0.0, 20.0, 10.0)
1675 );
1676
1677 let zero_area = Rect::from_ltrb(-5.0, 2.0, -5.0, 2.0);
1678 assert_eq!(
1679 a.expand_to_include(zero_area),
1680 Rect::from_ltrb(-5.0, 0.0, 10.0, 10.0)
1681 );
1682 }
1683
1684 #[test]
1685 fn rect_contains_includes_top_left_and_excludes_bottom_right() {
1686 let rect = Rect::from_ltrb(1.0, 1.0, 2.0, 2.0);
1687 assert!(rect.contains(Offset::new(1.0, 1.0)));
1688 assert!(!rect.contains(Offset::new(2.0, 2.0)));
1689 assert!(!rect.contains(Offset::new(2.0, 1.5)));
1690 }
1691
1692 #[test]
1693 fn rect_lerp_matches_darts_null_arms() {
1694 let rect = Rect::from_ltrb(4.0, 8.0, 12.0, 16.0);
1695 assert_eq!(Rect::lerp(None, None, 0.5), None);
1696 assert_eq!(
1697 Rect::lerp(Some(rect), None, 0.5),
1698 Some(Rect::from_ltrb(2.0, 4.0, 6.0, 8.0))
1699 );
1700 assert_eq!(
1701 Rect::lerp(None, Some(rect), 0.5),
1702 Some(Rect::from_ltrb(2.0, 4.0, 6.0, 8.0))
1703 );
1704 assert_eq!(
1705 Rect::lerp(Some(Rect::ZERO), Some(rect), 0.5),
1706 Some(Rect::from_ltrb(2.0, 4.0, 6.0, 8.0))
1707 );
1708 }
1709
1710 #[test]
1711 fn rect_shift_translate_inflate_deflate() {
1712 let rect = Rect::from_ltrb(0.0, 0.0, 4.0, 4.0);
1713 assert_eq!(
1714 rect.shift(Offset::new(1.0, 2.0)),
1715 Rect::from_ltrb(1.0, 2.0, 5.0, 6.0)
1716 );
1717 assert_eq!(rect.translate(1.0, 2.0), rect.shift(Offset::new(1.0, 2.0)));
1718 assert_eq!(rect.inflate(1.0), Rect::from_ltrb(-1.0, -1.0, 5.0, 5.0));
1719 assert_eq!(rect.inflate(1.0).deflate(1.0), rect);
1720 }
1721
1722 // engine geometry_test.dart 'Radius.clamp() operates as expected'.
1723 #[test]
1724 fn radius_clamp_operates_as_expected() {
1725 assert_eq!(
1726 Radius::circular(-100.0).clamp(Some(Radius::ZERO), None),
1727 Radius::circular(0.0)
1728 );
1729 assert_eq!(
1730 Radius::circular(100.0).clamp(None, Some(Radius::circular(10.0))),
1731 Radius::circular(10.0)
1732 );
1733 assert_eq!(
1734 Radius::elliptical(-100.0, 100.0)
1735 .clamp(Some(Radius::ZERO), Some(Radius::circular(10.0))),
1736 Radius::elliptical(0.0, 10.0)
1737 );
1738 assert_eq!(
1739 Radius::elliptical(100.0, -100.0)
1740 .clamp(Some(Radius::ZERO), Some(Radius::circular(10.0))),
1741 Radius::elliptical(10.0, 0.0)
1742 );
1743 }
1744
1745 // engine geometry_test.dart 'Radius.clampValues() operates as expected'.
1746 #[test]
1747 fn radius_clamp_values_operates_as_expected() {
1748 assert_eq!(
1749 Radius::circular(-100.0).clamp_values(Some(0.0), Some(0.0), None, None),
1750 Radius::circular(0.0)
1751 );
1752 assert_eq!(
1753 Radius::circular(100.0).clamp_values(None, None, Some(10.0), Some(20.0)),
1754 Radius::elliptical(10.0, 20.0)
1755 );
1756 assert_eq!(
1757 Radius::elliptical(-100.0, 100.0).clamp_values(
1758 Some(5.0),
1759 Some(6.0),
1760 Some(10.0),
1761 Some(20.0)
1762 ),
1763 Radius::elliptical(5.0, 20.0)
1764 );
1765 assert_eq!(
1766 Radius::elliptical(100.0, -100.0).clamp_values(
1767 Some(5.0),
1768 Some(6.0),
1769 Some(10.0),
1770 Some(20.0)
1771 ),
1772 Radius::elliptical(10.0, 6.0)
1773 );
1774 }
1775
1776 #[test]
1777 fn radius_arithmetic_is_component_wise() {
1778 let a = Radius::elliptical(10.0, 20.0);
1779 let b = Radius::elliptical(1.0, 2.0);
1780
1781 assert_eq!(a + b, Radius::elliptical(11.0, 22.0));
1782 assert_eq!(a - b, Radius::elliptical(9.0, 18.0));
1783 assert_eq!(a * 2.0, Radius::elliptical(20.0, 40.0));
1784 assert_eq!(a / 2.0, Radius::elliptical(5.0, 10.0));
1785 assert_eq!(-a, Radius::elliptical(-10.0, -20.0));
1786 assert_eq!(a.truncating_div(3.0), Radius::elliptical(3.0, 6.0));
1787 assert_eq!(
1788 Radius::elliptical(-5.0, 5.0) % 3.0,
1789 Radius::elliptical(1.0, 2.0)
1790 );
1791 assert_eq!(
1792 Radius::elliptical(-5.0, 5.0).truncating_div(3.0),
1793 Radius::elliptical(-1.0, 1.0)
1794 );
1795 }
1796
1797 #[test]
1798 fn radius_circular_equals_elliptical_when_axes_match() {
1799 assert_eq!(Radius::circular(5.0), Radius::elliptical(5.0, 5.0));
1800 assert_ne!(Radius::circular(5.0), Radius::elliptical(5.0, 6.0));
1801 assert_eq!(Radius::ZERO, Radius::circular(0.0));
1802 }
1803
1804 #[test]
1805 fn radius_lerp_defaults_a_missing_end_to_zero() {
1806 let a = Radius::elliptical(0.0, 10.0);
1807 let b = Radius::elliptical(10.0, 0.0);
1808
1809 assert_eq!(
1810 Radius::lerp(Some(a), Some(b), 0.5),
1811 Some(Radius::elliptical(5.0, 5.0))
1812 );
1813 assert_eq!(
1814 Radius::lerp(Some(a), None, 0.5),
1815 Some(Radius::elliptical(0.0, 5.0))
1816 );
1817 assert_eq!(
1818 Radius::lerp(None, Some(b), 0.5),
1819 Some(Radius::elliptical(5.0, 0.0))
1820 );
1821 assert_eq!(Radius::lerp(None, None, 0.5), None);
1822 }
1823
1824 #[test]
1825 fn radius_debug_matches_darts_to_string() {
1826 assert_eq!(
1827 format!("{:?}", Radius::circular(1.5)),
1828 "Radius.circular(1.5)"
1829 );
1830 assert_eq!(
1831 format!("{:?}", Radius::elliptical(1.0, 2.5)),
1832 "Radius.elliptical(1.0, 2.5)"
1833 );
1834 }
1835}