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
//! The sim crate runs a traffic simulation on top of the map_model. See also
//! https://a-b-street.github.io/docs/tech/trafficsim/index.html.
//!
//! The simulation is very roughly layered into two pieces: the low-level "mechanics" of simulating
//! individual agents over time, and higher-level systems like TripManager and TransitSimState that
//! glue together individual goals executed by the agents.
//!
//! Helpful terminology:
//! - sov = single occupancy vehicle, a car with just a driver and no passengers. (Car passengers
//!   are not currently modelled)

// Disable some noisy clippy warnings
#![allow(clippy::type_complexity, clippy::too_many_arguments)]

#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate log;

use std::fmt;

use serde::{Deserialize, Serialize};

use abstutil::{deserialize_usize, serialize_usize};
use geom::{Distance, Speed, Time};
use map_model::{
    BuildingID, IntersectionID, LaneID, Map, ParkingLotID, Path, PathConstraints, Position,
    TransitRouteID, TransitStopID,
};
use synthpop::TripEndpoint;

pub use crate::render::{
    CarStatus, DrawCarInput, DrawPedCrowdInput, DrawPedestrianInput, Intent, PedCrowdLocation,
    UnzoomedAgent,
};

pub use self::analytics::{Analytics, Problem, ProblemType, SlidingWindow, TripPhase};
pub(crate) use self::events::Event;
pub use self::events::{AlertLocation, TripPhaseType};
pub use self::make::SimFlags;
pub(crate) use self::make::{StartTripArgs, TripSpec};
pub(crate) use self::mechanics::{
    DrivingSimState, IntersectionSimState, ParkingSim, ParkingSimState, WalkingSimState,
};
pub(crate) use self::pandemic::PandemicModel;
pub use self::prebake::PrebakeSummary;
pub(crate) use self::recorder::TrafficRecorder;
pub(crate) use self::router::{ActionAtEnd, Router};
pub(crate) use self::scheduler::{Command, Scheduler};
pub use self::sim::{
    count_parked_cars_per_bldg, rand_dist, AgentProperties, AlertHandler, DelayCause, Sim,
    SimCallback, SimOptions,
};
pub(crate) use self::transit::TransitSimState;
pub use self::trips::{CommutersVehiclesCounts, Person, PersonState, TripInfo, TripResult};
pub(crate) use self::trips::{TripLeg, TripManager};
pub use synthpop::make::{fork_rng, BorderSpawnOverTime, ScenarioGenerator, SpawnOverTime};

mod analytics;
mod events;
mod make;
mod mechanics;
mod pandemic;
pub mod prebake;
mod recorder;
mod render;
mod router;
mod scheduler;
mod sim;
mod transit;
mod trips;

// http://pccsc.net/bicycle-parking-info/ says 68 inches, which is 1.73m
pub(crate) const BIKE_LENGTH: Distance = Distance::const_meters(1.8);
pub(crate) const MIN_CAR_LENGTH: Distance = Distance::const_meters(4.5);
pub(crate) const MAX_CAR_LENGTH: Distance = Distance::const_meters(6.5);
// Note this is more than MAX_CAR_LENGTH
pub(crate) const BUS_LENGTH: Distance = Distance::const_meters(12.5);
pub(crate) const LIGHT_RAIL_LENGTH: Distance = Distance::const_meters(60.0);

/// At all speeds (including at rest), cars must be at least this far apart, measured from front of
/// one car to the back of the other.
pub(crate) const FOLLOWING_DISTANCE: Distance = Distance::const_meters(1.0);

/// When spawning at borders, start the front of the vehicle this far along and gradually appear.
/// Getting too close to EPSILON_DIST can lead to get_draw_car having no geometry at all.
pub(crate) const SPAWN_DIST: Distance = Distance::const_meters(0.05);

// TODO Implement Eq, Hash, Ord manually to guarantee this.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CarID {
    /// The numeric ID must be globally unique, without considering VehicleType.
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub id: usize,
    /// VehicleType is bundled for convenience; many places need to know this without a lookup.
    pub vehicle_type: VehicleType,
}

