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