Skip to main content

plotters_ternary/coord/
geometry.rs

1use super::{
2    CartesianSegment, Component, Error, Normalization, TernaryPoint, TernaryViewport, Tolerance,
3    clip_segment, clip_segment_with_parameters,
4};
5
6/// The height of a unit-side equilateral triangle in logical Cartesian space.
7pub const EQUILATERAL_TRIANGLE_HEIGHT: f64 = 0.866_025_403_784_438_6;
8
9/// A point in the logical Cartesian plane used for ternary projection.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct TernaryCartesian {
12    /// Horizontal logical coordinate.
13    pub x: f64,
14    /// Vertical logical coordinate.
15    pub y: f64,
16}
17
18impl TernaryCartesian {
19    /// Construct a logical Cartesian point.
20    pub const fn new(x: f64, y: f64) -> Self {
21        Self { x, y }
22    }
23}
24
25/// Whether the apex of the equilateral triangle points up or down.
26#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
27pub enum TriangleOrientation {
28    /// Left `(0, 0)`, right `(1, 0)`, apex `(0.5, sqrt(3)/2)`.
29    #[default]
30    Up,
31    /// Left `(0, 0)`, right `(1, 0)`, apex `(0.5, -sqrt(3)/2)`.
32    Down,
33}
34
35/// The semantic component assigned to each geometric triangle slot.
36///
37/// `apex` denotes the point opposite the left/right base. It is above the base
38/// for [`TriangleOrientation::Up`] and below it for
39/// [`TriangleOrientation::Down`].
40#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
41pub struct VertexOrder {
42    left: Component,
43    right: Component,
44    apex: Component,
45}
46
47impl VertexOrder {
48    /// Construct a one-to-one mapping from components to left, right, and apex.
49    ///
50    /// ```
51    /// use plotters_ternary::{Component, VertexOrder};
52    ///
53    /// let order = VertexOrder::new(Component::B, Component::C, Component::A)?;
54    /// assert_eq!(order.apex(), Component::A);
55    /// # Ok::<(), plotters_ternary::Error>(())
56    /// ```
57    pub fn new(left: Component, right: Component, apex: Component) -> Result<Self, Error> {
58        if left == right || left == apex || right == apex {
59            return Err(Error::InvalidVertexOrder { left, right, apex });
60        }
61        Ok(Self { left, right, apex })
62    }
63
64    /// Return the component at the left base vertex.
65    pub const fn left(self) -> Component {
66        self.left
67    }
68
69    /// Return the component at the right base vertex.
70    pub const fn right(self) -> Component {
71        self.right
72    }
73
74    /// Return the component at the orientation-dependent apex.
75    pub const fn apex(self) -> Component {
76        self.apex
77    }
78}
79
80impl Default for VertexOrder {
81    /// Use A at the apex, B at the left base, and C at the right base.
82    fn default() -> Self {
83        Self {
84            left: Component::B,
85            right: Component::C,
86            apex: Component::A,
87        }
88    }
89}
90
91/// The location of a finite Cartesian point relative to the full triangle.
92#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
93pub enum TrianglePointLocation {
94    /// Strictly within the triangle by more than the supplied tolerance.
95    Inside,
96    /// On an edge, a corner, or within tolerance of one.
97    Boundary,
98    /// Materially beyond at least one triangle edge.
99    Outside,
100}
101
102/// A directed geometric edge of the canonical triangle.
103#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
104pub enum TriangleEdge {
105    /// Directed from the left base slot to the right base slot.
106    LeftRight,
107    /// Directed from the right base slot to the apex slot.
108    RightApex,
109    /// Directed from the apex slot to the left base slot.
110    ApexLeft,
111}
112
113impl TriangleEdge {
114    /// All edges in directed boundary order.
115    pub const ALL: [Self; 3] = [Self::LeftRight, Self::RightApex, Self::ApexLeft];
116}
117
118/// A visible edge fragment retaining its identity and source parameter range.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct VisibleTriangleEdge {
121    pub edge: TriangleEdge,
122    pub segment: CartesianSegment,
123    pub parameter_start: f64,
124    pub parameter_end: f64,
125}
126
127/// An equilateral ternary triangle and its component-to-vertex assignment.
128#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
129pub struct TernaryGeometry {
130    orientation: TriangleOrientation,
131    vertex_order: VertexOrder,
132}
133
134impl TernaryGeometry {
135    /// Construct geometry with the given orientation and component order.
136    pub const fn new(orientation: TriangleOrientation, vertex_order: VertexOrder) -> Self {
137        Self {
138            orientation,
139            vertex_order,
140        }
141    }
142
143    /// Return the triangle orientation.
144    pub const fn orientation(self) -> TriangleOrientation {
145        self.orientation
146    }
147
148    /// Return the component-to-vertex assignment.
149    pub const fn vertex_order(self) -> VertexOrder {
150        self.vertex_order
151    }
152
153    /// Return the logical Cartesian vertex for a semantic component.
154    pub fn vertex(self, component: Component) -> TernaryCartesian {
155        let [left, right, apex] = self.slot_vertices();
156        if component == self.vertex_order.left {
157            left
158        } else if component == self.vertex_order.right {
159            right
160        } else {
161            apex
162        }
163    }
164
165    /// Return the vertices in stable semantic A/B/C order.
166    pub fn vertices(self) -> [TernaryCartesian; 3] {
167        Component::ALL.map(|component| self.vertex(component))
168    }
169
170    /// Return a complete directed geometric triangle edge.
171    pub fn triangle_edge(self, edge: TriangleEdge) -> CartesianSegment {
172        let [left, right, apex] = self.slot_vertices();
173        match edge {
174            TriangleEdge::LeftRight => CartesianSegment::new(left, right),
175            TriangleEdge::RightApex => CartesianSegment::new(right, apex),
176            TriangleEdge::ApexLeft => CartesianSegment::new(apex, left),
177        }
178    }
179
180    /// Return all complete edges in directed boundary order.
181    pub fn triangle_edges(self) -> [(TriangleEdge, CartesianSegment); 3] {
182        TriangleEdge::ALL.map(|edge| (edge, self.triangle_edge(edge)))
183    }
184
185    /// Clip every original triangle edge and retain its identity and parameters.
186    pub fn visible_edges(
187        self,
188        viewport: TernaryViewport,
189        tolerance: Tolerance,
190    ) -> Result<Vec<VisibleTriangleEdge>, Error> {
191        let mut visible = Vec::with_capacity(3);
192        for (edge, source) in self.triangle_edges() {
193            if let Some(clipped) = clip_segment_with_parameters(source, viewport, tolerance)? {
194                visible.push(VisibleTriangleEdge {
195                    edge,
196                    segment: clipped.segment,
197                    parameter_start: clipped.parameter_start,
198                    parameter_end: clipped.parameter_end,
199                });
200            }
201        }
202        Ok(visible)
203    }
204
205    /// Construct the full-triangle segment where a semantic component equals `value`.
206    ///
207    /// Values within tolerance of zero or one are snapped to that boundary.
208    /// `value = 0` returns the opposite edge and `value = 1` returns a
209    /// zero-length segment at the component vertex.
210    pub fn component_isoline(
211        self,
212        component: Component,
213        value: f64,
214        tolerance: Tolerance,
215    ) -> Result<CartesianSegment, Error> {
216        tolerance.validate()?;
217        if !value.is_finite()
218            || (value < 0.0 && !tolerance.is_close(value, 0.0))
219            || (value > 1.0 && !tolerance.is_close(value, 1.0))
220        {
221            return Err(Error::InvalidIsolineValue { value, tolerance });
222        }
223
224        let value = if tolerance.is_close(value, 0.0) {
225            0.0
226        } else if tolerance.is_close(value, 1.0) {
227            1.0
228        } else {
229            value
230        };
231        let vertex = self.vertex(component);
232        let [first_other, second_other] = component.others();
233        Ok(CartesianSegment::new(
234            interpolate(self.vertex(first_other), vertex, value),
235            interpolate(self.vertex(second_other), vertex, value),
236        ))
237    }
238
239    /// Construct and clip one semantic component isoline to a viewport.
240    pub fn visible_component_isoline(
241        self,
242        component: Component,
243        value: f64,
244        viewport: TernaryViewport,
245        tolerance: Tolerance,
246    ) -> Result<Option<CartesianSegment>, Error> {
247        clip_segment(
248            self.component_isoline(component, value, tolerance)?,
249            viewport,
250            tolerance,
251        )
252    }
253
254    /// Validate and project a composition into the normalised ternary plane.
255    ///
256    /// The explicit policy permits source data using a non-unit required sum.
257    /// After validation, the three weights are divided by their validated sum
258    /// before the barycentric weighted sum is calculated.
259    ///
260    /// ```
261    /// use plotters_ternary::{Normalization, TernaryGeometry, TernaryPoint, Tolerance};
262    ///
263    /// let point = TernaryPoint::new(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0);
264    /// let projected = TernaryGeometry::default().project(
265    ///     point,
266    ///     Normalization::RequireUnitSum,
267    ///     Tolerance::default(),
268    /// )?;
269    /// assert!((projected.x - 0.5).abs() < 1.0e-12);
270    /// # Ok::<(), plotters_ternary::Error>(())
271    /// ```
272    pub fn project(
273        self,
274        point: TernaryPoint,
275        normalization: Normalization,
276        tolerance: Tolerance,
277    ) -> Result<TernaryCartesian, Error> {
278        let point = point.validate(normalization, tolerance)?;
279        let sum = point.sum();
280        let unit_components = point.as_array().map(|component| component / sum);
281        Ok(self.project_unit_components(unit_components))
282    }
283
284    /// Recover unit-sum A/B/C component weights from a Cartesian point.
285    ///
286    /// Points materially outside the full triangle return
287    /// [`Error::CartesianOutsideTriangle`]. Weights whose absolute value is at
288    /// most the absolute tolerance are set to zero, then the remaining weights
289    /// are rescaled to sum to one. This admits small boundary round-off without
290    /// silently clamping external points.
291    ///
292    /// ```
293    /// use plotters_ternary::{TernaryCartesian, TernaryGeometry, Tolerance};
294    ///
295    /// let point = TernaryGeometry::default()
296    ///     .unproject(TernaryCartesian::new(0.5, 0.0), Tolerance::default())?;
297    /// assert_eq!(point.as_array(), [0.0, 0.5, 0.5]);
298    /// # Ok::<(), plotters_ternary::Error>(())
299    /// ```
300    pub fn unproject(
301        self,
302        cartesian: TernaryCartesian,
303        tolerance: Tolerance,
304    ) -> Result<TernaryPoint, Error> {
305        tolerance.validate()?;
306        let weights = self.slot_weights(cartesian)?;
307        if self.classify_weights(weights, tolerance) == TrianglePointLocation::Outside {
308            return Err(Error::CartesianOutsideTriangle {
309                x: cartesian.x,
310                y: cartesian.y,
311                tolerance,
312            });
313        }
314
315        let mut weights = weights.map(|weight| {
316            if tolerance.is_near_zero(weight) {
317                0.0
318            } else {
319                weight
320            }
321        });
322        let sum: f64 = weights.into_iter().sum();
323        weights = weights.map(|weight| weight / sum);
324
325        let mut components = [0.0; 3];
326        components[self.vertex_order.left.index()] = weights[0];
327        components[self.vertex_order.right.index()] = weights[1];
328        components[self.vertex_order.apex.index()] = weights[2];
329        TernaryPoint::from(components).validate(Normalization::RequireUnitSum, tolerance)
330    }
331
332    /// Classify a finite Cartesian point against the complete ternary triangle.
333    ///
334    /// Non-finite coordinates are rejected because they have no geometric
335    /// location. This operation does not consider future rectangular viewports.
336    pub fn classify(
337        self,
338        cartesian: TernaryCartesian,
339        tolerance: Tolerance,
340    ) -> Result<TrianglePointLocation, Error> {
341        tolerance.validate()?;
342        let weights = self.slot_weights(cartesian)?;
343        Ok(self.classify_weights(weights, tolerance))
344    }
345
346    fn project_unit_components(self, components: [f64; 3]) -> TernaryCartesian {
347        let [left, right, apex] = self.slot_vertices();
348        let left_weight = components[self.vertex_order.left.index()];
349        let right_weight = components[self.vertex_order.right.index()];
350        let apex_weight = components[self.vertex_order.apex.index()];
351        TernaryCartesian {
352            x: left_weight * left.x + right_weight * right.x + apex_weight * apex.x,
353            y: left_weight * left.y + right_weight * right.y + apex_weight * apex.y,
354        }
355    }
356
357    fn slot_vertices(self) -> [TernaryCartesian; 3] {
358        let apex_y = match self.orientation {
359            TriangleOrientation::Up => EQUILATERAL_TRIANGLE_HEIGHT,
360            TriangleOrientation::Down => -EQUILATERAL_TRIANGLE_HEIGHT,
361        };
362        [
363            TernaryCartesian::new(0.0, 0.0),
364            TernaryCartesian::new(1.0, 0.0),
365            TernaryCartesian::new(0.5, apex_y),
366        ]
367    }
368
369    fn slot_weights(self, cartesian: TernaryCartesian) -> Result<[f64; 3], Error> {
370        if !cartesian.x.is_finite() || !cartesian.y.is_finite() {
371            return Err(Error::NonFiniteCartesian {
372                x: cartesian.x,
373                y: cartesian.y,
374            });
375        }
376
377        let [left, right, apex] = self.slot_vertices();
378        let right_from_left = subtract(right, left);
379        let apex_from_left = subtract(apex, left);
380        let point_from_left = subtract(cartesian, left);
381        let determinant = cross(right_from_left, apex_from_left);
382        let right_weight = cross(point_from_left, apex_from_left) / determinant;
383        let apex_weight = cross(right_from_left, point_from_left) / determinant;
384        let left_weight = 1.0 - right_weight - apex_weight;
385        Ok([left_weight, right_weight, apex_weight])
386    }
387
388    fn classify_weights(self, weights: [f64; 3], tolerance: Tolerance) -> TrianglePointLocation {
389        let _ = self;
390        if weights
391            .into_iter()
392            .any(|weight| weight < -tolerance.absolute)
393        {
394            TrianglePointLocation::Outside
395        } else if weights
396            .into_iter()
397            .any(|weight| tolerance.is_near_zero(weight))
398        {
399            TrianglePointLocation::Boundary
400        } else {
401            TrianglePointLocation::Inside
402        }
403    }
404}
405
406fn interpolate(start: TernaryCartesian, end: TernaryCartesian, parameter: f64) -> TernaryCartesian {
407    TernaryCartesian::new(
408        start.x + (end.x - start.x) * parameter,
409        start.y + (end.y - start.y) * parameter,
410    )
411}
412
413fn subtract(left: TernaryCartesian, right: TernaryCartesian) -> TernaryCartesian {
414    TernaryCartesian::new(left.x - right.x, left.y - right.y)
415}
416
417fn cross(left: TernaryCartesian, right: TernaryCartesian) -> f64 {
418    left.x * right.y - left.y * right.x
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424    use proptest::prelude::*;
425
426    const TOLERANCE: Tolerance = Tolerance {
427        absolute: 1.0e-9,
428        relative: 1.0e-9,
429    };
430    const ASSERTION_EPSILON: f64 = 1.0e-10;
431
432    fn unit_point(a: f64, b: f64, c: f64) -> TernaryPoint {
433        TernaryPoint::new(a, b, c)
434            .validate(Normalization::RequireUnitSum, TOLERANCE)
435            .unwrap()
436    }
437
438    fn assert_cartesian_close(actual: TernaryCartesian, expected: TernaryCartesian) {
439        assert!(
440            (actual.x - expected.x).abs() < ASSERTION_EPSILON,
441            "{actual:?}"
442        );
443        assert!(
444            (actual.y - expected.y).abs() < ASSERTION_EPSILON,
445            "{actual:?}"
446        );
447    }
448
449    fn assert_point_close(actual: TernaryPoint, expected: TernaryPoint) {
450        for component in Component::ALL {
451            assert!(
452                (actual.component(component) - expected.component(component)).abs()
453                    < ASSERTION_EPSILON,
454                "{component:?}: {actual:?} != {expected:?}"
455            );
456        }
457    }
458
459    fn all_orders() -> [VertexOrder; 6] {
460        [
461            VertexOrder::new(Component::A, Component::B, Component::C).unwrap(),
462            VertexOrder::new(Component::A, Component::C, Component::B).unwrap(),
463            VertexOrder::new(Component::B, Component::A, Component::C).unwrap(),
464            VertexOrder::new(Component::B, Component::C, Component::A).unwrap(),
465            VertexOrder::new(Component::C, Component::A, Component::B).unwrap(),
466            VertexOrder::new(Component::C, Component::B, Component::A).unwrap(),
467        ]
468    }
469
470    #[test]
471    fn conventional_pure_corners_edges_and_centroid_project_correctly() {
472        let geometry = TernaryGeometry::default();
473        let height = EQUILATERAL_TRIANGLE_HEIGHT;
474        for (point, expected) in [
475            (
476                unit_point(1.0, 0.0, 0.0),
477                TernaryCartesian::new(0.5, height),
478            ),
479            (unit_point(0.0, 1.0, 0.0), TernaryCartesian::new(0.0, 0.0)),
480            (unit_point(0.0, 0.0, 1.0), TernaryCartesian::new(1.0, 0.0)),
481            (
482                unit_point(0.5, 0.5, 0.0),
483                TernaryCartesian::new(0.25, height / 2.0),
484            ),
485            (
486                unit_point(0.5, 0.0, 0.5),
487                TernaryCartesian::new(0.75, height / 2.0),
488            ),
489            (unit_point(0.0, 0.5, 0.5), TernaryCartesian::new(0.5, 0.0)),
490            (
491                unit_point(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0),
492                TernaryCartesian::new(0.5, height / 3.0),
493            ),
494        ] {
495            assert_cartesian_close(
496                geometry
497                    .project(point, Normalization::RequireUnitSum, TOLERANCE)
498                    .unwrap(),
499                expected,
500            );
501        }
502    }
503
504    #[test]
505    fn vertex_orders_map_all_pure_components_and_preserve_abc_on_round_trip() {
506        let interior = unit_point(0.2, 0.3, 0.5);
507        for order in all_orders() {
508            let geometry = TernaryGeometry::new(TriangleOrientation::Up, order);
509            for component in Component::ALL {
510                let mut components = [0.0; 3];
511                components[component.index()] = 1.0;
512                let projected = geometry
513                    .project(
514                        TernaryPoint::from(components),
515                        Normalization::RequireUnitSum,
516                        TOLERANCE,
517                    )
518                    .unwrap();
519                assert_cartesian_close(projected, geometry.vertex(component));
520            }
521            let round_trip = geometry
522                .unproject(
523                    geometry
524                        .project(interior, Normalization::RequireUnitSum, TOLERANCE)
525                        .unwrap(),
526                    TOLERANCE,
527                )
528                .unwrap();
529            assert_point_close(round_trip, interior);
530        }
531    }
532
533    #[test]
534    fn both_orientations_have_expected_apexes_and_round_trip() {
535        let point = unit_point(0.2, 0.3, 0.5);
536        for (orientation, apex_y) in [
537            (TriangleOrientation::Up, EQUILATERAL_TRIANGLE_HEIGHT),
538            (TriangleOrientation::Down, -EQUILATERAL_TRIANGLE_HEIGHT),
539        ] {
540            let geometry = TernaryGeometry::new(orientation, VertexOrder::default());
541            assert_cartesian_close(
542                geometry.vertex(Component::A),
543                TernaryCartesian::new(0.5, apex_y),
544            );
545            let projected = geometry
546                .project(point, Normalization::RequireUnitSum, TOLERANCE)
547                .unwrap();
548            assert_point_close(geometry.unproject(projected, TOLERANCE).unwrap(), point);
549        }
550    }
551
552    #[test]
553    fn canonical_default_order_and_reverse_corners_are_semantic_abc() {
554        let order = VertexOrder::default();
555        assert_eq!(order.apex(), Component::A);
556        assert_eq!(order.left(), Component::B);
557        assert_eq!(order.right(), Component::C);
558
559        let geometry = TernaryGeometry::default();
560        for (component, vertex) in [
561            (
562                Component::A,
563                TernaryCartesian::new(0.5, EQUILATERAL_TRIANGLE_HEIGHT),
564            ),
565            (Component::B, TernaryCartesian::new(0.0, 0.0)),
566            (Component::C, TernaryCartesian::new(1.0, 0.0)),
567        ] {
568            assert_cartesian_close(geometry.vertex(component), vertex);
569            let recovered = geometry.unproject(vertex, TOLERANCE).unwrap();
570            for candidate in Component::ALL {
571                let expected = if candidate == component { 1.0 } else { 0.0 };
572                assert!((recovered.component(candidate) - expected).abs() < ASSERTION_EPSILON);
573            }
574        }
575    }
576
577    #[test]
578    fn default_component_isolines_are_parallel_to_semantic_opposite_edges() {
579        let geometry = TernaryGeometry::default();
580        for component in Component::ALL {
581            let isoline = geometry
582                .component_isoline(component, 0.4, TOLERANCE)
583                .unwrap();
584            let [first, second] = component.others();
585            let edge = CartesianSegment::new(geometry.vertex(first), geometry.vertex(second));
586            assert!(
587                cross(
588                    subtract(isoline.end, isoline.start),
589                    subtract(edge.end, edge.start),
590                )
591                .abs()
592                    < ASSERTION_EPSILON
593            );
594        }
595    }
596
597    #[test]
598    fn downward_default_keeps_a_apex_b_left_c_right() {
599        let geometry = TernaryGeometry::new(TriangleOrientation::Down, VertexOrder::default());
600        assert_cartesian_close(
601            geometry.vertex(Component::A),
602            TernaryCartesian::new(0.5, -EQUILATERAL_TRIANGLE_HEIGHT),
603        );
604        assert_cartesian_close(
605            geometry.vertex(Component::B),
606            TernaryCartesian::new(0.0, 0.0),
607        );
608        assert_cartesian_close(
609            geometry.vertex(Component::C),
610            TernaryCartesian::new(1.0, 0.0),
611        );
612    }
613
614    #[test]
615    fn vertex_order_rejects_duplicates() {
616        assert!(matches!(
617            VertexOrder::new(Component::A, Component::A, Component::C),
618            Err(Error::InvalidVertexOrder { .. })
619        ));
620    }
621
622    #[test]
623    fn classify_covers_interior_edges_corners_and_tolerance_boundary() {
624        let geometry = TernaryGeometry::default();
625        let height = EQUILATERAL_TRIANGLE_HEIGHT;
626        assert_eq!(
627            geometry
628                .classify(TernaryCartesian::new(0.5, 0.2), TOLERANCE)
629                .unwrap(),
630            TrianglePointLocation::Inside
631        );
632        for edge_or_corner in [
633            TernaryCartesian::new(0.5, 0.0),
634            TernaryCartesian::new(0.25, height / 2.0),
635            TernaryCartesian::new(0.75, height / 2.0),
636            TernaryCartesian::new(0.0, 0.0),
637            TernaryCartesian::new(1.0, 0.0),
638            TernaryCartesian::new(0.5, height),
639        ] {
640            assert_eq!(
641                geometry.classify(edge_or_corner, TOLERANCE).unwrap(),
642                TrianglePointLocation::Boundary
643            );
644        }
645        assert_eq!(
646            geometry
647                .classify(TernaryCartesian::new(0.5, 2.0e-9), TOLERANCE)
648                .unwrap(),
649            TrianglePointLocation::Inside
650        );
651        assert_eq!(
652            geometry
653                .classify(TernaryCartesian::new(0.5, -5.0e-10), TOLERANCE)
654                .unwrap(),
655            TrianglePointLocation::Boundary
656        );
657        assert_eq!(
658            geometry
659                .classify(TernaryCartesian::new(0.5, -1.0e-5), TOLERANCE)
660                .unwrap(),
661            TrianglePointLocation::Outside
662        );
663        for cartesian in [
664            TernaryCartesian::new(f64::NAN, 0.0),
665            TernaryCartesian::new(f64::INFINITY, 0.0),
666            TernaryCartesian::new(0.0, f64::NEG_INFINITY),
667        ] {
668            assert!(matches!(
669                geometry.classify(cartesian, TOLERANCE),
670                Err(Error::NonFiniteCartesian { .. })
671            ));
672        }
673        assert!(matches!(
674            geometry.unproject(TernaryCartesian::new(0.5, -1.0e-5), TOLERANCE),
675            Err(Error::CartesianOutsideTriangle { .. })
676        ));
677    }
678
679    fn oriented_viewport(
680        orientation: TriangleOrientation,
681        x_min: f64,
682        x_max: f64,
683        upward_y_min: f64,
684        upward_y_max: f64,
685    ) -> TernaryViewport {
686        match orientation {
687            TriangleOrientation::Up => {
688                TernaryViewport::new(x_min, x_max, upward_y_min, upward_y_max).unwrap()
689            }
690            TriangleOrientation::Down => {
691                TernaryViewport::new(x_min, x_max, -upward_y_max, -upward_y_min).unwrap()
692            }
693        }
694    }
695
696    #[test]
697    fn visible_edges_cover_full_cropped_interior_and_external_views() {
698        let height = EQUILATERAL_TRIANGLE_HEIGHT;
699        for orientation in [TriangleOrientation::Up, TriangleOrientation::Down] {
700            let geometry = TernaryGeometry::new(orientation, VertexOrder::default());
701            let full = geometry
702                .visible_edges(TernaryViewport::full(geometry), TOLERANCE)
703                .unwrap();
704            assert_eq!(full.len(), 3);
705            for visible in &full {
706                assert_eq!(visible.segment, geometry.triangle_edge(visible.edge));
707                assert_eq!(visible.parameter_start, 0.0);
708                assert_eq!(visible.parameter_end, 1.0);
709            }
710
711            let cases = [
712                (
713                    oriented_viewport(orientation, -0.05, 0.12, -0.05, 0.12),
714                    2,
715                    "left corner",
716                ),
717                (
718                    oriented_viewport(orientation, 0.88, 1.05, -0.05, 0.12),
719                    2,
720                    "right corner",
721                ),
722                (
723                    oriented_viewport(orientation, 0.45, 0.55, height - 0.12, height + 0.05),
724                    2,
725                    "apex corner",
726                ),
727                (
728                    oriented_viewport(orientation, 0.65, 1.05, -0.05, height + 0.05),
729                    2,
730                    "right crop",
731                ),
732                (
733                    oriented_viewport(orientation, -0.05, 0.35, -0.05, height + 0.05),
734                    2,
735                    "left crop",
736                ),
737                (
738                    oriented_viewport(orientation, 0.0, 1.0, 0.5, height + 0.05),
739                    2,
740                    "top crop",
741                ),
742                (
743                    oriented_viewport(orientation, 0.17, 0.25, 0.3, 0.4),
744                    1,
745                    "edge only",
746                ),
747                (
748                    oriented_viewport(orientation, 0.45, 0.55, 0.1, 0.2),
749                    0,
750                    "interior",
751                ),
752                (
753                    oriented_viewport(orientation, 2.0, 3.0, 2.0, 3.0),
754                    0,
755                    "external",
756                ),
757            ];
758
759            for (viewport, expected_count, description) in cases {
760                let visible = geometry.visible_edges(viewport, TOLERANCE).unwrap();
761                assert_eq!(
762                    visible.len(),
763                    expected_count,
764                    "{orientation:?}: {description}"
765                );
766                for fragment in visible {
767                    let source = geometry.triangle_edge(fragment.edge);
768                    assert_cartesian_close(
769                        fragment.segment.start,
770                        source.point_at(fragment.parameter_start),
771                    );
772                    assert_cartesian_close(
773                        fragment.segment.end,
774                        source.point_at(fragment.parameter_end),
775                    );
776                    assert!(fragment.parameter_start >= 0.0);
777                    assert!(fragment.parameter_end <= 1.0);
778                    assert!(fragment.parameter_start <= fragment.parameter_end);
779                }
780            }
781        }
782    }
783
784    #[test]
785    fn component_isolines_preserve_semantics_for_every_order_and_orientation() {
786        for orientation in [TriangleOrientation::Up, TriangleOrientation::Down] {
787            for order in all_orders() {
788                let geometry = TernaryGeometry::new(orientation, order);
789                for component in Component::ALL {
790                    for value in [0.0, 0.25, 0.5, 1.0] {
791                        let isoline = geometry
792                            .component_isoline(component, value, TOLERANCE)
793                            .unwrap();
794                        for endpoint in [isoline.start, isoline.end] {
795                            let composition = geometry.unproject(endpoint, TOLERANCE).unwrap();
796                            assert!(
797                                (composition.component(component) - value).abs()
798                                    < ASSERTION_EPSILON
799                            );
800                        }
801                        if value == 0.0 {
802                            let [first_other, second_other] = component.others();
803                            assert_cartesian_close(isoline.start, geometry.vertex(first_other));
804                            assert_cartesian_close(isoline.end, geometry.vertex(second_other));
805                        }
806                        if value == 1.0 {
807                            assert_cartesian_close(isoline.start, geometry.vertex(component));
808                            assert_eq!(isoline.start, isoline.end);
809                        }
810                    }
811                }
812            }
813        }
814    }
815
816    #[test]
817    fn isoline_tolerance_and_invalid_values_are_explicit() {
818        let geometry = TernaryGeometry::default();
819        for (value, expected) in [(-5.0e-10, 0.0), (1.0 + 5.0e-10, 1.0)] {
820            let isoline = geometry
821                .component_isoline(Component::A, value, TOLERANCE)
822                .unwrap();
823            for endpoint in [isoline.start, isoline.end] {
824                let point = geometry.unproject(endpoint, TOLERANCE).unwrap();
825                assert!((point.component(Component::A) - expected).abs() < ASSERTION_EPSILON);
826            }
827        }
828
829        for value in [-1.0e-5, 1.0 + 1.0e-5, f64::NAN, f64::INFINITY] {
830            assert!(matches!(
831                geometry.component_isoline(Component::A, value, TOLERANCE),
832                Err(Error::InvalidIsolineValue { .. })
833            ));
834        }
835    }
836
837    #[test]
838    fn viewport_and_triangle_classifications_remain_separate() {
839        let geometry = TernaryGeometry::default();
840        let interior = TernaryViewport::new(0.45, 0.55, 0.1, 0.2).unwrap();
841        assert!(
842            geometry
843                .visible_edges(interior, TOLERANCE)
844                .unwrap()
845                .is_empty()
846        );
847
848        let outside_triangle = TernaryCartesian::new(0.1, 0.8);
849        let local_viewport = TernaryViewport::new(0.05, 0.15, 0.75, 0.85).unwrap();
850        assert!(
851            local_viewport
852                .contains(outside_triangle, TOLERANCE)
853                .unwrap()
854        );
855        assert_eq!(
856            geometry.classify(outside_triangle, TOLERANCE).unwrap(),
857            TrianglePointLocation::Outside
858        );
859
860        let inside_triangle = TernaryCartesian::new(0.5, 0.2);
861        let remote_viewport = TernaryViewport::new(0.0, 0.2, 0.7, 0.8).unwrap();
862        assert_eq!(
863            geometry.classify(inside_triangle, TOLERANCE).unwrap(),
864            TrianglePointLocation::Inside
865        );
866        assert!(
867            !remote_viewport
868                .contains(inside_triangle, TOLERANCE)
869                .unwrap()
870        );
871    }
872
873    #[test]
874    fn cropped_edges_retain_expected_geometric_identities() {
875        let geometry = TernaryGeometry::default();
876        let height = EQUILATERAL_TRIANGLE_HEIGHT;
877        let cases = [
878            (
879                TernaryViewport::new(0.65, 1.05, -0.05, height + 0.05).unwrap(),
880                vec![TriangleEdge::LeftRight, TriangleEdge::RightApex],
881            ),
882            (
883                TernaryViewport::new(-0.05, 0.35, -0.05, height + 0.05).unwrap(),
884                vec![TriangleEdge::LeftRight, TriangleEdge::ApexLeft],
885            ),
886            (
887                TernaryViewport::new(0.0, 1.0, 0.5, height + 0.05).unwrap(),
888                vec![TriangleEdge::RightApex, TriangleEdge::ApexLeft],
889            ),
890            (
891                TernaryViewport::new(0.17, 0.25, 0.3, 0.4).unwrap(),
892                vec![TriangleEdge::ApexLeft],
893            ),
894        ];
895
896        for (viewport, expected) in cases {
897            let actual: Vec<_> = geometry
898                .visible_edges(viewport, TOLERANCE)
899                .unwrap()
900                .into_iter()
901                .map(|visible| visible.edge)
902                .collect();
903            assert_eq!(actual, expected);
904        }
905    }
906
907    #[test]
908    fn visible_component_isoline_uses_the_generic_clipper() {
909        let geometry = TernaryGeometry::default();
910        let viewport = TernaryViewport::new(0.4, 0.6, 0.4, 0.5).unwrap();
911        let visible = geometry
912            .visible_component_isoline(Component::A, 0.5, viewport, TOLERANCE)
913            .unwrap()
914            .unwrap();
915        assert!(viewport.contains(visible.start, TOLERANCE).unwrap());
916        assert!(viewport.contains(visible.end, TOLERANCE).unwrap());
917        for endpoint in [visible.start, visible.end] {
918            let composition = geometry.unproject(endpoint, TOLERANCE).unwrap();
919            assert!((composition.component(Component::A) - 0.5).abs() < ASSERTION_EPSILON);
920        }
921    }
922
923    proptest! {
924        #[test]
925        fn projection_round_trip_holds_for_bounded_non_negative_triples(
926            a in 0.0_f64..1.0,
927            b in 0.0_f64..1.0,
928            c in 0.0_f64..1.0,
929        ) {
930            prop_assume!(a + b + c > 1.0e-6);
931            let point = TernaryPoint::new(a, b, c)
932                .validate(Normalization::Normalize, TOLERANCE)
933                .unwrap();
934            for orientation in [TriangleOrientation::Up, TriangleOrientation::Down] {
935                for order in all_orders() {
936                    let geometry = TernaryGeometry::new(orientation, order);
937                    let projected = geometry
938                        .project(point, Normalization::RequireUnitSum, TOLERANCE)
939                        .unwrap();
940                    let recovered = geometry.unproject(projected, TOLERANCE).unwrap();
941                    for component in Component::ALL {
942                        prop_assert!(
943                            (recovered.component(component) - point.component(component)).abs()
944                                < ASSERTION_EPSILON
945                        );
946                    }
947                }
948            }
949        }
950    }
951}