Advertisement
okpalan

raytracer.cpp

Nov 4th, 2023
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.92 KB | Source Code | 0 0
  1. #include <cstdlib>
  2. #include <cstdio>
  3. #include <cmath>
  4. #include <fstream>
  5. #include <vector>
  6. #include <iostream>
  7. #include <cassert>
  8.  
  9.  
  10.  
  11. // #if defined __linux__ || defined __APPLE__
  12. // // "Compiled for Linux
  13. // #else
  14. // // Windows doesn't define these values by default, Linux does
  15. // #define M_PI 3.141592653589793
  16. // // #define INFINITY 1e8
  17. // #endif
  18. // how to compile
  19. //g++ -O3 -fopenmp -o raytracer trace.cpp
  20. // open with gimp
  21.  
  22. template<typename T>
  23. class Vec3
  24. {
  25. public:
  26.     T x, y, z;
  27.     Vec3() : x(T(0)), y(T(0)), z(T(0)) {}
  28.     Vec3(T xx) : x(xx), y(xx), z(xx) {}
  29.     Vec3(T xx, T yy, T zz) : x(xx), y(yy), z(zz) {}
  30.     Vec3& normalize()
  31.     {
  32.         T nor2 = length2();
  33.         if (nor2 > 0) {
  34.             T invNor = 1 / sqrt(nor2);
  35.             x *= invNor, y *= invNor, z *= invNor;
  36.         }
  37.         return *this;
  38.     }
  39.     Vec3<T> operator * (const T &f) const { return Vec3<T>(x * f, y * f, z * f); }
  40.     Vec3<T> operator * (const Vec3<T> &v) const { return Vec3<T>(x * v.x, y * v.y, z * v.z); }
  41.     T dot(const Vec3<T> &v) const { return x * v.x + y * v.y + z * v.z; }
  42.     Vec3<T> operator - (const Vec3<T> &v) const { return Vec3<T>(x - v.x, y - v.y, z - v.z); }
  43.     Vec3<T> operator + (const Vec3<T> &v) const { return Vec3<T>(x + v.x, y + v.y, z + v.z); }
  44.     Vec3<T>& operator += (const Vec3<T> &v) { x += v.x, y += v.y, z += v.z; return *this; }
  45.     Vec3<T>& operator *= (const Vec3<T> &v) { x *= v.x, y *= v.y, z *= v.z; return *this; }
  46.     Vec3<T> operator - () const { return Vec3<T>(-x, -y, -z); }
  47.     T length2() const { return x * x + y * y + z * z; }
  48.     T length() const { return sqrt(length2()); }
  49.     friend std::ostream & operator << (std::ostream &os, const Vec3<T> &v)
  50.     {
  51.         os << "[" << v.x << " " << v.y << " " << v.z << "]";
  52.         return os;
  53.     }
  54. };
  55.  
  56. typedef Vec3<float> Vec3f;
  57.  
  58. class Sphere
  59. {
  60. public:
  61.     Vec3f center;                           /// position of the sphere
  62.     float radius, radius2;                  /// sphere radius and radius^2
  63.     Vec3f surfaceColor, emissionColor;      /// surface color and emission (light)
  64.     float transparency, reflection;         /// surface transparency and reflectivity
  65.     Sphere(
  66.         const Vec3f &c,
  67.         const float &r,
  68.         const Vec3f &sc,
  69.         const float &refl = 0,
  70.         const float &transp = 0,
  71.         const Vec3f &ec = 0) :
  72.         center(c), radius(r), radius2(r * r), surfaceColor(sc), emissionColor(ec),
  73.         transparency(transp), reflection(refl)
  74.     { /* empty */ }
  75.  
  76.     bool intersect(const Vec3f &rayorig, const Vec3f &raydir, float &t0, float &t1) const
  77.     {
  78.         Vec3f l = center - rayorig;
  79.         float tca = l.dot(raydir);
  80.         if (tca < 0) return false;
  81.         float d2 = l.dot(l) - tca * tca;
  82.         if (d2 > radius2) return false;
  83.         float thc = sqrt(radius2 - d2);
  84.         t0 = tca - thc;
  85.         t1 = tca + thc;
  86.  
  87.         return true;
  88.     }
  89. };
  90.  
  91. // control depth recursion
  92. #define MAX_RAY_DEPTH 5
  93.  
  94. float mix(const float &a, const float &b, const float &mix)
  95. {
  96.     return b * mix + a * (1 - mix);
  97. }
  98.  
  99. //This is the main trace function. It takes a ray as argument (defined by its origin and direction). We test if this ray intersects any of the geometry in the scene. If the ray intersects an object, we compute the intersection point, the normal at the intersection point, and shade this point using this information. Shading depends on the surface property (is it transparent, reflective, diffuse). The function returns a color for the ray. If the ray intersects an object that is the color of the object at the intersection point, otherwise it returns the background color.
  100.  
  101. Vec3f trace(
  102.     const Vec3f &rayorig,
  103.     const Vec3f &raydir,
  104.     const std::vector<Sphere> &spheres,
  105.     const int &depth)
  106. {
  107.     //if (raydir.length() != 1) std::cerr << "Error " << raydir << std::endl;
  108.     float tnear = INFINITY;
  109.     const Sphere* sphere = NULL;
  110.     // find intersection of this ray with the sphere in the scene
  111.     for (unsigned i = 0; i < spheres.size(); ++i) {
  112.         float t0 = INFINITY, t1 = INFINITY;
  113.         if (spheres[i].intersect(rayorig, raydir, t0, t1)) {
  114.             if (t0 < 0) t0 = t1;
  115.             if (t0 < tnear) {
  116.                 tnear = t0;
  117.                 sphere = &spheres[i];
  118.             }
  119.         }
  120.     }
  121.     // if there's no intersection return black or background color
  122.     if (!sphere) return Vec3f(2);
  123.     Vec3f surfaceColor = 0; // color of the ray/surfaceof the object intersected by the ray
  124.     Vec3f phit = rayorig + raydir * tnear; // point of intersection
  125.     Vec3f nhit = phit - sphere->center; // normal at the intersection point
  126.     nhit.normalize(); // normalize normal direction
  127.     // If the normal and the view direction are not opposite to each other
  128.     // reverse the normal direction. That also means we are inside the sphere so set
  129.     // the inside bool to true. Finally reverse the sign of IdotN which we want
  130.     // positive.
  131.     float bias = 1e-4; // add some bias to the point from which we will be tracing
  132.     bool inside = false;
  133.     if (raydir.dot(nhit) > 0) nhit = -nhit, inside = true;
  134.     if ((sphere->transparency > 0 || sphere->reflection > 0) && depth < MAX_RAY_DEPTH) {
  135.         float facingratio = -raydir.dot(nhit);
  136.         // change the mix value to tweak the effect
  137.         float fresneleffect = mix(pow(1 - facingratio, 3), 1, 0.1);
  138.         // compute reflection direction (not need to normalize because all vectors
  139.         // are already normalized)
  140.         Vec3f refldir = raydir - nhit * 2 * raydir.dot(nhit);
  141.         refldir.normalize();
  142.         Vec3f reflection = trace(phit + nhit * bias, refldir, spheres, depth + 1);
  143.         Vec3f refraction = 0;
  144.         // if the sphere is also transparent compute refraction ray (transmission)
  145.         if (sphere->transparency) {
  146.             float ior = 1.1, eta = (inside) ? ior : 1 / ior; // are we inside or outside the surface?
  147.             float cosi = -nhit.dot(raydir);
  148.             float k = 1 - eta * eta * (1 - cosi * cosi);
  149.             Vec3f refrdir = raydir * eta + nhit * (eta *  cosi - sqrt(k));
  150.             refrdir.normalize();
  151.             refraction = trace(phit - nhit * bias, refrdir, spheres, depth + 1);
  152.         }
  153.         // the result is a mix of reflection and refraction (if the sphere is transparent)
  154.         surfaceColor = (
  155.             reflection * fresneleffect +
  156.             refraction * (1 - fresneleffect) * sphere->transparency) * sphere->surfaceColor;
  157.     }
  158.     else {
  159.         // it's a diffuse object, no need to raytrace any further
  160.         for (unsigned i = 0; i < spheres.size(); ++i) {
  161.             if (spheres[i].emissionColor.x > 0) {
  162.                 // this is a light
  163.                 Vec3f transmission = 1;
  164.                 Vec3f lightDirection = spheres[i].center - phit;
  165.                 lightDirection.normalize();
  166.                 for (unsigned j = 0; j < spheres.size(); ++j) {
  167.                     if (i != j) {
  168.                         float t0, t1;
  169.                         if (spheres[j].intersect(phit + nhit * bias, lightDirection, t0, t1)) {
  170.                             transmission = 0;
  171.                             break;
  172.                         }
  173.                     }
  174.                 }
  175.                 surfaceColor += sphere->surfaceColor * transmission *
  176.                 std::max(float(0), nhit.dot(lightDirection)) * spheres[i].emissionColor;
  177.             }
  178.         }
  179.     }
  180.  
  181.     return surfaceColor + sphere->emissionColor;
  182. }
  183.  
  184.  
  185. void render(const std::vector<Sphere> &spheres)
  186. {
  187.     unsigned width = 640, height = 480;
  188.     Vec3f *image = new Vec3f[width * height], *pixel = image;
  189.     float invWidth = 1 / float(width), invHeight = 1 / float(height);
  190.     float fov = 30, aspectratio = width / float(height);
  191.     float angle = tan(M_PI * 0.5 * fov / 180.);
  192.     // Trace rays
  193.     for (unsigned y = 0; y < height; ++y) {
  194.         for (unsigned x = 0; x < width; ++x, ++pixel) {
  195.             float xx = (2 * ((x + 0.5) * invWidth) - 1) * angle * aspectratio;
  196.             float yy = (1 - 2 * ((y + 0.5) * invHeight)) * angle;
  197.             Vec3f raydir(xx, yy, -1);
  198.             raydir.normalize();
  199.             *pixel = trace(Vec3f(0), raydir, spheres, 0);
  200.         }
  201.     }
  202.     // Save result to a PPM image (keep these flags if you compile under Windows)
  203.     std::ofstream ofs("./sphere-scene.ppm", std::ios::out | std::ios::binary);
  204.     ofs << "P6\n" << width << " " << height << "\n255\n";
  205.     for (unsigned i = 0; i < width * height; ++i) {
  206.         ofs << (unsigned char)(std::min(float(1), image[i].x) * 255) <<
  207.                (unsigned char)(std::min(float(1), image[i].y) * 255) <<
  208.                (unsigned char)(std::min(float(1), image[i].z) * 255);
  209.     }
  210.     ofs.close();
  211.     delete [] image;
  212. }
  213.  
  214. // In the main function, we will create the scene which is composed of 5 spheres
  215. // ,and 1 light (which is also a sphere). Then, once the scene description is complete we render that scene, by calling the render() function.
  216.  
  217. int main(int argc, char **argv)
  218. {
  219.     srand(13);
  220.     std::vector<Sphere> spheres;
  221.     // position, radius, surface color, reflectivity, transparency, emission color
  222.     spheres.push_back(Sphere(Vec3f( 0.0, -10004, -20), 10000, Vec3f(0.20, 0.20, 0.20), 0, 0.0));
  223.     spheres.push_back(Sphere(Vec3f( 0.0,      0, -20),     4, Vec3f(1.00, 0.32, 0.36), 1, 0.5));
  224.     spheres.push_back(Sphere(Vec3f( 5.0,     -1, -15),     2, Vec3f(0.90, 0.76, 0.46), 1, 0.0));
  225.     spheres.push_back(Sphere(Vec3f( 5.0,      0, -25),     3, Vec3f(0.65, 0.77, 0.97), 1, 0.0));
  226.     spheres.push_back(Sphere(Vec3f(-5.5,      0, -15),     3, Vec3f(0.90, 0.90, 0.90), 1, 0.0));
  227.     // light
  228.     spheres.push_back(Sphere(Vec3f( 0.0,     20, -30),     3, Vec3f(0.00, 0.00, 0.00), 0, 0.0, Vec3f(3)));
  229.     render(spheres);
  230.  
  231.     return 0;
  232. }
  233.  
  234.  
Tags: raytracer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement