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
use egui::{
DragPanButtons, InnerResponse, PointerButton, Response, Sense, Ui, UiBuilder, Vec2, Widget,
};
use crate::{
MapMemory, Options, Plugin, Position, Projector, Tiles, center::Center,
position::AdjustedPosition, tiles::draw_tiles,
};
struct Layer<'a> {
tiles: &'a mut dyn Tiles,
transparency: f32,
}
/// The actual map widget. Instances are to be created on each frame, as all necessary state is
/// stored in [`Tiles`] and [`MapMemory`].
///
/// # Examples
///
/// ```
/// # use walkers::{Map, Tiles, MapMemory, Position, lon_lat};
///
/// fn update(ui: &mut egui::Ui, tiles: &mut dyn Tiles, map_memory: &mut MapMemory) {
/// ui.add(Map::new(
/// Some(tiles), // `None`, if you don't want to show any tiles.
/// map_memory,
/// lon_lat(17.03664, 51.09916)
/// ));
/// }
/// ```
///
/// Initially, the map follows `my_position` argument which is typically fed by a GPS sensor or
/// other geo-localization method. If user drags the map, it enters a "detached state". You can use
/// [`MapMemory`]'s methods to change the state programmatically.
pub struct Map<'a, 'b, 'c> {
tiles: Option<&'b mut dyn Tiles>,
layers: Vec<Layer<'b>>,
memory: &'a mut MapMemory,
my_position: Position,
plugins: Vec<Box<dyn Plugin + 'c>>,
options: Options,
}
impl<'a, 'b, 'c> Map<'a, 'b, 'c> {
pub fn new(
tiles: Option<&'b mut dyn Tiles>,
memory: &'a mut MapMemory,
my_position: Position,
) -> Self {
Self {
tiles,
layers: Vec::default(),
memory,
my_position,
plugins: Vec::default(),
options: Options::default(),
}
}
/// Add plugin to the drawing pipeline. Plugins allow drawing custom shapes on the map.
pub fn with_plugin(mut self, plugin: impl Plugin + 'c) -> Self {
self.plugins.push(Box::new(plugin));
self
}
/// Add a tile layer. All layers are drawn on top of each other with given transparency.
pub fn with_layer(mut self, tiles: &'b mut dyn Tiles, transparency: f32) -> Self {
self.layers.push(Layer {
tiles,
transparency,
});
self
}
/// Set whether map should perform zoom gesture.
///
/// Zoom is typically triggered by the mouse wheel while holding <kbd>ctrl</kbd> key on native
/// and web, and by pinch gesture on Android.
pub fn zoom_gesture(mut self, enabled: bool) -> Self {
self.options.zoom_gesture_enabled = enabled;
self
}
/// Specify which pointer buttons can be used to pan by clicking and dragging.
pub fn drag_pan_buttons(mut self, buttons: DragPanButtons) -> Self {
self.options.drag_pan_buttons = buttons;
self
}
/// Change how far to zoom in/out.
/// Default value is 2.0
pub fn zoom_speed(mut self, speed: f64) -> Self {
self.options.zoom_speed = speed;
self
}
/// Set whether to enable double click primary mouse button to zoom
pub fn double_click_to_zoom(mut self, enabled: bool) -> Self {
self.options.double_click_to_zoom = enabled;
self
}
/// Set whether to enable double click secondary mouse button to zoom out
pub fn double_click_to_zoom_out(mut self, enabled: bool) -> Self {
self.options.double_click_to_zoom_out = enabled;
self
}
/// Sets the zoom behaviour
///
/// When enabled zoom is done with mouse wheel while holding <kbd>ctrl</kbd> key on native
/// and web. Panning is done with mouse wheel without <kbd>ctrl</kbd> key
///
/// When disabled, zooming can be done without holding <kbd>ctrl</kbd> key
/// but panning with mouse wheel is disabled
///
/// Has no effect on Android
pub fn zoom_with_ctrl(mut self, enabled: bool) -> Self {
self.options.zoom_with_ctrl = enabled;
self
}
/// Set if we can pan with mouse wheel.
/// By default, panning is disabled when zooming with ctrl is disabled.
/// Allow to disable panning even when zooming with ctrl is enabled.
pub fn panning(mut self, enabled: bool) -> Self {
self.options.panning = enabled;
self
}
/// Set the threshold for pulling the map back to `my_position` when dragged.
///
/// It can be used to prevent the map from being accidentally detached when the user clicks on
/// something causing a small drag.
pub fn pull_to_my_position_threshold(mut self, threshold: f32) -> Self {
self.options.pull_to_my_position_threshold = threshold;
self
}
/// Show the map widget inside a [`egui::Ui`].
pub fn show<R>(
mut self,
ui: &mut Ui,
add_contents: impl FnOnce(&mut Ui, &Response, &Projector, &MapMemory) -> R,
) -> InnerResponse<R> {
let (rect, mut response) =
ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
let mut changed = self.handle_gestures(ui, &response);
let delta_time = ui.input(|reader| reader.stable_dt);
let zoom = self.memory.zoom;
changed |= self
.memory
.center_mode
.update_movement(delta_time, zoom.into());
if changed {
response.mark_changed();
ui.request_repaint();
}
let map_center = self.position();
let painter = ui.painter().with_clip_rect(rect);
if let Some(tiles) = self.tiles {
draw_tiles(&painter, map_center, zoom, tiles, 1.0);
}
for layer in self.layers {
draw_tiles(&painter, map_center, zoom, layer.tiles, layer.transparency);
}
// Run plugins.
let projector = Projector::new(response.rect, self.memory, self.my_position);
for (idx, plugin) in self.plugins.into_iter().enumerate() {
let mut child_ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(idx));
plugin.run(&mut child_ui, &response, &projector, self.memory);
}
let mut child_ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt("inner"));
let inner = add_contents(&mut child_ui, &response, &projector, self.memory);
InnerResponse { inner, response }
}
}
impl Map<'_, '_, '_> {
/// Handle user inputs and recalculate everything accordingly. Returns whether something changed.
fn handle_gestures(&mut self, ui: &mut Ui, response: &Response) -> bool {
let zoom_delta = self.zoom_delta(ui, response);
// Zooming and dragging need to be exclusive, otherwise the map will get dragged when
// pinch gesture is used.
let changed = if (zoom_delta - 1.0).abs() > 0.001
&& ui.ui_contains_pointer()
&& self.options.zoom_gesture_enabled
{
// Displacement of mouse pointer relative to widget center
let offset = input_offset(ui, response);
// While zooming, we want to keep the location under the mouse pointer fixed on the
// screen. To achieve this, we first move the location to the widget's center,
// then adjust zoom level, finally move the location back to the original screen
// position.
if let Some(offset) = offset {
// If map is tracking `my_position` and the input offset is close, just let it be.
if self.memory.detached().is_some()
|| offset.length() > self.options.pull_to_my_position_threshold
{
self.memory.center_mode = Center::Exact(
AdjustedPosition::new(self.position()).shift(-offset, self.memory.zoom()),
);
}
}
// Shift by 1 because of the values given by zoom_delta(). Multiple by zoom_speed(defaults to 2.0),
// because then it felt right with both mouse wheel, and an Android phone.
self.memory
.zoom
.zoom_by((zoom_delta - 1.) * self.options.zoom_speed);
if let Some(offset) = offset {
self.memory.center_mode = self
.memory
.center_mode
.clone()
.shift(offset, self.memory.zoom());
}
true
} else {
self.memory.center_mode.handle_gestures(
response,
self.my_position,
self.options.pull_to_my_position_threshold,
self.options.drag_pan_buttons,
)
};
// Only enable panning with mouse_wheel if we are zooming with ctrl. But always allow touch devices to pan
let panning_enabled =
self.options.panning && (ui.input(|i| i.any_touches()) || self.options.zoom_with_ctrl);
if ui.ui_contains_pointer() && panning_enabled {
// Panning by scrolling, e.g. two-finger drag on a touchpad:
let scroll_delta = ui.input(|i| i.smooth_scroll_delta);
if scroll_delta != Vec2::ZERO {
self.memory.center_mode = Center::Exact(
AdjustedPosition::new(self.position()).shift(scroll_delta, self.memory.zoom()),
);
}
}
changed
}
/// Calculate the zoom delta based on the input.
fn zoom_delta(&self, ui: &mut Ui, response: &Response) -> f64 {
let mut zoom_delta = ui.input(|input| input.zoom_delta()) as f64;
if self.options.double_click_to_zoom
&& ui.ui_contains_pointer()
&& response.double_clicked_by(PointerButton::Primary)
{
zoom_delta = 2.0;
}
if self.options.double_click_to_zoom_out
&& ui.ui_contains_pointer()
&& response.double_clicked_by(PointerButton::Secondary)
{
zoom_delta = 0.0;
}
if !self.options.zoom_with_ctrl && zoom_delta == 1.0 {
// We only use the raw scroll values, if we are zooming without ctrl,
// and zoom_delta is not already over/under 1.0 (eg. a ctrl + scroll event or a pinch zoom)
// These values seem to correspond to the same values as one would get in `zoom_delta()`
zoom_delta = 1f64
+ ui.input(|input| {
input.smooth_scroll_delta.y * input.stable_dt.max(input.predicted_dt * 1.5)
}) as f64
/ 4.0;
};
zoom_delta
}
/// Get the real position at the map's center.
fn position(&self) -> Position {
self.memory.center_mode.position(self.my_position)
}
}
impl Widget for Map<'_, '_, '_> {
fn ui(self, ui: &mut Ui) -> Response {
self.show(ui, |_, _, _, _| ()).response
}
}
/// Get the offset of the input (either mouse or touch) relative to the center.
fn input_offset(ui: &mut Ui, response: &Response) -> Option<Vec2> {
let mouse_offset = response.hover_pos();
let touch_offset = ui
.input(|input| input.multi_touch())
.map(|multi_touch| multi_touch.center_pos);
// On touch we get both, so make touch the priority.
touch_offset
.or(mouse_offset)
.map(|pos| pos - response.rect.center())
}