buffer.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #ifndef BUFFER_H
  2. #define BUFFER_H
  3. // ===============================
  4. // AUTHOR : Angel Ortiz (angelo12 AT vt DOT edu)
  5. // CREATE DATE : 2018-07-10
  6. // PURPOSE : Buffer template used as render targets for the software renderer
  7. // ===============================
  8. #include "SDL.h"
  9. #include <cstring>
  10. #include <type_traits>
  11. #include <string.h>
  12. //Templated struct to emulate GPU buffers such as
  13. //the frame buffer and the ZBuffer
  14. //Also keeps track of a bunch of useful data about itself
  15. template<class T>
  16. struct Buffer{
  17. int mWidth, mHeight, mPixelCount, mPitch, mOrigin;
  18. T *buffer;
  19. //The buffer is actually just a simple 1D array which we access using an equation
  20. //Notice how it's not the usual (y*width + x) equation that you see for most quasi 2D arrays
  21. //This is because the origin is at the lower left (instead of upper left) and y moves upwards
  22. T& operator()(size_t x, size_t y){
  23. return buffer[mOrigin + -y*mWidth + x];
  24. }
  25. Buffer(int w, int h, T * array)
  26. : mWidth(w), mHeight(h), mPixelCount(w*h), mPitch(w*sizeof(T)),
  27. mOrigin(mHeight*mWidth - mWidth), buffer(array){}
  28. ~Buffer(){delete [] buffer;}
  29. //Cannot use memset to clear a float since the binary
  30. //Representation is more complex. We just iterate through the whole
  31. //thing and explicitely set it to zero instead
  32. void clear(){
  33. if(std::is_same<T,float>::value){
  34. for(int i = 0; i < mPixelCount;++i){
  35. buffer[i] = 0.0f;
  36. }
  37. }
  38. else{
  39. //Set to a 15% white color to make it nicer looking.
  40. std::memset(buffer,0xD, mPitch*mHeight);
  41. }
  42. }
  43. };
  44. #endif