# road_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "cmd_helper.h"
    00014 #include "road_internal.h"
    00015 #include "viewport_func.h"
    00016 #include "command_func.h"
    00017 #include "pathfinder/yapf/yapf_cache.h"
    00018 #include "depot_base.h"
    00019 #include "newgrf.h"
    00020 #include "autoslope.h"
    00021 #include "tunnelbridge_map.h"
    00022 #include "window_func.h"
    00023 #include "strings_func.h"
    00024 #include "vehicle_func.h"
    00025 #include "sound_func.h"
    00026 #include "tunnelbridge.h"
    00027 #include "cheat_type.h"
    00028 #include "effectvehicle_func.h"
    00029 #include "effectvehicle_base.h"
    00030 #include "elrail_func.h"
    00031 #include "roadveh.h"
    00032 #include "town.h"
    00033 #include "company_base.h"
    00034 #include "core/random_func.hpp"
    00035 #include "newgrf_railtype.h"
    00036 #include "date_func.h"
    00037 #include "genworld.h"
    00038 #include "trafficlight_func.h"
    00039 #include "company_gui.h"
    00040
    00041 #include "table/strings.h"
    00042
    00047 bool RoadVehiclesAreBuilt()
    00048 {
    00049   const RoadVehicle *rv;
    00050   FOR_ALL_ROADVEHICLES(rv) return true;
    00051
    00052   return false;
    00053 }
    00054
    00056 static const RoadBits _invalid_tileh_slopes_road[2][15] = {
    00057   /* The inverse of the mixable RoadBits on a leveled slope */
    00058   {
    00059     ROAD_NONE,         // SLOPE_FLAT
    00060     ROAD_NE | ROAD_SE, // SLOPE_W
    00061     ROAD_NE | ROAD_NW, // SLOPE_S
    00062
    00063     ROAD_NE,           // SLOPE_SW
    00064     ROAD_NW | ROAD_SW, // SLOPE_E
    00065     ROAD_NONE,         // SLOPE_EW
    00066
    00067     ROAD_NW,           // SLOPE_SE
    00068     ROAD_NONE,         // SLOPE_WSE
    00069     ROAD_SE | ROAD_SW, // SLOPE_N
    00070
    00071     ROAD_SE,           // SLOPE_NW
    00072     ROAD_NONE,         // SLOPE_NS
    00073     ROAD_NONE,         // SLOPE_ENW
    00074
    00075     ROAD_SW,           // SLOPE_NE
    00076     ROAD_NONE,         // SLOPE_SEN
    00077     ROAD_NONE          // SLOPE_NWS
    00078   },
    00079   /* The inverse of the allowed straight roads on a slope
    00080    * (with and without a foundation). */
    00081   {
    00082     ROAD_NONE, // SLOPE_FLAT
    00083     ROAD_NONE, // SLOPE_W    Foundation
    00084     ROAD_NONE, // SLOPE_S    Foundation
    00085
    00086     ROAD_Y,    // SLOPE_SW
    00087     ROAD_NONE, // SLOPE_E    Foundation
    00088     ROAD_ALL,  // SLOPE_EW
    00089
    00090     ROAD_X,    // SLOPE_SE
    00091     ROAD_ALL,  // SLOPE_WSE
    00092     ROAD_NONE, // SLOPE_N    Foundation
    00093
    00094     ROAD_X,    // SLOPE_NW
    00095     ROAD_ALL,  // SLOPE_NS
    00096     ROAD_ALL,  // SLOPE_ENW
    00097
    00098     ROAD_Y,    // SLOPE_NE
    00099     ROAD_ALL,  // SLOPE_SEN
    00100     ROAD_ALL   // SLOPE_NW
    00101   }
    00102 };
    00103
    00104 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
    00105
    00116 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
    00117 {
    00118   if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
    00119
    00120   /* Water can always flood and towns can always remove "normal" road pieces.
    00121    * Towns are not be allowed to remove non "normal" road pieces, like tram
    00122    * tracks as that would result in trams that cannot turn. */
    00123   if (_current_company == OWNER_WATER ||
    00124       (rt == ROADTYPE_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
    00125
    00126   /* Only do the special processing if the road is owned
    00127    * by a town */
    00128   if (owner != OWNER_TOWN) {
    00129     if (owner == OWNER_NONE) return CommandCost();
    00130     CommandCost ret = CheckOwnership(owner);
    00131     return ret;
    00132   }
    00133
    00134   if (!town_check) return CommandCost();
    00135
    00136   if (_cheats.magic_bulldozer.value) return CommandCost();
    00137
    00138   Town *t = ClosestTownFromTile(tile, UINT_MAX);
    00139   if (t == NULL) return CommandCost();
    00140
    00141   /* check if you're allowed to remove the street owned by a town
    00142    * removal allowance depends on difficulty setting */
    00143   CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
    00144   if (ret.Failed()) return ret;
    00145
    00146   /* Get a bitmask of which neighbouring roads has a tile */
    00147   RoadBits n = ROAD_NONE;
    00148   RoadBits present = GetAnyRoadBits(tile, rt);
    00149   if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1,  0), rt) & ROAD_SW)) n |= ROAD_NE;
    00150   if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile,  0,  1), rt) & ROAD_NW)) n |= ROAD_SE;
    00151   if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile,  1,  0), rt) & ROAD_NE)) n |= ROAD_SW;
    00152   if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile,  0, -1), rt) & ROAD_SE)) n |= ROAD_NW;
    00153
    00154   int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
    00155   /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
    00156    * then allow it */
    00157   if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
    00158     /* you can remove all kind of roads with extra dynamite */
    00159     if (!_settings_game.construction.extra_dynamite) {
    00160       SetDParam(0, t->index);
    00161       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
    00162     }
    00163     rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
    00164   }
    00165   ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
    00166
    00167   return CommandCost();
    00168 }
    00169
    00170
    00181 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadType rt, bool crossing_check, bool trafficlights_check, bool town_check = true)
    00182 {
    00183   RoadTypes rts = GetRoadTypes(tile);
    00184   /* The tile doesn't have the given road type */
    00185   if (!HasBit(rts, rt)) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
    00186
    00187   switch (GetTileType(tile)) {
    00188     case MP_ROAD: {
    00189       CommandCost ret = EnsureNoVehicleOnGround(tile);
    00190       if (ret.Failed()) return ret;
    00191       break;
    00192     }
    00193
    00194     case MP_STATION: {
    00195       if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
    00196
    00197       CommandCost ret = EnsureNoVehicleOnGround(tile);
    00198       if (ret.Failed()) return ret;
    00199       break;
    00200     }
    00201
    00202     case MP_TUNNELBRIDGE: {
    00203       if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
    00204       CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
    00205       if (ret.Failed()) return ret;
    00206       break;
    00207     }
    00208
    00209     default:
    00210       return CMD_ERROR;
    00211   }
    00212
    00213   CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rt), rt, flags, town_check);
    00214   if (ret.Failed()) return ret;
    00215
    00216   if (!IsTileType(tile, MP_ROAD)) {
    00217     /* If it's the last roadtype, just clear the whole tile */
    00218     if (rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00219
    00220     CommandCost cost(EXPENSES_CONSTRUCTION);
    00221     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    00222       TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
    00223       /* Pay for *every* tile of the bridge or tunnel */
    00224       uint len = GetTunnelBridgeLength(other_end, tile) + 2;
    00225       cost.AddCost(len * _price[PR_CLEAR_ROAD]);
    00226       if (flags & DC_EXEC) {
    00227         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    00228         if (c != NULL) {
    00229           /* A full diagonal road tile has two road bits. */
    00230           c->road_infrastructure[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
    00231           DirtyCompanyInfrastructureWindows(c->index);
    00232         }
    00233
    00234         SetRoadTypes(other_end, GetRoadTypes(other_end) & ~RoadTypeToRoadTypes(rt));
    00235         SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
    00236
    00237         /* If the owner of the bridge sells all its road, also move the ownership
    00238          * to the owner of the other roadtype. */
    00239         RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
    00240         Owner other_owner = GetRoadOwner(tile, other_rt);
    00241         if (other_owner != GetTileOwner(tile)) {
    00242           SetTileOwner(tile, other_owner);
    00243           SetTileOwner(other_end, other_owner);
    00244         }
    00245
    00246         /* Mark tiles dirty that have been repaved */
    00247         MarkTileDirtyByTile(tile);
    00248         MarkTileDirtyByTile(other_end);
    00249         if (IsBridge(tile)) {
    00250           TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
    00251
    00252           for (TileIndex t = tile + delta; t != other_end; t += delta) MarkTileDirtyByTile(t);
    00253         }
    00254       }
    00255     } else {
    00256       assert(IsDriveThroughStopTile(tile));
    00257       cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
    00258       if (flags & DC_EXEC) {
    00259       Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    00260         if (c != NULL) {
    00261           /* A full diagonal road tile has two road bits. */
    00262           c->road_infrastructure[rt] -= 2;
    00263           DirtyCompanyInfrastructureWindows(c->index);
    00264         }
    00265         SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
    00266         MarkTileDirtyByTile(tile);
    00267       }
    00268     }
    00269     return cost;
    00270   }
    00271
    00272   switch (GetRoadTileType(tile)) {
    00273     case ROAD_TILE_NORMAL: {
    00274       const Slope tileh = GetTileSlope(tile, NULL);
    00275       RoadBits present = GetRoadBits(tile, rt);
    00276       const RoadBits other = GetOtherRoadBits(tile, rt);
    00277       const Foundation f = GetRoadFoundation(tileh, present);
    00278
    00279       if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
    00280
    00281       /* Autocomplete to a straight road
    00282        * @li on steep slopes
    00283        * @li if the bits of the other roadtypes result in another foundation
    00284        * @li if build on slopes is disabled */
    00285       if (IsSteepSlope(tileh) || (IsStraightRoad(other) &&
    00286           (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
    00287           (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
    00288         pieces |= MirrorRoadBits(pieces);
    00289       }
    00290
    00291       /* limit the bits to delete to the existing bits. */
    00292       pieces &= present;
    00293       if (pieces == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
    00294
    00295       /* Now set present what it will be after the remove */
    00296       present ^= pieces;
    00297
    00298       /* Check if traffic lights are present and if removing them would cause the tile to have less than three roadbits (of any kind!). */
    00299       if (trafficlights_check && HasTrafficLights(tile) && (CountBits(present | GetOtherRoadBits(tile, rt)) < 3)) {
    00300         return_cmd_error(STR_ERROR_MUST_REMOVE_TRAFFIC_LIGHTS_FIRST);
    00301       }
    00302
    00303       /* Check for invalid RoadBit combinations on slopes */
    00304       if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
    00305           (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
    00306         return CMD_ERROR;
    00307       }
    00308
    00309       if (flags & DC_EXEC) {
    00310         if (HasRoadWorks(tile)) {
    00311           /* flooding tile with road works, don't forget to remove the effect vehicle too */
    00312           assert(_current_company == OWNER_WATER);
    00313           EffectVehicle *v;
    00314           FOR_ALL_EFFECTVEHICLES(v) {
    00315             if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
    00316               delete v;
    00317             }
    00318           }
    00319         }
    00320
    00321         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    00322         if (c != NULL) {
    00323           c->road_infrastructure[rt] -= CountBits(pieces);
    00324           DirtyCompanyInfrastructureWindows(c->index);
    00325         }
    00326
    00327         if (present == ROAD_NONE) {
    00328           RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
    00329           if (rts == ROADTYPES_NONE) {
    00330             /* Includes MarkTileDirtyByTile() */
    00331             DoClearSquare(tile);
    00332           } else {
    00333             if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
    00334               /* Update nearest-town index */
    00335               const Town *town = CalcClosestTownFromTile(tile);
    00336               SetTownIndex(tile, town == NULL ? (TownID)INVALID_TOWN : town->index);
    00337             }
    00338             SetRoadBits(tile, ROAD_NONE, rt);
    00339             SetRoadTypes(tile, rts);
    00340             MarkTileDirtyByTile(tile);
    00341           }
    00342         } else {
    00343           /* When bits are removed, you *always* end up with something that
    00344            * is not a complete straight road tile. However, trams do not have
    00345            * onewayness, so they cannot remove it either. */
    00346           if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
    00347           SetRoadBits(tile, present, rt);
    00348           MarkTileDirtyByTile(tile);
    00349         }
    00350       }
    00351
    00352       CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
    00353       /* If we build a foundation we have to pay for it. */
    00354       if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
    00355
    00356       return cost;
    00357     }
    00358
    00359     case ROAD_TILE_CROSSING: {
    00360       if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
    00361         return CMD_ERROR;
    00362       }
    00363
    00364       /* Don't allow road to be removed from the crossing when there is tram;
    00365        * we can't draw the crossing without roadbits ;) */
    00366       if (rt == ROADTYPE_ROAD && HasTileRoadType(tile, ROADTYPE_TRAM) && (flags & DC_EXEC || crossing_check)) return CMD_ERROR;
    00367
    00368       if (flags & DC_EXEC) {
    00369         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    00370         if (c != NULL) {
    00371           /* A full diagonal road tile has two road bits. */
    00372           c->road_infrastructure[rt] -= 2;
    00373           DirtyCompanyInfrastructureWindows(c->index);
    00374         }
    00375
    00376         Track railtrack = GetCrossingRailTrack(tile);
    00377         RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
    00378         if (rts == ROADTYPES_NONE) {
    00379           TrackBits tracks = GetCrossingRailBits(tile);
    00380           bool reserved = HasCrossingReservation(tile);
    00381           MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
    00382           if (reserved) SetTrackReservation(tile, tracks);
    00383
    00384           /* Update rail count for level crossings. The plain track should still be accounted
    00385            * for, so only subtract the difference to the level crossing cost. */
    00386           c = Company::GetIfValid(GetTileOwner(tile));
    00387           if (c != NULL) c->rail_infrastructure[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
    00388         } else {
    00389           SetRoadTypes(tile, rts);
    00390           /* If we ever get HWAY and it is possible without road then we will need to promote ownership and invalidate town index here, too */
    00391         }
    00392         MarkTileDirtyByTile(tile);
    00393         YapfNotifyTrackLayoutChange(tile, railtrack);
    00394       }
    00395       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
    00396     }
    00397
    00398     default:
    00399     case ROAD_TILE_DEPOT:
    00400       return CMD_ERROR;
    00401   }
    00402 }
    00403
    00404
    00416 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
    00417 {
    00418   /* Remove already build pieces */
    00419   CLRBITS(*pieces, existing);
    00420
    00421   /* If we can't build anything stop here */
    00422   if (*pieces == ROAD_NONE) return CMD_ERROR;
    00423
    00424   /* All RoadBit combos are valid on flat land */
    00425   if (tileh == SLOPE_FLAT) return CommandCost();
    00426
    00427   /* Proceed steep Slopes first to reduce lookup table size */
    00428   if (IsSteepSlope(tileh)) {
    00429     /* Force straight roads. */
    00430     *pieces |= MirrorRoadBits(*pieces);
    00431
    00432     /* Use existing as all existing since only straight
    00433      * roads are allowed here. */
    00434     existing |= other;
    00435
    00436     if ((existing == ROAD_NONE || existing == *pieces) && IsStraightRoad(*pieces)) {
    00437       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00438     }
    00439     return CMD_ERROR;
    00440   }
    00441
    00442   /* Save the merge of all bits of the current type */
    00443   RoadBits type_bits = existing | *pieces;
    00444
    00445   /* Roads on slopes */
    00446   if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
    00447
    00448     /* If we add leveling we've got to pay for it */
    00449     if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00450
    00451     return CommandCost();
    00452   }
    00453
    00454   /* Autocomplete uphill roads */
    00455   *pieces |= MirrorRoadBits(*pieces);
    00456   type_bits = existing | *pieces;
    00457
    00458   /* Uphill roads */
    00459   if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
    00460       (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
    00461
    00462     /* Slopes with foundation ? */
    00463     if (IsSlopeWithOneCornerRaised(tileh)) {
    00464
    00465       /* Prevent build on slopes if it isn't allowed */
    00466       if (_settings_game.construction.build_on_slopes) {
    00467
    00468         /* If we add foundation we've got to pay for it */
    00469         if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00470
    00471         return CommandCost();
    00472       }
    00473     } else {
    00474       if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    00475       return CommandCost();
    00476     }
    00477   }
    00478   return CMD_ERROR;
    00479 }
    00480
    00492 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00493 {
    00494   CommandCost cost(EXPENSES_CONSTRUCTION);
    00495
    00496   RoadBits existing = ROAD_NONE;
    00497   RoadBits other_bits = ROAD_NONE;
    00498
    00499   /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
    00500    * if a non-company is building the road */
    00501   if ((Company::IsValidID(_current_company) && p2 != 0) || (_current_company == OWNER_TOWN && !Town::IsValidID(p2))) return CMD_ERROR;
    00502   if (_current_company != OWNER_TOWN) {
    00503     const Town *town = CalcClosestTownFromTile(tile);
    00504     p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
    00505   }
    00506
    00507   RoadBits pieces = Extract<RoadBits, 0, 4>(p1);
    00508
    00509   /* do not allow building 'zero' road bits, code wouldn't handle it */
    00510   if (pieces == ROAD_NONE) return CMD_ERROR;
    00511
    00512   RoadType rt = Extract<RoadType, 4, 2>(p1);
    00513   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
    00514
    00515   DisallowedRoadDirections toggle_drd = Extract<DisallowedRoadDirections, 6, 2>(p1);
    00516
    00517   Slope tileh = GetTileSlope(tile, NULL);
    00518
    00519   bool need_to_clear = false;
    00520   switch (GetTileType(tile)) {
    00521     case MP_ROAD:
    00522       switch (GetRoadTileType(tile)) {
    00523         case ROAD_TILE_NORMAL: {
    00524           if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
    00525
    00526           other_bits = GetOtherRoadBits(tile, rt);
    00527           if (!HasTileRoadType(tile, rt)) break;
    00528
    00529           existing = GetRoadBits(tile, rt);
    00530           bool crossing = !IsStraightRoad(existing | pieces);
    00531           if (rt != ROADTYPE_TRAM && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
    00532             /* Junctions cannot be one-way */
    00533             return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
    00534           }
    00535           if ((existing & pieces) == pieces) {
    00536             /* We only want to set the (dis)allowed road directions */
    00537             if (toggle_drd != DRD_NONE && rt != ROADTYPE_TRAM) {
    00538               if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
    00539
    00540               Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    00541               if (owner != OWNER_NONE) {
    00542                 CommandCost ret = CheckOwnership(owner, tile);
    00543                 if (ret.Failed()) return ret;
    00544               }
    00545
    00546               DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
    00547               DisallowedRoadDirections dis_new      = dis_existing ^ toggle_drd;
    00548
    00549               /* We allow removing disallowed directions to break up
    00550                * deadlocks, but adding them can break articulated
    00551                * vehicles. As such, only when less is disallowed,
    00552                * i.e. bits are removed, we skip the vehicle check. */
    00553               if (CountBits(dis_existing) <= CountBits(dis_new)) {
    00554                 CommandCost ret = EnsureNoVehicleOnGround(tile);
    00555                 if (ret.Failed()) return ret;
    00556               }
    00557
    00558               /* Ignore half built tiles */
    00559               if ((flags & DC_EXEC) && rt != ROADTYPE_TRAM && IsStraightRoad(existing)) {
    00560                 SetDisallowedRoadDirections(tile, dis_new);
    00561                 MarkTileDirtyByTile(tile);
    00562               }
    00563               return CommandCost();
    00564             }
    00565             return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00566           }
    00567           break;
    00568         }
    00569
    00570         case ROAD_TILE_CROSSING:
    00571           other_bits = GetCrossingRoadBits(tile);
    00572           if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
    00573           pieces = other_bits; // we need to pay for both roadbits
    00574
    00575           if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00576           break;
    00577
    00578         case ROAD_TILE_DEPOT:
    00579           if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00580           goto do_clear;
    00581
    00582         default: NOT_REACHED();
    00583       }
    00584       break;
    00585
    00586     case MP_RAILWAY: {
    00587       if (IsSteepSlope(tileh)) {
    00588         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00589       }
    00590
    00591       /* Level crossings may only be built on these slopes */
    00592       if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
    00593         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00594       }
    00595
    00596       if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
    00597
    00598       if (RailNoLevelCrossings(GetRailType(tile))) {
    00599         return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
    00600       }
    00601
    00602       Axis roaddir;
    00603       switch (GetTrackBits(tile)) {
    00604         case TRACK_BIT_X:
    00605           if (pieces & ROAD_X) goto do_clear;
    00606           roaddir = AXIS_Y;
    00607           break;
    00608
    00609         case TRACK_BIT_Y:
    00610           if (pieces & ROAD_Y) goto do_clear;
    00611           roaddir = AXIS_X;
    00612           break;
    00613
    00614         default: goto do_clear;
    00615       }
    00616
    00617       CommandCost ret = EnsureNoVehicleOnGround(tile);
    00618       if (ret.Failed()) return ret;
    00619
    00620       if (flags & DC_EXEC) {
    00621         Track railtrack = AxisToTrack(OtherAxis(roaddir));
    00622         YapfNotifyTrackLayoutChange(tile, railtrack);
    00623         /* Update company infrastructure counts. A level crossing has two road bits. */
    00624         Company *c = Company::GetIfValid(_current_company);
    00625         if (c != NULL) {
    00626           c->road_infrastructure[rt] += 2;
    00627           if (rt != ROADTYPE_ROAD) c->road_infrastructure[ROADTYPE_ROAD] += 2;
    00628           DirtyCompanyInfrastructureWindows(_current_company);
    00629         }
    00630         /* Update rail count for level crossings. The plain track is already
    00631          * counted, so only add the difference to the level crossing cost. */
    00632         c = Company::GetIfValid(GetTileOwner(tile));
    00633         if (c != NULL) c->rail_infrastructure[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
    00634
    00635         /* Always add road to the roadtypes (can't draw without it) */
    00636         bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
    00637         MakeRoadCrossing(tile, _current_company, _current_company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
    00638         SetCrossingReservation(tile, reserved);
    00639         UpdateLevelCrossing(tile, false);
    00640         MarkTileDirtyByTile(tile);
    00641       }
    00642       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
    00643     }
    00644
    00645     case MP_STATION: {
    00646       if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00647       if (!IsDriveThroughStopTile(tile)) goto do_clear;
    00648
    00649       RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
    00650       if (pieces & ~curbits) goto do_clear;
    00651       pieces = curbits; // we need to pay for both roadbits
    00652
    00653       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00654       break;
    00655     }
    00656
    00657     case MP_TUNNELBRIDGE: {
    00658       if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
    00659       if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
    00660       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
    00661       /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
    00662       CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
    00663       if (ret.Failed()) return ret;
    00664       break;
    00665     }
    00666
    00667     default: {
    00668 do_clear:;
    00669       need_to_clear = true;
    00670       break;
    00671     }
    00672   }
    00673
    00674   if (need_to_clear) {
    00675     CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00676     if (ret.Failed()) return ret;
    00677     cost.AddCost(ret);
    00678   }
    00679
    00680   if (other_bits != pieces) {
    00681     /* Check the foundation/slopes when adding road/tram bits */
    00682     CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
    00683     /* Return an error if we need to build a foundation (ret != 0) but the
    00684      * current setting is turned off */
    00685     if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
    00686       return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00687     }
    00688     cost.AddCost(ret);
    00689   }
    00690
    00691   if (!need_to_clear) {
    00692     if (IsTileType(tile, MP_ROAD)) {
    00693       /* Don't put the pieces that already exist */
    00694       pieces &= ComplementRoadBits(existing);
    00695
    00696       /* Check if new road bits will have the same foundation as other existing road types */
    00697       if (IsNormalRoad(tile)) {
    00698         Slope slope = GetTileSlope(tile, NULL);
    00699         Foundation found_new = GetRoadFoundation(slope, pieces | existing);
    00700
    00701         /* Test if all other roadtypes can be built at that foundation */
    00702         for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
    00703           if (rtest != rt) { // check only other road types
    00704             RoadBits bits = GetRoadBits(tile, rtest);
    00705             /* do not check if there are not road bits of given type */
    00706             if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
    00707               return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
    00708             }
    00709           }
    00710         }
    00711       }
    00712     }
    00713
    00714     CommandCost ret = EnsureNoVehicleOnGround(tile);
    00715     if (ret.Failed()) return ret;
    00716
    00717   }
    00718   cost.AddCost(CountBits(pieces) * _price[PR_BUILD_ROAD]);
    00719
    00720   if (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) {
    00721     /* Pay for *every* tile of the bridge or tunnel */
    00722     cost.MultiplyCost(GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2);
    00723   }
    00724
    00725   if (flags & DC_EXEC) {
    00726     switch (GetTileType(tile)) {
    00727       case MP_ROAD: {
    00728         RoadTileType rtt = GetRoadTileType(tile);
    00729         if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
    00730           SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
    00731           SetRoadOwner(tile, rt, _current_company);
    00732           if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
    00733         }
    00734         if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
    00735         break;
    00736       }
    00737
    00738       case MP_TUNNELBRIDGE: {
    00739         TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
    00740
    00741         SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
    00742         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
    00743         SetRoadOwner(other_end, rt, _current_company);
    00744         SetRoadOwner(tile, rt, _current_company);
    00745
    00746         /* Mark tiles dirty that have been repaved */
    00747         MarkTileDirtyByTile(other_end);
    00748         MarkTileDirtyByTile(tile);
    00749         if (IsBridge(tile)) {
    00750           TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
    00751
    00752           for (TileIndex t = tile + delta; t != other_end; t += delta) MarkTileDirtyByTile(t);
    00753         }
    00754         break;
    00755       }
    00756
    00757       case MP_STATION:
    00758         assert(IsDriveThroughStopTile(tile));
    00759         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
    00760         SetRoadOwner(tile, rt, _current_company);
    00761         break;
    00762
    00763       default:
    00764         MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, _current_company, _current_company);
    00765         break;
    00766     }
    00767
    00768     /* Update company infrastructure count. */
    00769     Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
    00770     if (c != NULL) {
    00771       uint num_pieces = CountBits(pieces);
    00772       if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
    00773       c->road_infrastructure[rt] += num_pieces;
    00774       DirtyCompanyInfrastructureWindows(c->index);
    00775     }
    00776
    00777     if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
    00778       existing |= pieces;
    00779       SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
    00780           GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
    00781     }
    00782
    00783     MarkTileDirtyByTile(tile);
    00784   }
    00785   return cost;
    00786 }
    00787
    00803 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00804 {
    00805   DisallowedRoadDirections drd = DRD_NORTHBOUND;
    00806
    00807   if (p1 >= MapSize()) return CMD_ERROR;
    00808
    00809   TileIndex end_tile = p1;
    00810   RoadType rt = Extract<RoadType, 3, 2>(p2);
    00811   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
    00812
    00813   Axis axis = Extract<Axis, 2, 1>(p2);
    00814   /* Only drag in X or Y direction dictated by the direction variable */
    00815   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
    00816   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
    00817
    00818   DiagDirection dir = AxisToDiagDir(axis);
    00819
    00820   /* Swap direction, also the half-tile drag var (bit 0 and 1) */
    00821   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
    00822     dir = ReverseDiagDir(dir);
    00823     p2 ^= 3;
    00824     drd = DRD_SOUTHBOUND;
    00825   }
    00826
    00827   /* On the X-axis, we have to swap the initial bits, so they
    00828    * will be interpreted correctly in the GTTS. Furthermore
    00829    * when you just 'click' on one tile to build them. */
    00830   if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
    00831   /* No disallowed direction bits have to be toggled */
    00832   if (!HasBit(p2, 5)) drd = DRD_NONE;
    00833
    00834   CommandCost cost(EXPENSES_CONSTRUCTION);
    00835   CommandCost last_error = CMD_ERROR;
    00836   TileIndex tile = start_tile;
    00837   bool had_bridge = false;
    00838   bool had_tunnel = false;
    00839   bool had_success = false;
    00840   /* Start tile is the first tile clicked by the user. */
    00841   for (;;) {
    00842     RoadBits bits = AxisToRoadBits(axis);
    00843
    00844     /* Road parts only have to be built at the start tile or at the end tile. */
    00845     if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
    00846     if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
    00847
    00848     CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits, 0, flags, CMD_BUILD_ROAD);
    00849     if (ret.Failed()) {
    00850       last_error = ret;
    00851       if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
    00852         if (HasBit(p2, 6)) return last_error;
    00853         break;
    00854       }
    00855     } else {
    00856       had_success = true;
    00857       /* Only pay for the upgrade on one side of the bridges and tunnels */
    00858       if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    00859         if (IsBridge(tile)) {
    00860           if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
    00861             cost.AddCost(ret);
    00862           }
    00863           had_bridge = true;
    00864         } else { // IsTunnel(tile)
    00865           if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
    00866             cost.AddCost(ret);
    00867           }
    00868           had_tunnel = true;
    00869         }
    00870       } else {
    00871         cost.AddCost(ret);
    00872       }
    00873     }
    00874
    00875     if (tile == end_tile) break;
    00876
    00877     tile += TileOffsByDiagDir(dir);
    00878   }
    00879
    00880   return had_success ? cost : last_error;
    00881 }
    00882
    00896 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00897 {
    00898   CommandCost cost(EXPENSES_CONSTRUCTION);
    00899
    00900   if (p1 >= MapSize()) return CMD_ERROR;
    00901
    00902   TileIndex end_tile = p1;
    00903   RoadType rt = Extract<RoadType, 3, 2>(p2);
    00904   if (!IsValidRoadType(rt)) return CMD_ERROR;
    00905
    00906   Axis axis = Extract<Axis, 2, 1>(p2);
    00907   /* Only drag in X or Y direction dictated by the direction variable */
    00908   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
    00909   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
    00910
    00911   /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
    00912   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
    00913     TileIndex t = start_tile;
    00914     start_tile = end_tile;
    00915     end_tile = t;
    00916     p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
    00917   }
    00918
    00919   Money money = GetAvailableMoneyForCommand();
    00920   TileIndex tile = start_tile;
    00921   CommandCost last_error = CMD_ERROR;
    00922   bool had_success = false;
    00923   /* Start tile is the small number. */
    00924   for (;;) {
    00925     RoadBits bits = AxisToRoadBits(axis);
    00926
    00927     if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
    00928     if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
    00929
    00930     /* try to remove the halves. */
    00931     if (bits != 0) {
    00932       CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true, true);
    00933       if (ret.Succeeded()) {
    00934         if (flags & DC_EXEC) {
    00935           money -= ret.GetCost();
    00936           if (money < 0) {
    00937             _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
    00938             return cost;
    00939           }
    00940           RemoveRoad(tile, flags, bits, rt, true, true, false);
    00941         }
    00942         cost.AddCost(ret);
    00943         had_success = true;
    00944       } else {
    00945         /* Ownership errors are more important. */
    00946         if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
    00947       }
    00948     }
    00949
    00950     if (tile == end_tile) break;
    00951
    00952     tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
    00953   }
    00954
    00955   return had_success ? cost : last_error;
    00956 }
    00957
    00971 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00972 {
    00973   DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
    00974   RoadType rt = Extract<RoadType, 2, 2>(p1);
    00975
    00976   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
    00977
    00978   Slope tileh = GetTileSlope(tile, NULL);
    00979   if (tileh != SLOPE_FLAT && (
    00980         !_settings_game.construction.build_on_slopes ||
    00981         IsSteepSlope(tileh) ||
    00982         !CanBuildDepotByTileh(dir, tileh)
    00983       )) {
    00984     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00985   }
    00986
    00987   CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    00988   if (cost.Failed()) return cost;
    00989
    00990   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00991
    00992   if (!Depot::CanAllocateItem()) return CMD_ERROR;
    00993
    00994   if (flags & DC_EXEC) {
    00995     Depot *dep = new Depot(tile);
    00996     dep->build_date = _date;
    00997
    00998     /* A road depot has two road bits. */
    00999     Company::Get(_current_company)->road_infrastructure[rt] += 2;
    01000     DirtyCompanyInfrastructureWindows(_current_company);
    01001
    01002     MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
    01003     MarkTileDirtyByTile(tile);
    01004     MakeDefaultName(dep);
    01005   }
    01006   cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
    01007   return cost;
    01008 }
    01009
    01010 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
    01011 {
    01012   if (_current_company != OWNER_WATER) {
    01013     CommandCost ret = CheckTileOwnership(tile);
    01014     if (ret.Failed()) return ret;
    01015   }
    01016
    01017   CommandCost ret = EnsureNoVehicleOnGround(tile);
    01018   if (ret.Failed()) return ret;
    01019
    01020   if (flags & DC_EXEC) {
    01021     Company *c = Company::GetIfValid(GetTileOwner(tile));
    01022     if (c != NULL) {
    01023       /* A road depot has two road bits. */
    01024       c->road_infrastructure[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
    01025       DirtyCompanyInfrastructureWindows(c->index);
    01026     }
    01027
    01028     delete Depot::GetByTile(tile);
    01029     DoClearSquare(tile);
    01030   }
    01031
    01032   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
    01033 }
    01034
    01035 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
    01036 {
    01037   switch (GetRoadTileType(tile)) {
    01038     case ROAD_TILE_NORMAL: {
    01039       RoadBits b = GetAllRoadBits(tile);
    01040
    01041       /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
    01042       if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
    01043         CommandCost ret(EXPENSES_CONSTRUCTION);
    01044
    01045         /* Remove traffic light if necessary. */
    01046         if (HasTrafficLights(tile)) {
    01047           CommandCost tl_ret = CmdRemoveTrafficLights(tile, flags, 0, 0, 0);
    01048           if (tl_ret.Failed()) return tl_ret;
    01049           ret.AddCost(tl_ret);
    01050         }
    01051
    01052         /* Remove road bits. */
    01053         RoadType rt;
    01054         FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
    01055           CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rt), rt, true, false);
    01056           if (tmp_ret.Failed()) return tmp_ret;
    01057           ret.AddCost(tmp_ret);
    01058         }
    01059         return ret;
    01060       }
    01061       return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
    01062     }
    01063
    01064     case ROAD_TILE_CROSSING: {
    01065       RoadTypes rts = GetRoadTypes(tile);
    01066       CommandCost ret(EXPENSES_CONSTRUCTION);
    01067
    01068       if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
    01069
    01070       /* Must iterate over the roadtypes in a reverse manner because
    01071        * tram tracks must be removed before the road bits. */
    01072       RoadType rt = ROADTYPE_TRAM;
    01073       do {
    01074         if (HasBit(rts, rt)) {
    01075           CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rt, false, false);
    01076           if (tmp_ret.Failed()) return tmp_ret;
    01077           ret.AddCost(tmp_ret);
    01078         }
    01079       } while (rt-- != ROADTYPE_ROAD);
    01080
    01081       if (flags & DC_EXEC) {
    01082         DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    01083       }
    01084       return ret;
    01085     }
    01086
    01087     default:
    01088     case ROAD_TILE_DEPOT:
    01089       if (flags & DC_AUTO) {
    01090         return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
    01091       }
    01092       return RemoveRoadDepot(tile, flags);
    01093   }
    01094 }
    01095
    01096
    01097 struct DrawRoadTileStruct {
    01098   uint16 image;
    01099   byte subcoord_x;
    01100   byte subcoord_y;
    01101 };
    01102
    01103 #include "table/road_land.h"
    01104
    01112 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
    01113 {
    01114   /* Flat land and land without a road doesn't require a foundation */
    01115   if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
    01116
    01117   if (!IsSteepSlope(tileh)) {
    01118     /* Leveled RoadBits on a slope */
    01119     if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
    01120
    01121     /* Straight roads without foundation on a slope */
    01122     if (!IsSlopeWithOneCornerRaised(tileh) &&
    01123         (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
    01124       return FOUNDATION_NONE;
    01125   }
    01126
    01127   /* Roads on steep Slopes or on Slopes with one corner raised */
    01128   return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
    01129 }
    01130
    01131 const byte _road_sloped_sprites[14] = {
    01132   0,  0,  2,  0,
    01133   0,  1,  0,  0,
    01134   3,  0,  0,  0,
    01135   0,  0
    01136 };
    01137
    01148 static bool AlwaysDrawUnpavedRoads(TileIndex tile, Roadside roadside)
    01149 {
    01150   return (IsOnSnow(tile) &&
    01151       !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
    01152         roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
    01153 }
    01154
    01160 void DrawTramCatenary(const TileInfo *ti, RoadBits tram)
    01161 {
    01162   /* Do not draw catenary if it is invisible */
    01163   if (IsInvisibilitySet(TO_CATENARY)) return;
    01164
    01165   /* Don't draw the catenary under a low bridge */
    01166   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
    01167     uint height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
    01168
    01169     if (height <= GetTileMaxZ(ti->tile) + TILE_HEIGHT) return;
    01170   }
    01171
    01172   SpriteID front;
    01173   SpriteID back;
    01174
    01175   if (ti->tileh != SLOPE_FLAT) {
    01176     back  = SPR_TRAMWAY_BACK_WIRES_SLOPED  + _road_sloped_sprites[ti->tileh - 1];
    01177     front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
    01178   } else {
    01179     back  = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[tram];
    01180     front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
    01181   }
    01182
    01183   AddSortableSpriteToDraw(back,  PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
    01184   AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
    01185 }
    01186
    01195 void DrawRoadDetail(SpriteID img, TileInfo *ti, int dx, int dy, int h)
    01196 {
    01197   int x = ti->x | dx;
    01198   int y = ti->y | dy;
    01199   int32 z = ti->z;
    01200   if (ti->tileh != SLOPE_FLAT) z = GetSlopeZ(x, y);
    01201   AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
    01202 }
    01203
    01208 static void DrawRoadBits(TileInfo *ti)
    01209 {
    01210   RoadBits road = GetRoadBits(ti->tile, ROADTYPE_ROAD);
    01211   RoadBits tram = GetRoadBits(ti->tile, ROADTYPE_TRAM);
    01212
    01213   SpriteID image = 0;
    01214   PaletteID pal = PAL_NONE;
    01215
    01216   if (ti->tileh != SLOPE_FLAT) {
    01217     DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
    01218
    01219     /* DrawFoundation() modifies ti.
    01220      * Default sloped sprites.. */
    01221     if (ti->tileh != SLOPE_FLAT) image = _road_sloped_sprites[ti->tileh - 1] + 0x53F;
    01222   }
    01223
    01224   if (image == 0) image = _road_tile_sprites_1[road != ROAD_NONE ? road : tram];
    01225
    01226   Roadside roadside = GetRoadside(ti->tile);
    01227
    01228   if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
    01229     image += 19;
    01230   } else {
    01231     switch (roadside) {
    01232       case ROADSIDE_BARREN:           pal = PALETTE_TO_BARE_LAND; break;
    01233       case ROADSIDE_GRASS:            break;
    01234       case ROADSIDE_GRASS_ROAD_WORKS: break;
    01235       default:                        image -= 19; break; // Paved
    01236     }
    01237   }
    01238
    01239   DrawGroundSprite(image, pal);
    01240
    01241   /* For tram we overlay the road graphics with either tram tracks only
    01242    * (when there is actual road beneath the trams) or with tram tracks
    01243    * and some dirts which hides the road graphics */
    01244   if (tram != ROAD_NONE) {
    01245     if (ti->tileh != SLOPE_FLAT) {
    01246       image = _road_sloped_sprites[ti->tileh - 1] + SPR_TRAMWAY_SLOPED_OFFSET;
    01247     } else {
    01248       image = _road_tile_sprites_1[tram] - SPR_ROAD_Y;
    01249     }
    01250     image += (road == ROAD_NONE) ? SPR_TRAMWAY_TRAM : SPR_TRAMWAY_OVERLAY;
    01251     DrawGroundSprite(image, pal);
    01252   }
    01253
    01254   if (road != ROAD_NONE) {
    01255     DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
    01256     if (drd != DRD_NONE) {
    01257       DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialZ(8, 8, ti->tileh));
    01258     }
    01259   }
    01260
    01261   if (_settings_game.construction.traffic_lights && HasTrafficLights(ti->tile) && _cur_dpi->zoom <= ZOOM_LVL_DETAIL) DrawTrafficLights(ti);
    01262
    01263   if (HasRoadWorks(ti->tile)) {
    01264     /* Road works */
    01265     DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
    01266     return;
    01267   }
    01268
    01269   if (tram != ROAD_NONE) DrawTramCatenary(ti, tram);
    01270
    01271   /* Return if full detail is disabled, or we are zoomed fully out. */
    01272   if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
    01273
    01274   /* Do not draw details (street lights, trees) under low bridge */
    01275   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
    01276     uint height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
    01277     uint minz = GetTileMaxZ(ti->tile) + 2 * TILE_HEIGHT;
    01278
    01279     if (roadside == ROADSIDE_TREES) minz += TILE_HEIGHT;
    01280
    01281     if (height < minz) return;
    01282   }
    01283
    01284   /* If there are no road bits, return, as there is nothing left to do */
    01285   if (HasAtMostOneBit(road)) return;
    01286
    01287   /* Draw extra details. */
    01288   for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
    01289     DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
    01290   }
    01291 }
    01292
    01294 static void DrawTile_Road(TileInfo *ti)
    01295 {
    01296   switch (GetRoadTileType(ti->tile)) {
    01297     case ROAD_TILE_NORMAL:
    01298       DrawRoadBits(ti);
    01299       break;
    01300
    01301     case ROAD_TILE_CROSSING: {
    01302       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
    01303
    01304       PaletteID pal = PAL_NONE;
    01305       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
    01306
    01307       if (rti->UsesOverlay()) {
    01308         Axis axis = GetCrossingRailAxis(ti->tile);
    01309         SpriteID road = SPR_ROAD_Y + axis;
    01310
    01311         Roadside roadside = GetRoadside(ti->tile);
    01312
    01313         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
    01314           road += 19;
    01315         } else {
    01316           switch (roadside) {
    01317             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
    01318             case ROADSIDE_GRASS:  break;
    01319             default:              road -= 19; break; // Paved
    01320           }
    01321         }
    01322
    01323         DrawGroundSprite(road, pal);
    01324
    01325         SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
    01326         /* Draw tracks, but draw PBS reserved tracks darker. */
    01327         pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
    01328         DrawGroundSprite(rail, pal);
    01329
    01330         DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
    01331       } else {
    01332         SpriteID image = rti->base_sprites.crossing;
    01333
    01334         if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
    01335         if (IsCrossingBarred(ti->tile)) image += 2;
    01336
    01337         Roadside roadside = GetRoadside(ti->tile);
    01338
    01339         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
    01340           image += 8;
    01341         } else {
    01342           switch (roadside) {
    01343             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
    01344             case ROADSIDE_GRASS:  break;
    01345             default:              image += 4; break; // Paved
    01346           }
    01347         }
    01348
    01349         DrawGroundSprite(image, pal);
    01350
    01351         /* PBS debugging, draw reserved tracks darker */
    01352         if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
    01353           DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
    01354         }
    01355       }
    01356
    01357       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
    01358         DrawGroundSprite(SPR_TRAMWAY_OVERLAY + (GetCrossingRoadAxis(ti->tile) ^ 1), pal);
    01359         DrawTramCatenary(ti, GetCrossingRoadBits(ti->tile));
    01360       }
    01361       if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
    01362       break;
    01363     }
    01364
    01365     default:
    01366     case ROAD_TILE_DEPOT: {
    01367       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
    01368
    01369       PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
    01370
    01371       const DrawTileSprites *dts;
    01372       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
    01373         dts =  &_tram_depot[GetRoadDepotDirection(ti->tile)];
    01374       } else {
    01375         dts =  &_road_depot[GetRoadDepotDirection(ti->tile)];
    01376       }
    01377
    01378       DrawGroundSprite(dts->ground.sprite, PAL_NONE);
    01379       DrawOrigTileSeq(ti, dts, TO_BUILDINGS, palette);
    01380       break;
    01381     }
    01382   }
    01383   DrawBridgeMiddle(ti);
    01384 }
    01385
    01393 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
    01394 {
    01395   PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
    01396   const DrawTileSprites *dts = (rt == ROADTYPE_TRAM) ? &_tram_depot[dir] : &_road_depot[dir];
    01397
    01398   x += 33;
    01399   y += 17;
    01400
    01401   DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
    01402   DrawOrigTileSeqInGUI(x, y, dts, palette);
    01403 }
    01404
    01410 void UpdateNearestTownForRoadTiles(bool invalidate)
    01411 {
    01412   assert(!invalidate || _generating_world);
    01413
    01414   for (TileIndex t = 0; t < MapSize(); t++) {
    01415     if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
    01416       TownID tid = (TownID)INVALID_TOWN;
    01417       if (!invalidate) {
    01418         const Town *town = CalcClosestTownFromTile(t);
    01419         if (town != NULL) tid = town->index;
    01420       }
    01421       SetTownIndex(t, tid);
    01422     }
    01423   }
    01424 }
    01425
    01426 static uint GetSlopeZ_Road(TileIndex tile, uint x, uint y)
    01427 {
    01428   uint z;
    01429   Slope tileh = GetTileSlope(tile, &z);
    01430
    01431   if (tileh == SLOPE_FLAT) return z;
    01432   if (IsNormalRoad(tile)) {
    01433     Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
    01434     z += ApplyFoundationToSlope(f, &tileh);
    01435     return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
    01436   } else {
    01437     return z + TILE_HEIGHT;
    01438   }
    01439 }
    01440
    01441 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
    01442 {
    01443   if (IsNormalRoad(tile)) {
    01444     return GetRoadFoundation(tileh, GetAllRoadBits(tile));
    01445   } else {
    01446     return FlatteningFoundation(tileh);
    01447   }
    01448 }
    01449
    01456 static void AnimateTile_Road(TileIndex tile)
    01457 {
    01458   if (_settings_game.construction.traffic_lights && HasTrafficLights(tile)) {
    01459     if (_tick_counter % 16 == 0) MarkTileDirtyByTile(tile);
    01460   }
    01461 }
    01462
    01463 static const Roadside _town_road_types[][2] = {
    01464   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
    01465   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
    01466   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
    01467   { ROADSIDE_TREES,         ROADSIDE_TREES },
    01468   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
    01469 };
    01470
    01471 static const Roadside _town_road_types_2[][2] = {
    01472   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
    01473   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
    01474   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
    01475   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
    01476   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
    01477 };
    01478
    01479
    01480 static void TileLoop_Road(TileIndex tile)
    01481 {
    01482   switch (_settings_game.game_creation.landscape) {
    01483     case LT_ARCTIC:
    01484       if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
    01485         ToggleSnow(tile);
    01486         MarkTileDirtyByTile(tile);
    01487       }
    01488       break;
    01489
    01490     case LT_TROPIC:
    01491       if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
    01492         ToggleDesert(tile);
    01493         MarkTileDirtyByTile(tile);
    01494       }
    01495       break;
    01496   }
    01497
    01498   if (IsRoadDepot(tile)) return;
    01499
    01500   const Town *t = ClosestTownFromTile(tile, UINT_MAX);
    01501   if (!HasRoadWorks(tile)) {
    01502     HouseZonesBits grp = HZB_TOWN_EDGE;
    01503
    01504     if (t != NULL) {
    01505       grp = GetTownRadiusGroup(t, tile);
    01506
    01507       /* Show an animation to indicate road work */
    01508       if (t->road_build_months != 0 &&
    01509           (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
    01510           IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
    01511         if (GetFoundationSlope(tile, NULL) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
    01512           StartRoadWorks(tile);
    01513
    01514           SndPlayTileFx(SND_21_JACKHAMMER, tile);
    01515           CreateEffectVehicleAbove(
    01516             TileX(tile) * TILE_SIZE + 7,
    01517             TileY(tile) * TILE_SIZE + 7,
    01518             0,
    01519             EV_BULLDOZER);
    01520           MarkTileDirtyByTile(tile);
    01521           return;
    01522         }
    01523       }
    01524     }
    01525
    01526     {
    01527       /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
    01528       const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
    01529       Roadside cur_rs = GetRoadside(tile);
    01530
    01531       /* We have our desired type, do nothing */
    01532       if (cur_rs == new_rs[0]) return;
    01533
    01534       /* We have the pre-type of the desired type, switch to the desired type */
    01535       if (cur_rs == new_rs[1]) {
    01536         cur_rs = new_rs[0];
    01537       /* We have barren land, install the pre-type */
    01538       } else if (cur_rs == ROADSIDE_BARREN) {
    01539         cur_rs = new_rs[1];
    01540       /* We're totally off limits, remove any installation and make barren land */
    01541       } else {
    01542         cur_rs = ROADSIDE_BARREN;
    01543       }
    01544       SetRoadside(tile, cur_rs);
    01545       MarkTileDirtyByTile(tile);
    01546     }
    01547   } else {
    01548     /* In the first half of roadworks, generate traffic lights with a certain chance. */
    01549     if (_settings_game.construction.traffic_lights && _settings_game.construction.towns_build_traffic_lights &&
    01550         (GetRoadWorksCounter(tile) < 8) && (CountBits(GetRoadBits(tile, ROADTYPE_ROAD)) >= 3) &&
    01551         !HasTrafficLights(tile) && Chance16(1, 20)) {
    01552       CmdBuildTrafficLights(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, 0, 0, 0);
    01553       MarkTileDirtyByTile(tile);
    01554     }
    01555     if (IncreaseRoadWorksCounter(tile)) {
    01556       TerminateRoadWorks(tile);
    01557
    01558       if (_settings_game.economy.mod_road_rebuild) {
    01559         /* Generate a nicer town surface. */
    01560         const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
    01561         const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
    01562
    01563         if (old_rb != new_rb) {
    01564           RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), ROADTYPE_ROAD, true, true);
    01565         }
    01566       }
    01567
    01568       MarkTileDirtyByTile(tile);
    01569     }
    01570   }
    01571 }
    01572
    01573 static bool ClickTile_Road(TileIndex tile)
    01574 {
    01575   if (!IsRoadDepot(tile)) return false;
    01576
    01577   ShowDepotWindow(tile, VEH_ROAD);
    01578   return true;
    01579 }
    01580
    01581 /* Converts RoadBits to TrackBits */
    01582 static const TrackBits _road_trackbits[16] = {
    01583   TRACK_BIT_NONE,                                  // ROAD_NONE
    01584   TRACK_BIT_NONE,                                  // ROAD_NW
    01585   TRACK_BIT_NONE,                                  // ROAD_SW
    01586   TRACK_BIT_LEFT,                                  // ROAD_W
    01587   TRACK_BIT_NONE,                                  // ROAD_SE
    01588   TRACK_BIT_Y,                                     // ROAD_Y
    01589   TRACK_BIT_LOWER,                                 // ROAD_S
    01590   TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y,  // ROAD_Y | ROAD_SW
    01591   TRACK_BIT_NONE,                                  // ROAD_NE
    01592   TRACK_BIT_UPPER,                                 // ROAD_N
    01593   TRACK_BIT_X,                                     // ROAD_X
    01594   TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X,  // ROAD_X | ROAD_NW
    01595   TRACK_BIT_RIGHT,                                 // ROAD_E
    01596   TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
    01597   TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
    01598   TRACK_BIT_ALL,                                   // ROAD_ALL
    01599 };
    01600
    01601 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    01602 {
    01603   TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
    01604   TrackdirBits red_signals = TRACKDIR_BIT_NONE; // Crossing barred or red traffic light.
    01605   switch (mode) {
    01606     case TRANSPORT_RAIL:
    01607       if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
    01608       break;
    01609
    01610     case TRANSPORT_ROAD:
    01611       if ((GetRoadTypes(tile) & sub_mode) == 0) break;
    01612       switch (GetRoadTileType(tile)) {
    01613         case ROAD_TILE_NORMAL: {
    01614           const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
    01615           RoadType rt = (RoadType)FindFirstBit(sub_mode);
    01616           RoadBits bits = GetRoadBits(tile, rt);
    01617
    01618           /* no roadbit at this side of tile, return 0 */
    01619           if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
    01620
    01621           uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
    01622           if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
    01623           if (_settings_game.construction.traffic_lights && HasTrafficLights(tile))
    01624               red_signals = trackdirbits & GetTrafficLightDisallowedDirections(tile);
    01625           break;
    01626         }
    01627
    01628         case ROAD_TILE_CROSSING: {
    01629           Axis axis = GetCrossingRoadAxis(tile);
    01630
    01631           if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
    01632
    01633           trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
    01634           if (IsCrossingBarred(tile)) red_signals = trackdirbits;
    01635           if (IsLevelCrossingTile(TileAddByDiagDir(tile, AxisToDiagDir(axis))) &&
    01636               IsCrossingBarred(TileAddByDiagDir(tile, AxisToDiagDir(axis)))) {
    01637             red_signals &= (TrackdirBits)0x0102; // magic value. I think TRACKBIT_X_SW and TRACKBIT_X_NE should be swapped
    01638           }
    01639           if (IsLevelCrossingTile(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis)))) &&
    01640               IsCrossingBarred(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis))))) {
    01641             red_signals &= (TrackdirBits)0x0201; // inverse of above magic value
    01642           }
    01643           break;
    01644         }
    01645
    01646         default:
    01647         case ROAD_TILE_DEPOT: {
    01648           DiagDirection dir = GetRoadDepotDirection(tile);
    01649
    01650           if (side != INVALID_DIAGDIR && side != dir) break;
    01651
    01652           trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
    01653           break;
    01654         }
    01655       }
    01656       break;
    01657
    01658     default: break;
    01659   }
    01660   return CombineTrackStatus(trackdirbits, red_signals);
    01661 }
    01662
    01663 static const StringID _road_tile_strings[] = {
    01664   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01665   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01666   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01667   STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
    01668   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01669   STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
    01670   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01671   STR_LAI_ROAD_DESCRIPTION_ROAD,
    01672 };
    01673
    01674 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
    01675 {
    01676   Owner rail_owner = INVALID_OWNER;
    01677   Owner road_owner = INVALID_OWNER;
    01678   Owner tram_owner = INVALID_OWNER;
    01679
    01680   switch (GetRoadTileType(tile)) {
    01681     case ROAD_TILE_CROSSING: {
    01682       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
    01683       RoadTypes rts = GetRoadTypes(tile);
    01684       rail_owner = GetTileOwner(tile);
    01685       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    01686       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    01687
    01688       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
    01689       td->rail_speed = rti->max_speed;
    01690
    01691       break;
    01692     }
    01693
    01694     case ROAD_TILE_DEPOT:
    01695       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
    01696       road_owner = GetTileOwner(tile); // Tile has only one owner, roadtype does not matter
    01697       td->build_date = Depot::GetByTile(tile)->build_date;
    01698       break;
    01699
    01700     default: {
    01701       RoadTypes rts = GetRoadTypes(tile);
    01702       if (HasTrafficLights(tile)) {
    01703         td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_TRAFFIC_LIGHTS;
    01704       } else {
    01705         td->str = (HasBit(rts, ROADTYPE_ROAD) ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
    01706       }
    01707       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
    01708       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
    01709       break;
    01710     }
    01711   }
    01712
    01713   /* Now we have to discover, if the tile has only one owner or many:
    01714    *   - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
    01715    *   - Compare the found owner with the other owners, and test if they differ.
    01716    * Note: If road exists it will be the first_owner.
    01717    */
    01718   Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
    01719   bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
    01720
    01721   if (mixed_owners) {
    01722     /* Multiple owners */
    01723     td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
    01724     td->owner[0] = rail_owner;
    01725     td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
    01726     td->owner[1] = road_owner;
    01727     td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
    01728     td->owner[2] = tram_owner;
    01729   } else {
    01730     /* One to rule them all */
    01731     td->owner[0] = first_owner;
    01732   }
    01733 }
    01734
    01739 static const byte _roadveh_enter_depot_dir[4] = {
    01740   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
    01741 };
    01742
    01743 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
    01744 {
    01745   switch (GetRoadTileType(tile)) {
    01746     case ROAD_TILE_DEPOT: {
    01747       if (v->type != VEH_ROAD) break;
    01748
    01749       RoadVehicle *rv = RoadVehicle::From(v);
    01750       if (rv->frame == RVC_DEPOT_STOP_FRAME &&
    01751           _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
    01752         rv->state = RVSB_IN_DEPOT;
    01753         rv->vehstatus |= VS_HIDDEN;
    01754         rv->direction = ReverseDir(rv->direction);
    01755         if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
    01756         rv->tile = tile;
    01757
    01758         InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
    01759         return VETSB_ENTERED_WORMHOLE;
    01760       }
    01761       break;
    01762     }
    01763
    01764     default: break;
    01765   }
    01766   return VETSB_CONTINUE;
    01767 }
    01768
    01769
    01770 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
    01771 {
    01772   if (IsRoadDepot(tile)) {
    01773     if (GetTileOwner(tile) == old_owner) {
    01774       if (new_owner == INVALID_OWNER) {
    01775         DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
    01776       } else {
    01777         /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
    01778         RoadType rt = (RoadType)FIND_FIRST_BIT(GetRoadTypes(tile));
    01779         Company::Get(old_owner)->road_infrastructure[rt] -= 2;
    01780         Company::Get(new_owner)->road_infrastructure[rt] += 2;
    01781
    01782         SetTileOwner(tile, new_owner);
    01783       }
    01784     }
    01785     return;
    01786   }
    01787
    01788   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    01789     /* Update all roadtypes, no matter if they are present */
    01790     if (GetRoadOwner(tile, rt) == old_owner) {
    01791       if (HasTileRoadType(tile, rt)) {
    01792         /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
    01793         uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
    01794         Company::Get(old_owner)->road_infrastructure[rt] -= num_bits;
    01795         if (new_owner != INVALID_OWNER) Company::Get(new_owner)->road_infrastructure[rt] += num_bits;
    01796       }
    01797
    01798       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
    01799     }
    01800   }
    01801
    01802   if (IsLevelCrossing(tile)) {
    01803     if (GetTileOwner(tile) == old_owner) {
    01804       if (new_owner == INVALID_OWNER) {
    01805         DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
    01806       } else {
    01807         /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
    01808         Company::Get(old_owner)->rail_infrastructure[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
    01809         Company::Get(new_owner)->rail_infrastructure[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
    01810
    01811         SetTileOwner(tile, new_owner);
    01812       }
    01813     }
    01814   }
    01815 }
    01816
    01817 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
    01818 {
    01819   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
    01820     switch (GetRoadTileType(tile)) {
    01821       case ROAD_TILE_CROSSING:
    01822         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]);
    01823         break;
    01824
    01825       case ROAD_TILE_DEPOT:
    01826         if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    01827         break;
    01828
    01829       case ROAD_TILE_NORMAL: {
    01830         RoadBits bits = GetAllRoadBits(tile);
    01831         RoadBits bits_copy = bits;
    01832         /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
    01833         if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
    01834           /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
    01835           if (bits == bits_copy) {
    01836             uint z_old;
    01837             Slope tileh_old = GetTileSlope(tile, &z_old);
    01838
    01839             /* Get the slope on top of the foundation */
    01840             z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
    01841             z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
    01842
    01843             /* The surface slope must not be changed */
    01844             if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    01845           }
    01846         }
    01847         break;
    01848       }
    01849
    01850       default: NOT_REACHED();
    01851     }
    01852   }
    01853
    01854   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    01855 }
    01856
    01858 extern const TileTypeProcs _tile_type_road_procs = {
    01859   DrawTile_Road,           // draw_tile_proc
    01860   GetSlopeZ_Road,          // get_slope_z_proc
    01861   ClearTile_Road,          // clear_tile_proc
    01862   NULL,                    // add_accepted_cargo_proc
    01863   GetTileDesc_Road,        // get_tile_desc_proc
    01864   GetTileTrackStatus_Road, // get_tile_track_status_proc
    01865   ClickTile_Road,          // click_tile_proc
    01866   AnimateTile_Road,        // animate_tile_proc
    01867   TileLoop_Road,           // tile_loop_clear
    01868   ChangeTileOwner_Road,    // change_tile_owner_clear
    01869   NULL,                    // add_produced_cargo_proc
    01870   VehicleEnter_Road,       // vehicle_enter_tile_proc
    01871   GetFoundation_Road,      // get_foundation_proc
    01872   TerraformTile_Road,      // terraform_tile_proc
    01873 };