use crate::vec3::{dot, unit};
pub(crate) const DEFAULT_ANGLE: f32 = 30.0;
const MAX_AROUND: usize = 512;
const BUDGET: usize = 1 << 26;
#[cfg_attr(
not(any(feature = "lwo", feature = "ac3d", feature = "x3d")),
allow(dead_code, reason = "only formats with a smoothing angle of their own use it")
)]
pub(crate) fn corner_normals(
points: usize,
polys: &[(usize, usize)],
corners: &[u32],
face: &[[f32; 3]],
cos: impl Fn(usize) -> Option<f32>,
joins: impl Fn(usize, usize) -> bool,
) -> Vec<[f32; 3]> {
weighted(points, polys, corners, face, None, cos, joins)
}
pub(crate) fn default_normals(positions: &[[f32; 3]], indices: &[u32], degrees: f32) -> Vec<[f32; 3]> {
let tris = indices.len() / 3;
let mut face = Vec::with_capacity(tris);
let mut area = Vec::with_capacity(tris);
for t in indices.as_chunks::<3>().0 {
let [a, b, c] = t.map(|i| positions.get(i as usize).copied().unwrap_or([0.0; 3]).map(f64::from));
let (u, v) = (
[b[0] - a[0], b[1] - a[1], b[2] - a[2]],
[c[0] - a[0], c[1] - a[1], c[2] - a[2]],
);
let f = [
u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0],
];
let l = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt();
#[allow(
clippy::cast_possible_truncation,
reason = "a unit vector, and a weight that only needs its size"
)]
if l > 0.0 && l.is_finite() {
face.push(f.map(|x| (x / l) as f32));
area.push(l);
} else {
face.push([0.0; 3]);
area.push(0.0);
}
}
let most = area.iter().fold(0.0f64, |m, &a| m.max(a));
#[allow(clippy::cast_possible_truncation, reason = "between 0 and 1")]
let weight: Vec<f32> = area
.iter()
.map(|&a| if most > 0.0 { (a / most) as f32 } else { 0.0 })
.collect();
let polys: Vec<(usize, usize)> = (0..tris).map(|t| (t * 3, 3)).collect();
let cos = if degrees <= 0.0 {
None
} else if degrees >= 180.0 {
Some(-2.0)
} else {
Some(degrees.to_radians().cos())
};
let mut out = weighted(
positions.len(),
&polys,
&indices[..tris * 3],
&face,
Some(&weight),
|_| cos,
|_, _| true,
);
for (t, n) in out.chunks_exact_mut(3).enumerate() {
if weight[t] == 0.0 {
n.fill([0.0; 3]);
}
}
out.resize(indices.len(), [0.0; 3]);
out
}
fn weighted(
points: usize,
polys: &[(usize, usize)],
corners: &[u32],
face: &[[f32; 3]],
weight: Option<&[f32]>,
cos: impl Fn(usize) -> Option<f32>,
joins: impl Fn(usize, usize) -> bool,
) -> Vec<[f32; 3]> {
let span = |&(s, n): &(usize, usize)| corners.get(s..s.saturating_add(n)).unwrap_or(&[]);
let weigh = |q: usize| weight.map_or(1.0, |w| w.get(q).copied().unwrap_or(0.0));
let mut start = vec![0usize; points + 1];
for p in polys {
for &c in span(p) {
if let Some(s) = start.get_mut(c as usize + 1) {
*s += 1;
}
}
}
for i in 1..start.len() {
start[i] += start[i - 1];
}
let mut around = vec![0u32; start[points]];
let mut fill = start.clone();
for (i, p) in polys.iter().enumerate() {
for &c in span(p).iter().filter(|&&c| (c as usize) < points) {
let f = &mut fill[c as usize];
around[*f] = u32::try_from(i).unwrap_or(u32::MAX);
*f += 1;
}
}
let mut budget = BUDGET.saturating_add(corners.len().saturating_mul(64));
let mut means: std::collections::HashMap<usize, Option<[f32; 3]>> = std::collections::HashMap::new();
let mut paid: Vec<bool> = Vec::new();
let mut out = vec![[0.0; 3]; corners.len()];
for (p, &(s, n)) in polys.iter().enumerate() {
let own = face.get(p).copied().unwrap_or([0.0, 1.0, 0.0]);
let cos = cos(p);
for k in s..s.saturating_add(n).min(corners.len()) {
let c = corners[k] as usize;
let (Some(cos), Some(&a), Some(&b)) = (cos, start.get(c), start.get(c + 1)) else {
out[k] = own;
continue;
};
let list = &around[a..b];
if list.len() > MAX_AROUND {
if paid.is_empty() {
paid = vec![false; points];
}
if !paid[c] && !means.contains_key(&c) {
let cost = list.len().saturating_mul(list.len());
if cost <= budget {
budget -= cost;
paid[c] = true;
} else {
let mut sum = [0.0f32; 3];
for &q in list {
if let Some(&f) = face.get(q as usize) {
let w = weigh(q as usize);
sum = [sum[0] + f[0] * w, sum[1] + f[1] * w, sum[2] + f[2] * w];
}
}
means.insert(c, unit(sum));
}
}
if !paid[c] {
let mean = means.get(&c).copied().flatten();
out[k] = mean.filter(|m| dot(*m, own) >= cos).unwrap_or(own);
continue;
}
}
let mut sum = [0.0f32; 3];
let mut last = u32::MAX;
for &q in list {
if q == last {
continue;
}
last = q;
let q = q as usize;
let Some(&f) = face.get(q) else { continue };
if q == p || (joins(p, q) && dot(f, own) >= cos) {
let w = weigh(q);
sum = [sum[0] + f[0] * w, sum[1] + f[1] * w, sum[2] + f[2] * w];
}
}
out[k] = unit(sum).unwrap_or(own);
}
}
out
}
#[cfg(test)]
#[allow(clippy::float_cmp, reason = "exact directions")]
mod tests {
use super::*;
#[test]
fn creases_split_and_smooth() {
let corners = [0, 1, 2, 3, 1, 4, 5, 2];
let polys = [(0, 4), (4, 4)];
let face = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]];
let soft = corner_normals(6, &polys, &corners, &face, |_| Some(0.0), |_, _| true);
let h = std::f32::consts::FRAC_1_SQRT_2;
assert!((soft[1][0] - h).abs() < 1e-6 && (soft[1][2] - h).abs() < 1e-6);
assert_eq!(soft[0], face[0]);
let hard = corner_normals(6, &polys, &corners, &face, |_| Some(0.5), |_, _| true);
assert_eq!(hard[1], face[0]);
assert_eq!(hard[4], face[1]);
let apart = corner_normals(6, &polys, &corners, &face, |_| Some(0.0), |a, b| a == b);
assert_eq!(apart[1], face[0]);
let flat = corner_normals(6, &polys, &corners, &face, |_| None, |_, _| true);
assert_eq!(flat[5], face[1]);
let odd = corner_normals(2, &[(0, 9), (7, 3)], &corners, &face[..1], |_| Some(0.0), |_, _| true);
assert_eq!(odd.len(), corners.len());
}
#[test]
fn the_default_keeps_a_right_angle_hard_and_a_gentle_fold_smooth() {
let fold = |angle: f32| {
let (s, c) = angle.to_radians().sin_cos();
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -c, s]];
default_normals(&positions, &[0, 1, 2, 1, 0, 3], DEFAULT_ANGLE)
};
let hard = fold(90.0);
assert_eq!(hard[0], [0.0, 0.0, 1.0]);
assert!((hard[4][1] - 1.0).abs() < 1e-6, "{:?}", hard[4]);
let soft = fold(20.0);
assert_eq!(soft[0], soft[4]);
assert_eq!(soft[1], soft[3]);
assert!(soft[0][2] < 1.0 && soft[0][2] > 0.98, "{:?}", soft[0]);
assert_eq!(soft[2], [0.0, 0.0, 1.0]);
let none = default_normals(&[[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]], &[0, 1, 2], DEFAULT_ANGLE);
assert_eq!(none, [[0.0; 3]; 3]);
}
#[test]
fn the_tip_of_a_cone_with_many_faces_is_smooth() {
let n = 2000u32;
let mut positions = vec![[0.0, 0.0, 0.1]];
for k in 0..n {
#[allow(clippy::cast_precision_loss, reason = "a few thousand")]
let a = k as f32 / n as f32 * std::f32::consts::TAU;
positions.push([a.cos(), a.sin(), 0.0]);
}
let indices: Vec<u32> = (0..n).flat_map(|k| [0, 1 + k, 1 + (k + 1) % n]).collect();
let normals = default_normals(&positions, &indices, DEFAULT_ANGLE);
let face = crate::mesh::face_normal(positions[0], positions[1], positions[2]);
assert!(normals[0][2] > face[2] + 1e-3, "{:?} {face:?}", normals[0]);
assert_eq!(normals[2], normals[4]);
}
}