random_dir.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "random_dir.h"
  2. #include <igl/PI.h>
  3. #include <cmath>
  4. Eigen::Vector3d igl::random_dir()
  5. {
  6. using namespace Eigen;
  7. using namespace igl;
  8. double z = (double)rand() / (double)RAND_MAX*2.0 - 1.0;
  9. double t = (double)rand() / (double)RAND_MAX*2.0*PI;
  10. // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/
  11. double r = sqrt(1.0-z*z);
  12. double x = r * cos(t);
  13. double y = r * sin(t);
  14. return Vector3d(x,y,z);
  15. }
  16. Eigen::MatrixXd igl::random_dir_stratified(const int n)
  17. {
  18. using namespace Eigen;
  19. using namespace igl;
  20. using namespace std;
  21. const double m = floor(sqrt(double(n)));
  22. MatrixXd N(n,3);
  23. int row = 0;
  24. for(int i = 0;i<m;i++)
  25. {
  26. const double x = double(i)*1./m;
  27. for(int j = 0;j<m;j++)
  28. {
  29. const double y = double(j)*1./m;
  30. double z = (x+(1./m)*(double)rand() / (double)RAND_MAX)*2.0 - 1.0;
  31. double t = (y+(1./m)*(double)rand() / (double)RAND_MAX)*2.0*PI;
  32. double r = sqrt(1.0-z*z);
  33. N(row,0) = r * cos(t);
  34. N(row,1) = r * sin(t);
  35. N(row,2) = z;
  36. row++;
  37. }
  38. }
  39. // Finish off with uniform random directions
  40. for(;row<n;row++)
  41. {
  42. N.row(row) = random_dir();
  43. }
  44. return N;
  45. }