1use egui::{Pos2, Rect, pos2};
4
5use super::config::Plot3DConfig;
6use super::types::Bounds3D;
7
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Projection {
14 #[default]
16 Perspective,
17 Orthographic,
19}
20
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct Camera3D {
25 pub yaw: f32,
27 pub pitch: f32,
29 pub distance: f64,
31 pub target: [f64; 3],
33 pub fov: f32,
35 pub projection: Projection,
37}
38
39impl Default for Camera3D {
40 fn default() -> Self {
41 Self {
42 yaw: -0.72,
43 pitch: 0.42,
44 distance: 3.2,
45 target: [0.0; 3],
46 fov: 45.0,
47 projection: Projection::Perspective,
48 }
49 }
50}
51
52impl Camera3D {
53 pub(super) fn auto(bounds: Bounds3D, config: &Plot3DConfig, frame: Rect) -> Self {
55 let center = bounds.center();
56 let radius = corners(bounds)
57 .iter()
58 .map(|corner| {
59 let delta = [corner[0] - center[0], corner[1] - center[1], corner[2] - center[2]];
60 delta.iter().map(|value| value * value).sum::<f64>().sqrt()
61 })
62 .fold(0.0, f64::max)
63 .max(0.001);
64 let fov_degrees = if config.fov.is_finite() {
65 config.fov.clamp(15.0, 120.0)
66 } else {
67 45.0
68 };
69 let fov = f64::from(fov_degrees).to_radians();
70 let aspect = (frame.width() / frame.height().max(1.0)).max(0.05) as f64;
72 let wider = if aspect < 1.0 { radius / aspect } else { radius };
73 let distance = (wider / (fov * 0.5).tan() * 1.45).max(radius * 1.2);
74 Self {
75 yaw: if config.yaw.is_finite() {
76 config.yaw
77 } else {
78 Self::default().yaw
79 },
80 pitch: if config.pitch.is_finite() {
81 config.pitch.clamp(-1.5, 1.5)
82 } else {
83 Self::default().pitch
84 },
85 distance,
86 target: center,
87 fov: fov_degrees,
88 projection: config.projection,
89 }
90 }
91
92 pub fn orbit(self, delta: egui::Vec2) -> Self {
94 Self {
95 yaw: self.yaw - delta.x * 0.01,
96 pitch: (self.pitch + delta.y * 0.008).clamp(-1.5, 1.5),
97 ..self
98 }
99 }
100
101 pub fn zoom(self, factor: f64) -> Self {
103 Self {
104 distance: (self.distance / factor.clamp(0.05, 20.0)).clamp(1e-5, 1e12),
105 ..self
106 }
107 }
108
109 pub fn pan(self, delta: egui::Vec2, frame: Rect) -> Self {
111 let (right, up) = basis(self.yaw, self.pitch);
112 let units =
113 2.0 * self.distance * (f64::from(self.fov).to_radians() * 0.5).tan() / f64::from(frame.height().max(1.0));
114 let target = [
115 self.target[0] - right[0] * f64::from(delta.x) * units + up[0] * f64::from(delta.y) * units,
116 self.target[1] - right[1] * f64::from(delta.x) * units + up[1] * f64::from(delta.y) * units,
117 self.target[2] - right[2] * f64::from(delta.x) * units + up[2] * f64::from(delta.y) * units,
118 ];
119 Self { target, ..self }
120 }
121}
122
123#[derive(Clone, Copy, Debug)]
125pub(super) struct Projector {
126 frame: Rect,
127 eye: [f64; 3],
128 right: [f64; 3],
129 up: [f64; 3],
130 forward: [f64; 3],
131 focal: f64,
132 distance: f64,
133 projection: Projection,
134}
135
136impl Projector {
137 pub fn new(camera: Camera3D, frame: Rect) -> Self {
138 let (right, up) = basis(camera.yaw, camera.pitch);
139 let cp = f64::from(camera.pitch).cos();
140 let eye = [
141 camera.target[0] + camera.distance * cp * f64::from(camera.yaw).cos(),
142 camera.target[1] + camera.distance * cp * f64::from(camera.yaw).sin(),
143 camera.target[2] + camera.distance * f64::from(camera.pitch).sin(),
144 ];
145 let forward = normalize([
146 camera.target[0] - eye[0],
147 camera.target[1] - eye[1],
148 camera.target[2] - eye[2],
149 ]);
150 Self {
151 frame,
152 eye,
153 right,
154 up,
155 forward,
156 focal: 0.5 * f64::from(frame.height().max(1.0))
157 / (f64::from(if camera.fov.is_finite() {
158 camera.fov.clamp(15.0, 120.0)
159 } else {
160 45.0
161 })
162 .to_radians()
163 * 0.5)
164 .tan(),
165 distance: camera.distance.max(1e-6),
166 projection: camera.projection,
167 }
168 }
169
170 pub fn project(&self, point: [f64; 3]) -> Option<(Pos2, f64)> {
171 let rel = [point[0] - self.eye[0], point[1] - self.eye[1], point[2] - self.eye[2]];
172 let x = dot(rel, self.right);
173 let y = dot(rel, self.up);
174 let z = dot(rel, self.forward);
175 let scale = match self.projection {
176 Projection::Perspective => {
177 if z <= self.distance * 0.01 {
178 return None;
179 }
180 self.focal / z
181 }
182 Projection::Orthographic => self.focal / self.distance,
183 };
184 let pos = pos2(
185 self.frame.center().x + (x * scale) as f32,
186 self.frame.center().y - (y * scale) as f32,
187 );
188 if !pos.is_finite() {
189 return None;
190 }
191 let limit = f64::from(self.frame.width().max(self.frame.height()).max(1.0)) * 8.0;
195 let (left, right) = (
196 f64::from(self.frame.left()) - limit,
197 f64::from(self.frame.right()) + limit,
198 );
199 let (top, bottom) = (
200 f64::from(self.frame.top()) - limit,
201 f64::from(self.frame.bottom()) + limit,
202 );
203 let (px, py) = (f64::from(pos.x), f64::from(pos.y));
204 (px >= left && px <= right && py >= top && py <= bottom).then_some((pos, z))
205 }
206
207 pub fn eye(&self) -> [f64; 3] {
208 self.eye
209 }
210
211 pub fn frame(&self) -> Rect {
212 self.frame
213 }
214
215 pub fn depth(&self, point: [f64; 3]) -> f64 {
217 dot(
218 [point[0] - self.eye[0], point[1] - self.eye[1], point[2] - self.eye[2]],
219 self.forward,
220 )
221 }
222}
223
224pub(super) fn corners(bounds: Bounds3D) -> [[f64; 3]; 8] {
226 [
227 bounds.corner(false, false, false),
228 bounds.corner(true, false, false),
229 bounds.corner(false, true, false),
230 bounds.corner(true, true, false),
231 bounds.corner(false, false, true),
232 bounds.corner(true, false, true),
233 bounds.corner(false, true, true),
234 bounds.corner(true, true, true),
235 ]
236}
237
238fn basis(yaw: f32, pitch: f32) -> ([f64; 3], [f64; 3]) {
239 let (yaw, pitch) = (f64::from(yaw), f64::from(pitch));
240 let cp = pitch.cos();
241 let forward = [-cp * yaw.cos(), -cp * yaw.sin(), -pitch.sin()];
242 let right = normalize(cross(forward, [0.0, 0.0, 1.0]));
243 let right = if right == [0.0, 0.0, 0.0] {
244 [1.0, 0.0, 0.0]
245 } else {
246 right
247 };
248 let up = cross(right, forward);
249 (right, up)
250}
251
252fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
253 [
254 a[1] * b[2] - a[2] * b[1],
255 a[2] * b[0] - a[0] * b[2],
256 a[0] * b[1] - a[1] * b[0],
257 ]
258}
259
260fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
261 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
262}
263
264fn normalize(vector: [f64; 3]) -> [f64; 3] {
265 let length = dot(vector, vector).sqrt();
266 if length <= 1e-12 {
267 [0.0; 3]
268 } else {
269 [vector[0] / length, vector[1] / length, vector[2] / length]
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 #[test]
278 fn points_far_outside_the_frame_are_rejected() {
279 let frame = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
280 let projector = Projector::new(Camera3D::default(), frame);
281 assert!(projector.project([0.0, 0.0, 0.0]).is_some());
282 assert!(projector.project([1e12, 0.0, 0.0]).is_none());
283 }
284}