diff --git a/examples/raytracer/include/rt_image.h b/examples/raytracer/include/rt_image.h new file mode 100644 index 0000000..3861073 --- /dev/null +++ b/examples/raytracer/include/rt_image.h @@ -0,0 +1,26 @@ +#ifndef RT_IMAGE_H +#define RT_IMAGE_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + int width, height; + unsigned char *rgb; +} image; + +image *image_new(int width, int height); +void image_free(image *im); + +/* Both return 0 on success. */ +int image_write_ppm(const image *im, const char *path); +int image_write_png(const image *im, const char *path); + +const char *image_default_extension(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/examples/raytracer/src/image/image.c b/examples/raytracer/src/image/image.c new file mode 100644 index 0000000..f257d73 --- /dev/null +++ b/examples/raytracer/src/image/image.c @@ -0,0 +1,31 @@ +#include "rt_config.h" +#include "rt_image.h" +#include + +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 +} diff --git a/examples/raytracer/src/image/ppm.c b/examples/raytracer/src/image/ppm.c new file mode 100644 index 0000000..839b056 --- /dev/null +++ b/examples/raytracer/src/image/ppm.c @@ -0,0 +1,13 @@ +#include "rt_image.h" +#include + +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; +}