canvas.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Canvas implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <canvas.h>
  10. #include <lodepng.h>
  11. #define BPP (24)
  12. #define BytePP (BPP / 8)
  13. #define MIN(_a, _b) ((_a)<(_b)?(_a):(_b))
  14. #define MAX(_a, _b) ((_a)>(_b)?(_a):(_b))
  15. Canvas::Canvas(uint32_t width, uint32_t height) : width(width), height(height)
  16. {
  17. this->bitmap = (uint8_t *)calloc(4, width * height);
  18. this->stride = BytePP * width;
  19. }
  20. Canvas::~Canvas()
  21. {
  22. if (this->bitmap != nullptr)
  23. {
  24. free(this->bitmap);
  25. }
  26. }
  27. void Canvas::put_pixel(uint32_t x, uint32_t y, Colour c)
  28. {
  29. uint32_t offset = y * this->stride + x * BytePP;
  30. this->bitmap[offset + 0] = MAX(MIN(c.red() * 255, 255), 0);
  31. this->bitmap[offset + 1] = MAX(MIN(c.green() * 255, 255), 0);
  32. this->bitmap[offset + 2] = MAX(MIN(c.blue() * 255, 255), 0);
  33. }
  34. Colour Canvas::get_pixel(uint32_t x, uint32_t y)
  35. {
  36. uint32_t offset = y * this->stride + x * BytePP;
  37. return Colour(this->bitmap[offset + 0] / 255, this->bitmap[offset + 1] / 255, this->bitmap[offset + 2] / 255);
  38. }
  39. bool Canvas::SaveAsPNG(const char *filename)
  40. {
  41. uint32_t ret = lodepng_encode24_file(filename, this->bitmap, this->width, this->height);
  42. if (ret > 0)
  43. {
  44. printf("lodepng_encode_file returned %d!\n", ret);
  45. }
  46. return ret == 0;
  47. }