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
mod edit;
mod magnifying;
mod nearby;
mod route_sketcher;

use abstutil::prettyprint_usize;
use geom::{Circle, Distance, Pt2D};
use map_gui::tools::{nice_map_name, CityPicker, PopupMsg};
use map_model::{LaneType, PathConstraints, Road};
use widgetry::{
    lctrl, Color, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome,
    Panel, State, Text, Toggle, VerticalAlignment, Widget,
};

use crate::app::{App, Transition};
use crate::common::Warping;
use magnifying::MagnifyingGlass;
use nearby::Nearby;

lazy_static::lazy_static! {
    static ref DEDICATED_TRAIL: Color = Color::GREEN;
    static ref PROTECTED_BIKE_LANE: Color = Color::hex("#A4DE02");
    static ref PAINTED_BIKE_LANE: Color = Color::hex("#76BA1B");
    static ref GREENWAY: Color = Color::hex("#4C9A2A");
}

pub struct ExploreMap {
    top_panel: Panel,
    legend: Panel,
    magnifying_glass: MagnifyingGlass,
    network_layer: Drawable,
    elevation: bool,
    // TODO Also cache Nearby, but recalculate it after edits
    nearby: Option<Nearby>,

    changelist_key: (String, usize),
}

impl ExploreMap {
    pub fn new_state(ctx: &mut EventCtx, app: &mut App) -> Box<dyn State<App>> {
        app.opts.show_building_driveways = false;
        let edits = app.primary.map.get_edits();

        Box::new(ExploreMap {
            top_panel: make_top_panel(ctx),
            legend: make_legend(ctx, app, false, false),
            magnifying_glass: MagnifyingGlass::new(ctx, true),
            network_layer: render_network_layer(ctx, app),
            elevation: false,
            nearby: None,

            changelist_key: (edits.edits_name.clone(), edits.commands.len()),
        })
    }
}

impl State<App> for ExploreMap {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        {
            let edits = app.primary.map.get_edits();
            let changelist_key = (edits.edits_name.clone(), edits.commands.len());
            if self.changelist_key != changelist_key {
                self.changelist_key = changelist_key;
                self.network_layer = crate::ungap::render_network_layer(ctx, app);
            }
        }

        ctx.canvas_movement();

        self.magnifying_glass.event(ctx, app);

        if ctx.redo_mouseover() && self.elevation {
            let mut label = Text::new().into_widget(ctx);

            if ctx.canvas.cam_zoom < app.opts.min_zoom_for_detail {
                if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
                    if let Some((elevation, _)) = app
                        .session
                        .elevation_contours
                        .value()
                        .unwrap()
                        .0
                        .closest_pt(pt, Distance::meters(300.0))
                    {
                        label =
                            Line(format!("{} ft", elevation.to_feet().round())).into_widget(ctx);
                    }
                }
            }
            self.legend.replace(ctx, "current elevation", label);
        }

        if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
            if ctx.canvas.cam_zoom < app.opts.min_zoom_for_detail && ctx.normal_left_click() {
                return Transition::Push(Warping::new_state(
                    ctx,
                    pt,
                    Some(10.0),
                    None,
                    &mut app.primary,
                ));
            }
        }

        if let Outcome::Clicked(x) = self.top_panel.event(ctx) {
            match x.as_ref() {
                "about A/B Street" => {
                    return Transition::Push(PopupMsg::new_state(ctx, "TODO", vec!["TODO"]));
                }
                "Bike Master Plan" => {
                    return Transition::Push(PopupMsg::new_state(ctx, "TODO", vec!["TODO"]));
                }
                "Edit network" => {
                    return Transition::Push(edit::QuickEdit::new_state(ctx, app));
                }
                _ => unreachable!(),
            }
        }

        match self.legend.event(ctx) {
            Outcome::Clicked(x) => {
                return Transition::Push(match x.as_ref() {
                    "change map" => CityPicker::new_state(
                        ctx,
                        app,
                        Box::new(|ctx, app| {
                            Transition::Multi(vec![Transition::Pop, Transition::Replace(ExploreMap::new_state(ctx, app))])
                        }),
                    ),
                    // TODO Add physical picture examples
                    "highway" => PopupMsg::new_state(ctx, "Highways", vec!["Unless there's a separate trail (like on the 520 or I90 bridge), highways aren't accessible to biking"]),
                    "major street" => PopupMsg::new_state(ctx, "Major streets", vec!["Arterials have more traffic, but are often where businesses are located"]),
                    "minor street" => PopupMsg::new_state(ctx, "Minor streets", vec!["Local streets have a low volume of traffic and are usually comfortable for biking, even without dedicated infrastructure"]),
                    "trail" => PopupMsg::new_state(ctx, "Trails", vec!["Trails like the Burke Gilman are usually well-separated from vehicle traffic. The space is usually shared between people walking, cycling, and rolling."]),
                    "protected bike lane" => PopupMsg::new_state(ctx, "Protected bike lanes", vec!["Bike lanes separated from vehicle traffic by physical barriers or a few feet of striping"]),
                    "painted bike lane" => PopupMsg::new_state(ctx, "Painted bike lanes", vec!["Bike lanes without any separation from vehicle traffic. Often uncomfortably close to the \"door zone\" of parked cars."]),
                    "Stay Healthy Street / greenway" => PopupMsg::new_state(ctx, "Stay Healthy Streets and neighborhood greenways", vec!["Residential streets with additional signage and light barriers. These are intended to be low traffic, dedicated for people walking and biking."]),
                    // TODO Add URLs
                    "about the elevation data" => PopupMsg::new_state(ctx, "About the elevation data", vec!["Biking uphill next to traffic without any dedicated space isn't fun.", "Biking downhill next to traffic, especially in the door-zone of parked cars, and especially on Seattle's bumpy roads... is downright terrifying.", "", "Note the elevation data is incorrect near bridges.", "Thanks to King County LIDAR for the data, and Eldan Goldenberg for processing it."]),
                    "about the things nearby" => PopupMsg::new_state(ctx, "About the things nearby", vec!["Population daa from ?", "Amenities from OpenStreetMap", "A 1-minute biking buffer around the bike network is shown.", "Note 1 minutes depends on direction, especially with steep hills -- this starts FROM the network."]),
                    _ => unreachable!(),
            });
            }
            Outcome::Changed(x) => match x.as_ref() {
                "elevation" => {
                    self.elevation = self.legend.is_checked("elevation");
                    self.legend = make_legend(ctx, app, self.elevation, self.nearby.is_some());
                    if self.elevation {
                        let name = app.primary.map.get_name().clone();
                        if app.session.elevation_contours.key() != Some(name.clone()) {
                            let mut low = Distance::ZERO;
                            let mut high = Distance::ZERO;
                            for i in app.primary.map.all_intersections() {
                                low = low.min(i.elevation);
                                high = high.max(i.elevation);
                            }
                            // TODO Maybe also draw the uphill arrows on the steepest streets?
                            let value = crate::layer::elevation::make_elevation_contours(
                                ctx, app, low, high,
                            );
                            app.session.elevation_contours.set(name, value);
                        }
                    }
                }
                "things nearby" => {
                    if self.legend.is_checked("things nearby") {
                        let nearby = Nearby::new(ctx, app);
                        let label = Text::from(Line(format!(
                            "{} residents, {} shops",
                            prettyprint_usize(nearby.population),
                            prettyprint_usize(nearby.total_amenities)
                        )))
                        .into_widget(ctx);
                        self.legend.replace(ctx, "nearby info", label);
                        self.nearby = Some(nearby);
                    } else {
                        let label = Text::new().into_widget(ctx);
                        self.legend.replace(ctx, "nearby info", label);
                        self.nearby = None;
                    }
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.top_panel.draw(g);
        self.legend.draw(g);
        if g.canvas.cam_zoom < app.opts.min_zoom_for_detail {
            g.redraw(&self.network_layer);

            if self.elevation {
                if let Some((_, ref draw)) = app.session.elevation_contours.value() {
                    g.redraw(draw);
                }
            }
            if let Some(ref nearby) = self.nearby {
                g.redraw(&nearby.draw_buffer);
            }

            self.magnifying_glass.draw(g, app);
        }
    }
}

fn make_top_panel(ctx: &mut EventCtx) -> Panel {
    Panel::new_builder(Widget::row(vec![
        ctx.style()
            .btn_plain
            .btn()
            .image_path("system/assets/pregame/logo.svg")
            .image_dims(50.0)
            .build_widget(ctx, "about A/B Street"),
        // TODO Tab style?
        ctx.style()
            .btn_solid_primary
            .text("Today")
            .disabled(true)
            .build_def(ctx)
            .centered_vert(),
        ctx.style()
            .btn_solid_primary
            .text("Bike Master Plan")
            .build_def(ctx)
            .centered_vert(),
        ctx.style()
            .btn_solid_primary
            .icon_text("system/assets/tools/pencil.svg", "Edit network")
            .hotkey(lctrl(Key::E))
            .build_def(ctx)
            .centered_vert(),
    ]))
    .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
    .build(ctx)
}

fn make_legend(ctx: &mut EventCtx, app: &App, elevation: bool, nearby: bool) -> Panel {
    Panel::new_builder(Widget::col(vec![
        Widget::custom_row(vec![
            Line("Bike Network")
                .small_heading()
                .into_widget(ctx)
                .margin_right(18),
            ctx.style()
                .btn_popup_icon_text(
                    "system/assets/tools/map.svg",
                    nice_map_name(app.primary.map.get_name()),
                )
                .hotkey(lctrl(Key::L))
                .build_widget(ctx, "change map")
                .margin_right(8),
        ]),
        // TODO Looks too close to access restrictions
        legend(ctx, app.cs.unzoomed_highway, "highway"),
        legend(ctx, app.cs.unzoomed_arterial, "major street"),
        legend(ctx, app.cs.unzoomed_residential, "minor street"),
        legend(ctx, *DEDICATED_TRAIL, "trail"),
        legend(ctx, *PROTECTED_BIKE_LANE, "protected bike lane"),
        legend(ctx, *PAINTED_BIKE_LANE, "painted bike lane"),
        legend(ctx, *GREENWAY, "Stay Healthy Street / greenway"),
        // TODO Distinguish door-zone bike lanes?
        // TODO Call out bike turning boxes?
        // TODO Call out bike signals?
        Widget::row(vec![
            Toggle::checkbox(ctx, "elevation", Key::E, elevation),
            ctx.style()
                .btn_plain
                .icon("system/assets/tools/info.svg")
                .build_widget(ctx, "about the elevation data")
                .centered_vert(),
            Text::new()
                .into_widget(ctx)
                .named("current elevation")
                .centered_vert(),
        ]),
        Widget::row(vec![
            Toggle::checkbox(ctx, "things nearby", None, nearby),
            ctx.style()
                .btn_plain
                .icon("system/assets/tools/info.svg")
                .build_widget(ctx, "about the things nearby")
                .centered_vert(),
            Text::new()
                .into_widget(ctx)
                .named("nearby info")
                .centered_vert(),
        ]),
    ]))
    .aligned(HorizontalAlignment::Right, VerticalAlignment::Bottom)
    .build(ctx)
}

pub fn legend(ctx: &mut EventCtx, color: Color, label: &str) -> Widget {
    let radius = 15.0;
    Widget::row(vec![
        GeomBatch::from(vec![(
            color,
            Circle::new(Pt2D::new(radius, radius), Distance::meters(radius)).to_polygon(),
        )])
        .into_widget(ctx)
        .centered_vert(),
        ctx.style()
            .btn_plain
            .text(label)
            .build_def(ctx)
            .centered_vert(),
    ])
}

pub fn render_network_layer(ctx: &mut EventCtx, app: &App) -> Drawable {
    let mut batch = GeomBatch::new();
    // The basemap colors are beautiful, but we want to emphasize the bike network, so all's foggy
    // in love and war...
    batch.push(
        Color::BLACK.alpha(0.4),
        app.primary.map.get_boundary_polygon().clone(),
    );

    for r in app.primary.map.all_roads() {
        if r.is_cycleway() {
            batch.push(*DEDICATED_TRAIL, r.get_thick_polygon(&app.primary.map));
            continue;
        }

        if is_greenway(r) {
            batch.push(*GREENWAY, r.get_thick_polygon(&app.primary.map));
        }

        // Don't cover up the arterial/local classification -- add thick side lines to show bike
        // facilties in each direction.
        let mut bike_lane_left = false;
        let mut buffer_left = false;
        let mut bike_lane_right = false;
        let mut buffer_right = false;
        let mut on_left = true;
        for (_, _, lt) in r.lanes_ltr() {
            if lt == LaneType::Driving || lt == LaneType::Bus {
                // We're walking the lanes from left-to-right. So as soon as we hit a vehicle lane,
                // any bike lane we find is on the right side of the road.
                // (Barring really bizarre things like a bike lane in the middle of the road)
                on_left = false;
            } else if lt == LaneType::Biking {
                if on_left {
                    bike_lane_left = true;
                } else {
                    bike_lane_right = true;
                }
            } else if matches!(lt, LaneType::Buffer(_)) {
                if on_left {
                    buffer_left = true;
                } else {
                    buffer_right = true;
                }
            }

            let half_width = r.get_half_width(&app.primary.map);
            for (shift, bike_lane, buffer) in [
                (-1.0, bike_lane_left, buffer_left),
                (1.0, bike_lane_right, buffer_right),
            ] {
                let color = if bike_lane && buffer {
                    *PROTECTED_BIKE_LANE
                } else if bike_lane {
                    *PAINTED_BIKE_LANE
                } else {
                    // If we happen to have a buffer, but no bike lane, let's just not ask
                    // questions...
                    continue;
                };
                if let Ok(pl) = r.center_pts.shift_either_direction(shift * half_width) {
                    batch.push(color, pl.make_polygons(0.9 * half_width));
                }
            }
        }
    }
    batch.upload(ctx)
}

// TODO Check how other greenways are tagged.
// https://www.openstreetmap.org/way/262778812 has bicycle=designated, cycleway=shared_lane...
pub fn is_greenway(road: &Road) -> bool {
    !road
        .access_restrictions
        .allow_through_traffic
        .contains(PathConstraints::Car)
        && road
            .access_restrictions
            .allow_through_traffic
            .contains(PathConstraints::Bike)
}