impl fmt::Display for CarID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.vehicle_type {
            VehicleType::Car => write!(f, "Car #{}", self.id),
            VehicleType::Bus => write!(f, "Bus #{}", self.id),
            VehicleType::Train => write!(f, "Train #{}", self.id),
            VehicleType::Bike => write!(f, "Bike #{}", self.id),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PedestrianID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl fmt::Display for PedestrianID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Pedestrian #{}", self.0)
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Hash)]
pub enum AgentID {
    Car(CarID),
    Pedestrian(PedestrianID),
    // TODO Rename...
    BusPassenger(PersonID, CarID),
}

impl AgentID {
    pub(crate) fn as_car(self) -> CarID {
        match self {
            AgentID::Car(id) => id,
            _ => panic!("Not a CarID: {:?}", self),
        }
    }

    pub fn to_type(self) -> AgentType {
        match self {
            AgentID::Car(c) => match c.vehicle_type {
                VehicleType::Car => AgentType::Car,
                VehicleType::Bike => AgentType::Bike,
                VehicleType::Bus => AgentType::Bus,
                VehicleType::Train => AgentType::Train,
            },
            AgentID::Pedestrian(_) => AgentType::Pedestrian,
            AgentID::BusPassenger(_, _) => AgentType::TransitRider,
        }
    }

    pub fn to_vehicle_type(self) -> Option<VehicleType> {
        match self {
            AgentID::Car(c) => Some(c.vehicle_type),
            AgentID::Pedestrian(_) => None,
            AgentID::BusPassenger(_, _) => None,
        }
    }

    // Convenient debugging
    #[allow(unused)]
    pub(crate) fn is_car(&self, id: usize) -> bool {
        match self {
            AgentID::Car(c) => c.id == id,
            _ => false,
        }
    }

    pub(crate) fn is_pedestrian(&self) -> bool {
        matches!(self, AgentID::Pedestrian(_))
    }
}

impl fmt::Display for AgentID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AgentID::Car(id) => write!(f, "AgentID({})", id),
            AgentID::Pedestrian(id) => write!(f, "AgentID({})", id),
            AgentID::BusPassenger(person, bus) => write!(f, "AgentID({} on {})", person, bus),
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Hash)]
pub enum AgentType {
    Car,
    Bike,
    Bus,
    Train,
    Pedestrian,
    TransitRider,
}

impl AgentType {
    pub fn all() -> Vec<AgentType> {
        vec![
            AgentType::Car,
            AgentType::Bike,
            AgentType::Bus,
            AgentType::Train,
            AgentType::Pedestrian,
            AgentType::TransitRider,
        ]
    }

    pub fn noun(self) -> &'static str {
        match self {
            AgentType::Car => "Car",
            AgentType::Bike => "Bike",
            AgentType::Bus => "Bus",
            AgentType::Train => "Train",
            AgentType::Pedestrian => "Pedestrian",
            AgentType::TransitRider => "Transit rider",
        }
    }

    pub fn plural_noun(self) -> &'static str {
        match self {
            AgentType::Car => "cars",
            AgentType::Bike => "bikes",
            AgentType::Bus => "buses",
            AgentType::Train => "trains",
            AgentType::Pedestrian => "pedestrians",
            AgentType::TransitRider => "transit riders",
        }
    }

    pub fn ongoing_verb(self) -> &'static str {
        match self {
            AgentType::Car => "driving",
            AgentType::Bike => "biking",
            AgentType::Bus | AgentType::Train => unreachable!(),
            AgentType::Pedestrian => "walking",
            AgentType::TransitRider => "riding transit",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TripID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl abstutil::CloneableAny for TripID {}

impl fmt::Display for TripID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Trip #{}", self.0)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PersonID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl fmt::Display for PersonID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Person {}", self.0)
    }
}

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub enum VehicleType {
    Car,
    Bus,
    Train,
    Bike,
}

impl fmt::Display for VehicleType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VehicleType::Car => write!(f, "car"),
            VehicleType::Bus => write!(f, "bus"),
            VehicleType::Train => write!(f, "train"),
            VehicleType::Bike => write!(f, "bike"),
        }
    }
}

impl VehicleType {
    pub fn to_constraints(self) -> PathConstraints {
        match self {
            VehicleType::Car => PathConstraints::Car,
            VehicleType::Bus => PathConstraints::Bus,
            VehicleType::Train => PathConstraints::Train,
            VehicleType::Bike => PathConstraints::Bike,
        }
    }

