Ellipse.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Math/Float2.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// Ellipse centered around the origin
  8. /// @see https://en.wikipedia.org/wiki/Ellipse
  9. class Ellipse
  10. {
  11. public:
  12. JPH_OVERRIDE_NEW_DELETE
  13. /// Construct ellipse with radius A along the X-axis and B along the Y-axis
  14. Ellipse(float inA, float inB) : mA(inA), mB(inB) { JPH_ASSERT(inA > 0.0f); JPH_ASSERT(inB > 0.0f); }
  15. /// Check if inPoint is inside the ellipsse
  16. bool IsInside(const Float2 &inPoint) const
  17. {
  18. return Square(inPoint.x / mA) + Square(inPoint.y / mB) <= 1.0f;
  19. }
  20. /// Get the closest point on the ellipse to inPoint
  21. /// Assumes inPoint is outside the ellipse
  22. /// @see Rotation Joint Limits in Quaterion Space by Gino van den Bergen, section 10.1 in Game Engine Gems 3.
  23. Float2 GetClosestPoint(const Float2 &inPoint) const
  24. {
  25. float a_sq = Square(mA);
  26. float b_sq = Square(mB);
  27. // Equation of ellipse: f(x, y) = (x/a)^2 + (y/b)^2 - 1 = 0 [1]
  28. // Normal on surface: (df/dx, df/dy) = (2 x / a^2, 2 y / b^2)
  29. // Closest point (x', y') on ellipse to point (x, y): (x', y') + t (x / a^2, y / b^2) = (x, y)
  30. // <=> (x', y') = (a^2 x / (t + a^2), b^2 y / (t + b^2))
  31. // Requiring point to be on ellipse (substituting into [1]): g(t) = (a x / (t + a^2))^2 + (b y / (t + b^2))^2 - 1 = 0
  32. // Newton raphson iteration, starting at t = 0
  33. float t = 0.0f;
  34. for (;;)
  35. {
  36. // Calculate g(t)
  37. float t_plus_a_sq = t + a_sq;
  38. float t_plus_b_sq = t + b_sq;
  39. float gt = Square(mA * inPoint.x / t_plus_a_sq) + Square(mB * inPoint.y / t_plus_b_sq) - 1.0f;
  40. // Check if g(t) it is close enough to zero
  41. if (abs(gt) < 1.0e-6f)
  42. return Float2(a_sq * inPoint.x / t_plus_a_sq, b_sq * inPoint.y / t_plus_b_sq);
  43. // Get derivative dg/dt = g'(t) = -2 (b^2 y^2 / (t + b^2)^3 + a^2 x^2 / (t + a^2)^3)
  44. float gt_accent = -2.0f *
  45. (a_sq * Square(inPoint.x) / Cubed(t_plus_a_sq)
  46. + b_sq * Square(inPoint.y) / Cubed(t_plus_b_sq));
  47. // Calculate t for next iteration: tn+1 = tn - g(t) / g'(t)
  48. float tn = t - gt / gt_accent;
  49. t = tn;
  50. }
  51. }
  52. /// Get normal at point inPoint (non-normalized vector)
  53. Float2 GetNormal(const Float2 &inPoint) const
  54. {
  55. // Calculated by [d/dx f(x, y), d/dy f(x, y)], where f(x, y) is the ellipse equation from above
  56. return Float2(inPoint.x / Square(mA), inPoint.y / Square(mB));
  57. }
  58. private:
  59. float mA; ///< Radius along X-axis
  60. float mB; ///< Radius along Y-axis
  61. };
  62. JPH_NAMESPACE_END