use crate::mechanics::spatial::policies::DistancePolicy;
use crate::mechanics::spatial::types::{NodeId, SpatialGraph};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FixedDistance;
impl DistancePolicy for FixedDistance {
fn calculate_distance(&self, graph: &SpatialGraph, from: &NodeId, to: &NodeId) -> Option<f32> {
if from == to {
return Some(0.0);
}
let has_edge = graph.outgoing_edges(from).any(|e| &e.to == to)
|| graph
.incoming_edges(from)
.any(|e| &e.from == to && e.bidirectional);
if has_edge {
Some(1.0)
} else {
None
}
}
fn movement_cost(&self, graph: &SpatialGraph, from: &NodeId, to: &NodeId) -> Option<f32> {
let has_edge = graph.outgoing_edges(from).any(|e| &e.to == to)
|| graph
.incoming_edges(from)
.any(|e| &e.from == to && e.bidirectional);
if has_edge {
Some(1.0)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mechanics::spatial::types::{NodeType, SpatialEdge, SpatialNode};
#[test]
fn test_same_node() {
let graph = SpatialGraph::new();
let distance = FixedDistance;
let dist = distance.calculate_distance(&graph, &"A".to_string(), &"A".to_string());
assert_eq!(dist, Some(0.0));
}
#[test]
fn test_adjacent_nodes() {
let mut graph = SpatialGraph::new();
graph.add_node(SpatialNode::new("A", NodeType::City));
graph.add_node(SpatialNode::new("B", NodeType::City));
graph.add_edge(SpatialEdge::new("A", "B", 42.0));
let distance = FixedDistance;
let dist = distance.calculate_distance(&graph, &"A".to_string(), &"B".to_string());
assert_eq!(dist, Some(1.0));
let cost = distance.movement_cost(&graph, &"A".to_string(), &"B".to_string());
assert_eq!(cost, Some(1.0));
}
#[test]
fn test_not_connected() {
let mut graph = SpatialGraph::new();
graph.add_node(SpatialNode::new("A", NodeType::City));
graph.add_node(SpatialNode::new("B", NodeType::City));
let distance = FixedDistance;
let dist = distance.calculate_distance(&graph, &"A".to_string(), &"B".to_string());
assert_eq!(dist, None);
}
#[test]
fn test_bidirectional() {
let mut graph = SpatialGraph::new();
graph.add_node(SpatialNode::new("A", NodeType::City));
graph.add_node(SpatialNode::new("B", NodeType::City));
graph.add_edge(SpatialEdge::new_bidirectional("A", "B", 10.0));
let distance = FixedDistance;
let dist_ab = distance.calculate_distance(&graph, &"A".to_string(), &"B".to_string());
let dist_ba = distance.calculate_distance(&graph, &"B".to_string(), &"A".to_string());
assert_eq!(dist_ab, Some(1.0));
assert_eq!(dist_ba, Some(1.0));
}
}