File: los.cpp

package info (click to toggle)
gdal 3.12.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 92,396 kB
  • sloc: cpp: 1,224,305; ansic: 206,456; python: 26,284; java: 6,001; xml: 4,769; sh: 3,869; cs: 2,513; yacc: 1,306; makefile: 214
file content (361 lines) | stat: -rw-r--r-- 11,426 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/******************************************************************************
 *
 * Project:  Line of Sight
 * Purpose:  Core algorithm implementation for line of sight algorithms.
 * Author:   Ryan Friedman, ryanfriedman5410+gdal@gmail.com
 *
 ******************************************************************************
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include <functional>
#include <cmath>

#include "cpl_port.h"
#include "gdal_alg.h"

// There's a plethora of bresenham implementations, all questionable production quality.
// Bresenham optimizes for integer math, which makes sense for raster datasets in 2D.
// For 3D, a 3D bresenham could be used if the altitude is also integer resolution.
// 2D:
// https://codereview.stackexchange.com/questions/77460/bresenhams-line-algorithm-optimization
// https://gist.github.com/ssavi-ict/092501c69e2ffec65e96a8865470ad2f
// https://blog.demofox.org/2015/01/17/bresenhams-drawing-algorithms/
// https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
// https://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html
// https://stackoverflow.com/questions/10060046/drawing-lines-with-bresenhams-line-algorithm
// http://www.edepot.com/linebresenham.html
// 3D:
// https://gist.github.com/yamamushi/5823518

// Run bresenham terrain checking from (x1, y1) to (x2, y2).
// The callback is run at every point along the line,
// which should return True if the point is above terrain.
// Bresenham2D will return true if all points have LOS between the start and end.
static bool
Bresenham2D(const int x1, const int y1, const int x2, const int y2,
            std::function<auto(const int, const int)->bool> OnBresenhamPoint)
{
    bool isAboveTerrain = true;
    int dx, dy;
    int incx, incy;

    if (x2 >= x1)
    {
        dx = x2 - x1;
        incx = 1;
    }
    else
    {
        dx = x1 - x2;
        incx = -1;
    }

    if (y2 >= y1)
    {
        dy = y2 - y1;
        incy = 1;
    }
    else
    {
        dy = y1 - y2;
        incy = -1;
    }

    auto x = x1;
    auto y = y1;
    int balance;

    if (dx >= dy)
    {
        dy <<= 1;
        balance = dy - dx;
        dx *= 2;

        while (x != x2 && isAboveTerrain)
        {
            isAboveTerrain &= OnBresenhamPoint(x, y);
            if (balance >= 0)
            {
                y += incy;
                balance -= dx;
            }
            balance += dy;
            x += incx;
        }
        isAboveTerrain &= OnBresenhamPoint(x, y);
    }
    else
    {
        dx *= 2;
        balance = dx - dy;
        dy *= 2;

        while (y != y2 && isAboveTerrain)
        {
            isAboveTerrain &= OnBresenhamPoint(x, y);
            if (balance >= 0)
            {
                x += incx;
                balance -= dy;
            }
            balance += dx;
            y += incy;
        }
        isAboveTerrain &= OnBresenhamPoint(x, y);
    }
    return isAboveTerrain;
}

// Get the elevation of a single point.
static bool GetElevation(const GDALRasterBandH hBand, const int x, const int y,
                         double &val)
{
    /// @todo GDALCachedPixelAccessor may give increased performance.
    return GDALRasterIO(hBand, GF_Read, x, y, 1, 1, &val, 1, 1, GDT_Float64, 0,
                        0) == CE_None;
}

// Check a single location is above terrain.
static bool IsAboveTerrain(const GDALRasterBandH hBand, const int x,
                           const int y, const double z)
{
    double terrainHeight;
    if (GetElevation(hBand, x, y, terrainHeight))
    {
        return z > terrainHeight;
    }
    else
    {
        return false;
    }
}

/************************************************************************/
/*                        GDALIsLineOfSightVisible()                    */
/************************************************************************/

/**
 * Check Line of Sight between two points.
 * Both input coordinates must be within the raster coordinate bounds.
 *
 * This algorithm will check line of sight using a Bresenham algorithm.
 * https://www.researchgate.net/publication/2411280_Efficient_Line-of-Sight_Algorithms_for_Real_Terrain_Data
 * Line of sight is computed in raster coordinate space, and thus may not be appropriate.
 * For example, datasets referenced against geographic coordinate at high latitudes may have issues.
 *
 * @param hBand The band to read the DEM data from. This must NOT be null.
 *
 * @param xA The X location (raster column) of the first point to check on the raster.
 *
 * @param yA The Y location (raster row) of the first point to check on the raster.
 *
 * @param zA The Z location (height) of the first point to check.
 *
 * @param xB The X location (raster column) of the second point to check on the raster.
 *
 * @param yB The Y location (raster row) of the second point to check on the raster.
 *
 * @param zB The Z location (height) of the second point to check.
 *
 * @param[out] pnxTerrainIntersection The X location where the LOS line
 *             intersects with terrain, or nullptr if it does not intersect
 *             terrain.
 *
 * @param[out] pnyTerrainIntersection The Y location where the LOS line
 *             intersects with terrain, or nullptr if it does not intersect
 *             terrain.
 *
 * @param papszOptions Options for the line of sight algorithm (currently ignored).
 *
 * @return True if the two points are within Line of Sight.
 *
 * @since GDAL 3.9
 */

