src/layers/masked.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "terraingen/layers/masked.h" | ||
| 4 | |||
| 5 | #include "terraingen/geometry/geometry.h" | ||
| 6 | #include "terraingen/raster/cell_loops.h" | ||
| 7 | #include "terraingen/util/parallel.h" | ||
| 8 | #include "util/checks.h" | ||
| 9 | |||
| 10 | #include <algorithm> | ||
| 11 | #include <cmath> | ||
| 12 | #include <iterator> | ||
| 13 | #include <limits> | ||
| 14 | #include <memory> | ||
| 15 | #include <stdexcept> | ||
| 16 | #include <string> | ||
| 17 | #include <utility> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | namespace terraingen { | ||
| 21 | |||
| 22 | namespace { | ||
| 23 | |||
| 24 | /// `height` moved toward `inner` by `weight` in [0, 1]. | ||
| 25 | 35156 | float Blend(float height, float inner, double weight) { | |
| 26 | 35156 | if (weight >= 1.0) { | |
| 27 | return inner; | ||
| 28 | } | ||
| 29 | 17513 | return static_cast<float>(static_cast<double>(height) + | |
| 30 | 17513 | weight * (static_cast<double>(inner) - static_cast<double>(height))); | |
| 31 | } | ||
| 32 | |||
| 33 | /// The smallest window holding every one of `windows`; empty when there is none. | ||
| 34 | 19 | PixelWindow MergeWindows(const std::vector<PixelWindow>& windows) { | |
| 35 | 19 | if (windows.empty()) { | |
| 36 | 2 | return {}; | |
| 37 | } | ||
| 38 | 17 | PixelWindow joined = windows.front(); | |
| 39 | 34 | for (const PixelWindow& window : windows) { | |
| 40 | 17 | joined.colBegin = std::min(joined.colBegin, window.colBegin); | |
| 41 | 17 | joined.colEnd = std::max(joined.colEnd, window.colEnd); | |
| 42 | 17 | joined.rowBegin = std::min(joined.rowBegin, window.rowBegin); | |
| 43 | 17 | joined.rowEnd = std::max(joined.rowEnd, window.rowEnd); | |
| 44 | } | ||
| 45 | 17 | return joined; | |
| 46 | } | ||
| 47 | |||
| 48 | /// The cells of `window` of `heights` as a raster of their own, on the same lattice. | ||
| 49 | 14 | Raster<float> CopyWindow(const Raster<float>& heights, const PixelWindow& window) { | |
| 50 | 14 | Raster<float> copy(Subgrid(heights.Grid(), window)); | |
| 51 | 14 | copy.SetNoData(heights.NoData()); | |
| 52 | 481 | for (std::size_t row = window.rowBegin; row < window.rowEnd; ++row) { | |
| 53 | 25122 | for (std::size_t col = window.colBegin; col < window.colEnd; ++col) { | |
| 54 | 24655 | copy(col - window.colBegin, row - window.rowBegin) = heights(col, row); | |
| 55 | } | ||
| 56 | } | ||
| 57 | 14 | return copy; | |
| 58 | } | ||
| 59 | |||
| 60 | /// The signed distance from (`px`, `py`) to the edge of `box`, east offsets scaled by `xScale`. | ||
| 61 | 741 | double BoxDistance(const Bounds2d& box, double px, double py, double xScale) { | |
| 62 | 741 | const double dx = xScale * std::fmax(box.minX - px, px - box.maxX); | |
| 63 | 741 | const double dy = std::fmax(box.minY - py, py - box.maxY); | |
| 64 | 741 | if (dx <= 0.0 && dy <= 0.0) { | |
| 65 | 125 | return std::fmax(dx, dy); | |
| 66 | } | ||
| 67 | 616 | return std::hypot(std::fmax(dx, 0.0), std::fmax(dy, 0.0)); | |
| 68 | } | ||
| 69 | |||
| 70 | /// The squared distance from `p` to the segment from `a` to `b`, x scaled by `xScale`, and | ||
| 71 | /// whether the segment crosses the ray east of `p`. | ||
| 72 | struct EdgeProbe { | ||
| 73 | double squared; | ||
| 74 | bool crosses; | ||
| 75 | }; | ||
| 76 | 235347 | EdgeProbe ProbeEdge(Vec2d p, Vec2d a, Vec2d b, double xScale) { | |
| 77 | 470694 | const bool crosses = | |
| 78 | 235347 | (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y); | |
| 79 | 235347 | const double ex = xScale * (b.x - a.x); | |
| 80 | 235347 | const double ey = b.y - a.y; | |
| 81 | 235347 | const double wx = xScale * (p.x - a.x); | |
| 82 | 235347 | const double wy = p.y - a.y; | |
| 83 | 235347 | const double length = ex * ex + ey * ey; | |
| 84 | 470694 | const double t = length > 0.0 ? std::clamp((wx * ex + wy * ey) / length, 0.0, 1.0) : 0.0; | |
| 85 | 235347 | const double dx = wx - t * ex; | |
| 86 | 235347 | const double dy = wy - t * ey; | |
| 87 | 235347 | return {dx * dx + dy * dy, crosses}; | |
| 88 | } | ||
| 89 | |||
| 90 | /// The signed distance from `p` to the edges of `points` and `holes`, x scaled by `xScale`; | ||
| 91 | /// negative where a ray from `p` crosses them an odd number of times. | ||
| 92 | 29426 | double PolygonDistance(const std::vector<Vec2d>& points, | |
| 93 | const std::vector<std::vector<Vec2d>>& holes, Vec2d p, double xScale) { | ||
| 94 | 29426 | double squared = std::numeric_limits<double>::infinity(); | |
| 95 | 29426 | bool inside = false; | |
| 96 | 58861 | const auto ring = [&](const std::vector<Vec2d>& vertices) { | |
| 97 | 264782 | for (std::size_t i = 0, j = vertices.size() - 1; i < vertices.size(); j = i++) { | |
| 98 | 235347 | const EdgeProbe probe = ProbeEdge(p, vertices[j], vertices[i], xScale); | |
| 99 | 235347 | squared = std::fmin(squared, probe.squared); | |
| 100 | 235347 | inside = inside != probe.crosses; | |
| 101 | } | ||
| 102 | 58861 | }; | |
| 103 | 29426 | if (points.empty()) { | |
| 104 | return squared; | ||
| 105 | } | ||
| 106 | 29426 | ring(points); | |
| 107 | 29435 | for (const std::vector<Vec2d>& hole : holes) { | |
| 108 | 9 | if (!hole.empty()) { | |
| 109 | 9 | ring(hole); | |
| 110 | } | ||
| 111 | } | ||
| 112 | 29426 | const double distance = std::sqrt(squared); | |
| 113 | 29426 | return inside ? -distance : distance; | |
| 114 | } | ||
| 115 | |||
| 116 | /// Twice the signed area of the polygon `vertices`. | ||
| 117 | 18 | double TwiceArea(const std::vector<Vec2d>& vertices) { | |
| 118 | 18 | double sum = 0.0; | |
| 119 | 96 | for (std::size_t i = 0, j = vertices.size() - 1; i < vertices.size(); j = i++) { | |
| 120 | 78 | sum += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y); | |
| 121 | } | ||
| 122 | 18 | return sum; | |
| 123 | } | ||
| 124 | |||
| 125 | /// Checks one outline of a polygonal region, named `what` in errors. | ||
| 126 | /// @throws std::invalid_argument for fewer than 3 points, a point that is not finite, a | ||
| 127 | /// zero-length edge or no area. | ||
| 128 | 29 | void ValidateRing(const std::vector<Vec2d>& vertices, const std::string& what) { | |
| 129 | 29 | if (vertices.size() < 3) { | |
| 130 | 10 | throw std::invalid_argument("A polygonal region's " + what + | |
| 131 | 10 | " needs at least 3 points, not " + | |
| 132 | 15 | std::to_string(vertices.size())); | |
| 133 | } | ||
| 134 | 123 | for (std::size_t i = 0; i < vertices.size(); ++i) { | |
| 135 | 100 | if (!(std::isfinite(vertices[i].x) && std::isfinite(vertices[i].y))) { | |
| 136 | 3 | throw std::invalid_argument("A polygonal region's " + what + " has point " + | |
| 137 | 4 | std::to_string(i) + " not finite"); | |
| 138 | } | ||
| 139 | } | ||
| 140 | 107 | for (std::size_t i = 0, j = vertices.size() - 1; i < vertices.size(); j = i++) { | |
| 141 | 126 | if (vertices[i] == vertices[j]) { | |
| 142 | 5 | throw std::invalid_argument( | |
| 143 | 15 | "A polygonal region's " + what + " has a zero-length edge: point " + | |
| 144 | 23 | std::to_string(i) + " repeats point " + std::to_string(j) + | |
| 145 | 15 | (i == 0 ? "; the outline closes itself, so do not repeat the first point" : "")); | |
| 146 | } | ||
| 147 | } | ||
| 148 | 18 | if (TwiceArea(vertices) == 0.0) { | |
| 149 | 4 | throw std::invalid_argument("A polygonal region's " + what + | |
| 150 | 6 | " has no area: its points are all on one line"); | |
| 151 | } | ||
| 152 | 16 | } | |
| 153 | |||
| 154 | } // namespace | ||
| 155 | |||
| 156 | 192989 | double RegionShape::DistanceOutside(double x, double y, const Surface& surface) const { | |
| 157 | 223156 | const auto local = [&](double px, double xScale) { | |
| 158 | 30167 | if (kind == Kind::Polygon) { | |
| 159 | 29426 | return PolygonDistance(points, holes, {px, y}, xScale); | |
| 160 | } | ||
| 161 | 741 | return BoxDistance(rectangle, px, y, xScale); | |
| 162 | 192989 | }; | |
| 163 | 192989 | if (surface.IsBody()) { | |
| 164 | 2492 | if (kind == Kind::Circle) { | |
| 165 | 2253 | return surface.Distance(center, {x, y}) - radius; | |
| 166 | } | ||
| 167 | 239 | const double cosLat = std::cos(y * kDegree); | |
| 168 | 239 | double best = std::numeric_limits<double>::infinity(); | |
| 169 | 956 | for (const double shift : {-360.0, 0.0, 360.0}) { | |
| 170 | 1434 | best = std::fmin(best, surface.UnitLength() * local(x + shift, cosLat)); | |
| 171 | } | ||
| 172 | 239 | return best; | |
| 173 | } | ||
| 174 | 190497 | if (kind == Kind::Circle) { | |
| 175 | 161047 | return std::hypot(x - center.x, y - center.y) - radius; | |
| 176 | } | ||
| 177 | 29450 | return local(x, 1.0); | |
| 178 | } | ||
| 179 | |||
| 180 | 25 | Bounds2d RegionShape::Bounds(const Surface& surface) const { | |
| 181 | 25 | if (kind == Kind::Circle) { | |
| 182 | 14 | return surface.Expand({center.x, center.y, center.x, center.y}, radius); | |
| 183 | } | ||
| 184 | 11 | if (kind == Kind::Polygon) { | |
| 185 | 4 | if (points.empty()) { | |
| 186 | ✗ | return {}; | |
| 187 | } | ||
| 188 | 4 | Bounds2d box{points.front().x, points.front().y, points.front().x, points.front().y}; | |
| 189 | 10 | const auto grow = [&](const std::vector<Vec2d>& vertices) { | |
| 190 | 38 | for (const Vec2d& v : vertices) { | |
| 191 | 32 | box.minX = std::fmin(box.minX, v.x); | |
| 192 | 32 | box.minY = std::fmin(box.minY, v.y); | |
| 193 | 32 | box.maxX = std::fmax(box.maxX, v.x); | |
| 194 | 32 | box.maxY = std::fmax(box.maxY, v.y); | |
| 195 | } | ||
| 196 | 10 | }; | |
| 197 | 4 | grow(points); | |
| 198 | 6 | for (const std::vector<Vec2d>& hole : holes) { | |
| 199 | 2 | grow(hole); | |
| 200 | } | ||
| 201 | 4 | return box; | |
| 202 | } | ||
| 203 | 7 | return rectangle; | |
| 204 | } | ||
| 205 | |||
| 206 | 76 | void ValidateRegionShape(const RegionShape& shape) { | |
| 207 | 76 | if (shape.kind == RegionShape::Kind::Circle) { | |
| 208 | 34 | if (!(std::isfinite(shape.center.x) && std::isfinite(shape.center.y) && | |
| 209 | 91 | IsNonNegative(shape.radius))) { | |
| 210 | 3 | throw std::invalid_argument("A circular region needs a finite center and radius >= 0"); | |
| 211 | } | ||
| 212 | return; | ||
| 213 | } | ||
| 214 | 42 | if (shape.kind == RegionShape::Kind::Polygon) { | |
| 215 | 44 | ValidateRing(shape.points, "outline"); | |
| 216 | 16 | for (std::size_t h = 0; h < shape.holes.size(); ++h) { | |
| 217 | 16 | ValidateRing(shape.holes[h], "hole " + std::to_string(h)); | |
| 218 | } | ||
| 219 | return; | ||
| 220 | } | ||
| 221 | 20 | const Bounds2d& r = shape.rectangle; | |
| 222 | 20 | if (!(r.IsFinite() && r.minX <= r.maxX && r.minY <= r.maxY)) { | |
| 223 | 2 | throw std::invalid_argument("A rectangular region needs finite bounds with min <= max"); | |
| 224 | } | ||
| 225 | } | ||
| 226 | |||
| 227 | 42 | MaskedLayer::MaskedLayer(std::shared_ptr<const Layer> inner, RegionShape shape, double feather, | |
| 228 | 42 | BlendShape blend) | |
| 229 | 42 | : m_inner(std::move(inner)), m_shape(shape), m_feather(feather), m_blend(blend) { | |
| 230 | 42 | if (!m_inner) { | |
| 231 | 1 | throw std::invalid_argument("A masked layer needs a layer to apply"); | |
| 232 | } | ||
| 233 | 41 | ValidateRegionShape(m_shape); | |
| 234 | 39 | RequireNonNegative(m_feather, "Masked layer feather"); | |
| 235 | 47 | } | |
| 236 | |||
| 237 | 6 | LayerPtr MaskedLayer::Confining(LayerPtr inner) const { | |
| 238 | 6 | if (!inner) { | |
| 239 | 3 | return nullptr; | |
| 240 | } | ||
| 241 | 3 | auto confining = std::make_shared<MaskedLayer>(*this); | |
| 242 | 3 | confining->m_inner = std::move(inner); | |
| 243 | 3 | return confining; | |
| 244 | 3 | } | |
| 245 | |||
| 246 | 2 | LayerPtr MaskedLayer::Reseeded(std::uint64_t seed) const { | |
| 247 | 4 | return Confining(m_inner->Reseeded(seed)); | |
| 248 | } | ||
| 249 | |||
| 250 | 3 | LayerPtr MaskedLayer::Rebound(const LayerReplacements& replaced) const { | |
| 251 | 6 | return Confining(m_inner->Rebound(replaced)); | |
| 252 | } | ||
| 253 | |||
| 254 | 1 | LayerPtr MaskedLayer::Rebased(const TerrainBase& base) const { | |
| 255 | 2 | return Confining(m_inner->Rebased(base)); | |
| 256 | } | ||
| 257 | |||
| 258 | 192692 | double MaskedLayer::Weight(double x, double y, const Surface& surface) const { | |
| 259 | 192692 | const double distance = m_shape.DistanceOutside(x, y, surface); | |
| 260 | 192692 | if (distance <= 0.0) { | |
| 261 | return 1.0; | ||
| 262 | } | ||
| 263 | 169629 | if (distance >= m_feather) { | |
| 264 | return 0.0; | ||
| 265 | } | ||
| 266 | 23023 | return Falloff(distance, 0.0, m_feather, m_blend); | |
| 267 | } | ||
| 268 | |||
| 269 | 245 | bool MaskedLayer::Holds(double x, double y, const Surface& surface) const { | |
| 270 | 245 | return m_shape.DistanceOutside(x, y, surface) <= m_feather; | |
| 271 | } | ||
| 272 | |||
| 273 | 19 | PixelWindow MaskedLayer::InnerWindow(const RasterGrid& grid, const Surface& surface) const { | |
| 274 | 19 | const Bounds2d reach = surface.Expand(m_shape.Bounds(surface), m_feather); | |
| 275 | 19 | return MergeWindows(PixelWindowsIn(grid, reach, surface)); | |
| 276 | } | ||
| 277 | |||
| 278 | 4 | std::optional<RasterGrid> MaskedLayer::InnerGrid(const RasterGrid& grid, | |
| 279 | const Surface& surface) const { | ||
| 280 | 4 | const PixelWindow window = InnerWindow(grid, surface); | |
| 281 | 4 | if (window.Empty()) { | |
| 282 | 1 | return std::nullopt; | |
| 283 | } | ||
| 284 | 3 | return Subgrid(grid, window); | |
| 285 | } | ||
| 286 | |||
| 287 | 3 | CraterFeatures MaskedLayer::CratersOver(const RasterGrid& grid, double spacing) const { | |
| 288 | 3 | const auto* placer = dynamic_cast<const CraterPlacer*>(m_inner.get()); | |
| 289 | 6 | const Surface surface = LayerBase().value_or(TerrainBase{}).surface; | |
| 290 | 3 | const std::optional<RasterGrid> inner = InnerGrid(grid, surface); | |
| 291 | 3 | CraterFeatures held; | |
| 292 | 3 | if (placer == nullptr || !inner) { | |
| 293 | return held; | ||
| 294 | } | ||
| 295 | 2 | const CraterFeatures all = placer->CratersOver(*inner, spacing); | |
| 296 | 12 | for (std::size_t n = 0; n < all.craters.Size(); ++n) { | |
| 297 | 10 | const Crater crater = all.craters.At(n); | |
| 298 | 10 | if (Holds(crater.x, crater.y, surface)) { | |
| 299 | 3 | held.craters.Append(crater); | |
| 300 | 3 | held.attributes.push_back(all.attributes[n]); | |
| 301 | } | ||
| 302 | } | ||
| 303 | 2 | return held; | |
| 304 | 5 | } | |
| 305 | |||
| 306 | 1 | BoulderFeatures MaskedLayer::BouldersOver(const RasterGrid& grid, double spacing, | |
| 307 | const Ground* ground) const { | ||
| 308 | 1 | const auto* placer = dynamic_cast<const BoulderPlacer*>(m_inner.get()); | |
| 309 | 2 | const Surface surface = LayerBase().value_or(TerrainBase{}).surface; | |
| 310 | 1 | const std::optional<RasterGrid> inner = InnerGrid(grid, surface); | |
| 311 | 1 | BoulderFeatures held; | |
| 312 | 1 | if (placer == nullptr || !inner) { | |
| 313 | return held; | ||
| 314 | } | ||
| 315 | 1 | const BoulderFeatures all = placer->BouldersOver(*inner, spacing, ground); | |
| 316 | 116 | for (std::size_t i = 0; i < all.boulders.Size(); ++i) { | |
| 317 | 115 | if (Holds(all.boulders.X()[i], all.boulders.Y()[i], surface)) { | |
| 318 | 91 | held.boulders.Append(all.boulders.At(i)); | |
| 319 | } | ||
| 320 | } | ||
| 321 | 1 | std::copy_if(all.models.begin(), all.models.end(), std::back_inserter(held.models), | |
| 322 | 115 | [&](const BoulderModel& m) { return Holds(m.boulder.x, m.boulder.y, surface); }); | |
| 323 | 1 | return held; | |
| 324 | 2 | } | |
| 325 | |||
| 326 | 96038 | void MaskedLayer::ApplySamples(SampleBlock& samples, const LayerContext& context) const { | |
| 327 | 96038 | if (Raster<float>* grid = samples.Grid()) { | |
| 328 | 15 | ApplyToGrid(*grid, context); | |
| 329 | } else { | ||
| 330 | 96023 | ApplyToPoints(samples, context); | |
| 331 | } | ||
| 332 | 96038 | } | |
| 333 | |||
| 334 | 96023 | void MaskedLayer::ApplyToPoints(SampleBlock& samples, const LayerContext& context) const { | |
| 335 | 96023 | std::vector<std::size_t> indices; | |
| 336 | 96023 | std::vector<Vec2d> positions; | |
| 337 | 96023 | std::vector<float> heights; | |
| 338 | 96023 | std::vector<double> weights; | |
| 339 | 192046 | for (std::size_t i = 0; i < samples.Size(); ++i) { | |
| 340 | 96023 | const Vec2d p = samples.Position(i); | |
| 341 | 96023 | const double weight = | |
| 342 | 192045 | samples.IsNoData(i) ? 0.0 : Weight(p.x, p.y, context.SurfaceOrPlane()); | |
| 343 | 96023 | if (weight > 0.0) { | |
| 344 | 15754 | indices.push_back(i); | |
| 345 | 15754 | positions.push_back(p); | |
| 346 | 15754 | heights.push_back(samples.Height(i)); | |
| 347 | 15754 | weights.push_back(weight); | |
| 348 | } | ||
| 349 | } | ||
| 350 | 96023 | SampleBlock inside(positions, heights); | |
| 351 | 96023 | m_inner->Apply(inside, context); | |
| 352 | 111777 | for (std::size_t k = 0; k < indices.size(); ++k) { | |
| 353 | 15754 | float& height = samples.Height(indices[k]); | |
| 354 | 15754 | height = Blend(height, heights[k], weights[k]); | |
| 355 | } | ||
| 356 | 96023 | } | |
| 357 | |||
| 358 | 15 | void MaskedLayer::ApplyToGrid(Raster<float>& heights, const LayerContext& context) const { | |
| 359 | 15 | const Surface& surface = context.SurfaceOrPlane(); | |
| 360 | 15 | const PixelWindow window = InnerWindow(heights.Grid(), surface); | |
| 361 | 15 | if (window.Empty()) { | |
| 362 | 1 | return; | |
| 363 | } | ||
| 364 | 14 | Raster<float> inner = CopyWindow(heights, window); | |
| 365 | 14 | m_inner->Apply(inner, context); | |
| 366 | 28 | ParallelFor(window.rowEnd - window.rowBegin, context.threads, [&](std::size_t r) { | |
| 367 | 467 | const std::size_t row = window.rowBegin + r; | |
| 368 | 25122 | for (std::size_t col = window.colBegin; col < window.colEnd; ++col) { | |
| 369 | 24655 | float& cell = heights(col, row); | |
| 370 | 24671 | if (heights.IsNoData(cell)) { | |
| 371 | 1 | continue; | |
| 372 | } | ||
| 373 | 24654 | const Vec2d center = heights.CellCenter(col, row); | |
| 374 | 24654 | const double weight = Weight(center.x, center.y, surface); | |
| 375 | 24654 | if (weight > 0.0) { | |
| 376 | 19402 | cell = Blend(cell, inner(col - window.colBegin, r), weight); | |
| 377 | } | ||
| 378 | } | ||
| 379 | 467 | }); | |
| 380 | 14 | } | |
| 381 | |||
| 382 | } // namespace terraingen | ||
| 383 |