aboutsummaryrefslogtreecommitdiff
path: root/src/patterns.rs
blob: 12c790aa6493b66566af1050f3dcf42fae7ad369 (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
75
76
77
use crate::utils::parse_color;

/// 8x8 1-bit pattern data
/// 0 = foreground color, 1 = background color
pub const STITCH: [u8; 64] = [
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1,
];

pub const SHINGLES: [u8; 64] = [
    1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0,
    0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1,
];

pub const SHADOW_GRID: [u8; 64] = [
    1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0,
    0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0,
];

pub const WICKER: [u8; 64] = [
    0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0,
    0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0,
];

/// Creates a cairo surface pattern from pattern data
pub fn create_pattern(
    pattern_data: &[u8; 64],
    foreground: &str,
    background: &str,
) -> Result<cairo::SurfacePattern, cairo::Error> {
    let surface = cairo::ImageSurface::create(cairo::Format::Rgb24, 8, 8)?;

    {
        let ctx = cairo::Context::new(&surface)?;
        let fg = parse_color(foreground);
        let bg = parse_color(background);

        for y in 0..8 {
            for x in 0..8 {
                let value = pattern_data[y * 8 + x];
                let (r, g, b) = if value == 0 { fg } else { bg };

                ctx.set_source_rgb(r, g, b);
                ctx.rectangle(x as f64, y as f64, 1.0, 1.0);
                ctx.fill()?;
            }
        }
    }

    let pattern = cairo::SurfacePattern::create(&surface);
    pattern.set_extend(cairo::Extend::Repeat);
    Ok(pattern)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pattern_data_lengths() {
        assert_eq!(STITCH.len(), 64);
        assert_eq!(SHINGLES.len(), 64);
        assert_eq!(SHADOW_GRID.len(), 64);
        assert_eq!(WICKER.len(), 64);
    }

    #[test]
    fn test_pattern_values() {
        // All pattern values should be 0 or 1
        for &val in &STITCH {
            assert!(val == 0 || val == 1);
        }
        for &val in &SHINGLES {
            assert!(val == 0 || val == 1);
        }
    }
}