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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use std::collections::HashSet;

use geom::{Circle, Distance, Duration, FindClosest, PolyLine};
use map_gui::tools::{PopupMsg, ToggleZoomed};
use map_model::{Path, PathStep, RoutingParams, NORMAL_LANE_THICKNESS};
use sim::{TripEndpoint, TripMode};
use widgetry::{
    Color, Drawable, EventCtx, GeomBatch, GfxCtx, Line, LinePlot, Outcome, Panel, PlotOptions,
    Series, Text, Widget,
};

use crate::app::{App, Transition};

pub struct RouteResults {
    // It's tempting to glue together all of the paths. But since some waypoints might force the
    // path to double back on itself, rendering the path as a single PolyLine would break.
    paths: Vec<(Path, Option<PolyLine>)>,
    // Match each polyline to the index in paths
    closest_path_segment: FindClosest<usize>,
    stats: RouteStats,

    hover_on_line_plot: Option<(Distance, Drawable)>,
    hover_on_route_tooltip: Option<Text>,
    draw_route: ToggleZoomed,

    draw_high_stress: Drawable,
    draw_traffic_signals: Drawable,
    draw_unprotected_turns: Drawable,
}

struct RouteStats {
    total_distance: Distance,
    dist_along_high_stress_roads: Distance,
    total_time: Duration,
    num_traffic_signals: usize,
    num_unprotected_turns: usize,
    total_up: Distance,
    total_down: Distance,
}

impl RouteResults {
    pub fn main_route(
        ctx: &mut EventCtx,
        app: &App,
        waypoints: Vec<TripEndpoint>,
    ) -> (RouteResults, Widget) {
        RouteResults::new(
            ctx,
            app,
            waypoints,
            Color::CYAN,
            &app.session.routing_params,
        )
    }

    fn new(
        ctx: &mut EventCtx,
        app: &App,
        waypoints: Vec<TripEndpoint>,
        route_color: Color,
        params: &RoutingParams,
    ) -> (RouteResults, Widget) {
        let mut draw_route = ToggleZoomed::builder();
        let mut draw_high_stress = GeomBatch::new();
        let mut draw_traffic_signals = GeomBatch::new();
        let mut draw_unprotected_turns = GeomBatch::new();
        let map = &app.primary.map;

        let mut total_distance = Distance::ZERO;
        let mut total_time = Duration::ZERO;

        let mut dist_along_high_stress_roads = Distance::ZERO;
        let mut num_traffic_signals = 0;
        let mut num_unprotected_turns = 0;

        let mut elevation_pts: Vec<(Distance, Distance)> = Vec::new();
        let mut current_dist = Distance::ZERO;

        let mut paths = Vec::new();
        let mut closest_path_segment = FindClosest::new(map.get_bounds());

        for pair in waypoints.windows(2) {
            if let Some(path) = TripEndpoint::path_req(pair[0], pair[1], TripMode::Bike, map)
                .and_then(|req| map.pathfind_with_params(req, params).ok())
            {
                total_distance += path.total_length();
                total_time += path.estimate_duration(map, Some(map_model::MAX_BIKE_SPEED));

                for step in path.get_steps() {
                    let this_pl = step.as_traversable().get_polyline(map);
                    match step {
                        PathStep::Lane(l) | PathStep::ContraflowLane(l) => {
                            if map.get_parent(*l).high_stress_for_bikes(map) {
                                dist_along_high_stress_roads += this_pl.length();

                                // TODO It'd be nicer to build up contiguous subsets of the path
                                // that're stressful, and use trace
                                draw_high_stress.push(
                                    Color::RED,
                                    this_pl.make_polygons(5.0 * NORMAL_LANE_THICKNESS),
                                );
                            }
                        }
                        PathStep::Turn(t) => {
                            let i = map.get_i(t.parent);
                            elevation_pts.push((current_dist, i.elevation));
                            if i.is_traffic_signal() {
                                num_traffic_signals += 1;
                                draw_traffic_signals.push(Color::RED, i.polygon.clone());
                            }
                            if map.is_unprotected_turn(
                                t.src.road,
                                t.dst.road,
                                map.get_t(*t).turn_type,
                            ) {
                                num_unprotected_turns += 1;
                                draw_unprotected_turns.push(Color::RED, i.polygon.clone());
                            }
                        }
                    }
                    current_dist += this_pl.length();
                }

                let maybe_pl = path.trace(map);
                if let Some(ref pl) = maybe_pl {
                    let shape = pl.make_polygons(5.0 * NORMAL_LANE_THICKNESS);
                    draw_route
                        .unzoomed
                        .push(route_color.alpha(0.8), shape.clone());
                    draw_route.zoomed.push(route_color.alpha(0.5), shape);
                    closest_path_segment.add(paths.len(), pl.points());
                }
                paths.push((path, maybe_pl));
            }
        }

        let mut total_up = Distance::ZERO;
        let mut total_down = Distance::ZERO;
        for pair in elevation_pts.windows(2) {
            let dy = pair[1].1 - pair[0].1;
            if dy < Distance::ZERO {
                total_down -= dy;
            } else {
                total_up += dy;
            }
        }

        let stats = RouteStats {
            total_distance,
            dist_along_high_stress_roads,
            total_time,
            num_traffic_signals,
            num_unprotected_turns,
            total_up,
            total_down,
        };
        let elevation_plot = LinePlot::new_widget(
            ctx,
            "elevation",
            vec![Series {
                label: "Elevation".to_string(),
                color: Color::RED,
                pts: elevation_pts,
            }],
            PlotOptions {
                filterable: false,
                max_x: Some(current_dist.round_up_for_axis()),
                max_y: Some(map.max_elevation().round_up_for_axis()),
                disabled: HashSet::new(),
            },
            app.opts.units,
        );
        let widget = stats.to_widget(ctx, app, elevation_plot);

        (
            RouteResults {
                draw_route: draw_route.build(ctx),
                draw_high_stress: ctx.upload(draw_high_stress),
                draw_traffic_signals: ctx.upload(draw_traffic_signals),
                draw_unprotected_turns: ctx.upload(draw_unprotected_turns),
                paths,
                closest_path_segment,
                hover_on_line_plot: None,
                hover_on_route_tooltip: None,
                stats,
            },
            widget,
        )
    }

