random_dir.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "random_dir.h"
  9. #include <igl/PI.h>
  10. #include <cmath>
  11. IGL_INLINE Eigen::Vector3d igl::random_dir()
  12. {
  13. using namespace Eigen;
  14. double z = (double)rand() / (double)RAND_MAX*2.0 - 1.0;
  15. double t = (double)rand() / (double)RAND_MAX*2.0*PI;
  16. // http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/
  17. double r = sqrt(1.0-z*z);
  18. double x = r * cos(t);
  19. double y = r * sin(t);
  20. return Vector3d(x,y,z);
  21. }
  22. IGL_INLINE Eigen::MatrixXd igl::random_dir_stratified(const int n)
  23. {
  24. using namespace Eigen;
  25. using namespace std;
  26. const double m = std::floor(sqrt(double(n)));
  27. MatrixXd N(n,3);
  28. int row = 0;
  29. for(int i = 0;i<m;i++)
  30. {
  31. const double x = double(i)*1./m;
  32. for(int j = 0;j<m;j++)
  33. {
  34. const double y = double(j)*1./m;
  35. double z = (x+(1./m)*(double)rand() / (double)RAND_MAX)*2.0 - 1.0;
  36. double t = (y+(1./m)*(double)rand() / (double)RAND_MAX)*2.0*PI;
  37. double r = sqrt(1.0-z*z);
  38. N(row,0) = r * cos(t);
  39. N(row,1) = r * sin(t);
  40. N(row,2) = z;
  41. row++;
  42. }
  43. }
  44. // Finish off with uniform random directions
  45. for(;row<n;row++)
  46. {
  47. N.row(row) = random_dir();
  48. }
  49. return N;
  50. }