src/sources/seam_field.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "sources/seam_field.h" | ||
| 4 | |||
| 5 | #include "raster/kernels.h" | ||
| 6 | #include "terraingen/raster/resample.h" | ||
| 7 | |||
| 8 | #include <algorithm> | ||
| 9 | #include <array> | ||
| 10 | #include <cmath> | ||
| 11 | #include <cstdint> | ||
| 12 | #include <limits> | ||
| 13 | #include <utility> | ||
| 14 | |||
| 15 | namespace terraingen::detail { | ||
| 16 | |||
| 17 | namespace { | ||
| 18 | |||
| 19 | /// Posts along each side of a field tile. | ||
| 20 | constexpr std::size_t kTileSide = 64; | ||
| 21 | |||
| 22 | /// Rows of the lattice filled at once when finding where the earlier source has data. | ||
| 23 | constexpr std::size_t kStripRows = 64; | ||
| 24 | |||
| 25 | /// Posts from a gap within which the earlier source's posts hold their height difference. | ||
| 26 | constexpr std::size_t kBandPosts = 3; | ||
| 27 | |||
| 28 | /// Posts at the lattice's edges that are never solved for, so stencils stay on the lattice. | ||
| 29 | constexpr std::size_t kBorderPosts = 3; | ||
| 30 | |||
| 31 | /// Gauss-Seidel sweeps before and after each coarse correction. | ||
| 32 | constexpr int kSmoothingSweeps = 2; | ||
| 33 | |||
| 34 | /// Pairs of forward and backward Gauss-Seidel sweeps on the coarsest level. | ||
| 35 | constexpr int kCoarsestSweeps = 50; | ||
| 36 | |||
| 37 | /// Unknown posts at or below which a level is the coarsest. | ||
| 38 | constexpr std::size_t kCoarsestPosts = 32; | ||
| 39 | |||
| 40 | /// The most levels of a multigrid hierarchy. | ||
| 41 | constexpr std::size_t kMaxLevels = 24; | ||
| 42 | |||
| 43 | /// The residual, relative to the first, at which the conjugate gradients stop. | ||
| 44 | constexpr double kTolerance = 1e-10; | ||
| 45 | |||
| 46 | /// The most conjugate gradient iterations of a solve. | ||
| 47 | constexpr int kMaxIterations = 200; | ||
| 48 | |||
| 49 | /// Weights of the coarse posts a fine post's correction is interpolated from: its parent, the | ||
| 50 | /// parent's neighbor across the fine post's column, across its row, and diagonally. | ||
| 51 | constexpr std::array<double, 4> kTransfer{9.0 / 16.0, 3.0 / 16.0, 3.0 / 16.0, 1.0 / 16.0}; | ||
| 52 | |||
| 53 | /// A lattice's posts and the distances between them. | ||
| 54 | struct Posts { | ||
| 55 | std::size_t width = 0; | ||
| 56 | std::size_t height = 0; | ||
| 57 | double dx = 0.0; ///< Between columns, in the lattice's units. | ||
| 58 | double dy = 0.0; ///< Between rows, in the lattice's units. | ||
| 59 | GeoTransform transform{}; | ||
| 60 | |||
| 61 | 46 | std::size_t Size() const { | |
| 62 | 23 | return width * height; | |
| 63 | } | ||
| 64 | }; | ||
| 65 | |||
| 66 | /// Where the earlier source has data on the posts, and how far the later source is below it. | ||
| 67 | 23 | struct Sampled { | |
| 68 | std::vector<std::uint8_t> data; ///< 1 at each post where the earlier source has data. | ||
| 69 | /// The earlier source's height less the later one's at each post where both have data, NaN | ||
| 70 | /// elsewhere. | ||
| 71 | std::vector<float> difference; | ||
| 72 | }; | ||
| 73 | |||
| 74 | /// `earlier` and `later` filled at `spacing` on the posts a strip of rows at a time, `later` only | ||
| 75 | /// in the strips where `earlier` has data. | ||
| 76 | 23 | Sampled SampleSources(const Source& earlier, const Source& later, const Posts& posts, | |
| 77 | double spacing) { | ||
| 78 | 46 | Sampled sampled{std::vector<std::uint8_t>(posts.Size(), 0), | |
| 79 | 23 | std::vector<float>(posts.Size(), std::numeric_limits<float>::quiet_NaN())}; | |
| 80 | 68 | for (std::size_t top = 0; top < posts.height; top += kStripRows) { | |
| 81 | 45 | const std::size_t rows = std::min(kStripRows, posts.height - top); | |
| 82 | 45 | GeoTransform transform = posts.transform; | |
| 83 | 45 | const Vec2d origin = posts.transform.PixelToWorld(0.0, static_cast<double>(top)); | |
| 84 | 45 | transform.originX = origin.x; | |
| 85 | 45 | transform.originY = origin.y; | |
| 86 | 45 | Raster<float> above(RasterGrid{posts.width, rows, transform}); | |
| 87 | 45 | earlier.Fill(above, spacing); | |
| 88 | bool any = false; | ||
| 89 | 2657 | for (std::size_t row = 0; row < rows; ++row) { | |
| 90 | 914956 | for (std::size_t col = 0; col < posts.width; ++col) { | |
| 91 | 912344 | const bool has = !above.IsMissing(above(col, row)); | |
| 92 | 990404 | sampled.data[(top + row) * posts.width + col] = has ? 1 : 0; | |
| 93 | 912344 | any = any || has; | |
| 94 | } | ||
| 95 | } | ||
| 96 | 45 | if (!any) { | |
| 97 | 1 | continue; | |
| 98 | } | ||
| 99 | 44 | Raster<float> below(RasterGrid{posts.width, rows, transform}); | |
| 100 | 44 | later.Fill(below, spacing); | |
| 101 | 2626 | for (std::size_t row = 0; row < rows; ++row) { | |
| 102 | 910186 | for (std::size_t col = 0; col < posts.width; ++col) { | |
| 103 | 907604 | const float a = above(col, row); | |
| 104 | 907604 | const float b = below(col, row); | |
| 105 | 907604 | if (!above.IsMissing(a) && !below.IsMissing(b) && std::isfinite(a) && | |
| 106 | 834284 | std::isfinite(b)) { | |
| 107 | 834284 | sampled.difference[(top + row) * posts.width + col] = | |
| 108 | 834284 | static_cast<float>(static_cast<double>(a) - static_cast<double>(b)); | |
| 109 | } | ||
| 110 | } | ||
| 111 | } | ||
| 112 | 45 | } | |
| 113 | 23 | return sampled; | |
| 114 | } | ||
| 115 | |||
| 116 | /// 1 at each post within `radius` posts along both axes of a post without data. | ||
| 117 | 23 | std::vector<std::uint8_t> NearGaps(const std::vector<std::uint8_t>& data, const Posts& posts, | |
| 118 | std::size_t radius) { | ||
| 119 | 23 | const std::size_t width = posts.width; | |
| 120 | 23 | const std::size_t height = posts.height; | |
| 121 | 23 | std::vector<std::uint8_t> across(data.size(), 0); | |
| 122 | 2635 | for (std::size_t row = 0; row < height; ++row) { | |
| 123 | 914956 | for (std::size_t col = 0; col < width; ++col) { | |
| 124 | 912344 | const std::size_t last = std::min(width - 1, col + radius); | |
| 125 | 7633698 | for (std::size_t c = col >= radius ? col - radius : 0; c <= last; ++c) { | |
| 126 | 5891546 | if (data[row * width + c] == 0) { | |
| 127 | 82536 | across[row * width + col] = 1; | |
| 128 | 82536 | break; | |
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
| 132 | } | ||
| 133 | 23 | std::vector<std::uint8_t> marked(data.size(), 0); | |
| 134 | 2635 | for (std::size_t row = 0; row < height; ++row) { | |
| 135 | 2612 | const std::size_t last = std::min(height - 1, row + radius); | |
| 136 | 914956 | for (std::size_t col = 0; col < width; ++col) { | |
| 137 | 7603122 | for (std::size_t r = row >= radius ? row - radius : 0; r <= last; ++r) { | |
| 138 | 5865230 | if (across[r * width + col] != 0) { | |
| 139 | 86796 | marked[row * width + col] = 1; | |
| 140 | 86796 | break; | |
| 141 | } | ||
| 142 | } | ||
| 143 | } | ||
| 144 | } | ||
| 145 | 23 | return marked; | |
| 146 | 23 | } | |
| 147 | |||
| 148 | /// The chamfer distance in the lattice's units from each post to the nearest post with data, | ||
| 149 | /// over steps to the eight neighbors; with `carried`, each post without data takes the value of | ||
| 150 | /// `carried` at the post its distance comes from. | ||
| 151 | 23 | std::vector<float> DataDistances(const std::vector<std::uint8_t>& data, const Posts& posts, | |
| 152 | std::vector<float>* carried) { | ||
| 153 | 23 | const std::size_t width = posts.width; | |
| 154 | 23 | const std::size_t height = posts.height; | |
| 155 | 23 | std::vector<float> distance(data.size(), std::numeric_limits<float>::infinity()); | |
| 156 | 912367 | for (std::size_t k = 0; k < data.size(); ++k) { | |
| 157 | 912344 | if (data[k] != 0) { | |
| 158 | 834284 | distance[k] = 0.0f; | |
| 159 | } | ||
| 160 | } | ||
| 161 | 23 | const auto dx = static_cast<float>(posts.dx); | |
| 162 | 23 | const auto dy = static_cast<float>(posts.dy); | |
| 163 | 23 | const auto diagonal = static_cast<float>(std::hypot(posts.dx, posts.dy)); | |
| 164 | 608555 | const auto relax = [&](std::size_t to, std::size_t from, float step) { | |
| 165 | 608532 | const float through = distance[from] + step; | |
| 166 | 608532 | if (through < distance[to]) { | |
| 167 | 157697 | distance[to] = through; | |
| 168 | 157697 | if (carried) { | |
| 169 | 12705 | (*carried)[to] = (*carried)[from]; | |
| 170 | } | ||
| 171 | } | ||
| 172 | 608555 | }; | |
| 173 | 2635 | for (std::size_t row = 0; row < height; ++row) { | |
| 174 | 914956 | for (std::size_t col = 0; col < width; ++col) { | |
| 175 | 912344 | const std::size_t k = row * width + col; | |
| 176 | 912344 | if (data[k] != 0) { | |
| 177 | 834284 | continue; | |
| 178 | } | ||
| 179 | 78060 | if (col > 0) { | |
| 180 | 76724 | relax(k, k - 1, dx); | |
| 181 | } | ||
| 182 | 78060 | if (row > 0) { | |
| 183 | 76724 | relax(k, k - width, dy); | |
| 184 | 76724 | if (col > 0) { | |
| 185 | 75409 | relax(k, k - width - 1, diagonal); | |
| 186 | } | ||
| 187 | 76724 | if (col + 1 < width) { | |
| 188 | 75409 | relax(k, k - width + 1, diagonal); | |
| 189 | } | ||
| 190 | } | ||
| 191 | } | ||
| 192 | } | ||
| 193 | 2635 | for (std::size_t row = height; row-- > 0;) { | |
| 194 | 914956 | for (std::size_t col = width; col-- > 0;) { | |
| 195 | 912344 | const std::size_t k = row * width + col; | |
| 196 | 912344 | if (data[k] != 0) { | |
| 197 | 834284 | continue; | |
| 198 | } | ||
| 199 | 78060 | if (col + 1 < width) { | |
| 200 | 76724 | relax(k, k + 1, dx); | |
| 201 | } | ||
| 202 | 78060 | if (row + 1 < height) { | |
| 203 | 76724 | relax(k, k + width, dy); | |
| 204 | 76724 | if (col + 1 < width) { | |
| 205 | 75409 | relax(k, k + width + 1, diagonal); | |
| 206 | } | ||
| 207 | 76724 | if (col > 0) { | |
| 208 | 75409 | relax(k, k + width - 1, diagonal); | |
| 209 | } | ||
| 210 | } | ||
| 211 | } | ||
| 212 | } | ||
| 213 | 23 | return distance; | |
| 214 | } | ||
| 215 | |||
| 216 | /// Sets each post without data within `width` of a post with data to the height difference at | ||
| 217 | /// the nearest edge post, faded by a smoothstep from 1 at the edge to 0 at `width`. | ||
| 218 | 5 | void Feather(SeamField& field, const std::vector<std::uint8_t>& data, const Posts& posts, | |
| 219 | double width) { | ||
| 220 | 5 | std::vector<float> carried(data.size(), 0.0f); | |
| 221 | 239 | for (std::size_t row = 0; row < posts.height; ++row) { | |
| 222 | 11198 | for (std::size_t col = 0; col < posts.width; ++col) { | |
| 223 | 10964 | if (data[row * posts.width + col] != 0) { | |
| 224 | 4976 | carried[row * posts.width + col] = | |
| 225 | 4976 | field.Post(static_cast<std::ptrdiff_t>(col), static_cast<std::ptrdiff_t>(row)); | |
| 226 | } | ||
| 227 | } | ||
| 228 | } | ||
| 229 | 5 | const std::vector<float> distance = DataDistances(data, posts, &carried); | |
| 230 | 239 | for (std::size_t row = 0; row < posts.height; ++row) { | |
| 231 | 11198 | for (std::size_t col = 0; col < posts.width; ++col) { | |
| 232 | 10964 | const std::size_t k = row * posts.width + col; | |
| 233 | 10964 | if (data[k] != 0 || !(distance[k] < width)) { | |
| 234 | 8436 | continue; | |
| 235 | } | ||
| 236 | 2528 | const double t = static_cast<double>(distance[k]) / width; | |
| 237 | 2528 | const double weight = 1.0 - t * t * (3.0 - 2.0 * t); | |
| 238 | 2528 | field.Set(col, row, static_cast<float>(weight * static_cast<double>(carried[k]))); | |
| 239 | } | ||
| 240 | } | ||
| 241 | 5 | } | |
| 242 | |||
| 243 | /// A post's key, ordering posts by row, then column; a few posts before the lattice's first row | ||
| 244 | /// and column have keys too. | ||
| 245 | using Key = std::uint64_t; | ||
| 246 | |||
| 247 | /// Posts before the first row and column that have keys. | ||
| 248 | constexpr std::int64_t kKeyOffset = 16; | ||
| 249 | |||
| 250 | 1536080 | Key KeyAt(std::int64_t col, std::int64_t row) { | |
| 251 | 1536080 | return (static_cast<Key>(row + kKeyOffset) << 32) | static_cast<Key>(col + kKeyOffset); | |
| 252 | } | ||
| 253 | |||
| 254 | 400041 | std::int64_t KeyCol(Key key) { | |
| 255 | 400041 | return static_cast<std::int64_t>(key & 0xffffffffu) - kKeyOffset; | |
| 256 | } | ||
| 257 | |||
| 258 | 400041 | std::int64_t KeyRow(Key key) { | |
| 259 | 400041 | return static_cast<std::int64_t>(key >> 32) - kKeyOffset; | |
| 260 | } | ||
| 261 | |||
| 262 | /// The posts around a post that a 5-point stencil reads. | ||
| 263 | constexpr std::array<std::array<std::int64_t, 2>, 4> kNear5{{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}}; | ||
| 264 | |||
| 265 | /// The posts around a post that a 13-point stencil reads. | ||
| 266 | constexpr std::array<std::array<std::int64_t, 2>, 12> kNear13{{{-1, 0}, | ||
| 267 | {1, 0}, | ||
| 268 | {0, -1}, | ||
| 269 | {0, 1}, | ||
| 270 | {-2, 0}, | ||
| 271 | {2, 0}, | ||
| 272 | {0, -2}, | ||
| 273 | {0, 2}, | ||
| 274 | {-1, -1}, | ||
| 275 | {1, -1}, | ||
| 276 | {-1, 1}, | ||
| 277 | {1, 1}}}; | ||
| 278 | |||
| 279 | /// Calls `visit` with each post a stencil of `order` 1 (5 points) or 2 (13 points) reads around | ||
| 280 | /// `key`, but not `key` itself. | ||
| 281 | 119470 | template <typename Visit> void VisitStencil(Key key, int order, Visit visit) { | |
| 282 | 119470 | const std::int64_t col = KeyCol(key); | |
| 283 | 119470 | const std::int64_t row = KeyRow(key); | |
| 284 | 119470 | if (order == 1) { | |
| 285 | 393805 | for (const auto& offset : kNear5) { | |
| 286 | 315044 | visit(KeyAt(col + offset[0], row + offset[1])); | |
| 287 | } | ||
| 288 | } else { | ||
| 289 | 529217 | for (const auto& offset : kNear13) { | |
| 290 | 488508 | visit(KeyAt(col + offset[0], row + offset[1])); | |
| 291 | } | ||
| 292 | } | ||
| 293 | 119470 | } | |
| 294 | |||
| 295 | /// One level of the multigrid hierarchy of a seam solve: the posts solved for and those the | ||
| 296 | /// stencil reads around them, in row-major order, then a slot that always reads 0. | ||
| 297 | /// | ||
| 298 | /// The operator is B = -Laplacian + 1/L^2 on 5 points for `Height` and B applied twice, on 13 | ||
| 299 | /// points, for `Slope`; posts not solved for hold fixed values. | ||
| 300 | struct SolveLevel { | ||
| 301 | std::vector<Key> keys; ///< The posts, sorted. | ||
| 302 | std::vector<std::uint8_t> unknown; ///< Whether each post is solved for; 0 for the slot. | ||
| 303 | std::vector<std::uint32_t> neighbors; ///< Left, right, upper, lower post of each, or the slot. | ||
| 304 | std::vector<std::uint32_t> coarser; ///< The 4 posts of the next level each unknown reads. | ||
| 305 | double cx = 0.0; ///< 1 / dx^2. | ||
| 306 | double cy = 0.0; ///< 1 / dy^2. | ||
| 307 | double center = 0.0; ///< B's weight of the center post. | ||
| 308 | double diagonal = 0.0; ///< The operator's weight of the center post. | ||
| 309 | std::vector<double> solution; ///< The correction at this level. | ||
| 310 | std::vector<double> rhs; ///< What the operator should give at each unknown. | ||
| 311 | |||
| 312 | /// The slot that reads 0, past the posts. | ||
| 313 | 61420 | std::uint32_t Slot() const { | |
| 314 | 12678 | return static_cast<std::uint32_t>(keys.size()); | |
| 315 | } | ||
| 316 | |||
| 317 | /// The index of the post at `key`, or the slot without one. | ||
| 318 | 519644 | std::uint32_t Find(Key key) const { | |
| 319 | 519644 | const auto it = std::lower_bound(keys.begin(), keys.end(), key); | |
| 320 | 519644 | return it != keys.end() && *it == key ? static_cast<std::uint32_t>(it - keys.begin()) | |
| 321 | 12678 | : Slot(); | |
| 322 | } | ||
| 323 | }; | ||
| 324 | |||
| 325 | /// The level solving for `unknowns` (sorted, unique) with posts `dx` by `dy` apart. | ||
| 326 | 105 | SolveLevel MakeLevel(const std::vector<Key>& unknowns, int order, double dx, double dy, | |
| 327 | double screening) { | ||
| 328 | 105 | SolveLevel level; | |
| 329 | 105 | std::vector<Key> keys = unknowns; | |
| 330 | 69235 | for (const Key key : unknowns) { | |
| 331 | 534810 | VisitStencil(key, order, [&](Key around) { keys.push_back(around); }); | |
| 332 | } | ||
| 333 | 105 | std::sort(keys.begin(), keys.end()); | |
| 334 | 105 | keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); | |
| 335 | 105 | level.keys = std::move(keys); | |
| 336 | 105 | const std::uint32_t slot = level.Slot(); | |
| 337 | 105 | level.unknown.assign(static_cast<std::size_t>(slot) + 1, 0); | |
| 338 | 69235 | for (const Key key : unknowns) { | |
| 339 | 69130 | level.unknown[level.Find(key)] = 1; | |
| 340 | } | ||
| 341 | 105 | level.neighbors.assign(4 * (static_cast<std::size_t>(slot) + 1), slot); | |
| 342 | 84732 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 343 | 84627 | const std::int64_t col = KeyCol(level.keys[k]); | |
| 344 | 84627 | const std::int64_t row = KeyRow(level.keys[k]); | |
| 345 | 84627 | const Key left = KeyAt(col - 1, row); | |
| 346 | 84627 | const Key right = KeyAt(col + 1, row); | |
| 347 | 84627 | level.neighbors[4 * std::size_t{k}] = | |
| 348 | 84627 | k > 0 && level.keys[k - 1] == left ? k - 1 : level.Find(left); | |
| 349 | 84627 | level.neighbors[4 * std::size_t{k} + 1] = | |
| 350 | 84627 | k + 1 < slot && level.keys[k + 1] == right ? k + 1 : level.Find(right); | |
| 351 | 84627 | level.neighbors[4 * std::size_t{k} + 2] = level.Find(KeyAt(col, row - 1)); | |
| 352 | 84627 | level.neighbors[4 * std::size_t{k} + 3] = level.Find(KeyAt(col, row + 1)); | |
| 353 | } | ||
| 354 | 105 | level.cx = 1.0 / (dx * dx); | |
| 355 | 105 | level.cy = 1.0 / (dy * dy); | |
| 356 | 105 | level.center = 2.0 * level.cx + 2.0 * level.cy + screening; | |
| 357 | 105 | level.diagonal = order == 1 ? level.center | |
| 358 | 51 | : level.center * level.center + 2.0 * level.cx * level.cx + | |
| 359 | 51 | 2.0 * level.cy * level.cy; | |
| 360 | 105 | level.solution.assign(static_cast<std::size_t>(slot) + 1, 0.0); | |
| 361 | 105 | level.rhs.assign(static_cast<std::size_t>(slot) + 1, 0.0); | |
| 362 | 105 | return level; | |
| 363 | 105 | } | |
| 364 | |||
| 365 | /// Points each unknown post of `fine` at the posts of `coarse` its correction is interpolated | ||
| 366 | /// from (`kTransfer`). | ||
| 367 | 78 | void Link(SolveLevel& fine, const SolveLevel& coarse) { | |
| 368 | 78 | const std::uint32_t slot = fine.Slot(); | |
| 369 | 78 | fine.coarser.assign(4 * static_cast<std::size_t>(slot), coarse.Slot()); | |
| 370 | 83631 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 371 | 83553 | if (fine.unknown[k] == 0) { | |
| 372 | 14817 | continue; | |
| 373 | } | ||
| 374 | 68736 | const std::int64_t col = KeyCol(fine.keys[k]); | |
| 375 | 68736 | const std::int64_t row = KeyRow(fine.keys[k]); | |
| 376 | 68736 | const std::int64_t parentCol = col / 2; | |
| 377 | 68736 | const std::int64_t parentRow = row / 2; | |
| 378 | 68736 | const std::int64_t acrossCol = parentCol + (col % 2 == 1 ? 1 : -1); | |
| 379 | 68736 | const std::int64_t acrossRow = parentRow + (row % 2 == 1 ? 1 : -1); | |
| 380 | 68736 | std::uint32_t* to = &fine.coarser[4 * std::size_t{k}]; | |
| 381 | 68736 | to[0] = coarse.Find(KeyAt(parentCol, parentRow)); | |
| 382 | 68736 | to[1] = coarse.Find(KeyAt(acrossCol, parentRow)); | |
| 383 | 68736 | to[2] = coarse.Find(KeyAt(parentCol, acrossRow)); | |
| 384 | 68736 | to[3] = coarse.Find(KeyAt(acrossCol, acrossRow)); | |
| 385 | } | ||
| 386 | 78 | } | |
| 387 | |||
| 388 | /// B = -Laplacian + 1/L^2 of `values` at post `k`. | ||
| 389 | 31784520 | double ApplyScreened(const SolveLevel& level, const std::vector<double>& values, std::uint32_t k) { | |
| 390 | 31784520 | const std::uint32_t* adjacent = &level.neighbors[4 * std::size_t{k}]; | |
| 391 | 31784520 | return level.center * values[k] - level.cx * (values[adjacent[0]] + values[adjacent[1]]) - | |
| 392 | 31784520 | level.cy * (values[adjacent[2]] + values[adjacent[3]]); | |
| 393 | } | ||
| 394 | |||
| 395 | /// The operator of `order` (B, or B applied twice) of `values` at post `k`. | ||
| 396 | 9014576 | double Apply(const SolveLevel& level, int order, const std::vector<double>& values, | |
| 397 | std::uint32_t k) { | ||
| 398 | 9014576 | if (order == 1) { | |
| 399 | 3322090 | return ApplyScreened(level, values, k); | |
| 400 | } | ||
| 401 | 5692486 | const std::uint32_t* adjacent = &level.neighbors[4 * std::size_t{k}]; | |
| 402 | 5692486 | return level.center * ApplyScreened(level, values, k) - | |
| 403 | 5692486 | level.cx * (ApplyScreened(level, values, adjacent[0]) + | |
| 404 | 5692486 | ApplyScreened(level, values, adjacent[1])) - | |
| 405 | 5692486 | level.cy * (ApplyScreened(level, values, adjacent[2]) + | |
| 406 | 5692486 | ApplyScreened(level, values, adjacent[3])); | |
| 407 | } | ||
| 408 | |||
| 409 | /// One Gauss-Seidel sweep of the level's unknowns, in row-major order or its reverse. | ||
| 410 | 47044 | void Sweep(SolveLevel& level, int order, bool forward) { | |
| 411 | 47044 | const std::uint32_t slot = level.Slot(); | |
| 412 | 9087860 | for (std::uint32_t i = 0; i < slot; ++i) { | |
| 413 | 9040816 | const std::uint32_t k = forward ? i : slot - 1 - i; | |
| 414 | 9040816 | if (level.unknown[k] != 0) { | |
| 415 | 6432768 | level.solution[k] += | |
| 416 | 6432768 | (level.rhs[k] - Apply(level, order, level.solution, k)) / level.diagonal; | |
| 417 | } | ||
| 418 | } | ||
| 419 | 47044 | } | |
| 420 | |||
| 421 | /// A symmetric multigrid V-cycle from level `depth` down: an approximate solution of the | ||
| 422 | /// level's operator for its `rhs`, starting from 0, with 0 at every post not solved for. | ||
| 423 | 1873 | void VCycle(std::vector<SolveLevel>& levels, std::size_t depth, int order) { | |
| 424 | 1873 | SolveLevel& level = levels[depth]; | |
| 425 | 1873 | std::fill(level.solution.begin(), level.solution.end(), 0.0); | |
| 426 | 1873 | if (depth + 1 == levels.size()) { | |
| 427 | 21012 | for (int sweep = 0; sweep < kCoarsestSweeps; ++sweep) { | |
| 428 | 20600 | Sweep(level, order, true); | |
| 429 | 20600 | Sweep(level, order, false); | |
| 430 | } | ||
| 431 | return; | ||
| 432 | } | ||
| 433 | 4383 | for (int sweep = 0; sweep < kSmoothingSweeps; ++sweep) { | |
| 434 | 2922 | Sweep(level, order, true); | |
| 435 | } | ||
| 436 | 1461 | SolveLevel& coarse = levels[depth + 1]; | |
| 437 | 1461 | std::fill(coarse.rhs.begin(), coarse.rhs.end(), 0.0); | |
| 438 | 1461 | const std::uint32_t slot = level.Slot(); | |
| 439 | 1810740 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 440 | 1809279 | if (level.unknown[k] == 0) { | |
| 441 | 347487 | continue; | |
| 442 | } | ||
| 443 | 1461792 | const double residual = level.rhs[k] - Apply(level, order, level.solution, k); | |
| 444 | 7308960 | for (std::size_t q = 0; q < kTransfer.size(); ++q) { | |
| 445 | 5847168 | coarse.rhs[level.coarser[4 * std::size_t{k} + q]] += 0.25 * kTransfer[q] * residual; | |
| 446 | } | ||
| 447 | } | ||
| 448 | 572610 | for (std::size_t c = 0; c < coarse.rhs.size(); ++c) { | |
| 449 | 571149 | if (coarse.unknown[c] == 0) { | |
| 450 | 173177 | coarse.rhs[c] = 0.0; | |
| 451 | } | ||
| 452 | } | ||
| 453 | 1461 | VCycle(levels, depth + 1, order); | |
| 454 | 1810740 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 455 | 1809279 | if (level.unknown[k] == 0) { | |
| 456 | 347487 | continue; | |
| 457 | } | ||
| 458 | double correction = 0.0; | ||
| 459 | 7308960 | for (std::size_t q = 0; q < kTransfer.size(); ++q) { | |
| 460 | 5847168 | correction += kTransfer[q] * coarse.solution[level.coarser[4 * std::size_t{k} + q]]; | |
| 461 | } | ||
| 462 | 1461792 | level.solution[k] += correction; | |
| 463 | } | ||
| 464 | 4383 | for (int sweep = 0; sweep < kSmoothingSweeps; ++sweep) { | |
| 465 | 2922 | Sweep(level, order, false); | |
| 466 | } | ||
| 467 | } | ||
| 468 | |||
| 469 | /// The multigrid levels of `unknowns` (sorted), each coarser level halving the posts, linked. | ||
| 470 | 27 | std::vector<SolveLevel> BuildHierarchy(std::vector<Key> keys, int order, double dx, double dy, | |
| 471 | double screening) { | ||
| 472 | 27 | std::vector<SolveLevel> levels; | |
| 473 | 183 | for (;;) { | |
| 474 | 210 | levels.push_back(MakeLevel(keys, order, dx, dy, screening)); | |
| 475 | 105 | if (keys.size() <= kCoarsestPosts || levels.size() == kMaxLevels) { | |
| 476 | break; | ||
| 477 | } | ||
| 478 | 78 | std::vector<Key> coarse; | |
| 479 | 78 | coarse.reserve(keys.size()); | |
| 480 | 68814 | for (const Key key : keys) { | |
| 481 | 68736 | coarse.push_back(KeyAt(KeyCol(key) / 2, KeyRow(key) / 2)); | |
| 482 | } | ||
| 483 | 78 | std::sort(coarse.begin(), coarse.end()); | |
| 484 | 78 | coarse.erase(std::unique(coarse.begin(), coarse.end()), coarse.end()); | |
| 485 | 78 | keys = std::move(coarse); | |
| 486 | 78 | dx *= 2.0; | |
| 487 | 78 | dy *= 2.0; | |
| 488 | 78 | } | |
| 489 | 105 | for (std::size_t depth = 0; depth + 1 < levels.size(); ++depth) { | |
| 490 | 78 | Link(levels[depth], levels[depth + 1]); | |
| 491 | } | ||
| 492 | 27 | return levels; | |
| 493 | } | ||
| 494 | |||
| 495 | /// The solution of the finest level's operator for `residual`, by conjugate gradients | ||
| 496 | /// preconditioned with multigrid V-cycles over `levels`. | ||
| 497 | 27 | std::vector<double> PreconditionedCg(std::vector<SolveLevel>& levels, int order, | |
| 498 | std::vector<double> residual) { | ||
| 499 | 27 | SolveLevel& fine = levels.front(); | |
| 500 | 27 | const std::uint32_t slot = fine.Slot(); | |
| 501 | 2060 | const auto forUnknowns = [&](const auto& visit) { | |
| 502 | 6290200 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 503 | 6288140 | if (fine.unknown[k] != 0) { | |
| 504 | 5348380 | visit(k); | |
| 505 | } | ||
| 506 | } | ||
| 507 | 2060 | }; | |
| 508 | 1290 | const auto dot = [&](const std::vector<double>& a, const std::vector<double>& b) { | |
| 509 | 1263 | double sum = 0.0; | |
| 510 | 1263 | forUnknowns([&](std::uint32_t k) { sum += a[k] * b[k]; }); | |
| 511 | 1263 | return sum; | |
| 512 | 27 | }; | |
| 513 | 439 | const auto precondition = [&] { | |
| 514 | 412 | fine.rhs = residual; | |
| 515 | 412 | VCycle(levels, 0, order); | |
| 516 | 412 | return fine.solution; | |
| 517 | 27 | }; | |
| 518 | 27 | std::vector<double> solution(residual.size(), 0.0); | |
| 519 | 27 | std::vector<double> applied(residual.size(), 0.0); | |
| 520 | 27 | const double target = kTolerance * std::sqrt(dot(residual, residual)); | |
| 521 | 27 | std::vector<double> direction = precondition(); | |
| 522 | 27 | double fit = dot(residual, direction); | |
| 523 | 412 | for (int iteration = 0; iteration < kMaxIterations && fit > 0.0; ++iteration) { | |
| 524 | 1258040 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 525 | 1257628 | applied[k] = fine.unknown[k] != 0 ? Apply(fine, order, direction, k) : 0.0; | |
| 526 | } | ||
| 527 | 412 | const double curvature = dot(direction, applied); | |
| 528 | 412 | if (!(curvature > 0.0)) { | |
| 529 | break; | ||
| 530 | } | ||
| 531 | 412 | const double step = fit / curvature; | |
| 532 | 412 | forUnknowns([&](std::uint32_t k) { | |
| 533 | 1069676 | solution[k] += step * direction[k]; | |
| 534 | 1069676 | residual[k] -= step * applied[k]; | |
| 535 | 1069676 | }); | |
| 536 | 412 | if (std::sqrt(dot(residual, residual)) <= target) { | |
| 537 | break; | ||
| 538 | } | ||
| 539 | 385 | const std::vector<double> preconditioned = precondition(); | |
| 540 | 385 | const double next = dot(residual, preconditioned); | |
| 541 | 385 | const double ratio = next / fit; | |
| 542 | 385 | fit = next; | |
| 543 | 385 | forUnknowns( | |
| 544 | 385 | [&](std::uint32_t k) { direction[k] = preconditioned[k] + ratio * direction[k]; }); | |
| 545 | 385 | } | |
| 546 | 27 | return solution; | |
| 547 | 27 | } | |
| 548 | |||
| 549 | /// Solves the operator of `order` = 0 for the posts `unknowns` (sorted, one connected region) | ||
| 550 | /// with the posts around them fixed at their values in `field`, and sets them in `field`. | ||
| 551 | 27 | void SolveRegion(SeamField& field, const std::vector<Key>& unknowns, int order, double dx, | |
| 552 | double dy, double screening) { | ||
| 553 | 27 | std::vector<SolveLevel> levels = BuildHierarchy(unknowns, order, dx, dy, screening); | |
| 554 | 27 | const SolveLevel& fine = levels.front(); | |
| 555 | 27 | const std::uint32_t slot = fine.Slot(); | |
| 556 | 58499 | const auto post = [&](std::uint32_t k) { | |
| 557 | 58472 | return std::make_pair(KeyCol(fine.keys[k]), KeyRow(fine.keys[k])); | |
| 558 | 27 | }; | |
| 559 | 27 | std::vector<double> fixed(static_cast<std::size_t>(slot) + 1, 0.0); | |
| 560 | 58499 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 561 | 58472 | if (fine.unknown[k] == 0) { | |
| 562 | 8132 | const auto [col, row] = post(k); | |
| 563 | 8132 | fixed[k] = static_cast<double>( | |
| 564 | 8132 | field.Post(static_cast<std::ptrdiff_t>(col), static_cast<std::ptrdiff_t>(row))); | |
| 565 | } | ||
| 566 | } | ||
| 567 | 27 | std::vector<double> residual(fixed.size(), 0.0); | |
| 568 | 58499 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 569 | 58472 | residual[k] = fine.unknown[k] != 0 ? -Apply(fine, order, fixed, k) : 0.0; | |
| 570 | } | ||
| 571 | 27 | const std::vector<double> solution = PreconditionedCg(levels, order, std::move(residual)); | |
| 572 | 58499 | for (std::uint32_t k = 0; k < slot; ++k) { | |
| 573 | 58472 | if (fine.unknown[k] != 0) { | |
| 574 | 50340 | const auto [col, row] = post(k); | |
| 575 | 50340 | field.Set(static_cast<std::size_t>(col), static_cast<std::size_t>(row), | |
| 576 | 50340 | static_cast<float>(solution[k])); | |
| 577 | } | ||
| 578 | } | ||
| 579 | 27 | } | |
| 580 | |||
| 581 | /// `unknowns` (sorted) split into the regions a stencil of `order` connects, each sorted, in the | ||
| 582 | /// order of their first post. | ||
| 583 | 18 | std::vector<std::vector<Key>> Regions(const std::vector<Key>& unknowns, int order) { | |
| 584 | 18 | std::vector<std::uint8_t> seen(unknowns.size(), 0); | |
| 585 | 18 | std::vector<std::vector<Key>> regions; | |
| 586 | 18 | std::vector<std::size_t> queue; | |
| 587 | 50358 | for (std::size_t start = 0; start < unknowns.size(); ++start) { | |
| 588 | 50340 | if (seen[start] != 0) { | |
| 589 | 50313 | continue; | |
| 590 | } | ||
| 591 | 27 | seen[start] = 1; | |
| 592 | 27 | queue.assign(1, start); | |
| 593 | 27 | std::vector<Key> region; | |
| 594 | 50367 | for (std::size_t head = 0; head < queue.size(); ++head) { | |
| 595 | 50340 | const Key key = unknowns[queue[head]]; | |
| 596 | 50340 | region.push_back(key); | |
| 597 | 50340 | VisitStencil(key, order, [&](Key around) { | |
| 598 | 337872 | const auto it = std::lower_bound(unknowns.begin(), unknowns.end(), around); | |
| 599 | 337872 | if (it == unknowns.end() || *it != around) { | |
| 600 | 17172 | return; | |
| 601 | } | ||
| 602 | 320700 | const auto index = static_cast<std::size_t>(it - unknowns.begin()); | |
| 603 | 320700 | if (seen[index] == 0) { | |
| 604 | 50313 | seen[index] = 1; | |
| 605 | 50313 | queue.push_back(index); | |
| 606 | } | ||
| 607 | }); | ||
| 608 | } | ||
| 609 | 27 | std::sort(region.begin(), region.end()); | |
| 610 | 27 | regions.push_back(std::move(region)); | |
| 611 | 27 | } | |
| 612 | 18 | return regions; | |
| 613 | 18 | } | |
| 614 | |||
| 615 | } // namespace | ||
| 616 | |||
| 617 | 23 | SeamField::SeamField(const RasterGrid& lattice) | |
| 618 | 23 | : m_lattice(lattice), m_tileColumns((lattice.width + kTileSide - 1) / kTileSide), | |
| 619 | 23 | m_tiles(m_tileColumns * ((lattice.height + kTileSide - 1) / kTileSide)) {} | |
| 620 | |||
| 621 | 1052304 | float SeamField::Post(std::ptrdiff_t col, std::ptrdiff_t row) const { | |
| 622 | 1052304 | if (col < 0 || row < 0 || static_cast<std::size_t>(col) >= m_lattice.width || | |
| 623 | 1010516 | static_cast<std::size_t>(row) >= m_lattice.height) { | |
| 624 | return 0.0f; | ||
| 625 | } | ||
| 626 | 997108 | const auto c = static_cast<std::size_t>(col); | |
| 627 | 997108 | const auto r = static_cast<std::size_t>(row); | |
| 628 | 997108 | const std::vector<float>& tile = m_tiles[(r / kTileSide) * m_tileColumns + c / kTileSide]; | |
| 629 | 997108 | return tile.empty() ? 0.0f : tile[(r % kTileSide) * kTileSide + c % kTileSide]; | |
| 630 | } | ||
| 631 | |||
| 632 | 61604 | void SeamField::Set(std::size_t col, std::size_t row, float value) { | |
| 633 | 61604 | std::vector<float>& tile = m_tiles[(row / kTileSide) * m_tileColumns + col / kTileSide]; | |
| 634 | 61604 | if (tile.empty()) { | |
| 635 | 43 | if (value == 0.0f) { | |
| 636 | return; | ||
| 637 | } | ||
| 638 | 43 | tile.assign(kTileSide * kTileSide, 0.0f); | |
| 639 | } | ||
| 640 | 61604 | tile[(row % kTileSide) * kTileSide + col % kTileSide] = value; | |
| 641 | 61604 | m_set = true; | |
| 642 | } | ||
| 643 | |||
| 644 | 87946 | double SeamField::At(double x, double y) const { | |
| 645 | 87946 | if (!m_set) { | |
| 646 | return 0.0; | ||
| 647 | } | ||
| 648 | 66862 | const Vec2d pixel = m_lattice.transform.WorldToPixel(x, y); | |
| 649 | 66868 | const double fx = pixel.x - 0.5; | |
| 650 | 66868 | const double fy = pixel.y - 0.5; | |
| 651 | 66868 | const double left = std::floor(fx); | |
| 652 | 66868 | const double top = std::floor(fy); | |
| 653 | 66868 | if (!(left >= -2.0 && top >= -2.0 && left <= static_cast<double>(m_lattice.width) && | |
| 654 | 66415 | top <= static_cast<double>(m_lattice.height))) { | |
| 655 | return 0.0; | ||
| 656 | } | ||
| 657 | 1104811 | const auto post = [this](double col, double row) { | |
| 658 | 1038425 | return Post(static_cast<std::ptrdiff_t>(col), static_cast<std::ptrdiff_t>(row)); | |
| 659 | 66386 | }; | |
| 660 | 66386 | return *InterpolateLattice(fx, fy, ResampleMethod::Cubic, post, [](float) { return false; }); | |
| 661 | } | ||
| 662 | |||
| 663 | 33 | SeamField BuildSeamField(const Source& earlier, const Source& later, const RasterGrid& grid, | |
| 664 | const ChainSeams& seams) { | ||
| 665 | 33 | if (seams.mode == ChainSeamMode::None) { | |
| 666 | 10 | return {}; | |
| 667 | } | ||
| 668 | 23 | const RasterGrid lattice = SeamLattice(grid, seams); | |
| 669 | 23 | const GeoTransform& transform = lattice.transform; | |
| 670 | 23 | const Posts posts{lattice.width, lattice.height, transform.CellWidth(), transform.CellHeight(), | |
| 671 | 23 | transform}; | |
| 672 | 23 | const double spacing = grid.PixelSize(); | |
| 673 | 23 | const Sampled sampled = SampleSources(earlier, later, posts, spacing); | |
| 674 | 23 | const std::vector<std::uint8_t>& data = sampled.data; | |
| 675 | 23 | const auto has = [](std::uint8_t value) { return value != 0; }; | |
| 676 | 23 | if (std::all_of(data.begin(), data.end(), has) || std::none_of(data.begin(), data.end(), has)) { | |
| 677 | ✗ | return {}; | |
| 678 | } | ||
| 679 | 23 | SeamField field(lattice); | |
| 680 | 23 | const std::vector<std::uint8_t> band = NearGaps(data, posts, kBandPosts); | |
| 681 | 2635 | for (std::size_t row = 0; row < posts.height; ++row) { | |
| 682 | 914956 | for (std::size_t col = 0; col < posts.width; ++col) { | |
| 683 | 912344 | const std::size_t k = row * posts.width + col; | |
| 684 | 912344 | if (data[k] != 0 && band[k] != 0 && !std::isnan(sampled.difference[k])) { | |
| 685 | 8736 | field.Set(col, row, sampled.difference[k]); | |
| 686 | } | ||
| 687 | } | ||
| 688 | } | ||
| 689 | 23 | if (seams.mode == ChainSeamMode::Feather) { | |
| 690 | 5 | Feather(field, data, posts, seams.width); | |
| 691 | 5 | return field; | |
| 692 | } | ||
| 693 | 18 | const std::vector<float> distance = DataDistances(data, posts, nullptr); | |
| 694 | 18 | const double reach = SeamReach(seams); | |
| 695 | 18 | std::vector<Key> unknowns; | |
| 696 | 2288 | for (std::size_t row = kBorderPosts; row + kBorderPosts < posts.height; ++row) { | |
| 697 | 875762 | for (std::size_t col = kBorderPosts; col + kBorderPosts < posts.width; ++col) { | |
| 698 | 873492 | const std::size_t k = row * posts.width + col; | |
| 699 | 873492 | if (data[k] == 0 && static_cast<double>(distance[k]) <= reach) { | |
| 700 | 100680 | unknowns.push_back( | |
| 701 | 50340 | KeyAt(static_cast<std::int64_t>(col), static_cast<std::int64_t>(row))); | |
| 702 | } | ||
| 703 | } | ||
| 704 | } | ||
| 705 | 18 | const int order = seams.mode == ChainSeamMode::Slope ? 2 : 1; | |
| 706 | 18 | const double screening = 1.0 / (seams.decayLength * seams.decayLength); | |
| 707 | 45 | for (const std::vector<Key>& region : Regions(unknowns, order)) { | |
| 708 | 27 | SolveRegion(field, region, order, posts.dx, posts.dy, screening); | |
| 709 | 18 | } | |
| 710 | 18 | return field; | |
| 711 | 46 | } | |
| 712 | |||
| 713 | } // namespace terraingen::detail | ||
| 714 |