feat(examples): add the image buffer and a PPM writer

RGB framebuffer with tone mapping, and PPM output for the path where zlib is
unavailable.
This commit is contained in:
milner committed 2022-07-04 09:14:34 +00:00
1 parent 13409a1e8b
commit a1173c73b6
3 files changed
+70

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
#include "rt_config.h"
#include "rt_image.h"
#include <stdlib.h>
image *image_new(int width, int height) {
if (width <= 0 || height <= 0) return NULL;
image *im = (image *)malloc(sizeof *im);
if (!im) return NULL;
im->width = width;
im->height = height;
im->rgb = (unsigned char *)calloc((size_t)width * (size_t)height * 3u, 1u);
if (!im->rgb) {
free(im);
return NULL;
}
return im;
}
void image_free(image *im) {
if (!im) return;
free(im->rgb);
free(im);
}
const char *image_default_extension(void) {
#ifdef HAVE_ZLIB
return "png";
#else
return "ppm";
#endif
}
+13
View File
@@ -0,0 +1,13 @@
#include "rt_image.h"
#include <stdio.h>
int image_write_ppm(const image *im, const char *path) {
if (!im || !path) return -1;
FILE *f = fopen(path, "wb");
if (!f) return -1;
fprintf(f, "P6\n%d %d\n255\n", im->width, im->height);
size_t n = (size_t)im->width * (size_t)im->height * 3u;
int ok = fwrite(im->rgb, 1u, n, f) == n;
return (fclose(f) == 0 && ok) ? 0 : -1;
}