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
use std::collections::BTreeSet;

use maplit::btreeset;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;

use geom::Duration;
use map_gui::tools::{grey_out_map, nice_map_name};
use map_model::AreaType;
use sim::{AgentType, PersonID, TripID};
use synthpop::TripEndpoint;
use widgetry::tools::{open_browser, PopupMsg};
use widgetry::{
    lctrl, ControlState, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel,
    SimpleState, Text, TextExt, Toggle, VerticalAlignment, Widget,
};

use crate::app::{App, Transition};
use crate::common::jump_to_time_upon_startup;
use crate::edit::EditMode;
use crate::info::{OpenTrip, Tab};
use crate::sandbox::gameplay::{GameplayMode, GameplayState};
use crate::sandbox::{Actions, SandboxControls, SandboxMode, SpeedSetting};

/// A gameplay mode with specific controls for integration with
/// https://cyipt.github.io/acton/articles/the-actdev-project.html.
pub struct Actdev {
    top_right: Panel,
    scenario_name: String,
    bg_traffic: bool,
    once: bool,
}

impl Actdev {
    pub fn new_state(
        ctx: &mut EventCtx,
        scenario_name: String,
        bg_traffic: bool,
    ) -> Box<dyn GameplayState> {
        Box::new(Actdev {
            top_right: Panel::empty(ctx),
            scenario_name,
            bg_traffic,
            once: true,
        })
    }
}

