Skip to main content

ferrochart_core/drawing/
mod.rs

1//! Drawing tools.
2//!
3//! A drawing is a [`DrawingTool`]: anchors in data space ([`Anchor`]: time and
4//! price), a style, and code that turns them into frame primitives through a
5//! [`FrameBuilder`]. The [`DrawingManager`] (`Chart::drawings`) owns the
6//! drawings of a chart: it creates them from [`DrawingData`] through
7//! registered factories, keeps their z order, selection, visibility and lock
8//! state, and records changes as commands for undo/redo.
9//!
10//! Anchors are timestamps, not logical indices, so they survive `prepend` and
11//! axis rebuilds. Times outside the data are extrapolated with the spacing of
12//! the last (or first) two bars; times between two slots are interpolated.
13
14mod advanced;
15mod manager;
16mod tools;
17
18use core::fmt;
19
20use crate::data::{TimeIndex, Timestamp};
21use crate::format::NumberFormat;
22use crate::frame::{
23    DrawCmd, FontId, FontStyleRef, Frame, IconInst, LabelBg, LayerId, LineDash, LineInst, RectInst,
24    StrokeStyle, TextAlign, TextRun,
25};
26use crate::geom::{Css, PointPx, Px, RectPx, Rgba, Span};
27use crate::price_scale::{Normalize, PriceScale};
28use crate::text::{TextMeasurer, text_width};
29use crate::time_scale::TimeScale;
30
31pub(crate) use manager::LocalChange;
32pub use manager::{DrawingFactory, DrawingManager};
33/// Kinds of the built-in tools: the first batch, then the second. Long and short positions, the three pitchforks and the two Elliott
34/// waves are one tool each with several kinds.
35pub const BUILTIN_KINDS: [&str; 29] = [
36    "trend_line",
37    "ray",
38    "extended_line",
39    "horizontal_line",
40    "horizontal_ray",
41    "vertical_line",
42    "parallel_channel",
43    "rectangle",
44    "ellipse",
45    "text",
46    "price_range",
47    "date_range",
48    "fib_retracement",
49    "fib_extension",
50    "long_position",
51    "short_position",
52    "pitchfork",
53    "schiff_pitchfork",
54    "modified_schiff_pitchfork",
55    "gann_fan",
56    "fib_time_zones",
57    "xabcd_pattern",
58    "head_and_shoulders",
59    "elliott_impulse",
60    "elliott_correction",
61    "path",
62    "brush",
63    "arrow",
64    "callout",
65];
66
67/// Factory of the built-in kinds.
68pub(crate) fn builtin(data: &DrawingData) -> crate::error::Result<Box<dyn DrawingTool>> {
69    if advanced::SECOND_KINDS.contains(&data.kind.as_str()) {
70        advanced::build(data)
71    } else {
72        tools::builtin(data)
73    }
74}
75
76/// Spacing used to extrapolate times when the axis has a single slot (ms).
77const DEFAULT_STEP_MS: f64 = 60_000.0;
78/// Hit tolerance around lines (CSS px).
79pub(crate) const HIT_CSS: f32 = 4.0;
80
81/// Most anchors of an `Open` or `Freehand` drawing.
82pub const MAX_ANCHORS: usize = 4096;
83
84/// Distance (CSS px) the pointer moves before a freehand drawing gets its
85/// next anchor.
86pub(crate) const FREEHAND_STEP_CSS: f32 = 3.0;
87
88/// How a drawing is created.
89///
90/// # Examples
91///
92/// ```
93/// use ferrochart_core::drawing::AnchorCount;
94///
95/// assert_eq!(AnchorCount::Fixed(3).min(), 3);
96/// assert_eq!(AnchorCount::Open { min: 2 }.min(), 2);
97/// assert_eq!(AnchorCount::Freehand.min(), 2);
98/// ```
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum AnchorCount {
102    /// One click per anchor, `n` clicks (tools with more anchors add them in
103    /// [`DrawingTool::finish`]).
104    Fixed(usize),
105    /// One click per anchor until a double click or Enter, at least `min`
106    /// anchors (e.g. a path).
107    Open {
108        /// Fewest anchors.
109        min: usize,
110    },
111    /// Press, drag and release: an anchor every 3 CSS px of movement (e.g. a
112    /// brush), at least 2.
113    Freehand,
114}
115
116impl AnchorCount {
117    /// Fewest anchors a drawing of this kind has.
118    pub fn min(self) -> usize {
119        match self {
120            Self::Fixed(n) | Self::Open { min: n } => n,
121            Self::Freehand => 2,
122        }
123    }
124
125    /// Most anchors (`Fixed`: the clicks; tools may add more in `finish`).
126    pub(crate) fn max(self) -> usize {
127        match self {
128            Self::Fixed(n) => n,
129            Self::Open { .. } | Self::Freehand => MAX_ANCHORS,
130        }
131    }
132}
133
134/// A point of a drawing in data space.
135#[derive(Clone, Copy, Debug, PartialEq)]
136#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
137pub struct Anchor {
138    /// Time (UTC milliseconds); need not be a bar time.
139    pub time: Timestamp,
140    /// Price, in the units of the pane's first price series.
141    pub price: f64,
142}
143
144/// Colors and line settings of a drawing.
145#[derive(Clone, Copy, Debug, PartialEq)]
146#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
147pub struct DrawingStyle {
148    /// Line color.
149    pub line: Rgba,
150    /// Line width.
151    pub line_width: Css,
152    /// Line dash pattern.
153    pub line_dash: LineDash,
154    /// Fill color of areas; alpha 0 draws no fill.
155    pub fill: Rgba,
156    /// Text color.
157    pub text: Rgba,
158    /// Font size of texts and labels.
159    pub font_size: Css,
160}
161
162impl Default for DrawingStyle {
163    fn default() -> Self {
164        let blue = Rgba::hex(0x0029_62FF);
165        Self {
166            line: blue,
167            line_width: Css(1.0),
168            line_dash: LineDash::Solid,
169            fill: blue.with_alpha(40),
170            text: blue,
171            font_size: Css(12.0),
172        }
173    }
174}
175
176/// A tool-specific parameter of a drawing.
177#[derive(Clone, Debug, PartialEq)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
179pub enum Param {
180    /// A number.
181    Number(f64),
182    /// A flag.
183    Bool(bool),
184    /// A text.
185    Text(String),
186    /// A list of numbers (e.g. Fibonacci levels).
187    Numbers(Vec<f64>),
188}
189
190/// Format-independent saved form of a drawing: what
191/// [`DrawingTool::save`] returns and what factories build drawings from.
192///
193/// # Examples
194///
195/// ```
196/// use ferrochart_core::drawing::{Anchor, DrawingData, Param};
197///
198/// let mut data = DrawingData::new("text", vec![Anchor { time: 0, price: 10.0 }]);
199/// data.set("text", Param::Text("breakout".into()));
200/// assert_eq!(data.text("text"), Some("breakout"));
201/// ```
202#[derive(Clone, Debug, PartialEq)]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
204pub struct DrawingData {
205    /// Tool kind, e.g. `"trend_line"` (see [`BUILTIN_KINDS`]).
206    pub kind: String,
207    /// Anchors.
208    pub anchors: Vec<Anchor>,
209    /// Style.
210    pub style: DrawingStyle,
211    /// Tool-specific parameters, by key.
212    pub params: Vec<(String, Param)>,
213}
214
215impl DrawingData {
216    /// A drawing of `kind` with the default style and no parameters.
217    pub fn new(kind: &str, anchors: Vec<Anchor>) -> Self {
218        Self {
219            kind: kind.into(),
220            anchors,
221            style: DrawingStyle::default(),
222            params: Vec::new(),
223        }
224    }
225
226    /// The parameter `key`.
227    pub fn param(&self, key: &str) -> Option<&Param> {
228        self.params.iter().find(|(k, _)| k == key).map(|(_, v)| v)
229    }
230
231    /// Sets the parameter `key`.
232    pub fn set(&mut self, key: &str, value: Param) {
233        match self.params.iter_mut().find(|(k, _)| k == key) {
234            Some((_, v)) => *v = value,
235            None => self.params.push((key.into(), value)),
236        }
237    }
238
239    /// The number parameter `key`.
240    pub fn number(&self, key: &str) -> Option<f64> {
241        match self.param(key)? {
242            Param::Number(x) => Some(*x),
243            _ => None,
244        }
245    }
246
247    /// The text parameter `key`.
248    pub fn text(&self, key: &str) -> Option<&str> {
249        match self.param(key)? {
250            Param::Text(s) => Some(s),
251            _ => None,
252        }
253    }
254
255    /// The number-list parameter `key`.
256    pub fn numbers(&self, key: &str) -> Option<&[f64]> {
257        match self.param(key)? {
258            Param::Numbers(v) => Some(v),
259            _ => None,
260        }
261    }
262}
263
264/// What part of a drawing a point hits.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum HitPart {
267    /// Handle `n` of [`DrawingTool::handles`].
268    Handle(usize),
269    /// The drawing itself.
270    Body,
271}
272
273/// A drawing tool. Built-in tools are listed in
274/// [`BUILTIN_KINDS`]; custom tools are registered with
275/// [`DrawingManager::register`].
276///
277/// `build` runs for every frame and must not allocate (it only writes into
278/// the frame's pools through `out`).
279pub trait DrawingTool: Send {
280    /// Kind, e.g. `"trend_line"`.
281    fn kind(&self) -> &'static str;
282    /// Anchors.
283    fn anchors(&self) -> &[Anchor];
284    /// Anchors, for moving the drawing.
285    fn anchors_mut(&mut self) -> &mut Vec<Anchor>;
286    /// How the drawing is created.
287    fn anchor_count(&self) -> AnchorCount;
288    /// Draws the drawing.
289    fn build(&self, ctx: &DrawingCtx<'_>, out: &mut FrameBuilder<'_>);
290    /// What `p` hits, if anything (within [`DrawingCtx::hit_tolerance`] of
291    /// lines).
292    fn hit_test(&self, ctx: &DrawingCtx<'_>, p: PointPx) -> Option<HitPart>;
293    /// Handles of the selected drawing, written into `out` (empty on entry;
294    /// core reuses it, so any number of handles does not allocate). Handle
295    /// `k` is dragged with [`move_handle`](Self::move_handle)`(k, …)`.
296    fn handles(&self, ctx: &DrawingCtx<'_>, out: &mut Vec<PointPx>);
297    /// Style.
298    fn style(&self) -> &DrawingStyle;
299    /// Saved form; a factory given it builds an equal drawing.
300    fn save(&self) -> DrawingData;
301    /// Drags handle `handle` to `to`. The default moves anchor `handle`.
302    fn move_handle(&mut self, handle: usize, to: Anchor) {
303        if let Some(a) = self.anchors_mut().get_mut(handle) {
304            *a = to;
305        }
306    }
307    /// Called once the drawing is created (after the last click, or by
308    /// `DrawingManager::add`): tools with more anchors than clicks add the
309    /// others here.
310    fn finish(&mut self) {}
311}
312
313/// Coordinate conversions and measurements for [`DrawingTool`]s of one pane.
314pub struct DrawingCtx<'a> {
315    pub(crate) index: &'a TimeIndex,
316    pub(crate) time_scale: &'a TimeScale,
317    pub(crate) price_scale: &'a PriceScale,
318    pub(crate) norm: Normalize,
319    pub(crate) plot: RectPx,
320    pub(crate) dpr: f32,
321    pub(crate) labels: NumberFormat,
322    pub(crate) text: &'a dyn TextMeasurer,
323}
324
325impl DrawingCtx<'_> {
326    /// The pane's plot rectangle.
327    pub fn plot(&self) -> RectPx {
328        self.plot
329    }
330
331    /// Device pixel ratio.
332    pub fn dpr(&self) -> f32 {
333        self.dpr
334    }
335
336    /// `v` in physical pixels.
337    pub fn px(&self, v: Css) -> Px {
338        v.to_px(self.dpr)
339    }
340
341    /// Distance within which a point hits a line.
342    pub fn hit_tolerance(&self) -> f32 {
343        HIT_CSS * self.dpr
344    }
345
346    /// Width of one bar.
347    pub fn bar_spacing(&self) -> Px {
348        Px(self.time_scale.bar_spacing() as f32)
349    }
350
351    /// Logical index of `time`, fractional between slots and extrapolated
352    /// outside the data; `None` without data.
353    pub fn index_of_time(&self, time: Timestamp) -> Option<f64> {
354        index_of_time(self.index, time)
355    }
356
357    /// x of the fractional logical index `i`.
358    pub(crate) fn x_of_index(&self, i: f64) -> Option<f32> {
359        let x = f64::from(self.plot.x) + self.time_scale.index_to_x_f64(i);
360        x.is_finite().then_some(x.clamp(-1e7, 1e7) as f32)
361    }
362
363    /// x of `time`.
364    pub fn x_of(&self, time: Timestamp) -> Option<f32> {
365        let i = self.index_of_time(time)?;
366        let x = f64::from(self.plot.x) + self.time_scale.index_to_x_f64(i);
367        x.is_finite().then_some(x as f32)
368    }
369
370    /// y of `price`; `None` if it has none (e.g. ≤ 0 on a log scale).
371    pub fn y_of(&self, price: f64) -> Option<f32> {
372        let (top, h) = (f64::from(self.plot.y), f64::from(self.plot.h));
373        let y = self.price_scale.price_to_y(self.norm.apply(price), top, h);
374        // Keep far-away points finite for f32 geometry.
375        y.is_finite().then_some(y.clamp(-1e7, 1e7) as f32)
376    }
377
378    /// Price at `y`.
379    pub fn price_at(&self, y: f32) -> f64 {
380        let (top, h) = (f64::from(self.plot.y), f64::from(self.plot.h));
381        self.norm
382            .invert(self.price_scale.y_to_price(f64::from(y), top, h))
383    }
384
385    /// Time at `x`: interpolated between slots, extrapolated beyond the
386    /// data (the inverse of [`x_of`](Self::x_of), rounded to the
387    /// millisecond); `None` without data.
388    ///
389    /// # Examples
390    ///
391    /// ```
392    /// use std::sync::atomic::{AtomicI64, Ordering};
393    ///
394    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
395    /// use ferrochart_core::data::ValueColumns;
396    /// use ferrochart_core::drawing::FrameBuilder;
397    /// use ferrochart_core::frame::SeriesKind;
398    /// use ferrochart_core::geom::SizeCss;
399    /// use ferrochart_core::plugin::{LayerCtx, LayerPlugin, LayerPosition};
400    /// use ferrochart_core::testing::MonoMeasurer;
401    /// use ferrochart_core::{Chart, ChartOptions};
402    ///
403    /// static TIME: AtomicI64 = AtomicI64::new(0);
404    ///
405    /// struct Probe;
406    ///
407    /// impl LayerPlugin for Probe {
408    ///     fn position(&self) -> LayerPosition {
409    ///         LayerPosition::Overlay
410    ///     }
411    ///     fn build(&self, ctx: &LayerCtx<'_>, _: &mut FrameBuilder<'_>) {
412    ///         let Some(c) = ctx.coords() else { return };
413    ///         // Half way between the bars at 60 s and 120 s.
414    ///         if let Some(t) = c.x_of(90_000).and_then(|x| c.time_at(x)) {
415    ///             TIME.store(t, Ordering::Relaxed);
416    ///         }
417    ///     }
418    /// }
419    ///
420    /// let mut chart = Chart::new(ChartOptions::default());
421    /// chart.resize(SizeCss { w: 800.0, h: 400.0 }, 1.0);
422    /// let pane = chart.main_pane();
423    /// let line = chart.add_series(pane, SeriesKind::Line, SeriesOptions::default())?;
424    /// chart.set_data(line, SeriesData::Value(ValueColumns {
425    ///     time: (0..10).map(|i| i * 60_000).collect(),
426    ///     value: vec![1.0; 10],
427    ///     color: None,
428    /// }))?;
429    /// chart.add_layer(Some(pane), Box::new(Probe))?;
430    /// chart.build_frame(0.0, &MonoMeasurer);
431    /// assert_eq!(TIME.load(Ordering::Relaxed), 90_000);
432    /// # Ok::<(), ferrochart_core::Error>(())
433    /// ```
434    pub fn time_at(&self, x: f32) -> Option<Timestamp> {
435        let i = self.time_scale.x_to_index(Px(x - self.plot.x));
436        time_of_index(self.index, i)
437    }
438
439    /// Screen position of `a`.
440    pub fn point(&self, a: Anchor) -> Option<PointPx> {
441        Some(PointPx {
442            x: self.x_of(a.time)?.clamp(-1e7, 1e7),
443            y: self.y_of(a.price)?,
444        })
445    }
446
447    /// Stroke of `style`'s lines (whole pixels, at least 1).
448    pub fn stroke(&self, style: &DrawingStyle) -> StrokeStyle {
449        StrokeStyle {
450            width: Px(style.line_width.to_px(self.dpr).0.round().max(1.0)),
451            color: style.line,
452            dash: style.line_dash,
453        }
454    }
455
456    /// Font of `size`.
457    pub fn font(&self, size: Css) -> FontStyleRef {
458        FontStyleRef {
459            font: FontId(0),
460            size: size.to_px(self.dpr).0,
461        }
462    }
463
464    /// Width of `text`.
465    pub fn text_width(&self, text: &str, font: FontStyleRef) -> f32 {
466        text_width(self.text, text, font)
467    }
468
469    /// Line height of `font`.
470    pub fn line_height(&self, font: FontStyleRef) -> f32 {
471        self.text.line_height(font)
472    }
473
474    /// Writes `price` with the pane's precision.
475    pub fn write_price(&self, out: &mut impl fmt::Write, price: f64) {
476        match self.labels {
477            f @ (NumberFormat::Fixed(_) | NumberFormat::Auto(_)) => f,
478            NumberFormat::Percent(_) | NumberFormat::Compact => NumberFormat::Fixed(2),
479        }
480        .write(out, price);
481    }
482}
483
484/// Writes the primitives of a drawing into the frame (main layer, clipped to
485/// the pane by the caller).
486pub struct FrameBuilder<'a> {
487    pub(crate) frame: &'a mut Frame,
488    pub(crate) layer: LayerId,
489}
490
491impl<'a> FrameBuilder<'a> {
492    /// A builder writing into `layer` of `frame`, for code that builds
493    /// frames outside a [`Chart`](crate::Chart) (`ferrochart-plot`).
494    ///
495    /// ```
496    /// use ferrochart_core::drawing::FrameBuilder;
497    /// use ferrochart_core::frame::{Frame, LayerId, StrokeStyle};
498    /// use ferrochart_core::geom::{PointPx, Px, Rgba};
499    ///
500    /// let mut frame = Frame::default();
501    /// let mut b = FrameBuilder::new(&mut frame, LayerId::Main);
502    /// let stroke = StrokeStyle { color: Rgba::hex(0xFFFF_FFFF), width: Px(1.0), dash: Default::default() };
503    /// b.line(PointPx { x: 0.0, y: 0.0 }, PointPx { x: 10.0, y: 0.0 }, stroke);
504    /// assert_eq!(frame.pools.lines.len(), 1);
505    /// ```
506    pub fn new(frame: &'a mut Frame, layer: LayerId) -> Self {
507        Self { frame, layer }
508    }
509
510    /// A line segment.
511    pub fn line(&mut self, from: PointPx, to: PointPx, stroke: StrokeStyle) {
512        self.frame
513            .push_line(self.layer, LineInst { from, to, stroke });
514    }
515
516    fn points(&mut self, pts: impl IntoIterator<Item = PointPx>) -> Span {
517        let start = self.frame.pools.points.len();
518        self.frame.pools.points.extend(pts);
519        let len = self.frame.pools.points.len() - start;
520        Span {
521            start: u32::try_from(start).unwrap_or(u32::MAX),
522            len: u32::try_from(len).unwrap_or(0),
523        }
524    }
525
526    /// A polyline through `pts`.
527    pub fn polyline(&mut self, pts: impl IntoIterator<Item = PointPx>, style: StrokeStyle) {
528        let points = self.points(pts);
529        if points.len >= 2 {
530            self.frame
531                .push_cmd(self.layer, DrawCmd::Polyline { points, style });
532        }
533    }
534
535    /// A filled polygon with vertices `pts`.
536    pub fn polygon(&mut self, pts: impl IntoIterator<Item = PointPx>, fill: Rgba) {
537        let points = self.points(pts);
538        if points.len >= 3 && fill.a > 0 {
539            self.frame
540                .push_cmd(self.layer, DrawCmd::Polygon { points, fill });
541        }
542    }
543
544    /// A filled axis-aligned rectangle.
545    pub fn rect(&mut self, rect: RectPx, color: Rgba) {
546        if color.a > 0 && rect.w > 0.0 && rect.h > 0.0 {
547            self.frame.push_rect(self.layer, RectInst { rect, color });
548        }
549    }
550
551    /// A line of text; `pos.y` is its vertical center.
552    pub fn text(&mut self, pos: PointPx, text: &str, label: Label) {
553        let span = self.frame.push_str(text);
554        self.push_run(pos, span, label);
555    }
556
557    /// A line of formatted text, written straight into the frame's text pool.
558    pub fn text_fmt(&mut self, pos: PointPx, args: fmt::Arguments<'_>, label: Label) {
559        let start = self.frame.pools.text.len();
560        let _ = fmt::Write::write_fmt(&mut self.frame.pools.text, args);
561        let len = self.frame.pools.text.len() - start;
562        let span = Span {
563            start: u32::try_from(start).unwrap_or(u32::MAX),
564            len: u32::try_from(len).unwrap_or(0),
565        };
566        self.push_run(pos, span, label);
567    }
568
569    fn push_run(&mut self, pos: PointPx, text: Span, label: Label) {
570        self.frame.push_text(
571            self.layer,
572            TextRun {
573                pos,
574                text,
575                style: label.font,
576                color: label.color,
577                align: label.align,
578                bg: label.bg,
579            },
580        );
581    }
582
583    /// An icon from the built-in set (`transform_helpers::ICON_*`).
584    pub fn icon(&mut self, icon: IconInst) {
585        self.frame.push_icon(self.layer, icon);
586    }
587}
588
589/// How [`FrameBuilder::text`] draws a text.
590#[derive(Clone, Copy, Debug, PartialEq)]
591pub struct Label {
592    /// Font.
593    pub font: FontStyleRef,
594    /// Text color.
595    pub color: Rgba,
596    /// Alignment relative to `pos.x`.
597    pub align: TextAlign,
598    /// Optional background box.
599    pub bg: Option<LabelBg>,
600}
601
602/// Distance from `p` to the segment `a`–`b`.
603///
604/// # Examples
605///
606/// ```
607/// use ferrochart_core::drawing::distance_to_segment;
608/// use ferrochart_core::geom::PointPx;
609///
610/// let (a, b) = (PointPx { x: 0.0, y: 0.0 }, PointPx { x: 10.0, y: 0.0 });
611/// assert_eq!(distance_to_segment(PointPx { x: 5.0, y: 3.0 }, a, b), 3.0);
612/// assert_eq!(distance_to_segment(PointPx { x: 13.0, y: 4.0 }, a, b), 5.0);
613/// ```
614pub fn distance_to_segment(p: PointPx, a: PointPx, b: PointPx) -> f32 {
615    let (dx, dy) = (b.x - a.x, b.y - a.y);
616    let len2 = dx * dx + dy * dy;
617    let t = if len2 > 0.0 {
618        (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0)
619    } else {
620        0.0
621    };
622    (p.x - (a.x + t * dx)).hypot(p.y - (a.y + t * dy))
623}
624
625/// The part of the line through `a` and `b` inside `rect`: from `a` (or from
626/// the edge if `back`) to `b` (or to the edge if `forward`). `None` if it
627/// misses the rectangle.
628///
629/// # Examples
630///
631/// ```
632/// use ferrochart_core::drawing::clip_line;
633/// use ferrochart_core::geom::{PointPx, RectPx};
634///
635/// let r = RectPx { x: 0.0, y: 0.0, w: 100.0, h: 100.0 };
636/// let (a, b) = (PointPx { x: 10.0, y: 50.0 }, PointPx { x: 20.0, y: 50.0 });
637/// let (p, q) = clip_line(a, b, r, false, true).unwrap();
638/// assert_eq!((p.x, q.x), (10.0, 100.0));
639/// ```
640pub fn clip_line(
641    a: PointPx,
642    b: PointPx,
643    rect: RectPx,
644    back: bool,
645    forward: bool,
646) -> Option<(PointPx, PointPx)> {
647    let (dx, dy) = (b.x - a.x, b.y - a.y);
648    if dx == 0.0 && dy == 0.0 {
649        return Some((a, b));
650    }
651    let mut t0 = if back { f32::NEG_INFINITY } else { 0.0 };
652    let mut t1 = if forward { f32::INFINITY } else { 1.0 };
653    // Liang–Barsky.
654    for (p, q) in [
655        (-dx, a.x - rect.x),
656        (dx, rect.right() - a.x),
657        (-dy, a.y - rect.y),
658        (dy, rect.bottom() - a.y),
659    ] {
660        if p == 0.0 {
661            if q < 0.0 {
662                return None;
663            }
664            continue;
665        }
666        let r = q / p;
667        if p < 0.0 {
668            t0 = t0.max(r);
669        } else {
670            t1 = t1.min(r);
671        }
672    }
673    if t0 > t1 || !t0.is_finite() || !t1.is_finite() {
674        return None;
675    }
676    let at = |t: f32| PointPx {
677        x: a.x + t * dx,
678        y: a.y + t * dy,
679    };
680    Some((at(t0), at(t1)))
681}
682
683/// Whether `p` is inside the polygon `pts` (even-odd rule).
684pub fn point_in_polygon(p: PointPx, pts: &[PointPx]) -> bool {
685    let mut inside = false;
686    let mut j = pts.len().wrapping_sub(1);
687    for (i, a) in pts.iter().enumerate() {
688        let Some(b) = pts.get(j) else {
689            return false;
690        };
691        if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
692            inside = !inside;
693        }
694        j = i;
695    }
696    inside
697}
698
699/// Spacing of the slots after the last one (`at_end`) or before the first.
700fn step(index: &TimeIndex, at_end: bool) -> f64 {
701    let (first, end) = (index.first_index(), index.end_index());
702    let pair = if at_end {
703        (index.time_at(end - 2), index.time_at(end - 1))
704    } else {
705        (index.time_at(first), index.time_at(first + 1))
706    };
707    match pair {
708        (Some(a), Some(b)) if b > a => (b - a) as f64,
709        _ => DEFAULT_STEP_MS,
710    }
711}
712
713/// Logical index of `time`: exact on slots, interpolated between them,
714/// extrapolated outside.
715pub(crate) fn index_of_time(index: &TimeIndex, time: Timestamp) -> Option<f64> {
716    if index.is_empty() {
717        return None;
718    }
719    let (first, last) = (index.first_index(), index.end_index() - 1);
720    let (t0, t1) = (index.time_at(first)?, index.time_at(last)?);
721    if time > t1 {
722        return Some(last as f64 + (time - t1) as f64 / step(index, true));
723    }
724    if time < t0 {
725        return Some(first as f64 - (t0 - time) as f64 / step(index, false));
726    }
727    let j = index.lower_bound(time);
728    let tj = index.time_at(j)?;
729    if tj == time {
730        return Some(j as f64);
731    }
732    let tp = index.time_at(j - 1)?;
733    Some((j - 1) as f64 + (time - tp) as f64 / (tj - tp) as f64)
734}
735
736/// Time of the fractional logical index `i` (inverse of [`index_of_time`]).
737pub(crate) fn time_of_index(index: &TimeIndex, i: f64) -> Option<Timestamp> {
738    if index.is_empty() || !i.is_finite() {
739        return None;
740    }
741    let (first, last) = (index.first_index(), index.end_index() - 1);
742    let (t0, t1) = (index.time_at(first)?, index.time_at(last)?);
743    let t = if i >= last as f64 {
744        t1 as f64 + (i - last as f64) * step(index, true)
745    } else if i <= first as f64 {
746        t0 as f64 - (first as f64 - i) * step(index, false)
747    } else {
748        let j = i.floor() as i64;
749        let (a, b) = (index.time_at(j)?, index.time_at(j + 1)?);
750        a as f64 + (i - j as f64) * (b - a) as f64
751    };
752    Some(t.round().clamp(-9.0e18, 9.0e18) as i64)
753}
754
755/// Pixel center of a 1-px (odd width) line at `v`.
756pub(crate) fn crisp(v: f32, width: Px) -> f32 {
757    if (width.0 as i32) % 2 == 1 {
758        v.floor() + 0.5
759    } else {
760        v.round()
761    }
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    #[test]
769    fn times_map_to_indices_and_back() {
770        let index = TimeIndex::from_times(vec![100, 200, 400]).unwrap_or_default();
771        assert_eq!(index_of_time(&index, 200), Some(1.0));
772        assert_eq!(index_of_time(&index, 300), Some(1.5));
773        // Extrapolated with the last spacing (200) and the first one (100).
774        assert_eq!(index_of_time(&index, 800), Some(4.0));
775        assert_eq!(index_of_time(&index, 0), Some(-1.0));
776        for i in [-3.0, -0.5, 0.0, 1.25, 2.0, 7.0] {
777            let t = time_of_index(&index, i).unwrap_or_default();
778            let back = index_of_time(&index, t).unwrap_or_default();
779            assert!((back - i).abs() < 1e-9, "{i} -> {t} -> {back}");
780        }
781        assert_eq!(index_of_time(&TimeIndex::default(), 5), None);
782    }
783
784    #[test]
785    fn lines_are_clipped_to_the_plot() {
786        let r = RectPx {
787            x: 0.0,
788            y: 0.0,
789            w: 100.0,
790            h: 50.0,
791        };
792        let (a, b) = (PointPx { x: 10.0, y: 10.0 }, PointPx { x: 20.0, y: 20.0 });
793        let (p, q) = clip_line(a, b, r, true, true).unwrap_or((a, a));
794        assert_eq!(
795            (p, q),
796            (PointPx { x: 0.0, y: 0.0 }, PointPx { x: 50.0, y: 50.0 })
797        );
798        assert_eq!(clip_line(a, b, r, false, false), Some((a, b)));
799        let outside = PointPx { x: 200.0, y: 10.0 };
800        assert_eq!(
801            clip_line(outside, PointPx { x: 300.0, y: 10.0 }, r, false, true),
802            None
803        );
804    }
805
806    #[test]
807    fn polygons_contain_points() {
808        let sq = [
809            PointPx { x: 0.0, y: 0.0 },
810            PointPx { x: 10.0, y: 0.0 },
811            PointPx { x: 10.0, y: 10.0 },
812            PointPx { x: 0.0, y: 10.0 },
813        ];
814        assert!(point_in_polygon(PointPx { x: 5.0, y: 5.0 }, &sq));
815        assert!(!point_in_polygon(PointPx { x: 15.0, y: 5.0 }, &sq));
816        assert!(!point_in_polygon(PointPx { x: 5.0, y: 5.0 }, &[]));
817    }
818}