1use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5
6use super::algo::{astar, kosaraju_scc};
7use super::coord::Coord;
8use super::error::RoutingError;
9use super::geo::haversine_distance;
10use super::graph::{DiGraph, EdgeIdx, NodeIdx};
11use super::spatial::{KdTree, Point2D, Segment, SegmentIndex};
12
13#[derive(Debug, Clone)]
14pub struct NodeData {
15 pub lat: f64,
16 pub lng: f64,
17}
18
19impl NodeData {
20 #[inline]
21 pub fn coord(&self) -> Coord {
22 Coord::new(self.lat, self.lng)
23 }
24}
25
26#[derive(Debug, Clone)]
27pub struct EdgeData {
28 pub travel_time_s: f64,
29 pub distance_m: f64,
30 pub name: Option<String>,
31}
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct StreetRun {
36 pub name: String,
37 pub distance_m: f64,
38}
39
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct RouteResult {
42 pub duration_seconds: i64,
43 pub distance_meters: f64,
44 pub geometry: Vec<Coord>,
45 pub streets: Vec<StreetRun>,
49}
50
51pub(crate) fn merge_street_runs(
54 pieces: impl IntoIterator<Item = (Option<String>, f64)>,
55) -> Vec<StreetRun> {
56 let mut runs: Vec<StreetRun> = Vec::new();
57 for (name, distance) in pieces {
58 let Some(name) = name else { continue };
59 if distance <= 0.0 {
60 continue;
61 }
62 match runs.last_mut() {
63 Some(last) if last.name == name => last.distance_m += distance,
64 _ => runs.push(StreetRun {
65 name,
66 distance_m: distance,
67 }),
68 }
69 }
70 runs
71}
72
73impl RouteResult {
74 pub fn simplify(mut self, tolerance_m: f64) -> Self {
80 if self.geometry.len() <= 2 {
81 return self;
82 }
83
84 self.geometry = douglas_peucker(&self.geometry, tolerance_m);
85 self
86 }
87}
88
89#[derive(Debug, Clone, Copy, Default)]
90pub struct SnappedCoord {
91 pub original: Coord,
92 pub snapped: Coord,
93 pub snap_distance_m: f64,
94 pub(crate) node_index: NodeIdx,
95}
96
97#[derive(Debug, Clone, Copy)]
99struct SpatialPoint {
100 node_index: NodeIdx,
101}
102
103#[derive(Debug, Clone, Copy)]
105struct SpatialSegment {
106 from_node: NodeIdx,
107 to_node: NodeIdx,
108 edge_index: EdgeIdx,
109}
110
111#[derive(Debug, Clone, Copy)]
112pub struct EdgeSnappedLocation {
113 pub original: Coord,
114 pub snapped: Coord,
115 pub snap_distance_m: f64,
116 pub(crate) edge_index: EdgeIdx,
117 pub(crate) position: f64,
118 pub(crate) from_node: NodeIdx,
119 pub(crate) to_node: NodeIdx,
120}
121
122#[derive(Debug, Clone, Copy)]
123struct EdgeTraversal {
124 node: NodeIdx,
125 time_s: f64,
126 distance_m: f64,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum SnapAccess {
137 Incoming,
138 Outgoing,
139 Both,
140}
141
142impl SnapAccess {
143 fn allows(&self, incoming: bool, outgoing: bool) -> bool {
144 match self {
145 SnapAccess::Incoming => incoming,
146 SnapAccess::Outgoing => outgoing,
147 SnapAccess::Both => incoming && outgoing,
148 }
149 }
150}
151
152pub struct RoadNetwork {
153 pub(super) graph: DiGraph<NodeData, EdgeData>,
154 spatial_index: Option<KdTree<SpatialPoint>>,
155 edge_spatial_index: Option<SegmentIndex<SpatialSegment>>,
156 node_access: Option<(Vec<bool>, Vec<bool>)>,
159 max_speed_mps: f64,
160}
161
162impl RoadNetwork {
163 pub fn new() -> Self {
164 Self {
165 graph: DiGraph::new(),
166 spatial_index: None,
167 edge_spatial_index: None,
168 node_access: None,
169 max_speed_mps: 0.0,
170 }
171 }
172
173 pub(super) fn add_node_at(&mut self, lat: f64, lng: f64) -> NodeIdx {
174 self.graph.add_node(NodeData { lat, lng })
175 }
176
177 pub(super) fn add_edge(&mut self, from: NodeIdx, to: NodeIdx, data: EdgeData) {
178 self.record_edge_speed(&data);
179 self.graph.add_edge(from, to, data);
180 }
181
182 pub fn add_edge_by_index(
183 &mut self,
184 from: usize,
185 to: usize,
186 travel_time_s: f64,
187 distance_m: f64,
188 ) {
189 self.add_edge_named_by_index(from, to, travel_time_s, distance_m, None);
190 }
191
192 pub(super) fn add_edge_named_by_index(
193 &mut self,
194 from: usize,
195 to: usize,
196 travel_time_s: f64,
197 distance_m: f64,
198 name: Option<String>,
199 ) {
200 let from_idx = NodeIdx::new(from);
201 let to_idx = NodeIdx::new(to);
202 let data = EdgeData {
203 travel_time_s,
204 distance_m,
205 name,
206 };
207 self.record_edge_speed(&data);
208 self.graph.add_edge(from_idx, to_idx, data);
209 }
210
211 pub(super) fn build_spatial_index(&mut self) {
212 let points: Vec<(Point2D, SpatialPoint)> = self
214 .graph
215 .node_indices()
216 .filter_map(|node_idx| {
217 let node = self.graph.node_weight(node_idx)?;
218 Some((
219 Point2D::new(node.lat, node.lng),
220 SpatialPoint {
221 node_index: node_idx,
222 },
223 ))
224 })
225 .collect();
226
227 self.spatial_index = Some(KdTree::from_items(points));
228
229 let segments: Vec<(Segment, SpatialSegment)> = self
231 .graph
232 .edge_indices()
233 .filter_map(|edge_idx| {
234 let (from_node, to_node) = self.graph.edge_endpoints(edge_idx)?;
235 let from_data = self.graph.node_weight(from_node)?;
236 let to_data = self.graph.node_weight(to_node)?;
237 Some((
238 Segment::new(
239 Point2D::new(from_data.lat, from_data.lng),
240 Point2D::new(to_data.lat, to_data.lng),
241 ),
242 SpatialSegment {
243 from_node,
244 to_node,
245 edge_index: edge_idx,
246 },
247 ))
248 })
249 .collect();
250
251 self.edge_spatial_index = Some(SegmentIndex::bulk_load(segments));
252
253 let node_count = self.graph.node_count();
257 if node_count > 0 {
258 let mut incoming = vec![false; node_count];
259 let mut outgoing = vec![false; node_count];
260 for (from, to) in self
261 .graph
262 .edge_indices()
263 .filter_map(|edge| self.graph.edge_endpoints(edge))
264 {
265 outgoing[from.index()] = true;
266 incoming[to.index()] = true;
267 }
268 self.node_access = Some((incoming, outgoing));
269 }
270 }
271
272 fn allows_access(&self, node_index: NodeIdx, access: SnapAccess) -> bool {
277 match self.node_access.as_ref() {
278 Some((incoming, outgoing)) => {
279 let index = node_index.index();
280 access.allows(
281 incoming.get(index).copied().unwrap_or(false),
282 outgoing.get(index).copied().unwrap_or(false),
283 )
284 }
285 None => true,
286 }
287 }
288
289 pub fn snap_road_index_with_access(
294 &self,
295 coord: Coord,
296 access: SnapAccess,
297 ) -> Result<SnappedCoord, RoutingError> {
298 let tree = self
299 .spatial_index
300 .as_ref()
301 .ok_or(RoutingError::SnapFailed {
302 coord,
303 nearest_distance_m: None,
304 })?;
305
306 let query = Point2D::new(coord.lat, coord.lng);
307 const SNAP_CANDIDATES: usize = 64;
308 let candidates = tree.nearest_n_neighbors(&query, SNAP_CANDIDATES);
309 let chosen = candidates
310 .iter()
311 .find(|(candidate, _)| self.allows_access(candidate.node_index, access))
312 .or_else(|| candidates.first())
313 .ok_or(RoutingError::SnapFailed {
314 coord,
315 nearest_distance_m: None,
316 })?;
317
318 let node_data =
319 self.graph
320 .node_weight(chosen.0.node_index)
321 .ok_or(RoutingError::SnapFailed {
322 coord,
323 nearest_distance_m: None,
324 })?;
325
326 let snapped = Coord::new(node_data.lat, node_data.lng);
327 let snap_distance_m = haversine_distance(coord, snapped);
328
329 Ok(SnappedCoord {
330 original: coord,
331 snapped,
332 snap_distance_m,
333 node_index: chosen.0.node_index,
334 })
335 }
336
337 fn record_edge_speed(&mut self, edge: &EdgeData) {
338 if edge.travel_time_s <= 0.0 || edge.distance_m <= 0.0 {
339 return;
340 }
341
342 let speed_mps = edge.distance_m / edge.travel_time_s;
343 if speed_mps.is_finite() {
344 self.max_speed_mps = self.max_speed_mps.max(speed_mps);
345 }
346 }
347
348 fn distance_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
349 let Some(from_node) = self.graph.node_weight(from) else {
350 return 0.0;
351 };
352 let Some(to_node) = self.graph.node_weight(to) else {
353 return 0.0;
354 };
355 haversine_distance(from_node.coord(), to_node.coord())
356 }
357
358 fn time_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
359 if !self.max_speed_mps.is_finite() || self.max_speed_mps <= 0.0 {
360 return 0.0;
361 }
362
363 self.distance_lower_bound_between(from, to) / self.max_speed_mps
364 }
365
366 fn node_path_geometry(&self, path: &[NodeIdx]) -> Vec<Coord> {
367 path.iter()
368 .filter_map(|&idx| self.graph.node_weight(idx).map(|n| n.coord()))
369 .collect()
370 }
371
372 fn node_path_metrics(&self, path: &[NodeIdx]) -> (f64, f64) {
373 let mut distance = 0.0;
374 let mut time = 0.0;
375
376 for window in path.windows(2) {
377 if let Some(edge) = self.graph.find_edge(window[0], window[1]) {
378 if let Some(weight) = self.graph.edge_weight(edge) {
379 distance += weight.distance_m;
380 time += weight.travel_time_s;
381 }
382 }
383 }
384
385 (distance, time)
386 }
387
388 fn route_result_from_node_path(&self, path: &[NodeIdx], duration_seconds: i64) -> RouteResult {
389 let geometry = self.node_path_geometry(path);
390 let (distance, _) = self.node_path_metrics(path);
391 let pieces = path.windows(2).map(|window| {
392 self.graph
393 .find_edge(window[0], window[1])
394 .and_then(|edge| self.graph.edge_weight(edge))
395 .map(|weight| (weight.name.clone(), weight.distance_m))
396 .unwrap_or((None, 0.0))
397 });
398
399 RouteResult {
400 duration_seconds,
401 distance_meters: distance,
402 geometry,
403 streets: merge_street_runs(pieces),
404 }
405 }
406
407 pub fn nodes_iter(&self) -> impl Iterator<Item = (f64, f64)> + '_ {
409 self.graph
410 .node_indices()
411 .filter_map(|idx| self.graph.node_weight(idx).map(|n| (n.lat, n.lng)))
412 }
413
414 pub fn edges_iter(&self) -> impl Iterator<Item = (usize, usize, f64, f64)> + '_ {
417 self.graph.edge_indices().filter_map(|idx| {
418 let (from, to) = self.graph.edge_endpoints(idx)?;
419 let weight = self.graph.edge_weight(idx)?;
420 Some((
421 from.index(),
422 to.index(),
423 weight.travel_time_s,
424 weight.distance_m,
425 ))
426 })
427 }
428
429 pub fn edges_with_names_iter(
432 &self,
433 ) -> impl Iterator<Item = (usize, usize, f64, f64, Option<String>)> + '_ {
434 self.graph.edge_indices().filter_map(|idx| {
435 let (from, to) = self.graph.edge_endpoints(idx)?;
436 let weight = self.graph.edge_weight(idx)?;
437 Some((
438 from.index(),
439 to.index(),
440 weight.travel_time_s,
441 weight.distance_m,
442 weight.name.clone(),
443 ))
444 })
445 }
446
447 pub fn snap_to_road(&self, coord: Coord) -> Option<NodeIdx> {
451 self.spatial_index
452 .as_ref()?
453 .nearest_neighbor(&Point2D::new(coord.lat, coord.lng))
454 .map(|p| p.node_index)
455 }
456
457 pub fn snap_to_road_detailed(&self, coord: Coord) -> Result<SnappedCoord, RoutingError> {
462 let tree = self
463 .spatial_index
464 .as_ref()
465 .ok_or(RoutingError::SnapFailed {
466 coord,
467 nearest_distance_m: None,
468 })?;
469
470 let query = Point2D::new(coord.lat, coord.lng);
471 let (nearest, _dist_sq) =
472 tree.nearest_neighbor_with_distance(&query)
473 .ok_or(RoutingError::SnapFailed {
474 coord,
475 nearest_distance_m: None,
476 })?;
477
478 let node_data =
480 self.graph
481 .node_weight(nearest.node_index)
482 .ok_or(RoutingError::SnapFailed {
483 coord,
484 nearest_distance_m: None,
485 })?;
486
487 let snapped = Coord::new(node_data.lat, node_data.lng);
488 let snap_distance_m = haversine_distance(coord, snapped);
489
490 Ok(SnappedCoord {
491 original: coord,
492 snapped,
493 snap_distance_m,
494 node_index: nearest.node_index,
495 })
496 }
497
498 pub fn snap_to_edge(&self, coord: Coord) -> Result<EdgeSnappedLocation, RoutingError> {
503 let index = self
504 .edge_spatial_index
505 .as_ref()
506 .ok_or(RoutingError::SnapFailed {
507 coord,
508 nearest_distance_m: None,
509 })?;
510
511 let query = Point2D::new(coord.lat, coord.lng);
512 let (segment, seg_data, proj_point, _dist_sq) =
513 index
514 .nearest_segment(&query)
515 .ok_or(RoutingError::SnapFailed {
516 coord,
517 nearest_distance_m: None,
518 })?;
519
520 let (_, position) = segment.project_point(&query);
522 let snapped = Coord::new(proj_point.x, proj_point.y);
523 let snap_distance_m = haversine_distance(coord, snapped);
524
525 Ok(EdgeSnappedLocation {
526 original: coord,
527 snapped,
528 snap_distance_m,
529 edge_index: seg_data.edge_index,
530 position,
531 from_node: seg_data.from_node,
532 to_node: seg_data.to_node,
533 })
534 }
535
536 pub fn route(&self, from: Coord, to: Coord) -> Result<RouteResult, RoutingError> {
543 let start_snap = self.snap_road_index_with_access(from, SnapAccess::Outgoing)?;
544 let end_snap = self.snap_road_index_with_access(to, SnapAccess::Incoming)?;
545
546 self.route_snapped(&start_snap, &end_snap)
547 }
548
549 pub fn route_edge_snapped(
554 &self,
555 from: &EdgeSnappedLocation,
556 to: &EdgeSnappedLocation,
557 ) -> Result<RouteResult, RoutingError> {
558 let from_edge = self
559 .graph
560 .edge_weight(from.edge_index)
561 .ok_or(RoutingError::NoPath {
562 from: from.original,
563 to: to.original,
564 })?;
565 let to_edge = self
566 .graph
567 .edge_weight(to.edge_index)
568 .ok_or(RoutingError::NoPath {
569 from: from.original,
570 to: to.original,
571 })?;
572
573 if from.edge_index == to.edge_index {
575 if to.position < from.position {
576 return Err(RoutingError::NoPath {
577 from: from.original,
578 to: to.original,
579 });
580 }
581
582 let segment_time = from_edge.travel_time_s;
583 let segment_dist = from_edge.distance_m;
584 let travel_fraction = to.position - from.position;
585 return Ok(RouteResult {
586 duration_seconds: (segment_time * travel_fraction).round() as i64,
587 distance_meters: segment_dist * travel_fraction,
588 geometry: vec![from.snapped, to.snapped],
589 streets: merge_street_runs([(
590 from_edge.name.clone(),
591 segment_dist * travel_fraction,
592 )]),
593 });
594 }
595
596 let start_exit = EdgeTraversal {
597 node: from.to_node,
598 time_s: from_edge.travel_time_s * (1.0 - from.position),
599 distance_m: from_edge.distance_m * (1.0 - from.position),
600 };
601 let end_entry = EdgeTraversal {
602 node: to.from_node,
603 time_s: to_edge.travel_time_s * to.position,
604 distance_m: to_edge.distance_m * to.position,
605 };
606
607 let best_result = if start_exit.node == end_entry.node {
608 Some((start_exit.time_s + end_entry.time_s, vec![start_exit.node]))
609 } else {
610 astar(
611 &self.graph,
612 start_exit.node,
613 |n| n == end_entry.node,
614 |e| e.travel_time_s,
615 |n| self.time_lower_bound_between(n, end_entry.node),
616 )
617 .map(|(path_cost, path)| (start_exit.time_s + path_cost + end_entry.time_s, path))
618 };
619
620 match best_result {
621 Some((total_cost, path)) => {
622 let mut geometry = vec![from.snapped];
623 for coord in self.node_path_geometry(&path) {
624 if geometry.last().copied() != Some(coord) {
625 geometry.push(coord);
626 }
627 }
628 if geometry.last().copied() != Some(to.snapped) {
629 geometry.push(to.snapped);
630 }
631
632 let (path_distance, _) = self.node_path_metrics(&path);
633 let distance = start_exit.distance_m + path_distance + end_entry.distance_m;
634 let mut pieces = Vec::new();
635 pieces.push((from_edge.name.clone(), start_exit.distance_m));
636 for window in path.windows(2) {
637 if let Some(edge) = self.graph.find_edge(window[0], window[1]) {
638 if let Some(weight) = self.graph.edge_weight(edge) {
639 pieces.push((weight.name.clone(), weight.distance_m));
640 }
641 }
642 }
643 pieces.push((to_edge.name.clone(), end_entry.distance_m));
644
645 Ok(RouteResult {
646 duration_seconds: total_cost.round() as i64,
647 distance_meters: distance,
648 geometry,
649 streets: merge_street_runs(pieces),
650 })
651 }
652 None => Err(RoutingError::NoPath {
653 from: from.original,
654 to: to.original,
655 }),
656 }
657 }
658
659 pub fn route_snapped(
664 &self,
665 from: &SnappedCoord,
666 to: &SnappedCoord,
667 ) -> Result<RouteResult, RoutingError> {
668 if from.node_index == to.node_index {
669 return Ok(RouteResult {
671 duration_seconds: 0,
672 distance_meters: 0.0,
673 geometry: vec![from.snapped, to.snapped],
674 streets: Vec::new(),
675 });
676 }
677
678 let result = astar(
679 &self.graph,
680 from.node_index,
681 |n| n == to.node_index,
682 |e| e.travel_time_s,
683 |n| self.time_lower_bound_between(n, to.node_index),
684 );
685
686 match result {
687 Some((cost, path)) => Ok(self.route_result_from_node_path(&path, cost.round() as i64)),
688 None => Err(RoutingError::NoPath {
689 from: from.original,
690 to: to.original,
691 }),
692 }
693 }
694
695 pub fn route_with(
700 &self,
701 from: Coord,
702 to: Coord,
703 objective: Objective,
704 ) -> Result<RouteResult, RoutingError> {
705 let start_snap = self.snap_to_road_detailed(from)?;
706 let end_snap = self.snap_to_road_detailed(to)?;
707
708 if start_snap.node_index == end_snap.node_index {
709 return Ok(RouteResult {
710 duration_seconds: 0,
711 distance_meters: 0.0,
712 geometry: vec![start_snap.snapped, end_snap.snapped],
713 streets: Vec::new(),
714 });
715 }
716
717 let result = match objective {
718 Objective::Time => astar(
719 &self.graph,
720 start_snap.node_index,
721 |n| n == end_snap.node_index,
722 |e| e.travel_time_s,
723 |n| self.time_lower_bound_between(n, end_snap.node_index),
724 ),
725 Objective::Distance => astar(
726 &self.graph,
727 start_snap.node_index,
728 |n| n == end_snap.node_index,
729 |e| e.distance_m,
730 |n| self.distance_lower_bound_between(n, end_snap.node_index),
731 ),
732 };
733
734 match result {
735 Some((_, path)) => {
736 let (distance, time) = self.node_path_metrics(&path);
737 Ok(RouteResult {
738 duration_seconds: time.round() as i64,
739 distance_meters: distance,
740 geometry: self.node_path_geometry(&path),
741 streets: merge_street_runs(path.windows(2).map(|window| {
742 self.graph
743 .find_edge(window[0], window[1])
744 .and_then(|edge| self.graph.edge_weight(edge))
745 .map(|weight| (weight.name.clone(), weight.distance_m))
746 .unwrap_or((None, 0.0))
747 })),
748 })
749 }
750 None => Err(RoutingError::NoPath { from, to }),
751 }
752 }
753
754 pub fn node_count(&self) -> usize {
755 self.graph.node_count()
756 }
757
758 pub fn edge_count(&self) -> usize {
759 self.graph.edge_count()
760 }
761
762 pub fn strongly_connected_components(&self) -> usize {
763 kosaraju_scc(&self.graph).len()
764 }
765
766 pub fn largest_component_fraction(&self) -> f64 {
767 let sccs = kosaraju_scc(&self.graph);
768 if sccs.is_empty() {
769 return 0.0;
770 }
771 let largest = sccs.iter().map(|c| c.len()).max().unwrap_or(0);
772 let total = self.graph.node_count();
773 if total == 0 {
774 0.0
775 } else {
776 largest as f64 / total as f64
777 }
778 }
779
780 pub fn is_strongly_connected(&self) -> bool {
781 self.strongly_connected_components() == 1
782 }
783
784 pub fn filter_to_largest_scc(&mut self) {
786 let sccs = kosaraju_scc(&self.graph);
787 if sccs.len() <= 1 {
788 return; }
790
791 let largest_scc: HashSet<NodeIdx> = sccs
793 .into_iter()
794 .max_by_key(|scc| scc.len())
795 .unwrap_or_default()
796 .into_iter()
797 .collect();
798
799 self.graph.retain_nodes(|n, _| largest_scc.contains(&n));
801
802 self.build_spatial_index();
803 }
804}
805
806impl Default for RoadNetwork {
807 fn default() -> Self {
808 Self::new()
809 }
810}
811
812impl RoadNetwork {
813 pub fn from_test_data(nodes: &[(f64, f64)], edges: &[(usize, usize, f64, f64)]) -> Self {
833 let mut network = Self::new();
834
835 for &(lat, lng) in nodes {
837 network.add_node_at(lat, lng);
838 }
839
840 for &(from, to, time_s, dist_m) in edges {
842 network.add_edge_by_index(from, to, time_s, dist_m);
843 }
844
845 network.build_spatial_index();
847
848 network
849 }
850
851 pub fn from_test_data_named(
868 nodes: &[(f64, f64)],
869 edges: &[(usize, usize, f64, f64, &str)],
870 ) -> Self {
871 let mut network = Self::new();
872
873 for &(lat, lng) in nodes {
874 network.add_node_at(lat, lng);
875 }
876
877 for &(from, to, time_s, dist_m, name) in edges {
878 network.add_edge_named_by_index(from, to, time_s, dist_m, Some(name.to_string()));
879 }
880
881 network.build_spatial_index();
882
883 network
884 }
885}
886
887#[cfg(test)]
888#[path = "network_tests.rs"]
889mod tests;
890
891#[cfg(test)]
892#[path = "network_name_tests.rs"]
893mod name_tests;
894
895#[derive(Debug, Clone, Copy, PartialEq, Eq)]
896pub enum Objective {
897 Time,
898 Distance,
899}
900
901fn douglas_peucker(points: &[Coord], tolerance_m: f64) -> Vec<Coord> {
903 if points.len() <= 2 {
904 return points.to_vec();
905 }
906
907 let first = points[0];
908 let last = points[points.len() - 1];
909 let mut max_dist = 0.0;
910 let mut max_idx = 0;
911
912 for (i, point) in points.iter().enumerate().skip(1).take(points.len() - 2) {
913 let dist = perpendicular_distance(*point, first, last);
914 if dist > max_dist {
915 max_dist = dist;
916 max_idx = i;
917 }
918 }
919
920 if max_dist > tolerance_m {
921 let mut left = douglas_peucker(&points[..=max_idx], tolerance_m);
922 let right = douglas_peucker(&points[max_idx..], tolerance_m);
923
924 left.pop();
925 left.extend(right);
926 left
927 } else {
928 vec![first, last]
929 }
930}
931
932fn perpendicular_distance(point: Coord, line_start: Coord, line_end: Coord) -> f64 {
933 let dx = line_end.lng - line_start.lng;
934 let dy = line_end.lat - line_start.lat;
935
936 let line_length_sq = dx * dx + dy * dy;
937 if line_length_sq < f64::EPSILON {
938 return haversine_distance(point, line_start);
939 }
940
941 let t =
942 ((point.lng - line_start.lng) * dx + (point.lat - line_start.lat) * dy) / line_length_sq;
943 let t = t.clamp(0.0, 1.0);
944
945 let projected = Coord::new(line_start.lat + t * dy, line_start.lng + t * dx);
946
947 haversine_distance(point, projected)
948}