bool GDALIsLineOfSightVisible(const GDALRasterBandH hBand, const int xA,
                              const int yA, const double zA, const int xB,
                              const int yB, const double zB,
                              int *pnxTerrainIntersection,
                              int *pnyTerrainIntersection,
                              CPL_UNUSED CSLConstList papszOptions)
{
    VALIDATE_POINTER1(hBand, "GDALIsLineOfSightVisible", false);

    // A lambda to set the X-Y intersection if it's not null
    auto SetXYIntersection = [&](const int x, const int y)
    {
        if (pnxTerrainIntersection != nullptr)
        {
            *pnxTerrainIntersection = x;
        }
        if (pnyTerrainIntersection != nullptr)
        {
            *pnyTerrainIntersection = y;
        }
    };

    if (pnxTerrainIntersection)
        *pnxTerrainIntersection = -1;

    if (pnyTerrainIntersection)
        *pnyTerrainIntersection = -1;

    // Perform a preliminary check of the start and end points.
    if (!IsAboveTerrain(hBand, xA, yA, zA))
    {
        SetXYIntersection(xA, yA);
        return false;
    }
    if (!IsAboveTerrain(hBand, xB, yB, zB))
    {
        SetXYIntersection(xB, yB);
        return false;
    }

    // If both X and Y are the same, no further checks are needed.
    if (xA == xB && yA == yB)
    {
        return true;
    }

    // Lambda for Linear interpolate like C++20 std::lerp.
    auto lerp = [](const double a, const double b, const double t)
    { return a + t * (b - a); };

    // Lambda for getting Z test height given y input along the LOS line.
    // Only to be used for vertical line checks.
    auto GetZValueFromY = [&](const int y) -> double
    {
        // A ratio of 0.0 corresponds to being at yA.
        const auto ratio =
            static_cast<double>(y - yA) / static_cast<double>(yB - yA);
        return lerp(zA, zB, ratio);
    };

    // Lambda for getting Z test height given x input along the LOS line.
    // Only to be used for horizontal line checks.
    auto GetZValueFromX = [&](const int x) -> double
    {
        // A ratio of 0.0 corresponds to being at xA.
        const auto ratio =
            static_cast<double>(x - xA) / static_cast<double>(xB - xA);
        return lerp(zA, zB, ratio);
    };

    // Lambda for checking path safety of a vertical line.
    // Returns true if the path has clear LOS.
    auto CheckVerticalLine = [&]() -> bool
    {
        CPLAssert(xA == xB);
        CPLAssert(yA != yB);

        if (yA < yB)
        {
            for (int y = yA; y <= yB; ++y)
            {
                const auto zTest = GetZValueFromY(y);
                if (!IsAboveTerrain(hBand, xA, y, zTest))
                {
                    SetXYIntersection(xA, y);
                    return false;
                }
            }
            return true;
        }
        else
        {
            for (int y = yA; y >= yB; --y)
            {
                const auto zTest = GetZValueFromY(y);
                if (!IsAboveTerrain(hBand, xA, y, zTest))
                {
                    SetXYIntersection(xA, y);
                    return false;
                }
            }
            return true;
        }
    };

    // Lambda for checking path safety of a horizontal line.
    // Returns true if the path has clear LOS.
    auto CheckHorizontalLine = [&]() -> bool
    {
        CPLAssert(yA == yB);
        CPLAssert(xA != xB);

        if (xA < xB)
        {
            for (int x = xA; x <= xB; ++x)
            {
                const auto zTest = GetZValueFromX(x);
                if (!IsAboveTerrain(hBand, x, yA, zTest))
                {
                    SetXYIntersection(x, yA);
                    return false;
                }
            }
            return true;
        }
        else
        {
            for (int x = xA; x >= xB; --x)
            {
                const auto zTest = GetZValueFromX(x);
                if (!IsAboveTerrain(hBand, x, yA, zTest))
                {
                    SetXYIntersection(x, yA);
                    return false;
                }
            }
            return true;
        }
    };

    // Handle special cases if it's a vertical or horizontal line (don't use bresenham).
    if (xA == xB)
    {
        return CheckVerticalLine();
    }
    if (yA == yB)
    {
        return CheckHorizontalLine();
    }

    // Use an interpolated Z height with 2D bresenham for the remaining cases.

    // Lambda for computing the square of a number
    auto SQUARE = [](const double d) -> double { return d * d; };

    // Lambda for getting Z test height given x-y input along the bresenham line.
    auto GetZValueFromXY = [&](const int x, const int y) -> double
    {
        const auto rNum = SQUARE(static_cast<double>(x - xA)) +
                          SQUARE(static_cast<double>(y - yA));
        const auto rDenom = SQUARE(static_cast<double>(xB - xA)) +
                            SQUARE(static_cast<double>(yB - yA));
        /// @todo In order to reduce CPU cost and avoid a sqrt operation, consider
        /// the approach to just the ratio along x or y depending on whether
        /// the line is steep or shallow.
        /// See https://github.com/OSGeo/gdal/pull/9506#discussion_r1532459689.
        const double ratio =
            sqrt(static_cast<double>(rNum) / static_cast<double>(rDenom));
        return lerp(zA, zB, ratio);
    };

    // Lambda to get elevation at a bresenham-computed location.
    auto OnBresenhamPoint = [&](const int x, const int y) -> bool
    {
        const auto z = GetZValueFromXY(x, y);
        const auto isAbove = IsAboveTerrain(hBand, x, y, z);
        if (!isAbove)
        {
            SetXYIntersection(x, y);
        }
        return IsAboveTerrain(hBand, x, y, z);
    };

    return Bresenham2D(xA, yA, xB, yB, OnBresenhamPoint);
}