    pub(crate) fn is_transit(self) -> bool {
        match self {
            VehicleType::Car => false,
            VehicleType::Bus => true,
            VehicleType::Train => true,
            VehicleType::Bike => false,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Vehicle {
    pub id: CarID,
    pub owner: Option<PersonID>,
    pub vehicle_type: VehicleType,
    pub length: Distance,
    pub max_speed: Option<Speed>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct VehicleSpec {
    pub vehicle_type: VehicleType,
    pub length: Distance,
    pub max_speed: Option<Speed>,
}

impl VehicleSpec {
    pub(crate) fn make(self, id: CarID, owner: Option<PersonID>) -> Vehicle {
        assert_eq!(id.vehicle_type, self.vehicle_type);
        Vehicle {
            id,
            owner,
            vehicle_type: self.vehicle_type,
            length: self.length,
            max_speed: self.max_speed,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ParkingSpot {
    /// Lane and idx
    Onstreet(LaneID, usize),
    /// Building and idx (pretty meaningless)
    Offstreet(BuildingID, usize),
    Lot(ParkingLotID, usize),
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ParkedCar {
    pub vehicle: Vehicle,
    pub spot: ParkingSpot,
    pub parked_since: Time,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum DrivingGoal {
    ParkNear(BuildingID),
    Border(IntersectionID, LaneID),
}

impl DrivingGoal {
    pub fn goal_pos(&self, constraints: PathConstraints, map: &Map) -> Option<Position> {
        match self {
            DrivingGoal::ParkNear(b) => match constraints {
                PathConstraints::Car => {
                    let driving_lane = map.find_driving_lane_near_building(*b);
                    let sidewalk_pos = map.get_b(*b).sidewalk_pos;
                    if driving_lane.road == sidewalk_pos.lane().road {
                        Some(sidewalk_pos.equiv_pos(driving_lane, map))
                    } else {
                        Some(Position::start(driving_lane))
                    }
                }
                PathConstraints::Bike => Some(map.get_b(*b).biking_connection(map)?.0),
                PathConstraints::Bus | PathConstraints::Train | PathConstraints::Pedestrian => {
                    unreachable!()
                }
            },
            DrivingGoal::Border(_, l) => Some(Position::end(*l, map)),
        }
    }

    pub fn make_router(&self, owner: CarID, path: Path, map: &Map) -> Router {
        match self {
            DrivingGoal::ParkNear(b) => {
                if owner.vehicle_type == VehicleType::Bike {
                    Router::bike_then_stop(owner, path, SidewalkSpot::bike_rack(*b, map).unwrap())
                } else {
                    Router::park_near(owner, path, *b)
                }
            }
            DrivingGoal::Border(i, last_lane) => {
                Router::end_at_border(owner, path, map.get_l(*last_lane).length(), *i)
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub(crate) struct SidewalkSpot {
    pub connection: SidewalkPOI,
    pub sidewalk_pos: Position,
}

/// Point of interest, that is
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub(crate) enum SidewalkPOI {
    /// Note that for offstreet parking, the path will be the same as the building's front path.
    ParkingSpot(ParkingSpot),
    /// Don't actually know where this goes yet!
    DeferredParkingSpot,
    Building(BuildingID),
    TransitStop(TransitStopID),
    Border(IntersectionID),
    /// The bikeable position
    BikeRack(Position),
    SuddenlyAppear,
}

impl SidewalkSpot {
    /// Pretty hacky case
    pub fn deferred_parking_spot() -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::DeferredParkingSpot,
            sidewalk_pos: Position::start(LaneID::dummy()),
        }
    }

    pub fn parking_spot(
        spot: ParkingSpot,
        map: &Map,
        parking_sim: &ParkingSimState,
    ) -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::ParkingSpot(spot),
            sidewalk_pos: parking_sim.spot_to_sidewalk_pos(spot, map),
        }
    }

    pub fn building(b: BuildingID, map: &Map) -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::Building(b),
            sidewalk_pos: map.get_b(b).sidewalk_pos,
        }
    }

    // TODO For the case when we have to start/stop biking somewhere else, this won't match up with
    // a building though!
    pub fn bike_rack(b: BuildingID, map: &Map) -> Option<SidewalkSpot> {
        let (bike_pos, sidewalk_pos) = map.get_b(b).biking_connection(map)?;
        Some(SidewalkSpot {
            connection: SidewalkPOI::BikeRack(bike_pos),
            sidewalk_pos,
        })
    }

    pub fn bus_stop(stop: TransitStopID, map: &Map) -> SidewalkSpot {
        SidewalkSpot {
            sidewalk_pos: map.get_ts(stop).sidewalk_pos,
            connection: SidewalkPOI::TransitStop(stop),
        }
    }

    // Recall sidewalks are bidirectional.
    pub fn start_at_border(i: IntersectionID, map: &Map) -> Option<SidewalkSpot> {
        Some(SidewalkSpot {
            sidewalk_pos: TripEndpoint::start_walking_at_border(i, map)?,
            connection: SidewalkPOI::Border(i),
        })
    }

    pub fn end_at_border(i: IntersectionID, map: &Map) -> Option<SidewalkSpot> {
        Some(SidewalkSpot {
            sidewalk_pos: TripEndpoint::end_walking_at_border(i, map)?,
            connection: SidewalkPOI::Border(i),
        })
    }

    pub fn suddenly_appear(pos: Position, map: &Map) -> SidewalkSpot {
        let lane = map.get_l(pos.lane());
        assert!(lane.is_walkable());
        assert!(pos.dist_along() <= lane.length());
        SidewalkSpot {
            sidewalk_pos: pos,
            connection: SidewalkPOI::SuddenlyAppear,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
pub(crate) struct TimeInterval {
    // TODO Private fields
    pub start: Time,
    pub end: Time,
}

impl TimeInterval {
    pub fn new(start: Time, end: Time) -> TimeInterval {
        if end < start {
            panic!("Bad TimeInterval {} .. {}", start, end);
        }
        TimeInterval { start, end }
    }

    pub fn percent(&self, t: Time) -> f64 {
        if self.start == self.end {
            return 1.0;
        }

        let x = (t - self.start) / (self.end - self.start);
        assert!((0.0..=1.0).contains(&x));
        x
    }

    pub fn percent_clamp_end(&self, t: Time) -> f64 {
        if t > self.end {
            return 1.0;
        }
        self.percent(t)
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
pub(crate) struct DistanceInterval {
    // TODO Private fields
    pub start: Distance,
    pub end: Distance,
}

impl DistanceInterval {
    pub fn new_driving(start: Distance, end: Distance) -> DistanceInterval {
        if end < start {
            panic!("Bad DistanceInterval {} .. {}", start, end);
        }
        DistanceInterval { start, end }
    }

    pub fn new_walking(start: Distance, end: Distance) -> DistanceInterval {
        // start > end is fine, might be contraflow.
        DistanceInterval { start, end }
    }

    pub fn lerp(&self, x: f64) -> Distance {
        assert!((0.0..=1.0).contains(&x));
        self.start + x * (self.end - self.start)
    }

    pub fn length(&self) -> Distance {
        (self.end - self.start).abs()
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub(crate) struct CreatePedestrian {
    pub id: PedestrianID,
    pub start: SidewalkSpot,
    pub speed: Speed,
    pub goal: SidewalkSpot,
    pub path: Path,
    pub trip: TripID,
    pub person: PersonID,
}

#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub(crate) struct CreateCar {
    pub vehicle: Vehicle,
    pub router: Router,
    pub maybe_parked_car: Option<ParkedCar>,
    /// None for buses
    pub trip_and_person: Option<(TripID, PersonID)>,
    pub maybe_route: Option<TransitRouteID>,
}

impl CreateCar {
    pub fn for_appearing(
        vehicle: Vehicle,
        router: Router,
        trip: TripID,
        person: PersonID,
    ) -> CreateCar {
        CreateCar {
            vehicle,
            router,
            maybe_parked_car: None,
            trip_and_person: Some((trip, person)),
            maybe_route: None,
        }
    }

    // TODO Maybe inline in trips, the only caller.
    pub fn for_parked_car(
        parked_car: ParkedCar,
        router: Router,
        trip: TripID,
        person: PersonID,
    ) -> CreateCar {
        CreateCar {
            vehicle: parked_car.vehicle.clone(),
            router,
            maybe_parked_car: Some(parked_car),
            trip_and_person: Some((trip, person)),
            maybe_route: None,
        }
    }
}

pub fn pedestrian_body_radius() -> Distance {
    map_model::SIDEWALK_THICKNESS / 4.0
}