typer/
img_buffer.rs

1
2pub type ColorRGBA = [u8;4];
3
4pub struct ImgBuffer {
5	pub buffer: Vec<u8>,
6	pub width: usize,
7	pub height: usize,
8}
9
10
11pub struct ImgBufferRef<'a> {
12	pub buffer: &'a mut Vec<u8>,
13	pub width: usize,
14	pub height: usize,
15}
16
17pub trait ImgBufferTrait {
18	#[inline] fn get_pixel_mut(&mut self, x: usize, y: usize) -> &mut [u8];
19	#[inline] fn width(&self) -> usize;
20	#[inline] fn height(&self) -> usize;
21
22	fn blend_pixel (&mut self, x:usize ,y:usize, pixel: &[u8;4], v:f32) {
23		if 
24			x > self.width()-1 || 
25			y > self.height()-1
26				{return}
27
28		let o_pixel = self.get_pixel_mut(x, y);
29		let f_pixel = [
30			pixel[0] as f32 / 255.0,
31			pixel[1] as f32 / 255.0,
32			pixel[2] as f32 / 255.0,
33			pixel[3] as f32 / 255.0,
34		];
35		let alpha = f_pixel[3] * v;
36		let o_alpha = o_pixel[3] as f32 / 255.0;
37
38		o_pixel[0] = ((((o_pixel[0] as f32 / 255.0) * (1.0-alpha)) + (f_pixel[0]*alpha)) * 255.0) as u8;
39		o_pixel[1] = ((((o_pixel[1] as f32 / 255.0) * (1.0-alpha)) + (f_pixel[1]*alpha)) * 255.0) as u8;
40		o_pixel[2] = ((((o_pixel[2] as f32 / 255.0) * (1.0-alpha)) + (f_pixel[2]*alpha)) * 255.0) as u8;
41		o_pixel[3] = ( (alpha * v).max(o_alpha) * 255.0 ) as u8;
42	}
43
44	fn put_pixel(&mut self, x:usize ,y:usize, pixel: &[u8;4]) {
45		let o_pixel = self.get_pixel_mut(x, y);
46		o_pixel[0] = pixel[0];
47		o_pixel[1] = pixel[1];
48		o_pixel[2] = pixel[2];
49		o_pixel[3] = pixel[3];
50	}
51
52	fn clear(&mut self, color: &[u8;4]);
53}
54
55impl ImgBuffer {
56	pub fn new(width:usize, height:usize, fill: &[u8; 4]) -> Self {
57		let capacity = width * height * 4;
58		let mut buffer: Vec<u8> = Vec::with_capacity(capacity);
59
60		for _ in 0..width * height {
61			buffer.extend_from_slice(fill);
62		}
63
64		Self {
65			width,
66			height,
67			buffer,
68		}
69	}
70}
71
72impl ImgBufferTrait for ImgBuffer {
73
74	#[inline] fn width(&self) -> usize {self.width}
75	#[inline] fn height(&self) -> usize {self.height}
76	#[inline] fn get_pixel_mut(&mut self, x: usize, y: usize) -> &mut [u8] {
77		let i =  y * (self.width*4) + (x * 4);
78		&mut self.buffer[i..(i+4)]
79	}
80
81	fn clear(&mut self, color: &[u8;4]) {
82		for i in 0..self.buffer.len() {
83			self.buffer[i] = color[i%4];
84		}
85	}
86}
87
88
89impl <'a> ImgBufferRef<'a> {
90	pub fn new(width:usize, height:usize, buffer: &'a mut Vec<u8>) -> Self {
91		Self {
92			width,
93			height,
94			buffer,
95		}
96	}	
97}
98
99
100impl <'a> ImgBufferTrait for ImgBufferRef<'a> {
101	
102	#[inline] 
103	fn width(&self) -> usize {self.width}
104	#[inline] 
105	fn height(&self) -> usize {self.height}
106	#[inline]
107	fn get_pixel_mut(&mut self, x: usize, y: usize) -> &mut [u8] {
108		let i =  y * (self.width*4) + (x * 4);
109		&mut self.buffer[i..(i+4)]
110	}
111	
112	fn clear(&mut self, color: &[u8;4]) {
113		for i in 0..self.buffer.len() {
114			self.buffer[i] = color[i%4];
115		}
116	}
117}