blob: 4eba44802a10e234f2d3a09c1024ed89d89a69fe [file] [log] [blame]
Philipp Schradere8ad6382017-04-09 21:51:21 +00001#include "frc971/shooter_interpolation/interpolation.h"
2
3#include <algorithm>
4#include <utility>
5#include <vector>
6
7namespace frc971 {
8namespace shooter_interpolation {
9
10namespace {
11
12double Blend(double coefficient, double a1, double a2) {
13 return (1 - coefficient) * a1 + coefficient * a2;
14}
15
16ShotParams Blend(double coefficient, ShotParams a1, ShotParams a2) {
17 return ShotParams{Blend(coefficient, a1.angle, a2.angle),
18 Blend(coefficient, a1.power, a2.power)};
19}
20
21} // namespace
22
23InterpolationTable::InterpolationTable(
Philipp Schrader9a833362017-04-09 22:56:16 +000024 const ::std::vector<::std::pair<double, ShotParams>> &table)
25 : table_(table) {
26 ::std::sort(table_.begin(), table_.end(),
Philipp Schradere8ad6382017-04-09 21:51:21 +000027 [](const ::std::pair<double, ShotParams> &a,
28 const ::std::pair<double, ShotParams> &b) {
29 return a.first < b.first;
30 });
31}
32
Parker Schuh208a58d2017-04-12 20:51:38 -070033ShotParams InterpolationTable::GetShooterData(double distance) const {
Philipp Schradere8ad6382017-04-09 21:51:21 +000034 // Points to to the smallest item such that it->first >= dist, or end() if no
35 // such item exists.
Philipp Schrader9a833362017-04-09 22:56:16 +000036 auto it = ::std::lower_bound(table_.begin(), table_.end(), distance,
37 [](const ::std::pair<double, ShotParams> &a,
38 double dist) { return a.first < dist; });
39 if (it == table_.begin()) {
Philipp Schradere8ad6382017-04-09 21:51:21 +000040 return it->second;
Philipp Schrader9a833362017-04-09 22:56:16 +000041 } else if (it == table_.end()) {
42 return table_.back().second;
Philipp Schradere8ad6382017-04-09 21:51:21 +000043 } else {
44 auto x_a2 = it;
45 auto x_a1 = it - 1;
46 double x1 = x_a1->first;
47 double x2 = x_a2->first;
48 double coefficient = (distance - x1) / (x2 - x1);
49 return Blend(coefficient, x_a1->second, x_a2->second);
50 }
51}
52
53} // namespace shooter_interpolation
54} // namespace frc971