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
// TODO I've considered moving this out of map_gui completely, to remove all dependencies on the
// sim crate. If that's desirable, get_obj in DrawMap is the only dependency.

use std::borrow::Borrow;
use std::collections::HashMap;

use aabb_quadtree::QuadTree;

use geom::{Circle, Pt2D, Time};
use map_model::{Map, Traversable};
use sim::{AgentID, Sim, UnzoomedAgent, VehicleType};
use widgetry::{Color, Drawable, GeomBatch, GfxCtx, Panel, Prerender};

use crate::colors::ColorScheme;
use crate::options::Options;
use crate::render::{
    draw_vehicle, unzoomed_agent_radius, DrawPedCrowd, DrawPedestrian, Renderable,
};

pub struct AgentCache {
    /// This is controlled almost entirely by the minimap panel. It has no meaning in edit mode.
    pub unzoomed_agents: UnzoomedAgents,

    // This time applies to agents_per_on. unzoomed has its own possibly separate Time!
    time: Option<Time>,
    agents_per_on: HashMap<Traversable, Vec<Box<dyn Renderable>>>,
    // when either of (time, unzoomed agent filters) change, recalculate (a quadtree of all agents,
    // draw all agents)
    unzoomed: Option<(Time, UnzoomedAgents, QuadTree<AgentID>, Drawable)>,
}

impl AgentCache {
    pub fn new() -> AgentCache {
        AgentCache {
            unzoomed_agents: UnzoomedAgents::new(),
            time: None,
            agents_per_on: HashMap::new(),
            unzoomed: None,
        }
    }

    pub fn get(&self, on: Traversable) -> Vec<&dyn Renderable> {
        self.agents_per_on[&on]
            .iter()
            .map(|obj| obj.borrow())
            .collect()
    }

    pub fn populate_if_needed(
        &mut self,
        on: Traversable,
        map: &Map,
        sim: &Sim,
        cs: &ColorScheme,
        prerender: &Prerender,
    ) {
        let now = sim.time();
        if Some(now) == self.time && self.agents_per_on.contains_key(&on) {
            return;
        }
        let step_count = sim.step_count();

        let mut list: Vec<Box<dyn Renderable>> = Vec::new();
        for c in sim.get_draw_cars(on, map).into_iter() {
            list.push(draw_vehicle(c, map, sim, prerender, cs));
        }
        let (loners, crowds) = sim.get_draw_peds(on, map);
        for p in loners {
            list.push(Box::new(DrawPedestrian::new(
                p, step_count, map, sim, prerender, cs,
            )));
        }
        for c in crowds {
            list.push(Box::new(DrawPedCrowd::new(c, map, prerender, cs)));
        }

        if Some(now) != self.time {
            self.agents_per_on.clear();
            self.time = Some(now);
        }

        self.agents_per_on.insert(on, list);
    }

    /// If the sim time has changed or the unzoomed agent filters have been modified, recalculate
    /// the quadtree and drawable for all unzoomed agents.
    pub fn calculate_unzoomed_agents<P: AsRef<Prerender>>(
        &mut self,
        prerender: &mut P,
        map: &Map,
        sim: &Sim,
        cs: &ColorScheme,
    ) -> &QuadTree<AgentID> {
        let now = sim.time();
        let mut recalc = true;
        if let Some((time, ref orig_agents, _, _)) = self.unzoomed {
            if now == time && self.unzoomed_agents == orig_agents.clone() {
                recalc = false;
            }
        }

        if recalc {
            let highlighted = sim.get_highlighted_people();

            let mut batch = GeomBatch::new();
            let mut quadtree = QuadTree::default(map.get_bounds().as_bbox());
            // It's quite silly to produce triangles for the same circle over and over again. ;)
            let car_circle = Circle::new(
                Pt2D::new(0.0, 0.0),
                unzoomed_agent_radius(Some(VehicleType::Car)),
            )
            .to_polygon();
            let ped_circle =
                Circle::new(Pt2D::new(0.0, 0.0), unzoomed_agent_radius(None)).to_polygon();

            for agent in sim.get_unzoomed_agents(map) {
                if let Some(mut color) = self.unzoomed_agents.color(&agent, cs) {
                    // If the sim has highlighted people, then fade all others out.
                    if highlighted
                        .as_ref()
                        .and_then(|h| agent.person.as_ref().map(|p| !h.contains(p)))
                        .unwrap_or(false)
                    {
                        // TODO Tune. How's this look at night?
                        color = color.tint(0.5);
                    }

                    let circle = if agent.id.to_vehicle_type().is_some() {
                        car_circle.translate(agent.pos.x(), agent.pos.y())
                    } else {
                        ped_circle.translate(agent.pos.x(), agent.pos.y())
                    };
                    quadtree.insert_with_box(agent.id, circle.get_bounds().as_bbox());
                    batch.push(color, circle);
                }
            }

            let draw = prerender.as_ref().upload(batch);

            self.unzoomed = Some((now, self.unzoomed_agents.clone(), quadtree, draw));
        }

        &self.unzoomed.as_ref().unwrap().2
    }

    pub fn draw_unzoomed_agents(
        &mut self,
        g: &mut GfxCtx,
        map: &Map,
        sim: &Sim,
        cs: &ColorScheme,
        opts: &Options,
    ) {
        self.calculate_unzoomed_agents(g, map, sim, cs);
        g.redraw(&self.unzoomed.as_ref().unwrap().3);

        if opts.debug_all_agents {
            let mut cnt = 0;
            for input in sim.get_all_draw_cars(map) {
                cnt += 1;
                draw_vehicle(input, map, sim, g.prerender, cs);
            }
            println!(
                "At {}, debugged {} cars",
                sim.time(),
                abstutil::prettyprint_usize(cnt)
            );
            // Pedestrians aren't the ones crashing
        }
    }
}

#[derive(PartialEq, Clone)]
pub struct UnzoomedAgents {
    cars: bool,
    bikes: bool,
    buses_and_trains: bool,
    peds: bool,
}

impl UnzoomedAgents {
    pub fn new() -> UnzoomedAgents {
        UnzoomedAgents {
            cars: true,
            bikes: true,
            buses_and_trains: true,
            peds: true,
        }
    }

    pub fn cars(&self) -> bool {
        self.cars
    }
    pub fn bikes(&self) -> bool {
        self.bikes
    }
    pub fn buses_and_trains(&self) -> bool {
        self.buses_and_trains
    }
    pub fn peds(&self) -> bool {
        self.peds
    }

    fn color(&self, agent: &UnzoomedAgent, color_scheme: &ColorScheme) -> Option<Color> {
        match agent.id.to_vehicle_type() {
            Some(VehicleType::Car) => {
                if self.cars {
                    Some(color_scheme.unzoomed_car)
                } else {
                    None
                }
            }
            Some(VehicleType::Bike) => {
                if self.bikes {
                    Some(color_scheme.unzoomed_bike)
                } else {
                    None
                }
            }
            Some(VehicleType::Bus) | Some(VehicleType::Train) => {
                if self.buses_and_trains {
                    Some(color_scheme.unzoomed_bus)
                } else {
                    None
                }
            }
            None => {
                if self.peds {
                    Some(color_scheme.unzoomed_pedestrian)
                } else {
                    None
                }
            }
        }
    }

    pub fn update(&mut self, panel: &Panel) {
        self.cars = panel.is_checked("Car");
        self.bikes = panel.is_checked("Bike");
        self.buses_and_trains = panel.is_checked("Bus");
        self.peds = panel.is_checked("Walk");
    }
}