diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 3bd96f21e4..28ad1ea2fe 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -432,15 +432,20 @@ static std::array _vehicle_tile_hash{}; VehiclesNearTileXY::Iterator::Iterator(int32_t x, int32_t y) { const int COLL_DIST = 6; + pos_rect.left = x - COLL_DIST; + pos_rect.right = x + COLL_DIST; + pos_rect.top = y - COLL_DIST; + pos_rect.bottom = y + COLL_DIST; /* Hash area to scan */ - this->hxmin = this->hx = GetTileHash1D((x - COLL_DIST) / TILE_SIZE); - this->hxmax = GetTileHash1D((x + COLL_DIST) / TILE_SIZE); - this->hymin = this->hy = GetTileHash1D((y - COLL_DIST) / TILE_SIZE); - this->hymax = GetTileHash1D((y + COLL_DIST) / TILE_SIZE); + this->hxmin = this->hx = GetTileHash1D(pos_rect.left / TILE_SIZE); + this->hxmax = GetTileHash1D(pos_rect.right / TILE_SIZE); + this->hymin = this->hy = GetTileHash1D(pos_rect.top / TILE_SIZE); + this->hymax = GetTileHash1D(pos_rect.bottom / TILE_SIZE); this->current_veh = _vehicle_tile_hash[ComposeTileHash(this->hx, this->hy)]; this->SkipEmptyBuckets(); + this->SkipFalseMatches(); } /** @@ -471,6 +476,14 @@ void VehiclesNearTileXY::Iterator::SkipEmptyBuckets() } } +/** + * Advance the internal state until it reaches a vehicle within the search area. + */ +void VehiclesNearTileXY::Iterator::SkipFalseMatches() +{ + while (this->current_veh != nullptr && !this->pos_rect.Contains({this->current_veh->x_pos, this->current_veh->y_pos})) this->Increment(); +} + /** * Iterator constructor. * Find first vehicle on tile. diff --git a/src/vehicle_func.h b/src/vehicle_func.h index e8409ab9a8..9c882ac08f 100644 --- a/src/vehicle_func.h +++ b/src/vehicle_func.h @@ -139,6 +139,7 @@ public: Iterator &operator++() { this->Increment(); + this->SkipFalseMatches(); return *this; } @@ -149,12 +150,14 @@ public: return result; } private: + Rect pos_rect; uint hxmin, hxmax, hymin, hymax; uint hx, hy; Vehicle *current_veh; void Increment(); void SkipEmptyBuckets(); + void SkipFalseMatches(); }; explicit VehiclesNearTileXY(int32_t x, int32_t y) : start(x, y) {}