82 lines
2.0 KiB
Rust
82 lines
2.0 KiB
Rust
|
|
#[derive(Copy, Clone)]
|
|
pub struct Cell {
|
|
// display coordinates of the cell
|
|
pub x : f32,
|
|
pub y : f32,
|
|
pub width : f32,
|
|
pub height : f32,
|
|
|
|
// position of the cell in the grid (0-based)
|
|
pub pos_x: u32,
|
|
pub pos_y: u32,
|
|
}
|
|
|
|
pub struct CellGrid {
|
|
// display coordinates of the grid
|
|
x: f32,
|
|
y: f32,
|
|
width: f32,
|
|
height: f32,
|
|
|
|
// size fo the grid, in number of cells
|
|
num_x: u32,
|
|
num_y: u32,
|
|
|
|
// current position when iterating
|
|
pos_x: u32,
|
|
pos_y: u32,
|
|
|
|
// current cell when iterating
|
|
curr: Cell,
|
|
}
|
|
|
|
impl CellGrid {
|
|
pub fn new(x: f32, y: f32, width: f32, height: f32, num_x: u32, num_y: u32) -> Self {
|
|
Self {
|
|
x,
|
|
y,
|
|
width,
|
|
height,
|
|
num_x,
|
|
num_y,
|
|
pos_x: 0,
|
|
pos_y: 0,
|
|
curr: Cell {x, y, width, height, pos_x: 0, pos_y: 0}
|
|
}
|
|
}
|
|
|
|
fn compute_cell(&mut self) -> () {
|
|
self.curr.pos_x = self.pos_x;
|
|
self.curr.pos_y = self.pos_y;
|
|
|
|
let beg_x: f32 = self.x + (self.width * self.curr.pos_x as f32) / self.num_x as f32;
|
|
let end_x: f32 = self.x + (self.width * (self.curr.pos_x + 1) as f32) / self.num_x as f32;
|
|
self.curr.x = beg_x.trunc();
|
|
self.curr.width = end_x.trunc() - self.curr.x;
|
|
|
|
let beg_y: f32 = self.y + (self.height * self.curr.pos_y as f32) / self.num_y as f32;
|
|
let end_y: f32 = self.y + (self.height * (self.curr.pos_y + 1) as f32) / self.num_y as f32;
|
|
self.curr.y = beg_y.trunc();
|
|
self.curr.height = end_y.trunc() - self.curr.y;
|
|
}
|
|
}
|
|
|
|
impl Iterator for CellGrid {
|
|
type Item = Cell;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
if self.pos_y >= self.num_y {
|
|
None
|
|
} else {
|
|
self.compute_cell();
|
|
|
|
self.pos_x += 1;
|
|
if self.pos_x >= self.num_x {
|
|
self.pos_x = 0;
|
|
self.pos_y += 1;
|
|
}
|
|
Some(self.curr)
|
|
}
|
|
}
|
|
} |