Merge branch 'development' into feature/no_multiplayer_grf_limit
[openttd-joker.git] / src / road_cmd.cpp
blob6062f6c75af70379edec696b53313315d7526235
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file road_cmd.cpp Commands related to road tiles. */
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "road_internal.h"
15 #include "viewport_func.h"
16 #include "command_func.h"
17 #include "pathfinder/yapf/yapf_cache.h"
18 #include "depot_base.h"
19 #include "newgrf.h"
20 #include "autoslope.h"
21 #include "tunnelbridge_map.h"
22 #include "strings_func.h"
23 #include "vehicle_func.h"
24 #include "sound_func.h"
25 #include "tunnelbridge.h"
26 #include "cheat_type.h"
27 #include "effectvehicle_func.h"
28 #include "effectvehicle_base.h"
29 #include "elrail_func.h"
30 #include "roadveh.h"
31 #include "town.h"
32 #include "company_base.h"
33 #include "core/random_func.hpp"
34 #include "newgrf_railtype.h"
35 #include "date_func.h"
36 #include "genworld.h"
37 #include "company_gui.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 /**
44 * Verify whether a road vehicle is available.
45 * @return \c true if at least one road vehicle is available, \c false if not
47 bool RoadVehiclesAreBuilt()
49 const RoadVehicle *rv;
50 FOR_ALL_ROADVEHICLES(rv) return true;
52 return false;
55 /** Invalid RoadBits on slopes. */
56 extern const RoadBits _invalid_tileh_slopes_road[2][15] = {
57 /* The inverse of the mixable RoadBits on a leveled slope */
59 ROAD_NONE, // SLOPE_FLAT
60 ROAD_NE | ROAD_SE, // SLOPE_W
61 ROAD_NE | ROAD_NW, // SLOPE_S
63 ROAD_NE, // SLOPE_SW
64 ROAD_NW | ROAD_SW, // SLOPE_E
65 ROAD_NONE, // SLOPE_EW
67 ROAD_NW, // SLOPE_SE
68 ROAD_NONE, // SLOPE_WSE
69 ROAD_SE | ROAD_SW, // SLOPE_N
71 ROAD_SE, // SLOPE_NW
72 ROAD_NONE, // SLOPE_NS
73 ROAD_NONE, // SLOPE_ENW
75 ROAD_SW, // SLOPE_NE
76 ROAD_NONE, // SLOPE_SEN
77 ROAD_NONE // SLOPE_NWS
79 /* The inverse of the allowed straight roads on a slope
80 * (with and without a foundation). */
82 ROAD_NONE, // SLOPE_FLAT
83 ROAD_NONE, // SLOPE_W Foundation
84 ROAD_NONE, // SLOPE_S Foundation
86 ROAD_Y, // SLOPE_SW
87 ROAD_NONE, // SLOPE_E Foundation
88 ROAD_ALL, // SLOPE_EW
90 ROAD_X, // SLOPE_SE
91 ROAD_ALL, // SLOPE_WSE
92 ROAD_NONE, // SLOPE_N Foundation
94 ROAD_X, // SLOPE_NW
95 ROAD_ALL, // SLOPE_NS
96 ROAD_ALL, // SLOPE_ENW
98 ROAD_Y, // SLOPE_NE
99 ROAD_ALL, // SLOPE_SEN
100 ROAD_ALL // SLOPE_NW
104 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
107 * Is it allowed to remove the given road bits from the given tile?
108 * @param tile the tile to remove the road from
109 * @param remove the roadbits that are going to be removed
110 * @param owner the actual owner of the roadbits of the tile
111 * @param rt the road type to remove the bits from
112 * @param flags command flags
113 * @param town_check Shall the town rating checked/affected
114 * @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
116 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
118 if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
120 /* Water can always flood and towns can always remove "normal" road pieces.
121 * Towns are not be allowed to remove non "normal" road pieces, like tram
122 * tracks as that would result in trams that cannot turn. */
123 if (_current_company == OWNER_WATER ||
124 (rt == ROADTYPE_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
126 /* Only do the special processing if the road is owned
127 * by a town */
128 if (owner != OWNER_TOWN) {
129 if (owner == OWNER_NONE) return CommandCost();
130 CommandCost ret = CheckOwnership(owner);
131 return ret;
134 if (!town_check) return CommandCost();
136 if (_cheats.magic_bulldozer.value) return CommandCost();
138 Town *t = ClosestTownFromTile(tile, UINT_MAX);
139 if (t == NULL) return CommandCost();
141 /* check if you're allowed to remove the street owned by a town
142 * removal allowance depends on difficulty setting */
143 CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
144 if (ret.Failed()) return ret;
146 /* Get a bitmask of which neighbouring roads has a tile */
147 RoadBits n = ROAD_NONE;
148 RoadBits present = GetAnyRoadBits(tile, rt);
149 if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rt) & ROAD_SW)) n |= ROAD_NE;
150 if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rt) & ROAD_NW)) n |= ROAD_SE;
151 if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rt) & ROAD_NE)) n |= ROAD_SW;
152 if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rt) & ROAD_SE)) n |= ROAD_NW;
154 int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
155 /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
156 * then allow it */
157 if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
158 /* you can remove all kind of roads with extra dynamite */
159 if (!_settings_game.construction.extra_dynamite) {
160 SetDParam(0, t->index);
161 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
163 rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
165 ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
167 return CommandCost();
172 * Delete a piece of road.
173 * @param tile tile where to remove road from
174 * @param flags operation to perform
175 * @param pieces roadbits to remove
176 * @param rt roadtype to remove
177 * @param crossing_check should we check if there is a tram track when we are removing road from crossing?
178 * @param town_check should we check if the town allows removal?
180 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadType rt, bool crossing_check, bool town_check = true)
182 RoadTypes rts = GetRoadTypes(tile);
183 /* The tile doesn't have the given road type */
184 if (!HasBit(rts, rt)) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
186 switch (GetTileType(tile)) {
187 case MP_ROAD: {
188 CommandCost ret = EnsureNoVehicleOnGround(tile);
189 if (ret.Failed()) return ret;
190 break;
193 case MP_STATION: {
194 if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
196 CommandCost ret = EnsureNoVehicleOnGround(tile);
197 if (ret.Failed()) return ret;
198 break;
201 case MP_TUNNELBRIDGE: {
202 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
203 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
204 if (ret.Failed()) return ret;
205 break;
208 default:
209 return CMD_ERROR;
212 CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rt), rt, flags, town_check);
213 if (ret.Failed()) return ret;
215 if (!IsTileType(tile, MP_ROAD)) {
216 const bool custom_bridge_head = IsBridgeTile(tile) &&
217 HasBridgeFlatRamp(GetTileSlope(tile), DiagDirToAxis(GetTunnelBridgeDirection(tile))) &&
218 (_settings_game.construction.road_custom_bridge_heads || IsRoadCustomBridgeHead(tile));
220 /* If it's the last roadtype, just clear the whole tile */
221 if (rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
223 CommandCost cost(EXPENSES_CONSTRUCTION);
224 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
225 const RoadBits entrance_piece = DiagDirToRoadBits(GetTunnelBridgeDirection(tile));
226 const RoadBits axial_pieces = AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile)));
227 const RoadBits existing = IsBridge(tile) ? GetCustomBridgeHeadRoadBits(tile, rt) : axial_pieces;
228 const RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
230 /* handle case where we would otherwise leave a single bridge entrance piece */
231 if ((existing & ~pieces) == entrance_piece) {
232 pieces |= entrance_piece;
235 /* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
236 if ((existing & pieces) == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
238 if (!custom_bridge_head) pieces |= axial_pieces;
240 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
241 const uint middle_len = GetTunnelBridgeLength(other_end, tile);
242 uint pieces_count = 0;
244 const RoadBits other_end_existing = IsBridge(other_end) ? GetCustomBridgeHeadRoadBits(other_end, rt) : axial_pieces;
245 RoadBits other_end_pieces = ROAD_NONE;
246 if (pieces & entrance_piece) {
247 other_end_pieces |= MirrorRoadBits(entrance_piece);
248 /* if removing the other end entrance would only leave one piece, remove that too */
249 if (CountBits(other_end_existing & ~other_end_pieces) == 1) {
250 other_end_pieces |= other_end_existing;
252 pieces_count += middle_len * 2;
253 if (custom_bridge_head && ((GetCustomBridgeHeadRoadBits(tile, other_rt) & entrance_piece) == ROAD_NONE)) {
254 /* can't leave no entrance pieces for any road type */
255 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
258 pieces_count += CountBits(pieces & existing);
259 pieces_count += CountBits(other_end_pieces & other_end_existing);
261 cost.AddCost(pieces_count * _price[PR_CLEAR_ROAD]);
262 if (flags & DC_EXEC) {
263 SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
265 const RoadBits bits = existing & ~pieces;
266 const RoadBits other_bits = other_end_existing & ~other_end_pieces;
268 if (bits == ROAD_NONE) SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
269 if (other_bits == ROAD_NONE) SetRoadTypes(other_end, GetRoadTypes(other_end) & ~RoadTypeToRoadTypes(rt));
271 if (IsBridge(tile)) {
272 SetCustomBridgeHeadRoadBits(tile, rt, bits);
273 SetCustomBridgeHeadRoadBits(other_end, rt, other_bits);
276 if (bits == ROAD_NONE && other_bits == ROAD_NONE) {
277 /* If the owner of the bridge sells all its road, also move the ownership
278 * to the owner of the other roadtype, unless the bridge owner is a town. */
279 Owner other_owner = GetRoadOwner(tile, other_rt);
280 if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
281 SetTileOwner(tile, other_owner);
282 SetTileOwner(other_end, other_owner);
286 /* Mark tiles dirty that have been repaved */
287 if (IsBridge(tile)) {
288 MarkBridgeDirty(tile);
289 } else {
290 MarkTileDirtyByTile(tile);
291 MarkTileDirtyByTile(other_end);
294 AddRoadTunnelBridgeInfrastructure(tile, other_end);
295 DirtyAllCompanyInfrastructureWindows();
297 } else {
298 assert(IsDriveThroughStopTile(tile));
299 cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
300 if (flags & DC_EXEC) {
301 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
302 if (c != NULL) {
303 /* A full diagonal road tile has two road bits. */
304 c->infrastructure.road[rt] -= 2;
305 DirtyCompanyInfrastructureWindows(c->index);
307 SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
308 MarkTileDirtyByTile(tile);
311 return cost;
314 switch (GetRoadTileType(tile)) {
315 case ROAD_TILE_NORMAL: {
316 Slope tileh = GetTileSlope(tile);
318 /* Steep slopes behave the same as slopes with one corner raised. */
319 if (IsSteepSlope(tileh)) {
320 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
323 RoadBits present = GetRoadBits(tile, rt);
324 const RoadBits other = GetOtherRoadBits(tile, rt);
325 const Foundation f = GetRoadFoundation(tileh, present);
327 if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
329 /* Autocomplete to a straight road
330 * @li if the bits of the other roadtypes result in another foundation
331 * @li if build on slopes is disabled */
332 if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
333 (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
334 pieces |= MirrorRoadBits(pieces);
337 /* limit the bits to delete to the existing bits. */
338 pieces &= present;
339 if (pieces == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
341 /* Now set present what it will be after the remove */
342 present ^= pieces;
344 /* Check for invalid RoadBit combinations on slopes */
345 if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
346 (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
347 return CMD_ERROR;
350 if (flags & DC_EXEC) {
351 if (HasRoadWorks(tile)) {
352 /* flooding tile with road works, don't forget to remove the effect vehicle too */
353 assert(_current_company == OWNER_WATER);
354 EffectVehicle *v;
355 FOR_ALL_EFFECTVEHICLES(v) {
356 if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
357 delete v;
362 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
363 if (c != NULL) {
364 c->infrastructure.road[rt] -= CountBits(pieces);
365 DirtyCompanyInfrastructureWindows(c->index);
368 if (present == ROAD_NONE) {
369 RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
370 if (rts == ROADTYPES_NONE) {
371 /* Includes MarkTileDirtyByTile() */
372 DoClearSquare(tile);
373 } else {
374 if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
375 /* Update nearest-town index */
376 const Town *town = CalcClosestTownFromTile(tile);
377 SetTownIndex(tile, town == NULL ? (TownID)INVALID_TOWN : town->index);
379 SetRoadBits(tile, ROAD_NONE, rt);
380 SetRoadTypes(tile, rts);
381 MarkTileDirtyByTile(tile);
383 } else {
384 /* When bits are removed, you *always* end up with something that
385 * is not a complete straight road tile. However, trams do not have
386 * onewayness, so they cannot remove it either. */
387 if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
388 SetRoadBits(tile, present, rt);
389 MarkTileDirtyByTile(tile);
393 CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
394 /* If we build a foundation we have to pay for it. */
395 if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
397 return cost;
400 case ROAD_TILE_CROSSING: {
401 if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
402 return CMD_ERROR;
405 /* Don't allow road to be removed from the crossing when there is tram;
406 * we can't draw the crossing without roadbits ;) */
407 if (rt == ROADTYPE_ROAD && HasTileRoadType(tile, ROADTYPE_TRAM) && (flags & DC_EXEC || crossing_check)) return CMD_ERROR;
409 if (flags & DC_EXEC) {
410 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
411 if (c != NULL) {
412 /* A full diagonal road tile has two road bits. */
413 c->infrastructure.road[rt] -= 2;
414 DirtyCompanyInfrastructureWindows(c->index);
417 Track railtrack = GetCrossingRailTrack(tile);
418 RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
419 if (rts == ROADTYPES_NONE) {
420 TrackBits tracks = GetCrossingRailBits(tile);
421 bool reserved = HasCrossingReservation(tile);
422 MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
423 if (reserved) SetTrackReservation(tile, tracks);
425 /* Update rail count for level crossings. The plain track should still be accounted
426 * for, so only subtract the difference to the level crossing cost. */
427 c = Company::GetIfValid(GetTileOwner(tile));
428 if (c != NULL) {
429 c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
430 DirtyCompanyInfrastructureWindows(c->index);
432 } else {
433 SetRoadTypes(tile, rts);
435 MarkTileDirtyByTile(tile);
436 YapfNotifyTrackLayoutChange(tile, railtrack);
438 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
441 default:
442 case ROAD_TILE_DEPOT:
443 return CMD_ERROR;
449 * Calculate the costs for roads on slopes
450 * Aside modify the RoadBits to fit on the slopes
452 * @note The RoadBits are modified too!
453 * @param tileh The current slope
454 * @param pieces The RoadBits we want to add
455 * @param existing The existent RoadBits of the current type
456 * @param other The other existent RoadBits
457 * @return The costs for these RoadBits on this slope
459 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
461 /* Remove already build pieces */
462 CLRBITS(*pieces, existing);
464 /* If we can't build anything stop here */
465 if (*pieces == ROAD_NONE) return CMD_ERROR;
467 /* All RoadBit combos are valid on flat land */
468 if (tileh == SLOPE_FLAT) return CommandCost();
470 /* Steep slopes behave the same as slopes with one corner raised. */
471 if (IsSteepSlope(tileh)) {
472 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
475 /* Save the merge of all bits of the current type */
476 RoadBits type_bits = existing | *pieces;
478 /* Roads on slopes */
479 if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
481 /* If we add leveling we've got to pay for it */
482 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
484 return CommandCost();
487 /* Autocomplete uphill roads */
488 *pieces |= MirrorRoadBits(*pieces);
489 type_bits = existing | *pieces;
491 /* Uphill roads */
492 if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
493 (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
495 /* Slopes with foundation ? */
496 if (IsSlopeWithOneCornerRaised(tileh)) {
498 /* Prevent build on slopes if it isn't allowed */
499 if (_settings_game.construction.build_on_slopes) {
501 /* If we add foundation we've got to pay for it */
502 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
504 return CommandCost();
506 } else {
507 if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
508 return CommandCost();
511 return CMD_ERROR;
515 * Build a piece of road.
516 * @param tile tile where to build road
517 * @param flags operation to perform
518 * @param p1 bit 0..3 road pieces to build (RoadBits)
519 * bit 4..5 road type
520 * bit 6..7 disallowed directions to toggle
521 * bit 8 disable custom bridge heads
522 * @param p2 the town that is building the road (0 if not applicable)
523 * @param text unused
524 * @return the cost of this operation or an error
526 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
528 CompanyID company = _current_company;
529 CommandCost cost(EXPENSES_CONSTRUCTION);
531 RoadBits existing = ROAD_NONE;
532 RoadBits other_bits = ROAD_NONE;
534 /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
535 * if a non-company is building the road */
536 if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CMD_ERROR;
537 if (company != OWNER_TOWN) {
538 const Town *town = CalcClosestTownFromTile(tile);
539 p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
541 if (company == OWNER_DEITY) {
542 company = OWNER_TOWN;
544 /* If we are not within a town, we are not owned by the town */
545 if (town == NULL || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
546 company = OWNER_NONE;
551 RoadBits pieces = Extract<RoadBits, 0, 4>(p1);
553 /* do not allow building 'zero' road bits, code wouldn't handle it */
554 if (pieces == ROAD_NONE) return CMD_ERROR;
556 RoadType rt = Extract<RoadType, 4, 2>(p1);
557 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
559 DisallowedRoadDirections toggle_drd = Extract<DisallowedRoadDirections, 6, 2>(p1);
561 bool disable_custom_bridge_heads = HasBit(p1, 8);
563 Slope tileh = GetTileSlope(tile);
565 bool need_to_clear = false;
566 switch (GetTileType(tile)) {
567 case MP_ROAD:
568 switch (GetRoadTileType(tile)) {
569 case ROAD_TILE_NORMAL: {
570 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
572 other_bits = GetOtherRoadBits(tile, rt);
573 if (!HasTileRoadType(tile, rt)) break;
575 existing = GetRoadBits(tile, rt);
576 bool crossing = !IsStraightRoad(existing | pieces);
577 if (rt != ROADTYPE_TRAM && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
578 /* Junctions cannot be one-way */
579 return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
581 if ((existing & pieces) == pieces) {
582 /* We only want to set the (dis)allowed road directions */
583 if (toggle_drd != DRD_NONE && rt != ROADTYPE_TRAM) {
584 if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
586 Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
587 if (owner != OWNER_NONE) {
588 CommandCost ret = CheckOwnership(owner, tile);
589 if (ret.Failed()) return ret;
592 DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
593 DisallowedRoadDirections dis_new = dis_existing ^ toggle_drd;
595 /* We allow removing disallowed directions to break up
596 * deadlocks, but adding them can break articulated
597 * vehicles. As such, only when less is disallowed,
598 * i.e. bits are removed, we skip the vehicle check. */
599 if (CountBits(dis_existing) <= CountBits(dis_new)) {
600 CommandCost ret = EnsureNoVehicleOnGround(tile);
601 if (ret.Failed()) return ret;
604 /* Ignore half built tiles */
605 if ((flags & DC_EXEC) && rt != ROADTYPE_TRAM && IsStraightRoad(existing)) {
606 SetDisallowedRoadDirections(tile, dis_new);
607 MarkTileDirtyByTile(tile);
609 return CommandCost();
611 return_cmd_error(STR_ERROR_ALREADY_BUILT);
613 /* Disallow breaking end-of-line of someone else
614 * so trams can still reverse on this tile. */
615 if (rt == ROADTYPE_TRAM && HasExactlyOneBit(existing)) {
616 Owner owner = GetRoadOwner(tile, rt);
617 if (Company::IsValidID(owner)) {
618 CommandCost ret = CheckOwnership(owner);
619 if (ret.Failed()) return ret;
622 break;
625 case ROAD_TILE_CROSSING:
626 other_bits = GetCrossingRoadBits(tile);
627 if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
628 pieces = other_bits; // we need to pay for both roadbits
630 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
631 break;
633 case ROAD_TILE_DEPOT:
634 if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
635 goto do_clear;
637 default: NOT_REACHED();
639 break;
641 case MP_RAILWAY: {
642 if (IsSteepSlope(tileh)) {
643 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
646 /* Level crossings may only be built on these slopes */
647 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
648 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
651 if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
653 if (RailNoLevelCrossings(GetRailType(tile))) {
654 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
657 Axis roaddir;
658 switch (GetTrackBits(tile)) {
659 case TRACK_BIT_X:
660 if (pieces & ROAD_X) goto do_clear;
661 roaddir = AXIS_Y;
662 break;
664 case TRACK_BIT_Y:
665 if (pieces & ROAD_Y) goto do_clear;
666 roaddir = AXIS_X;
667 break;
669 default: goto do_clear;
672 CommandCost ret = EnsureNoVehicleOnGround(tile);
673 if (ret.Failed()) return ret;
675 if (flags & DC_EXEC) {
676 Track railtrack = AxisToTrack(OtherAxis(roaddir));
677 YapfNotifyTrackLayoutChange(tile, railtrack);
678 /* Update company infrastructure counts. A level crossing has two road bits. */
679 Company *c = Company::GetIfValid(company);
680 if (c != NULL) {
681 c->infrastructure.road[rt] += 2;
682 if (rt != ROADTYPE_ROAD) c->infrastructure.road[ROADTYPE_ROAD] += 2;
683 DirtyCompanyInfrastructureWindows(company);
685 /* Update rail count for level crossings. The plain track is already
686 * counted, so only add the difference to the level crossing cost. */
687 c = Company::GetIfValid(GetTileOwner(tile));
688 if (c != NULL) {
689 c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
690 DirtyCompanyInfrastructureWindows(c->index);
693 /* Always add road to the roadtypes (can't draw without it) */
694 bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
695 MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
696 SetCrossingReservation(tile, reserved);
697 UpdateLevelCrossing(tile, false);
698 MarkTileDirtyByTile(tile);
700 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
703 case MP_STATION: {
704 if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
705 if (!IsDriveThroughStopTile(tile)) goto do_clear;
707 RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
708 if (pieces & ~curbits) goto do_clear;
709 pieces = curbits; // we need to pay for both roadbits
711 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
712 break;
715 case MP_TUNNELBRIDGE: {
716 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
718 const TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
720 if (IsBridge(tile)) {
721 const DiagDirection entrance_dir = GetTunnelBridgeDirection(tile);
722 const RoadBits entrance_piece = DiagDirToRoadBits(entrance_dir);
723 const RoadBits axial_pieces = AxisToRoadBits(DiagDirToAxis(entrance_dir));
724 existing = GetCustomBridgeHeadRoadBits(tile, rt);
726 if (!(_settings_game.construction.road_custom_bridge_heads && HasBridgeFlatRamp(tileh, DiagDirToAxis(entrance_dir))) || disable_custom_bridge_heads) {
727 /* Ordinary bridge heads only */
728 /* Only allow building the outer roadbit, so building long roads stops at existing bridges */
729 if (MirrorRoadBits(entrance_piece) != pieces) goto do_clear;
730 pieces = axial_pieces;
732 if ((existing & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
733 if ((pieces & ~axial_pieces) && !_settings_game.construction.build_on_slopes) {
734 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
737 /* Steep slopes behave the same as slopes with one corner raised. */
738 const Slope normalised_tileh = IsSteepSlope(tileh) ? SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh)) : tileh;
740 if ((_invalid_tileh_slopes_road[0][normalised_tileh & SLOPE_ELEVATED] & (pieces & ~entrance_piece)) != ROAD_NONE) {
741 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
744 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
745 CommandCost ret = TunnelBridgeIsFree(tile, other_end);
746 if (ret.Failed()) return ret;
748 if ((existing | pieces) == entrance_piece) {
750 * Don't allow the custom bridge head bits to be only the entrance piece
751 * as this makes road vehicles go haywire
753 pieces = axial_pieces;
756 RoadBits added_pieces = (existing | pieces) & ~existing;
757 uint added_pieces_count = CountBits(added_pieces);
758 RoadBits other_end_added_pieces = ROAD_NONE;
759 RoadBits other_end_existing = ROAD_NONE;
761 if (added_pieces & entrance_piece) {
762 /* adding road to whole bridge */
764 other_end_added_pieces = MirrorRoadBits(entrance_piece);
765 added_pieces_count += 1 + (GetTunnelBridgeLength(tile, other_end) * 2);
767 other_end_existing = GetCustomBridgeHeadRoadBits(other_end, rt);
768 assert((other_end_added_pieces & other_end_existing) == ROAD_NONE);
770 if (other_end_existing == ROAD_NONE) {
772 * Don't allow the other end custom bridge head bits to be only the entrance piece
773 * as this makes road vehicles go haywire
775 other_end_added_pieces = axial_pieces;
776 added_pieces_count++;
780 cost.AddCost(added_pieces_count * _price[PR_BUILD_ROAD]);
782 if (flags & DC_EXEC) {
783 SubtractRoadTunnelBridgeInfrastructure(tile, other_end);
785 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
786 if (!existing) SetRoadOwner(tile, rt, company);
787 SetCustomBridgeHeadRoadBits(tile, rt, existing | pieces);
788 if (other_end_added_pieces) {
789 SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
790 if (!other_end_existing) SetRoadOwner(other_end, rt, company);
791 SetCustomBridgeHeadRoadBits(other_end, rt, other_end_existing | other_end_added_pieces);
794 MarkBridgeDirty(tile);
796 AddRoadTunnelBridgeInfrastructure(tile, other_end);
797 DirtyAllCompanyInfrastructureWindows();
800 return cost;
801 } else { // IsTunnel(tile)
802 /* Only allow building the outer roadbit, so building long roads stops at existing bridges */
803 if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
804 if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
805 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
806 CommandCost ret = TunnelBridgeIsFree(tile, other_end);
807 if (ret.Failed()) return ret;
809 break;
812 default: {
813 do_clear:;
814 need_to_clear = true;
815 break;
819 if (need_to_clear) {
820 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
821 if (ret.Failed()) return ret;
822 cost.AddCost(ret);
825 if (other_bits != pieces) {
826 /* Check the foundation/slopes when adding road/tram bits */
827 CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
828 /* Return an error if we need to build a foundation (ret != 0) but the
829 * current setting is turned off */
830 if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
831 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
833 cost.AddCost(ret);
836 if (!need_to_clear) {
837 if (IsTileType(tile, MP_ROAD)) {
838 /* Don't put the pieces that already exist */
839 pieces &= ComplementRoadBits(existing);
841 /* Check if new road bits will have the same foundation as other existing road types */
842 if (IsNormalRoad(tile)) {
843 Slope slope = GetTileSlope(tile);
844 Foundation found_new = GetRoadFoundation(slope, pieces | existing);
846 /* Test if all other roadtypes can be built at that foundation */
847 for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
848 if (rtest != rt) { // check only other road types
849 RoadBits bits = GetRoadBits(tile, rtest);
850 /* do not check if there are not road bits of given type */
851 if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
852 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
859 CommandCost ret = EnsureNoVehicleOnGround(tile);
860 if (ret.Failed()) return ret;
864 uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
865 /* There are 2 pieces on *every* tile of the bridge or tunnel */
866 2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
867 /* Count pieces */
868 CountBits(pieces);
870 cost.AddCost(num_pieces * _price[PR_BUILD_ROAD]);
872 if (flags & DC_EXEC) {
873 switch (GetTileType(tile)) {
874 case MP_ROAD: {
875 RoadTileType rtt = GetRoadTileType(tile);
876 if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
877 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
878 SetRoadOwner(tile, rt, company);
879 if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
881 if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
882 break;
885 case MP_TUNNELBRIDGE: {
886 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
888 SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
889 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
890 SetRoadOwner(other_end, rt, company);
891 SetRoadOwner(tile, rt, company);
893 /* Mark tiles dirty that have been repaved */
894 if (IsBridge(tile)) {
895 NOT_REACHED();
896 } else {
897 MarkTileDirtyByTile(other_end);
898 MarkTileDirtyByTile(tile);
900 break;
903 case MP_STATION:
904 assert(IsDriveThroughStopTile(tile));
905 SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
906 SetRoadOwner(tile, rt, company);
907 break;
909 default:
910 MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, company, company);
911 break;
914 /* Update company infrastructure count. */
915 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
916 if (c != NULL) {
917 if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
918 c->infrastructure.road[rt] += num_pieces;
919 DirtyCompanyInfrastructureWindows(c->index);
922 if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
923 existing |= pieces;
924 SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
925 GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
928 MarkTileDirtyByTile(tile);
930 return cost;
934 * Checks whether a road or tram connection can be found when building a new road or tram.
935 * @param tile Tile at which the road being built will end.
936 * @param rt Roadtype of the road being built.
937 * @param dir Direction that the road is following.
938 * @return True if the next tile at dir direction is suitable for being connected directly by a second roadbit at the end of the road being built.
940 static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
942 RoadBits bits = GetAnyRoadBits(tile + TileOffsByDiagDir(dir), rt, false);
943 return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
947 * Build a long piece of road.
948 * @param start_tile start tile of drag (the building cost will appear over this tile)
949 * @param flags operation to perform
950 * @param p1 end tile of drag
951 * @param p2 various bitstuffed elements
952 * - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1). Only used if bit 6 is set or if we are building a single tile
953 * - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2). Only used if bit 6 is set or if we are building a single tile
954 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
955 * - p2 = (bit 3 + 4) - road type
956 * - p2 = (bit 5) - set road direction
957 * - p2 = (bit 6) - defines two different behaviors for this command:
958 * - 0 = Build up to an obstacle. Do not build the first and last roadbits unless they can be connected to something, or if we are building a single tile
959 * - 1 = Fail if an obstacle is found. Always take into account bit 0 and 1. Disable custom bridge heads. This behavior is used for scripts
960 * @param text unused
961 * @return the cost of this operation or an error
963 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
965 DisallowedRoadDirections drd = DRD_NORTHBOUND;
967 if (p1 >= MapSize()) return CMD_ERROR;
969 TileIndex end_tile = p1;
970 RoadType rt = Extract<RoadType, 3, 2>(p2);
971 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
973 Axis axis = Extract<Axis, 2, 1>(p2);
974 /* Only drag in X or Y direction dictated by the direction variable */
975 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
976 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
978 DiagDirection dir = AxisToDiagDir(axis);
980 /* Swap direction, also the half-tile drag var (bit 0 and 1) */
981 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
982 dir = ReverseDiagDir(dir);
983 p2 ^= 3;
984 drd = DRD_SOUTHBOUND;
987 /* On the X-axis, we have to swap the initial bits, so they
988 * will be interpreted correctly in the GTTS. Furthermore
989 * when you just 'click' on one tile to build them. */
990 if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
991 /* No disallowed direction bits have to be toggled */
992 if (!HasBit(p2, 5)) drd = DRD_NONE;
994 CommandCost cost(EXPENSES_CONSTRUCTION);
995 CommandCost last_error = CMD_ERROR;
996 TileIndex tile = start_tile;
997 bool had_success = false;
998 bool is_ai = HasBit(p2, 6);
1000 /* Start tile is the first tile clicked by the user. */
1001 for (;;) {
1002 RoadBits bits = AxisToRoadBits(axis);
1004 /* Determine which road parts should be built. */
1005 if (!is_ai && start_tile != end_tile) {
1006 /* Only build the first and last roadbit if they can connect to something. */
1007 if (tile == end_tile && !CanConnectToRoad(tile, rt, dir)) {
1008 bits = DiagDirToRoadBits(ReverseDiagDir(dir));
1009 } else if (tile == start_tile && !CanConnectToRoad(tile, rt, ReverseDiagDir(dir))) {
1010 bits = DiagDirToRoadBits(dir);
1012 } else {
1013 /* Road parts only have to be built at the start tile or at the end tile. */
1014 if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
1015 if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
1018 CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits | (is_ai ? 1 << 8 : 0), 0, flags, CMD_BUILD_ROAD);
1019 if (ret.Failed()) {
1020 last_error = ret;
1021 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
1022 if (is_ai) return last_error;
1023 break;
1025 } else {
1026 had_success = true;
1027 cost.AddCost(ret);
1030 /* Do not run into or across bridges/tunnels */
1031 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1032 if (GetTunnelBridgeDirection(tile) == dir) break;
1035 if (tile == end_tile) break;
1037 tile += TileOffsByDiagDir(dir);
1039 /* Do not run onto a bridge/tunnel tile from below/above */
1040 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1041 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) break;
1045 return had_success ? cost : last_error;
1049 * Remove a long piece of road.
1050 * @param start_tile start tile of drag
1051 * @param flags operation to perform
1052 * @param p1 end tile of drag
1053 * @param p2 various bitstuffed elements
1054 * - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1)
1055 * - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2)
1056 * - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
1057 * - p2 = (bit 3 + 4) - road type
1058 * @param text unused
1059 * @return the cost of this operation or an error
1061 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1063 CommandCost cost(EXPENSES_CONSTRUCTION);
1065 if (p1 >= MapSize()) return CMD_ERROR;
1067 TileIndex end_tile = p1;
1068 RoadType rt = Extract<RoadType, 3, 2>(p2);
1069 if (!IsValidRoadType(rt)) return CMD_ERROR;
1071 Axis axis = Extract<Axis, 2, 1>(p2);
1072 /* Only drag in X or Y direction dictated by the direction variable */
1073 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
1074 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
1076 /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
1077 if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
1078 TileIndex t = start_tile;
1079 start_tile = end_tile;
1080 end_tile = t;
1081 p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
1084 Money money = GetAvailableMoneyForCommand();
1085 TileIndex tile = start_tile;
1086 CommandCost last_error = CMD_ERROR;
1087 bool had_success = false;
1088 /* Start tile is the small number. */
1089 for (;;) {
1090 RoadBits bits = AxisToRoadBits(axis);
1092 if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
1093 if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
1095 /* try to remove the halves. */
1096 if (bits != 0) {
1097 CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true);
1098 if (ret.Succeeded()) {
1099 if (flags & DC_EXEC) {
1100 money -= ret.GetCost();
1101 if (money < 0) {
1102 _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
1103 return cost;
1105 RemoveRoad(tile, flags, bits, rt, true, false);
1107 cost.AddCost(ret);
1108 had_success = true;
1109 } else {
1110 /* Ownership errors are more important. */
1111 if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
1115 if (tile == end_tile) break;
1117 tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
1120 return had_success ? cost : last_error;
1124 * Build a road depot.
1125 * @param tile tile where to build the depot
1126 * @param flags operation to perform
1127 * @param p1 bit 0..1 entrance direction (DiagDirection)
1128 * bit 2..3 road type
1129 * @param p2 unused
1130 * @param text unused
1131 * @return the cost of this operation or an error
1133 * @todo When checking for the tile slope,
1134 * distinguish between "Flat land required" and "land sloped in wrong direction"
1136 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1138 DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
1139 RoadType rt = Extract<RoadType, 2, 2>(p1);
1141 if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
1143 Slope tileh = GetTileSlope(tile);
1144 if (tileh != SLOPE_FLAT && (
1145 !_settings_game.construction.build_on_slopes ||
1146 !CanBuildDepotByTileh(dir, tileh)
1147 )) {
1148 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
1151 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1152 if (cost.Failed()) return cost;
1154 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1156 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1158 if (flags & DC_EXEC) {
1159 Depot *dep = new Depot(tile);
1160 dep->build_date = _date;
1162 /* A road depot has two road bits. */
1163 Company::Get(_current_company)->infrastructure.road[rt] += 2;
1164 DirtyCompanyInfrastructureWindows(_current_company);
1166 MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
1167 MarkTileDirtyByTile(tile);
1168 MakeDefaultName(dep);
1170 cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
1171 return cost;
1174 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
1176 if (_current_company != OWNER_WATER) {
1177 CommandCost ret = CheckTileOwnership(tile);
1178 if (ret.Failed()) return ret;
1181 CommandCost ret = EnsureNoVehicleOnGround(tile);
1182 if (ret.Failed()) return ret;
1184 if (flags & DC_EXEC) {
1185 Company *c = Company::GetIfValid(GetTileOwner(tile));
1186 if (c != NULL) {
1187 /* A road depot has two road bits. */
1188 c->infrastructure.road[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
1189 DirtyCompanyInfrastructureWindows(c->index);
1192 delete Depot::GetByTile(tile);
1193 DoClearSquare(tile);
1196 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
1199 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
1201 switch (GetRoadTileType(tile)) {
1202 case ROAD_TILE_NORMAL: {
1203 RoadBits b = GetAllRoadBits(tile);
1205 /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
1206 if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
1207 CommandCost ret(EXPENSES_CONSTRUCTION);
1208 RoadType rt;
1209 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1210 CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rt), rt, true);
1211 if (tmp_ret.Failed()) return tmp_ret;
1212 ret.AddCost(tmp_ret);
1214 return ret;
1216 return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1219 case ROAD_TILE_CROSSING: {
1220 RoadTypes rts = GetRoadTypes(tile);
1221 CommandCost ret(EXPENSES_CONSTRUCTION);
1223 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1225 /* Must iterate over the roadtypes in a reverse manner because
1226 * tram tracks must be removed before the road bits. */
1227 RoadType rt = ROADTYPE_TRAM;
1228 do {
1229 if (HasBit(rts, rt)) {
1230 CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rt, false);
1231 if (tmp_ret.Failed()) return tmp_ret;
1232 ret.AddCost(tmp_ret);
1234 } while (rt-- != ROADTYPE_ROAD);
1236 if (flags & DC_EXEC) {
1237 DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1239 return ret;
1242 default:
1243 case ROAD_TILE_DEPOT:
1244 if (flags & DC_AUTO) {
1245 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1247 return RemoveRoadDepot(tile, flags);
1252 struct DrawRoadTileStruct {
1253 uint16 image;
1254 byte subcoord_x;
1255 byte subcoord_y;
1258 #include "table/road_land.h"
1261 * Get the foundationtype of a RoadBits Slope combination
1263 * @param tileh The Slope part
1264 * @param bits The RoadBits part
1265 * @return The resulting Foundation
1267 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
1269 /* Flat land and land without a road doesn't require a foundation */
1270 if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
1272 /* Steep slopes behave the same as slopes with one corner raised. */
1273 if (IsSteepSlope(tileh)) {
1274 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
1277 /* Leveled RoadBits on a slope */
1278 if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
1280 /* Straight roads without foundation on a slope */
1281 if (!IsSlopeWithOneCornerRaised(tileh) &&
1282 (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
1283 return FOUNDATION_NONE;
1285 /* Roads on steep Slopes or on Slopes with one corner raised */
1286 return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
1289 const byte _road_sloped_sprites[14] = {
1290 0, 0, 2, 0,
1291 0, 1, 0, 0,
1292 3, 0, 0, 0,
1293 0, 0
1297 * Should the road be drawn as a unpaved snow/desert road?
1298 * By default, roads are always drawn as unpaved if they are on desert or
1299 * above the snow line, but NewGRFs can override this for desert.
1301 * @param tile The tile the road is on
1302 * @param roadside What sort of road this is
1303 * @return True if snow/desert road sprites should be used.
1305 static bool DrawRoadAsSnowDesert(TileIndex tile, Roadside roadside)
1307 return (IsOnSnow(tile) &&
1308 !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
1309 roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
1313 * Draws the catenary for the given tile
1314 * @param ti information about the tile (slopes, height etc)
1315 * @param tram the roadbits for the tram
1317 void DrawRoadCatenary(const TileInfo *ti, RoadBits tram)
1319 /* Do not draw catenary if it is invisible */
1320 if (IsInvisibilitySet(TO_CATENARY)) return;
1322 /* Don't draw the catenary under a low bridge */
1323 if (IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
1324 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1326 if (height <= GetTileMaxZ(ti->tile) + 1) return;
1329 SpriteID front;
1330 SpriteID back;
1332 if (ti->tileh != SLOPE_FLAT) {
1333 back = SPR_TRAMWAY_BACK_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1334 front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1335 } else {
1336 back = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[tram];
1337 front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
1340 AddSortableSpriteToDraw(back, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1341 AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
1345 * Draws details on/around the road
1346 * @param img the sprite to draw
1347 * @param ti the tile to draw on
1348 * @param dx the offset from the top of the BB of the tile
1349 * @param dy the offset from the top of the BB of the tile
1350 * @param h the height of the sprite to draw
1352 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h)
1354 int x = ti->x | dx;
1355 int y = ti->y | dy;
1356 int z = ti->z;
1357 if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
1358 AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
1362 * Draw ground sprite and road pieces
1363 * @param ti TileInfo
1365 void DrawRoadBits(TileInfo *ti)
1367 const bool is_bridge = IsTileType(ti->tile, MP_TUNNELBRIDGE);
1368 RoadBits road = is_bridge ? GetCustomBridgeHeadRoadBits(ti->tile, ROADTYPE_ROAD) : GetRoadBits(ti->tile, ROADTYPE_ROAD);
1369 RoadBits tram = is_bridge ? GetCustomBridgeHeadRoadBits(ti->tile, ROADTYPE_TRAM) : GetRoadBits(ti->tile, ROADTYPE_TRAM);
1371 SpriteID image = 0;
1372 PaletteID pal = PAL_NONE;
1374 if (ti->tileh != SLOPE_FLAT) {
1375 DrawFoundation(ti, is_bridge ? FOUNDATION_LEVELED : GetRoadFoundation(ti->tileh, road | tram));
1377 /* DrawFoundation() modifies ti.
1378 * Default sloped sprites.. */
1379 if (ti->tileh != SLOPE_FLAT) image = _road_sloped_sprites[ti->tileh - 1] + SPR_ROAD_SLOPE_START;
1382 if (image == 0) image = _road_tile_sprites_1[road != ROAD_NONE ? road : tram];
1384 Roadside roadside = is_bridge ? ROADSIDE_PAVED : GetRoadside(ti->tile);
1386 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1387 image += 19;
1388 } else {
1389 switch (roadside) {
1390 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1391 case ROADSIDE_GRASS: break;
1392 case ROADSIDE_GRASS_ROAD_WORKS: break;
1393 default: image -= 19; break; // Paved
1397 DrawGroundSprite(image, pal);
1399 /* For tram we overlay the road graphics with either tram tracks only
1400 * (when there is actual road beneath the trams) or with tram tracks
1401 * and some dirts which hides the road graphics */
1402 if (tram != ROAD_NONE) {
1403 if (ti->tileh != SLOPE_FLAT) {
1404 image = _road_sloped_sprites[ti->tileh - 1] + SPR_TRAMWAY_SLOPED_OFFSET;
1405 } else {
1406 image = _road_tile_sprites_1[tram] - SPR_ROAD_Y;
1408 image += (road == ROAD_NONE) ? SPR_TRAMWAY_TRAM : SPR_TRAMWAY_OVERLAY;
1409 DrawGroundSprite(image, pal);
1412 if (!is_bridge && road != ROAD_NONE) {
1413 DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
1414 if (drd != DRD_NONE) {
1415 DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
1419 if (!is_bridge && HasRoadWorks(ti->tile)) {
1420 /* Road works */
1421 DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
1422 return;
1425 if (tram != ROAD_NONE) DrawRoadCatenary(ti, tram);
1427 /* Return if full detail is disabled, or we are zoomed fully out. */
1428 if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
1430 /* Do not draw details (street lights, trees) under low bridge */
1431 if (IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
1432 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1433 int minz = GetTileMaxZ(ti->tile) + 2;
1435 if (roadside == ROADSIDE_TREES) minz++;
1437 if (height < minz) return;
1440 /* If there are no road bits, return, as there is nothing left to do */
1441 if (HasAtMostOneBit(road)) return;
1443 /* Draw extra details. */
1444 for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
1445 DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
1449 /** Tile callback function for rendering a road tile to the screen */
1450 static void DrawTile_Road(TileInfo *ti)
1452 switch (GetRoadTileType(ti->tile)) {
1453 case ROAD_TILE_NORMAL:
1454 DrawRoadBits(ti);
1455 DrawOverlay(ti, MP_ROAD);
1456 break;
1458 case ROAD_TILE_CROSSING: {
1459 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1461 DrawOverlay(ti, MP_ROAD);
1463 PaletteID pal = PAL_NONE;
1464 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1466 if (rti->UsesOverlay()) {
1467 Axis axis = GetCrossingRailAxis(ti->tile);
1468 SpriteID road = SPR_ROAD_Y + axis;
1470 Roadside roadside = GetRoadside(ti->tile);
1472 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1473 road += 19;
1474 } else {
1475 switch (roadside) {
1476 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1477 case ROADSIDE_GRASS: break;
1478 default: road -= 19; break; // Paved
1482 DrawGroundSprite(road, pal);
1484 SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
1485 /* Draw tracks, but draw PBS reserved tracks darker. */
1486 pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
1487 DrawGroundSprite(rail, pal);
1489 DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
1490 } else {
1491 SpriteID image = rti->base_sprites.crossing;
1493 if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
1494 if (IsCrossingBarred(ti->tile)) image += 2;
1496 Roadside roadside = GetRoadside(ti->tile);
1498 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1499 image += 8;
1500 } else {
1501 switch (roadside) {
1502 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1503 case ROADSIDE_GRASS: break;
1504 default: image += 4; break; // Paved
1508 DrawGroundSprite(image, pal);
1510 /* PBS debugging, draw reserved tracks darker */
1511 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
1512 DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
1516 if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
1517 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + (GetCrossingRoadAxis(ti->tile) ^ 1), pal);
1518 DrawRoadCatenary(ti, GetCrossingRoadBits(ti->tile));
1520 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
1521 break;
1524 default:
1525 case ROAD_TILE_DEPOT: {
1526 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1528 PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
1530 const DrawTileSprites *dts;
1531 if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
1532 dts = &_tram_depot[GetRoadDepotDirection(ti->tile)];
1533 } else {
1534 dts = &_road_depot[GetRoadDepotDirection(ti->tile)];
1537 DrawGroundSprite(dts->ground.sprite, PAL_NONE);
1538 DrawOverlay(ti, MP_ROAD);
1539 DrawOrigTileSeq(ti, dts, TO_BUILDINGS, palette);
1540 break;
1543 DrawBridgeMiddle(ti);
1547 * Draw the road depot sprite.
1548 * @param x The x offset to draw at.
1549 * @param y The y offset to draw at.
1550 * @param dir The direction the depot must be facing.
1551 * @param rt The road type of the depot to draw.
1553 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
1555 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
1556 const DrawTileSprites *dts = (rt == ROADTYPE_TRAM) ? &_tram_depot[dir] : &_road_depot[dir];
1558 DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
1559 DrawOrigTileSeqInGUI(x, y, dts, palette);
1563 * Updates cached nearest town for all road tiles
1564 * @param invalidate are we just invalidating cached data?
1565 * @pre invalidate == true implies _generating_world == true
1567 void UpdateNearestTownForRoadTiles(bool invalidate)
1569 assert(!invalidate || _generating_world);
1571 for (TileIndex t = 0; t < MapSize(); t++) {
1572 if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1573 TownID tid = (TownID)INVALID_TOWN;
1574 if (!invalidate) {
1575 const Town *town = CalcClosestTownFromTile(t);
1576 if (town != NULL) tid = town->index;
1578 SetTownIndex(t, tid);
1583 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
1586 if (IsNormalRoad(tile)) {
1587 int z;
1588 Slope tileh = GetTilePixelSlope(tile, &z);
1589 if (tileh == SLOPE_FLAT) return z;
1591 Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
1592 z += ApplyPixelFoundationToSlope(f, &tileh);
1593 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
1594 } else {
1595 return GetTileMaxPixelZ(tile);
1599 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
1601 if (IsNormalRoad(tile)) {
1602 return GetRoadFoundation(tileh, GetAllRoadBits(tile));
1603 } else {
1604 return FlatteningFoundation(tileh);
1608 static const Roadside _town_road_types[][2] = {
1609 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1610 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1611 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1612 { ROADSIDE_TREES, ROADSIDE_TREES },
1613 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1616 static const Roadside _town_road_types_2[][2] = {
1617 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1618 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1619 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1620 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1621 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1625 static void TileLoop_Road(TileIndex tile)
1627 switch (_settings_game.game_creation.landscape) {
1628 case LT_ARCTIC:
1629 if (IsOnSnow(tile) != (GetTileMaxZ(tile) > GetSnowLine())) {
1630 ToggleSnow(tile);
1631 MarkTileDirtyByTile(tile);
1633 break;
1635 case LT_TROPIC:
1636 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
1637 ToggleDesert(tile);
1638 MarkTileDirtyByTile(tile);
1640 break;
1643 if (IsRoadDepot(tile)) return;
1645 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
1646 if (!HasRoadWorks(tile)) {
1647 HouseZonesBits grp = HZB_TOWN_EDGE;
1649 if (t != NULL) {
1650 grp = GetTownRadiusGroup(t, tile);
1652 /* Show an animation to indicate road work */
1653 if (t->road_build_months != 0 &&
1654 (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
1655 IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
1656 if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
1657 StartRoadWorks(tile);
1659 if (_settings_client.sound.ambient) SndPlayTileFx(SND_21_JACKHAMMER, tile);
1660 CreateEffectVehicleAbove(
1661 TileX(tile) * TILE_SIZE + 7,
1662 TileY(tile) * TILE_SIZE + 7,
1664 EV_BULLDOZER);
1665 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1666 return;
1672 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
1673 const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
1674 Roadside cur_rs = GetRoadside(tile);
1676 /* We have our desired type, do nothing */
1677 if (cur_rs == new_rs[0]) return;
1679 /* We have the pre-type of the desired type, switch to the desired type */
1680 if (cur_rs == new_rs[1]) {
1681 cur_rs = new_rs[0];
1682 /* We have barren land, install the pre-type */
1683 } else if (cur_rs == ROADSIDE_BARREN) {
1684 cur_rs = new_rs[1];
1685 /* We're totally off limits, remove any installation and make barren land */
1686 } else {
1687 cur_rs = ROADSIDE_BARREN;
1689 SetRoadside(tile, cur_rs);
1690 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1692 } else if (IncreaseRoadWorksCounter(tile)) {
1693 TerminateRoadWorks(tile);
1695 if (_settings_game.economy.mod_road_rebuild) {
1696 /* Generate a nicer town surface */
1697 const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
1698 const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
1700 if (old_rb != new_rb) {
1701 RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), ROADTYPE_ROAD, true);
1705 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1709 static bool ClickTile_Road(TileIndex tile)
1711 if (!IsRoadDepot(tile)) return false;
1713 ShowDepotWindow(tile, VEH_ROAD);
1714 return true;
1717 /* Converts RoadBits to TrackBits */
1718 extern const TrackBits _road_trackbits[16] = {
1719 TRACK_BIT_NONE, // ROAD_NONE
1720 TRACK_BIT_NONE, // ROAD_NW
1721 TRACK_BIT_NONE, // ROAD_SW
1722 TRACK_BIT_LEFT, // ROAD_W
1723 TRACK_BIT_NONE, // ROAD_SE
1724 TRACK_BIT_Y, // ROAD_Y
1725 TRACK_BIT_LOWER, // ROAD_S
1726 TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y, // ROAD_Y | ROAD_SW
1727 TRACK_BIT_NONE, // ROAD_NE
1728 TRACK_BIT_UPPER, // ROAD_N
1729 TRACK_BIT_X, // ROAD_X
1730 TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X, // ROAD_X | ROAD_NW
1731 TRACK_BIT_RIGHT, // ROAD_E
1732 TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
1733 TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
1734 TRACK_BIT_ALL, // ROAD_ALL
1737 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
1739 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
1740 TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
1741 switch (mode) {
1742 case TRANSPORT_RAIL:
1743 if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
1744 break;
1746 case TRANSPORT_ROAD:
1747 if ((GetRoadTypes(tile) & sub_mode) == 0) break;
1748 switch (GetRoadTileType(tile)) {
1749 case ROAD_TILE_NORMAL: {
1750 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
1751 RoadType rt = (RoadType)FindFirstBit(sub_mode);
1752 RoadBits bits = GetRoadBits(tile, rt);
1754 /* no roadbit at this side of tile, return 0 */
1755 if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
1757 uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
1758 if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
1759 break;
1762 case ROAD_TILE_CROSSING: {
1763 Axis axis = GetCrossingRoadAxis(tile);
1765 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
1767 trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
1768 if (IsCrossingBarred(tile)) red_signals = trackdirbits;
1769 if (IsLevelCrossingTile(TileAddByDiagDir(tile, AxisToDiagDir(axis))) &&
1770 IsCrossingBarred(TileAddByDiagDir(tile, AxisToDiagDir(axis)))) {
1771 red_signals &= (TrackdirBits)0x0102; // magic value. I think TRACKBIT_X_SW and TRACKBIT_X_NE should be swapped
1773 if (IsLevelCrossingTile(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis)))) &&
1774 IsCrossingBarred(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis))))) {
1775 red_signals &= (TrackdirBits)0x0201; // inverse of above magic value
1777 break;
1780 default:
1781 case ROAD_TILE_DEPOT: {
1782 DiagDirection dir = GetRoadDepotDirection(tile);
1784 if (side != INVALID_DIAGDIR && side != dir) break;
1786 trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
1787 break;
1790 break;
1792 default: break;
1794 return CombineTrackStatus(trackdirbits, red_signals);
1797 static const StringID _road_tile_strings[] = {
1798 STR_LAI_ROAD_DESCRIPTION_ROAD,
1799 STR_LAI_ROAD_DESCRIPTION_ROAD,
1800 STR_LAI_ROAD_DESCRIPTION_ROAD,
1801 STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
1802 STR_LAI_ROAD_DESCRIPTION_ROAD,
1803 STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
1804 STR_LAI_ROAD_DESCRIPTION_ROAD,
1805 STR_LAI_ROAD_DESCRIPTION_ROAD,
1808 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
1810 Owner rail_owner = INVALID_OWNER;
1811 Owner road_owner = INVALID_OWNER;
1812 Owner tram_owner = INVALID_OWNER;
1814 switch (GetRoadTileType(tile)) {
1815 case ROAD_TILE_CROSSING: {
1816 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
1817 RoadTypes rts = GetRoadTypes(tile);
1818 rail_owner = GetTileOwner(tile);
1819 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1820 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1822 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
1823 td->railtype = rti->strings.name;
1824 td->rail_speed = rti->max_speed;
1826 break;
1829 case ROAD_TILE_DEPOT:
1830 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
1831 road_owner = GetTileOwner(tile); // Tile has only one owner, roadtype does not matter
1832 td->build_date = Depot::GetByTile(tile)->build_date;
1833 break;
1835 default: {
1836 RoadTypes rts = GetRoadTypes(tile);
1837 td->str = (HasBit(rts, ROADTYPE_ROAD) ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
1838 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
1839 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
1840 break;
1844 /* Now we have to discover, if the tile has only one owner or many:
1845 * - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
1846 * - Compare the found owner with the other owners, and test if they differ.
1847 * Note: If road exists it will be the first_owner.
1849 Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
1850 bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
1852 if (mixed_owners) {
1853 /* Multiple owners */
1854 td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
1855 td->owner[0] = rail_owner;
1856 td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
1857 td->owner[1] = road_owner;
1858 td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
1859 td->owner[2] = tram_owner;
1860 } else {
1861 /* One to rule them all */
1862 td->owner[0] = first_owner;
1867 * Given the direction the road depot is pointing, this is the direction the
1868 * vehicle should be travelling in in order to enter the depot.
1870 static const byte _roadveh_enter_depot_dir[4] = {
1871 TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
1874 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
1876 switch (GetRoadTileType(tile)) {
1877 case ROAD_TILE_DEPOT: {
1878 if (v->type != VEH_ROAD) break;
1880 RoadVehicle *rv = RoadVehicle::From(v);
1881 if (rv->frame == RVC_DEPOT_STOP_FRAME &&
1882 _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
1883 rv->state = RVSB_IN_DEPOT;
1884 rv->vehstatus |= VS_HIDDEN;
1885 rv->direction = ReverseDir(rv->direction);
1886 if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
1887 rv->tile = tile;
1889 InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
1890 return VETSB_ENTERED_WORMHOLE;
1892 break;
1895 default: break;
1897 return VETSB_CONTINUE;
1901 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
1903 if (IsRoadDepot(tile)) {
1904 if (GetTileOwner(tile) == old_owner) {
1905 if (new_owner == INVALID_OWNER) {
1906 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
1907 } else {
1908 /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
1909 RoadType rt = (RoadType)FIND_FIRST_BIT(GetRoadTypes(tile));
1910 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
1911 Company::Get(new_owner)->infrastructure.road[rt] += 2;
1913 SetTileOwner(tile, new_owner);
1914 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1915 if (GetRoadOwner(tile, rt) == old_owner) {
1916 SetRoadOwner(tile, rt, new_owner);
1921 return;
1924 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1925 /* Update all roadtypes, no matter if they are present */
1926 if (GetRoadOwner(tile, rt) == old_owner) {
1927 if (HasTileRoadType(tile, rt)) {
1928 /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
1929 uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
1930 Company::Get(old_owner)->infrastructure.road[rt] -= num_bits;
1931 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_bits;
1934 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
1938 if (IsLevelCrossing(tile)) {
1939 if (GetTileOwner(tile) == old_owner) {
1940 if (new_owner == INVALID_OWNER) {
1941 DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
1942 } else {
1943 /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
1944 Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
1945 Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
1947 SetTileOwner(tile, new_owner);
1953 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
1955 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
1956 switch (GetRoadTileType(tile)) {
1957 case ROAD_TILE_CROSSING:
1958 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) && HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1959 break;
1961 case ROAD_TILE_DEPOT:
1962 if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1963 break;
1965 case ROAD_TILE_NORMAL: {
1966 RoadBits bits = GetAllRoadBits(tile);
1967 RoadBits bits_copy = bits;
1968 /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
1969 if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
1970 /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
1971 if (bits == bits_copy) {
1972 int z_old;
1973 Slope tileh_old = GetTileSlope(tile, &z_old);
1975 /* Get the slope on top of the foundation */
1976 z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
1977 z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
1979 /* The surface slope must not be changed */
1980 if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
1983 break;
1986 default: NOT_REACHED();
1990 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1993 /** Tile callback functions for road tiles */
1994 extern const TileTypeProcs _tile_type_road_procs = {
1995 DrawTile_Road, // draw_tile_proc
1996 GetSlopePixelZ_Road, // get_slope_z_proc
1997 ClearTile_Road, // clear_tile_proc
1998 NULL, // add_accepted_cargo_proc
1999 GetTileDesc_Road, // get_tile_desc_proc
2000 GetTileTrackStatus_Road, // get_tile_track_status_proc
2001 ClickTile_Road, // click_tile_proc
2002 NULL, // animate_tile_proc
2003 TileLoop_Road, // tile_loop_proc
2004 ChangeTileOwner_Road, // change_tile_owner_proc
2005 NULL, // add_produced_cargo_proc
2006 VehicleEnter_Road, // vehicle_enter_tile_proc
2007 GetFoundation_Road, // get_foundation_proc
2008 TerraformTile_Road, // terraform_tile_proc