1use crate::Framebuffer;
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum ImageRegionError {
17 InvalidDimensions,
19 OutOfBounds,
21 InvalidStride,
23 LayoutOverflow,
25 SourceTooShort {
27 required: usize,
29 actual: usize,
31 },
32}
33
34impl std::fmt::Display for ImageRegionError {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 match self {
37 Self::InvalidDimensions => f.write_str("invalid image region dimensions"),
38 Self::OutOfBounds => f.write_str("image region is outside the framebuffer"),
39 Self::InvalidStride => {
40 f.write_str("image region source stride is smaller than its width")
41 }
42 Self::LayoutOverflow => f.write_str("image region source layout overflows usize"),
43 Self::SourceTooShort { required, actual } => write!(
44 f,
45 "image region needs {required} source pixels, but only {actual} are available"
46 ),
47 }
48 }
49}
50
51impl std::error::Error for ImageRegionError {}
52
53impl Framebuffer {
54 pub fn crop(&self, x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageRegionError> {
81 self.validate_region(x, y, width, height)?;
82 let mut cropped =
84 Self::new(width, height).map_err(|_| ImageRegionError::InvalidDimensions)?;
85 let stride = self.width() as usize;
86 let start = y as usize * stride + x as usize;
87 cropped.blit_rgba(0, 0, width, height, &self.pixels()[start..], stride)?;
88 Ok(cropped)
89 }
90
91 pub fn blit_rgba(
127 &mut self,
128 x: u32,
129 y: u32,
130 width: u32,
131 height: u32,
132 source: &[[u8; 4]],
133 source_stride: usize,
134 ) -> Result<(), ImageRegionError> {
135 self.validate_region(x, y, width, height)?;
136 let width = width as usize;
137 let height = height as usize;
138 if source_stride < width {
139 return Err(ImageRegionError::InvalidStride);
140 }
141 let required = (height - 1)
142 .checked_mul(source_stride)
143 .and_then(|offset| offset.checked_add(width))
144 .ok_or(ImageRegionError::LayoutOverflow)?;
145 if source.len() < required {
146 return Err(ImageRegionError::SourceTooShort {
147 required,
148 actual: source.len(),
149 });
150 }
151
152 let destination_stride = self.width() as usize;
153 let destination_start = y as usize * destination_stride + x as usize;
154 let destination = self.pixels_mut();
155 for row in 0..height {
156 let src = row * source_stride;
158 let dst = destination_start + row * destination_stride;
159 destination[dst..dst + width].copy_from_slice(&source[src..src + width]);
160 }
161 Ok(())
162 }
163
164 fn validate_region(
165 &self,
166 x: u32,
167 y: u32,
168 width: u32,
169 height: u32,
170 ) -> Result<(), ImageRegionError> {
171 if width == 0 || height == 0 {
172 return Err(ImageRegionError::InvalidDimensions);
173 }
174 if x > self.width()
176 || y > self.height()
177 || width > self.width() - x
178 || height > self.height() - y
179 {
180 return Err(ImageRegionError::OutOfBounds);
181 }
182 Ok(())
183 }
184
185 pub fn to_ppm(&self) -> Vec<u8> {
187 let mut output = format!("P6\n{} {}\n255\n", self.width, self.height).into_bytes();
188 output.reserve(self.pixels().len() * 3);
189 for pixel in self.pixels() {
190 output.extend_from_slice(&pixel[..3]);
191 }
192 output
193 }
194 pub fn to_png(&self) -> Vec<u8> {
197 let width = self.width as usize;
198 let height = self.height as usize;
199 let row_bytes = width * 4;
200 let filtered_len = row_bytes * height + height;
201 let block_count = filtered_len.div_ceil(65535);
202 let zlib_len = 2 + filtered_len + block_count * 5 + 4;
203 let mut output = Vec::with_capacity(8 + 25 + 12 + zlib_len + 12);
205 output.extend_from_slice(b"\x89PNG\r\n\x1a\n");
206 let mut header = [0_u8; 13];
207 header[0..4].copy_from_slice(&self.width.to_be_bytes());
208 header[4..8].copy_from_slice(&self.height.to_be_bytes());
209 header[8..13].copy_from_slice(&[8, 6, 0, 0, 0]);
210 chunk(&mut output, b"IHDR", &header);
211
212 output.extend_from_slice(&(zlib_len as u32).to_be_bytes());
215 let idat_start = output.len();
216 output.extend_from_slice(b"IDAT");
217 output.extend_from_slice(&[0x78, 0x01]);
218
219 let mut adler_a = 1_u32;
220 let mut adler_b = 0_u32;
221 let mut remaining_total = filtered_len;
222 let mut block_rem = 0_usize;
223 let pixels = self.pixels();
224 for row in pixels.chunks_exact(width) {
225 let raw = row.as_flattened();
226 let mut emit = |mut slice: &[u8]| {
228 adler32_update(&mut adler_a, &mut adler_b, slice);
229 while !slice.is_empty() {
230 if block_rem == 0 {
231 let block_len = remaining_total.min(65535);
232 remaining_total -= block_len;
233 output.push(u8::from(remaining_total == 0));
234 let len16 = block_len as u16;
235 output.extend_from_slice(&len16.to_le_bytes());
236 output.extend_from_slice(&(!len16).to_le_bytes());
237 block_rem = block_len;
238 }
239 let take = slice.len().min(block_rem);
240 output.extend_from_slice(&slice[..take]);
241 slice = &slice[take..];
242 block_rem -= take;
243 }
244 };
245 emit(&[0]);
246 emit(raw);
247 }
248 let adler = (adler_b << 16) | adler_a;
249 output.extend_from_slice(&adler.to_be_bytes());
250 let idat_crc = crc32_slice(&output[idat_start..]);
251 output.extend_from_slice(&idat_crc.to_be_bytes());
252 chunk(&mut output, b"IEND", &[]);
253 output
254 }
255 #[cfg(not(target_arch = "wasm32"))]
256 pub fn save_png(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
257 std::fs::write(path, self.to_png())
258 }
259 #[cfg(not(target_arch = "wasm32"))]
260 pub fn save_ppm(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
261 std::fs::write(path, self.to_ppm())
262 }
263}
264fn adler32_update(a: &mut u32, b: &mut u32, mut bytes: &[u8]) {
265 const NMAX: usize = 5552;
267 let mut s1 = *a;
268 let mut s2 = *b;
269 while !bytes.is_empty() {
270 let take = bytes.len().min(NMAX);
271 let (head, tail) = bytes.split_at(take);
272 let chunks = head.chunks_exact(16);
273 let rem = chunks.remainder();
274 for c in chunks {
275 for &byte in c {
276 s1 += u32::from(byte);
277 s2 += s1;
278 }
279 }
280 for &byte in rem {
281 s1 += u32::from(byte);
282 s2 += s1;
283 }
284 s1 %= 65521;
285 s2 %= 65521;
286 bytes = tail;
287 }
288 *a = s1;
289 *b = s2;
290}
291#[cfg(test)]
292fn adler32(bytes: &[u8]) -> u32 {
293 let (mut a, mut b) = (1_u32, 0_u32);
294 adler32_update(&mut a, &mut b, bytes);
295 (b << 16) | a
296}
297#[cfg(test)]
298fn crc32(bytes: impl Iterator<Item = u8>) -> u32 {
299 let mut crc = !0_u32;
300 for byte in bytes {
301 crc = (crc >> 8) ^ CRC32_TABLES[0][((crc ^ u32::from(byte)) & 0xff) as usize];
302 }
303 !crc
304}
305const CRC32_TABLES: [[u32; 256]; 8] = {
306 let mut tables = [[0_u32; 256]; 8];
307 let mut i = 0;
308 while i < 256 {
309 let mut c = i as u32;
310 let mut k = 0;
311 while k < 8 {
312 c = (c >> 1) ^ if c & 1 != 0 { 0xedb8_8320 } else { 0 };
313 k += 1;
314 }
315 tables[0][i] = c;
316 i += 1;
317 }
318 let mut t = 1;
319 while t < 8 {
320 let mut i = 0;
321 while i < 256 {
322 let prev = tables[t - 1][i];
323 tables[t][i] = (prev >> 8) ^ tables[0][(prev & 0xff) as usize];
324 i += 1;
325 }
326 t += 1;
327 }
328 tables
329};
330fn crc32_update(mut crc: u32, bytes: &[u8]) -> u32 {
331 let chunks = bytes.chunks_exact(8);
332 let rem = chunks.remainder();
333 for chunk in chunks {
334 let low = crc ^ u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
335 let high = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
336 crc = CRC32_TABLES[7][(low & 0xff) as usize]
337 ^ CRC32_TABLES[6][((low >> 8) & 0xff) as usize]
338 ^ CRC32_TABLES[5][((low >> 16) & 0xff) as usize]
339 ^ CRC32_TABLES[4][(low >> 24) as usize]
340 ^ CRC32_TABLES[3][(high & 0xff) as usize]
341 ^ CRC32_TABLES[2][((high >> 8) & 0xff) as usize]
342 ^ CRC32_TABLES[1][((high >> 16) & 0xff) as usize]
343 ^ CRC32_TABLES[0][(high >> 24) as usize];
344 }
345 for &byte in rem {
346 crc = (crc >> 8) ^ CRC32_TABLES[0][((crc ^ u32::from(byte)) & 0xff) as usize];
347 }
348 crc
349}
350fn crc32_slice(bytes: &[u8]) -> u32 {
351 !crc32_update(!0_u32, bytes)
352}
353fn chunk(output: &mut Vec<u8>, kind: &[u8; 4], bytes: &[u8]) {
354 output.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
355 output.extend_from_slice(kind);
356 output.extend_from_slice(bytes);
357 let crc = !crc32_update(crc32_update(!0_u32, kind), bytes);
358 output.extend_from_slice(&crc.to_be_bytes());
359}
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 fn patterned_frame(width: u32, height: u32) -> Framebuffer {
365 let mut frame = Framebuffer::new(width, height).unwrap();
366 for (i, pixel) in frame.pixels_mut().iter_mut().enumerate() {
367 *pixel = [i as u8, 255 - i as u8, i as u8 * 7, [0, 128, 255][i % 3]];
368 }
369 frame
370 }
371
372 fn rendered_frame() -> Framebuffer {
373 use crate::{
374 Camera, ClipDepth, Color, Mat4, Mesh, MeshCache, RenderItem, SoftwareRenderer,
375 };
376 use crate::{Vec3, Vertex, vec3};
377
378 let mut renderer = SoftwareRenderer::new(8, 8).unwrap();
379 let mut cache = MeshCache::new();
380 let mesh = cache
381 .insert(Mesh {
382 vertices: [
383 vec3(-0.8, -0.8, 0.5),
384 vec3(0.8, -0.8, 0.5),
385 vec3(0.0, 0.8, 0.5),
386 ]
387 .map(|position| Vertex::new(position, Vec3::Z, Color::new(1.0, 0.0, 0.0, 1.0)))
388 .to_vec(),
389 indices: vec![0, 1, 2],
390 })
391 .unwrap();
392 renderer
393 .render(
394 &cache,
395 &[RenderItem::new(mesh, Mat4::IDENTITY)],
396 Camera {
397 view_projection: Mat4::IDENTITY,
398 position: Vec3::ZERO,
399 clip_depth: ClipDepth::ZeroToOne,
400 },
401 )
402 .unwrap();
403 assert!(renderer.framebuffer.depths().iter().any(|d| d.is_finite()));
404 renderer.framebuffer
405 }
406
407 #[test]
408 fn crop_preserves_row_order_rgba_and_owns_its_pixels() {
409 let frame = patterned_frame(4, 3);
410 let before = frame.pixels().to_vec();
411 let depths = frame.depths().to_vec();
412 let mut cropped = frame.crop(1, 1, 2, 2).unwrap();
413 assert_eq!((cropped.width(), cropped.height()), (2, 2));
414 assert_eq!(
415 cropped.pixels(),
416 &[before[5], before[6], before[9], before[10]]
417 );
418 assert_eq!(cropped.depths(), &[f32::INFINITY; 4]);
419 cropped.pixels_mut().fill([255; 4]);
420 assert_eq!(frame.pixels(), before);
421 assert_eq!(frame.depths(), depths);
422 assert_eq!(frame.crop(0, 0, 4, 3).unwrap().pixels(), before);
423 assert_eq!(frame.crop(3, 2, 1, 1).unwrap().pixels(), &[before[11]]);
424 }
425
426 #[test]
427 fn crop_rejects_empty_outside_and_overflowing_rectangles() {
428 let frame = patterned_frame(4, 3);
429 let before = frame.pixels().to_vec();
430 for (x, y, width, height, error) in [
431 (0, 0, 0, 1, ImageRegionError::InvalidDimensions),
432 (0, 0, 1, 0, ImageRegionError::InvalidDimensions),
433 (4, 0, 1, 1, ImageRegionError::OutOfBounds),
434 (0, 3, 1, 1, ImageRegionError::OutOfBounds),
435 (3, 1, 2, 1, ImageRegionError::OutOfBounds),
436 (1, 2, 1, 2, ImageRegionError::OutOfBounds),
437 (u32::MAX, 0, 2, 1, ImageRegionError::OutOfBounds),
438 (0, u32::MAX, 1, 2, ImageRegionError::OutOfBounds),
439 (1, 0, u32::MAX, 1, ImageRegionError::OutOfBounds),
440 (0, 1, 1, u32::MAX, ImageRegionError::OutOfBounds),
441 ] {
442 assert_eq!(frame.crop(x, y, width, height).err(), Some(error));
443 assert_eq!(frame.pixels(), before);
444 }
445 }
446
447 #[test]
448 fn blit_skips_padding_and_copies_all_alpha_values_verbatim() {
449 let mut frame = patterned_frame(4, 3);
450 let before = frame.pixels().to_vec();
451 let transparent = [201, 102, 53, 0];
452 let translucent = [120, 60, 30, 128];
453 let opaque = [10, 20, 30, 255];
454 let padding = [99; 4];
455 let source = [
457 transparent,
458 translucent,
459 padding,
460 padding,
461 opaque,
462 transparent,
463 ];
464 frame.blit_rgba(2, 1, 2, 2, &source, 4).unwrap();
465 let mut expected = before;
466 expected[6..8].copy_from_slice(&source[..2]);
467 expected[10..12].copy_from_slice(&source[4..6]);
468 assert_eq!(frame.pixels(), expected);
469
470 let mut padded_source = source.to_vec();
472 padded_source.extend([padding; 3]);
473 frame.blit_rgba(2, 1, 2, 2, &padded_source, 4).unwrap();
474 assert_eq!(frame.pixels(), expected);
475 }
476
477 #[test]
478 fn region_operations_leave_rendered_depth_unchanged() {
479 let mut frame = rendered_frame();
480 let pixels = frame.pixels().to_vec();
481 let depths = frame.depths().to_vec();
482 let cropped = frame.crop(0, 0, 8, 8).unwrap();
483 assert_eq!(cropped.pixels(), pixels);
484 assert!(cropped.depths().iter().all(|&d| d == f32::INFINITY));
485 assert_eq!(frame.depths(), depths);
486
487 let replacement = [[111, 22, 3, 0]; 64];
488 frame.blit_rgba(0, 0, 8, 8, &replacement, 8).unwrap();
489 assert_eq!(frame.pixels(), replacement);
490 assert_eq!(frame.depths(), depths);
491 }
492
493 #[test]
494 fn blit_rejects_bad_bounds_stride_and_overflow_before_any_write() {
495 let mut frame = rendered_frame();
496 let pixels = frame.pixels().to_vec();
497 let depths = frame.depths().to_vec();
498 let source = [[42; 4]; 64];
499 for (x, y, width, height, stride, error) in [
500 (0, 0, 0, 1, 0, ImageRegionError::InvalidDimensions),
501 (0, 0, 1, 0, 0, ImageRegionError::InvalidDimensions),
502 (8, 0, 1, 1, 1, ImageRegionError::OutOfBounds),
503 (0, 8, 1, 1, 1, ImageRegionError::OutOfBounds),
504 (7, 0, 2, 1, 2, ImageRegionError::OutOfBounds),
505 (0, 7, 1, 2, 1, ImageRegionError::OutOfBounds),
506 (u32::MAX, 0, 2, 1, 2, ImageRegionError::OutOfBounds),
507 (0, u32::MAX, 1, 2, 1, ImageRegionError::OutOfBounds),
508 (1, 0, u32::MAX, 1, 2, ImageRegionError::OutOfBounds),
509 (0, 1, 1, u32::MAX, 1, ImageRegionError::OutOfBounds),
510 (0, 0, 2, 2, 1, ImageRegionError::InvalidStride),
511 (0, 0, 1, 1, 0, ImageRegionError::InvalidStride),
512 (0, 0, 1, 2, usize::MAX, ImageRegionError::LayoutOverflow),
513 (
514 0,
515 0,
516 1,
517 3,
518 usize::MAX / 2 + 1,
519 ImageRegionError::LayoutOverflow,
520 ),
521 ] {
522 assert_eq!(
523 frame.blit_rgba(x, y, width, height, &source, stride),
524 Err(error)
525 );
526 assert_eq!(frame.pixels(), pixels);
527 assert_eq!(frame.depths(), depths);
528 }
529 }
530
531 #[test]
532 fn blit_rejects_every_truncation_including_a_short_final_row_transactionally() {
533 let mut frame = rendered_frame();
534 let pixels = frame.pixels().to_vec();
535 let depths = frame.depths().to_vec();
536 let source = [[10, 20, 30, 0]; 5];
537 for end in 0..source.len() {
538 assert_eq!(
539 frame.blit_rgba(2, 1, 2, 2, &source[..end], 3),
540 Err(ImageRegionError::SourceTooShort {
541 required: 5,
542 actual: end,
543 })
544 );
545 assert_eq!(frame.pixels(), pixels);
546 assert_eq!(frame.depths(), depths);
547 }
548 frame.blit_rgba(2, 1, 2, 2, &source, 3).unwrap();
549 assert_eq!(frame.pixel(3, 2), Some(source[4]));
550 assert_eq!(frame.depths(), depths);
551 }
552
553 #[test]
554 fn single_row_blit_does_not_require_or_step_over_unused_stride() {
555 let mut frame = patterned_frame(4, 3);
556 let mut expected = frame.pixels().to_vec();
557 let source = [[90, 80, 70, 60], [50, 40, 30, 20]];
558 frame.blit_rgba(2, 2, 2, 1, &source, usize::MAX).unwrap();
559 expected[10..12].copy_from_slice(&source);
560 assert_eq!(frame.pixels(), expected);
561 }
562
563 #[test]
564 fn all_small_regions_match_per_pixel_crop_and_blit_reference() {
565 let source = patterned_frame(4, 3);
566 let background = [213, 127, 29, 65];
567 for sy in 0..source.height() {
568 for sx in 0..source.width() {
569 for height in 1..=source.height() - sy {
570 for width in 1..=source.width() - sx {
571 let cropped = source.crop(sx, sy, width, height).unwrap();
572 for y in 0..height {
573 for x in 0..width {
574 assert_eq!(cropped.pixel(x, y), source.pixel(sx + x, sy + y));
575 }
576 }
577 for dy in 0..=4 - height {
578 for dx in 0..=5 - width {
579 let mut destination = Framebuffer::new(5, 4).unwrap();
580 destination.pixels_mut().fill(background);
581 let offset = (sy * source.width() + sx) as usize;
582 destination
583 .blit_rgba(
584 dx,
585 dy,
586 width,
587 height,
588 &source.pixels()[offset..],
589 source.width() as usize,
590 )
591 .unwrap();
592 for y in 0..destination.height() {
593 for x in 0..destination.width() {
594 let expected = if x >= dx
595 && x < dx + width
596 && y >= dy
597 && y < dy + height
598 {
599 source.pixel(sx + x - dx, sy + y - dy)
600 } else {
601 Some(background)
602 };
603 assert_eq!(destination.pixel(x, y), expected);
604 }
605 }
606 }
607 }
608 }
609 }
610 }
611 }
612 }
613
614 #[test]
615 fn checksum_known_vectors() {
616 assert_eq!(crc32(b"123456789".iter().copied()), 0xcbf43926);
617 assert_eq!(adler32(b"Wikipedia"), 0x11e60398);
618 }
619}