PageRenderTime 23ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Attraction.cpp

https://github.com/bloomtime/CinderTraer
C++ | 119 lines | 84 code | 28 blank | 7 comment | 6 complexity | 47bfbbf0ed3e3180ccd984e5bef415f0 MD5 | raw file
  1. // attract positive repel negative
  2. #include <cmath>
  3. #include "cinder/Vector.h"
  4. #include "Attraction.h"
  5. namespace traer { namespace physics {
  6. Attraction::Attraction( Particle* _a, Particle* _b, float _k, float _distanceMin )
  7. {
  8. a = _a;
  9. b = _b;
  10. k = _k;
  11. on = true;
  12. distanceMin = _distanceMin;
  13. distanceMinSquared = distanceMin*distanceMin;
  14. }
  15. float Attraction::getMinimumDistance()
  16. {
  17. return distanceMin;
  18. }
  19. void Attraction::setMinimumDistance( float d )
  20. {
  21. distanceMin = d;
  22. distanceMinSquared = d*d;
  23. }
  24. void Attraction::turnOff()
  25. {
  26. on = false;
  27. }
  28. void Attraction::turnOn()
  29. {
  30. on = true;
  31. }
  32. void Attraction::setStrength( float _k )
  33. {
  34. k = k;
  35. }
  36. Particle* Attraction::getOneEnd()
  37. {
  38. return a;
  39. }
  40. Particle* Attraction::getTheOtherEnd()
  41. {
  42. return b;
  43. }
  44. void Attraction::apply()
  45. {
  46. if ( on && ( !a->fixed || !b->fixed ) )
  47. {
  48. ci::Vec3f a2b = a->position - b->position;
  49. float a2bDistanceSquared = a2b.lengthSquared();
  50. if ( a2bDistanceSquared < distanceMinSquared )
  51. a2bDistanceSquared = distanceMinSquared;
  52. float force = k * a->mass * b->mass / a2bDistanceSquared;
  53. // make unit vector
  54. //a2b /= sqrt(a2bDistanceSquared);
  55. // multiply by force
  56. //a2b *= force;
  57. a2b *= Q_rsqrt(a2bDistanceSquared) * force;
  58. // apply
  59. if ( !a->fixed )
  60. a->force -= a2b;
  61. if ( !b->fixed )
  62. b->force += a2b;
  63. }
  64. }
  65. float Attraction::getStrength()
  66. {
  67. return k;
  68. }
  69. bool Attraction::isOn() const
  70. {
  71. return on;
  72. }
  73. bool Attraction::isOff() const
  74. {
  75. return !on;
  76. }
  77. float Attraction::Q_rsqrt( float number )
  78. {
  79. long i;
  80. float x2, y;
  81. const float threehalfs = 1.5F;
  82. x2 = number * 0.5F;
  83. y = number;
  84. i = * ( long * ) &y; // evil floating point bit level hacking [sic]
  85. i = 0x5f3759df - ( i >> 1 ); // what the fuck? [sic]
  86. y = * ( float * ) &i;
  87. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  88. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  89. return y;
  90. }
  91. } } // namespace traer::physics