1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! 3D→2D projection for Axes3D (matplotlib mplot3d look-at + perspective).
//!
//! Follows matplotlib's `Axes3D.get_proj`:
//! - `elev` / `azim` place the eye on a sphere around the data box
//! - box aspect defaults to `4:4:3` (`set_box_aspect(None)`)
//! - perspective with `focal_length=1`, `dist=10`
use std::f64::consts::PI;
use crate::mpl_policy::axes3d as ax3_policy;
/// A point in 3D data space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point3 {
/// X coordinate.
pub x: f64,
/// Y coordinate.
pub y: f64,
/// Z coordinate.
pub z: f64,
}
impl Point3 {
/// Create a new 3D point.
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
/// Linear interpolation between two points.
pub fn lerp(self, other: Self, t: f64) -> Self {
Self {
x: self.x + (other.x - self.x) * t,
y: self.y + (other.y - self.y) * t,
z: self.z + (other.z - self.z) * t,
}
}
}
/// Camera parameters for 3D projection.
#[derive(Debug, Clone, Copy)]
pub struct Camera {
/// Elevation angle in degrees (default 30°, like matplotlib).
pub elev: f64,
/// Azimuth angle in degrees (default -60°, like matplotlib).
pub azim: f64,
}
impl Default for Camera {
fn default() -> Self {
Self {
elev: ax3_policy::ELEV,
azim: ax3_policy::AZIM,
}
}
}
/// Projected 2D point with depth for painter's algorithm sorting.
#[derive(Debug, Clone, Copy)]
pub struct Projected {
/// Screen x (right is positive).
pub x: f64,
/// Screen y (up is positive).
pub y: f64,
/// Depth (larger = farther from camera).
pub depth: f64,
}
/// View / perspective projection matching matplotlib `Axes3D.get_proj`.
#[derive(Debug, Clone, Copy)]
pub struct Projection {
/// Camera-right unit vector (world).
u: Point3,
/// Camera-up unit vector (world).
v: Point3,
/// Camera-out unit vector (world), from box center toward eye.
w: Point3,
/// Eye position in world (box) coordinates.
eye: Point3,
/// Focal length (matplotlib default 1).
focal: f64,
}
impl Projection {
/// Build a projection from camera angles (degrees).
pub fn from_camera(camera: Camera) -> Self {
let [ax, ay, az] = ax3_policy::box_aspect();
let elev = camera.elev * PI / 180.0;
let azim = camera.azim * PI / 180.0;
// Eye direction on the unit sphere (matplotlib `get_proj`).
let p0 = elev.cos() * azim.cos();
let p1 = elev.cos() * azim.sin();
let p2 = elev.sin();
let focal = ax3_policy::FOCAL_LENGTH;
let cx = 0.5 * ax;
let cy = 0.5 * ay;
let cz = 0.5 * az;
let eye = Point3::new(
cx + ax3_policy::DIST * focal * p0,
cy + ax3_policy::DIST * focal * p1,
cz + ax3_policy::DIST * focal * p2,
);
// Viewing axes (`proj3d._view_axes`).
let w = normalize_vec(Point3::new(eye.x - cx, eye.y - cy, eye.z - cz));
let up = Point3::new(0.0, 0.0, if elev.abs() > PI / 2.0 { -1.0 } else { 1.0 });
let u = normalize_vec(cross(up, w));
let v = cross(w, u);
Self {
u,
v,
w,
eye,
focal,
}
}
/// Project a point already in world/box coordinates `[0, aspect]³`.
pub fn project(&self, p: Point3) -> Projected {
// View: rows [u,v,w] applied to (p - eye).
let qx = p.x - self.eye.x;
let qy = p.y - self.eye.y;
let qz = p.z - self.eye.z;
let cam_x = self.u.x * qx + self.u.y * qy + self.u.z * qz;
let cam_y = self.v.x * qx + self.v.y * qy + self.v.z * qz;
let cam_z = self.w.x * qx + self.w.y * qy + self.w.z * qz;
// Perspective (`proj3d._persp_transformation(-dist, dist, focal)`).
let clip_x = self.focal * cam_x;
let clip_y = self.focal * cam_y;
let clip_w = -cam_z;
let inv_w = 1.0 / clip_w;
Projected {
x: clip_x * inv_w,
y: clip_y * inv_w,
// Larger = farther (cam_z is more negative when farther from eye).
depth: -cam_z,
}
}
/// Project a 3D data point given axis ranges.
pub fn project_data(
&self,
p: Point3,
x_range: (f64, f64),
y_range: (f64, f64),
z_range: (f64, f64),
) -> Projected {
let [ax, ay, az] = ax3_policy::box_aspect();
// `world_transformation`: data → [0, aspect_i].
let wx = normalize(p.x, x_range.0, x_range.1) * ax;
let wy = normalize(p.y, y_range.0, y_range.1) * ay;
let wz = normalize(p.z, z_range.0, z_range.1) * az;
self.project(Point3::new(wx, wy, wz))
}
}
fn normalize(v: f64, min: f64, max: f64) -> f64 {
let span = (max - min).abs();
if span < 1e-12 {
0.5
} else {
(v - min) / span
}
}
fn normalize_vec(p: Point3) -> Point3 {
let n = (p.x * p.x + p.y * p.y + p.z * p.z).sqrt().max(1e-15);
Point3::new(p.x / n, p.y / n, p.z / n)
}
fn cross(a: Point3, b: Point3) -> Point3 {
Point3::new(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
)
}
/// Axis bounding box corners in world/box coordinates (`[0, aspect]³`).
pub fn cube_corners() -> [Point3; 8] {
let [ax, ay, az] = ax3_policy::box_aspect();
[
Point3::new(0.0, 0.0, 0.0),
Point3::new(ax, 0.0, 0.0),
Point3::new(ax, ay, 0.0),
Point3::new(0.0, ay, 0.0),
Point3::new(0.0, 0.0, az),
Point3::new(ax, 0.0, az),
Point3::new(ax, ay, az),
Point3::new(0.0, ay, az),
]
}
/// The 12 edges of the cube as pairs of corner indices.
pub const CUBE_EDGES: [(usize, usize); 12] = [
(0, 1),
(1, 2),
(2, 3),
(3, 0), // bottom face
(4, 5),
(5, 6),
(6, 7),
(7, 4), // top face
(0, 4),
(1, 5),
(2, 6),
(3, 7), // verticals
];
/// Determine which 3 faces of the cube are "back" (should be drawn first / show axes).
/// Returns edge indices for the 3 back-facing edges that should carry tick labels.
pub fn back_edges(proj: &Projection) -> BackEdges {
let corners = cube_corners();
let projected: Vec<Projected> = corners.iter().map(|&c| proj.project(c)).collect();
// Find the corner with maximum depth (farthest from camera) — that's the
// "back corner" where 3 axes meet (matplotlib draws axes there).
let back_idx = projected
.iter()
.enumerate()
.max_by(|a, b| {
a.1.depth
.partial_cmp(&b.1.depth)
.unwrap_or(std::cmp::Ordering::Equal)
})
.map(|(i, _)| i)
.unwrap_or(0);
// The 3 edges emanating from the back corner.
let mut edges = [0usize; 3];
let mut count = 0;
for (ei, &(a, b)) in CUBE_EDGES.iter().enumerate() {
if (a == back_idx || b == back_idx) && count < 3 {
edges[count] = ei;
count += 1;
}
}
BackEdges {
edge_indices: edges,
back_corner: back_idx,
}
}
/// Result of back-edge detection for axis drawing.
#[derive(Debug, Clone, Copy)]
pub struct BackEdges {
/// Indices into [`CUBE_EDGES`] for the 3 back-facing axis edges.
pub edge_indices: [usize; 3],
/// Index into the 8 corners for the farthest (back) corner.
pub back_corner: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_camera_projects_center_to_origin() {
let proj = Projection::from_camera(Camera::default());
let [ax, ay, az] = ax3_policy::box_aspect();
let p = proj.project(Point3::new(0.5 * ax, 0.5 * ay, 0.5 * az));
assert!(p.x.abs() < 1e-9, "x={}", p.x);
assert!(p.y.abs() < 1e-9, "y={}", p.y);
}
#[test]
fn azim_matches_matplotlib_bottom_tip() {
// At elev=30, azim=-60 the floor corner (x_max, y_min, z_min) is lowest on screen.
let proj = Projection::from_camera(Camera {
elev: 30.0,
azim: -60.0,
});
let ranges = ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0));
let corners = [
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
Point3::new(1.0, 1.0, 0.0),
];
let ys: Vec<f64> = corners
.iter()
.map(|&c| proj.project_data(c, ranges.0, ranges.1, ranges.2).y)
.collect();
let bottom = ys
.iter()
.enumerate()
.min_by(|a, b| a.1.partial_cmp(b.1).unwrap())
.map(|(i, _)| i)
.unwrap();
assert_eq!(bottom, 1, "expected (1,0,0) as bottom tip like mplot3d");
}
#[test]
fn perspective_matches_matplotlib_ndc() {
// Numeric check against Axes3D.get_proj for elev=30, azim=-55 on unit data cube.
let proj = Projection::from_camera(Camera {
elev: 30.0,
azim: -55.0,
});
let ranges = ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0));
let p = proj.project_data(Point3::new(1.0, 0.0, 0.0), ranges.0, ranges.1, ranges.2);
// From matplotlib reference run in this session:
assert!((p.x - 0.015378404066198009).abs() < 1e-6, "x={}", p.x);
assert!((p.y - (-0.08428173010311531)).abs() < 1e-6, "y={}", p.y);
}
#[test]
fn normalize_works() {
assert!((normalize(5.0, 0.0, 10.0) - 0.5).abs() < 1e-12);
assert!((normalize(0.0, 0.0, 10.0)).abs() < 1e-12);
assert!((normalize(10.0, 0.0, 10.0) - 1.0).abs() < 1e-12);
}
}