./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
14 / 14
100.0%
Branches:
6 / 6
100.0%
Functions:
3 / 3
100.0%

src/noise/structure_function.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "terraingen/noise/structure_function.h"
4
5 #include <array>
6 #include <cmath>
7 #include <cstddef>
8
9 namespace terraingen {
10
11 namespace {
12
13 /// `PerlinStructureFunction(r) / r^2` at r = 2^(k / 4) for k from `kFirstQuarter`, estimated from
14 /// 2^26 pairs each.
15 constexpr int kFirstQuarter = -24;
16 constexpr std::array<double, 33> kStructureOverSquare{
17 0.772366, 0.772241, 0.772129, 0.771929, 0.771444, 0.770975, 0.770202, 0.769434, 0.767832,
18 0.766070, 0.763032, 0.759311, 0.753675, 0.745950, 0.735267, 0.720564, 0.700391, 0.673043,
19 0.636947, 0.589660, 0.530574, 0.459215, 0.377706, 0.291690, 0.209524, 0.141536, 0.094237,
20 0.065236, 0.046153, 0.032397, 0.022947, 0.016231, 0.011443};
21 constexpr double kLargeLag = 0.183120;
22
23 /// `Perlin3StructureFunction(r) / r^2` on the same lags, estimated from 2^24 pairs each.
24 constexpr std::array<double, 33> kStructure3OverSquare{
25 0.494082, 0.494230, 0.494034, 0.493864, 0.493805, 0.493342, 0.493074, 0.492376, 0.491455,
26 0.490546, 0.488813, 0.486484, 0.483336, 0.478718, 0.472398, 0.463827, 0.452007, 0.435827,
27 0.414506, 0.386695, 0.351648, 0.308521, 0.258949, 0.205715, 0.153652, 0.108458, 0.074433,
28 0.051596, 0.036333, 0.025663, 0.018156, 0.012839, 0.009067};
29 constexpr double kLargeLag3 = 0.145198;
30
31 /// A structure function at lag `r` from its `table` of value over r^2, `large` beyond the table.
32 4373 double Interpolated(const std::array<double, 33>& table, double large, double r) {
33
2/2
✓ Branch 0 taken 4370 times.
✓ Branch 1 taken 3 times.
4373 if (!(r > 0.0)) {
34 return 0.0;
35 }
36 4370 const double quarters = 4.0 * std::log2(r) - kFirstQuarter;
37
2/2
✓ Branch 0 taken 646 times.
✓ Branch 1 taken 3724 times.
4370 if (quarters <= 0.0) {
38 646 return table.front() * r * r;
39 }
40 3724 const auto last = static_cast<double>(table.size() - 1);
41
2/2
✓ Branch 0 taken 1766 times.
✓ Branch 1 taken 1958 times.
3724 if (quarters >= last) {
42 return large;
43 }
44 1766 const auto k = static_cast<std::size_t>(quarters);
45 1766 const double t = quarters - static_cast<double>(k);
46 1766 return ((1.0 - t) * table[k] + t * table[k + 1]) * r * r;
47 }
48
49 } // namespace
50
51 2472 double PerlinStructureFunction(double r) {
52 2472 return Interpolated(kStructureOverSquare, kLargeLag, r);
53 }
54
55 1901 double Perlin3StructureFunction(double r) {
56 1901 return Interpolated(kStructure3OverSquare, kLargeLag3, r);
57 }
58
59 } // namespace terraingen
60