Skip to content

Commit

Permalink
Refactored circle generation logic in primitive meshes.
Browse files Browse the repository at this point in the history
  • Loading branch information
gibletfeets committed Mar 30, 2024
1 parent 19017ba commit 49ea8c8
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions crates/bevy_render/src/mesh/primitives/circle_iterator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::f32::consts::TAU;
use bevy_math::Vec2;


#[derive(Debug, Clone, Copy)]
pub (crate) struct CircleIterator {
count: usize,
theta: f32,
wrap: bool
}

impl CircleIterator {
pub (crate) fn new(count: usize, wrap: bool) -> CircleIterator {
if wrap {
Self {count: count+1, theta: -TAU/(count as f32), wrap }
} else {
Self {count: count, theta: -TAU/(count as f32), wrap }
}

}
}
impl Iterator for CircleIterator {
type Item = Vec2;
fn next(&mut self) -> Option<Self::Item> {


if self.count != 0 {
if self.wrap {
self.count -= 1;
Some(Vec2::new(
(self.theta*self.count as f32).cos(),
(self.theta*self.count as f32).sin()
))
} else {
let res = Some(Vec2::new(
(self.theta*self.count as f32).cos(),
(self.theta*self.count as f32).sin()
));
self.count -= 1;
res
}

} else {
None
}
}
}

mod tests {
use super::*;
#[test]
fn check_count() {
let vertices: Vec<Vec2> = CircleIterator::new(6, false).collect();
assert_eq!(vertices.len(), 6);
let vertices: Vec<Vec2> = CircleIterator::new(6, true).collect();
assert_eq!(vertices.len(), 7);
}

#[test]
fn check_distances() {
let epsilon = 0.00001;
let mut vertices : Vec<Vec2> = CircleIterator::new(6, true).collect();
let center = Vec2::new(0.0, 0.0);
let distances_center: Vec<f32> = vertices.iter().map(|x| center.distance(*x)).collect();
assert!(distances_center.windows(2).all(|w| (w[0] - w[1]).abs() < epsilon));
let distances_neighbors: Vec<f32> = vertices.windows(2).map(|w| w[0].distance(w[1])).collect();
assert!(distances_neighbors.windows(2).all(|w| (w[0] - w[1]).abs() < epsilon));
}
}

0 comments on commit 49ea8c8

Please sign in to comment.