FhSim  3.1.0
Marine systems simulation
Loading...
Searching...
No Matches
TableLookup.h
1#ifndef TableLookup_h__
2#define TableLookup_h__
3
4#include <cstddef>
5#include <functional>
6#include <string>
7#include <utility>
8#include <vector>
9
10namespace Ship
11{
12
18{
19public:
20 using Sink = std::function<void(const std::string&)>;
21
22 void SetSink(Sink sink) { m_sink = std::move(sink); }
23
25 void Warn(const std::string& message)
26 {
27 if (m_count++ == 0 && m_sink) {
28 m_sink(message);
29 }
30 }
31
33 int Count() const { return m_count; }
34
35private:
36 Sink m_sink;
37 int m_count = 0;
38};
39
42{
43 std::size_t lower;
44 double value;
45 bool held;
46};
47
53inline AxisInterval FindInterval(const std::vector<double>& axis, double x)
54{
55 if (axis.size() < 2) {
56 return {0, axis.empty() ? x : axis.front(), axis.empty() || x != axis.front()};
57 }
58 if (!(x >= axis.front())) { // also holds a NaN to the first node
59 return {0, axis.front(), true};
60 }
61 if (x > axis.back()) {
62 return {axis.size() - 2, axis.back(), true};
63 }
64 std::size_t lower = 0;
65 while (lower + 2 < axis.size() && axis[lower + 1] < x) {
66 ++lower;
67 }
68 return {lower, x, false};
69}
70
72inline double Lerp(double xLow, double xHigh, double yLow, double yHigh, double x)
73{
74 if (xHigh == xLow) {
75 return yLow;
76 }
77 return yLow + (yHigh - yLow) * (x - xLow) / (xHigh - xLow);
78}
79
80} // namespace Ship
81
82#endif // TableLookup_h__
Definition TableLookup.h:18
void Warn(const std::string &message)
Passes message to the sink the first time only.
Definition TableLookup.h:25
int Count() const
How many times Warn was called.
Definition TableLookup.h:33
Simple waypoint object.
Definition CableAttach.h:16
AxisInterval FindInterval(const std::vector< double > &axis, double x)
Definition TableLookup.h:53
double Lerp(double xLow, double xHigh, double yLow, double yHigh, double x)
The linear value at x between the nodes (xLow, yLow) and (xHigh, yHigh); yLow when the nodes coincide...
Definition TableLookup.h:72
The interval of an ascending axis that holds a value, with the value held at the edges.
Definition TableLookup.h:42
bool held
true when the queried value was outside the axis
Definition TableLookup.h:45
double value
the queried value held to [axis.front(), axis.back()]
Definition TableLookup.h:44
std::size_t lower
index of the lower node; lower + 1 is the upper node. Zero for an axis of one node.
Definition TableLookup.h:43