diff options
Diffstat (limited to 'src/shapes.rs')
| -rw-r--r-- | src/shapes.rs | 95 |
1 files changed, 95 insertions, 0 deletions
diff --git a/src/shapes.rs b/src/shapes.rs new file mode 100644 index 0000000..2b8db2c --- /dev/null +++ b/src/shapes.rs @@ -0,0 +1,95 @@ +use wmap_parser::Shape; + +/// Draws a vertex shape at the given position +pub fn draw_vertex( + ctx: &cairo::Context, + shape: &Shape, + x: f64, + y: f64, + width: f64, + height: f64, +) -> Result<(), cairo::Error> { + match shape { + Shape::Circle => draw_circle(ctx, x, y, width, height), + Shape::Square => draw_square(ctx, x, y, width, height), + Shape::Triangle => draw_triangle(ctx, x, y, width, height), + Shape::X => draw_x(ctx, x, y, width, height), + } +} + +fn draw_circle( + ctx: &cairo::Context, + x: f64, + y: f64, + width: f64, + height: f64, +) -> Result<(), cairo::Error> { + ctx.save()?; + ctx.translate(x + width / 2.0, y + height / 2.0); + ctx.scale(width / 2.0, height / 2.0); + ctx.arc(0.0, 0.0, 1.0, 0.0, 2.0 * std::f64::consts::PI); + ctx.restore()?; + ctx.fill()?; + Ok(()) +} + +fn draw_square( + ctx: &cairo::Context, + x: f64, + y: f64, + width: f64, + height: f64, +) -> Result<(), cairo::Error> { + ctx.rectangle(x, y, width, height); + ctx.fill()?; + Ok(()) +} + +fn draw_triangle( + ctx: &cairo::Context, + x: f64, + y: f64, + width: f64, + height: f64, +) -> Result<(), cairo::Error> { + ctx.move_to(x + width / 2.0, y); + ctx.line_to(x + width, y + height); + ctx.line_to(x, y + height); + ctx.close_path(); + ctx.fill()?; + Ok(()) +} + +fn draw_x( + ctx: &cairo::Context, + x: f64, + y: f64, + width: f64, + height: f64, +) -> Result<(), cairo::Error> { + let line_width = 2.0; + ctx.set_line_width(line_width); + ctx.move_to(x, y); + ctx.line_to(x + width, y + height); + ctx.move_to(x + width, y); + ctx.line_to(x, y + height); + ctx.stroke()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_draw_shapes() { + // Just verify the functions don't panic + let surface = cairo::ImageSurface::create(cairo::Format::Rgb24, 100, 100).unwrap(); + let ctx = cairo::Context::new(&surface).unwrap(); + + assert!(draw_vertex(&ctx, &Shape::Circle, 0.0, 0.0, 25.0, 25.0).is_ok()); + assert!(draw_vertex(&ctx, &Shape::Square, 0.0, 0.0, 25.0, 25.0).is_ok()); + assert!(draw_vertex(&ctx, &Shape::Triangle, 0.0, 0.0, 25.0, 25.0).is_ok()); + assert!(draw_vertex(&ctx, &Shape::X, 0.0, 0.0, 25.0, 25.0).is_ok()); + } +} |