use std::collections::VecDeque;
use std::f64::consts::PI;
use mln_tile_id::geometry_tile_data::{GeometryCoordinate, GeometryCoordinates};
use crate::geometry::anchor::Anchor;
fn dist(a: GeometryCoordinate, b: GeometryCoordinate) -> f32 {
let dx = f64::from(i32::from(b.x) - i32::from(a.x));
let dy = f64::from(i32::from(b.y) - i32::from(a.y));
(dx * dx + dy * dy).sqrt() as f32
}
fn angle_to(a: GeometryCoordinate, b: GeometryCoordinate) -> f64 {
f64::from(i32::from(a.y) - i32::from(b.y)).atan2(f64::from(i32::from(a.x) - i32::from(b.x)))
}
struct Corner {
distance: f32,
angle_delta: f32,
}
#[must_use]
pub(crate) fn check_max_angle(
line: &GeometryCoordinates,
anchor: &Anchor,
label_length: f32,
window_size: f32,
max_angle: f32,
) -> bool {
let Some(segment) = anchor.segment else {
return true;
};
let mut p: GeometryCoordinate = GeometryCoordinate::new(anchor.point.x as i16, anchor.point.y as i16);
let mut index: usize = segment + 1;
let mut anchor_distance: f32 = 0.0;
while anchor_distance > -label_length / 2.0 {
if index == 0 {
return false;
}
index -= 1;
anchor_distance -= dist(line[index], p);
p = line[index];
}
anchor_distance += dist(line[index], line[index + 1]);
index += 1;
let mut recent_corners: VecDeque<Corner> = VecDeque::new();
let mut recent_angle_delta: f32 = 0.0;
while anchor_distance < label_length / 2.0 {
if index + 1 >= line.len() {
return false;
}
let prev = &line[index - 1];
let current = &line[index];
let next = &line[index + 1];
let mut angle_delta: f64 = angle_to(*prev, *current) - angle_to(*current, *next);
angle_delta = ((angle_delta + 3.0 * PI) % (PI * 2.0) - PI).abs();
recent_corners.push_back(Corner { distance: anchor_distance, angle_delta: angle_delta as f32 });
recent_angle_delta += angle_delta as f32;
while let Some(front) = recent_corners.front() {
if anchor_distance - front.distance > window_size {
recent_angle_delta -= front.angle_delta;
recent_corners.pop_front();
} else {
break;
}
}
if recent_angle_delta > max_angle {
return false;
}
index += 1;
anchor_distance += dist(*current, *next);
}
true
}