aboutsummaryrefslogtreecommitdiff
path: root/src/shapes.rs
blob: bf408be22f7334af1f3a53e8fd29e3373e2cef4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use cairo::{Context, Error};
use std::f64::consts::PI;
use wmap_parser::Shape;

/// Draws a vertex shape at the given position
pub fn draw_vertex(
    context: &Context,
    shape: &Shape,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
) -> Result<(), Error> {
    match shape {
        Shape::Circle => draw_circle(context, x, y, width, height),
        Shape::Square => draw_square(context, x, y, width, height),
        Shape::Triangle => draw_triangle(context, x, y, width, height),
        Shape::X => draw_x(context, x, y, width, height),
    }
}

fn draw_circle(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    context.save()?;
    context.translate(x + width / 2.0, y + height / 2.0);
    context.scale(width / 2.0, height / 2.0);
    context.arc(0.0, 0.0, 1.0, 0.0, 2.0 * PI);
    context.restore()?;
    context.fill()?;
    Ok(())
}

fn draw_square(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    context.rectangle(x, y, width, height);
    context.fill()?;
    Ok(())
}

fn draw_triangle(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    context.move_to(x + width / 2.0, y);
    context.line_to(x + width, y + height);
    context.line_to(x, y + height);
    context.close_path();
    context.fill()?;
    Ok(())
}

fn draw_x(context: &Context, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    let line_width = 2.0;
    context.set_line_width(line_width);
    context.move_to(x, y);
    context.line_to(x + width, y + height);
    context.move_to(x + width, y);
    context.line_to(x, y + height);
    context.stroke()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use cairo::{Context, Format, ImageSurface};

    #[test]
    fn test_draw_shapes() {
        // Just verify the functions don't panic
        let surface = ImageSurface::create(Format::Rgb24, 100, 100).unwrap();
        let context = Context::new(&surface).unwrap();

        assert!(draw_vertex(&context, &Shape::Circle, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&context, &Shape::Square, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&context, &Shape::Triangle, 0.0, 0.0, 25.0, 25.0).is_ok());
        assert!(draw_vertex(&context, &Shape::X, 0.0, 0.0, 25.0, 25.0).is_ok());
    }
}