use egui::{Pos2, Rect, pos2};
use super::axis::{Bounds, Scale};
pub(super) use crisol_plot_core::transform::{SecondAxis, YAxis};
#[derive(Clone, Copy, Debug)]
pub(super) struct Transform {
pub frame: Rect,
pub view: Bounds,
pub x_scale: Scale,
pub y_scale: Scale,
pub y2: Option<SecondAxis>,
}
impl Transform {
pub fn for_axis(self, axis: YAxis) -> Self {
match (axis, self.y2) {
(YAxis::Right, Some(y2)) => Self {
view: Bounds {
min_y: y2.min,
max_y: y2.max,
..self.view
},
y_scale: y2.scale,
..self
},
_ => self,
}
}
pub fn to_screen(self, point: [f64; 2]) -> Pos2 {
let x = self.x_scale.forward(point[0]);
let y = self.y_scale.forward(point[1]);
self.scaled_to_screen(x, y)
}
pub fn scaled_to_screen(&self, x: f64, y: f64) -> Pos2 {
let tx = (x - self.view.min_x) / self.view.width();
let ty = (y - self.view.min_y) / self.view.height();
pos2(
self.frame.left() + (tx * f64::from(self.frame.width())) as f32,
self.frame.bottom() - (ty * f64::from(self.frame.height())) as f32,
)
}
pub fn to_scaled(self, pos: Pos2) -> [f64; 2] {
let tx = f64::from((pos.x - self.frame.left()) / self.frame.width());
let ty = f64::from((self.frame.bottom() - pos.y) / self.frame.height());
[
self.view.min_x + tx * self.view.width(),
self.view.min_y + ty * self.view.height(),
]
}
pub fn to_data(self, pos: Pos2) -> [f64; 2] {
let [x, y] = self.to_scaled(pos);
[self.x_scale.inverse(x), self.y_scale.inverse(y)]
}
pub fn units_per_point(&self) -> [f64; 2] {
[
self.view.width() / f64::from(self.frame.width().max(1.0)),
self.view.height() / f64::from(self.frame.height().max(1.0)),
]
}
}