Posted By

gyunjgf2 on 05/16/12


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

LordCasius


Voxel Raycaster


 / Published in: C++
 

Traverses unit cubes given a starting position and direction vector.

  1. //Raycaster.h
  2.  
  3. #ifndef RAYCASTER_H
  4. #define RAYCASTER_H
  5.  
  6. #include <glm\glm.hpp>
  7.  
  8. class Raycaster
  9. {
  10. public:
  11. Raycaster(glm::vec3 p, glm::vec3 p_dir);
  12. glm::ivec3 getNextVoxel();
  13. private:
  14. glm::vec3 pos;
  15. glm::vec3 dir;
  16. bool xplus;
  17. bool yplus;
  18. bool zplus;
  19. };
  20.  
  21. #endif
  22.  
  23.  
  24. //Raycaster.cpp
  25. #include "Raycaster.h"
  26.  
  27. Raycaster::Raycaster(glm::vec3 p, glm::vec3 p_dir)
  28. {
  29. pos = p;
  30. dir = p_dir;
  31. xplus = true;
  32. yplus = true;
  33. zplus = true;
  34. if (dir.x < 0)
  35. xplus = false;
  36. if (dir.y < 0)
  37. yplus = false;
  38. if (dir.z < 0)
  39. zplus = false;
  40. }
  41.  
  42. glm::ivec3 Raycaster::getNextVoxel()
  43. {
  44. int nextX = (int) pos.x;
  45. int nextY = (int) pos.y;
  46. int nextZ = (int) pos.z;
  47. if (xplus)
  48. nextX++;
  49. if (yplus)
  50. nextY++;
  51. if (zplus)
  52. nextZ++;
  53. float distanceX = nextX - pos.x;
  54. float distanceY = nextY - pos.y;
  55. float distanceZ = nextZ - pos.z;
  56. float qx = distanceX / dir.x;
  57. float qy = distanceY / dir.y;
  58. float qz = distanceZ / dir.z;
  59.  
  60. //The qx/y/z+=0.000001; is a quick and dirty solution
  61. //to enable the continuation of the raycast.
  62. if (qx <= qy && qx <= qz)
  63. {
  64. qx+=0.000001;
  65. pos += qx * dir;
  66. }
  67. else if (qy <= qx && qy <= qz)
  68. {
  69. qy+=0.000001;
  70. pos += qy * dir;
  71. }
  72. else if (qz <= qx && qz <= qy)
  73. {
  74. qz+=0.000001;
  75. pos += qz * dir;
  76. }
  77.  
  78. return glm::ivec3( (int) pos.x, (int) pos.y, (int) pos.z);
  79.  
  80. }

Report this snippet  

You need to login to post a comment.