use super::types::{CameraPose, StoneGeometryBuf};
use indicatrix::{
geometry::stone_metrics::{SolidStatus, build_solid_mesh},
optics::raytracer::{DEFAULT_FOV_DEG, DEFAULT_POSE},
};
use std::f32::consts::FRAC_PI_2;
const FIT_MARGIN: f32 = 1.15;
pub const RESET_POSE: CameraPose = CameraPose {
yaw: DEFAULT_POSE.yaw,
pitch: DEFAULT_POSE.pitch,
distance: DEFAULT_POSE.distance,
};
#[must_use]
pub fn orbit_distance_bounds(bounding_radius: f64) -> (f32, f32) {
const MIN_FACTOR: f32 = 0.8;
const MAX_FACTOR: f32 = 16.0 / 3.0;
#[expect(
clippy::cast_possible_truncation,
reason = "f32 is the camera precision; a mesh bounding radius is in the normal float range"
)]
let radius = (bounding_radius as f32).max(0.01);
(radius * MIN_FACTOR, radius * MAX_FACTOR)
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "f32 is the camera precision; a mesh bounding radius is in the normal float range"
)]
pub fn fit_distance_for_radius(bounding_radius: f64) -> f32 {
let half_fov_tan = (DEFAULT_FOV_DEG.to_radians() * 0.5).tan();
(bounding_radius as f32).max(0.01) / half_fov_tan * FIT_MARGIN
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "f32 is the camera precision; a mesh bounding radius is in the normal float range"
)]
pub fn fit_distance_for_view(bounding_radius: f64, aspect: f32) -> f32 {
let narrow = if aspect.is_finite() && aspect > 0.0 {
aspect.min(1.0)
} else {
1.0
};
let outline_tan = (DEFAULT_FOV_DEG.to_radians() * 0.5).tan() * narrow / FIT_MARGIN;
(bounding_radius as f32).max(0.01) * outline_tan.recip().hypot(1.0)
}
#[must_use]
pub fn planar_bounding_radius(stone: &StoneGeometryBuf) -> Option<f64> {
let planes: Vec<_> = stone
.planes
.iter()
.map(|plane| plane.to_halfspace_f64())
.collect();
match build_solid_mesh(&planes) {
SolidStatus::Closed(mesh) => Some(
mesh.positions
.iter()
.map(|position| position.length())
.fold(0.0_f64, f64::max),
),
_ => None,
}
}
#[must_use]
pub fn wrap_pitch(pitch: f32) -> f32 {
use std::f32::consts::PI;
(pitch + PI).rem_euclid(2.0 * PI) - PI
}
#[must_use]
pub fn orbit_step(pose: CameraPose, dx: f32, dy: f32) -> CameraPose {
CameraPose {
yaw: dx.mul_add(-0.008, pose.yaw),
pitch: wrap_pitch(dy.mul_add(0.008, pose.pitch)),
distance: pose.distance,
}
}
#[must_use]
pub fn zoom_step(distance: f32, delta: f32, bounding_radius: f64) -> f32 {
let (min, max) = orbit_distance_bounds(bounding_radius);
delta.mul_add(-0.002, distance).clamp(min, max)
}
#[must_use]
pub fn standard_view(kind: i32, pose: CameraPose, bounding_radius: f64) -> CameraPose {
if kind == 5 {
let (min, max) = orbit_distance_bounds(bounding_radius);
return CameraPose {
distance: fit_distance_for_view(bounding_radius, 1.0).clamp(min, max),
..pose
};
}
let (yaw, pitch) = match kind {
1 => (0.0, FRAC_PI_2),
2 => (0.0, -FRAC_PI_2),
3 => (-FRAC_PI_2, 0.0),
4 => (FRAC_PI_2, 0.0),
_ => (0.0, 0.0),
};
CameraPose { yaw, pitch, ..pose }
}
#[cfg(test)]
mod tests;