Advertisement
Guest User

Grafika példa program

a guest
Jan 25th, 2014
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 14.08 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;
  97.   Color color;
  98.   Vector dir;
  99.   float spot_cutoff;
  100. };
  101.  
  102. struct Material {
  103.   virtual ~Material() { }
  104.   virtual Color getColor(Intersection, const Light[], size_t) = 0;
  105. };
  106.  
  107. struct Object {
  108.   Material *mat;
  109.   Object(Material* m) : mat(m) { }
  110.   virtual ~Object() { }
  111.   virtual Intersection intersectRay(Ray) = 0;
  112. };
  113.  
  114. struct Scene {
  115.   static const size_t max_obj_num = 100;
  116.   size_t obj_num;
  117.   Object* objs[max_obj_num];
  118.  
  119.   void AddObject(Object *o) {
  120.     objs[obj_num++] = o;
  121.   }
  122.  
  123.   ~Scene() {
  124.     for(int i = 0; i != obj_num; ++i) {
  125.       delete objs[i];
  126.     }
  127.   }
  128.  
  129.   static const size_t max_lgt_num = 10;
  130.   size_t lgt_num;
  131.   Light lgts[max_obj_num];
  132.  
  133.   void AddLight(const Light& l) {
  134.     lgts[lgt_num++] = l;
  135.   }
  136.  
  137.   static const Vector env_color;
  138.  
  139.   Scene() : obj_num(0) { }
  140.  
  141.   Color shootRay(Ray r) const {
  142.     Intersection closest_intersection;
  143.     float closest_intersection_dist;
  144.     int closest_index = -1;
  145.  
  146.     for(int i = 0; i < obj_num; ++i) {
  147.       Intersection inter = objs[i]->intersectRay(r);
  148.       if(!inter.is_valid)
  149.         continue;
  150.       float dist = (inter.pos - r.origin).length();
  151.       if(closest_index == -1 || dist < closest_intersection_dist) {
  152.         closest_intersection = inter;
  153.         closest_intersection_dist = dist;
  154.         closest_index = i;
  155.       }
  156.     }
  157.  
  158.     if(closest_index != -1) {
  159.       return objs[closest_index]->mat->getColor(closest_intersection, lgts, lgt_num);
  160.     } else {
  161.       return env_color;
  162.     }
  163.   }
  164. } scene;
  165. const Vector Scene::env_color = Vector(135./255., 206./255., 235./255.);
  166.  
  167. struct Camera {
  168.   Vector pos, plane_pos, right, up;
  169.  
  170.   Camera(float fov, const Vector& eye, const Vector& target, const Vector& plane_up)
  171.       : pos(eye - (target-eye).normalize() / (2*tan((fov*M_PI/180)/2))), plane_pos(eye)
  172.    {
  173.       Vector fwd = (plane_pos - pos).normalize();
  174.       right = cross(fwd, plane_up).normalize();
  175.       up = cross(right, fwd).normalize();
  176.    }
  177.  
  178.   void takePicture() {
  179.     for(int x = 0; x < Screen::height; ++x)
  180.       for(int y = 0; y < Screen::width; ++y)
  181.         capturePixel(x, y);
  182.   }
  183.  
  184.   void capturePixel(float x, float y) {
  185.     Vector pos_on_plane = Vector(
  186.       (x - Screen::width/2) / (Screen::width/2),
  187.       // Itt nem kell megfordítani az y tengelyt. A bal fölső sarok az origó most.
  188.       (y - Screen::height/2) / (Screen::height/2),
  189.       0
  190.     );
  191.  
  192.     Vector plane_intersection = plane_pos + pos_on_plane.x * right + pos_on_plane.y * up;
  193.  
  194.     Ray r = {pos, (plane_intersection - pos).normalize()};
  195.     Screen::Pixel(x, y) = scene.shootRay(r);
  196.   }
  197. } camera(60, Vector(-3, 2, -2), Vector(), Vector(0, 1, 0));
  198.  
  199. // Idáig egy általános raytracert definiáltam. Innentől jönnek a konkrétumok.
  200.  
  201. struct DiffuseMaterial : public Material {
  202.   Color own_color;
  203.  
  204.   DiffuseMaterial(const Color& color) : own_color(color) { }
  205.  
  206.   Color getColor(Intersection inter, const Light* lgts, size_t lgt_num) {
  207.     Color accum_color;
  208.  
  209.     for(int i = 0; i < lgt_num; ++i) {
  210.       const Light& light = lgts[i];
  211.       switch(light.type) {
  212.         case Light::Ambient: {
  213.           accum_color += light.color * own_color;
  214.         } break;
  215.         case Light::Directional: {
  216.           float intensity = max(dot(inter.normal, light.pos.normalize()), 0.0f);
  217.           accum_color += intensity * light.color * own_color;
  218.         } break;
  219.         case Light::Spot: {
  220.           Vector light_to_pos = inter.pos - light.pos;
  221.           if(dot(light_to_pos.normalize(), light.dir) < light.spot_cutoff) {
  222.             break; // Ha nincs megvilágítva, akkor ne csináljuk semmit.
  223.           } // Különben számoljuk pont fényforrással.
  224.         } // NINCS break!
  225.         case Light::Point: {
  226.           Vector pos_to_light = light.pos - inter.pos;
  227.           float attenuation = pow(1/pos_to_light.length(), 2);
  228.           float intensity = max(dot(inter.normal, pos_to_light.normalize()), 0.0f);
  229.           accum_color += attenuation * intensity * light.color * own_color;
  230.         } break;
  231.       }
  232.     }
  233.  
  234.     return accum_color.saturate();
  235.   }
  236. };
  237.  
  238. DiffuseMaterial white(Color(1.0f, 1.0f, 1.0f));
  239. DiffuseMaterial blue(Color(0.0f, 0.4f, 1.0f));
  240.  
  241. struct Triangle : public Object {
  242.   Vector a, b, c, normal;
  243.  
  244.   // Az óra járásával ellentétes (CCW) körüljárási irányt feltételez ez a kód.
  245.   Triangle(Material* mat, const Vector& a, const Vector& b, const Vector& c)
  246.     : Object(mat), a(a), b(b), c(c) {
  247.       Vector ab = b - a;
  248.       Vector ac = c - a;
  249.       normal = cross(ab.normalize(), ac.normalize()).normalize();
  250.   }
  251.  
  252.   // Ennek a függvénynek a megértéséhez rajzolj magadnak egyszerű ábrákat!
  253.   Intersection intersectRay(Ray r) {
  254.     // Először számoljuk ki, hogy melyen mekkora távot
  255.     // tesz meg a sugár, míg eléri a háromszög síkját
  256.     // A számoláshoz tudnuk kell hogy ha egy 'v' vektort
  257.     // skaliráisan szorzunk egy egységvektorral, akkor
  258.     // az eredmény a 'v'-nek az egységvektorra vetített
  259.     // hossza lesz. Ezt felhasználva, ha a sugár kiindulási
  260.     // pontjából a sík egy pontjba mutató vektort levetítjük
  261.     // a sík normál vektorára, akkor megkapjuk, hogy milyen
  262.     // távol van a sugár kiindulási pontja a síktól. Továbbá,
  263.     // ha az a sugár irányát vetítjük a normálvektorra, akkor meg
  264.     // megtudjuk, hogy az milyen gyorsan halad a sík fele.
  265.     // Innen a már csak a t = s / v képletet kell csak használnunk.
  266.     float ray_travel_dist = dot(a - r.origin, normal) / dot(r.direction, normal);
  267.  
  268.     // Ha a háromszög az ellenkező irányba van, mint
  269.     // amerre a sugár megy, akkor nincs metszéspontjuk
  270.     if(ray_travel_dist < 0)
  271.       return Intersection();
  272.  
  273.     // Számoljuk ki, hogy a sugár hol metszi a sugár síkját.
  274.     Vector plane_intersection = r.origin + ray_travel_dist * r.direction;
  275.  
  276.     /* Most már csak el kell döntenünk, hogy ez a pont a háromszög
  277.        belsejében van-e. Erre két lehetőség van:
  278.      
  279.        - A háromszög összes élére megnézzük, hogy a pontot a hároszög
  280.        egy megfelelő pontjával összekötve a kapott szakasz, és a háromszög
  281.        élének a vektoriális szorzata a normál irányába mutat-e.
  282.        Pl:
  283.      
  284.                  a
  285.                / |
  286.               /  |
  287.              /   |
  288.             /  x |  y
  289.            /     |
  290.           b------c
  291.  
  292.        Nézzük meg az x és y pontra ezt az algoritmust.
  293.        A cross(ab, ax), a cross(bc, bx), és a cross(ca, cx) és kifele mutat a
  294.        képernyőből, ugyan abba az irányba mint a normál vektor. Ezt amúgy a
  295.        dot(cross(ab, ax), normal) >= 0 összefüggéssel egyszerű ellenőrizni.
  296.        Az algoritmus alapján az x a háromszög belsejében van.
  297.  
  298.        Míg az y esetében a cross(ca, cy) befele mutat, a normállal ellenkező irányba,
  299.        tehát a dot(cross(ca, cy), normal) < 0 ami az algoritmus szerint azt jelenti,
  300.        hogy az y pont a háromszögön kívül van.
  301.      
  302.        - A ötlet lehetőség a barycentrikus koordinátáknak azt a tulajdonságát használja
  303.        ki, hogy azok a háromszög belsejében lévő pontokra kivétel nélkül nem negatívak,
  304.        míg a háromszögön kívül lévő pontokra legalább egy koordináta negatív.
  305.        Ennek a megoldásnak a használatához ki kell jelölnünk két tetszőleges, de egymásra
  306.        merőleges vektort a síkon, ezekre le kell vetíteninünk a háromszög pontjait, és
  307.        kérdéses pontot, és az így kapott koordinátákra alakzmanunk kell egy a wikipediáról
  308.        egyszerűen kimásolható képletet:
  309.        http://en.wikipedia.org/wiki/Barycentric_coordinate_system#Converting_to_barycentric_coordinates
  310.      
  311.        Én az első lehetőséget implementálom. */
  312.  
  313.     const Vector& x = plane_intersection;
  314.  
  315.     Vector ab = b - a;
  316.     Vector ax = x - a;
  317.  
  318.     Vector bc = c - b;
  319.     Vector bx = x - b;
  320.  
  321.     Vector ca = a - c;
  322.     Vector cx = x - c;
  323.  
  324.     if(dot(cross(ab, ax), normal) >= 0)
  325.       if(dot(cross(bc, bx), normal) >= 0)
  326.         if(dot(cross(ca, cx), normal) >= 0)
  327.           return Intersection(x, normal, true);
  328.  
  329.     return Intersection();
  330.   }
  331. };
  332.  
  333. void onDisplay() {
  334.   glClear(GL_COLOR_BUFFER_BIT);
  335.  
  336.   camera.takePicture();
  337.   Screen::Draw();
  338.  
  339.   glutSwapBuffers();
  340. }
  341.  
  342. void onIdle() {
  343.   static bool first_call = true;
  344.   if(first_call) {
  345.     glutPostRedisplay();
  346.     first_call = false;
  347.   }
  348. }
  349.  
  350. void onInitialization() {
  351.   Light amb = {Light::Ambient, Vector(), Color(0.2f, 0.2f, 0.2f)};
  352.   Light point = {Light::Point, Vector(-3, 4, -2), Color(20.0f, 20.0f, 20.0f)};
  353.   scene.AddLight(amb);
  354.   scene.AddLight(point);
  355.  
  356.   // Ground
  357.   scene.AddObject(new Triangle(&white, Vector(-10, -1.1f, -10), Vector(-10, -1.1f, +10), Vector(+10, -1.1f, +10)));
  358.   scene.AddObject(new Triangle(&white, Vector(+10, -1.1f, +10), Vector(+10, -1.1f, -10), Vector(-10, -1.1f, -10)));
  359.  
  360.   // Front face
  361.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(-1, -1, -1), Vector(-1, +1, -1)));
  362.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, -1), Vector(+1, +1, -1), Vector(+1, -1, -1)));
  363.  
  364.   // Back face
  365.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, +1), Vector(-1, -1, +1), Vector(-1, +1, +1)));
  366.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, +1), Vector(+1, +1, +1), Vector(+1, -1, +1)));
  367.  
  368.   // Right face
  369.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(+1, -1, +1), Vector(+1, +1, +1)));
  370.   scene.AddObject(new Triangle(&blue, Vector(+1, +1, +1), Vector(+1, +1, -1), Vector(+1, -1, -1)));
  371.  
  372.   // Left face
  373.   scene.AddObject(new Triangle(&blue, Vector(-1, -1, -1), Vector(-1, -1, +1), Vector(-1, +1, +1)));
  374.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, +1), Vector(-1, +1, -1), Vector(-1, -1, -1)));
  375.  
  376.   // Upper face
  377.   scene.AddObject(new Triangle(&blue, Vector(-1, +1, -1), Vector(-1, +1, +1), Vector(+1, +1, +1)));
  378.   scene.AddObject(new Triangle(&blue, Vector(+1, +1, -1), Vector(-1, +1, -1), Vector(+1, +1, +1)));
  379.  
  380.   // Lower face
  381.   scene.AddObject(new Triangle(&blue, Vector(-1, -1, +1), Vector(-1, -1, -1), Vector(+1, -1, +1)));
  382.   scene.AddObject(new Triangle(&blue, Vector(+1, -1, -1), Vector(+1, -1, +1), Vector(-1, -1, -1)));
  383. }
  384.  
  385. void onKeyboard(unsigned char key, int, int) {}
  386.  
  387. void onKeyboardUp(unsigned char key, int, int) {}
  388.  
  389. void onMouse(int, int, int, int) {}
  390.  
  391. void onMouseMotion(int, int) {}
  392.  
  393. int main(int argc, char **argv) {
  394.   glutInit(&argc, argv);
  395.   glutInitWindowSize(Screen::width, Screen::height);
  396.   glutInitWindowPosition(100, 100);
  397.   glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
  398.  
  399.   glutCreateWindow("Grafika pelda program");
  400.  
  401.   glMatrixMode(GL_MODELVIEW);
  402.   glLoadIdentity();
  403.   glMatrixMode(GL_PROJECTION);
  404.   glLoadIdentity();
  405.  
  406.   onInitialization();
  407.  
  408.   glutDisplayFunc(onDisplay);
  409.   glutMouseFunc(onMouse);
  410.   glutIdleFunc(onIdle);
  411.   glutKeyboardFunc(onKeyboard);
  412.   glutKeyboardUpFunc(onKeyboardUp);
  413.   glutMotionFunc(onMouseMotion);
  414.  
  415.   glutMainLoop();
  416.  
  417.   return 0;
  418. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement