Advertisement
nbonneel

Template with Vector and stb_image

Jan 5th, 2023
1,215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <vector>
  3.  
  4. #define STB_IMAGE_WRITE_IMPLEMENTATION
  5. #include "stb_image_write.h"
  6.  
  7. #define STB_IMAGE_IMPLEMENTATION
  8. #include "stb_image.h"
  9.  
  10. static inline double sqr(double x) { return x * x; }
  11.  
  12. class Vector {
  13. public:
  14.     explicit Vector(double x = 0, double y = 0, double z = 0) {
  15.         coord[0] = x;
  16.         coord[1] = y;
  17.         coord[2] = z;
  18.     }
  19.     double& operator[](int i) { return coord[i]; }
  20.     double operator[](int i) const { return coord[i]; }
  21.  
  22.     Vector& operator+=(const Vector& v) {
  23.         coord[0] += v[0];
  24.         coord[1] += v[1];
  25.         coord[2] += v[2];
  26.         return *this;
  27.     }
  28.  
  29.     double norm2() const {
  30.         return sqr(coord[0]) + sqr(coord[1]) + sqr(coord[2]);
  31.     }
  32.  
  33.     double coord[3];
  34. };
  35.  
  36. Vector operator+(const Vector& a, const Vector& b) {
  37.     return Vector(a[0] + b[0], a[1] + b[1], a[2] + b[2]);
  38. }
  39. Vector operator-(const Vector& a, const Vector& b) {
  40.     return Vector(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
  41. }
  42. Vector operator*(const Vector& a, double b) {
  43.     return Vector(a[0]*b, a[1]*b, a[2]*b);
  44. }
  45. Vector operator*(double a, const Vector& b) {
  46.     return Vector(a*b[0], a*b[1], a*b[2]);
  47. }
  48.  
  49. double dot(const Vector& a, const Vector& b) {
  50.     return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  51. }
  52.  
  53.  
  54. int main() {
  55.     int W = 512;
  56.     int H = 512;
  57.  
  58.     Vector center(0.2, 0.1, 0.);
  59.  
  60.     std::vector<unsigned char> image(W*H * 3, 0);
  61. #pragma omp parallel for
  62.     for (int i = 0; i < H; i++) {
  63.         for (int j = 0; j < W; j++) {
  64.            
  65.             Vector v(j / (double)W - 0.5, i / (double)H - 0.5, 0.);
  66.             double gaussianVal = exp(-(v-center).norm2()/(2*sqr(0.2)));
  67.  
  68.             image[(i*W + j) * 3 + 0] = 127* gaussianVal;   // RED
  69.             image[(i*W + j) * 3 + 1] = 50 * gaussianVal;  // GREEN
  70.             image[(i*W + j) * 3 + 2] = 255 * gaussianVal;  // BLUE
  71.         }
  72.     }
  73.     stbi_write_png("image.png", W, H, 3, &image[0], 0);
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement