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
|
//! Actual rendering functions for heatmaps.
//!
//! We begin the rendering by using [`render_heatcounter`] to turn a list of GPX tracks into a
//! [`HeatCounter`], which is basically a grayscale heatmap, where each pixel represents the number
//! of tracks that goes through this pixel.
//!
//! We then render the colored heatmap tiles using [`lazy_colorization`], which provides us with
//! colorful PNG data.
use std::thread;
use color_eyre::{eyre::Result, Report};
use image::{ImageBuffer, Luma, Pixel, RgbaImage};
use nalgebra::{vector, Vector2};
use rayon::iter::ParallelIterator;
use super::{
gpx::Coordinates,
layer::{self, TileLayer},
};
/// Represents a fully rendered tile.
#[derive(Debug, Clone)]
pub struct RenderedTile {
/// The `x` coordinate of the tile.
pub x: u64,
/// The `y` coordinate of the tile.
pub y: u64,
/// The encoded (PNG) image data, ready to be saved to disk.
pub data: Vec<u8>,
}
/// Type for the intermediate heat counters.
pub type HeatCounter = TileLayer<Luma<u8>>;
fn render_circle<P: Pixel>(layer: &mut TileLayer<P>, center: (u64, u64), radius: u64, pixel: P) {
let topleft = (center.0 - radius, center.1 - radius);
let rad_32: u32 = radius.try_into().unwrap();
let mut circle = ImageBuffer::<P, Vec<P::Subpixel>>::new(rad_32 * 2 + 1, rad_32 * 2 + 1);
imageproc::drawing::draw_filled_circle_mut(
&mut circle,
(
i32::try_from(radius).unwrap(),
i32::try_from(radius).unwrap(),
),
radius.try_into().unwrap(),
pixel,
);
layer.blit_nonzero(topleft.0, topleft.1, &circle);
}
fn direction_vector(a: (u64, u64), b: (u64, u64)) -> Vector2<f64> {
let dx = if b.0 > a.0 {
(b.0 - a.0) as f64
} else {
-((a.0 - b.0) as f64)
};
let dy = if b.1 > a.1 {
(b.1 - a.1) as f64
} else {
-((a.1 - b.1) as f64)
};
vector![dx, dy]
}
fn render_line<P: Pixel>(
layer: &mut TileLayer<P>,
start: (u64, u64),
end: (u64, u64),
thickness: u64,
pixel: P,
) {
use imageproc::point::Point;
if start == end {
return;
}
fn unsigned_add(a: Vector2<u64>, b: Vector2<i32>) -> Vector2<u64> {
let x = if b[0] < 0 {
a[0] - u64::from(b[0].unsigned_abs())
} else {
a[0] + u64::try_from(b[0]).unwrap()
};
let y = if b[1] < 0 {
a[1] - u64::from(b[1].unsigned_abs())
} else {
a[1] + u64::try_from(b[1]).unwrap()
};
vector![x, y]
}
let r = direction_vector(start, end);
let normal = vector![r[1], -r[0]].normalize();
let start = vector![start.0, start.1];
let end = vector![end.0, end.1];
let displacement = normal * thickness as f64;
let displacement = displacement.map(|x| x as i32);
if displacement == vector![0, 0] {
return;
}
let polygon = [
unsigned_add(start, displacement),
unsigned_add(end, displacement),
unsigned_add(end, -displacement),
unsigned_add(start, -displacement),
];
let min_x = polygon.iter().map(|p| p[0]).min().unwrap();
let min_y = polygon.iter().map(|p| p[1]).min().unwrap();
let max_x = polygon.iter().map(|p| p[0]).max().unwrap();
let max_y = polygon.iter().map(|p| p[1]).max().unwrap();
let mut overlay = ImageBuffer::<P, Vec<P::Subpixel>>::new(
(max_x - min_x).try_into().unwrap(),
(max_y - min_y).try_into().unwrap(),
);
let adjusted_poly = polygon
.into_iter()
.map(|p| Point::new((p[0] - min_x) as i32, (p[1] - min_y) as i32))
.collect::<Vec<_>>();
imageproc::drawing::draw_polygon_mut(&mut overlay, &adjusted_poly, pixel);
layer.blit_nonzero(min_x, min_y, &overlay);
}
fn merge_heat_counter(base: &mut HeatCounter, overlay: &HeatCounter) {
for (tx, ty, source) in overlay.enumerate_tiles() {
let target = base.tile_mut(tx, ty);
for (x, y, source) in source.enumerate_pixels() {
let target = target.get_pixel_mut(x, y);
target[0] += source[0];
}
}
}
fn colorize_tile(tile: &ImageBuffer<Luma<u8>, Vec<u8>>, max: u32) -> RgbaImage {
let gradient = colorgrad::yl_or_rd();
let mut result = ImageBuffer::from_pixel(tile.width(), tile.height(), [0, 0, 0, 0].into());
for (x, y, pixel) in tile.enumerate_pixels() {
if pixel[0] > 0 {
let alpha = pixel[0] as f64 / max as f64;
let color = gradient.at(1.0 - alpha);
let target = result.get_pixel_mut(x, y);
*target = color.to_rgba8().into();
}
}
result
}
/// Lazily colorizes a [`HeatCounter`] by colorizing it tile-by-tile and saving a tile before
/// rendering the next one.
///
/// This function calls the given callback with each rendered tile, and the function is responsible
/// for saving it. If the callback returns an `Err(...)`, the error is passed through.
///
/// Note that this function internally uses `rayon` for parallization. If you want to limit the
/// number of threads used, set up the global [`rayon::ThreadPool`] first.
pub fn lazy_colorization<F: FnMut(RenderedTile) -> Result<()> + Send>(
layer: HeatCounter,
mut save_callback: F,
) -> Result<()> {
let max = layer.pixels().map(|l| l.0[0]).max().unwrap_or_default();
if max == 0 {
return Ok(());
}
let (tx, rx) = crossbeam_channel::bounded::<RenderedTile>(30);
thread::scope(|s| {
let saver = s.spawn(move || loop {
let Ok(tile) = rx.recv() else { return Ok::<_, Report>(()) };
save_callback(tile)?;
});
layer
.into_parallel_tiles()
.try_for_each_with(tx, |tx, (tile_x, tile_y, tile)| {
let colorized = colorize_tile(&tile, max.into());
let data = layer::compress_png_as_bytes(&colorized)?;
tx.send(RenderedTile {
x: tile_x,
y: tile_y,
data,
})?;
Ok::<(), Report>(())
})?;
saver.join().unwrap()?;
Ok::<_, Report>(())
})?;
Ok(())
}
/// Renders the heat counter for the given zoom level and track points.
///
/// The given callback will be called when a track has been rendered and merged into the
/// accumulator, to allow for UI feedback. The passed parameter is the number of tracks that have
/// been rendered since the last call.
pub fn render_heatcounter<F: Fn(usize) + Send + Sync>(
zoom: u32,
tracks: &[Vec<Coordinates>],
progress_callback: F,
) -> HeatCounter {
let mut heatcounter = TileLayer::from_pixel([0].into());
for track in tracks {
let mut layer = TileLayer::from_pixel([0].into());
let points = track
.iter()
.map(|coords| coords.web_mercator(zoom))
.collect::<Vec<_>>();
for point in points.iter() {
render_circle(&mut layer, *point, (zoom as u64 / 4).max(2) - 1, [1].into());
}
for (a, b) in points.iter().zip(points.iter().skip(1)) {
render_line(&mut layer, *a, *b, (zoom as u64 / 4).max(1), [1].into());
}
merge_heat_counter(&mut heatcounter, &layer);
progress_callback(1);
}
heatcounter
}
|