* Find the vehicle close to the clicked coordinates. * @param vp Viewport clicked in. * @param x X coordinate in the viewport. * @param y Y coordinate in the viewport. * @return Closest vehicle, or \c nullptr if none found. */
| 1213 | * @return Closest vehicle, or \c nullptr if none found. |
| 1214 | */ |
| 1215 | Vehicle *CheckClickOnVehicle(const Viewport &vp, int x, int y) |
| 1216 | { |
| 1217 | Vehicle *found = nullptr; |
| 1218 | uint dist, best_dist = UINT_MAX; |
| 1219 | |
| 1220 | x -= vp.left; |
| 1221 | y -= vp.top; |
| 1222 | if (!IsInsideMM(x, 0, vp.width) || !IsInsideMM(y, 0, vp.height)) return nullptr; |
| 1223 | |
| 1224 | x = ScaleByZoom(x, vp.zoom) + vp.virtual_left; |
| 1225 | y = ScaleByZoom(y, vp.zoom) + vp.virtual_top; |
| 1226 | |
| 1227 | /* Border size of MAX_VEHICLE_PIXEL_xy */ |
| 1228 | const int xb = MAX_VEHICLE_PIXEL_X * ZOOM_BASE; |
| 1229 | const int yb = MAX_VEHICLE_PIXEL_Y * ZOOM_BASE; |
| 1230 | |
| 1231 | /* The hash area to scan */ |
| 1232 | uint xl = GetViewportHashX(x - xb); |
| 1233 | uint xu = GetViewportHashX(x); |
| 1234 | uint yl = GetViewportHashY(y - yb); |
| 1235 | uint yu = GetViewportHashY(y); |
| 1236 | |
| 1237 | for (uint hy = yl;; hy = (hy + GEN_HASHY_INC) & GEN_HASHY_MASK) { |
| 1238 | for (uint hx = xl;; hx = (hx + GEN_HASHX_INC) & GEN_HASHX_MASK) { |
| 1239 | Vehicle *v = _vehicle_viewport_hash[hx + hy]; // already masked & 0xFFF |
| 1240 | |
| 1241 | while (v != nullptr) { |
| 1242 | if (!v->vehstatus.Any({VehState::Hidden, VehState::Unclickable}) && |
| 1243 | x >= v->coord.left && x <= v->coord.right && |
| 1244 | y >= v->coord.top && y <= v->coord.bottom) { |
| 1245 | |
| 1246 | dist = std::max( |
| 1247 | abs(((v->coord.left + v->coord.right) >> 1) - x), |
| 1248 | abs(((v->coord.top + v->coord.bottom) >> 1) - y) |
| 1249 | ); |
| 1250 | |
| 1251 | if (dist < best_dist) { |
| 1252 | found = v; |
| 1253 | best_dist = dist; |
| 1254 | } |
| 1255 | } |
| 1256 | v = v->hash_viewport_next; |
| 1257 | } |
| 1258 | if (hx == xu) break; |
| 1259 | } |
| 1260 | if (hy == yu) break; |
| 1261 | } |
| 1262 | |
| 1263 | return found; |
| 1264 | } |
| 1265 | |
| 1266 | /** |
| 1267 | * Decrease the value of a vehicle. |
no test coverage detected