    pub fn event(
        &mut self,
        ctx: &mut EventCtx,
        app: &App,
        outcome: &Outcome,
        panel: &mut Panel,
    ) -> Option<Transition> {
        if let Outcome::Clicked(x) = outcome {
            match x.as_ref() {
                "high-stress roads" => {
                    return Some(Transition::Push(PopupMsg::new_state(
                        ctx,
                        "High-stress roads",
                        vec![
                            "Roads are defined as high-stress for biking if:",
                            "- they're classified as arterials",
                            "- they lack dedicated space for biking",
                        ],
                    )));
                }
                // No effect. Maybe these should be toggles, so people can pan the map around and
                // see these in more detail?
                "traffic signals" | "unprotected turns" => {
                    return Some(Transition::Keep);
                }
                _ => {
                    return None;
                }
            }
        }

        let current_dist_along = panel
            .find::<LinePlot<Distance, Distance>>("elevation")
            .get_hovering()
            .get(0)
            .map(|pair| pair.0);
        if self.hover_on_line_plot.as_ref().map(|pair| pair.0) != current_dist_along {
            self.hover_on_line_plot = current_dist_along.map(|mut dist| {
                let mut batch = GeomBatch::new();
                // Find this position on the route
                for (path, maybe_pl) in &self.paths {
                    if dist > path.total_length() {
                        dist -= path.total_length();
                        continue;
                    }
                    if let Some(ref pl) = maybe_pl {
                        if let Ok((pt, _)) = pl.dist_along(dist) {
                            batch.push(
                                Color::CYAN,
                                Circle::new(pt, Distance::meters(30.0)).to_polygon(),
                            );
                        }
                    }
                    break;
                }

                (dist, batch.upload(ctx))
            });
        }

        if ctx.redo_mouseover() {
            self.hover_on_route_tooltip = None;
            if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
                if let Some((idx, pt)) = self
                    .closest_path_segment
                    .closest_pt(pt, 10.0 * NORMAL_LANE_THICKNESS)
                {
                    // Find the total distance along the route
                    let mut dist = Distance::ZERO;
                    for (path, _) in &self.paths[0..idx] {
                        dist += path.total_length();
                    }
                    if let Some(ref pl) = self.paths[idx].1 {
                        if let Some((dist_here, _)) = pl.dist_along_of_point(pt) {
                            // The LinePlot doesn't hold onto the original Series, so it can't help
                            // us figure out elevation here. Let's match this point to the original
                            // path and guess elevation ourselves...
                            let map = &app.primary.map;
                            let elevation = match self.paths[idx]
                                .0
                                .get_step_at_dist_along(map, dist_here)
                                // We often seem to slightly exceed the total length, so just clamp
                                // here...
                                .unwrap_or_else(|_| self.paths[idx].0.last_step())
                            {
                                PathStep::Lane(l) | PathStep::ContraflowLane(l) => {
                                    // TODO Interpolate
                                    map.get_i(map.get_l(l).src_i).elevation
                                }
                                PathStep::Turn(t) => map.get_i(t.parent).elevation,
                            };
                            panel
                                .find_mut::<LinePlot<Distance, Distance>>("elevation")
                                .set_hovering(ctx, dist + dist_here, elevation);
                            self.hover_on_route_tooltip = Some(Text::from(Line(format!(
                                "Elevation: {}",
                                elevation.to_string(&app.opts.units)
                            ))));
                        }
                    }
                }
            }
        }

        None
    }

    pub fn draw(&self, g: &mut GfxCtx, app: &App, panel: &Panel) {
        self.draw_route.draw(g, app);
        if let Some((_, ref draw)) = self.hover_on_line_plot {
            g.redraw(draw);
        }
        if let Some(ref txt) = self.hover_on_route_tooltip {
            g.draw_mouse_tooltip(txt.clone());
        }
        if panel.currently_hovering() == Some(&"high-stress roads".to_string()) {
            g.redraw(&self.draw_high_stress);
        }
        if panel.currently_hovering() == Some(&"traffic signals".to_string()) {
            g.redraw(&self.draw_traffic_signals);
        }
        if panel.currently_hovering() == Some(&"unprotected turns".to_string()) {
            g.redraw(&self.draw_unprotected_turns);
        }
    }
}

impl RouteStats {
    fn to_widget(&self, ctx: &mut EventCtx, app: &App, elevation_plot: Widget) -> Widget {
        let pct_stressful = if self.total_distance == Distance::ZERO {
            0.0
        } else {
            ((self.dist_along_high_stress_roads / self.total_distance) * 100.0).round()
        };

        Widget::col(vec![
            Line("Route details").small_heading().into_widget(ctx),
            Text::from_all(vec![
                Line("Distance: ").secondary(),
                Line(self.total_distance.to_string(&app.opts.units)),
            ])
            .into_widget(ctx),
            Widget::row(vec![
                Text::from_all(vec![
                    Line(format!(
                        "  {} or {}%",
                        self.dist_along_high_stress_roads.to_string(&app.opts.units),
                        pct_stressful
                    )),
                    Line(" along ").secondary(),
                ])
                .into_widget(ctx)
                .centered_vert(),
                ctx.style()
                    .btn_plain
                    .btn()
                    .label_underlined_text("high-stress roads")
                    .build_def(ctx),
            ]),
            Text::from_all(vec![
                Line("Estimated time: ").secondary(),
                Line(self.total_time.to_string(&app.opts.units)),
            ])
            .into_widget(ctx),
            Widget::row(vec![
                Line("Traffic signals crossed: ")
                    .secondary()
                    .into_widget(ctx)
                    .centered_vert(),
                ctx.style()
                    .btn_plain
                    .btn()
                    .label_underlined_text(self.num_traffic_signals.to_string())
                    .build_widget(ctx, "traffic signals"),
            ]),
            Widget::row(vec![
                Line("Unprotected left turns onto busy roads: ")
                    .secondary()
                    .into_widget(ctx)
                    .centered_vert(),
                ctx.style()
                    .btn_plain
                    .btn()
                    .label_underlined_text(self.num_unprotected_turns.to_string())
                    .build_widget(ctx, "unprotected turns"),
            ]),
            Text::from_all(vec![
                Line("Elevation change: ").secondary(),
                Line(format!(
                    "{}↑, {}↓",
                    self.total_up.to_string(&app.opts.units),
                    self.total_down.to_string(&app.opts.units)
                )),
            ])
            .into_widget(ctx),
            elevation_plot,
        ])
    }
}

pub struct AltRouteResults {
    closest_path_segment: FindClosest<usize>,
    stats: RouteStats,
    hovering: bool,
    draw_route: ToggleZoomed,
    tooltip: Text,
}

impl AltRouteResults {
    pub fn low_stress(
        ctx: &mut EventCtx,
        app: &App,
        waypoints: Vec<TripEndpoint>,
    ) -> AltRouteResults {
        let (results, _) = RouteResults::new(
            ctx,
            app,
            waypoints,
            Color::grey(0.3),
            &RoutingParams {
                avoid_high_stress: 2.0,
                ..Default::default()
            },
        );
        AltRouteResults {
            closest_path_segment: results.closest_path_segment,
            stats: results.stats,
            hovering: false,
            draw_route: results.draw_route,
            tooltip: Text::new(),
        }
    }

    pub fn compare_to_main_route(&mut self, app: &App, main: &RouteResults) {
        let mut txt = Text::new();
        txt.add_line(Line("Click to use low-stress route"));

        cmp_dist(
            &mut txt,
            app,
            self.stats.total_distance - main.stats.total_distance,
            "shorter",
            "longer",
        );
        cmp_duration(
            &mut txt,
            app,
            self.stats.total_time - main.stats.total_time,
            "shorter",
            "longer",
        );
        cmp_dist(
            &mut txt,
            app,
            self.stats.dist_along_high_stress_roads - main.stats.dist_along_high_stress_roads,
            "less on high-stress roads",
            "more on high-stress roads",
        );

        if self.stats.total_up != main.stats.total_up
            || self.stats.total_down != main.stats.total_down
        {
            txt.add_line(Line("Elevation change: "));
            let up = self.stats.total_up - main.stats.total_up;
            if up < Distance::ZERO {
                txt.append(
                    Line(format!("{} less ↑", (-up).to_string(&app.opts.units))).fg(Color::GREEN),
                );
                txt.append(Line(", "));
            } else if up > Distance::ZERO {
                txt.append(
                    Line(format!("{} more ↑", up.to_string(&app.opts.units))).fg(Color::RED),
                );
                txt.append(Line(", "));
            }

            // Unclear if more down should be "good" or "bad", so we'll omit color
            let down = self.stats.total_down - main.stats.total_down;
            if down < Distance::ZERO {
                txt.append(Line(format!(
                    "{} less ↓",
                    (-down).to_string(&app.opts.units)
                )));
            } else if down > Distance::ZERO {
                txt.append(Line(format!("{} more ↓", down.to_string(&app.opts.units))));
            }
        }

        self.tooltip = txt;
    }

    pub fn event(&mut self, ctx: &mut EventCtx) {
        if ctx.redo_mouseover() {
            self.hovering = false;
            if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
                if self
                    .closest_path_segment
                    .closest_pt(pt, 10.0 * NORMAL_LANE_THICKNESS)
                    .is_some()
                {
                    self.hovering = true;
                }
            }
        }
    }

    pub fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.draw_route.draw(g, app);

        if self.hovering {
            g.draw_mouse_tooltip(self.tooltip.clone());
        }
    }
}

fn cmp_dist(txt: &mut Text, app: &App, dist: Distance, shorter: &str, longer: &str) {
    if dist < Distance::ZERO {
        txt.add_line(
            Line(format!(
                "{} {}",
                (-dist).to_string(&app.opts.units),
                shorter
            ))
            .fg(Color::GREEN),
        );
    } else if dist > Distance::ZERO {
        txt.add_line(
            Line(format!("{} {}", dist.to_string(&app.opts.units), longer)).fg(Color::RED),
        );
    }
}

fn cmp_duration(txt: &mut Text, app: &App, duration: Duration, shorter: &str, longer: &str) {
    if duration < Duration::ZERO {
        txt.add_line(
            Line(format!(
                "{} {}",
                (-duration).to_string(&app.opts.units),
                shorter
            ))
            .fg(Color::GREEN),
        );
    } else if duration > Duration::ZERO {
        txt.add_line(
            Line(format!(
                "{} {}",
                duration.to_string(&app.opts.units),
                longer
            ))
            .fg(Color::RED),
        );
    }
}