Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. void part2()
  2. {
  3.     std::cout << "Part 2: Simple ray tracer, one sphere with orthographic projection" << std::endl;
  4.  
  5.     const std::string filename("part2.png");
  6.     MatrixXd C = MatrixXd::Zero(800,800); // Store the color
  7.     MatrixXd A = MatrixXd::Zero(800,800); // Store the alpha mask
  8.  
  9.     // The camera is orthographic, pointing in the direction -z and covering the unit square (-1,1) in x and y
  10.    
  11.     Vector3d origin(-1,1,1);
  12.     Vector3d x_displacement(2.0/C.cols(),0,0);
  13.     Vector3d y_displacement(0,-2.0/C.rows(),0);
  14.  
  15.     // Single light source
  16.     const Vector3d light_position(-1,1,1);
  17.  
  18.     for (unsigned i=0;i<C.cols();i++)
  19.     {
  20.         for (unsigned j=0;j<C.rows();j++)
  21.         {
  22.             // Prepare the ray
  23.             Vector3d ray_origin = origin + double(i)*x_displacement + double(j)*y_displacement;
  24.             Vector3d ray_direction = RowVector3d(0,0,-1);
  25.  
  26.             // Intersect with the sphere
  27.             // NOTE: this is a special case of a sphere centered in the origin and for orthographic rays aligned with the z axis
  28.             Vector2d ray_on_xy(ray_origin(0),ray_origin(1));
  29.             const double sphere_radius = 0.9;
  30.  
  31.             if (ray_on_xy.norm()<sphere_radius)
  32.             {
  33.                 // The ray hit the sphere, compute the exact intersection point
  34.                 Vector3d ray_intersection(ray_on_xy(0),ray_on_xy(1),sqrt(sphere_radius*sphere_radius - ray_on_xy.squaredNorm()));
  35.  
  36.                 // Compute normal at the intersection point
  37.                 Vector3d ray_normal = ray_intersection.normalized();
  38.  
  39.                 // Simple diffuse model
  40.                 C(i,j) = (light_position-ray_intersection).normalized().transpose() * ray_normal;
  41.  
  42.                 // Clamp to zero
  43.                 C(i,j) = max(C(i,j),0.);
  44.  
  45.                 // Disable the alpha mask for this pixel
  46.                 A(i,j) = 1;
  47.             }
  48.         }
  49.     }
  50.    
  51.    
  52.     // Save to png
  53.     write_matrix_to_png(C,C,C,A,filename);
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement