canvas.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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(const Canvas &b)
  21. {
  22. this->width = b.width;
  23. this->height = b.height;
  24. this->stride = b.stride;
  25. this->bitmap = (uint8_t *)calloc(4, b.width * b.height);
  26. memcpy(this->bitmap, b.bitmap, 4 * b.width * b.height);
  27. }
  28. Canvas::Canvas(const Canvas *b)
  29. {
  30. this->width = b->width;
  31. this->height = b->height;
  32. this->stride = b->stride;
  33. this->bitmap = (uint8_t *)calloc(4, b->width * b->height);
  34. memcpy(this->bitmap, b->bitmap, 4 * b->width * b->height);
  35. }
  36. Canvas::~Canvas()
  37. {
  38. if (this->bitmap != nullptr)
  39. {
  40. free(this->bitmap);
  41. }
  42. }
  43. void Canvas::putPixel(uint32_t x, uint32_t y, Tuple colour)
  44. {
  45. uint32_t offset = y * this->stride + x * BytePP;
  46. this->bitmap[offset + 0] = MAX(MIN(colour.x * 255, 255), 0);
  47. this->bitmap[offset + 1] = MAX(MIN(colour.y * 255, 255), 0);
  48. this->bitmap[offset + 2] = MAX(MIN(colour.z * 255, 255), 0);
  49. }
  50. Colour Canvas::getPixel(uint32_t x, uint32_t y)
  51. {
  52. uint32_t offset = y * this->stride + x * BytePP;
  53. return Colour(this->bitmap[offset + 0] / 255.0, this->bitmap[offset + 1] / 255.0, this->bitmap[offset + 2] / 255.0);
  54. }
  55. bool Canvas::SaveAsPNG(const char *filename)
  56. {
  57. uint32_t ret = lodepng_encode24_file(filename, this->bitmap, this->width, this->height);
  58. return ret == 0;
  59. }
  60. Canvas::Canvas(const char *pngfile)
  61. {
  62. uint32_t ret = lodepng_decode24_file(&this->bitmap, &this->width, &this->height, pngfile);
  63. if(ret){ printf("error %u: %s\n", ret, lodepng_error_text(ret));}
  64. printf("%p - %d - %d\n", this->bitmap, this->width, this->height);
  65. }