impl GameplayState for Actdev {
    fn event(
        &mut self,
        ctx: &mut EventCtx,
        app: &mut App,
        controls: &mut SandboxControls,
        actions: &mut Actions,
    ) -> Option<Transition> {
        if self.once {
            self.once = false;

            if self.bg_traffic {
                let mut highlight = BTreeSet::new();
                let study_area = &app
                    .primary
                    .map
                    .all_areas()
                    .iter()
                    .find(|a| a.area_type == AreaType::StudyArea)
                    .unwrap()
                    .polygon;

                for person in app.primary.sim.get_all_people() {
                    if let TripEndpoint::Building(b) =
                        app.primary.sim.trip_info(person.trips[0]).start
                    {
                        if study_area.contains_pt(app.primary.map.get_b(b).polygon.center()) {
                            highlight.insert(person.id);
                        }
                    }
                }
                app.primary.sim.set_highlighted_people(highlight);
            }

            // The top-right panel never changes height, so we can set this just once.
            controls.time_panel.as_mut().unwrap().override_height =
                Some(self.top_right.panel_dims().height);

            controls
                .time_panel
                .as_mut()
                .unwrap()
                .resume(ctx, app, SpeedSetting::Faster);
        }

        match self.top_right.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "change scenario" => {
                    let scenario = if self.scenario_name == "base" {
                        "go_active"
                    } else {
                        "base"
                    };
                    return Some(Transition::Replace(SandboxMode::async_new(
                        app,
                        GameplayMode::Actdev(
                            app.primary.map.get_name().clone(),
                            scenario.to_string(),
                            self.bg_traffic,
                        ),
                        jump_to_time_upon_startup(Duration::hours(8)),
                    )));
                }
                "Edit map" => Some(Transition::Push(EditMode::new_state(
                    ctx,
                    app,
                    GameplayMode::Actdev(
                        app.primary.map.get_name().clone(),
                        self.scenario_name.clone(),
                        self.bg_traffic,
                    ),
                ))),
                "about A/B Street" => {
                    let panel = Panel::new_builder(Widget::col(vec![
                        Widget::row(vec![
                            Line("About A/B Street").small_heading().into_widget(ctx),
                            ctx.style().btn_close_widget(ctx),
                        ]),
                        Line("Created by Dustin Carlino, Yuwen Li, & Michael Kirk")
                            .small()
                            .into_widget(ctx),
                        Text::from(
                            "A/B Street is a traffic simulation game based on OpenStreetMap. You \
                             can modify roads and intersections, measure the effects on different \
                             groups, and advocate for your proposal.",
                        )
                        .wrap_to_pct(ctx, 50)
                        .into_widget(ctx),
                        "This is a simplified version. Check out the full version below."
                            .text_widget(ctx),
                        ctx.style().btn_outline.text("abstreet.org").build_def(ctx),
                    ]))
                    .build(ctx);
                    Some(Transition::Push(<dyn SimpleState<_>>::new_state(
                        panel,
                        Box::new(About),
                    )))
                }
                "Follow someone" => {
                    if let Some((person, trip)) = find_active_trip(app) {
                        // The user may not realize they have to close layers; do it for them.
                        app.primary.layer = None;
                        ctx.canvas.cam_zoom = 40.0;
                        controls.common.as_mut().unwrap().launch_info_panel(
                            ctx,
                            app,
                            Tab::PersonTrips(person, OpenTrip::single(trip)),
                            actions,
                        );
                        None
                    } else {
                        return Some(Transition::Push(PopupMsg::new_state(
                            ctx,
                            "Nobody's around...",
                            vec!["There are no active trips right now"],
                        )));
                    }
                }
                "Cycling" => {
                    app.primary.layer =
                        Some(Box::new(crate::layer::map::BikeActivity::new(ctx, app)));
                    None
                }
                "Walking" => {
                    app.primary.layer = Some(Box::new(crate::layer::traffic::Throughput::new(
                        ctx,
                        app,
                        btreeset! { AgentType::Pedestrian },
                    )));
                    None
                }
                _ => unreachable!(),
            },
            Outcome::Changed(_) => {
                // Background traffic was toggled
                return Some(Transition::Replace(SandboxMode::async_new(
                    app,
                    GameplayMode::Actdev(
                        app.primary.map.get_name().clone(),
                        self.scenario_name.clone(),
                        !self.bg_traffic,
                    ),
                    jump_to_time_upon_startup(Duration::hours(8)),
                )));
            }
            _ => None,
        }
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        self.top_right.draw(g);
    }

    fn recreate_panels(&mut self, ctx: &mut EventCtx, app: &App) {
        let col = Widget::col(vec![
            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"),
                Line(nice_map_name(app.primary.map.get_name()))
                    .small_heading()
                    .into_widget(ctx),
                ctx.style()
                    .btn_outline
                    .icon_text("system/assets/tools/pencil.svg", "Edit map")
                    .hotkey(lctrl(Key::E))
                    .build_def(ctx),
            ])
            .centered(),
            Widget::row(vec![
                ctx.style()
                    .btn_popup_icon_text("system/assets/tools/calendar.svg", "scenario")
                    .label_styled_text(
                        match self.scenario_name.as_ref() {
                            "base" => Text::from_all(vec![
                                Line("Baseline / "),
                                Line("Go Active").secondary(),
                            ]),
                            "go_active" => Text::from_all(vec![
                                Line("Baseline").secondary(),
                                Line(" / Go Active"),
                            ]),
                            _ => unreachable!(),
                        },
                        ControlState::Default,
                    )
                    .build_widget(ctx, "change scenario"),
                Toggle::checkbox(ctx, "background traffic", None, self.bg_traffic),
            ]),
            Widget::row(vec![
                ctx.style()
                    .btn_plain
                    .icon_text("system/assets/tools/location.svg", "Follow someone")
                    .build_def(ctx),
                ctx.style()
                    .btn_plain
                    .icon_text("system/assets/meters/pedestrian.svg", "Walking")
                    .build_def(ctx),
                ctx.style()
                    .btn_plain
                    .icon_text("system/assets/meters/bike.svg", "Cycling")
                    .build_def(ctx),
            ]),
        ]);

        self.top_right = Panel::new_builder(col)
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx);
    }

    fn has_tool_panel(&self) -> bool {
        // Get rid of the home button, which would allow escaping to the title screen
        false
    }
}

struct About;

impl SimpleState<App> for About {
    fn on_click(&mut self, _: &mut EventCtx, _: &mut App, x: &str, _: &mut Panel) -> Transition {
        if x == "close" {
            return Transition::Pop;
        } else if x == "abstreet.org" {
            open_browser("https://abstreet.org");
        }
        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        grey_out_map(g, app);
    }
}

fn find_active_trip(app: &App) -> Option<(PersonID, TripID)> {
    let mut all = Vec::new();
    for agent in app.primary.sim.active_agents() {
        if let Some(trip) = app.primary.sim.agent_to_trip(agent) {
            if let Some(person) = app.primary.sim.trip_to_person(trip) {
                all.push((person, trip));
            }
        }
    }
    all.choose(&mut XorShiftRng::from_entropy()).cloned()
}