IDRandomUtil.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <cmath>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include "BulletInverseDynamics/IDConfig.hpp"
  5. #include "BulletInverseDynamics/IDMath.hpp"
  6. #include "IDRandomUtil.hpp"
  7. namespace btInverseDynamics
  8. {
  9. // constants for random mass and inertia generation
  10. // these are arbitrary positive values.
  11. static const float mass_min = 0.001;
  12. static const float mass_max = 1.0;
  13. void randomInit() { srand(time(NULL)); }
  14. void randomInit(unsigned seed) { srand(seed); }
  15. int randomInt(int low, int high) { return rand() % (high + 1 - low) + low; }
  16. float randomFloat(float low, float high)
  17. {
  18. return low + static_cast<float>(rand()) / RAND_MAX * (high - low);
  19. }
  20. float randomMass() { return randomFloat(mass_min, mass_max); }
  21. vec3 randomInertiaPrincipal()
  22. {
  23. vec3 inertia;
  24. do
  25. {
  26. inertia(0) = randomFloat(mass_min, mass_max);
  27. inertia(1) = randomFloat(mass_min, mass_max);
  28. inertia(2) = randomFloat(mass_min, mass_max);
  29. } while (inertia(0) + inertia(1) < inertia(2) || inertia(0) + inertia(2) < inertia(1) ||
  30. inertia(1) + inertia(2) < inertia(0));
  31. return inertia;
  32. }
  33. mat33 randomInertiaMatrix()
  34. {
  35. // generate random valid inertia matrix by first getting valid components
  36. // along major axes and then rotating by random amount
  37. vec3 principal = randomInertiaPrincipal();
  38. mat33 rot(transformX(randomFloat(-BT_ID_PI, BT_ID_PI)) * transformY(randomFloat(-BT_ID_PI, BT_ID_PI)) *
  39. transformZ(randomFloat(-BT_ID_PI, BT_ID_PI)));
  40. mat33 inertia;
  41. inertia(0, 0) = principal(0);
  42. inertia(0, 1) = 0;
  43. inertia(0, 2) = 0;
  44. inertia(1, 0) = 0;
  45. inertia(1, 1) = principal(1);
  46. inertia(1, 2) = 0;
  47. inertia(2, 0) = 0;
  48. inertia(2, 1) = 0;
  49. inertia(2, 2) = principal(2);
  50. return rot * inertia * rot.transpose();
  51. }
  52. vec3 randomAxis()
  53. {
  54. vec3 axis;
  55. idScalar length;
  56. do
  57. {
  58. axis(0) = randomFloat(-1.0, 1.0);
  59. axis(1) = randomFloat(-1.0, 1.0);
  60. axis(2) = randomFloat(-1.0, 1.0);
  61. length = BT_ID_SQRT(BT_ID_POW(axis(0), 2) + BT_ID_POW(axis(1), 2) + BT_ID_POW(axis(2), 2));
  62. } while (length < 0.01);
  63. return axis / length;
  64. }
  65. } // namespace btInverseDynamics