64 lines
1.5 KiB
Rust
64 lines
1.5 KiB
Rust
|
use bevy::prelude::*;
|
||
|
|
||
|
#[derive(Default, Debug, PartialEq)]
|
||
|
pub struct Polygon {
|
||
|
points: Vec<Vec2>,
|
||
|
finished: bool,
|
||
|
}
|
||
|
|
||
|
impl Polygon {
|
||
|
const PROXIMITY_THRESHOLD: f32 = 5.0;
|
||
|
|
||
|
pub fn add_point(&mut self, point: Vec2) -> bool {
|
||
|
debug_assert_eq!(self.finished, false);
|
||
|
|
||
|
// polygon must be at least an triangle
|
||
|
// and check if we can close up the polygon
|
||
|
if self.points.len() >= 3 && self.check_first_for_proximity(point) {
|
||
|
self.points.push(point);
|
||
|
self.finished = true;
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
// deny too close points
|
||
|
if !self.check_all_for_proximity(point) {
|
||
|
self.points.push(point);
|
||
|
}
|
||
|
|
||
|
false
|
||
|
}
|
||
|
|
||
|
pub fn finished(&self) -> bool {
|
||
|
self.finished
|
||
|
}
|
||
|
|
||
|
fn check_all_for_proximity(&self, point: Vec2) -> bool {
|
||
|
self.points
|
||
|
.iter()
|
||
|
.any(|p| p.distance(point) < Self::PROXIMITY_THRESHOLD)
|
||
|
}
|
||
|
|
||
|
fn check_first_for_proximity(&self, point: Vec2) -> bool {
|
||
|
debug_assert!(!self.points.is_empty());
|
||
|
|
||
|
self.points.first().unwrap().distance(point) < Self::PROXIMITY_THRESHOLD
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[derive(Resource, Default, Debug, PartialEq)]
|
||
|
pub struct ObjectInfos {
|
||
|
polygons: Vec<Polygon>,
|
||
|
}
|
||
|
|
||
|
impl ObjectInfos {
|
||
|
pub fn active_polygon(&mut self) -> Option<&mut Polygon> {
|
||
|
self.polygons.iter_mut().find(|polygon| !polygon.finished())
|
||
|
}
|
||
|
|
||
|
pub fn add_polygon(&mut self) -> &mut Polygon {
|
||
|
self.polygons.push(Polygon::default());
|
||
|
self.polygons.last_mut().unwrap()
|
||
|
}
|
||
|
}
|