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
use geom::{Angle, ArrowCap, Distance, PolyLine};
use widgetry::mapspace::{ToggleZoomed, World};
use widgetry::{
    Color, DrawBaselayer, EventCtx, GeomBatch, GfxCtx, Key, Outcome, Panel, State, TextExt, Toggle,
    Widget,
};

use super::auto::Heuristic;
use super::per_neighborhood::{FilterableObj, Tab};
use super::{Neighborhood, NeighborhoodID};
use crate::{App, Transition};

pub struct Viewer {
    panel: Panel,
    neighborhood: Neighborhood,
    world: World<FilterableObj>,
    draw_top_layer: ToggleZoomed,
}

impl Viewer {
    pub fn new_state(ctx: &mut EventCtx, app: &App, id: NeighborhoodID) -> Box<dyn State<App>> {
        let neighborhood = Neighborhood::new(ctx, app, id);

        let mut viewer = Viewer {
            panel: Panel::empty(ctx),
            neighborhood,
            world: World::unbounded(),
            draw_top_layer: ToggleZoomed::empty(ctx),
        };
        viewer.update(ctx, app);
        Box::new(viewer)
    }

    fn update(&mut self, ctx: &mut EventCtx, app: &App) {
        let disconnected_cells = self
            .neighborhood
            .cells
            .iter()
            .filter(|c| c.is_disconnected())
            .count();
        let warning = if disconnected_cells == 0 {
            String::new()
        } else {
            format!("{} cells are totally disconnected", disconnected_cells)
        };

        self.panel = Tab::Connectivity
            .panel_builder(
                ctx,
                app,
                Widget::col(vec![
                    Widget::row(vec![
                        "Draw traffic cells as".text_widget(ctx).centered_vert(),
                        Toggle::choice(
                            ctx,
                            "draw cells",
                            "areas",
                            "streets",
                            Key::D,
                            app.session.draw_cells_as_areas,
                        ),
                    ]),
                    Widget::row(vec![
                        "Draw entrances/exits as".text_widget(ctx).centered_vert(),
                        Toggle::choice(
                            ctx,
                            "draw borders",
                            "arrows",
                            "outlines",
                            Key::E,
                            app.session.draw_borders_as_arrows,
                        ),
                    ]),
                    warning.text_widget(ctx),
                    Widget::row(vec![
                        Widget::dropdown(
                            ctx,
                            "heuristic",
                            app.session.heuristic,
                            Heuristic::choices(),
                        ),
                        ctx.style()
                            .btn_outline
                            .text("Automatically stop rat-runs")
                            .hotkey(Key::A)
                            .build_def(ctx),
                    ]),
                ]),
            )
            .build(ctx);

        let (world, draw_top_layer) = make_world(ctx, app, &self.neighborhood);
        self.world = world;
        self.draw_top_layer = draw_top_layer;
    }
}

impl State<App> for Viewer {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => {
                if x == "Automatically stop rat-runs" {
                    ctx.loading_screen("automatically filter a neighborhood", |ctx, timer| {
                        app.session
                            .heuristic
                            .apply(ctx, app, &self.neighborhood, timer);
                    });
                    self.neighborhood = Neighborhood::new(ctx, app, self.neighborhood.id);
                    self.update(ctx, app);
                    return Transition::Keep;
                }

                return Tab::Connectivity
                    .handle_action(ctx, app, x.as_ref(), self.neighborhood.id)
                    .unwrap();
            }
            Outcome::Changed(x) => {
                app.session.draw_cells_as_areas = self.panel.is_checked("draw cells");
                app.session.draw_borders_as_arrows = self.panel.is_checked("draw borders");
                app.session.heuristic = self.panel.dropdown_value("heuristic");

                if x != "heuristic" {
                    let (world, draw_top_layer) = make_world(ctx, app, &self.neighborhood);
                    self.world = world;
                    self.draw_top_layer = draw_top_layer;
                }
            }
            _ => {}
        }

        let world_outcome = self.world.event(ctx);
        if super::per_neighborhood::handle_world_outcome(ctx, app, world_outcome) {
            self.neighborhood = Neighborhood::new(ctx, app, self.neighborhood.id);
            self.update(ctx, app);
        }

        Transition::Keep
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::Custom
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        crate::draw_with_layering(g, app, |g| self.world.draw(g));
        g.redraw(&self.neighborhood.fade_irrelevant);
        self.draw_top_layer.draw(g);

        self.panel.draw(g);
        app.session.draw_all_filters.draw(g);
        // TODO Since we cover such a small area, treating multiple segments of one road as the
        // same might be nice. And we should seed the quadtree with the locations of filters and
        // arrows, possibly.
        if g.canvas.is_unzoomed() {
            self.neighborhood.labels.draw(g, app);
        }
    }
}

