Skip to main content

plotters_ternary/series/
marker.rs

1//! Portable scientific marker geometry and Plotters drawing elements.
2//!
3//! Marker geometry is normalized around `(0, 0)` before a concrete
4//! [`MarkerElement`] maps it to a Plotters backend anchor.
5
6use std::fmt;
7
8use plotters::backend::DrawingBackend;
9use plotters::element::{Drawable, PointCollection};
10use plotters::style::{Color, RGBAColor, ShapeStyle};
11use plotters_backend::{BackendCoord, DrawingErrorKind};
12
13const MIN_SIDES: u8 = 3;
14const MAX_SIDES: u8 = 16;
15const CIRCLE_SEGMENTS: usize = 32;
16const EPS: f64 = 1.0e-10;
17
18/// Policy governing whether a point marker centre must be in the logical
19/// ternary viewport. `Centre` is intentionally not marker-bounds clipping.
20#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
21pub enum MarkerClipMode {
22    /// Draw only when the marker centre is inside or on the viewport.
23    #[default]
24    Centre,
25    /// Draw regardless of viewport containment; Plotters may truncate it.
26    None,
27}
28
29/// Direction used by radial marker partitions.
30///
31/// `0 degrees` points right and positive angles turn counter-clockwise in ordinary
32/// mathematical coordinates (visually toward the top of backend pixel space).
33#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
34pub enum SweepDirection {
35    /// Advance toward increasing angles.
36    #[default]
37    CounterClockwise,
38    /// Advance toward decreasing angles.
39    Clockwise,
40}
41
42/// A built-in scientific marker outline.
43///
44/// `Plus` is the orthogonal `+` symbol; `Cross` is the diagonal `x` symbol.
45/// `Triangle` is retained as the legacy spelling for [`MarkerShape::TriangleUp`].
46#[derive(Clone, Copy, Debug, Default, PartialEq)]
47pub enum MarkerShape {
48    /// A circle, approximated by 32 shared logical vertices.
49    #[default]
50    Circle,
51    /// An ellipse with positive horizontal-to-vertical aspect ratio.
52    Ellipse { aspect_ratio: f64 },
53    /// An axis-aligned square.
54    Square,
55    /// A rectangle with positive horizontal-to-vertical aspect ratio.
56    Rectangle { aspect_ratio: f64 },
57    /// A square with a finite corner ratio in `0.0..=0.5`.
58    RoundedSquare { corner_ratio: f64 },
59    /// A 45-degree square.
60    Diamond,
61    /// Historical alias for [`MarkerShape::TriangleUp`].
62    Triangle,
63    /// An upward-pointing triangle.
64    TriangleUp,
65    /// A downward-pointing triangle.
66    TriangleDown,
67    /// A left-pointing triangle.
68    TriangleLeft,
69    /// A right-pointing triangle.
70    TriangleRight,
71    /// A regular polygon with intrinsic rotation.
72    RegularPolygon { sides: u8, rotation_deg: f64 },
73    /// A star with alternating outer and inner vertices.
74    Star {
75        points: u8,
76        inner_ratio: f64,
77        rotation_deg: f64,
78    },
79    /// Stroke-only orthogonal `+`.
80    Plus,
81    /// Stroke-only diagonal `x`.
82    Cross,
83    /// Stroke-only multi-arm symbol.
84    Asterisk { arms: u8 },
85}
86
87impl MarkerShape {
88    /// A pentagon with no intrinsic rotation.
89    pub const fn pentagon() -> Self {
90        Self::RegularPolygon {
91            sides: 5,
92            rotation_deg: 0.0,
93        }
94    }
95    /// A hexagon with no intrinsic rotation.
96    pub const fn hexagon() -> Self {
97        Self::RegularPolygon {
98            sides: 6,
99            rotation_deg: 0.0,
100        }
101    }
102    /// An octagon with no intrinsic rotation.
103    pub const fn octagon() -> Self {
104        Self::RegularPolygon {
105            sides: 8,
106            rotation_deg: 0.0,
107        }
108    }
109    /// A four-point star with the conventional inner ratio.
110    pub const fn star4() -> Self {
111        Self::Star {
112            points: 4,
113            inner_ratio: 0.45,
114            rotation_deg: 0.0,
115        }
116    }
117    /// A five-point star with the conventional inner ratio.
118    pub const fn star5() -> Self {
119        Self::Star {
120            points: 5,
121            inner_ratio: 0.45,
122            rotation_deg: 0.0,
123        }
124    }
125    /// A six-point star with the conventional inner ratio.
126    pub const fn star6() -> Self {
127        Self::Star {
128            points: 6,
129            inner_ratio: 0.45,
130            rotation_deg: 0.0,
131        }
132    }
133    /// An eight-point star with the conventional inner ratio.
134    pub const fn star8() -> Self {
135        Self::Star {
136            points: 8,
137            inner_ratio: 0.45,
138            rotation_deg: 0.0,
139        }
140    }
141    /// Whether the shape can carry a fill or partition.
142    pub const fn is_fillable(self) -> bool {
143        !matches!(self, Self::Plus | Self::Cross | Self::Asterisk { .. })
144    }
145    fn canonical(self) -> Self {
146        if matches!(self, Self::Triangle) {
147            Self::TriangleUp
148        } else {
149            self
150        }
151    }
152}
153
154/// A validated shape plus an additional rotation.
155#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct MarkerGeometry {
157    shape: MarkerShape,
158    rotation_deg: f64,
159}
160
161impl MarkerGeometry {
162    /// Construct validated geometry.
163    pub fn new(shape: MarkerShape) -> Result<Self, MarkerError> {
164        let geometry = Self {
165            shape: shape.canonical(),
166            rotation_deg: 0.0,
167        };
168        geometry.validate()?;
169        Ok(geometry)
170    }
171    /// Add a finite counter-clockwise rotation in degrees.
172    pub fn rotated(mut self, rotation_deg: f64) -> Result<Self, MarkerError> {
173        self.rotation_deg = rotation_deg;
174        self.validate()?;
175        Ok(self)
176    }
177    /// Return the canonical shape.
178    pub const fn shape(self) -> MarkerShape {
179        self.shape
180    }
181    /// Return the additional rotation.
182    pub const fn rotation_deg(self) -> f64 {
183        self.rotation_deg
184    }
185    /// Whether this geometry supports fills.
186    pub const fn is_fillable(self) -> bool {
187        self.shape.is_fillable()
188    }
189
190    /// Return a normalized, centred outer outline.
191    pub fn outline(self) -> Result<Vec<LocalPoint>, MarkerError> {
192        self.validate()?;
193        let mut points = match self.shape {
194            MarkerShape::Circle => ellipse(1.0),
195            MarkerShape::Ellipse { aspect_ratio } => ellipse(aspect_ratio),
196            MarkerShape::Square => rectangle(1.0),
197            MarkerShape::Rectangle { aspect_ratio } => rectangle(aspect_ratio),
198            MarkerShape::RoundedSquare { corner_ratio } => rounded_square(corner_ratio),
199            MarkerShape::Diamond => vec![p(0.0, -1.0), p(1.0, 0.0), p(0.0, 1.0), p(-1.0, 0.0)],
200            MarkerShape::TriangleUp => triangle(0.0),
201            MarkerShape::TriangleRight => triangle(270.0),
202            MarkerShape::TriangleDown => triangle(180.0),
203            MarkerShape::TriangleLeft => triangle(90.0),
204            MarkerShape::RegularPolygon {
205                sides,
206                rotation_deg,
207            } => regular(sides, rotation_deg),
208            MarkerShape::Star {
209                points,
210                inner_ratio,
211                rotation_deg,
212            } => star(points, inner_ratio, rotation_deg),
213            MarkerShape::Plus | MarkerShape::Cross | MarkerShape::Asterisk { .. } => Vec::new(),
214            MarkerShape::Triangle => unreachable!("legacy triangle is canonicalized"),
215        };
216        for point in &mut points {
217            *point = rotate(*point, self.rotation_deg);
218        }
219        Ok(normalize(points))
220    }
221
222    /// Return stroke-only local segments.
223    pub fn stroke_segments(self) -> Result<Vec<LocalSegment>, MarkerError> {
224        self.validate()?;
225        let segments = match self.shape {
226            MarkerShape::Plus => vec![
227                seg(p(-1.0, 0.0), p(1.0, 0.0)),
228                seg(p(0.0, -1.0), p(0.0, 1.0)),
229            ],
230            MarkerShape::Cross => vec![
231                seg(p(-1.0, -1.0), p(1.0, 1.0)),
232                seg(p(-1.0, 1.0), p(1.0, -1.0)),
233            ],
234            MarkerShape::Asterisk { arms } => (0..arms)
235                .map(|i| {
236                    let angle = f64::from(i) * 180.0 / f64::from(arms);
237                    seg(rotate(p(-1.0, 0.0), angle), rotate(p(1.0, 0.0), angle))
238                })
239                .collect(),
240            _ => Vec::new(),
241        };
242        Ok(segments
243            .into_iter()
244            .map(|s| {
245                seg(
246                    rotate(s.start, self.rotation_deg),
247                    rotate(s.end, self.rotation_deg),
248                )
249            })
250            .collect())
251    }
252
253    fn validate(self) -> Result<(), MarkerError> {
254        finite_rotation(self.rotation_deg)?;
255        match self.shape {
256            MarkerShape::Ellipse { aspect_ratio } | MarkerShape::Rectangle { aspect_ratio } => {
257                if !aspect_ratio.is_finite() || aspect_ratio <= 0.0 {
258                    return Err(MarkerError::InvalidAspectRatio {
259                        value: aspect_ratio,
260                    });
261                }
262            }
263            MarkerShape::RoundedSquare { corner_ratio } => {
264                if !corner_ratio.is_finite() || !(0.0..=0.5).contains(&corner_ratio) {
265                    return Err(MarkerError::InvalidCornerRatio {
266                        value: corner_ratio,
267                    });
268                }
269            }
270            MarkerShape::RegularPolygon {
271                sides,
272                rotation_deg,
273            } => {
274                count(sides, MarkerError::InvalidPolygonSides { sides })?;
275                finite_rotation(rotation_deg)?;
276            }
277            MarkerShape::Star {
278                points,
279                inner_ratio,
280                rotation_deg,
281            } => {
282                count(points, MarkerError::InvalidStarPoints { points })?;
283                if !inner_ratio.is_finite() || !(0.0..1.0).contains(&inner_ratio) {
284                    return Err(MarkerError::InvalidStarInnerRatio { value: inner_ratio });
285                }
286                finite_rotation(rotation_deg)?;
287            }
288            MarkerShape::Asterisk { arms } => {
289                count(arms, MarkerError::InvalidAsteriskArms { arms })?
290            }
291            _ => {}
292        }
293        Ok(())
294    }
295}
296
297fn count(value: u8, error: MarkerError) -> Result<(), MarkerError> {
298    if (MIN_SIDES..=MAX_SIDES).contains(&value) {
299        Ok(())
300    } else {
301        Err(error)
302    }
303}
304fn finite_rotation(value: f64) -> Result<(), MarkerError> {
305    if value.is_finite() {
306        Ok(())
307    } else {
308        Err(MarkerError::NonFiniteRotation { value })
309    }
310}
311
312/// A colored, weighted marker slice.
313#[derive(Clone, Copy, Debug, PartialEq)]
314pub struct MarkerSlice {
315    /// Positive finite relative weight.
316    pub weight: f64,
317    /// Fill colour.
318    pub color: RGBAColor,
319}
320
321impl MarkerSlice {
322    /// Construct from a normal Plotters colour.
323    pub fn new<C: Color>(weight: f64, color: C) -> Self {
324        Self {
325            weight,
326            color: color.to_rgba(),
327        }
328    }
329}
330
331/// Interior partition geometry.
332#[derive(Clone, Copy, Debug, PartialEq)]
333pub enum MarkerPartition {
334    /// Sectors begin at `start_angle_deg` and follow `direction`.
335    Radial {
336        start_angle_deg: f64,
337        direction: SweepDirection,
338    },
339    /// Slice 0 upper, slice 1 lower.
340    Horizontal,
341    /// Slice 0 left, slice 1 right.
342    Vertical,
343    /// Slice 0 upper/right of visual `/`, slice 1 opposite.
344    DiagonalForward,
345    /// Slice 0 upper/left of visual `\\`, slice 1 opposite.
346    DiagonalBackward,
347    /// Upper-right, lower-right, lower-left, upper-left, rotated counter-clockwise.
348    Quadrants { rotation_deg: f64 },
349}
350
351/// Interior marker fill treatment.
352#[derive(Clone, Debug, PartialEq)]
353pub enum MarkerFill {
354    /// No fill; a visible edge is required.
355    Empty,
356    /// One solid fill.
357    Solid { color: RGBAColor },
358    /// Independently coloured regions and an optional divider style.
359    Partitioned {
360        partition: MarkerPartition,
361        slices: Vec<MarkerSlice>,
362        divider: Option<ShapeStyle>,
363    },
364}
365
366/// Complete validated marker appearance.
367#[derive(Clone, Debug, PartialEq)]
368pub struct MarkerStyle {
369    /// Outline and extra rotation.
370    pub geometry: MarkerGeometry,
371    /// Interior treatment.
372    pub fill: MarkerFill,
373    /// Common outer edge, drawn only after fill and dividers.
374    pub edge: Option<ShapeStyle>,
375}
376
377impl MarkerStyle {
378    /// Build an empty contour marker.
379    pub fn empty<S: Into<ShapeStyle>>(shape: MarkerShape, edge: S) -> Result<Self, MarkerError> {
380        Self::new(
381            MarkerGeometry::new(shape)?,
382            MarkerFill::Empty,
383            Some(edge.into()),
384        )
385    }
386    /// Build an independently filled and edged marker.
387    pub fn solid<C: Color, S: Into<ShapeStyle>>(
388        shape: MarkerShape,
389        color: C,
390        edge: S,
391    ) -> Result<Self, MarkerError> {
392        Self::new(
393            MarkerGeometry::new(shape)?,
394            MarkerFill::Solid {
395                color: color.to_rgba(),
396            },
397            Some(edge.into()),
398        )
399    }
400    /// Build a fully filled FactSage-style marker with the same edge and fill colour.
401    pub fn fact_sage<C: Color>(shape: MarkerShape, color: C) -> Result<Self, MarkerError> {
402        let color = color.to_rgba();
403        Self::new(
404            MarkerGeometry::new(shape)?,
405            MarkerFill::Solid { color },
406            Some(ShapeStyle {
407                color,
408                filled: false,
409                stroke_width: 1,
410            }),
411        )
412    }
413    /// Build a partitioned marker through the common validated path.
414    pub fn partitioned(
415        shape: MarkerShape,
416        partition: MarkerPartition,
417        slices: Vec<MarkerSlice>,
418        divider: Option<ShapeStyle>,
419        edge: Option<ShapeStyle>,
420    ) -> Result<Self, MarkerError> {
421        Self::new(
422            MarkerGeometry::new(shape)?,
423            MarkerFill::Partitioned {
424                partition,
425                slices,
426                divider,
427            },
428            edge,
429        )
430    }
431    /// Build two to four equal radial sectors, beginning at 90 degrees and sweeping clockwise.
432    pub fn equal_radial<C: Color, I: IntoIterator<Item = C>>(
433        shape: MarkerShape,
434        colors: I,
435        edge: Option<ShapeStyle>,
436    ) -> Result<Self, MarkerError> {
437        Self::partitioned(
438            shape,
439            MarkerPartition::Radial {
440                start_angle_deg: 90.0,
441                direction: SweepDirection::Clockwise,
442            },
443            colors
444                .into_iter()
445                .map(|color| MarkerSlice::new(1.0, color))
446                .collect(),
447            None,
448            edge,
449        )
450    }
451    /// Build weighted radial sectors.
452    pub fn weighted_radial(
453        shape: MarkerShape,
454        start_angle_deg: f64,
455        direction: SweepDirection,
456        slices: Vec<MarkerSlice>,
457        divider: Option<ShapeStyle>,
458        edge: Option<ShapeStyle>,
459    ) -> Result<Self, MarkerError> {
460        Self::partitioned(
461            shape,
462            MarkerPartition::Radial {
463                start_angle_deg,
464                direction,
465            },
466            slices,
467            divider,
468            edge,
469        )
470    }
471    /// Build a horizontal two-colour marker (upper first).
472    pub fn horizontal<C0: Color, C1: Color>(
473        shape: MarkerShape,
474        first: C0,
475        second: C1,
476        edge: Option<ShapeStyle>,
477    ) -> Result<Self, MarkerError> {
478        Self::two(shape, MarkerPartition::Horizontal, first, second, edge)
479    }
480    /// Build a vertical two-colour marker (left first).
481    pub fn vertical<C0: Color, C1: Color>(
482        shape: MarkerShape,
483        first: C0,
484        second: C1,
485        edge: Option<ShapeStyle>,
486    ) -> Result<Self, MarkerError> {
487        Self::two(shape, MarkerPartition::Vertical, first, second, edge)
488    }
489    /// Build a visual `/` two-colour marker.
490    pub fn diagonal_forward<C0: Color, C1: Color>(
491        shape: MarkerShape,
492        first: C0,
493        second: C1,
494        edge: Option<ShapeStyle>,
495    ) -> Result<Self, MarkerError> {
496        Self::two(shape, MarkerPartition::DiagonalForward, first, second, edge)
497    }
498    /// Build a visual `\\` two-colour marker.
499    pub fn diagonal_backward<C0: Color, C1: Color>(
500        shape: MarkerShape,
501        first: C0,
502        second: C1,
503        edge: Option<ShapeStyle>,
504    ) -> Result<Self, MarkerError> {
505        Self::two(
506            shape,
507            MarkerPartition::DiagonalBackward,
508            first,
509            second,
510            edge,
511        )
512    }
513    /// Build four equal quadrants in upper-right, lower-right, lower-left, upper-left order.
514    pub fn quadrants<C: Color, I: IntoIterator<Item = C>>(
515        shape: MarkerShape,
516        rotation_deg: f64,
517        colors: I,
518        edge: Option<ShapeStyle>,
519    ) -> Result<Self, MarkerError> {
520        Self::partitioned(
521            shape,
522            MarkerPartition::Quadrants { rotation_deg },
523            colors
524                .into_iter()
525                .map(|color| MarkerSlice::new(1.0, color))
526                .collect(),
527            None,
528            edge,
529        )
530    }
531    /// Construct a fully explicit marker style.
532    pub fn new(
533        geometry: MarkerGeometry,
534        fill: MarkerFill,
535        edge: Option<ShapeStyle>,
536    ) -> Result<Self, MarkerError> {
537        let style = Self {
538            geometry,
539            fill,
540            edge,
541        };
542        style.validate()?;
543        Ok(style)
544    }
545    /// Validate this style without creating a drawable element.
546    pub fn validate(&self) -> Result<(), MarkerError> {
547        self.geometry.validate()?;
548        if !self.geometry.is_fillable() {
549            if !matches!(self.fill, MarkerFill::Empty) {
550                return Err(MarkerError::FillUnsupportedForStrokeOnly {
551                    shape: self.geometry.shape(),
552                });
553            }
554            return self
555                .edge
556                .is_some()
557                .then_some(())
558                .ok_or(MarkerError::EmptyMarkerWithoutEdge);
559        }
560        match &self.fill {
561            MarkerFill::Empty => self
562                .edge
563                .is_some()
564                .then_some(())
565                .ok_or(MarkerError::EmptyMarkerWithoutEdge),
566            MarkerFill::Solid { .. } => Ok(()),
567            MarkerFill::Partitioned {
568                partition, slices, ..
569            } => validate_partition(*partition, slices),
570        }
571    }
572    /// Prepare the shared backend-neutral draw plan.
573    pub fn drawing(&self) -> Result<MarkerDrawing, MarkerError> {
574        self.validate()?;
575        if !self.geometry.is_fillable() {
576            return Ok(MarkerDrawing {
577                outline: Vec::new(),
578                fills: Vec::new(),
579                dividers: Vec::new(),
580                divider_style: None,
581                edge: self.edge,
582                strokes: self.geometry.stroke_segments()?,
583            });
584        }
585        let outline = self.geometry.outline()?;
586        let (fills, dividers, divider_style) = match &self.fill {
587            MarkerFill::Empty => (Vec::new(), Vec::new(), None),
588            MarkerFill::Solid { color } => (
589                vec![MarkerFillPolygon {
590                    points: outline.clone(),
591                    color: *color,
592                }],
593                Vec::new(),
594                None,
595            ),
596            MarkerFill::Partitioned {
597                partition,
598                slices,
599                divider,
600            } => (
601                partition_fills(&outline, *partition, slices),
602                divider.as_ref().map_or_else(Vec::new, |_| {
603                    partition_dividers(&outline, *partition, slices)
604                }),
605                *divider,
606            ),
607        };
608        Ok(MarkerDrawing {
609            outline,
610            fills,
611            dividers,
612            divider_style,
613            edge: self.edge,
614            strokes: Vec::new(),
615        })
616    }
617    /// Scale only edge and divider widths for a high-resolution bitmap pass.
618    pub fn scaled(&self, factor: u32) -> Self {
619        let mut result = self.clone();
620        if let Some(edge) = result.edge.as_mut() {
621            edge.stroke_width = edge.stroke_width.saturating_mul(factor);
622        }
623        if let MarkerFill::Partitioned { divider, .. } = &mut result.fill
624            && let Some(divider) = divider.as_mut()
625        {
626            divider.stroke_width = divider.stroke_width.saturating_mul(factor);
627        }
628        result
629    }
630    pub(crate) fn from_legacy(shape: MarkerShape, style: ShapeStyle) -> Result<Self, MarkerError> {
631        let geometry = MarkerGeometry::new(shape)?;
632        if geometry.is_fillable() {
633            let fill = if style.filled {
634                MarkerFill::Solid { color: style.color }
635            } else {
636                MarkerFill::Empty
637            };
638            Self::new(geometry, fill, (!style.filled).then_some(style))
639        } else {
640            Self::new(geometry, MarkerFill::Empty, Some(style))
641        }
642    }
643    fn two<C0: Color, C1: Color>(
644        shape: MarkerShape,
645        partition: MarkerPartition,
646        first: C0,
647        second: C1,
648        edge: Option<ShapeStyle>,
649    ) -> Result<Self, MarkerError> {
650        Self::partitioned(
651            shape,
652            partition,
653            vec![MarkerSlice::new(1.0, first), MarkerSlice::new(1.0, second)],
654            None,
655            edge,
656        )
657    }
658}
659
660fn validate_partition(
661    partition: MarkerPartition,
662    slices: &[MarkerSlice],
663) -> Result<(), MarkerError> {
664    let required = match partition {
665        MarkerPartition::Radial {
666            start_angle_deg, ..
667        } => {
668            finite_rotation(start_angle_deg)?;
669            None
670        }
671        MarkerPartition::Quadrants { rotation_deg } => {
672            finite_rotation(rotation_deg)?;
673            Some(4)
674        }
675        _ => Some(2),
676    };
677    if slices.is_empty() {
678        return Err(MarkerError::EmptyPartition);
679    }
680    if slices.len() > 4 {
681        return Err(MarkerError::TooManySlices {
682            count: slices.len(),
683            maximum: 4,
684        });
685    }
686    if let Some(expected) = required
687        && slices.len() != expected
688    {
689        return Err(MarkerError::InvalidSliceCount {
690            expected,
691            actual: slices.len(),
692        });
693    }
694    for (index, slice) in slices.iter().enumerate() {
695        if !slice.weight.is_finite() || slice.weight <= 0.0 {
696            return Err(MarkerError::InvalidSliceWeight {
697                index,
698                weight: slice.weight,
699            });
700        }
701    }
702    Ok(())
703}
704
705/// A normalized backend-neutral marker point.
706#[derive(Clone, Copy, Debug, PartialEq)]
707pub struct LocalPoint {
708    pub x: f64,
709    pub y: f64,
710}
711/// A normalized local line segment.
712#[derive(Clone, Copy, Debug, PartialEq)]
713pub struct LocalSegment {
714    pub start: LocalPoint,
715    pub end: LocalPoint,
716}
717/// A coloured local polygon.
718#[derive(Clone, Debug, PartialEq)]
719pub struct MarkerFillPolygon {
720    pub points: Vec<LocalPoint>,
721    pub color: RGBAColor,
722}
723/// Prepared local marker drawing order: fills, dividers, one outer edge.
724#[derive(Clone, Debug, PartialEq)]
725pub struct MarkerDrawing {
726    pub outline: Vec<LocalPoint>,
727    pub fills: Vec<MarkerFillPolygon>,
728    pub dividers: Vec<LocalSegment>,
729    pub divider_style: Option<ShapeStyle>,
730    pub edge: Option<ShapeStyle>,
731    pub strokes: Vec<LocalSegment>,
732}
733
734/// A concrete owned Plotters element for one scientific marker.
735///
736/// The anchor is always the visual centre, whether it is a logical ternary
737/// point or a backend-pixel legend coordinate.
738pub struct MarkerElement<Coord> {
739    anchor: Coord,
740    size: u32,
741    drawing: MarkerDrawing,
742}
743impl<Coord> MarkerElement<Coord> {
744    /// Validate and build an element.
745    pub fn new(anchor: Coord, size: u32, style: MarkerStyle) -> Result<Self, MarkerError> {
746        if size == 0 {
747            return Err(MarkerError::InvalidSize { size });
748        }
749        Ok(Self {
750            anchor,
751            size,
752            drawing: style.drawing()?,
753        })
754    }
755    /// Return backend-pixel half-size.
756    pub const fn size(&self) -> u32 {
757        self.size
758    }
759    /// Inspect local geometry.
760    pub const fn drawing(&self) -> &MarkerDrawing {
761        &self.drawing
762    }
763}
764impl<'a, Coord> PointCollection<'a, Coord> for &'a MarkerElement<Coord> {
765    type Point = &'a Coord;
766    type IntoIter = std::iter::Once<&'a Coord>;
767    fn point_iter(self) -> Self::IntoIter {
768        std::iter::once(&self.anchor)
769    }
770}
771impl<Coord, DB: DrawingBackend> Drawable<DB> for MarkerElement<Coord> {
772    fn draw<I: Iterator<Item = BackendCoord>>(
773        &self,
774        mut points: I,
775        backend: &mut DB,
776        _: (u32, u32),
777    ) -> Result<(), DrawingErrorKind<DB::ErrorType>> {
778        let Some(anchor) = points.next() else {
779            return Ok(());
780        };
781        let map = |point: LocalPoint| backend_point(anchor, point, self.size);
782        for fill in &self.drawing.fills {
783            backend.fill_polygon(
784                fill.points.iter().copied().map(map),
785                &fill.color.to_backend_color(),
786            )?;
787        }
788        if let Some(style) = self.drawing.divider_style {
789            for divider in &self.drawing.dividers {
790                backend.draw_path([map(divider.start), map(divider.end)], &style)?;
791            }
792        }
793        if let Some(style) = self.drawing.edge {
794            if let Some(first) = self.drawing.outline.first().copied() {
795                let mut path: Vec<_> = self.drawing.outline.iter().copied().map(map).collect();
796                path.push(map(first));
797                backend.draw_path(path, &style)?;
798            }
799            for stroke in &self.drawing.strokes {
800                backend.draw_path([map(stroke.start), map(stroke.end)], &style)?;
801            }
802        }
803        Ok(())
804    }
805}
806fn backend_point(anchor: BackendCoord, point: LocalPoint, size: u32) -> BackendCoord {
807    (
808        round(f64::from(anchor.0) + point.x * f64::from(size)),
809        round(f64::from(anchor.1) + point.y * f64::from(size)),
810    )
811}
812fn round(value: f64) -> i32 {
813    value
814        .round()
815        .clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32
816}
817
818/// Marker validation error.
819#[derive(Clone, Debug, PartialEq)]
820#[non_exhaustive]
821pub enum MarkerError {
822    InvalidSize { size: u32 },
823    InvalidAspectRatio { value: f64 },
824    InvalidCornerRatio { value: f64 },
825    InvalidPolygonSides { sides: u8 },
826    InvalidStarPoints { points: u8 },
827    InvalidStarInnerRatio { value: f64 },
828    InvalidAsteriskArms { arms: u8 },
829    NonFiniteRotation { value: f64 },
830    FillUnsupportedForStrokeOnly { shape: MarkerShape },
831    EmptyMarkerWithoutEdge,
832    EmptyPartition,
833    TooManySlices { count: usize, maximum: usize },
834    InvalidSliceCount { expected: usize, actual: usize },
835    InvalidSliceWeight { index: usize, weight: f64 },
836}
837impl fmt::Display for MarkerError {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        match self {
840            Self::InvalidSize { size } => {
841                write!(f, "marker size must be greater than zero: {size}")
842            }
843            Self::InvalidAspectRatio { value } => write!(
844                f,
845                "marker aspect ratio must be finite and positive: {value:?}"
846            ),
847            Self::InvalidCornerRatio { value } => write!(
848                f,
849                "rounded-square corner ratio must be in 0.0..=0.5: {value:?}"
850            ),
851            Self::InvalidPolygonSides { sides } => write!(
852                f,
853                "regular polygon sides must be in {MIN_SIDES}..={MAX_SIDES}: {sides}"
854            ),
855            Self::InvalidStarPoints { points } => write!(
856                f,
857                "star points must be in {MIN_SIDES}..={MAX_SIDES}: {points}"
858            ),
859            Self::InvalidStarInnerRatio { value } => {
860                write!(f, "star inner ratio must be in (0, 1): {value:?}")
861            }
862            Self::InvalidAsteriskArms { arms } => write!(
863                f,
864                "asterisk arms must be in {MIN_SIDES}..={MAX_SIDES}: {arms}"
865            ),
866            Self::NonFiniteRotation { value } => {
867                write!(f, "marker rotation must be finite: {value:?}")
868            }
869            Self::FillUnsupportedForStrokeOnly { shape } => {
870                write!(f, "{shape:?} is stroke-only and cannot be filled")
871            }
872            Self::EmptyMarkerWithoutEdge => {
873                write!(f, "empty or stroke-only marker requires an edge")
874            }
875            Self::EmptyPartition => write!(f, "marker partition requires slices"),
876            Self::TooManySlices { count, maximum } => write!(
877                f,
878                "marker partition supports at most {maximum} slices: {count}"
879            ),
880            Self::InvalidSliceCount { expected, actual } => write!(
881                f,
882                "marker partition requires exactly {expected} slices: {actual}"
883            ),
884            Self::InvalidSliceWeight { index, weight } => write!(
885                f,
886                "marker slice {index} weight must be finite and positive: {weight:?}"
887            ),
888        }
889    }
890}
891impl std::error::Error for MarkerError {}
892
893fn p(x: f64, y: f64) -> LocalPoint {
894    LocalPoint { x, y }
895}
896fn seg(start: LocalPoint, end: LocalPoint) -> LocalSegment {
897    LocalSegment { start, end }
898}
899fn polar(angle: f64) -> LocalPoint {
900    let radians = angle.to_radians();
901    p(radians.cos(), -radians.sin())
902}
903fn rotate(point: LocalPoint, angle: f64) -> LocalPoint {
904    let radians = angle.to_radians();
905    let (sin, cos) = radians.sin_cos();
906    p(
907        point.x * cos + point.y * sin,
908        -point.x * sin + point.y * cos,
909    )
910}
911fn ellipse(aspect: f64) -> Vec<LocalPoint> {
912    let (x, y) = if aspect >= 1.0 {
913        (1.0, aspect.recip())
914    } else {
915        (aspect, 1.0)
916    };
917    (0..CIRCLE_SEGMENTS)
918        .map(|index| {
919            let q = polar(360.0 * index as f64 / CIRCLE_SEGMENTS as f64);
920            p(q.x * x, q.y * y)
921        })
922        .collect()
923}
924fn rectangle(aspect: f64) -> Vec<LocalPoint> {
925    let (x, y) = if aspect >= 1.0 {
926        (1.0, aspect.recip())
927    } else {
928        (aspect, 1.0)
929    };
930    vec![p(-x, -y), p(x, -y), p(x, y), p(-x, y)]
931}
932fn rounded_square(ratio: f64) -> Vec<LocalPoint> {
933    if ratio <= EPS {
934        return rectangle(1.0);
935    }
936    let c = 1.0 - ratio;
937    [(c, -c, -90.0), (c, c, 0.0), (-c, c, 90.0), (-c, -c, 180.0)]
938        .into_iter()
939        .flat_map(|(x, y, start)| {
940            (0..5).map(move |index| {
941                let q = polar(start + 90.0 * index as f64 / 4.0);
942                p(x + ratio * q.x, y + ratio * q.y)
943            })
944        })
945        .collect()
946}
947fn triangle(rotation: f64) -> Vec<LocalPoint> {
948    [p(0.0, -1.0), p(1.0, 1.0), p(-1.0, 1.0)]
949        .into_iter()
950        .map(|point| rotate(point, rotation))
951        .collect()
952}
953fn regular(sides: u8, rotation: f64) -> Vec<LocalPoint> {
954    (0..sides)
955        .map(|index| polar(-90.0 + rotation + 360.0 * f64::from(index) / f64::from(sides)))
956        .collect()
957}
958fn star(points: u8, inner: f64, rotation: f64) -> Vec<LocalPoint> {
959    (0..usize::from(points) * 2)
960        .map(|index| {
961            let q = polar(-90.0 + rotation + 180.0 * index as f64 / f64::from(points));
962            let radius = if index % 2 == 0 { 1.0 } else { inner };
963            p(q.x * radius, q.y * radius)
964        })
965        .collect()
966}
967fn normalize(mut points: Vec<LocalPoint>) -> Vec<LocalPoint> {
968    if points.is_empty() {
969        return points;
970    }
971    let min_x = points.iter().map(|q| q.x).fold(f64::INFINITY, f64::min);
972    let max_x = points.iter().map(|q| q.x).fold(f64::NEG_INFINITY, f64::max);
973    let min_y = points.iter().map(|q| q.y).fold(f64::INFINITY, f64::min);
974    let max_y = points.iter().map(|q| q.y).fold(f64::NEG_INFINITY, f64::max);
975    let cx = (min_x + max_x) / 2.0;
976    let cy = (min_y + max_y) / 2.0;
977    let extent = ((max_x - min_x) / 2.0).max((max_y - min_y) / 2.0);
978    for q in &mut points {
979        q.x = (q.x - cx) / extent;
980        q.y = (q.y - cy) / extent;
981    }
982    points
983}
984
985fn partition_fills(
986    outline: &[LocalPoint],
987    partition: MarkerPartition,
988    slices: &[MarkerSlice],
989) -> Vec<MarkerFillPolygon> {
990    match partition {
991        MarkerPartition::Radial {
992            start_angle_deg,
993            direction,
994        } => radial_fills(outline, start_angle_deg, direction, slices),
995        MarkerPartition::Horizontal => two_fills(outline, slices, |q| -q.y),
996        MarkerPartition::Vertical => two_fills(outline, slices, |q| -q.x),
997        MarkerPartition::DiagonalForward => two_fills(outline, slices, |q| -(q.x + q.y)),
998        MarkerPartition::DiagonalBackward => two_fills(outline, slices, |q| q.x - q.y),
999        MarkerPartition::Quadrants { rotation_deg } => {
1000            quadrant_fills(outline, rotation_deg, slices)
1001        }
1002    }
1003}
1004fn radial_fills(
1005    outline: &[LocalPoint],
1006    start: f64,
1007    direction: SweepDirection,
1008    slices: &[MarkerSlice],
1009) -> Vec<MarkerFillPolygon> {
1010    let total: f64 = slices.iter().map(|slice| slice.weight).sum();
1011    let sign = if direction == SweepDirection::CounterClockwise {
1012        1.0
1013    } else {
1014        -1.0
1015    };
1016    let mut current = start;
1017    let mut output = Vec::new();
1018    for slice in slices {
1019        let sweep = 360.0 * slice.weight / total;
1020        let next = current + sign * sweep;
1021        if sweep >= 360.0 - EPS {
1022            output.push(MarkerFillPolygon {
1023                points: outline.to_vec(),
1024                color: slice.color,
1025            });
1026        } else {
1027            let (first, last) = if direction == SweepDirection::CounterClockwise {
1028                (current, next)
1029            } else {
1030                (next, current)
1031            };
1032            output.extend(
1033                fan(outline)
1034                    .into_iter()
1035                    .flat_map(|triangle| sector_clip(&triangle, first, last))
1036                    .filter(|points| points.len() >= 3 && area(points).abs() > EPS)
1037                    .map(|points| MarkerFillPolygon {
1038                        points,
1039                        color: slice.color,
1040                    }),
1041            );
1042        }
1043        current = next;
1044    }
1045    output
1046}
1047fn two_fills<F: Fn(LocalPoint) -> f64 + Copy>(
1048    outline: &[LocalPoint],
1049    slices: &[MarkerSlice],
1050    distance: F,
1051) -> Vec<MarkerFillPolygon> {
1052    fan(outline)
1053        .into_iter()
1054        .flat_map(|triangle| {
1055            [(slices[0].color, 1.0), (slices[1].color, -1.0)]
1056                .into_iter()
1057                .filter_map(move |(color, sign)| {
1058                    let points = clip_half(&triangle, |q| sign * distance(q));
1059                    (points.len() >= 3 && area(&points).abs() > EPS)
1060                        .then_some(MarkerFillPolygon { points, color })
1061                })
1062        })
1063        .collect()
1064}
1065fn quadrant_fills(
1066    outline: &[LocalPoint],
1067    rotation: f64,
1068    slices: &[MarkerSlice],
1069) -> Vec<MarkerFillPolygon> {
1070    fan(outline)
1071        .into_iter()
1072        .flat_map(|triangle| {
1073            (0..4).filter_map(move |index| {
1074                let mut clipped = triangle.clone();
1075                let signs = match index {
1076                    0 => [(1.0, 0.0), (0.0, -1.0)],
1077                    1 => [(1.0, 0.0), (0.0, 1.0)],
1078                    2 => [(-1.0, 0.0), (0.0, 1.0)],
1079                    _ => [(-1.0, 0.0), (0.0, -1.0)],
1080                };
1081                for (x, y) in signs {
1082                    clipped = clip_half(&clipped, |q| {
1083                        let q = rotate(q, -rotation);
1084                        if x != 0.0 { x * q.x } else { y * q.y }
1085                    });
1086                }
1087                (clipped.len() >= 3 && area(&clipped).abs() > EPS).then_some(MarkerFillPolygon {
1088                    points: clipped,
1089                    color: slices[index].color,
1090                })
1091            })
1092        })
1093        .collect()
1094}
1095fn partition_dividers(
1096    outline: &[LocalPoint],
1097    partition: MarkerPartition,
1098    slices: &[MarkerSlice],
1099) -> Vec<LocalSegment> {
1100    match partition {
1101        MarkerPartition::Radial {
1102            start_angle_deg,
1103            direction,
1104        } => {
1105            let total: f64 = slices.iter().map(|slice| slice.weight).sum();
1106            let sign = if direction == SweepDirection::CounterClockwise {
1107                1.0
1108            } else {
1109                -1.0
1110            };
1111            let mut current = start_angle_deg;
1112            slices
1113                .iter()
1114                .take(slices.len().saturating_sub(1))
1115                .filter_map(|slice| {
1116                    current += sign * 360.0 * slice.weight / total;
1117                    ray(outline, current).map(|end| seg(p(0.0, 0.0), end))
1118                })
1119                .collect()
1120        }
1121        MarkerPartition::Horizontal => line_inside(outline, p(-1.0, 0.0), p(1.0, 0.0)),
1122        MarkerPartition::Vertical => line_inside(outline, p(0.0, -1.0), p(0.0, 1.0)),
1123        MarkerPartition::DiagonalForward => line_inside(outline, p(-1.0, 1.0), p(1.0, -1.0)),
1124        MarkerPartition::DiagonalBackward => line_inside(outline, p(-1.0, -1.0), p(1.0, 1.0)),
1125        MarkerPartition::Quadrants { rotation_deg } => {
1126            let h = seg(
1127                rotate(p(-1.0, 0.0), rotation_deg),
1128                rotate(p(1.0, 0.0), rotation_deg),
1129            );
1130            let v = seg(
1131                rotate(p(0.0, -1.0), rotation_deg),
1132                rotate(p(0.0, 1.0), rotation_deg),
1133            );
1134            line_inside(outline, h.start, h.end)
1135                .into_iter()
1136                .chain(line_inside(outline, v.start, v.end))
1137                .collect()
1138        }
1139    }
1140}
1141fn fan(outline: &[LocalPoint]) -> Vec<Vec<LocalPoint>> {
1142    outline
1143        .iter()
1144        .copied()
1145        .zip(outline.iter().copied().cycle().skip(1))
1146        .take(outline.len())
1147        .map(|(a, b)| vec![p(0.0, 0.0), a, b])
1148        .collect()
1149}
1150fn sector_clip(polygon: &[LocalPoint], start: f64, end: f64) -> Vec<Vec<LocalPoint>> {
1151    let sweep = end - start;
1152    if sweep <= EPS {
1153        return Vec::new();
1154    }
1155    let chunks = (sweep / 179.0).ceil() as usize;
1156    (0..chunks)
1157        .filter_map(|index| {
1158            let a = polar(start + sweep * index as f64 / chunks as f64);
1159            let b = polar(start + sweep * (index + 1) as f64 / chunks as f64);
1160            let first = clip_half(polygon, |q| cross_math(a, q));
1161            let second = clip_half(&first, |q| cross_math(q, b));
1162            (second.len() >= 3).then_some(second)
1163        })
1164        .collect()
1165}
1166fn clip_half<F: Fn(LocalPoint) -> f64>(polygon: &[LocalPoint], distance: F) -> Vec<LocalPoint> {
1167    let Some(mut before) = polygon.last().copied() else {
1168        return Vec::new();
1169    };
1170    let mut before_distance = distance(before);
1171    let mut output = Vec::new();
1172    for current in polygon.iter().copied() {
1173        let current_distance = distance(current);
1174        let inside_before = before_distance >= -EPS;
1175        let inside_current = current_distance >= -EPS;
1176        if inside_before != inside_current {
1177            let ratio = before_distance / (before_distance - current_distance);
1178            output.push(p(
1179                before.x + (current.x - before.x) * ratio,
1180                before.y + (current.y - before.y) * ratio,
1181            ));
1182        }
1183        if inside_current {
1184            output.push(current);
1185        }
1186        before = current;
1187        before_distance = current_distance;
1188    }
1189    output
1190}
1191fn area(points: &[LocalPoint]) -> f64 {
1192    points
1193        .iter()
1194        .copied()
1195        .zip(points.iter().copied().cycle().skip(1))
1196        .take(points.len())
1197        .map(|(a, b)| a.x * b.y - a.y * b.x)
1198        .sum::<f64>()
1199        / 2.0
1200}
1201fn cross_math(a: LocalPoint, b: LocalPoint) -> f64 {
1202    a.x * -b.y - -a.y * b.x
1203}
1204fn cross(a: LocalPoint, b: LocalPoint) -> f64 {
1205    a.x * b.y - a.y * b.x
1206}
1207fn ray(outline: &[LocalPoint], angle: f64) -> Option<LocalPoint> {
1208    let d = polar(angle);
1209    outline
1210        .iter()
1211        .copied()
1212        .zip(outline.iter().copied().cycle().skip(1))
1213        .take(outline.len())
1214        .filter_map(|(a, b)| {
1215            let edge = p(b.x - a.x, b.y - a.y);
1216            let denominator = cross(d, edge);
1217            if denominator.abs() <= EPS {
1218                return None;
1219            }
1220            let t = cross(a, edge) / denominator;
1221            let u = cross(a, d) / denominator;
1222            (t >= -EPS && (-EPS..=1.0 + EPS).contains(&u)).then_some(p(d.x * t, d.y * t))
1223        })
1224        .max_by(|a, b| {
1225            (a.x * a.x + a.y * a.y)
1226                .partial_cmp(&(b.x * b.x + b.y * b.y))
1227                .unwrap_or(std::cmp::Ordering::Equal)
1228        })
1229}
1230fn line_inside(outline: &[LocalPoint], start: LocalPoint, end: LocalPoint) -> Vec<LocalSegment> {
1231    let d = p(end.x - start.x, end.y - start.y);
1232    let mut values = vec![-2.0, 2.0];
1233    for (a, b) in outline
1234        .iter()
1235        .copied()
1236        .zip(outline.iter().copied().cycle().skip(1))
1237        .take(outline.len())
1238    {
1239        let edge = p(b.x - a.x, b.y - a.y);
1240        let denominator = cross(d, edge);
1241        if denominator.abs() <= EPS {
1242            continue;
1243        }
1244        let r = p(a.x - start.x, a.y - start.y);
1245        let t = cross(r, edge) / denominator;
1246        let u = cross(r, d) / denominator;
1247        if (-EPS..=1.0 + EPS).contains(&u) {
1248            values.push(t);
1249        }
1250    }
1251    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1252    values.dedup_by(|a, b| (*a - *b).abs() <= EPS);
1253    values
1254        .windows(2)
1255        .filter_map(|pair| {
1256            let m = (pair[0] + pair[1]) / 2.0;
1257            let midpoint = p(start.x + m * d.x, start.y + m * d.y);
1258            inside(midpoint, outline).then_some(seg(
1259                p(start.x + pair[0] * d.x, start.y + pair[0] * d.y),
1260                p(start.x + pair[1] * d.x, start.y + pair[1] * d.y),
1261            ))
1262        })
1263        .collect()
1264}
1265fn inside(point: LocalPoint, polygon: &[LocalPoint]) -> bool {
1266    polygon
1267        .iter()
1268        .copied()
1269        .zip(polygon.iter().copied().cycle().skip(1))
1270        .take(polygon.len())
1271        .fold(false, |state, (a, b)| {
1272            let crosses = (a.y > point.y) != (b.y > point.y)
1273                && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x;
1274            if crosses { !state } else { state }
1275        })
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280    use plotters::prelude::*;
1281
1282    use super::*;
1283
1284    const EDGE: ShapeStyle = ShapeStyle {
1285        color: RGBAColor(20, 30, 40, 1.0),
1286        filled: false,
1287        stroke_width: 2,
1288    };
1289
1290    fn polygon_area(polygons: &[MarkerFillPolygon]) -> f64 {
1291        polygons
1292            .iter()
1293            .map(|polygon| area(&polygon.points).abs())
1294            .sum()
1295    }
1296
1297    fn assert_centred(points: &[LocalPoint]) {
1298        let min_x = points
1299            .iter()
1300            .map(|point| point.x)
1301            .fold(f64::INFINITY, f64::min);
1302        let max_x = points
1303            .iter()
1304            .map(|point| point.x)
1305            .fold(f64::NEG_INFINITY, f64::max);
1306        let min_y = points
1307            .iter()
1308            .map(|point| point.y)
1309            .fold(f64::INFINITY, f64::min);
1310        let max_y = points
1311            .iter()
1312            .map(|point| point.y)
1313            .fold(f64::NEG_INFINITY, f64::max);
1314        assert!((min_x + max_x).abs() < 1.0e-9);
1315        assert!((min_y + max_y).abs() < 1.0e-9);
1316        assert!(max_x - min_x <= 2.0 + 1.0e-9);
1317        assert!(max_y - min_y <= 2.0 + 1.0e-9);
1318    }
1319
1320    #[test]
1321    fn fillable_outlines_are_centred_and_rotation_preserves_their_centre() {
1322        let shapes = [
1323            MarkerShape::Circle,
1324            MarkerShape::Ellipse { aspect_ratio: 1.8 },
1325            MarkerShape::Square,
1326            MarkerShape::Rectangle { aspect_ratio: 0.6 },
1327            MarkerShape::RoundedSquare { corner_ratio: 0.25 },
1328            MarkerShape::Diamond,
1329            MarkerShape::TriangleUp,
1330            MarkerShape::TriangleDown,
1331            MarkerShape::TriangleLeft,
1332            MarkerShape::TriangleRight,
1333            MarkerShape::hexagon(),
1334            MarkerShape::star5(),
1335        ];
1336        for shape in shapes {
1337            let outline = MarkerGeometry::new(shape).unwrap().outline().unwrap();
1338            assert_centred(&outline);
1339            let rotated = MarkerGeometry::new(shape)
1340                .unwrap()
1341                .rotated(37.0)
1342                .unwrap()
1343                .outline()
1344                .unwrap();
1345            assert_centred(&rotated);
1346        }
1347    }
1348
1349    #[test]
1350    fn triangles_have_distinct_tip_directions() {
1351        let outline = |shape| MarkerGeometry::new(shape).unwrap().outline().unwrap();
1352        let up = outline(MarkerShape::TriangleUp);
1353        let down = outline(MarkerShape::TriangleDown);
1354        let left = outline(MarkerShape::TriangleLeft);
1355        let right = outline(MarkerShape::TriangleRight);
1356        assert_ne!(up, down);
1357        assert_ne!(left, right);
1358        assert_eq!(up.iter().filter(|point| point.y < -0.99).count(), 1);
1359        assert_eq!(down.iter().filter(|point| point.y > 0.99).count(), 1);
1360        assert_eq!(left.iter().filter(|point| point.x < -0.99).count(), 1);
1361        assert_eq!(right.iter().filter(|point| point.x > 0.99).count(), 1);
1362        assert_eq!(
1363            MarkerGeometry::new(MarkerShape::Triangle).unwrap().shape(),
1364            MarkerShape::TriangleUp
1365        );
1366    }
1367
1368    #[test]
1369    fn regular_and_star_vertices_follow_the_requested_pattern() {
1370        assert_eq!(
1371            MarkerGeometry::new(MarkerShape::pentagon())
1372                .unwrap()
1373                .outline()
1374                .unwrap()
1375                .len(),
1376            5
1377        );
1378        let star = MarkerGeometry::new(MarkerShape::Star {
1379            points: 6,
1380            inner_ratio: 0.4,
1381            rotation_deg: 0.0,
1382        })
1383        .unwrap()
1384        .outline()
1385        .unwrap();
1386        assert_eq!(star.len(), 12);
1387        let radii: Vec<_> = star
1388            .iter()
1389            .map(|point| (point.x * point.x + point.y * point.y).sqrt())
1390            .collect();
1391        for pair in radii.windows(2) {
1392            assert!((pair[0] - pair[1]).abs() > 0.15);
1393        }
1394    }
1395
1396    #[test]
1397    fn empty_solid_and_stroke_only_models_have_unambiguous_draw_plans() {
1398        let empty = MarkerStyle::empty(MarkerShape::Circle, EDGE)
1399            .unwrap()
1400            .drawing()
1401            .unwrap();
1402        assert!(empty.fills.is_empty());
1403        assert!(empty.edge.is_some());
1404        let solid = MarkerStyle::solid(MarkerShape::Square, RED, EDGE)
1405            .unwrap()
1406            .drawing()
1407            .unwrap();
1408        assert_eq!(solid.fills.len(), 1);
1409        assert_eq!(solid.fills[0].points.len(), 4);
1410        let stroke = MarkerStyle::empty(MarkerShape::Plus, EDGE)
1411            .unwrap()
1412            .drawing()
1413            .unwrap();
1414        assert!(stroke.outline.is_empty());
1415        assert_eq!(stroke.strokes.len(), 2);
1416        assert!(matches!(
1417            MarkerStyle::solid(MarkerShape::Cross, RED, EDGE),
1418            Err(MarkerError::FillUnsupportedForStrokeOnly { .. })
1419        ));
1420    }
1421
1422    #[test]
1423    fn radial_weights_are_normalized_and_dividers_follow_their_angles() {
1424        let style = MarkerStyle::weighted_radial(
1425            MarkerShape::Circle,
1426            0.0,
1427            SweepDirection::CounterClockwise,
1428            vec![MarkerSlice::new(1.0, RED), MarkerSlice::new(3.0, BLUE)],
1429            Some(WHITE.stroke_width(1)),
1430            Some(EDGE),
1431        )
1432        .unwrap();
1433        let drawing = style.drawing().unwrap();
1434        assert_eq!(drawing.dividers.len(), 1);
1435        let end = drawing.dividers[0].end;
1436        let angle = (-end.y).atan2(end.x).to_degrees().rem_euclid(360.0);
1437        assert!((angle - 90.0).abs() < 1.0e-6, "{angle}");
1438        let outer = area(&drawing.outline).abs();
1439        assert!(
1440            (polygon_area(&drawing.fills) - outer).abs() < 1.0e-6,
1441            "{} {outer}",
1442            polygon_area(&drawing.fills)
1443        );
1444    }
1445
1446    #[test]
1447    fn every_partition_mode_covers_its_outer_shape_without_outer_edge_duplication() {
1448        let modes = [
1449            MarkerStyle::horizontal(MarkerShape::Circle, RED, BLUE, Some(EDGE)).unwrap(),
1450            MarkerStyle::vertical(MarkerShape::Circle, RED, BLUE, Some(EDGE)).unwrap(),
1451            MarkerStyle::diagonal_forward(MarkerShape::Circle, RED, BLUE, Some(EDGE)).unwrap(),
1452            MarkerStyle::diagonal_backward(MarkerShape::Circle, RED, BLUE, Some(EDGE)).unwrap(),
1453            MarkerStyle::quadrants(
1454                MarkerShape::Circle,
1455                25.0,
1456                [RED, BLUE, GREEN, YELLOW],
1457                Some(EDGE),
1458            )
1459            .unwrap(),
1460        ];
1461        for style in modes {
1462            let drawing = style.drawing().unwrap();
1463            let outer = area(&drawing.outline).abs();
1464            assert!((polygon_area(&drawing.fills) - outer).abs() < 1.0e-6);
1465            assert_eq!(drawing.edge, Some(EDGE));
1466            for polygon in drawing.fills {
1467                for point in polygon.points {
1468                    assert!(point.x.abs() <= 1.0 + 1.0e-8 && point.y.abs() <= 1.0 + 1.0e-8);
1469                }
1470            }
1471        }
1472    }
1473
1474    #[test]
1475    fn divider_is_optional_and_edge_and_fill_are_independent() {
1476        let no_divider = MarkerStyle::horizontal(MarkerShape::Diamond, RED, BLUE, Some(EDGE))
1477            .unwrap()
1478            .drawing()
1479            .unwrap();
1480        assert!(no_divider.dividers.is_empty());
1481        let with_divider = MarkerStyle::partitioned(
1482            MarkerShape::Diamond,
1483            MarkerPartition::Horizontal,
1484            vec![MarkerSlice::new(1.0, RED), MarkerSlice::new(1.0, BLUE)],
1485            Some(WHITE.stroke_width(2)),
1486            Some(EDGE),
1487        )
1488        .unwrap()
1489        .drawing()
1490        .unwrap();
1491        assert_eq!(with_divider.dividers.len(), 1);
1492        assert_eq!(with_divider.edge.unwrap().color, EDGE.color);
1493        assert_eq!(with_divider.fills[0].color, RED.to_rgba());
1494    }
1495
1496    #[test]
1497    fn svg_draw_order_emits_one_outer_edge_after_partition_fills() {
1498        let edge = ShapeStyle {
1499            color: RGBAColor(1, 2, 3, 1.0),
1500            filled: false,
1501            stroke_width: 2,
1502        };
1503        let style = MarkerStyle::partitioned(
1504            MarkerShape::Circle,
1505            MarkerPartition::Vertical,
1506            vec![MarkerSlice::new(1.0, RED), MarkerSlice::new(1.0, BLUE)],
1507            Some(WHITE.stroke_width(1)),
1508            Some(edge),
1509        )
1510        .unwrap();
1511        let marker = MarkerElement::new((40, 40), 16, style).unwrap();
1512        let mut svg = String::new();
1513        {
1514            let root = SVGBackend::with_string(&mut svg, (80, 80)).into_drawing_area();
1515            root.fill(&WHITE).unwrap();
1516            root.draw(&marker).unwrap();
1517            root.present().unwrap();
1518        }
1519        assert!(!svg.contains("<image"));
1520        assert_eq!(svg.matches("stroke=\"#010203\"").count(), 1);
1521        let last_fill = svg.rfind("fill=\"#0000FF\"").unwrap();
1522        let edge_position = svg.rfind("stroke=\"#010203\"").unwrap();
1523        assert!(edge_position > last_fill);
1524    }
1525
1526    #[test]
1527    fn invalid_marker_models_are_rejected() {
1528        assert!(matches!(
1529            MarkerGeometry::new(MarkerShape::RegularPolygon {
1530                sides: 2,
1531                rotation_deg: 0.0
1532            }),
1533            Err(MarkerError::InvalidPolygonSides { .. })
1534        ));
1535        assert!(matches!(
1536            MarkerGeometry::new(MarkerShape::Star {
1537                points: 17,
1538                inner_ratio: 0.5,
1539                rotation_deg: 0.0
1540            }),
1541            Err(MarkerError::InvalidStarPoints { .. })
1542        ));
1543        assert!(matches!(
1544            MarkerGeometry::new(MarkerShape::Star {
1545                points: 5,
1546                inner_ratio: 1.0,
1547                rotation_deg: 0.0
1548            }),
1549            Err(MarkerError::InvalidStarInnerRatio { .. })
1550        ));
1551        assert!(matches!(
1552            MarkerStyle::equal_radial(MarkerShape::Circle, Vec::<RGBColor>::new(), Some(EDGE)),
1553            Err(MarkerError::EmptyPartition)
1554        ));
1555        assert!(matches!(
1556            MarkerStyle::equal_radial(
1557                MarkerShape::Circle,
1558                [RED, BLUE, GREEN, YELLOW, BLACK],
1559                Some(EDGE)
1560            ),
1561            Err(MarkerError::TooManySlices { .. })
1562        ));
1563        assert!(matches!(
1564            MarkerStyle::weighted_radial(
1565                MarkerShape::Circle,
1566                0.0,
1567                SweepDirection::Clockwise,
1568                vec![MarkerSlice::new(0.0, RED)],
1569                None,
1570                Some(EDGE)
1571            ),
1572            Err(MarkerError::InvalidSliceWeight { .. })
1573        ));
1574        assert!(matches!(
1575            MarkerStyle::empty(MarkerShape::Circle, EDGE)
1576                .unwrap()
1577                .scaled(0)
1578                .validate(),
1579            Ok(())
1580        ));
1581    }
1582}