Advertisement
MMBC

raytracer.cpp

Jul 1st, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <fstream>
  2. #include <cmath>
  3.  
  4. struct Vec {
  5.     double x, y, z;
  6.     Vec(){x=y=z=0;}
  7.     Vec(double a, double b, double c){x=a,y=b,z=c;}
  8.     Vec operator- (Vec v) {return Vec(x-v.x,y-v.y,z-v.z);}
  9. };
  10.  
  11. double dot(Vec v, Vec b) {return (v.x*b.x+v.y*b.y+v.z*b.z);}
  12.  
  13. struct Ray {
  14.     Vec o;          // origin
  15.     Vec d;          // direction
  16.     Ray(Vec i, Vec j) {o=i,d=j;}
  17. };
  18.  
  19. struct Sphere {
  20.     Vec c;              // Center
  21.     double r;           // Radius
  22.     Sphere(Vec i, double j){c=i, r=j;}
  23.     bool intersect(Ray ray, double &t) {
  24.         Vec o = ray.o;
  25.         Vec d = ray.d;
  26.         Vec oc = o-c;
  27.         double b = 2*dot(oc,d);
  28.         double c = dot(oc, oc)-r*r;
  29.         double disc = b*b-4*c;
  30.         if (disc < 0) return false;
  31.         else {
  32.             disc = sqrt(disc);
  33.             double t0 = -b-disc;
  34.             double t1 = -b+disc;
  35.  
  36.             t = (t0 < t1) ? t0 : t1;
  37.             return true;
  38.         }
  39.     }
  40. };
  41.  
  42. struct Color {
  43.     double r,g,b;
  44.     Color(){r=g=b=0;}
  45.     Color(double i, double j, double k){r=i,g=j,b=k;}
  46. };
  47.  
  48. int main() {
  49.  
  50.     const int W = 500;          // Image width
  51.     const int H = 500;          // Image height;
  52.  
  53.     std::ofstream out("out.ppm");
  54.     out << "P3" << std::endl << W << std::endl << H << std::endl << "255" << std::endl;
  55.  
  56.     Color pixel_col[H][W];
  57.  
  58.     Color white(255, 255, 255);
  59.     Sphere sphere(Vec(W/2,H/2,50),20);
  60.  
  61.     // for each pixel
  62.     for (int y = 0; y < H; y++) {
  63.         for (int x = 0; x < W; x++) {
  64.  
  65.             // send a ray through each pixel
  66.             Ray ray(Vec(x, y, 0),Vec(0, 0, 1));
  67.  
  68.             double t = 20000;
  69.  
  70.             // Check for intersections
  71.             if (sphere.intersect(ray,t)) {
  72.                 pixel_col[y][x] = white;
  73.             }
  74.             out << pixel_col[y][x].r << std::endl;
  75.             out << pixel_col[y][x].g << std::endl;
  76.             out << pixel_col[y][x].b << std::endl;
  77.         }
  78.     }
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement