ingraph/primitives/geometry/quad.rs
1//! [`Quad<T>`](Quad): four corners in WINDING ORDER, and the one convention in this house that a
2//! test exists to pin rather than to document.
3
4use crate::{
5 ColumnEq, ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker,
6 CursorValue, DefaultMarker, DefaultVecMarker, FieldName, PayloadFilter, QuantifiedMarker,
7};
8
9use super::{NormCoord, Point2, Point2Filter};
10
11/// **One leaf, and it is the value** — Quad<T> means its columns in the sequence it declares them, so
12/// no term over one ever expands and the word is the whole row.
13impl<T> crate::DeclaredLeaves for Quad<T> {}
14
15#[cfg(test)]
16mod tests;
17
18/// **A QUADRILATERAL** — four corners, in whatever `T` the declaration measures in.
19///
20/// ```text
21/// top_left ●──────────● top_right
22/// │ │
23/// │ │
24/// bottom_left ●──────────● bottom_right
25/// ```
26///
27/// It is the shape a rectangle stops being able to hold: a document photographed at an angle, a
28/// text line on a curled page, a barcode seen off-axis. A [`BoundingBox`](super::BoundingBox) can
29/// only be the axis-aligned box AROUND such a thing, which is a different and coarser fact.
30///
31/// # PERIMETER WINDING ORDER — top-left, top-right, bottom-right, bottom-left
32///
33/// **The order is not raster order, and reading it as one builds a bow-tie out of every real
34/// quadrilateral.** `(TL, TR, BL, BR)` — the order a reader who thinks in rows expects — walks the
35/// perimeter as a figure-eight, crossing itself between the second and third corners. That is
36/// `avanalyze`'s `DocumentSegment` contract word for word, whose own note says a conformance suite
37/// pins it by feeding a well-formed quad in winding order; this house pins it the same way, in
38/// `quad/tests.rs`, because a convention that only a doc comment holds is a convention one
39/// refactor away from being lost.
40///
41/// The corner NAMES are what make the order checkable rather than remembered. A positional
42/// four-tuple would let two of the four be transposed with no type error and no test failure that
43/// named the cause; four [`Point2<T>`](Point2) fields under their own names cannot be.
44///
45/// # A DUMB GENERIC HOLDER, and the corners are not checked against each other
46///
47/// [`new`](Self::new) is total and `const`. **Convexity, self-intersection and whether the corner a
48/// field calls `top_left` is actually the topmost-leftmost are NOT checked**, and the omission is
49/// deliberate rather than deferred: a quadrilateral seen at an angle can have its `top_left` below
50/// its `top_right` in the frame, so a check that enforced the names would refuse exactly the
51/// observations this type exists to hold. What the names carry is the ORDER a producer emits in,
52/// which is the thing a consumer has to agree about.
53///
54/// # NO `Ord`, and the BOX around a quad is a METHOD rather than a conversion
55///
56/// Four positions have no order, for [`Point2`]'s reason multiplied. The axis-aligned box around a
57/// quad IS a genuine reading and it has landed as [`bounds`](Self::bounds) — bounded on the
58/// component's own comparison and subtraction, spelled at the method rather than at the type. It is
59/// not a `From`: the projection is LOSSY, so a caller says the word.
60///
61/// # Examples
62///
63/// ```
64/// use ingraph::{NormCoord, Point2, Quad};
65///
66/// let corner = |x: f32, y: f32| Point2::try_unit(x, y).unwrap();
67/// let page = Quad::new(
68/// corner(0.10, 0.12),
69/// corner(0.90, 0.10),
70/// corner(0.92, 0.88),
71/// corner(0.08, 0.90),
72/// );
73///
74/// assert_eq!(page.top_left().x(), NormCoord::new(0.10).unwrap());
75/// assert_eq!(page.bottom_left().y(), NormCoord::new(0.90).unwrap());
76/// ```
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78pub struct Quad<T> {
79 top_left: Point2<T>,
80 top_right: Point2<T>,
81 bottom_right: Point2<T>,
82 bottom_left: Point2<T>,
83}
84
85impl<T> Quad<T> {
86 /// The quadrilateral through these four corners, **in winding order**.
87 ///
88 /// The parameter order is the winding one and the names say so, which is the whole of this
89 /// constructor's contract: see the type's note for what reading it as raster order costs.
90 #[inline]
91 #[must_use]
92 pub const fn new(
93 top_left: Point2<T>,
94 top_right: Point2<T>,
95 bottom_right: Point2<T>,
96 bottom_left: Point2<T>,
97 ) -> Self {
98 Self {
99 top_left,
100 top_right,
101 bottom_right,
102 bottom_left,
103 }
104 }
105
106 /// The first corner in winding order.
107 #[inline]
108 pub const fn top_left(&self) -> Point2<T>
109 where
110 T: Copy,
111 {
112 self.top_left
113 }
114
115 /// The second corner in winding order.
116 #[inline]
117 pub const fn top_right(&self) -> Point2<T>
118 where
119 T: Copy,
120 {
121 self.top_right
122 }
123
124 /// The third corner in winding order.
125 #[inline]
126 pub const fn bottom_right(&self) -> Point2<T>
127 where
128 T: Copy,
129 {
130 self.bottom_right
131 }
132
133 /// The fourth corner in winding order.
134 #[inline]
135 pub const fn bottom_left(&self) -> Point2<T>
136 where
137 T: Copy,
138 {
139 self.bottom_left
140 }
141
142 /// The four corners, **in winding order** — the reading a renderer walks a perimeter with.
143 ///
144 /// An array rather than an iterator, because the arity is the type's and a caller destructuring
145 /// four names wants them by position once they have agreed what the positions mean.
146 #[inline]
147 pub const fn corners(&self) -> [Point2<T>; 4]
148 where
149 T: Copy,
150 {
151 [
152 self.top_left,
153 self.top_right,
154 self.bottom_right,
155 self.bottom_left,
156 ]
157 }
158
159 /// **THE TIGHTEST AXIS-ALIGNED RECTANGLE THE FOUR CORNERS SPAN** — derived at the call, stored by
160 /// nobody.
161 ///
162 /// A quad is what a rectangle stops being able to hold, and this is the reduction back: the
163 /// smallest `xywh` box containing all four corners. It is what a crop, a thumbnail and an area
164 /// filter each want from a photographed page, and it is LOSSY — the angle is gone — which is why
165 /// it is a method a caller spells rather than a `From` the compiler applies.
166 ///
167 /// A stored box beside the corners would have been a fifth value the corners already determine and
168 /// an `UPDATE` could put out of step with them. That is
169 /// [`BoundingBox`](super::BoundingBox)'s own argument for `xywh` over a second corner, read one
170 /// figure up.
171 ///
172 /// # THE BOUND IS THIS METHOD'S, and the census that picked it
173 ///
174 /// `T: Copy + PartialOrd + Sub<Output = T>` — the honest minimum for *four comparisons and two
175 /// subtractions*, stated at the method exactly as [`corners`](Self::corners) states its own
176 /// `T: Copy`. A quad over a component with no arithmetic is still a quad a caller can build, store
177 /// and read back; only this reading is unavailable on it.
178 ///
179 /// **`PartialOrd` rather than `Ord`, and the choice is what admits the floats.** `f32` and `f64`
180 /// are the widths every producer of quads measures in and neither publishes `Ord`. The comparison
181 /// below is written with `<` so an INCOMPARABLE pair — a `NaN` corner in a component that admits
182 /// one — leaves the running extreme where it was rather than panicking inside a reduction.
183 ///
184 /// # [`NormCoord`](super::NormCoord) IS OUT OF BOUNDS HERE, and it is a census finding
185 ///
186 /// The unit interval is closed under MULTIPLICATION and not under SUBTRACTION — `0.2 - 0.8` is
187 /// `-0.6`, which is no coordinate — so that type publishes a `Mul` and no `Sub`, and this method's
188 /// bound is therefore unsatisfied by it. `Quad<f32>` and `Quad<f64>` reach it and
189 /// `Quad<NormCoord>` does not.
190 ///
191 /// That is deliberate rather than an omission. Closing it would mean an operator that saturates,
192 /// clamps or panics on the values its own domain excludes, which is the *value quietly minted
193 /// around the hole* this house refuses at every other door. What a normalized caller spends
194 /// instead is one [`map`](Self::map)-shaped hop into the width it wants to measure the box in —
195 /// and the reduction is a fraction of a frame either way.
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// use ingraph::{Point2, Quad};
201 ///
202 /// // A page photographed at an angle: no two corners share a coordinate.
203 /// let page = Quad::new(
204 /// Point2::new(0.10_f32, 0.11),
205 /// Point2::new(0.90, 0.12),
206 /// Point2::new(0.91, 0.88),
207 /// Point2::new(0.13, 0.89),
208 /// );
209 ///
210 /// let around = page.bounds();
211 /// assert_eq!(around.x(), 0.10);
212 /// assert_eq!(around.y(), 0.11);
213 /// assert_eq!(around.width(), 0.91 - 0.10);
214 /// assert_eq!(around.height(), 0.89 - 0.11);
215 /// ```
216 #[must_use]
217 pub fn bounds(&self) -> super::BoundingBox<T>
218 where
219 T: Copy + PartialOrd + core::ops::Sub<Output = T>,
220 {
221 let corners = self.corners();
222 let (mut min_x, mut min_y) = (corners[0].x(), corners[0].y());
223 let (mut max_x, mut max_y) = (min_x, min_y);
224
225 for corner in &corners[1..] {
226 let (x, y) = (corner.x(), corner.y());
227
228 // `<` rather than a `min`/`max` reduction, so an incomparable pair leaves the running
229 // extreme where it was instead of reaching a total order the component does not publish.
230 if x < min_x {
231 min_x = x;
232 }
233 if max_x < x {
234 max_x = x;
235 }
236 if y < min_y {
237 min_y = y;
238 }
239 if max_y < y {
240 max_y = y;
241 }
242 }
243
244 super::BoundingBox::new(min_x, min_y, max_x - min_x, max_y - min_y)
245 }
246}
247
248impl Quad<NormCoord> {
249 /// **The unit frame's constructor** — eight numbers, four corners, winding order.
250 ///
251 /// Each pair goes through [`Point2::try_unit`], so the refusal is the COMPONENT's and this
252 /// constructor adds no rule of its own. A quad has no sum rule to check —
253 /// [`BoundingBox::try_unit`](super::BoundingBox::try_unit) has one because an extent is added to
254 /// a corner, and every number here IS a corner.
255 ///
256 /// # Errors
257 ///
258 /// [`OutsideTheUnitInterval`](super::OutsideTheUnitInterval) where any of the eight is not a
259 /// coordinate.
260 ///
261 /// # Examples
262 ///
263 /// ```
264 /// use ingraph::Quad;
265 ///
266 /// assert!(Quad::try_unit((0.1, 0.1), (0.9, 0.1), (0.9, 0.9), (0.1, 0.9)).is_ok());
267 /// assert!(Quad::try_unit((0.1, 0.1), (1.9, 0.1), (0.9, 0.9), (0.1, 0.9)).is_err());
268 /// ```
269 pub fn try_unit(
270 top_left: (f32, f32),
271 top_right: (f32, f32),
272 bottom_right: (f32, f32),
273 bottom_left: (f32, f32),
274 ) -> Result<Self, super::OutsideTheUnitInterval> {
275 let corner = |(x, y): (f32, f32)| Point2::try_unit(x, y);
276
277 Ok(Self::new(
278 corner(top_left)?,
279 corner(top_right)?,
280 corner(bottom_right)?,
281 corner(bottom_left)?,
282 ))
283 }
284}
285
286/// The first corner's segment.
287pub(super) const TOP_LEFT: &FieldName = FieldName::new("top_left");
288
289/// The second corner's segment.
290pub(super) const TOP_RIGHT: &FieldName = FieldName::new("top_right");
291
292/// The third corner's segment.
293pub(super) const BOTTOM_RIGHT: &FieldName = FieldName::new("bottom_right");
294
295/// The fourth corner's segment.
296pub(super) const BOTTOM_LEFT: &FieldName = FieldName::new("bottom_left");
297
298/// **The EIGHT columns a quadrilateral spans** — four corners, each a nested
299/// [`Point2<T>`](Point2), each spending its own two.
300///
301/// The corners NEST rather than flatten, so a declaration writes `corners_top_left_x` and the frame
302/// says which corner a column belongs to. Flattening them would put eight columns called `x`, `y`,
303/// `x`, `y`, … in one namespace, which is a collision the renderer would have to invent names
304/// around.
305///
306/// The LEAF GUARD is stated on the COMPONENT rather than on the corner, and that is the honest
307/// place: `Point2<T>` is a composite by construction so an assertion about ITS width would always
308/// fail, while the fact that decides this type's arity is the one two levels down — a component
309/// spanning one column makes a corner two and a quad eight.
310///
311/// ```compile_fail,E0080
312/// use ingraph::{ColumnKind, Quad, TimeRange};
313///
314/// const _: usize = <Quad<TimeRange> as ColumnKind>::SEGMENTS.len();
315/// ```
316impl<T: ColumnKind> ColumnKind for Quad<T> {
317 const SEGMENTS: &'static [ColumnShape] = {
318 assert!(
319 T::SEGMENTS.is_empty(),
320 "a quad's component spans ONE column: a composite component would make the quad's own width \
321 depend on it, and a fixed-arity row cannot state that"
322 );
323 &[
324 ColumnShape::Composite {
325 field: Some(ColumnName::of(TOP_LEFT)),
326 segments: <Point2<T> as ColumnKind>::SEGMENTS,
327 },
328 ColumnShape::Composite {
329 field: Some(ColumnName::of(TOP_RIGHT)),
330 segments: <Point2<T> as ColumnKind>::SEGMENTS,
331 },
332 ColumnShape::Composite {
333 field: Some(ColumnName::of(BOTTOM_RIGHT)),
334 segments: <Point2<T> as ColumnKind>::SEGMENTS,
335 },
336 ColumnShape::Composite {
337 field: Some(ColumnName::of(BOTTOM_LEFT)),
338 segments: <Point2<T> as ColumnKind>::SEGMENTS,
339 },
340 ]
341 };
342}
343
344/// A quadrilateral is one column value when all four of its corners are, in winding order — the
345/// same order the columns nest under.
346impl<T: ColumnEq> ColumnEq for Quad<T> {
347 #[inline]
348 fn column_eq(&self, other: &Self) -> bool {
349 self.top_left.column_eq(&other.top_left)
350 && self.top_right.column_eq(&other.top_right)
351 && self.bottom_right.column_eq(&other.bottom_right)
352 && self.bottom_left.column_eq(&other.bottom_left)
353 }
354}
355
356/// **The DECLARED half — EIGHT words**, the component's own, eight times, in the order the segments
357/// above state.
358impl<Db, T> crate::StoredAs<Db> for Quad<T>
359where
360 T: crate::StoredAs<Db>,
361{
362 const WORDS: &'static [&'static str] = &[
363 <T as crate::StoredAs<Db>>::WORDS[0],
364 <T as crate::StoredAs<Db>>::WORDS[0],
365 <T as crate::StoredAs<Db>>::WORDS[0],
366 <T as crate::StoredAs<Db>>::WORDS[0],
367 <T as crate::StoredAs<Db>>::WORDS[0],
368 <T as crate::StoredAs<Db>>::WORDS[0],
369 <T as crate::StoredAs<Db>>::WORDS[0],
370 <T as crate::StoredAs<Db>>::WORDS[0],
371 ];
372}
373
374/// **THE ADMISSION**, delegating to the component. `Vec<Quad<NormCoord>>` is every text line on a
375/// page, every document in a photograph — the shape a segmentation pass produces.
376impl<T: crate::CollectionElement> crate::CollectionElement for Quad<T> {}
377
378/// **EIGHT BINDS OUT**, four corners with three commas between them; each corner writes its own.
379#[cfg(feature = "sqlx")]
380impl<T, Db> crate::Carrier<Db> for Quad<T>
381where
382 Db: sqlx::Database,
383 T: crate::Carrier<Db>,
384{
385 fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
386 <Point2<T> as crate::Carrier<Db>>::push_bind(&self.top_left, qb);
387 qb.push(", ");
388 <Point2<T> as crate::Carrier<Db>>::push_bind(&self.top_right, qb);
389 qb.push(", ");
390 <Point2<T> as crate::Carrier<Db>>::push_bind(&self.bottom_right, qb);
391 qb.push(", ");
392 <Point2<T> as crate::Carrier<Db>>::push_bind(&self.bottom_left, qb);
393 }
394}
395
396/// **AND THE EIGHT BACK IN**, each corner beneath its own frame.
397#[cfg(feature = "sqlx")]
398impl<'a, R, T> crate::Assemble<'a, R> for Quad<T>
399where
400 R: sqlx::Row,
401 T: crate::Assemble<'a, R>,
402{
403 fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
404 let top_left: Point2<T> = crate::assembled(row, TOP_LEFT, under)?;
405 let top_right: Point2<T> = crate::assembled(row, TOP_RIGHT, under)?;
406 let bottom_right: Point2<T> = crate::assembled(row, BOTTOM_RIGHT, under)?;
407 let bottom_left: Point2<T> = crate::assembled(row, BOTTOM_LEFT, under)?;
408
409 Ok(Self::new(top_left, top_right, bottom_right, bottom_left))
410 }
411}
412
413/// **THE KEYSET POSITION** — the four corners in WINDING order, which is the segment order.
414///
415/// A STORAGE order, for the family's reason: this type publishes no [`Ord`].
416impl<T: CursorValue> CursorValue for Quad<T> {
417 fn write_cursor(&self, out: &mut Vec<u8>) {
418 for corner in [
419 &self.top_left,
420 &self.top_right,
421 &self.bottom_right,
422 &self.bottom_left,
423 ] {
424 CursorValue::write_cursor(corner, out);
425 }
426 }
427
428 fn read_cursor(bytes: &[u8]) -> Option<Self> {
429 let corner = bytes.len() / 4;
430 if corner == 0 || corner * 4 != bytes.len() {
431 return None;
432 }
433
434 let read =
435 |nth: usize| <Point2<T> as CursorValue>::read_cursor(&bytes[nth * corner..][..corner]);
436
437 Some(Self::new(read(0)?, read(1)?, read(2)?, read(3)?))
438 }
439}
440
441/// The COMPOSITE reading, on the family's terms.
442impl<T: DefaultMarker> DefaultMarker for Quad<T> {
443 type Marker = CompositeMarker<Quad<T>>;
444}
445
446/// **A COLLECTION of quadrilaterals is asked through the QUANTIFIERS alone.**
447impl<T: DefaultMarker> DefaultVecMarker for Quad<T> {
448 type Marker = QuantifiedMarker<Vec<Quad<T>>>;
449}
450
451/// What guards a [`Quad<T>`] column — its own filter at both seats, framework-open through
452/// [`PayloadFilter<T>`](crate::PayloadFilter).
453impl<T> CompositeFilterMarker for Quad<T>
454where
455 T: DefaultMarker,
456{
457 type Filter = QuadFilter<PayloadFilter<T>>;
458 type ColumnFilter = QuadFilter<PayloadFilter<T>>;
459}
460
461/// **FOUR CORNER FACETS, each a whole [`Point2Filter`], and no whole-quad operator.**
462///
463/// ```text
464/// input QuadF32Filter {
465/// topLeft: Point2F32Filter topRight: Point2F32Filter
466/// bottomRight: Point2F32Filter bottomLeft: Point2F32Filter
467/// }
468/// ```
469///
470/// The facets NEST rather than publishing eight component slots, which mirrors the columns: a
471/// corner is a citizen, so everything a [`Point2Filter`] can answer is answerable one level up
472/// without a line of it being restated. That is the recursion
473/// [`MediaTimeRangeFilter`](crate::MediaTimeRangeFilter) has over its timebase, one house over.
474///
475/// The leaf-tuple EQUALITY is the conjunction of the eight leaf facets, and whole-quad ordering is
476/// refused STRUCTURALLY — no slot takes a quad-shaped bound. Both arguments are at
477/// [`BoundingBoxFilter`](super::BoundingBoxFilter).
478///
479/// The SPATIAL door here is the widest in the family and the least ready: *this quad contains that
480/// point* is a point-in-polygon test, which is a computation rather than a column comparison and
481/// belongs to whatever can run one. Nothing about the columns stored here forecloses it.
482pub struct QuadFilter<CF> {
483 pub(super) top_left: Option<Point2Filter<CF>>,
484 pub(super) top_right: Option<Point2Filter<CF>>,
485 pub(super) bottom_right: Option<Point2Filter<CF>>,
486 pub(super) bottom_left: Option<Point2Filter<CF>>,
487}
488
489impl<CF> QuadFilter<CF> {
490 /// The empty filter — no corner set, so a column guarded by it is unconstrained.
491 #[inline]
492 #[must_use]
493 pub const fn new() -> Self {
494 Self {
495 top_left: None,
496 top_right: None,
497 bottom_right: None,
498 bottom_left: None,
499 }
500 }
501
502 crate::graphql::filter::opt_accessor!(
503 top_left: Point2Filter<CF> => with_top_left, set_top_left, maybe_top_left, update_top_left
504 );
505 crate::graphql::filter::opt_accessor!(
506 top_right: Point2Filter<CF> => with_top_right, set_top_right, maybe_top_right, update_top_right
507 );
508 crate::graphql::filter::opt_accessor!(
509 bottom_right: Point2Filter<CF> =>
510 with_bottom_right, set_bottom_right, maybe_bottom_right, update_bottom_right
511 );
512 crate::graphql::filter::opt_accessor!(
513 bottom_left: Point2Filter<CF> =>
514 with_bottom_left, set_bottom_left, maybe_bottom_left, update_bottom_left
515 );
516}
517
518impl<CF: crate::GraphqlFilter> QuadFilter<CF> {
519 /// True while NO operator slot is set on ANY corner.
520 pub fn is_empty(&self) -> bool {
521 [
522 &self.top_left,
523 &self.top_right,
524 &self.bottom_right,
525 &self.bottom_left,
526 ]
527 .into_iter()
528 .all(|corner| corner.as_ref().is_none_or(crate::GraphqlFilter::is_empty))
529 }
530}
531
532impl<CF: crate::GraphqlFilter> crate::GraphqlFilter for QuadFilter<CF> {
533 #[inline]
534 fn is_empty(&self) -> bool {
535 Self::is_empty(self)
536 }
537}
538
539impl<CF> Default for QuadFilter<CF> {
540 #[inline]
541 fn default() -> Self {
542 Self::new()
543 }
544}
545
546impl<CF: core::fmt::Debug> core::fmt::Debug for QuadFilter<CF> {
547 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
548 f.debug_struct("QuadFilter")
549 .field("top_left", &self.top_left)
550 .field("top_right", &self.top_right)
551 .field("bottom_right", &self.bottom_right)
552 .field("bottom_left", &self.bottom_left)
553 .finish()
554 }
555}
556
557impl<CF: Clone> Clone for QuadFilter<CF> {
558 fn clone(&self) -> Self {
559 Self {
560 top_left: self.top_left.clone(),
561 top_right: self.top_right.clone(),
562 bottom_right: self.bottom_right.clone(),
563 bottom_left: self.bottom_left.clone(),
564 }
565 }
566}
567
568impl<CF: PartialEq> PartialEq for QuadFilter<CF> {
569 fn eq(&self, other: &Self) -> bool {
570 self.top_left == other.top_left
571 && self.top_right == other.top_right
572 && self.bottom_right == other.bottom_right
573 && self.bottom_left == other.bottom_left
574 }
575}