Skip to main content

plotters_ternary/chart/
contour_display.rs

1//! Chart-space contour colour bars and portable labels.
2//!
3//! These APIs consume final numerical contour coordinates and never mutate or
4//! reconstruct them.
5
6use std::f64::consts::{FRAC_PI_2, PI};
7use std::fmt;
8
9use plotters::backend::DrawingBackend;
10use plotters::element::{EmptyElement, PathElement, Rectangle, Text};
11use plotters::style::{BLACK, Color, FontStyle, RGBAColor, ShapeStyle, WHITE};
12use ternary_contours::{ContourPath, ContourSet};
13
14use crate::coord::{Normalization, TernaryCartesian, TernaryPoint};
15use crate::series::{InvalidPointPolicy, SeriesError, prepare_polyline};
16
17use super::{AxisTextStyle, RotatedText, TernaryChart, TernaryChartError};
18
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20#[non_exhaustive]
21pub enum ContourLabelMode {
22    #[default]
23    Tangent,
24    Curved,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct ContourLabelAnchor {
29    pub level: f64,
30    pub path_index: usize,
31    pub arc_fraction: f64,
32}
33impl ContourLabelAnchor {
34    pub const fn new(level: f64, path_index: usize, arc_fraction: f64) -> Self {
35        Self {
36            level,
37            path_index,
38            arc_fraction,
39        }
40    }
41}
42
43#[derive(Clone, Debug, Default, PartialEq)]
44#[non_exhaustive]
45pub enum ContourLabelPlacement {
46    #[default]
47    Automatic,
48    Repeated {
49        spacing: f64,
50    },
51    Manual(Vec<ContourLabelAnchor>),
52}
53
54#[derive(Clone)]
55pub struct ContourLabelStyle {
56    text: AxisTextStyle,
57    halo_color: Option<RGBAColor>,
58    halo_width: u32,
59    normal_offset: f64,
60}
61impl Default for ContourLabelStyle {
62    fn default() -> Self {
63        Self {
64            text: AxisTextStyle::sans_serif(19, FontStyle::Bold, BLACK.to_rgba()),
65            halo_color: Some(WHITE.to_rgba()),
66            halo_width: 2,
67            normal_offset: 0.0,
68        }
69    }
70}
71impl ContourLabelStyle {
72    pub fn new(text: AxisTextStyle) -> Self {
73        Self {
74            text,
75            ..Self::default()
76        }
77    }
78    pub fn halo<C: Color>(mut self, color: C, width: u32) -> Self {
79        self.halo_color = Some(color.to_rgba());
80        self.halo_width = width;
81        self
82    }
83    pub fn without_halo(mut self) -> Self {
84        self.halo_color = None;
85        self.halo_width = 0;
86        self
87    }
88    pub fn normal_offset(mut self, pixels: f64) -> Self {
89        self.normal_offset = pixels;
90        self
91    }
92    pub fn text_style(&self) -> &AxisTextStyle {
93        &self.text
94    }
95    pub const fn halo_width(&self) -> u32 {
96        self.halo_width
97    }
98    pub const fn normal_offset_pixels(&self) -> f64 {
99        self.normal_offset
100    }
101}
102
103type LabelFormatter<'a> = Box<dyn Fn(f64) -> String + 'a>;
104/// Formatting, placement, clearance and appearance policy for contour labels.
105pub struct ContourLabelConfig<'a> {
106    mode: ContourLabelMode,
107    placement: ContourLabelPlacement,
108    style: ContourLabelStyle,
109    formatter: LabelFormatter<'a>,
110    minimum_visible_length: f64,
111    endpoint_clearance: f64,
112    viewport_clearance: f64,
113    maximum_curvature_degrees: f64,
114    collision_padding: f64,
115}
116impl Default for ContourLabelConfig<'_> {
117    fn default() -> Self {
118        Self {
119            mode: ContourLabelMode::Tangent,
120            placement: ContourLabelPlacement::Automatic,
121            style: ContourLabelStyle::default(),
122            formatter: Box::new(|level| format!("{level:.3}")),
123            minimum_visible_length: 90.0,
124            endpoint_clearance: 20.0,
125            viewport_clearance: 8.0,
126            maximum_curvature_degrees: 32.0,
127            collision_padding: 5.0,
128        }
129    }
130}
131impl<'a> ContourLabelConfig<'a> {
132    pub fn new() -> Self {
133        Self::default()
134    }
135    pub fn mode(mut self, value: ContourLabelMode) -> Self {
136        self.mode = value;
137        self
138    }
139    pub fn placement(mut self, value: ContourLabelPlacement) -> Self {
140        self.placement = value;
141        self
142    }
143    pub fn style(mut self, value: ContourLabelStyle) -> Self {
144        self.style = value;
145        self
146    }
147    pub fn formatter<F, S>(mut self, value: F) -> Self
148    where
149        F: Fn(f64) -> S + 'a,
150        S: Into<String>,
151    {
152        self.formatter = Box::new(move |level| value(level).into());
153        self
154    }
155    pub fn minimum_visible_length(mut self, value: f64) -> Self {
156        self.minimum_visible_length = value;
157        self
158    }
159    pub fn endpoint_clearance(mut self, value: f64) -> Self {
160        self.endpoint_clearance = value;
161        self
162    }
163    pub fn viewport_clearance(mut self, value: f64) -> Self {
164        self.viewport_clearance = value;
165        self
166    }
167    pub fn maximum_curvature_degrees(mut self, value: f64) -> Self {
168        self.maximum_curvature_degrees = value;
169        self
170    }
171    pub fn collision_padding(mut self, value: f64) -> Self {
172        self.collision_padding = value;
173        self
174    }
175    fn validate(&self) -> Result<(), ContourDisplayError> {
176        for (name, value, positive) in [
177            ("minimum_visible_length", self.minimum_visible_length, false),
178            ("endpoint_clearance", self.endpoint_clearance, false),
179            ("viewport_clearance", self.viewport_clearance, false),
180            (
181                "maximum_curvature_degrees",
182                self.maximum_curvature_degrees,
183                true,
184            ),
185            ("collision_padding", self.collision_padding, false),
186        ] {
187            if !value.is_finite() || value < 0.0 || (positive && value == 0.0) {
188                return Err(ContourDisplayError::InvalidOption { name, value });
189            }
190        }
191        if !self.style.normal_offset.is_finite() {
192            return Err(ContourDisplayError::InvalidOption {
193                name: "normal_offset",
194                value: self.style.normal_offset,
195            });
196        }
197        if let ContourLabelPlacement::Repeated { spacing } = self.placement
198            && (!spacing.is_finite() || spacing <= 0.0)
199        {
200            return Err(ContourDisplayError::InvalidOption {
201                name: "repeated_label_spacing",
202                value: spacing,
203            });
204        }
205        if let ContourLabelPlacement::Manual(anchors) = &self.placement {
206            for anchor in anchors {
207                if !anchor.level.is_finite()
208                    || !anchor.arc_fraction.is_finite()
209                    || !(0.0..=1.0).contains(&anchor.arc_fraction)
210                {
211                    return Err(ContourDisplayError::InvalidManualAnchor {
212                        level: anchor.level,
213                        path_index: anchor.path_index,
214                        arc_fraction: anchor.arc_fraction,
215                    });
216                }
217            }
218        }
219        Ok(())
220    }
221}
222
223#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
224pub enum ContourColorBarOrientation {
225    #[default]
226    Vertical,
227    Horizontal,
228}
229#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
230pub enum ContourColorBarPosition {
231    UpperLeft,
232    #[default]
233    UpperRight,
234    LowerLeft,
235    LowerRight,
236}
237type ColorMap<'a> = Box<dyn Fn(f64) -> RGBAColor + 'a>;
238/// Continuous scalar-level key drawn in chart layout space.
239pub struct ContourColorBar<'a> {
240    minimum: f64,
241    maximum: f64,
242    map: ColorMap<'a>,
243    orientation: ContourColorBarOrientation,
244    position: ContourColorBarPosition,
245    length: u32,
246    thickness: u32,
247    margin: i32,
248    ticks: Vec<f64>,
249    formatter: LabelFormatter<'a>,
250    title: Option<String>,
251    text_style: AxisTextStyle,
252    border_style: ShapeStyle,
253}
254impl<'a> ContourColorBar<'a> {
255    pub fn new<F>(minimum: f64, maximum: f64, map: F) -> Result<Self, ContourDisplayError>
256    where
257        F: Fn(f64) -> RGBAColor + 'a,
258    {
259        if !minimum.is_finite() || !maximum.is_finite() || maximum <= minimum {
260            return Err(ContourDisplayError::InvalidColorBarRange { minimum, maximum });
261        }
262        Ok(Self {
263            minimum,
264            maximum,
265            map: Box::new(map),
266            orientation: ContourColorBarOrientation::Vertical,
267            position: ContourColorBarPosition::UpperRight,
268            length: 220,
269            thickness: 18,
270            margin: 18,
271            ticks: (0..=4)
272                .map(|i| minimum + (maximum - minimum) * f64::from(i) / 4.0)
273                .collect(),
274            formatter: Box::new(|value| format!("{value:.2}")),
275            title: None,
276            text_style: AxisTextStyle::sans_serif(16, FontStyle::Normal, BLACK.to_rgba()),
277            border_style: BLACK.stroke_width(1),
278        })
279    }
280    pub fn orientation(mut self, value: ContourColorBarOrientation) -> Self {
281        self.orientation = value;
282        self
283    }
284    pub fn position(mut self, value: ContourColorBarPosition) -> Self {
285        self.position = value;
286        self
287    }
288    pub fn size(mut self, length: u32, thickness: u32) -> Self {
289        self.length = length;
290        self.thickness = thickness;
291        self
292    }
293    pub fn margin(mut self, value: i32) -> Self {
294        self.margin = value;
295        self
296    }
297    pub fn tick_values(mut self, value: Vec<f64>) -> Self {
298        self.ticks = value;
299        self
300    }
301    pub fn formatter<F, S>(mut self, value: F) -> Self
302    where
303        F: Fn(f64) -> S + 'a,
304        S: Into<String>,
305    {
306        self.formatter = Box::new(move |v| value(v).into());
307        self
308    }
309    pub fn title<S: Into<String>>(mut self, value: S) -> Self {
310        self.title = Some(value.into());
311        self
312    }
313    pub fn text_style(mut self, value: AxisTextStyle) -> Self {
314        self.text_style = value;
315        self
316    }
317    pub fn border_style<S: Into<ShapeStyle>>(mut self, value: S) -> Self {
318        self.border_style = value.into();
319        self
320    }
321    fn validate(&self) -> Result<(), ContourDisplayError> {
322        if self.length == 0 || self.thickness == 0 {
323            return Err(ContourDisplayError::InvalidColorBarSize {
324                length: self.length,
325                thickness: self.thickness,
326            });
327        }
328        if self
329            .ticks
330            .iter()
331            .any(|v| !v.is_finite() || *v < self.minimum || *v > self.maximum)
332        {
333            return Err(ContourDisplayError::InvalidColorBarTicks);
334        }
335        Ok(())
336    }
337}
338
339#[derive(Clone, Debug, PartialEq)]
340#[non_exhaustive]
341pub enum ContourDisplayError {
342    InvalidOption {
343        name: &'static str,
344        value: f64,
345    },
346    InvalidManualAnchor {
347        level: f64,
348        path_index: usize,
349        arc_fraction: f64,
350    },
351    ManualLevelNotFound {
352        level: f64,
353    },
354    ManualPathNotFound {
355        level: f64,
356        path_index: usize,
357    },
358    InvalidColorBarRange {
359        minimum: f64,
360        maximum: f64,
361    },
362    InvalidColorBarSize {
363        length: u32,
364        thickness: u32,
365    },
366    InvalidColorBarTicks,
367}
368impl fmt::Display for ContourDisplayError {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        match self {
371            Self::InvalidOption { name, value } => {
372                write!(f, "invalid contour display option {name}: {value:?}")
373            }
374            Self::InvalidManualAnchor {
375                level,
376                path_index,
377                arc_fraction,
378            } => write!(
379                f,
380                "invalid manual contour anchor at level {level:?}, path {path_index}, fraction {arc_fraction:?}"
381            ),
382            Self::ManualLevelNotFound { level } => {
383                write!(f, "manual contour-label level was not found: {level:?}")
384            }
385            Self::ManualPathNotFound { level, path_index } => write!(
386                f,
387                "manual contour-label path {path_index} was not found at level {level:?}"
388            ),
389            Self::InvalidColorBarRange { minimum, maximum } => write!(
390                f,
391                "colour-bar range must be finite and increasing: {minimum:?}..{maximum:?}"
392            ),
393            Self::InvalidColorBarSize { length, thickness } => write!(
394                f,
395                "colour-bar dimensions must be nonzero: {length}x{thickness}"
396            ),
397            Self::InvalidColorBarTicks => write!(
398                f,
399                "colour-bar ticks must be finite and within the configured range"
400            ),
401        }
402    }
403}
404impl std::error::Error for ContourDisplayError {}
405#[derive(Clone, Copy, Debug, PartialEq)]
406struct PixelPoint {
407    x: f64,
408    y: f64,
409}
410impl PixelPoint {
411    fn distance(self, other: Self) -> f64 {
412        (self.x - other.x).hypot(self.y - other.y)
413    }
414    fn interpolate(self, other: Self, t: f64) -> Self {
415        Self {
416            x: self.x + t * (other.x - self.x),
417            y: self.y + t * (other.y - self.y),
418        }
419    }
420}
421#[derive(Clone, Copy, Debug, PartialEq)]
422struct Bounds {
423    x_min: f64,
424    x_max: f64,
425    y_min: f64,
426    y_max: f64,
427}
428impl Bounds {
429    fn padded(self, p: f64) -> Self {
430        Self {
431            x_min: self.x_min - p,
432            x_max: self.x_max + p,
433            y_min: self.y_min - p,
434            y_max: self.y_max + p,
435        }
436    }
437    fn overlaps(self, o: Self) -> bool {
438        self.x_min < o.x_max && self.x_max > o.x_min && self.y_min < o.y_max && self.y_max > o.y_min
439    }
440    fn inside(self, o: Self, c: f64) -> bool {
441        self.x_min >= o.x_min + c
442            && self.x_max <= o.x_max - c
443            && self.y_min >= o.y_min + c
444            && self.y_max <= o.y_max - c
445    }
446    fn union(self, o: Self) -> Self {
447        Self {
448            x_min: self.x_min.min(o.x_min),
449            x_max: self.x_max.max(o.x_max),
450            y_min: self.y_min.min(o.y_min),
451            y_max: self.y_max.max(o.y_max),
452        }
453    }
454}
455#[derive(Clone)]
456struct ProjectedPath {
457    logical: Vec<TernaryCartesian>,
458    pixels: Vec<PixelPoint>,
459    cumulative: Vec<f64>,
460}
461impl ProjectedPath {
462    fn new<DB: DrawingBackend>(
463        chart: &TernaryChart<'_, DB>,
464        logical: Vec<TernaryCartesian>,
465    ) -> Self {
466        let pixels = logical
467            .iter()
468            .map(|p| {
469                let (x, y) = chart.plotting_area().map_coordinate(&(p.x, p.y));
470                PixelPoint {
471                    x: f64::from(x),
472                    y: f64::from(y),
473                }
474            })
475            .collect::<Vec<_>>();
476        let mut cumulative = Vec::with_capacity(pixels.len());
477        cumulative.push(0.0);
478        for pair in pixels.windows(2) {
479            cumulative.push(cumulative.last().copied().unwrap_or(0.0) + pair[0].distance(pair[1]));
480        }
481        Self {
482            logical,
483            pixels,
484            cumulative,
485        }
486    }
487    fn length(&self) -> f64 {
488        self.cumulative.last().copied().unwrap_or(0.0)
489    }
490    fn sample(&self, distance: f64) -> Option<(TernaryCartesian, PixelPoint)> {
491        if self.logical.len() < 2 {
492            return None;
493        }
494        let distance = distance.clamp(0.0, self.length());
495        let index = self
496            .cumulative
497            .partition_point(|v| *v < distance)
498            .min(self.cumulative.len() - 1);
499        let segment = index.saturating_sub(1).min(self.logical.len() - 2);
500        let (start, end) = (self.cumulative[segment], self.cumulative[segment + 1]);
501        let t = if end > start {
502            (distance - start) / (end - start)
503        } else {
504            0.0
505        };
506        let (a, b) = (self.logical[segment], self.logical[segment + 1]);
507        Some((
508            TernaryCartesian {
509                x: a.x + t * (b.x - a.x),
510                y: a.y + t * (b.y - a.y),
511            },
512            self.pixels[segment].interpolate(self.pixels[segment + 1], t),
513        ))
514    }
515    fn tangent(&self, distance: f64, window: f64) -> Option<(f64, bool)> {
516        let left = self.sample((distance - window).max(0.0))?.1;
517        let right = self.sample((distance + window).min(self.length()))?.1;
518        readable_angle((right.y - left.y).atan2(right.x - left.x))
519    }
520    fn curvature_degrees(&self, distance: f64, span: f64) -> Option<f64> {
521        let left = self.tangent((distance - span).max(0.0), 4.0)?.0;
522        let right = self.tangent((distance + span).min(self.length()), 4.0)?.0;
523        Some(angle_difference(left, right).to_degrees().abs())
524    }
525}
526struct VisibleFragment {
527    level: f64,
528    path_index: usize,
529    path: ProjectedPath,
530}
531#[derive(Clone)]
532struct LabelGlyph {
533    logical: TernaryCartesian,
534    text: String,
535    angle: f64,
536    offset: (i32, i32),
537}
538#[derive(Clone)]
539struct PreparedLabel {
540    glyphs: Vec<LabelGlyph>,
541    bounds: Bounds,
542    mask_interval: (f64, f64),
543}
544
545fn visible_fragments<DB: DrawingBackend>(
546    chart: &TernaryChart<'_, DB>,
547    contours: &ContourSet,
548) -> Result<Vec<VisibleFragment>, TernaryChartError<DB::ErrorType>> {
549    let mut fragments = Vec::new();
550    for level in &contours.levels {
551        for (path_index, path) in level.paths.iter().enumerate() {
552            let mut source = path
553                .points
554                .iter()
555                .copied()
556                .map(|p| TernaryPoint::from(p.as_array()))
557                .collect::<Vec<_>>();
558            if path.closed && !source.is_empty() {
559                source.push(source[0]);
560            }
561            for logical in prepare_polyline(
562                chart.geometry,
563                chart.viewport,
564                source,
565                Normalization::RequireUnitSum,
566                chart.tolerance,
567                InvalidPointPolicy::Error,
568            )? {
569                if logical.len() >= 2 {
570                    fragments.push(VisibleFragment {
571                        level: level.value,
572                        path_index,
573                        path: ProjectedPath::new(chart, logical),
574                    });
575                }
576            }
577        }
578    }
579    Ok(fragments)
580}
581fn project_complete_path<DB: DrawingBackend>(
582    chart: &TernaryChart<'_, DB>,
583    path: &ContourPath,
584) -> Result<ProjectedPath, TernaryChartError<DB::ErrorType>> {
585    let mut logical = path
586        .points
587        .iter()
588        .copied()
589        .map(|p| {
590            chart.geometry.project(
591                TernaryPoint::from(p.as_array()),
592                Normalization::RequireUnitSum,
593                chart.tolerance,
594            )
595        })
596        .collect::<Result<Vec<_>, _>>()?;
597    if path.closed && !logical.is_empty() {
598        logical.push(logical[0]);
599    }
600    Ok(ProjectedPath::new(chart, logical))
601}
602
603fn prepare_labels<DB: DrawingBackend>(
604    chart: &TernaryChart<'_, DB>,
605    contours: &ContourSet,
606    config: &ContourLabelConfig<'_>,
607) -> Result<Vec<PreparedLabel>, TernaryChartError<DB::ErrorType>> {
608    let viewport = viewport_pixel_bounds(chart);
609    let mut reserved: Vec<Bounds> = Vec::new();
610    let mut result = Vec::new();
611    if let ContourLabelPlacement::Manual(anchors) = &config.placement {
612        for anchor in anchors {
613            let level = contours
614                .levels
615                .iter()
616                .find(|v| level_matches(v.value, anchor.level))
617                .ok_or(SeriesError::ContourDisplay(
618                    ContourDisplayError::ManualLevelNotFound {
619                        level: anchor.level,
620                    },
621                ))?;
622            let source = level
623                .paths
624                .get(anchor.path_index)
625                .ok_or(SeriesError::ContourDisplay(
626                    ContourDisplayError::ManualPathNotFound {
627                        level: anchor.level,
628                        path_index: anchor.path_index,
629                    },
630                ))?;
631            let path = project_complete_path(chart, source)?;
632            let text = (config.formatter)(level.value);
633            let dimensions = chart
634                .plotting_area()
635                .estimate_text_size(&text, &config.style.text.plotters_style())?;
636            if let Some(candidate) = make_label(
637                &path,
638                anchor.arc_fraction * path.length(),
639                &text,
640                dimensions,
641                config,
642                viewport,
643                false,
644                chart,
645            )? && !reserved.iter().any(|b| candidate.bounds.overlaps(*b))
646            {
647                reserved.push(candidate.bounds);
648                result.push(candidate);
649            }
650        }
651        return Ok(result);
652    }
653    let fragments = visible_fragments(chart, contours)?;
654    for level in &contours.levels {
655        let text = (config.formatter)(level.value);
656        let dimensions = chart
657            .plotting_area()
658            .estimate_text_size(&text, &config.style.text.plotters_style())?;
659        for path_index in 0..level.paths.len() {
660            let eligible = fragments
661                .iter()
662                .filter(|f| level_matches(f.level, level.value) && f.path_index == path_index)
663                .collect::<Vec<_>>();
664            match config.placement {
665                ContourLabelPlacement::Automatic => {
666                    let mut candidates = Vec::new();
667                    for fragment in eligible {
668                        for distance in automatic_distances(
669                            fragment.path.length(),
670                            f64::from(dimensions.0),
671                            config.endpoint_clearance,
672                        ) {
673                            if let Some(candidate) = make_label(
674                                &fragment.path,
675                                distance,
676                                &text,
677                                dimensions,
678                                config,
679                                viewport,
680                                true,
681                                chart,
682                            )? {
683                                let curvature = fragment
684                                    .path
685                                    .curvature_degrees(distance, f64::from(dimensions.0) * 0.3)
686                                    .unwrap_or(180.0);
687                                let score = -(distance - fragment.path.length() * 0.5).abs()
688                                    - 2.0 * curvature;
689                                candidates.push((score, candidate));
690                            }
691                        }
692                    }
693                    candidates.sort_by(|a, b| b.0.total_cmp(&a.0));
694                    if let Some((_, candidate)) = candidates
695                        .into_iter()
696                        .find(|(_, c)| !reserved.iter().any(|b| c.bounds.overlaps(*b)))
697                    {
698                        reserved.push(candidate.bounds);
699                        result.push(candidate);
700                    }
701                }
702                ContourLabelPlacement::Repeated { spacing } => {
703                    for fragment in eligible {
704                        for distance in repeated_distances(
705                            fragment.path.length(),
706                            f64::from(dimensions.0),
707                            config.endpoint_clearance,
708                            spacing,
709                        ) {
710                            if let Some(candidate) = make_label(
711                                &fragment.path,
712                                distance,
713                                &text,
714                                dimensions,
715                                config,
716                                viewport,
717                                true,
718                                chart,
719                            )? && !reserved.iter().any(|b| candidate.bounds.overlaps(*b))
720                            {
721                                reserved.push(candidate.bounds);
722                                result.push(candidate);
723                            }
724                        }
725                    }
726                }
727                ContourLabelPlacement::Manual(_) => unreachable!(),
728            }
729        }
730    }
731    Ok(result)
732}
733
734#[allow(clippy::too_many_arguments)]
735fn make_label<DB: DrawingBackend>(
736    path: &ProjectedPath,
737    distance: f64,
738    text: &str,
739    dimensions: (u32, u32),
740    config: &ContourLabelConfig<'_>,
741    viewport: Bounds,
742    enforce_clearance: bool,
743    chart: &TernaryChart<'_, DB>,
744) -> Result<Option<PreparedLabel>, TernaryChartError<DB::ErrorType>> {
745    let width = f64::from(dimensions.0.max(1));
746    let height = f64::from(dimensions.1.max(config.style.text.size()));
747    let half = width * 0.5 + 5.0;
748    if path.length()
749        < config
750            .minimum_visible_length
751            .max(width + 2.0 * config.endpoint_clearance)
752        || (enforce_clearance
753            && (distance < config.endpoint_clearance + half
754                || path.length() - distance < config.endpoint_clearance + half))
755    {
756        return Ok(None);
757    }
758    if path
759        .curvature_degrees(distance, half * 0.75)
760        .unwrap_or(f64::INFINITY)
761        > config.maximum_curvature_degrees
762    {
763        return Ok(None);
764    }
765    let Some((angle, reversed)) = path.tangent(distance, (width * 0.15).max(6.0)) else {
766        return Ok(None);
767    };
768    let label = match config.mode {
769        ContourLabelMode::Tangent => {
770            let Some((logical, pixel)) = path.sample(distance) else {
771                return Ok(None);
772            };
773            let offset = normal_offset(angle, config.style.normal_offset);
774            PreparedLabel {
775                glyphs: vec![LabelGlyph {
776                    logical,
777                    text: text.to_owned(),
778                    angle,
779                    offset,
780                }],
781                bounds: rotated_bounds(pixel, width, height, angle, offset)
782                    .padded(config.collision_padding),
783                mask_interval: mask_interval(distance, width, 6.0, path.length()),
784            }
785        }
786        ContourLabelMode::Curved => {
787            let style = config.style.text.plotters_style();
788            let mut advances = Vec::new();
789            for ch in text.chars() {
790                let glyph = ch.to_string();
791                let (w, h) = chart.plotting_area().estimate_text_size(&glyph, &style)?;
792                advances.push((glyph, f64::from(w.max(1)), f64::from(h.max(1))));
793            }
794            let total = advances.iter().map(|v| v.1).sum::<f64>();
795            if total > path.length() - 2.0 * config.endpoint_clearance {
796                return Ok(None);
797            }
798            let mut cursor = -total * 0.5;
799            let mut glyphs = Vec::new();
800            let mut bounds: Option<Bounds> = None;
801            for (glyph, advance, glyph_height) in advances {
802                let local = cursor + advance * 0.5;
803                cursor += advance;
804                let d = if reversed {
805                    distance - local
806                } else {
807                    distance + local
808                };
809                let Some((logical, pixel)) = path.sample(d) else {
810                    return Ok(None);
811                };
812                let Some((glyph_angle, _)) = path.tangent(d, (advance * 0.5).max(3.0)) else {
813                    return Ok(None);
814                };
815                let offset = normal_offset(glyph_angle, config.style.normal_offset);
816                let b = rotated_bounds(
817                    pixel,
818                    advance,
819                    glyph_height.max(height),
820                    glyph_angle,
821                    offset,
822                );
823                bounds = Some(bounds.map_or(b, |old| old.union(b)));
824                if !glyph.chars().all(char::is_whitespace) {
825                    glyphs.push(LabelGlyph {
826                        logical,
827                        text: glyph,
828                        angle: glyph_angle,
829                        offset,
830                    });
831                }
832            }
833            PreparedLabel {
834                glyphs,
835                bounds: bounds
836                    .unwrap_or(Bounds {
837                        x_min: 0.0,
838                        x_max: 0.0,
839                        y_min: 0.0,
840                        y_max: 0.0,
841                    })
842                    .padded(config.collision_padding),
843                mask_interval: mask_interval(distance, total, 6.0, path.length()),
844            }
845        }
846    };
847    if !label.bounds.inside(viewport, config.viewport_clearance) {
848        return Ok(None);
849    }
850    Ok(Some(label))
851}
852impl<'a, DB: DrawingBackend + 'a> TernaryChart<'a, DB> {
853    pub fn draw_contour_labels(
854        &self,
855        contours: &ContourSet,
856        config: &ContourLabelConfig<'_>,
857    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
858        config.validate().map_err(SeriesError::ContourDisplay)?;
859        for label in prepare_labels(self, contours, config)? {
860            draw_label(self, &label, &config.style)?;
861        }
862        Ok(())
863    }
864    pub fn draw_contour_color_bar(
865        &self,
866        bar: &ContourColorBar<'_>,
867    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
868        self.draw_contour_color_bar_geometry(bar, 1)?;
869        self.draw_contour_color_bar_text(bar)
870    }
871    pub fn draw_contour_color_bar_geometry(
872        &self,
873        bar: &ContourColorBar<'_>,
874        scale: u32,
875    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
876        bar.validate().map_err(SeriesError::ContourDisplay)?;
877        let layout = color_bar_layout(self, bar, scale);
878        let cells = 64_i32;
879        for index in 0..cells {
880            let start = f64::from(index) / f64::from(cells);
881            let end = f64::from(index + 1) / f64::from(cells);
882            let style = (bar.map)((start + end) * 0.5).filled();
883            let (first, second) = match bar.orientation {
884                ContourColorBarOrientation::Vertical => {
885                    let y0 = layout.origin.1 + layout.length
886                        - (end * f64::from(layout.length)).round() as i32;
887                    let y1 = layout.origin.1 + layout.length
888                        - (start * f64::from(layout.length)).round() as i32;
889                    (
890                        (layout.origin.0, y0),
891                        (layout.origin.0 + layout.thickness, y1),
892                    )
893                }
894                ContourColorBarOrientation::Horizontal => {
895                    let x0 = layout.origin.0 + (start * f64::from(layout.length)).round() as i32;
896                    let x1 = layout.origin.0 + (end * f64::from(layout.length)).round() as i32;
897                    (
898                        (x0, layout.origin.1),
899                        (x1, layout.origin.1 + layout.thickness),
900                    )
901                }
902            };
903            self.plotting_area().draw(
904                &(EmptyElement::<_, DB>::at((layout.anchor.x, layout.anchor.y))
905                    + Rectangle::new([first, second], style)),
906            )?;
907        }
908        let outline = match bar.orientation {
909            ContourColorBarOrientation::Vertical => [
910                layout.origin,
911                (
912                    layout.origin.0 + layout.thickness,
913                    layout.origin.1 + layout.length,
914                ),
915            ],
916            ContourColorBarOrientation::Horizontal => [
917                layout.origin,
918                (
919                    layout.origin.0 + layout.length,
920                    layout.origin.1 + layout.thickness,
921                ),
922            ],
923        };
924        self.plotting_area().draw(
925            &(EmptyElement::<_, DB>::at((layout.anchor.x, layout.anchor.y))
926                + Rectangle::new(outline, scaled_shape(bar.border_style, scale))),
927        )?;
928        for value in &bar.ticks {
929            let t = ((*value - bar.minimum) / (bar.maximum - bar.minimum)).clamp(0.0, 1.0);
930            let points = match bar.orientation {
931                ContourColorBarOrientation::Vertical => {
932                    let y = layout.origin.1 + layout.length
933                        - (t * f64::from(layout.length)).round() as i32;
934                    [
935                        (layout.origin.0 + layout.thickness, y),
936                        (layout.origin.0 + layout.thickness + 6 * scale as i32, y),
937                    ]
938                }
939                ContourColorBarOrientation::Horizontal => {
940                    let x = layout.origin.0 + (t * f64::from(layout.length)).round() as i32;
941                    [
942                        (x, layout.origin.1 + layout.thickness),
943                        (x, layout.origin.1 + layout.thickness + 6 * scale as i32),
944                    ]
945                }
946            };
947            self.plotting_area().draw(
948                &(EmptyElement::<_, DB>::at((layout.anchor.x, layout.anchor.y))
949                    + PathElement::new(points, BLACK.stroke_width(scale))),
950            )?;
951        }
952        Ok(())
953    }
954    pub fn draw_contour_color_bar_text(
955        &self,
956        bar: &ContourColorBar<'_>,
957    ) -> Result<(), TernaryChartError<DB::ErrorType>> {
958        bar.validate().map_err(SeriesError::ContourDisplay)?;
959        let layout = color_bar_layout(self, bar, 1);
960        let style = bar.text_style.plotters_style();
961        for value in &bar.ticks {
962            let t = ((*value - bar.minimum) / (bar.maximum - bar.minimum)).clamp(0.0, 1.0);
963            let offset = match bar.orientation {
964                ContourColorBarOrientation::Vertical => {
965                    let y = layout.origin.1 + layout.length
966                        - (t * f64::from(layout.length)).round() as i32;
967                    (layout.origin.0 + layout.thickness + 10, y - 8)
968                }
969                ContourColorBarOrientation::Horizontal => {
970                    let x = layout.origin.0 + (t * f64::from(layout.length)).round() as i32;
971                    (x - 14, layout.origin.1 + layout.thickness + 10)
972                }
973            };
974            self.plotting_area().draw(
975                &(EmptyElement::<_, DB>::at((layout.anchor.x, layout.anchor.y))
976                    + Text::new((bar.formatter)(*value), offset, style.clone())),
977            )?;
978        }
979        if let Some(title) = &bar.title {
980            let offset = (
981                layout.origin.0,
982                layout.origin.1 - bar.text_style.size() as i32 - 4,
983            );
984            self.plotting_area().draw(
985                &(EmptyElement::<_, DB>::at((layout.anchor.x, layout.anchor.y))
986                    + Text::new(title.clone(), offset, style)),
987            )?;
988        }
989        Ok(())
990    }
991}
992
993fn draw_label<DB: DrawingBackend>(
994    chart: &TernaryChart<'_, DB>,
995    label: &PreparedLabel,
996    style: &ContourLabelStyle,
997) -> Result<(), TernaryChartError<DB::ErrorType>> {
998    let _ = label.mask_interval;
999    if let Some(color) = style.halo_color {
1000        let halo = AxisTextStyle::new(
1001            style.text.family(),
1002            style.text.size(),
1003            style.text.font_style(),
1004            color,
1005        );
1006        let radius = style.halo_width as i32;
1007        for glyph in &label.glyphs {
1008            for y in -radius..=radius {
1009                for x in -radius..=radius {
1010                    if (x == 0 && y == 0) || x * x + y * y > radius * radius {
1011                        continue;
1012                    }
1013                    chart.plotting_area().draw(&RotatedText::new(
1014                        (glyph.logical.x, glyph.logical.y),
1015                        glyph.text.clone(),
1016                        halo.clone(),
1017                        glyph.angle,
1018                        (glyph.offset.0 + x, glyph.offset.1 + y),
1019                    ))?;
1020                }
1021            }
1022        }
1023    }
1024    for glyph in &label.glyphs {
1025        chart.plotting_area().draw(&RotatedText::new(
1026            (glyph.logical.x, glyph.logical.y),
1027            glyph.text.clone(),
1028            style.text.clone(),
1029            glyph.angle,
1030            glyph.offset,
1031        ))?;
1032    }
1033    Ok(())
1034}
1035fn automatic_distances(length: f64, width: f64, endpoint: f64) -> Vec<f64> {
1036    let start = endpoint + width * 0.5 + 5.0;
1037    let end = length - start;
1038    if end < start {
1039        return Vec::new();
1040    }
1041    (0..=16)
1042        .map(|i| start + (end - start) * f64::from(i) / 16.0)
1043        .collect()
1044}
1045fn repeated_distances(length: f64, width: f64, endpoint: f64, spacing: f64) -> Vec<f64> {
1046    let clearance = endpoint + width * 0.5 + 5.0;
1047    let usable = length - 2.0 * clearance;
1048    if usable < 0.0 {
1049        return Vec::new();
1050    }
1051    let count = (usable / spacing).floor() as usize + 1;
1052    if count == 1 {
1053        return vec![length * 0.5];
1054    }
1055    let actual = usable / (count - 1) as f64;
1056    (0..count).map(|i| clearance + i as f64 * actual).collect()
1057}
1058fn readable_angle(mut angle: f64) -> Option<(f64, bool)> {
1059    if !angle.is_finite() {
1060        return None;
1061    }
1062    while angle > PI {
1063        angle -= 2.0 * PI;
1064    }
1065    while angle <= -PI {
1066        angle += 2.0 * PI;
1067    }
1068    let mut reversed = false;
1069    if angle > FRAC_PI_2 {
1070        angle -= PI;
1071        reversed = true;
1072    } else if angle < -FRAC_PI_2 {
1073        angle += PI;
1074        reversed = true;
1075    }
1076    Some((angle, reversed))
1077}
1078fn angle_difference(left: f64, right: f64) -> f64 {
1079    let mut d = right - left;
1080    while d > PI {
1081        d -= 2.0 * PI;
1082    }
1083    while d < -PI {
1084        d += 2.0 * PI;
1085    }
1086    d
1087}
1088fn normal_offset(angle: f64, distance: f64) -> (i32, i32) {
1089    (
1090        (-angle.sin() * distance).round() as i32,
1091        (angle.cos() * distance).round() as i32,
1092    )
1093}
1094fn rotated_bounds(
1095    c: PixelPoint,
1096    width: f64,
1097    height: f64,
1098    angle: f64,
1099    offset: (i32, i32),
1100) -> Bounds {
1101    let hx = 0.5 * (width * angle.cos().abs() + height * angle.sin().abs());
1102    let hy = 0.5 * (width * angle.sin().abs() + height * angle.cos().abs());
1103    let x = c.x + f64::from(offset.0);
1104    let y = c.y + f64::from(offset.1);
1105    Bounds {
1106        x_min: x - hx,
1107        x_max: x + hx,
1108        y_min: y - hy,
1109        y_max: y + hy,
1110    }
1111}
1112fn mask_interval(distance: f64, width: f64, gap: f64, length: f64) -> (f64, f64) {
1113    let half = width * 0.5 + gap;
1114    ((distance - half).max(0.0), (distance + half).min(length))
1115}
1116fn viewport_pixel_bounds<DB: DrawingBackend>(chart: &TernaryChart<'_, DB>) -> Bounds {
1117    let v = chart.viewport();
1118    let corners = [
1119        (v.x_min(), v.y_min()),
1120        (v.x_min(), v.y_max()),
1121        (v.x_max(), v.y_min()),
1122        (v.x_max(), v.y_max()),
1123    ];
1124    let pixels = corners.map(|p| chart.plotting_area().map_coordinate(&p));
1125    Bounds {
1126        x_min: f64::from(pixels.iter().map(|p| p.0).min().unwrap_or(0)),
1127        x_max: f64::from(pixels.iter().map(|p| p.0).max().unwrap_or(0)),
1128        y_min: f64::from(pixels.iter().map(|p| p.1).min().unwrap_or(0)),
1129        y_max: f64::from(pixels.iter().map(|p| p.1).max().unwrap_or(0)),
1130    }
1131}
1132fn level_matches(a: f64, b: f64) -> bool {
1133    (a - b).abs() <= 1.0e-12 * a.abs().max(b.abs()).max(1.0)
1134}
1135#[derive(Clone, Copy)]
1136struct ColorBarLayout {
1137    anchor: TernaryCartesian,
1138    origin: (i32, i32),
1139    length: i32,
1140    thickness: i32,
1141}
1142fn color_bar_layout<DB: DrawingBackend>(
1143    chart: &TernaryChart<'_, DB>,
1144    bar: &ContourColorBar<'_>,
1145    scale: u32,
1146) -> ColorBarLayout {
1147    let v = chart.viewport();
1148    let (anchor, right, lower) = match bar.position {
1149        ContourColorBarPosition::UpperLeft => (
1150            TernaryCartesian {
1151                x: v.x_min(),
1152                y: v.y_max(),
1153            },
1154            false,
1155            false,
1156        ),
1157        ContourColorBarPosition::UpperRight => (
1158            TernaryCartesian {
1159                x: v.x_max(),
1160                y: v.y_max(),
1161            },
1162            true,
1163            false,
1164        ),
1165        ContourColorBarPosition::LowerLeft => (
1166            TernaryCartesian {
1167                x: v.x_min(),
1168                y: v.y_min(),
1169            },
1170            false,
1171            true,
1172        ),
1173        ContourColorBarPosition::LowerRight => (
1174            TernaryCartesian {
1175                x: v.x_max(),
1176                y: v.y_min(),
1177            },
1178            true,
1179            true,
1180        ),
1181    };
1182    let length = bar.length.saturating_mul(scale) as i32;
1183    let thickness = bar.thickness.saturating_mul(scale) as i32;
1184    let margin = bar.margin.saturating_mul(scale as i32);
1185    let (w, h) = match bar.orientation {
1186        ContourColorBarOrientation::Vertical => (thickness, length),
1187        ContourColorBarOrientation::Horizontal => (length, thickness),
1188    };
1189    ColorBarLayout {
1190        anchor,
1191        origin: (
1192            if right { -margin - w } else { margin },
1193            if lower { -margin - h } else { margin },
1194        ),
1195        length,
1196        thickness,
1197    }
1198}
1199fn scaled_shape(style: ShapeStyle, scale: u32) -> ShapeStyle {
1200    style.stroke_width(style.stroke_width.saturating_mul(scale))
1201}
1202#[cfg(test)]
1203mod tests {
1204    use super::*;
1205    fn straight_path(reverse: bool) -> ProjectedPath {
1206        let mut logical = vec![
1207            TernaryCartesian { x: 0.0, y: 0.0 },
1208            TernaryCartesian { x: 0.5, y: 0.0 },
1209            TernaryCartesian { x: 1.0, y: 0.0 },
1210        ];
1211        let mut pixels = vec![
1212            PixelPoint { x: 0.0, y: 50.0 },
1213            PixelPoint { x: 100.0, y: 50.0 },
1214            PixelPoint { x: 200.0, y: 50.0 },
1215        ];
1216        if reverse {
1217            logical.reverse();
1218            pixels.reverse();
1219        }
1220        ProjectedPath {
1221            logical,
1222            pixels,
1223            cumulative: vec![0.0, 100.0, 200.0],
1224        }
1225    }
1226    #[test]
1227    fn projected_arc_length_sampling_and_tangent_are_stable() {
1228        let path = straight_path(false);
1229        assert_eq!(path.length(), 200.0);
1230        let (logical, pixel) = path.sample(75.0).unwrap();
1231        assert!((logical.x - 0.375).abs() < 1.0e-12);
1232        assert_eq!(pixel, PixelPoint { x: 75.0, y: 50.0 });
1233        assert_eq!(path.tangent(75.0, 5.0), Some((0.0, false)));
1234    }
1235    #[test]
1236    fn upside_down_tangents_are_corrected() {
1237        let (angle, reversed) = readable_angle(PI).unwrap();
1238        assert!(angle.abs() < 1.0e-12);
1239        assert!(reversed);
1240        assert!(readable_angle(FRAC_PI_2 * 0.9).unwrap().0.abs() <= FRAC_PI_2);
1241    }
1242    #[test]
1243    fn curvature_endpoint_and_viewport_helpers_reject_bad_candidates() {
1244        let path = ProjectedPath {
1245            logical: vec![
1246                TernaryCartesian { x: 0.0, y: 0.0 },
1247                TernaryCartesian { x: 0.5, y: 0.5 },
1248                TernaryCartesian { x: 1.0, y: 0.0 },
1249            ],
1250            pixels: vec![
1251                PixelPoint { x: 0.0, y: 100.0 },
1252                PixelPoint { x: 100.0, y: 0.0 },
1253                PixelPoint { x: 200.0, y: 100.0 },
1254            ],
1255            cumulative: vec![0.0, 141.421356, 282.842712],
1256        };
1257        assert!(path.curvature_degrees(path.length() * 0.5, 50.0).unwrap() > 60.0);
1258        assert!(automatic_distances(60.0, 50.0, 20.0).is_empty());
1259        let inner = Bounds {
1260            x_min: 1.0,
1261            x_max: 9.0,
1262            y_min: 1.0,
1263            y_max: 9.0,
1264        };
1265        let outer = Bounds {
1266            x_min: 0.0,
1267            x_max: 10.0,
1268            y_min: 0.0,
1269            y_max: 10.0,
1270        };
1271        assert!(!inner.inside(outer, 2.0));
1272    }
1273    #[test]
1274    fn repeated_spacing_collision_and_masks_are_deterministic() {
1275        assert_eq!(
1276            repeated_distances(500.0, 80.0, 20.0, 150.0),
1277            vec![65.0, 250.0, 435.0]
1278        );
1279        assert_eq!(mask_interval(100.0, 60.0, 5.0, 200.0), (65.0, 135.0));
1280        let a = Bounds {
1281            x_min: 0.0,
1282            x_max: 10.0,
1283            y_min: 0.0,
1284            y_max: 10.0,
1285        };
1286        let b = Bounds {
1287            x_min: 9.0,
1288            x_max: 20.0,
1289            y_min: 0.0,
1290            y_max: 10.0,
1291        };
1292        assert!(a.overlaps(b));
1293    }
1294    #[test]
1295    fn manual_anchors_and_color_bars_validate() {
1296        let invalid = ContourLabelConfig::new().placement(ContourLabelPlacement::Manual(vec![
1297            ContourLabelAnchor::new(1.0, 0, 1.5),
1298        ]));
1299        assert!(invalid.validate().is_err());
1300        assert!(ContourColorBar::new(1.0, 1.0, |_| BLACK.to_rgba()).is_err());
1301        assert!(
1302            ContourColorBar::new(0.0, 1.0, |_| BLACK.to_rgba())
1303                .unwrap()
1304                .validate()
1305                .is_ok()
1306        );
1307    }
1308}