fn make_world(
    ctx: &mut EventCtx,
    app: &App,
    neighborhood: &Neighborhood,
) -> (World<FilterableObj>, ToggleZoomed) {
    let map = &app.map;
    let mut world = World::bounded(map.get_bounds());

    super::per_neighborhood::populate_world(ctx, app, neighborhood, &mut world, |id| id, 0);

    // The world is drawn in between areas and roads, but some things need to be drawn on top of
    // roads
    let mut draw_top_layer = GeomBatch::new();

    let render_cells = super::draw_cells::RenderCells::new(map, neighborhood);
    if app.session.draw_cells_as_areas {
        world.draw_master_batch(ctx, render_cells.draw());
    } else {
        for (idx, cell) in neighborhood.cells.iter().enumerate() {
            let color = render_cells.colors[idx].alpha(0.9);
            for (r, interval) in &cell.roads {
                let road = map.get_r(*r);
                draw_top_layer.push(
                    color,
                    road.center_pts
                        .exact_slice(interval.start, interval.end)
                        .make_polygons(road.get_width()),
                );
            }
            for i in
                map_gui::tools::intersections_from_roads(&cell.roads.keys().cloned().collect(), map)
            {
                draw_top_layer.push(color, map.get_i(i).polygon.clone());
            }
        }
    }

    // Draw the borders of each cell
    for (idx, cell) in neighborhood.cells.iter().enumerate() {
        let color = render_cells.colors[idx];
        for i in &cell.borders {
            let angles: Vec<Angle> = cell
                .roads
                .keys()
                .filter_map(|r| {
                    let road = map.get_r(*r);
                    // Design choice: when we have a filter right at the entrance of a
                    // neighborhood, it creates its own little cell allowing access to just the
                    // very beginning of the road. Let's not draw anything for that.
                    if app.session.modal_filters.roads.contains_key(r) {
                        None
                    } else if road.src_i == *i {
                        Some(road.center_pts.first_line().angle())
                    } else if road.dst_i == *i {
                        Some(road.center_pts.last_line().angle().opposite())
                    } else {
                        None
                    }
                })
                .collect();
            // Tiny cell with a filter right at the border
            if angles.is_empty() {
                continue;
            }

            if app.session.draw_borders_as_arrows {
                let center = map.get_i(*i).polygon.center();
                let angle = Angle::average(angles);

                // TODO Consider showing borders with one-way roads. For now, always point the
                // arrow into the neighborhood
                draw_top_layer.push(
                    color.alpha(0.8),
                    PolyLine::must_new(vec![
                        center.project_away(Distance::meters(30.0), angle.opposite()),
                        center.project_away(Distance::meters(10.0), angle.opposite()),
                    ])
                    .make_arrow(Distance::meters(6.0), ArrowCap::Triangle),
                );
            } else if let Ok(p) = map.get_i(*i).polygon.to_outline(Distance::meters(2.0)) {
                draw_top_layer.push(color, p);
            }
        }
    }

    let mut top_layer = ToggleZoomed::builder();
    top_layer.unzoomed = draw_top_layer.clone();
    top_layer.zoomed = draw_top_layer.clone();

    // Draw one-way arrows
    for r in neighborhood
        .orig_perimeter
        .interior
        .iter()
        .chain(neighborhood.orig_perimeter.roads.iter().map(|id| &id.road))
    {
        let road = map.get_r(*r);
        if road.osm_tags.is("oneway", "yes") {
            let arrow_len = Distance::meters(10.0);
            let thickness = Distance::meters(1.0);
            for (pt, angle) in road
                .center_pts
                .step_along(Distance::meters(30.0), Distance::meters(5.0))
            {
                if let Ok(poly) = PolyLine::must_new(vec![
                    pt.project_away(arrow_len / 2.0, angle.opposite()),
                    pt.project_away(arrow_len / 2.0, angle),
                ])
                .make_arrow(thickness * 2.0, ArrowCap::Triangle)
                .to_outline(thickness / 2.0)
                {
                    top_layer.unzoomed.push(Color::BLACK, poly);
                }
            }
        }
    }

    world.initialize_hover(ctx);

    (world, top_layer.build(ctx))
}