Host C Specs


Directory: src/c/
Coverage: low: ≥ 0% medium: ≥ 75.0% high: ≥ 90.0%
Coverage Exec / Excl / Total
Lines: 100.0% 13 / 0 / 13
Functions: 100.0% 3 / 0 / 3
Branches: 100.0% 4 / 0 / 4

core/clock/tide.c
Line Branch Exec Source
1 /**
2 * @file tide.c
3 * @brief The rise and fall of a semidiurnal tide, from a plain running minute count.
4 *
5 * @ingroup lib_core
6 */
7 #include "clock/tide.h"
8
9 /// Half the cycle's length cubed, rounded down, which rounds the smoothstep to the nearest point
10 #define TIDE_HALF_CUBE ((TIDE_PERIOD_MIN * TIDE_PERIOD_MIN * TIDE_PERIOD_MIN) / 2)
11
12 // the most tide_level's first division can take, a remainder of the period less one minute times the
13 // largest scale, plus the half cube
14 _Static_assert((int64_t)(TIDE_PERIOD_MIN - 1) * 300 * TIDE_PERIOD_MIN
15 + (int64_t)TIDE_PERIOD_MIN * TIDE_PERIOD_MIN * TIDE_PERIOD_MIN / 2
16 <= INT32_MAX,
17 "a longer TIDE_PERIOD_MIN overflows tide_level's 32-bit maths");
18
19 /**
20 * @brief Where in the cycle a minute count lands.
21 *
22 * C truncates a negative division towards zero, which leaves a negative remainder, so this
23 * pulls it back up by hand.
24 *
25 * @param minutes A running minute count, on the same base as tide_level.
26 * @return The phase within the cycle, 0 to TIDE_PERIOD_MIN - 1.
27 */
28 5978 static int32_t phase(int32_t minutes)
29 {
30 5978 int32_t within = minutes % TIDE_PERIOD_MIN;
31
32
2/2
✓ Branch 2 → 3 taken 1489 times.
✓ Branch 2 → 4 taken 4489 times.
5978 return within < 0 ? within + TIDE_PERIOD_MIN : within;
33 }
34
35 5976 int tide_level(int32_t minutes)
36 {
37 // twice the phase, folded back at the turn, so it climbs from 0 to the period over the first
38 // half of the cycle and comes back down over the second
39 5976 int32_t twice = phase(minutes) * 2;
40
2/2
✓ Branch 3 → 4 taken 2980 times.
✓ Branch 3 → 5 taken 2996 times.
5976 int32_t climb = twice < TIDE_PERIOD_MIN ? twice : 2 * TIDE_PERIOD_MIN - twice;
41
42 // the smoothstep curve 3t^2-2t^3 of climb over the period, scaled to 0..100 and rounded once to
43 // the nearest point, so the level moves at most one point a minute
44 // dividing by the period and then by its square gives the same whole number as dividing by the
45 // cube, and keeps every step under 400 million, inside 32 bits
46 // the half cube that rounds it goes in before the first division
47 // added any later, the steps round down first and high water lasts only a few minutes
48 5976 int32_t square = climb * climb;
49 5976 int32_t scale = 100 * (3 * TIDE_PERIOD_MIN - 2 * climb);
50 5976 int32_t part = ((square % TIDE_PERIOD_MIN) * scale + TIDE_HALF_CUBE) / TIDE_PERIOD_MIN;
51 5976 int32_t over_period = (square / TIDE_PERIOD_MIN) * scale + part;
52
53 5976 return (int)(over_period / (TIDE_PERIOD_MIN * TIDE_PERIOD_MIN));
54 }
55
56 2 bool tide_rising(int32_t minutes)
57 {
58 2 return phase(minutes) * 2 < TIDE_PERIOD_MIN;
59 }
60