use crate::color::Color;
use glium::texture::{ClientFormat, RawImage2d, Texture2dDataSource};
use std::{
borrow::Cow,
ops::{Deref, DerefMut, Index, IndexMut},
};
pub struct Image {
width: usize,
height: usize,
pixels: Vec<Color>,
}
pub struct RC(pub usize, pub usize);
pub struct XY(pub usize, pub usize);
impl Image {
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
pub fn new(width: usize, height: usize) -> Image {
Image {
width,
height,
pixels: vec![Color { r: 0, g: 0, b: 0 }; (width * height) as usize],
}
}
pub fn fill(&mut self, color: Color) {
for pix in &mut self.pixels {
*pix = color;
}
}
}
impl Index<RC> for Image {
type Output = Color;
fn index(&self, RC(row, col): RC) -> &Self::Output {
&self.pixels[(row * self.width + col) as usize]
}
}
impl IndexMut<RC> for Image {
fn index_mut(&mut self, RC(row, col): RC) -> &mut Self::Output {
&mut self.pixels[(row * self.width + col) as usize]
}
}
impl Index<XY> for Image {
type Output = Color;
fn index(&self, XY(x, y): XY) -> &Self::Output {
&self.pixels[(y * self.width + x) as usize]
}
}
impl IndexMut<XY> for Image {
fn index_mut(&mut self, XY(x, y): XY) -> &mut Self::Output {
&mut self.pixels[(y * self.width + x) as usize]
}
}
impl Deref for Image {
type Target = [Color];
fn deref(&self) -> &Self::Target {
&self.pixels
}
}
impl DerefMut for Image {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.pixels
}
}
impl<'a> Texture2dDataSource<'a> for &'a Image {
type Data = u8;
fn into_raw(self) -> RawImage2d<'a, Self::Data> {
RawImage2d {
data: Cow::Borrowed(unsafe {
std::slice::from_raw_parts(self.pixels.as_ptr() as *const u8, self.pixels.len() * 3)
}),
width: self.width as u32,
height: self.height as u32,
format: ClientFormat::U8U8U8,
}
}
}