/
Rasterizer.scala
457 lines (417 loc) · 16.1 KB
/
Rasterizer.scala
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
* Copyright 2016 Azavea
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package geotrellis.raster.rasterize
import geotrellis.raster._
import geotrellis.raster.rasterize.extent.ExtentRasterizer
import geotrellis.raster.rasterize.polygon.PolygonRasterizer
import geotrellis.util.Constants.{DOUBLE_EPSILON => EPSILON}
import geotrellis.vector._
import spire.syntax.cfor._
import scala.language.higherKinds
trait Transformer[+B] {
def apply(col: Int, row: Int): B
}
/**
* An object holding rasterizer functions.
*/
object Rasterizer {
/**
* A type encoding rasterizer options.
*/
case class Options(
includePartial: Boolean,
sampleType: PixelSampleType
)
/**
* A companion object for the [[Options]] type. Includes a
* function to produce the default options settings.
*/
object Options {
def DEFAULT = Options(includePartial = true, sampleType = PixelIsPoint)
}
/**
* Create a raster from a geometry feature.
*
* @param geom Geometry to rasterize
* @param rasterExtent Definition of raster to create
* @param value Single value to burn
*/
def rasterizeWithValue(geom: Geometry, rasterExtent: RasterExtent, value: Int): Tile = {
val cols = rasterExtent.cols
val array = Array.ofDim[Int](rasterExtent.cols * rasterExtent.rows).fill(NODATA)
val f2 = (col: Int, row: Int) =>
array(row * cols + col) = value
foreachCellByGeometry(geom, rasterExtent)(f2)
ArrayTile(array, rasterExtent.cols, rasterExtent.rows)
}
/**
* Create a raster from a geometry feature.
*
* @param feature Feature to rasterize
* @param rasterExtent Definition of raster to create
* @param f Function that takes col, row, feature and returns value to burn
*/
def rasterize(feature: Geometry, rasterExtent: RasterExtent)(f: (Int, Int) => Int) = {
val cols = rasterExtent.cols
val array = Array.ofDim[Int](rasterExtent.cols * rasterExtent.rows).fill(NODATA)
val f2 = (col: Int, row: Int) =>
array(row * cols + col) = f(col, row)
foreachCellByGeometry(feature, rasterExtent)(f2)
ArrayTile(array, rasterExtent.cols, rasterExtent.rows)
}
/**
* Given a Geometry and a [[RasterExtent]], call the function 'f'
* at each pixel in the raster extent covered by the geometry. The
* two arguments to the function 'f' are the column and row.
*/
def foreachCellByGeometry(geom: Geometry, re: RasterExtent)(f: (Int, Int) => Unit): Unit =
foreachCellByGeometry(geom, re, Options.DEFAULT)(f)
/**
* Perform a zonal summary by invoking a function on each cell
* under provided features.
*
* This function is a closure that returns Unit; all results are a
* side effect of this function.
*
* Note: the function f should modify a mutable variable as a side
* effect. While not ideal, this avoids the unavoidable boxing
* that occurs when a Function3 returns a primitive value.
*
* @param geom Feature for calculation
* @param re RasterExtent to use for iterating through cells
* @param options Options for the (Multi)Polygon and Extent rasterizers
* @param f A function that takes (col: Int, row: Int) and produces nothing
*/
def foreachCellByGeometry(geom: Geometry, re: RasterExtent, options : Options)(f: (Int, Int) => Unit): Unit = {
geom match {
case geom: Point => foreachCellByPoint(geom, re)(f)
case geom: MultiPoint => foreachCellByMultiPoint(geom, re)(f)
case geom: MultiLine => foreachCellByMultiLineString(geom, re)(f)
case geom: Line => foreachCellByLineString(geom, re)(f)
case geom: Polygon => PolygonRasterizer.foreachCellByPolygon(geom, re, options)(f)
case geom: MultiPolygon => foreachCellByMultiPolygon(geom, re, options)(f)
case geom: GeometryCollection => geom.geometries.foreach(foreachCellByGeometry(_, re, options)(f))
case geom: Extent => ExtentRasterizer.foreachCellByExtent(geom, re, options)(f)
}
}
/**
* Invoke a function on raster cells under a point feature.
*
* The function f is a closure that should alter a mutable variable
* by side effect (to avoid boxing).
*/
def foreachCellByPoint(geom: Point, re: RasterExtent)(f: (Int, Int) => Unit) {
val col = re.mapXToGrid(geom.x)
val row = re.mapYToGrid(geom.y)
f(col, row)
}
/**
* Given a MultiPoint and a [[RasterExtent]], call the function 'f'
* at each pixel in the raster extent covered by the geometry. The
* two arguments to the function 'f' are the column and row.
*/
def foreachCellByMultiPoint(p: MultiPoint, re: RasterExtent)(f: (Int, Int) => Unit) {
p.points.foreach(foreachCellByPoint(_, re)(f))
}
/**
* Invoke a function on each point in a sequences of Points.
*/
def foreachCellByPointSeq(pSet: Seq[Point], re: RasterExtent)(f: (Int, Int) => Unit) {
pSet.foreach(foreachCellByPoint(_, re)(f))
}
/**
* Apply function f to every cell contained within MultiLineString.
*
* @param g MultiLineString used to define zone
* @param re RasterExtent used to determine cols and rows
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellByMultiLineString(g: MultiLine, re: RasterExtent)(f: (Int, Int) => Unit) {
g.lines.foreach(foreachCellByLineString(_, re)(f))
}
/**
* Apply function f to every cell contained within MultiLineString.
*
* @param g MultiLineString used to define zone
* @param re RasterExtent used to determine cols and rows
* @param c Desired connectivity of the line
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellByMultiLineString(
g: MultiLine,
re: RasterExtent,
c: Connectivity
)(f: (Int, Int) => Unit) {
g.lines.foreach(foreachCellByLineString(_, re, c)(f))
}
/**
* Given a Polygon and a [[RasterExtent]], call the function 'f' at
* each pixel in the raster extent covered by the geometry. The
* two arguments to the function 'f' are the column and row.
*/
def foreachCellByPolygon(p: Polygon, re: RasterExtent)(f: (Int, Int) => Unit): Unit =
foreachCellByPolygon(p, re, Options.DEFAULT)(f)
/**
* Apply function f(col, row, feature) to every cell contained
* within polygon.
*
* @param p Polygon used to define zone
* @param re RasterExtent used to determine cols and rows
* @param options The options parameter controls whether to treat pixels as points or areas and whether to report partially-intersected areas.
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellByPolygon(p: Polygon, re: RasterExtent, options: Options)(f: (Int, Int) => Unit) {
PolygonRasterizer.foreachCellByPolygon(p, re, options)(f)
}
/**
* Given a MultiPolygon and a [[RasterExtent]], call the function
* 'f' at each pixel in the raster extent covered by the geometry.
* The two arguments to the function 'f' are the column and row.
*/
def foreachCellByMultiPolygon[D](p: MultiPolygon, re: RasterExtent)(f: (Int, Int) => Unit): Unit =
foreachCellByMultiPolygon(p, re, Options.DEFAULT)(f)
/**
* Apply function f to every cell contained with MultiPolygon.
*
* @param p MultiPolygon used to define zone
* @param re RasterExtent used to determine cols and rows
* @param options The options parameter controls whether to treat pixels as points or areas and whether to report partially-intersected areas.
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellByMultiPolygon[D](p: MultiPolygon, re: RasterExtent, options: Options)(f: (Int, Int) => Unit) {
p.polygons.foreach(PolygonRasterizer.foreachCellByPolygon(_, re, options)(f))
}
/**
* Iterates over the cells determined by the segments of a
* LineString. The iteration happens in the direction from the
* first point to the last point.
*/
def foreachCellByLineString(
line: Line,
re: RasterExtent,
c: Connectivity
)(f: (Int, Int) => Unit) {
val coords = line.jtsGeom.getCoordinates()
var i = 1; while (i < coords.size) {
val x1 = re.mapXToGrid(coords(i-1).x)
val y1 = re.mapYToGrid(coords(i-1).y)
val x2 = re.mapXToGrid(coords(i+0).x)
val y2 = re.mapYToGrid(coords(i+0).y)
foreachCellInGridLine(x1, y1, x2, y2, re, i != coords.size - 1, c)(f)
i += 1
}
}
/**
* Iterates over the cells determined by the segments of a
* LineString. The iteration happens in the direction from the
* first point to the last point.
*/
def foreachCellByLineString(line: Line, re: RasterExtent)(f: (Int, Int) => Unit) {
val coords = line.jtsGeom.getCoordinates()
var i = 1; while (i < coords.size) {
val x1 = re.mapXToGrid(coords(i-1).x)
val y1 = re.mapYToGrid(coords(i-1).y)
val x2 = re.mapXToGrid(coords(i+0).x)
val y2 = re.mapYToGrid(coords(i+0).y)
foreachCellInGridLine(x1, y1, x2, y2, line, re, i != coords.size - 1)(f)
i += 1
}
}
/**
* Implementation of the Bresenham line drawing algorithm. Only
* calls on cell coordinates within raster extent.
*
* The parameter 'skipLast' is a flag which is 'true' if the
* function should skip function calling the last cell (x1, y1) and
* false otherwise. This is useful for not duplicating end points
* when calling for multiple line segments.
*
* @param p LineString used to define zone
* @param re RasterExtent used to determine cols and rows
* @param skipLast Boolean flag
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellInGridLine[D](
x0: Int, y0: Int,
x1: Int, y1: Int,
p: Line, re: RasterExtent,
skipLast: Boolean = false
)(f: (Int, Int) => Unit): Unit = {
foreachCellInGridLine(x0, y0, x1, y1, re, skipLast, EightNeighbors)(f)
}
/**
* Implementation of the Bresenham line drawing algorithm. Only
* calls on cell coordinates within raster extent.
*
* The parameter 'skipLast' is a flag which is 'true' if the
* function should skip function calling the last cell (x1, y1) and
* false otherwise. This is useful for not duplicating end points
* when calling for multiple line segments.
*
* @param p LineString used to define zone
* @param re RasterExtent used to determine cols and rows
* @param skipLast Boolean flag
* @param f Function to apply: f(cols, row, feature)
*/
def foreachCellInGridLine(
x0: Int, y0: Int,
x1: Int, y1: Int,
re: RasterExtent,
skipLast: Boolean,
c: Connectivity
)(f: (Int, Int) => Unit): Unit = {
val dx=math.abs(x1 - x0)
val sx=if (x0 < x1) 1 else -1
val dy=math.abs(y1 - y0)
val sy=if (y0 < y1) 1 else -1
var x = x0
var y = y0
var err = (if (dx>dy) dx else -dy) / 2
var e2 = err
while(x != x1 || y != y1){
if(0 <= x && x < re.cols &&
0 <= y && y < re.rows) { f(x, y); }
e2 = err
if (e2 > -dx) { err -= dy; x += sx; }
if (e2 < dy) {
if (c == FourNeighbors &&
e2 > -dx &&
0 <= x && x < re.cols &&
0 <= y && y < re.rows) f(x, y)
err += dx; y += sy;
}
}
if(!skipLast &&
0 <= x && x < re.cols &&
0 <= y && y < re.rows) { f(x, y); }
}
/**
* Iterates over the cells determined by the segments of a
* LineString. The iteration happens in the direction from the
* first point to the last point.
*/
@deprecated("This function will be deprecated in 2.0 in favor of richer options on foreachCellByGeometry", "1.2")
def foreachCellByLineStringDouble(line: Line, re: RasterExtent)(f: (Int, Int) => Unit) {
val coords = line.jtsGeom.getCoordinates()
var i = 1; while (i < coords.size) {
foreachCellInGridLineDouble(coords(i-1).x, coords(i-1).y, coords(i+0).x, coords(i+0).y, re, line.isClosed || i != coords.size - 1)(f)
i += 1
}
}
/**
* Implementation drawn from ``A Fast Voxel Traversal Algorithm for Ray
* Tracing'' by John Amanatides and Andrew Woo. Dept. of Computer Science,
* University of Toronto.
*
* The parameter 'skipLast' is a flag which is 'true' if the
* function should skip function calling the last cell (x1, y1) and
* false otherwise. This is useful for not duplicating end points
* when calling for multiple line segments.
*
* @param x0 x-coordinate of initial point
* @param y0 y-coordinate of initial point
* @param x1 x-coordinate of final point
* @param y1 y-coordinate of final point
* @param re RasterExtent used to determine cols and rows
* @param skipLast Boolean flag
* @param f Function to apply: f(cols, row, feature)
*/
private def foreachCellInGridLineDouble(
x0: Double, y0: Double,
x1: Double, y1: Double,
re: RasterExtent,
skipLast: Boolean
)(f: (Int, Int) => Unit): Unit = {
def clamp(lo: Int, hi: Int)(x: Int) = {
if (x < lo)
lo
else
if (x > hi)
hi
else
x
}
// Find cell of first intersection with extent and ray
val (initialPoint, finalPoint) = re.extent.intersection(Line((x0, y0), (x1, y1))) match {
case NoResult => return
case PointResult(p) => (p, None)
case LineResult(l) =>
val p0 = l.vertices(0)
val p1 = l.vertices(1)
val base = Point(x0, y0)
if (base.distance(p0) <= base.distance(p1))
(p0, Some(p1))
else
(p1, Some(p0))
}
var (cellX, cellY) = {
val (x, y) = re.mapToGrid(initialPoint)
(clamp(0, re.cols - 1)(x), clamp(0, re.rows - 1)(y))
}
if (finalPoint.isEmpty) {
f(cellX, cellY)
return
}
val (finalX, finalY) = {
val (x, y) = re.mapToGrid(finalPoint.get)
(clamp(0, re.cols - 1)(x), clamp(0, re.rows - 1)(y))
}
val stepX = math.signum(x1 - x0).toInt
val stepY = math.signum(y0 - y1).toInt
val firstX = if (stepX==0) Double.PositiveInfinity else (re.gridColToMap(cellX) + re.gridColToMap(cellX + stepX)) / 2.0
val firstY = if (stepY==0) Double.PositiveInfinity else (re.gridRowToMap(cellY) + re.gridRowToMap(cellY + stepY)) / 2.0
val (dx, dy) = (finalPoint.get.x - initialPoint.x, finalPoint.get.y - initialPoint.y)
var (tMaxX, tMaxY) = ((firstX - initialPoint.x) / dx, (firstY - initialPoint.y) / dy)
val (tDeltaX, tDeltaY) = (re.cellwidth / math.abs(dx), re.cellheight / math.abs(dy))
do {
f(cellX, cellY)
if (math.abs(tMaxX - tMaxY) < EPSILON) {
// crossing at grid intersection
(stepX, stepY) match {
case ( 1, -1) =>
cellX += stepX
tMaxX += tDeltaX
case ( 1, 1) =>
cellX += stepX
cellY += stepY
tMaxX += tDeltaX
tMaxY += tDeltaY
case (-1, 1) =>
cellY += stepY
tMaxY += tDeltaY
case (-1, -1) =>
cellX += stepX
cellY += stepY
tMaxX += tDeltaX
tMaxY += tDeltaY
case _ =>
throw new RuntimeException(s"Arrived at illegal configuration: stepX=$stepX, stepY=$stepY")
}
} else {
// regular crossing
if (tMaxX < tMaxY) {
tMaxX += tDeltaX
cellX += stepX
} else {
tMaxY += tDeltaY
cellY += stepY
}
}
} while (cellX != finalX || cellY != finalY)
if (!skipLast)
f(cellX, cellY)
}
}