RohamCsiga

Vik Wiki Grafika - Árnyékok

Jan 25th, 2014
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 15.34 KB | None | 0 0
  1. #include <math.h>
  2. #include <stdlib.h>
  3.  
  4. #if defined(__APPLE__)
  5.   #include <OpenGL/gl.h>
  6.   #include <OpenGL/glu.h>
  7.   #include <GLUT/glut.h>
  8. #else
  9.   #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  10.     #include <windows.h>
  11.   #endif
  12.   #include <GL/gl.h>
  13.   #include <GL/glu.h>
  14.   #include <GL/glut.h>
  15. #endif
  16.  
  17. #ifndef M_PI
  18.   #define M_PI 3.14159265359
  19. #endif
  20.  
  21. template <typename T>
  22. T max(T a, T b) {
  23.   return a > b ? a : b;
  24. }
  25.  
  26. template <typename T>
  27. T min(T a, T b) {
  28.   return a < b ? a : b;
  29. }
  30.  
  31. struct Vector {
  32.   union { float x, r; }; // x és r néven is lehessen hivatkozni erre a tagra.
  33.   union { float y, g; };
  34.   union { float z, b; };
  35.  
  36.   Vector(float v = 0) : x(v), y(v), z(v) { }
  37.   Vector(float x, float y, float z) : x(x), y(y), z(z) { }
  38.   Vector operator+(const Vector& v) const { return Vector(x + v.x, y + v.y, z + v.z); }
  39.   Vector operator-(const Vector& v) const { return Vector(x - v.x, y - v.y, z - v.z); }
  40.   Vector operator*(const Vector& v) const { return Vector(x * v.x, y * v.y, z * v.z); }
  41.   Vector operator/(const Vector& v) const { return Vector(x / v.x, y / v.y, z / v.z); }
  42.   Vector& operator+=(const Vector& v) { x += v.x, y += v.y, z += v.z; return *this; }
  43.   Vector& operator-=(const Vector& v) { x -= v.x, y -= v.y, z -= v.z; return *this; }
  44.   Vector& operator*=(const Vector& v) { x *= v.x, y *= v.y, z *= v.z; return *this; }
  45.   Vector& operator/=(const Vector& v) { x /= v.x, y /= v.y, z /= v.z; return *this; }
  46.   Vector operator-() const { return Vector(-x, -y, -z); }
  47.   float dot(const Vector& v) const { return x*v.x + y*v.y + z*v.z; }
  48.   Vector cross(const Vector& v) const { return Vector(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x); }
  49.   float length() const { return sqrt(x*x + y*y + z*z); }
  50.   Vector normalize() const { float l = length(); if(l > 1e-3) { return (*this/l); } else { return Vector(); } }
  51.   bool isNull() const { return length() < 1e-3; }
  52.   Vector saturate() const { return Vector(max(min(x, 1.0f), 0.0f), max(min(y, 1.0f), 0.0f), max(min(z, 1.0f), 0.0f)); }
  53. };
  54.  
  55. // Azoknak, akik a shader kódokban használt szintakszishoz hozzá vannak szokva (mint pl. én)
  56. inline float dot(const Vector& lhs, const Vector& rhs) {
  57.   return lhs.dot(rhs);
  58. }
  59.  
  60. inline Vector cross(const Vector& lhs, const Vector& rhs) {
  61.   return lhs.cross(rhs);
  62. }
  63.  
  64. inline Vector operator*(float f, const Vector& v) {
  65.   return v*f;
  66. }
  67.  
  68. typedef Vector Color;
  69.  
  70. struct Screen {
  71.   static const int width = 600;
  72.   static const int height = 600;
  73.   static Color image[width * height];
  74.   static void Draw() {
  75.     glDrawPixels(width, height, GL_RGB, GL_FLOAT, image);
  76.   }
  77.   static Color& Pixel(size_t x, size_t y) {
  78.     return image[y*width + x];
  79.   }
  80. };
  81. Color Screen::image[width * height]; // A statikus adattagat out-of-line példányosítani kell (kivéve az inteket és enumokat).
  82.  
  83. struct Ray {
  84.   Vector origin, direction;
  85. };
  86.  
  87. struct Intersection {
  88.   Vector pos, normal;
  89.   bool is_valid;
  90.   Intersection(Vector pos = Vector(), Vector normal = Vector(), bool is_valid = false)
  91.     : pos(pos), normal(normal), is_valid(is_valid) { }
  92. };
  93.  
  94. struct Light {
  95.   enum LightType {Ambient, Directional, Point, Spot} type;
  96.   Vector pos, dir;
  97.   Color color;
  98.   float spot_cutoff;
  99. };
  100.  
  101. struct Material {
  102.   virtual ~Material() { }
  103.   virtual Color getColor(Intersection, const Light[], size_t) = 0;
  104. };
  105.  
  106. struct Object {
  107.   Material *mat;
  108.   Object(Material* m) : mat(m) { }
  109.   virtual ~Object() { }
  110.   virtual Intersection intersectRay(Ray) = 0;
  111. };
  112.  
  113. struct Scene {
  114.   static const size_t max_obj_num = 100;
  115.   size_t obj_num;
  116.   Object* objs[max_obj_num];
  117.  
  118.   void AddObject(Object *o) {
  119.     objs[obj_num++] = o;
  120.   }
  121.  
  122.   ~Scene() {
  123.     for(int i = 0; i != obj_num; ++i) {
  124.       delete objs[i];
  125.     }
  126.   }
  127.  
  128.   static const size_t max_lgt_num = 10;
  129.   size_t lgt_num;
  130.   Light lgts[max_obj_num];
  131.  
  132.   void AddLight(const Light& l) {
  133.     lgts[lgt_num++] = l;
  134.   }
  135.  
  136.   static const Vector env_color;
  137.  
  138.   Scene() : obj_num(0) { }
  139.  
  140.   Intersection getClosestIntersection(Ray r, int* index = NULL) const {
  141.     Intersection closest_intersection;
  142.     float closest_intersection_dist;
  143.     int closest_index = -1;
  144.  
  145.     for(int i = 0; i < obj_num; ++i) {
  146.       Intersection inter = objs[i]->intersectRay(r);
  147.       if(!inter.is_valid)
  148.         continue;
  149.       float dist = (inter.pos - r.origin).length();
  150.       if(closest_index == -1 || dist < closest_intersection_dist) {
  151.         closest_intersection = inter;
  152.         closest_intersection_dist = dist;
  153.         closest_index = i;
  154.       }
  155.     }
  156.  
  157.     if(index) {
  158.       *index = closest_index;
  159.     }
  160.     return closest_intersection;
  161.   }
  162.  
  163.   Color shootRay(Ray r) const {
  164.     int index;
  165.     Intersection inter = getClosestIntersection(r, &index);
  166.  
  167.     if(index != -1) {
  168.       return objs[index]->mat->getColor(inter, lgts, lgt_num);
  169.     } else {
  170.       return env_color;
  171.     }
  172.   }
  173. } scene;
  174. const Vector Scene::env_color = Vector(135./255., 206./255., 235./255.);
  175.  
  176. struct Camera {
  177.   Vector pos, plane_pos, right, up;
  178.  
  179.   Camera(float fov, const Vector& eye, const Vector& target, const Vector& plane_up)
  180.       : pos(eye - (target-eye).normalize() / (2*tan((fov*M_PI/180)/2))), plane_pos(eye)
  181.    {
  182.       Vector fwd = (plane_pos - pos).normalize();
  183.       right = cross(fwd, plane_up).normalize();
  184.       up = cross(right, fwd).normalize();
  185.    }
  186.  
  187.   void takePicture() {
  188.     for(int x = 0; x < Screen::height; ++x)
  189.       for(int y = 0; y < Screen::width; ++y)
  190.         capturePixel(x, y);
  191.   }
  192.  
  193.   void capturePixel(float x, float y) {
  194.     Vector pos_on_plane = Vector(
  195.       (x - Screen::width/2) / (Screen::width/2),
  196.       // Itt nem kell megfordítani az y tengelyt. A bal fölső sarok az origó most.
  197.       (y - Screen::height/2) / (Screen::height/2),
  198.       0
  199.     );
  200.  
  201.     Vector plane_intersection = plane_pos + pos_on_plane.x * right + pos_on_plane.y * up;
  202.  
  203.     Ray r = {pos, (plane_intersection - pos).normalize()};
  204.     Screen::Pixel(x, y) = scene.shootRay(r);
  205.   }
  206. } camera(60, Vector(-3, 2, -2), Vector(), Vector(0, 1, 0));
  207.  
  208. // Idáig egy általános raytracert definiáltam. Innentől jönnek a konkrétumok.
  209.  
  210. struct DiffuseMaterial : public Material {
  211.   Color own_color;
  212.  
  213.   DiffuseMaterial(const Color& color) : own_color(color) { }
  214.  
  215.   Color getColor(Intersection inter, const Light* lgts, size_t lgt_num) {
  216.     Color accum_color;
  217.  
  218.     for(int i = 0; i < lgt_num; ++i) {
  219.       const Light& light = lgts[i];
  220.  
  221.       switch(light.type) {
  222.         case Light::Ambient: {
  223.           accum_color += light.color * own_color;
  224.         } break;
  225.         case Light::Directional: {
  226.           // Lőjjünk egy sugarat a fényforrás irányába.
  227.           Ray shadow_checker = {inter.pos + 1e-3*light.dir, light.dir}; // Az irányfény iránya nálam a forrás felé futat.
  228.           Intersection shadow_checker_int = scene.getClosestIntersection(shadow_checker);
  229.           if(shadow_checker_int.is_valid) {
  230.             break; // Ha bármivel is ütközik, akkor árnyékban vagyunk
  231.           }
  232.  
  233.           float intensity = max(dot(inter.normal, light.dir.normalize()), 0.0f);
  234.           accum_color += intensity * light.color * own_color;
  235.         } break;
  236.         case Light::Spot: {
  237.           Vector light_to_pos = inter.pos - light.pos;
  238.           if(dot(light_to_pos.normalize(), light.dir) < light.spot_cutoff) {
  239.             break; // Ha nincs megvilágítva, akkor ne csináljuk semmit.
  240.           } // Különben számoljuk pont fényforrással.
  241.         } // NINCS break!
  242.         case Light::Point: {
  243.           // Lőjjünk egy sugarat a fényforrás felől a konkrét pont irányába
  244.           Ray shadow_checker = {light.pos, (inter.pos - light.pos).normalize()};
  245.           Intersection shadow_checker_int = scene.getClosestIntersection(shadow_checker);
  246.           if(shadow_checker_int.is_valid &&
  247.             (shadow_checker_int.pos-light.pos).length() + 1e-3 < (inter.pos-light.pos).length()) {
  248.             break; // Ha bármivel is ütközik, ami közelebb van a fényhez, mint mi, akkor árnyékban vagyunk
  249.           }
  250.  
  251.           Vector pos_to_light = light.pos - inter.pos;
  252.           float attenuation = pow(1/pos_to_light.length(), 2);
  253.           float intensity = max(dot(inter.normal, pos_to_light.normalize()), 0.0f);
  254.           accum_color += attenuation * intensity * light.color * own_color;
  255.         } break;
  256.       }
  257.     }
  258.  
  259.     return accum_color.saturate();
  260.   }
  261. };
  262.  
  263. DiffuseMaterial white(Color(1.0f, 1.0f, 1.0f));
  264. DiffuseMaterial blue(Color(0.0f, 0.4f, 1.0f));
  265.  
  266. struct Triangle : public Object {
  267.   Vector a, b, c, normal;
  268.  
  269.   // Az óra járásával ellentétes (CCW) körüljárási irányt feltételez ez a kód.
  270.   Triangle(Material* mat, const Vector& a, const Vector& b, const Vector& c)
  271.     : Object(mat), a(a), b(b), c(c) {
  272.       Vector ab = b - a;
  273.       Vector ac = c - a;
  274.       normal = cross(ab.normalize(), ac.normalize()).normalize();
  275.   }
  276.  
  277.   // Ennek a függvénynek a megértéséhez rajzolj magadnak egyszerű ábrákat!
  278.   Intersection intersectRay(Ray r) {
  279.     // Először számoljuk ki, hogy melyen mekkora távot
  280.     // tesz meg a sugár, míg eléri a háromszög síkját
  281.     // A számoláshoz tudnuk kell hogy ha egy 'v' vektort
  282.     // skaliráisan szorzunk egy egységvektorral, akkor
  283.     // az eredmény a 'v'-nek az egységvektorra vetített
  284.     // hossza lesz. Ezt felhasználva, ha a sugár kiindulási
  285.     // pontjából a sík egy pontjba mutató vektort levetítjük
  286.     // a sík normál vektorára, akkor megkapjuk, hogy milyen
  287.     // távol van a sugár kiindulási pontja a síktól. Továbbá,
  288.     // ha az a sugár irányát vetítjük a normálvektorra, akkor meg
  289.     // megtudjuk, hogy az milyen gyorsan halad a sík fele.
  290.     // Innen a már csak a t = s / v képletet kell csak használnunk.
  291.     float ray_travel_dist = dot(a - r.origin, normal) / dot(r.direction, normal);
  292.  
  293.     // Ha a háromszög az ellenkező irányba van, mint
  294.     // amerre a sugár megy, akkor nincs metszéspontjuk
  295.     if(ray_travel_dist < 0)
  296.       return Intersection();
  297.  
  298.     // Számoljuk ki, hogy a sugár hol metszi a sugár síkját.
  299.     Vector plane_intersection = r.origin + ray_travel_dist * r.direction;
  300.  
  301.     /* Most már csak el kell döntenünk, hogy ez a pont a háromszög
  302.        belsejében van-e. Erre két lehetőség van:
  303.      
  304.        - A háromszög összes élére megnézzük, hogy a pontot a hároszög
  305.        egy megfelelő pontjával összekötve a kapott szakasz, és a háromszög
  306.        élének a vektoriális szorzata a normál irányába mutat-e.
  307.        Pl:
  308.      
  309.                  a
  310.                / |
  311.               /  |
  312.              /   |
  313.             /  x |  y
  314.            /     |
  315.           b------c
  316.  
  317.        Nézzük meg az x és y pontra ezt az algoritmust.
  318.        A cross(ab, ax), a cross(bc, bx), és a cross(ca, cx) és kifele mutat a
  319.        képernyőből, ugyan abba az irányba mint a normál vektor. Ezt amúgy a
  320.        dot(cross(ab, ax), normal) >= 0 összefüggéssel egyszerű ellenőrizni.
  321.        Az algoritmus alapján az x a háromszög belsejében van.
  322.  
  323.        Míg az y esetében a cross(ca, cy) befele mutat, a normállal ellenkező irányba,
  324.        tehát a dot(cross(ca, cy), normal) < 0 ami az algoritmus szerint azt jelenti,
  325.        hogy az y pont a háromszögön kívül van.
  326.      
  327.        - A ötlet lehetőség a barycentrikus koordinátáknak azt a tulajdonságát használja
  328.        ki, hogy azok a háromszög belsejében lévő pontokra kivétel nélkül nem negatívak,
  329.        míg a háromszögön kívül lévő pontokra legalább egy koordináta negatív.
  330.        Ennek a megoldásnak a használatához ki kell jelölnünk két tetszőleges, de egymásra
  331.        merőleges vektort a síkon, ezekre le kell vetíteninünk a háromszög pontjait, és
  332.        kérdéses pontot, és az így kapott koordinátákra alakzmanunk kell egy a wikipediáról
  333.        egyszerűen kimásolható képletet:
  334.        http://en.wikipedia.org/wiki/Barycentric_coordinate_system#Converting_to_barycentric_coordinates
  335.      
  336.        Én az első lehetőséget implementálom. */
  337.  
  338.     const Vector& x = plane_intersection;
  339.  
  340.     Vector ab = b - a;
  341.     Vector ax = x - a;
  342.  
  343.     Vector bc = c - b;
  344.     Vector bx = x - b;
  345.  
  346.     Vector ca = a - c;
  347.     Vector cx = x - c;
  348.  
  349.     if(dot(cross(ab, ax), normal) >= 0)
  350.       if(dot(cross(bc, bx), normal) >= 0)
  351.         if(dot(cross(ca, cx), normal) >= 0)
  352.           return Intersection(x, normal, true);
  353.  
  354.     return Intersection();
  355.   }
  356. };
  357.  
  358. void onDisplay() {
  359.   glClear(GL_COLOR_BUFFER_BIT);
  360.  
  361.   camera.takePicture();
  362.   Screen::Draw();
  363.  
  364.   glutSwapBuffers();
  365. }
  366.  
  367. void onIdle() {
  368.   static bool first_call = true;
  369.   if(first_call) {
  370.     glutPostRedisplay();
  371.     first_call = false;
  372.   }
  373. }
  374.  
  375. void onInitialization() {
  376.   Light amb = {Light::Ambient, Vector(), Vector(), Color(0.2f, 0.2f, 0.2f)};
  377.   Light dir = {Light::Directional, Vector(), Vector(3, 4, 2), Color(0.6f, 0.6f, 0.6f)};
  378.   Light point = {Light::Point, Vector(3, 4, 2), Vector(), Color(20.0f, 20.0f, 20.0f)};
  379.   scene.AddLight(amb);
  380.   scene.AddLight(dir);
  381.   scene.AddLight(point);
  382.  
  383.   // Ground
  384.   scene.AddObject(new Triangle(&white, Vector(-10, -1.1f, -10), Vector(-10, -1.1f, +10), Vector(+10, -1.1f, +10)));
  385.   scene.AddObject(new Triangle(&white, Vector(+10, -1.1f, +10), Vector(+10, -1.1f, -10), Vector(-10, -1.1f, -10)));
  386.  
  387.   // Front face
  388.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(-1, -1, -1), Vector(-1, +1, -1)));
  389.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, -1), Vector(+1, +1, -1), Vector(+1, -1, -1)));
  390.  
  391.   // Back face
  392.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, +1), Vector(-1, -1, +1), Vector(-1, +1, +1)));
  393.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, +1), Vector(+1, +1, +1), Vector(+1, -1, +1)));
  394.  
  395.   // Right face
  396.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(+1, -1, +1), Vector(+1, +1, +1)));
  397.   scene.AddObject(new Triangle(&blue, Vector(+1, +1, +1), Vector(+1, +1, -1), Vector(+1, -1, -1)));
  398.  
  399.   // Left face
  400.   scene.AddObject(new Triangle(&blue, Vector(-1, -1, -1), Vector(-1, -1, +1), Vector(-1, +1, +1)));
  401.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, +1), Vector(-1, +1, -1), Vector(-1, -1, -1)));
  402.  
  403.   // Upper face
  404.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, -1), Vector(-1, +1, +1), Vector(+1, +1, +1)));
  405.   scene.AddObject(new Triangle(&blue, Vector(+1, +1, -1), Vector(-1, +1, -1), Vector(+1, +1, +1)));
  406.  
  407.   // Lower face
  408.   scene.AddObject(new Triangle(&blue, Vector(-1, -1, +1), Vector(-1, -1, -1), Vector(+1, -1, +1)));
  409.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(+1, -1, +1), Vector(-1, -1, -1)));
  410. }
  411.  
  412. void onKeyboard(unsigned char key, int, int) {}
  413.  
  414. void onKeyboardUp(unsigned char key, int, int) {}
  415.  
  416. void onMouse(int, int, int, int) {}
  417.  
  418. void onMouseMotion(int, int) {}
  419.  
  420. int main(int argc, char **argv) {
  421.   glutInit(&argc, argv);
  422.   glutInitWindowSize(Screen::width, Screen::height);
  423.   glutInitWindowPosition(100, 100);
  424.   glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
  425.  
  426.   glutCreateWindow("Grafika pelda program");
  427.  
  428.   glMatrixMode(GL_MODELVIEW);
  429.   glLoadIdentity();
  430.   glMatrixMode(GL_PROJECTION);
  431.   glLoadIdentity();
  432.  
  433.   onInitialization();
  434.  
  435.   glutDisplayFunc(onDisplay);
  436.   glutMouseFunc(onMouse);
  437.   glutIdleFunc(onIdle);
  438.   glutKeyboardFunc(onKeyboard);
  439.   glutKeyboardUpFunc(onKeyboardUp);
  440.   glutMotionFunc(onMouseMotion);
  441.  
  442.   glutMainLoop();
  443.  
  444.   return 0;
  445. }
Advertisement
Add Comment
Please, Sign In to add comment