// most of this module was written out of frustration // TODO: make all this less messy use sdl2::{pixels::Color, rect::Point, render::Canvas, video::Window}; use crate::{consts::colors::*, rect}; #[derive(Debug, Copy, Clone)] pub enum GridKind { Rectangle, Isometric, } pub struct Grid { pub enabled: bool, pub color: Color, pub kind: GridKind, } impl Grid { pub fn new() -> Self { Self { enabled: true, color: GRID_COLOR, kind: GridKind::Rectangle, } } pub fn draw( &self, canvas: &mut Canvas, zoom: u8, start: &Point, width: u32, height: u32, ) { let cs = zoom as u32; let (x, y) = (start.x(), start.y()); canvas.set_draw_color(self.color); match self.kind { GridKind::Rectangle => { let mut vertical_tuples = (1..width) .map(|i| { let x = (i * cs) as i32; let y = (height * cs) as i32; if i % 2 == 0 { (*start + Point::new(x, 0), *start + Point::new(x, y)) } else { (*start + Point::new(x, y), *start + Point::new(x, 0)) } }) .collect::>(); // SAFETY // The mem space occupied by a [(T, T); N] is the same as twice the mem space of a // [T; 2 * N], where T is not a dynamically sized type. let verticals: Vec = unsafe { vertical_tuples.set_len(vertical_tuples.len() * 2); std::mem::transmute(vertical_tuples) }; let mut horizontal_tuples = (1..height) .map(|j| { let x = (width * cs) as i32; let y = (j * cs) as i32; if j % 2 == 0 { (*start + Point::new(0, y), *start + Point::new(x, y)) } else { (*start + Point::new(x, y), *start + Point::new(0, y)) } }) .collect::>(); let horizontals: Vec = unsafe { horizontal_tuples.set_len(horizontal_tuples.len() * 2); std::mem::transmute(horizontal_tuples) }; canvas.draw_lines(&verticals[..]).unwrap(); canvas.draw_lines(&horizontals[..]).unwrap(); } GridKind::Isometric => { canvas.set_clip_rect(Some(rect!(x, y, width * cs, height * cs))); for i in (0..2 * height + width).step_by(2) { let begin = ((i * cs) as i32, 0i32); let end = (0i32, (i * cs) as i32 / 2); canvas .draw_line(*start + begin.into(), *start + end.into()) .unwrap(); let begin_m = ((i as i32 - 2 * height as i32) * cs as i32, 0i32); let end_m = ( (width * cs) as i32, ((width + 2 * height - i) * cs) as i32 / 2, ); canvas .draw_line(*start + begin_m.into(), *start + end_m.into()) .unwrap(); } canvas.set_clip_rect(None); } } } }