LinearCurve.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/ObjectStream/SerializableObject.h>
  5. #include <Jolt/Core/QuickSort.h>
  6. JPH_NAMESPACE_BEGIN
  7. class StreamOut;
  8. class StreamIn;
  9. // A set of points (x, y) that form a linear curve
  10. class LinearCurve
  11. {
  12. public:
  13. JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(LinearCurve)
  14. /// A point on the curve
  15. class Point
  16. {
  17. public:
  18. JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(Point)
  19. float mX = 0.0f;
  20. float mY = 0.0f;
  21. };
  22. /// Remove all points
  23. void Clear() { mPoints.clear(); }
  24. /// Reserve memory for inNumPoints points
  25. void Reserve(uint inNumPoints) { mPoints.reserve(inNumPoints); }
  26. /// Add a point to the curve. Points must be inserted in ascending X or Sort() needs to be called when all points have been added.
  27. /// @param inX X value
  28. /// @param inY Y value
  29. void AddPoint(float inX, float inY) { mPoints.push_back({ inX, inY }); }
  30. /// Sort the points on X ascending
  31. void Sort() { QuickSort(mPoints.begin(), mPoints.end(), [](const Point &inLHS, const Point &inRHS) { return inLHS.mX < inRHS.mX; }); }
  32. /// Get the lowest X value
  33. float GetMinX() const { return mPoints.empty()? 0.0f : mPoints.front().mX; }
  34. /// Get the highest X value
  35. float GetMaxX() const { return mPoints.empty()? 0.0f : mPoints.back().mX; }
  36. /// Sample value on the curve
  37. /// @param inX X value to sample at
  38. /// @return Interpolated Y value
  39. float GetValue(float inX) const;
  40. /// Saves the state of this object in binary form to inStream.
  41. void SaveBinaryState(StreamOut &inStream) const;
  42. /// Restore the state of this object from inStream.
  43. void RestoreBinaryState(StreamIn &inStream);
  44. /// The points on the curve, should be sorted ascending by x
  45. using Points = Array<Point>;
  46. Points mPoints;
  47. };
  48. JPH_NAMESPACE_END