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
use std::collections::{HashMap, HashSet};

use abstutil::MultiMap;
use geom::{Angle, Circle, Distance, Pt2D, Speed};
use map_gui::ID;
use map_model::{BuildingID, Direction, IntersectionID, LaneType, RoadID};
use widgetry::EventCtx;

use crate::controls::InstantController;
use crate::App;

pub const ZOOM: f64 = 10.0;

pub struct Player {
    pos: Pt2D,
    on: On,
    bldgs_along_road: BuildingsAlongRoad,

    controls: InstantController,
}

impl Player {
    pub fn new(ctx: &mut EventCtx, app: &App, start: IntersectionID) -> Player {
        ctx.canvas.cam_zoom = ZOOM;
        let pos = app.map.get_i(start).polygon.center();
        ctx.canvas.center_on_map_pt(pos);

        Player {
            pos,
            on: On::Intersection(start),
            bldgs_along_road: BuildingsAlongRoad::new(app),

            controls: InstantController::new(),
        }
    }

    /// Returns any buildings we passed
    pub fn update_with_speed(
        &mut self,
        ctx: &mut EventCtx,
        app: &App,
        speed: Speed,
    ) -> Vec<BuildingID> {
        let (dx, dy) = self.controls.displacement(ctx, speed);
        if dx != 0.0 || dy != 0.0 {
            self.apply_displacement(ctx, app, dx, dy, true)
        // TODO Do the center_on_map_pt here, actually
        } else {
            Vec::new()
        }
    }

    fn apply_displacement(
        &mut self,
        ctx: &mut EventCtx,
        app: &App,
        dx: f64,
        dy: f64,
        recurse: bool,
    ) -> Vec<BuildingID> {
        let new_pos = self.pos.offset(dx, dy);

        // Make sure we only move between roads/intersections that're actually connected. Don't
        // warp to bridges/tunnels.
        let (valid_roads, valid_intersections) = self.on.get_connections(app);

        // Make sure we're still on the road
        let mut on = None;
        for id in app
            .draw_map
            .get_matching_objects(Circle::new(self.pos, Distance::meters(3.0)).get_bounds())
        {
            if let ID::Intersection(i) = id {
                if valid_intersections.contains(&i) && app.map.get_i(i).polygon.contains_pt(new_pos)
                {
                    on = Some(On::Intersection(i));
                    break;
                }
            } else if let ID::Road(r) = id {
                let road = app.map.get_r(r);
                if valid_roads.contains(&r)
                    && !road.is_light_rail()
                    && road.get_thick_polygon(&app.map).contains_pt(new_pos)
                {
                    // Where along the road are we?
                    let pt_on_center_line = road.center_pts.project_pt(new_pos);
                    if let Some((dist, _)) = road.center_pts.dist_along_of_point(pt_on_center_line)
                    {
                        on = Some(On::Road(r, dist));
                    } else {
                        error!(
                            "{} snapped to {} on {}, but dist_along_of_point failed",
                            new_pos, pt_on_center_line, r
                        );
                    }
                    break;
                }
            }
        }

        let mut buildings_passed = Vec::new();
        if let Some(new_on) = on {
            self.pos = new_pos;
            ctx.canvas.center_on_map_pt(self.pos);

            if let (On::Road(r1, dist1), On::Road(r2, dist2)) = (self.on.clone(), new_on.clone()) {
                if r1 == r2 {
                    // Find all buildings in this range of distance along
                    buildings_passed.extend(self.bldgs_along_road.query_range(r1, dist1, dist2));
                }
            }
            self.on = new_on;
        } else {
            // We went out of bounds. Undo this movement.
            // TODO Draw a line between the old and new position, and snap to the boundary of
            // whatever we hit.

            // Apply horizontal and vertical movement independently, so we "slide" along boundaries
            // if possible
            if recurse {
                let orig = self.pos;
                if dx != 0.0 {
                    buildings_passed.extend(self.apply_displacement(ctx, app, dx, 0.0, false));
                }
                if dy != 0.0 {
                    buildings_passed.extend(self.apply_displacement(ctx, app, 0.0, dy, false));
                }

                // If we're stuck, try bouncing in the opposite direction.
                // TODO This is jittery and we can sometimes go out of bounds now. :D
                if self.pos == orig {
                    buildings_passed.extend(self.apply_displacement(ctx, app, -dx, -dy, false));
                }
            }
        }
        buildings_passed
    }

    pub fn get_pos(&self) -> Pt2D {
        self.pos
    }

    pub fn get_angle(&self) -> Angle {
        self.controls.facing
    }

    /// Is the player currently on a road with a bus or bike lane?
    pub fn on_good_road(&self, app: &App) -> bool {
        if let On::Road(r, _) = self.on {
            for (_, _, lt) in app.map.get_r(r).lanes_ltr() {
                if lt == LaneType::Biking || lt == LaneType::Bus {
                    return true;
                }
            }
        }
        false
    }
}

#[derive(Clone, PartialEq)]
enum On {
    Intersection(IntersectionID),
    // Distance along the center line
    Road(RoadID, Distance),
}

impl On {
    fn get_connections(&self, app: &App) -> (HashSet<RoadID>, HashSet<IntersectionID>) {
        let mut valid_roads = HashSet::new();
        let mut valid_intersections = HashSet::new();
        match self {
            On::Road(r, _) => {
                let r = app.map.get_r(*r);
                valid_intersections.insert(r.src_i);
                valid_intersections.insert(r.dst_i);
                // Intersections might be pretty small
                valid_roads.extend(app.map.get_i(r.src_i).roads.clone());
                valid_roads.extend(app.map.get_i(r.dst_i).roads.clone());
            }
            On::Intersection(i) => {
                let i = app.map.get_i(*i);
                for r in &i.roads {
                    valid_roads.insert(*r);
                    // Roads can be small
                    let r = app.map.get_r(*r);
                    valid_intersections.insert(r.src_i);
                    valid_intersections.insert(r.dst_i);
                }
            }
        }
        (valid_roads, valid_intersections)
    }
}

struct BuildingsAlongRoad {
    // For each road, all of the buildings along it. Ascending distance, with the distance matching
    // the road's center points.
    per_road: HashMap<RoadID, Vec<(Distance, BuildingID)>>,
}

impl BuildingsAlongRoad {
    fn new(app: &App) -> BuildingsAlongRoad {
        let mut raw: MultiMap<RoadID, (Distance, BuildingID)> = MultiMap::new();
        for b in app.map.all_buildings() {
            // TODO Happily assuming road and lane length is roughly the same
            let road = app.map.get_parent(b.sidewalk_pos.lane());
            let dist = match road.dir(b.sidewalk_pos.lane()) {
                Direction::Fwd => b.sidewalk_pos.dist_along(),
                Direction::Back => road.center_pts.length() - b.sidewalk_pos.dist_along(),
            };
            raw.insert(road.id, (dist, b.id));
        }

        let mut per_road = HashMap::new();
        for (road, list) in raw.consume() {
            // BTreeSet will sort by the distance
            per_road.insert(road, list.into_iter().collect());
        }

        BuildingsAlongRoad { per_road }
    }

    fn query_range(&self, road: RoadID, dist1: Distance, dist2: Distance) -> Vec<BuildingID> {
        if dist1 > dist2 {
            return self.query_range(road, dist2, dist1);
        }

        let mut results = Vec::new();
        if let Some(list) = self.per_road.get(&road) {
            // TODO Binary search to find start?
            for (dist, b) in list {
                if *dist >= dist1 && *dist <= dist2 {
                    results.push(*b);
                }
            }
        }
        results
    }
}