servicepoint-binding-uniffi/servicepoint2/src/pixel_grid.rs

86 lines
2.3 KiB
Rust
Raw Normal View History

2024-05-10 01:35:24 +02:00
use crate::{BitVec, PIXEL_HEIGHT, PIXEL_WIDTH};
2024-05-09 23:30:18 +02:00
2024-05-12 01:30:55 +02:00
/// A grid of pixels stored in packed bytes.
2024-05-10 01:35:24 +02:00
#[derive(Debug, Clone)]
2024-05-09 23:30:18 +02:00
pub struct PixelGrid {
2024-05-12 01:30:55 +02:00
/// the width in pixels
2024-05-09 23:30:18 +02:00
pub width: usize,
2024-05-12 01:30:55 +02:00
/// the height in pixels
2024-05-09 23:30:18 +02:00
pub height: usize,
bit_vec: BitVec,
}
impl PixelGrid {
2024-05-12 01:30:55 +02:00
/// Creates a new pixel grid with the specified dimensions.
///
/// # Arguments
///
/// * `width`: size in pixels in x-direction
/// * `height`: size in pixels in y-direction
///
/// returns: PixelGrid initialized to all pixels off
///
/// # Panics
///
/// - when the width is not dividable by 8
2024-05-10 01:35:24 +02:00
pub fn new(width: usize, height: usize) -> Self {
2024-05-09 23:30:18 +02:00
assert_eq!(width % 8, 0);
Self {
width,
height,
bit_vec: BitVec::new(width * height),
}
}
2024-05-12 01:30:55 +02:00
/// Creates a new pixel grid with the size of the whole screen.
2024-05-10 01:35:24 +02:00
pub fn max_sized() -> Self {
Self::new(PIXEL_WIDTH as usize, PIXEL_HEIGHT as usize)
}
2024-05-12 01:30:55 +02:00
/// Loads a pixel grid with the specified dimensions from the provided data.
///
/// # Arguments
///
/// * `width`: size in pixels in x-direction
/// * `height`: size in pixels in y-direction
///
/// returns: PixelGrid that contains a copy of the provided data
///
/// # Panics
///
/// - when the dimensions and data size do not match exactly.
/// - when the width is not dividable by 8
pub fn load(width: usize, height: usize, data: &[u8]) -> Self {
assert_eq!(width % 8, 0);
assert_eq!(data.len(), height * width / 8);
Self {
width,
height,
2024-05-12 01:30:55 +02:00
bit_vec: BitVec::from(data),
}
}
2024-05-12 01:30:55 +02:00
/// Sets the byte value at the specified position
2024-05-09 23:30:18 +02:00
pub fn set(&mut self, x: usize, y: usize, value: bool) -> bool {
self.bit_vec.set(x + y * self.width, value)
}
2024-05-12 01:30:55 +02:00
/// Get the current value at the specified position
///
/// returns: current pixel value
2024-05-09 23:30:18 +02:00
pub fn get(&self, x: usize, y: usize) -> bool {
self.bit_vec.get(x + y * self.width)
}
2024-05-10 12:24:07 +02:00
2024-05-12 01:30:55 +02:00
/// Sets all pixels in the grid to the specified value
2024-05-10 12:24:07 +02:00
pub fn fill(&mut self, value: bool) {
self.bit_vec.fill(value);
}
2024-05-09 23:30:18 +02:00
}
2024-05-10 00:53:12 +02:00
impl Into<Vec<u8>> for PixelGrid {
fn into(self) -> Vec<u8> {
self.bit_vec.into()
2024-05-09 23:30:18 +02:00
}
}