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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use crate::raw::{OriginalRoad, RawMap};
use crate::{
    osm, Area, AreaID, Building, BuildingID, BuildingType, BusRoute, BusRouteID, BusStop,
    BusStopID, ControlStopSign, ControlTrafficSignal, Intersection, IntersectionID, Lane, LaneID,
    LaneType, Map, MapEdits, MovementID, OffstreetParking, ParkingLot, ParkingLotID, Path,
    PathConstraints, PathRequest, Pathfinder, Position, Road, RoadID, Turn, TurnID, TurnType, Zone,
};
use abstutil::Timer;
use geom::{Bounds, GPSBounds, Polygon, Pt2D, Ring, Time};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MapConfig {
    // If true, driving happens on the right side of the road (USA). If false, on the left
    // (Australia).
    pub driving_side: DrivingSide,
    pub bikes_can_use_bus_lanes: bool,
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
pub enum DrivingSide {
    Right,
    Left,
}

impl Map {
    pub fn new(path: String, timer: &mut Timer) -> Map {
        if path.starts_with(&abstutil::path_all_maps()) {
            match abstutil::maybe_read_binary(path.clone(), timer) {
                Ok(map) => {
                    let mut map: Map = map;
                    map.edits = map.new_edits();

                    if false {
                        use abstutil::{prettyprint_usize, serialized_size_bytes};
                        println!(
                            "Total map size: {} bytes",
                            prettyprint_usize(serialized_size_bytes(&map))
                        );
                        println!(
                            "- {} roads: {} bytes",
                            prettyprint_usize(map.roads.len()),
                            prettyprint_usize(serialized_size_bytes(&map.roads))
                        );
                        println!(
                            "- {} lanes: {} bytes",
                            prettyprint_usize(map.lanes.len()),
                            prettyprint_usize(serialized_size_bytes(&map.lanes))
                        );
                        println!(
                            "- {} intersections: {} bytes",
                            prettyprint_usize(map.intersections.len()),
                            prettyprint_usize(serialized_size_bytes(&map.intersections))
                        );
                        println!(
                            "- {} turns: {} bytes",
                            prettyprint_usize(map.turns.len()),
                            prettyprint_usize(serialized_size_bytes(&map.turns))
                        );
                        println!(
                            "- {} buildings: {} bytes",
                            prettyprint_usize(map.buildings.len()),
                            prettyprint_usize(serialized_size_bytes(&map.buildings))
                        );
                        println!(
                            "- {} areas: {} bytes",
                            prettyprint_usize(map.areas.len()),
                            prettyprint_usize(serialized_size_bytes(&map.areas))
                        );
                        println!(
                            "- {} parking lots: {} bytes",
                            prettyprint_usize(map.parking_lots.len()),
                            prettyprint_usize(serialized_size_bytes(&map.parking_lots))
                        );
                        println!(
                            "- {} zones: {} bytes",
                            prettyprint_usize(map.zones.len()),
                            prettyprint_usize(serialized_size_bytes(&map.zones))
                        );
                        // This is the partridge in the pear tree, I suppose
                        println!(
                            "- pathfinder: {} bytes",
                            prettyprint_usize(serialized_size_bytes(&map.pathfinder))
                        );
                    }

                    return map;
                }
                Err(err) => {
                    Map::corrupt_err(path, err);
                    std::process::exit(1);
                }
            }
        }

        let raw: RawMap = if path.starts_with(&abstutil::path_all_raw_maps()) {
            abstutil::read_binary(path, timer)
        } else {
            // Synthetic
            abstutil::read_json(path, timer)
        };
        Map::create_from_raw(raw, true, timer)
    }

    pub fn corrupt_err(path: String, err: std::io::Error) {
        println!("\nError loading {}: {}\n", path, err);
        if err.to_string().contains("No such file") {
            println!(
                "{} is missing. You may need to do: cargo run --bin updater",
                path
            );
        } else {
            println!(
                "{} is out-of-date. You may need to update your build (git pull) or download new \
                 data (cargo run --bin updater). If this is a custom map, you need to import it \
                 again.",
                path
            );
        }
        println!(
            "Check https://dabreegster.github.io/abstreet/dev/index.html and file an issue if you \
             have trouble."
        );
    }

    // Just for temporary std::mem::replace tricks.
    pub fn blank() -> Map {
        Map {
            roads: Vec::new(),
            lanes: Vec::new(),
            intersections: Vec::new(),
            turns: BTreeMap::new(),
            buildings: Vec::new(),
            bus_stops: BTreeMap::new(),
            bus_routes: Vec::new(),
            areas: Vec::new(),
            parking_lots: Vec::new(),
            zones: Vec::new(),
            boundary_polygon: Ring::must_new(vec![
                Pt2D::new(0.0, 0.0),
                Pt2D::new(1.0, 0.0),
                Pt2D::new(1.0, 1.0),
                Pt2D::new(0.0, 0.0),
            ])
            .to_polygon(),
            stop_signs: BTreeMap::new(),
            traffic_signals: BTreeMap::new(),
            gps_bounds: GPSBounds::new(),
            bounds: Bounds::new(),
            config: MapConfig {
                driving_side: DrivingSide::Right,
                bikes_can_use_bus_lanes: true,
            },
            pathfinder: Pathfinder::Dijkstra,
            pathfinder_dirty: false,
            city_name: "blank city".to_string(),
            name: "blank".to_string(),
            edits: MapEdits::new(),
        }
    }

    pub fn all_roads(&self) -> &Vec<Road> {
        &self.roads
    }

    pub fn all_lanes(&self) -> &Vec<Lane> {
        &self.lanes
    }

    pub fn all_intersections(&self) -> &Vec<Intersection> {
        &self.intersections
    }

    pub fn all_turns(&self) -> &BTreeMap<TurnID, Turn> {
        &self.turns
    }

    pub fn all_buildings(&self) -> &Vec<Building> {
        &self.buildings
    }

    pub fn all_areas(&self) -> &Vec<Area> {
        &self.areas
    }

    pub fn all_parking_lots(&self) -> &Vec<ParkingLot> {
        &self.parking_lots
    }

    pub fn all_zones(&self) -> &Vec<Zone> {
        &self.zones
    }

    pub fn maybe_get_r(&self, id: RoadID) -> Option<&Road> {
        self.roads.get(id.0)
    }

    pub fn maybe_get_l(&self, id: LaneID) -> Option<&Lane> {
        self.lanes.get(id.0)
    }

    pub fn maybe_get_i(&self, id: IntersectionID) -> Option<&Intersection> {
        self.intersections.get(id.0)
    }

    pub fn maybe_get_t(&self, id: TurnID) -> Option<&Turn> {
        self.turns.get(&id)
    }

    pub fn maybe_get_b(&self, id: BuildingID) -> Option<&Building> {
        self.buildings.get(id.0)
    }

    pub fn maybe_get_pl(&self, id: ParkingLotID) -> Option<&ParkingLot> {
        self.parking_lots.get(id.0)
    }

    pub fn maybe_get_a(&self, id: AreaID) -> Option<&Area> {
        self.areas.get(id.0)
    }

    pub fn maybe_get_bs(&self, id: BusStopID) -> Option<&BusStop> {
        self.bus_stops.get(&id)
    }

    pub fn maybe_get_stop_sign(&self, id: IntersectionID) -> Option<&ControlStopSign> {
        self.stop_signs.get(&id)
    }

    pub fn maybe_get_traffic_signal(&self, id: IntersectionID) -> Option<&ControlTrafficSignal> {
        self.traffic_signals.get(&id)
    }

    pub fn maybe_get_br(&self, route: BusRouteID) -> Option<&BusRoute> {
        self.bus_routes.get(route.0)
    }

    pub fn get_r(&self, id: RoadID) -> &Road {
        &self.roads[id.0]
    }

    pub fn get_l(&self, id: LaneID) -> &Lane {
        &self.lanes[id.0]
    }

    pub fn get_i(&self, id: IntersectionID) -> &Intersection {
        &self.intersections[id.0]
    }

    pub fn get_t(&self, id: TurnID) -> &Turn {
        // When pathfinding breaks, seeing this TurnID is useful.
        if let Some(ref t) = self.turns.get(&id) {
            t
        } else {
            panic!("Can't get_t({})", id);
        }
    }

    pub fn get_b(&self, id: BuildingID) -> &Building {
        &self.buildings[id.0]
    }

    pub fn get_a(&self, id: AreaID) -> &Area {
        &self.areas[id.0]
    }

    pub fn get_pl(&self, id: ParkingLotID) -> &ParkingLot {
        &self.parking_lots[id.0]
    }

    pub fn get_stop_sign(&self, id: IntersectionID) -> &ControlStopSign {
        &self.stop_signs[&id]
    }

    pub fn get_traffic_signal(&self, id: IntersectionID) -> &ControlTrafficSignal {
        &self.traffic_signals[&id]
    }

    // All these helpers should take IDs and return objects.

    pub fn get_turns_in_intersection<'a>(
        &'a self,
        id: IntersectionID,
    ) -> impl Iterator<Item = &'a Turn> + 'a {
        self.get_i(id).turns.iter().map(move |t| self.get_t(*t))
    }

    // The turns may belong to two different intersections!
    pub fn get_turns_from_lane(&self, l: LaneID) -> Vec<&Turn> {
        let lane = self.get_l(l);
        let mut turns: Vec<&Turn> = self
            .get_i(lane.dst_i)
            .turns
            .iter()
            .map(|t| self.get_t(*t))
            .filter(|t| t.id.src == l)
            .collect();
        // Sidewalks/shoulders are bidirectional
        if lane.is_walkable() {
            for t in &self.get_i(lane.src_i).turns {
                if t.src == l {
                    turns.push(self.get_t(*t));
                }
            }
        }
        turns
    }

    pub fn get_turns_to_lane(&self, l: LaneID) -> Vec<&Turn> {
        let lane = self.get_l(l);
        let mut turns: Vec<&Turn> = self
            .get_i(lane.src_i)
            .turns
            .iter()
            .map(|t| self.get_t(*t))
            .filter(|t| t.id.dst == l)
            .collect();
        // Sidewalks/shoulders are bidirectional
        if lane.is_walkable() {
            for t in &self.get_i(lane.dst_i).turns {
                if t.dst == l {
                    turns.push(self.get_t(*t));
                }
            }
        }
        turns
    }

    pub fn get_turn_between(
        &self,
        from: LaneID,
        to: LaneID,
        parent: IntersectionID,
    ) -> Option<TurnID> {
        self.get_i(parent)
            .turns
            .iter()
            .find(|t| t.src == from && t.dst == to)
            .cloned()
    }

    pub fn get_next_turns_and_lanes<'a>(
        &'a self,
        from: LaneID,
        parent: IntersectionID,
    ) -> impl Iterator<Item = (&'a Turn, &'a Lane)> + 'a {
        self.get_i(parent)
            .turns
            .iter()
            .filter(move |t| t.src == from)
            .map(move |t| (self.get_t(*t), self.get_l(t.dst)))
    }

    pub fn get_turns_for(&self, from: LaneID, constraints: PathConstraints) -> Vec<&Turn> {
        let mut turns: Vec<&Turn> = self
            .get_next_turns_and_lanes(from, self.get_l(from).dst_i)
            .into_iter()
            .filter(|(_, l)| constraints.can_use(l, self))
            .map(|(t, _)| t)
            .collect();
        // Sidewalks are bidirectional
        if constraints == PathConstraints::Pedestrian {
            turns.extend(
                self.get_next_turns_and_lanes(from, self.get_l(from).src_i)
                    .into_iter()
                    .filter(|(_, l)| constraints.can_use(l, self))
                    .map(|(t, _)| t),
            );
        }
        turns
    }

    // These come back sorted
    pub fn get_next_roads(&self, from: RoadID) -> impl Iterator<Item = RoadID> {
        let mut roads: BTreeSet<RoadID> = BTreeSet::new();

        let r = self.get_r(from);
        for id in vec![r.src_i, r.dst_i].into_iter() {
            roads.extend(self.get_i(id).roads.clone());
        }

        roads.into_iter()
    }

    pub fn get_parent(&self, id: LaneID) -> &Road {
        let l = self.get_l(id);
        self.get_r(l.parent)
    }

    pub fn get_gps_bounds(&self) -> &GPSBounds {
        &self.gps_bounds
    }

    pub fn get_bounds(&self) -> &Bounds {
        &self.bounds
    }

    pub fn get_city_name(&self) -> &String {
        &self.city_name
    }

    pub fn get_name(&self) -> &String {
        &self.name
    }

    pub fn all_bus_stops(&self) -> &BTreeMap<BusStopID, BusStop> {
        &self.bus_stops
    }

    pub fn get_bs(&self, stop: BusStopID) -> &BusStop {
        &self.bus_stops[&stop]
    }

    pub fn get_br(&self, route: BusRouteID) -> &BusRoute {
        &self.bus_routes[route.0]
    }

    pub fn all_bus_routes(&self) -> &Vec<BusRoute> {
        &self.bus_routes
    }

    pub fn get_bus_route(&self, name: &str) -> Option<&BusRoute> {
        self.bus_routes.iter().find(|r| r.full_name == name)
    }

    pub fn get_routes_serving_stop(&self, stop: BusStopID) -> Vec<&BusRoute> {
        let mut routes = Vec::new();
        for r in &self.bus_routes {
            if r.stops.contains(&stop) {
                routes.push(r);
            }
        }
        routes
    }

    pub fn building_to_road(&self, id: BuildingID) -> &Road {
        self.get_parent(self.get_b(id).sidewalk())
    }

    // This and all_outgoing_borders are expensive to constantly repeat
    pub fn all_incoming_borders(&self) -> Vec<&Intersection> {
        let mut result: Vec<&Intersection> = Vec::new();
        for i in &self.intersections {
            if i.is_incoming_border() {
                result.push(i);
            }
        }
        result
    }

    pub fn all_outgoing_borders(&self) -> Vec<&Intersection> {
        let mut result: Vec<&Intersection> = Vec::new();
        for i in &self.intersections {
            if i.is_outgoing_border() {
                result.push(i);
            }
        }
        result
    }

    pub fn save(&self) {
        assert!(self.edits.edits_name.starts_with("Untitled Proposal"));
        assert!(self.edits.commands.is_empty());
        assert!(!self.pathfinder_dirty);
        abstutil::write_binary(abstutil::path_map(&self.name), self);
    }

    // Cars trying to park near this building should head for the driving lane returned here, then
    // start their search. Some parking lanes are connected to driving lanes that're "parking
    // blackholes" -- if there are no free spots on that lane, then the roads force cars to a
    // border.
    // TODO Making driving_connection do this.
    pub fn find_driving_lane_near_building(&self, b: BuildingID) -> LaneID {
        let sidewalk = self.get_b(b).sidewalk();
        if let Some(l) = self.get_parent(sidewalk).find_closest_lane(
            sidewalk,
            |l| PathConstraints::Car.can_use(l, self),
            self,
        ) {
            if !self.get_l(l).driving_blackhole {
                return l;
            }
        }

        let mut roads_queue: VecDeque<RoadID> = VecDeque::new();
        let mut visited: HashSet<RoadID> = HashSet::new();
        {
            let start = self.building_to_road(b).id;
            roads_queue.push_back(start);
            visited.insert(start);
        }

        loop {
            if roads_queue.is_empty() {
                panic!(
                    "Giving up looking for a driving lane near {}, searched {} roads: {:?}",
                    b,
                    visited.len(),
                    visited
                );
            }
            let r = self.get_r(roads_queue.pop_front().unwrap());

            for (l, lt) in r
                .children_forwards()
                .into_iter()
                .chain(r.children_backwards().into_iter())
            {
                if lt == LaneType::Driving {
                    if !self.get_l(l).driving_blackhole {
                        return l;
                    }
                }
            }

            for next_r in self.get_next_roads(r.id).into_iter() {
                if !visited.contains(&next_r) {
                    roads_queue.push_back(next_r);
                    visited.insert(next_r);
                }
            }
        }
    }

    pub fn get_boundary_polygon(&self) -> &Polygon {
        &self.boundary_polygon
    }

    pub fn pathfind(&self, req: PathRequest) -> Option<Path> {
        assert!(!self.pathfinder_dirty);
        self.pathfinder.pathfind(req, self)
    }
    pub fn pathfind_avoiding_zones(
        &self,
        req: PathRequest,
        avoid: BTreeSet<LaneID>,
    ) -> Option<Path> {
        assert!(!self.pathfinder_dirty);
        self.pathfinder.pathfind_avoiding_zones(req, avoid, self)
    }

    pub fn should_use_transit(
        &self,
        start: Position,
        end: Position,
    ) -> Option<(BusStopID, Option<BusStopID>, BusRouteID)> {
        self.pathfinder.should_use_transit(self, start, end)
    }

    // None for SharedSidewalkCorners
    pub fn get_movement(&self, t: TurnID) -> Option<MovementID> {
        if let Some(ref ts) = self.maybe_get_traffic_signal(t.parent) {
            if self.get_t(t).turn_type == TurnType::SharedSidewalkCorner {
                return None;
            }
            for m in ts.movements.values() {
                if m.members.contains(&t) {
                    return Some(m.id);
                }
            }
            panic!("{} doesn't belong to any movements", t);
        }
        None
    }

    pub fn find_r_by_osm_id(&self, id: OriginalRoad) -> Result<RoadID, String> {
        for r in self.all_roads() {
            if r.orig_id == id {
                return Ok(r.id);
            }
        }
        Err(format!("Can't find {}", id))
    }

    pub fn find_i_by_osm_id(&self, id: osm::NodeID) -> Result<IntersectionID, String> {
        for i in self.all_intersections() {
            if i.orig_id == id {
                return Ok(i.id);
            }
        }
        Err(format!("Can't find {}", id))
    }

    pub fn find_b_by_osm_id(&self, id: osm::OsmID) -> Option<BuildingID> {
        for b in self.all_buildings() {
            if b.orig_id == id {
                return Some(b.id);
            }
        }
        None
    }

    pub fn find_br(&self, id: osm::RelationID) -> Option<BusRouteID> {
        for br in self.all_bus_routes() {
            if br.osm_rel_id == id {
                return Some(br.id);
            }
        }
        None
    }

    // TODO Sort of a temporary hack
    pub fn hack_override_offstreet_spots(&mut self, spots_per_bldg: usize) {
        for b in &mut self.buildings {
            if let OffstreetParking::Private(ref mut num_spots, _) = b.parking {
                *num_spots = spots_per_bldg;
            }
        }
    }
    pub fn hack_override_offstreet_spots_individ(&mut self, b: BuildingID, spots: usize) {
        let b = &mut self.buildings[b.0];
        if let OffstreetParking::Private(ref mut num_spots, _) = b.parking {
            *num_spots = spots;
        }
    }

    pub fn hack_override_bldg_type(&mut self, b: BuildingID, bldg_type: BuildingType) {
        self.buildings[b.0].bldg_type = bldg_type;
    }

    pub fn hack_override_orig_spawn_times(&mut self, br: BusRouteID, times: Vec<Time>) {
        self.bus_routes[br.0].orig_spawn_times = times.clone();
        self.bus_routes[br.0].spawn_times = times;
    }

    pub fn get_languages(&self) -> BTreeSet<&str> {
        let mut languages = BTreeSet::new();
        for r in self.all_roads() {
            for key in r.osm_tags.inner().keys() {
                if let Some(x) = key.strip_prefix("name:") {
                    languages.insert(x);
                }
            }
        }
        for b in self.all_buildings() {
            for (names, _) in &b.amenities {
                for key in names.0.keys() {
                    if let Some(lang) = key {
                        languages.insert(lang);
                    }
                }
            }
        }
        languages
    }

    pub fn get_config(&self) -> &MapConfig {
        &self.config
    }
}