curve.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Curve interpolation
  3. *
  4. * Copyright (c) 2018-2020 Michael Buesch <m@bues.ch>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. */
  20. #include "compat.h"
  21. #include "debug.h"
  22. #include "curve.h"
  23. #include "util.h"
  24. /* Calculate and interpolate a curve Y value from an X value.
  25. *
  26. * y
  27. * ^ *
  28. * | *
  29. * -|- *
  30. * | *
  31. * |*
  32. * +------|---->x
  33. */
  34. uint16_t curve_interpolate(const struct curve_point __flash *curve,
  35. uint8_t curve_size,
  36. uint16_t x)
  37. {
  38. const struct curve_point __flash *rhp, *lhp;
  39. uint8_t i;
  40. uint16_t lx, ly;
  41. uint16_t rx, ry;
  42. uint16_t y;
  43. uint32_t tmp;
  44. /* Find the curve points
  45. * left handed and right handed to the x value. */
  46. lhp = &curve[0];
  47. rhp = lhp;
  48. for (i = 0u; i < curve_size; i++) {
  49. rhp = &curve[i];
  50. if (rhp->x >= x)
  51. break;
  52. lhp = rhp;
  53. }
  54. lx = lhp->x;
  55. ly = lhp->y;
  56. rx = rhp->x;
  57. ry = rhp->y;
  58. /* Linear interpolation between lhp and rhp:
  59. * ((x - lx) * ((ry - ly) / (rx - lx))) + ly */
  60. if (rx - lx == 0u) {
  61. y = ly;
  62. } else {
  63. tmp = x - lx;
  64. tmp *= ry - ly;
  65. tmp /= rx - lx;
  66. tmp += ly;
  67. y = lim_u16(tmp);
  68. }
  69. return y;
  70. }