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(GetTileOwner(tile));
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         } else {
00384           SetRoadTypes(tile, rts);
00385           /* If we ever get HWAY and it is possible without road then we will need to promote ownership and invalidate town index here, too */
00386         }
00387         MarkTileDirtyByTile(tile);
00388         YapfNotifyTrackLayoutChange(tile, railtrack);
00389       }
00390       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
00391     }
00392 
00393     default:
00394     case ROAD_TILE_DEPOT:
00395       return CMD_ERROR;
00396   }
00397 }
00398 
00399 
00411 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
00412 {
00413   /* Remove already build pieces */
00414   CLRBITS(*pieces, existing);
00415 
00416   /* If we can't build anything stop here */
00417   if (*pieces == ROAD_NONE) return CMD_ERROR;
00418 
00419   /* All RoadBit combos are valid on flat land */
00420   if (tileh == SLOPE_FLAT) return CommandCost();
00421 
00422   /* Proceed steep Slopes first to reduce lookup table size */
00423   if (IsSteepSlope(tileh)) {
00424     /* Force straight roads. */
00425     *pieces |= MirrorRoadBits(*pieces);
00426 
00427     /* Use existing as all existing since only straight
00428      * roads are allowed here. */
00429     existing |= other;
00430 
00431     if ((existing == ROAD_NONE || existing == *pieces) && IsStraightRoad(*pieces)) {
00432       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00433     }
00434     return CMD_ERROR;
00435   }
00436 
00437   /* Save the merge of all bits of the current type */
00438   RoadBits type_bits = existing | *pieces;
00439 
00440   /* Roads on slopes */
00441   if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
00442 
00443     /* If we add leveling we've got to pay for it */
00444     if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00445 
00446     return CommandCost();
00447   }
00448 
00449   /* Autocomplete uphill roads */
00450   *pieces |= MirrorRoadBits(*pieces);
00451   type_bits = existing | *pieces;
00452 
00453   /* Uphill roads */
00454   if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
00455       (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
00456 
00457     /* Slopes with foundation ? */
00458     if (IsSlopeWithOneCornerRaised(tileh)) {
00459 
00460       /* Prevent build on slopes if it isn't allowed */
00461       if (_settings_game.construction.build_on_slopes) {
00462 
00463         /* If we add foundation we've got to pay for it */
00464         if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00465 
00466         return CommandCost();
00467       }
00468     } else {
00469       if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00470       return CommandCost();
00471     }
00472   }
00473   return CMD_ERROR;
00474 }
00475 
00487 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00488 {
00489   CommandCost cost(EXPENSES_CONSTRUCTION);
00490 
00491   RoadBits existing = ROAD_NONE;
00492   RoadBits other_bits = ROAD_NONE;
00493 
00494   /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
00495    * if a non-company is building the road */
00496   if ((Company::IsValidID(_current_company) && p2 != 0) || (_current_company == OWNER_TOWN && !Town::IsValidID(p2))) return CMD_ERROR;
00497   if (_current_company != OWNER_TOWN) {
00498     const Town *town = CalcClosestTownFromTile(tile);
00499     p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
00500   }
00501 
00502   RoadBits pieces = Extract<RoadBits, 0, 4>(p1);
00503 
00504   /* do not allow building 'zero' road bits, code wouldn't handle it */
00505   if (pieces == ROAD_NONE) return CMD_ERROR;
00506 
00507   RoadType rt = Extract<RoadType, 4, 2>(p1);
00508   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
00509 
00510   DisallowedRoadDirections toggle_drd = Extract<DisallowedRoadDirections, 6, 2>(p1);
00511 
00512   Slope tileh = GetTileSlope(tile, NULL);
00513 
00514   bool need_to_clear = false;
00515   switch (GetTileType(tile)) {
00516     case MP_ROAD:
00517       switch (GetRoadTileType(tile)) {
00518         case ROAD_TILE_NORMAL: {
00519           if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
00520 
00521           other_bits = GetOtherRoadBits(tile, rt);
00522           if (!HasTileRoadType(tile, rt)) break;
00523 
00524           existing = GetRoadBits(tile, rt);
00525           bool crossing = !IsStraightRoad(existing | pieces);
00526           if (rt != ROADTYPE_TRAM && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
00527             /* Junctions cannot be one-way */
00528             return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
00529           }
00530           if ((existing & pieces) == pieces) {
00531             /* We only want to set the (dis)allowed road directions */
00532             if (toggle_drd != DRD_NONE && rt != ROADTYPE_TRAM) {
00533               if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
00534 
00535               Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00536               if (owner != OWNER_NONE) {
00537                 CommandCost ret = CheckOwnership(owner, tile);
00538                 if (ret.Failed()) return ret;
00539               }
00540 
00541               DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
00542               DisallowedRoadDirections dis_new      = dis_existing ^ toggle_drd;
00543 
00544               /* We allow removing disallowed directions to break up
00545                * deadlocks, but adding them can break articulated
00546                * vehicles. As such, only when less is disallowed,
00547                * i.e. bits are removed, we skip the vehicle check. */
00548               if (CountBits(dis_existing) <= CountBits(dis_new)) {
00549                 CommandCost ret = EnsureNoVehicleOnGround(tile);
00550                 if (ret.Failed()) return ret;
00551               }
00552 
00553               /* Ignore half built tiles */
00554               if ((flags & DC_EXEC) && rt != ROADTYPE_TRAM && IsStraightRoad(existing)) {
00555                 SetDisallowedRoadDirections(tile, dis_new);
00556                 MarkTileDirtyByTile(tile);
00557               }
00558               return CommandCost();
00559             }
00560             return_cmd_error(STR_ERROR_ALREADY_BUILT);
00561           }
00562           break;
00563         }
00564 
00565         case ROAD_TILE_CROSSING:
00566           other_bits = GetCrossingRoadBits(tile);
00567           if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
00568           pieces = other_bits; // we need to pay for both roadbits
00569 
00570           if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00571           break;
00572 
00573         case ROAD_TILE_DEPOT:
00574           if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00575           goto do_clear;
00576 
00577         default: NOT_REACHED();
00578       }
00579       break;
00580 
00581     case MP_RAILWAY: {
00582       if (IsSteepSlope(tileh)) {
00583         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00584       }
00585 
00586       /* Level crossings may only be built on these slopes */
00587       if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
00588         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00589       }
00590 
00591       if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
00592 
00593       if (RailNoLevelCrossings(GetRailType(tile))) {
00594         return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
00595       }
00596 
00597       Axis roaddir;
00598       switch (GetTrackBits(tile)) {
00599         case TRACK_BIT_X:
00600           if (pieces & ROAD_X) goto do_clear;
00601           roaddir = AXIS_Y;
00602           break;
00603 
00604         case TRACK_BIT_Y:
00605           if (pieces & ROAD_Y) goto do_clear;
00606           roaddir = AXIS_X;
00607           break;
00608 
00609         default: goto do_clear;
00610       }
00611 
00612       CommandCost ret = EnsureNoVehicleOnGround(tile);
00613       if (ret.Failed()) return ret;
00614 
00615       if (flags & DC_EXEC) {
00616         Track railtrack = AxisToTrack(OtherAxis(roaddir));
00617         YapfNotifyTrackLayoutChange(tile, railtrack);
00618         /* Update company infrastructure counts. A level crossing has two road bits. */
00619         Company *c = Company::GetIfValid(_current_company);
00620         if (c != NULL) {
00621           c->road_infrastructure[rt] += 2;
00622           if (rt != ROADTYPE_ROAD) c->road_infrastructure[ROADTYPE_ROAD] += 2;
00623           DirtyCompanyInfrastructureWindows(_current_company);
00624         }
00625         /* Always add road to the roadtypes (can't draw without it) */
00626         bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
00627         MakeRoadCrossing(tile, _current_company, _current_company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
00628         SetCrossingReservation(tile, reserved);
00629         UpdateLevelCrossing(tile, false);
00630         MarkTileDirtyByTile(tile);
00631       }
00632       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
00633     }
00634 
00635     case MP_STATION: {
00636       if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00637       if (!IsDriveThroughStopTile(tile)) goto do_clear;
00638 
00639       RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
00640       if (pieces & ~curbits) goto do_clear;
00641       pieces = curbits; // we need to pay for both roadbits
00642 
00643       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00644       break;
00645     }
00646 
00647     case MP_TUNNELBRIDGE: {
00648       if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
00649       if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
00650       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00651       /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
00652       CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
00653       if (ret.Failed()) return ret;
00654       break;
00655     }
00656 
00657     default: {
00658 do_clear:;
00659       need_to_clear = true;
00660       break;
00661     }
00662   }
00663 
00664   if (need_to_clear) {
00665     CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00666     if (ret.Failed()) return ret;
00667     cost.AddCost(ret);
00668   }
00669 
00670   if (other_bits != pieces) {
00671     /* Check the foundation/slopes when adding road/tram bits */
00672     CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
00673     /* Return an error if we need to build a foundation (ret != 0) but the
00674      * current setting is turned off */
00675     if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
00676       return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00677     }
00678     cost.AddCost(ret);
00679   }
00680 
00681   if (!need_to_clear) {
00682     if (IsTileType(tile, MP_ROAD)) {
00683       /* Don't put the pieces that already exist */
00684       pieces &= ComplementRoadBits(existing);
00685 
00686       /* Check if new road bits will have the same foundation as other existing road types */
00687       if (IsNormalRoad(tile)) {
00688         Slope slope = GetTileSlope(tile, NULL);
00689         Foundation found_new = GetRoadFoundation(slope, pieces | existing);
00690 
00691         /* Test if all other roadtypes can be built at that foundation */
00692         for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
00693           if (rtest != rt) { // check only other road types
00694             RoadBits bits = GetRoadBits(tile, rtest);
00695             /* do not check if there are not road bits of given type */
00696             if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
00697               return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00698             }
00699           }
00700         }
00701       }
00702     }
00703 
00704     CommandCost ret = EnsureNoVehicleOnGround(tile);
00705     if (ret.Failed()) return ret;
00706 
00707   }
00708   cost.AddCost(CountBits(pieces) * _price[PR_BUILD_ROAD]);
00709 
00710   if (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) {
00711     /* Pay for *every* tile of the bridge or tunnel */
00712     cost.MultiplyCost(GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2);
00713   }
00714 
00715   if (flags & DC_EXEC) {
00716     switch (GetTileType(tile)) {
00717       case MP_ROAD: {
00718         RoadTileType rtt = GetRoadTileType(tile);
00719         if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
00720           SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00721           SetRoadOwner(tile, rt, _current_company);
00722           if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
00723         }
00724         if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
00725         break;
00726       }
00727 
00728       case MP_TUNNELBRIDGE: {
00729         TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
00730 
00731         SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
00732         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00733         SetRoadOwner(other_end, rt, _current_company);
00734         SetRoadOwner(tile, rt, _current_company);
00735 
00736         /* Mark tiles dirty that have been repaved */
00737         MarkTileDirtyByTile(other_end);
00738         MarkTileDirtyByTile(tile);
00739         if (IsBridge(tile)) {
00740           TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
00741 
00742           for (TileIndex t = tile + delta; t != other_end; t += delta) MarkTileDirtyByTile(t);
00743         }
00744         break;
00745       }
00746 
00747       case MP_STATION:
00748         assert(IsDriveThroughStopTile(tile));
00749         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00750         SetRoadOwner(tile, rt, _current_company);
00751         break;
00752 
00753       default:
00754         MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, _current_company, _current_company);
00755         break;
00756     }
00757 
00758     /* Update company infrastructure count. */
00759     Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00760     if (c != NULL) {
00761       uint num_pieces = CountBits(pieces);
00762       if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
00763       c->road_infrastructure[rt] += num_pieces;
00764       DirtyCompanyInfrastructureWindows(c->index);
00765     }
00766 
00767     if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
00768       existing |= pieces;
00769       SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
00770           GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
00771     }
00772 
00773     MarkTileDirtyByTile(tile);
00774   }
00775   return cost;
00776 }
00777 
00793 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00794 {
00795   DisallowedRoadDirections drd = DRD_NORTHBOUND;
00796 
00797   if (p1 >= MapSize()) return CMD_ERROR;
00798 
00799   TileIndex end_tile = p1;
00800   RoadType rt = Extract<RoadType, 3, 2>(p2);
00801   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
00802 
00803   Axis axis = Extract<Axis, 2, 1>(p2);
00804   /* Only drag in X or Y direction dictated by the direction variable */
00805   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
00806   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
00807 
00808   DiagDirection dir = AxisToDiagDir(axis);
00809 
00810   /* Swap direction, also the half-tile drag var (bit 0 and 1) */
00811   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
00812     dir = ReverseDiagDir(dir);
00813     p2 ^= 3;
00814     drd = DRD_SOUTHBOUND;
00815   }
00816 
00817   /* On the X-axis, we have to swap the initial bits, so they
00818    * will be interpreted correctly in the GTTS. Furthermore
00819    * when you just 'click' on one tile to build them. */
00820   if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
00821   /* No disallowed direction bits have to be toggled */
00822   if (!HasBit(p2, 5)) drd = DRD_NONE;
00823 
00824   CommandCost cost(EXPENSES_CONSTRUCTION);
00825   CommandCost last_error = CMD_ERROR;
00826   TileIndex tile = start_tile;
00827   bool had_bridge = false;
00828   bool had_tunnel = false;
00829   bool had_success = false;
00830   /* Start tile is the first tile clicked by the user. */
00831   for (;;) {
00832     RoadBits bits = AxisToRoadBits(axis);
00833 
00834     /* Road parts only have to be built at the start tile or at the end tile. */
00835     if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
00836     if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
00837 
00838     CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits, 0, flags, CMD_BUILD_ROAD);
00839     if (ret.Failed()) {
00840       last_error = ret;
00841       if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
00842         if (HasBit(p2, 6)) return last_error;
00843         break;
00844       }
00845     } else {
00846       had_success = true;
00847       /* Only pay for the upgrade on one side of the bridges and tunnels */
00848       if (IsTileType(tile, MP_TUNNELBRIDGE)) {
00849         if (IsBridge(tile)) {
00850           if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
00851             cost.AddCost(ret);
00852           }
00853           had_bridge = true;
00854         } else { // IsTunnel(tile)
00855           if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
00856             cost.AddCost(ret);
00857           }
00858           had_tunnel = true;
00859         }
00860       } else {
00861         cost.AddCost(ret);
00862       }
00863     }
00864 
00865     if (tile == end_tile) break;
00866 
00867     tile += TileOffsByDiagDir(dir);
00868   }
00869 
00870   return had_success ? cost : last_error;
00871 }
00872 
00886 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00887 {
00888   CommandCost cost(EXPENSES_CONSTRUCTION);
00889 
00890   if (p1 >= MapSize()) return CMD_ERROR;
00891 
00892   TileIndex end_tile = p1;
00893   RoadType rt = Extract<RoadType, 3, 2>(p2);
00894   if (!IsValidRoadType(rt)) return CMD_ERROR;
00895 
00896   Axis axis = Extract<Axis, 2, 1>(p2);
00897   /* Only drag in X or Y direction dictated by the direction variable */
00898   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
00899   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
00900 
00901   /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
00902   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
00903     TileIndex t = start_tile;
00904     start_tile = end_tile;
00905     end_tile = t;
00906     p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
00907   }
00908 
00909   Money money = GetAvailableMoneyForCommand();
00910   TileIndex tile = start_tile;
00911   CommandCost last_error = CMD_ERROR;
00912   bool had_success = false;
00913   /* Start tile is the small number. */
00914   for (;;) {
00915     RoadBits bits = AxisToRoadBits(axis);
00916 
00917     if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
00918     if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
00919 
00920     /* try to remove the halves. */
00921     if (bits != 0) {
00922       CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true, true);
00923       if (ret.Succeeded()) {
00924         if (flags & DC_EXEC) {
00925           money -= ret.GetCost();
00926           if (money < 0) {
00927             _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
00928             return cost;
00929           }
00930           RemoveRoad(tile, flags, bits, rt, true, true, false);
00931         }
00932         cost.AddCost(ret);
00933         had_success = true;
00934       } else {
00935         /* Ownership errors are more important. */
00936         if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
00937       }
00938     }
00939 
00940     if (tile == end_tile) break;
00941 
00942     tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
00943   }
00944 
00945   return had_success ? cost : last_error;
00946 }
00947 
00961 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00962 {
00963   DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
00964   RoadType rt = Extract<RoadType, 2, 2>(p1);
00965 
00966   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
00967 
00968   Slope tileh = GetTileSlope(tile, NULL);
00969   if (tileh != SLOPE_FLAT && (
00970         !_settings_game.construction.build_on_slopes ||
00971         IsSteepSlope(tileh) ||
00972         !CanBuildDepotByTileh(dir, tileh)
00973       )) {
00974     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00975   }
00976 
00977   CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00978   if (cost.Failed()) return cost;
00979 
00980   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00981 
00982   if (!Depot::CanAllocateItem()) return CMD_ERROR;
00983 
00984   if (flags & DC_EXEC) {
00985     Depot *dep = new Depot(tile);
00986     dep->build_date = _date;
00987 
00988     /* A road depot has two road bits. */
00989     Company::Get(_current_company)->road_infrastructure[rt] += 2;
00990     DirtyCompanyInfrastructureWindows(_current_company);
00991 
00992     MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
00993     MarkTileDirtyByTile(tile);
00994     MakeDefaultName(dep);
00995   }
00996   cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
00997   return cost;
00998 }
00999 
01000 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
01001 {
01002   if (_current_company != OWNER_WATER) {
01003     CommandCost ret = CheckTileOwnership(tile);
01004     if (ret.Failed()) return ret;
01005   }
01006 
01007   CommandCost ret = EnsureNoVehicleOnGround(tile);
01008   if (ret.Failed()) return ret;
01009 
01010   if (flags & DC_EXEC) {
01011     Company *c = Company::GetIfValid(GetTileOwner(tile));
01012     if (c != NULL) {
01013       /* A road depot has two road bits. */
01014       c->road_infrastructure[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
01015       DirtyCompanyInfrastructureWindows(c->index);
01016     }
01017 
01018     delete Depot::GetByTile(tile);
01019     DoClearSquare(tile);
01020   }
01021 
01022   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
01023 }
01024 
01025 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
01026 {
01027   switch (GetRoadTileType(tile)) {
01028     case ROAD_TILE_NORMAL: {
01029       RoadBits b = GetAllRoadBits(tile);
01030 
01031       /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
01032       if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
01033         CommandCost ret(EXPENSES_CONSTRUCTION);
01034 
01035         /* Remove traffic light if necessary. */
01036         if (HasTrafficLights(tile)) {
01037           CommandCost tl_ret = CmdRemoveTrafficLights(tile, flags, 0, 0, 0);
01038           if (tl_ret.Failed()) return tl_ret;
01039           ret.AddCost(tl_ret);
01040         }
01041 
01042         /* Remove road bits. */
01043         RoadType rt;
01044         FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01045           CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rt), rt, true, false);
01046           if (tmp_ret.Failed()) return tmp_ret;
01047           ret.AddCost(tmp_ret);
01048         }
01049         return ret;
01050       }
01051       return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
01052     }
01053 
01054     case ROAD_TILE_CROSSING: {
01055       RoadTypes rts = GetRoadTypes(tile);
01056       CommandCost ret(EXPENSES_CONSTRUCTION);
01057 
01058       if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
01059 
01060       /* Must iterate over the roadtypes in a reverse manner because
01061        * tram tracks must be removed before the road bits. */
01062       RoadType rt = ROADTYPE_TRAM;
01063       do {
01064         if (HasBit(rts, rt)) {
01065           CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rt, false, false);
01066           if (tmp_ret.Failed()) return tmp_ret;
01067           ret.AddCost(tmp_ret);
01068         }
01069       } while (rt-- != ROADTYPE_ROAD);
01070 
01071       if (flags & DC_EXEC) {
01072         DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01073       }
01074       return ret;
01075     }
01076 
01077     default:
01078     case ROAD_TILE_DEPOT:
01079       if (flags & DC_AUTO) {
01080         return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
01081       }
01082       return RemoveRoadDepot(tile, flags);
01083   }
01084 }
01085 
01086 
01087 struct DrawRoadTileStruct {
01088   uint16 image;
01089   byte subcoord_x;
01090   byte subcoord_y;
01091 };
01092 
01093 #include "table/road_land.h"
01094 
01102 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
01103 {
01104   /* Flat land and land without a road doesn't require a foundation */
01105   if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
01106 
01107   if (!IsSteepSlope(tileh)) {
01108     /* Leveled RoadBits on a slope */
01109     if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
01110 
01111     /* Straight roads without foundation on a slope */
01112     if (!IsSlopeWithOneCornerRaised(tileh) &&
01113         (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
01114       return FOUNDATION_NONE;
01115   }
01116 
01117   /* Roads on steep Slopes or on Slopes with one corner raised */
01118   return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
01119 }
01120 
01121 const byte _road_sloped_sprites[14] = {
01122   0,  0,  2,  0,
01123   0,  1,  0,  0,
01124   3,  0,  0,  0,
01125   0,  0
01126 };
01127 
01138 static bool AlwaysDrawUnpavedRoads(TileIndex tile, Roadside roadside)
01139 {
01140   return (IsOnSnow(tile) &&
01141       !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
01142         roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
01143 }
01144 
01150 void DrawTramCatenary(const TileInfo *ti, RoadBits tram)
01151 {
01152   /* Do not draw catenary if it is invisible */
01153   if (IsInvisibilitySet(TO_CATENARY)) return;
01154 
01155   /* Don't draw the catenary under a low bridge */
01156   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
01157     uint height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
01158 
01159     if (height <= GetTileMaxZ(ti->tile) + TILE_HEIGHT) return;
01160   }
01161 
01162   SpriteID front;
01163   SpriteID back;
01164 
01165   if (ti->tileh != SLOPE_FLAT) {
01166     back  = SPR_TRAMWAY_BACK_WIRES_SLOPED  + _road_sloped_sprites[ti->tileh - 1];
01167     front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
01168   } else {
01169     back  = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[tram];
01170     front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
01171   }
01172 
01173   AddSortableSpriteToDraw(back,  PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
01174   AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
01175 }
01176 
01185 void DrawRoadDetail(SpriteID img, TileInfo *ti, int dx, int dy, int h)
01186 {
01187   int x = ti->x | dx;
01188   int y = ti->y | dy;
01189   int32 z = ti->z;
01190   if (ti->tileh != SLOPE_FLAT) z = GetSlopeZ(x, y);
01191   AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
01192 }
01193 
01198 static void DrawRoadBits(TileInfo *ti)
01199 {
01200   RoadBits road = GetRoadBits(ti->tile, ROADTYPE_ROAD);
01201   RoadBits tram = GetRoadBits(ti->tile, ROADTYPE_TRAM);
01202 
01203   SpriteID image = 0;
01204   PaletteID pal = PAL_NONE;
01205 
01206   if (ti->tileh != SLOPE_FLAT) {
01207     DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
01208 
01209     /* DrawFoundation() modifies ti.
01210      * Default sloped sprites.. */
01211     if (ti->tileh != SLOPE_FLAT) image = _road_sloped_sprites[ti->tileh - 1] + 0x53F;
01212   }
01213 
01214   if (image == 0) image = _road_tile_sprites_1[road != ROAD_NONE ? road : tram];
01215 
01216   Roadside roadside = GetRoadside(ti->tile);
01217 
01218   if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01219     image += 19;
01220   } else {
01221     switch (roadside) {
01222       case ROADSIDE_BARREN:           pal = PALETTE_TO_BARE_LAND; break;
01223       case ROADSIDE_GRASS:            break;
01224       case ROADSIDE_GRASS_ROAD_WORKS: break;
01225       default:                        image -= 19; break; // Paved
01226     }
01227   }
01228 
01229   DrawGroundSprite(image, pal);
01230 
01231   /* For tram we overlay the road graphics with either tram tracks only
01232    * (when there is actual road beneath the trams) or with tram tracks
01233    * and some dirts which hides the road graphics */
01234   if (tram != ROAD_NONE) {
01235     if (ti->tileh != SLOPE_FLAT) {
01236       image = _road_sloped_sprites[ti->tileh - 1] + SPR_TRAMWAY_SLOPED_OFFSET;
01237     } else {
01238       image = _road_tile_sprites_1[tram] - SPR_ROAD_Y;
01239     }
01240     image += (road == ROAD_NONE) ? SPR_TRAMWAY_TRAM : SPR_TRAMWAY_OVERLAY;
01241     DrawGroundSprite(image, pal);
01242   }
01243 
01244   if (road != ROAD_NONE) {
01245     DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
01246     if (drd != DRD_NONE) {
01247       DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialZ(8, 8, ti->tileh));
01248     }
01249   }
01250 
01251   if (_settings_game.construction.traffic_lights && HasTrafficLights(ti->tile) && _cur_dpi->zoom <= ZOOM_LVL_DETAIL) DrawTrafficLights(ti);
01252 
01253   if (HasRoadWorks(ti->tile)) {
01254     /* Road works */
01255     DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
01256     return;
01257   }
01258 
01259   if (tram != ROAD_NONE) DrawTramCatenary(ti, tram);
01260 
01261   /* Return if full detail is disabled, or we are zoomed fully out. */
01262   if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
01263 
01264   /* Do not draw details (street lights, trees) under low bridge */
01265   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
01266     uint height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
01267     uint minz = GetTileMaxZ(ti->tile) + 2 * TILE_HEIGHT;
01268 
01269     if (roadside == ROADSIDE_TREES) minz += TILE_HEIGHT;
01270 
01271     if (height < minz) return;
01272   }
01273 
01274   /* If there are no road bits, return, as there is nothing left to do */
01275   if (HasAtMostOneBit(road)) return;
01276 
01277   /* Draw extra details. */
01278   for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
01279     DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
01280   }
01281 }
01282 
01284 static void DrawTile_Road(TileInfo *ti)
01285 {
01286   switch (GetRoadTileType(ti->tile)) {
01287     case ROAD_TILE_NORMAL:
01288       DrawRoadBits(ti);
01289       break;
01290 
01291     case ROAD_TILE_CROSSING: {
01292       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
01293 
01294       PaletteID pal = PAL_NONE;
01295       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01296 
01297       if (rti->UsesOverlay()) {
01298         Axis axis = GetCrossingRailAxis(ti->tile);
01299         SpriteID road = SPR_ROAD_Y + axis;
01300 
01301         Roadside roadside = GetRoadside(ti->tile);
01302 
01303         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01304           road += 19;
01305         } else {
01306           switch (roadside) {
01307             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
01308             case ROADSIDE_GRASS:  break;
01309             default:              road -= 19; break; // Paved
01310           }
01311         }
01312 
01313         DrawGroundSprite(road, pal);
01314 
01315         SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
01316         /* Draw tracks, but draw PBS reserved tracks darker. */
01317         pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
01318         DrawGroundSprite(rail, pal);
01319 
01320         DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
01321       } else {
01322         SpriteID image = rti->base_sprites.crossing;
01323 
01324         if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
01325         if (IsCrossingBarred(ti->tile)) image += 2;
01326 
01327         Roadside roadside = GetRoadside(ti->tile);
01328 
01329         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01330           image += 8;
01331         } else {
01332           switch (roadside) {
01333             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
01334             case ROADSIDE_GRASS:  break;
01335             default:              image += 4; break; // Paved
01336           }
01337         }
01338 
01339         DrawGroundSprite(image, pal);
01340 
01341         /* PBS debugging, draw reserved tracks darker */
01342         if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
01343           DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
01344         }
01345       }
01346 
01347       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
01348         DrawGroundSprite(SPR_TRAMWAY_OVERLAY + (GetCrossingRoadAxis(ti->tile) ^ 1), pal);
01349         DrawTramCatenary(ti, GetCrossingRoadBits(ti->tile));
01350       }
01351       if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
01352       break;
01353     }
01354 
01355     default:
01356     case ROAD_TILE_DEPOT: {
01357       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
01358 
01359       PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
01360 
01361       const DrawTileSprites *dts;
01362       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
01363         dts =  &_tram_depot[GetRoadDepotDirection(ti->tile)];
01364       } else {
01365         dts =  &_road_depot[GetRoadDepotDirection(ti->tile)];
01366       }
01367 
01368       DrawGroundSprite(dts->ground.sprite, PAL_NONE);
01369       DrawOrigTileSeq(ti, dts, TO_BUILDINGS, palette);
01370       break;
01371     }
01372   }
01373   DrawBridgeMiddle(ti);
01374 }
01375 
01383 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
01384 {
01385   PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
01386   const DrawTileSprites *dts = (rt == ROADTYPE_TRAM) ? &_tram_depot[dir] : &_road_depot[dir];
01387 
01388   x += 33;
01389   y += 17;
01390 
01391   DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
01392   DrawOrigTileSeqInGUI(x, y, dts, palette);
01393 }
01394 
01400 void UpdateNearestTownForRoadTiles(bool invalidate)
01401 {
01402   assert(!invalidate || _generating_world);
01403 
01404   for (TileIndex t = 0; t < MapSize(); t++) {
01405     if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
01406       TownID tid = (TownID)INVALID_TOWN;
01407       if (!invalidate) {
01408         const Town *town = CalcClosestTownFromTile(t);
01409         if (town != NULL) tid = town->index;
01410       }
01411       SetTownIndex(t, tid);
01412     }
01413   }
01414 }
01415 
01416 static uint GetSlopeZ_Road(TileIndex tile, uint x, uint y)
01417 {
01418   uint z;
01419   Slope tileh = GetTileSlope(tile, &z);
01420 
01421   if (tileh == SLOPE_FLAT) return z;
01422   if (IsNormalRoad(tile)) {
01423     Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
01424     z += ApplyFoundationToSlope(f, &tileh);
01425     return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
01426   } else {
01427     return z + TILE_HEIGHT;
01428   }
01429 }
01430 
01431 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
01432 {
01433   if (IsNormalRoad(tile)) {
01434     return GetRoadFoundation(tileh, GetAllRoadBits(tile));
01435   } else {
01436     return FlatteningFoundation(tileh);
01437   }
01438 }
01439 
01446 static void AnimateTile_Road(TileIndex tile)
01447 {
01448   if (_settings_game.construction.traffic_lights && HasTrafficLights(tile)) {
01449     if (_tick_counter % 16 == 0) MarkTileDirtyByTile(tile);
01450   }
01451 }
01452 
01453 static const Roadside _town_road_types[][2] = {
01454   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
01455   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01456   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01457   { ROADSIDE_TREES,         ROADSIDE_TREES },
01458   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
01459 };
01460 
01461 static const Roadside _town_road_types_2[][2] = {
01462   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
01463   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01464   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
01465   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
01466   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
01467 };
01468 
01469 
01470 static void TileLoop_Road(TileIndex tile)
01471 {
01472   switch (_settings_game.game_creation.landscape) {
01473     case LT_ARCTIC:
01474       if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
01475         ToggleSnow(tile);
01476         MarkTileDirtyByTile(tile);
01477       }
01478       break;
01479 
01480     case LT_TROPIC:
01481       if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
01482         ToggleDesert(tile);
01483         MarkTileDirtyByTile(tile);
01484       }
01485       break;
01486   }
01487 
01488   if (IsRoadDepot(tile)) return;
01489 
01490   const Town *t = ClosestTownFromTile(tile, UINT_MAX);
01491   if (!HasRoadWorks(tile)) {
01492     HouseZonesBits grp = HZB_TOWN_EDGE;
01493 
01494     if (t != NULL) {
01495       grp = GetTownRadiusGroup(t, tile);
01496 
01497       /* Show an animation to indicate road work */
01498       if (t->road_build_months != 0 &&
01499           (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
01500           IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
01501         if (GetFoundationSlope(tile, NULL) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
01502           StartRoadWorks(tile);
01503 
01504           SndPlayTileFx(SND_21_JACKHAMMER, tile);
01505           CreateEffectVehicleAbove(
01506             TileX(tile) * TILE_SIZE + 7,
01507             TileY(tile) * TILE_SIZE + 7,
01508             0,
01509             EV_BULLDOZER);
01510           MarkTileDirtyByTile(tile);
01511           return;
01512         }
01513       }
01514     }
01515 
01516     {
01517       /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
01518       const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
01519       Roadside cur_rs = GetRoadside(tile);
01520 
01521       /* We have our desired type, do nothing */
01522       if (cur_rs == new_rs[0]) return;
01523 
01524       /* We have the pre-type of the desired type, switch to the desired type */
01525       if (cur_rs == new_rs[1]) {
01526         cur_rs = new_rs[0];
01527       /* We have barren land, install the pre-type */
01528       } else if (cur_rs == ROADSIDE_BARREN) {
01529         cur_rs = new_rs[1];
01530       /* We're totally off limits, remove any installation and make barren land */
01531       } else {
01532         cur_rs = ROADSIDE_BARREN;
01533       }
01534       SetRoadside(tile, cur_rs);
01535       MarkTileDirtyByTile(tile);
01536     }
01537   } else {
01538     /* In the first half of roadworks, generate traffic lights with a certain chance. */
01539     if (_settings_game.construction.traffic_lights && _settings_game.construction.towns_build_traffic_lights &&
01540         (GetRoadWorksCounter(tile) < 8) && (CountBits(GetRoadBits(tile, ROADTYPE_ROAD)) >= 3) &&
01541         !HasTrafficLights(tile) && Chance16(1, 20)) {
01542       CmdBuildTrafficLights(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, 0, 0, 0);
01543       MarkTileDirtyByTile(tile);
01544     }
01545     if (IncreaseRoadWorksCounter(tile)) {
01546       TerminateRoadWorks(tile);
01547 
01548       if (_settings_game.economy.mod_road_rebuild) {
01549         /* Generate a nicer town surface. */
01550         const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
01551         const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
01552 
01553         if (old_rb != new_rb) {
01554           RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), ROADTYPE_ROAD, true, true);
01555         }
01556       }
01557 
01558       MarkTileDirtyByTile(tile);
01559     }
01560   }
01561 }
01562 
01563 static bool ClickTile_Road(TileIndex tile)
01564 {
01565   if (!IsRoadDepot(tile)) return false;
01566 
01567   ShowDepotWindow(tile, VEH_ROAD);
01568   return true;
01569 }
01570 
01571 /* Converts RoadBits to TrackBits */
01572 static const TrackBits _road_trackbits[16] = {
01573   TRACK_BIT_NONE,                                  // ROAD_NONE
01574   TRACK_BIT_NONE,                                  // ROAD_NW
01575   TRACK_BIT_NONE,                                  // ROAD_SW
01576   TRACK_BIT_LEFT,                                  // ROAD_W
01577   TRACK_BIT_NONE,                                  // ROAD_SE
01578   TRACK_BIT_Y,                                     // ROAD_Y
01579   TRACK_BIT_LOWER,                                 // ROAD_S
01580   TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y,  // ROAD_Y | ROAD_SW
01581   TRACK_BIT_NONE,                                  // ROAD_NE
01582   TRACK_BIT_UPPER,                                 // ROAD_N
01583   TRACK_BIT_X,                                     // ROAD_X
01584   TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X,  // ROAD_X | ROAD_NW
01585   TRACK_BIT_RIGHT,                                 // ROAD_E
01586   TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
01587   TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
01588   TRACK_BIT_ALL,                                   // ROAD_ALL
01589 };
01590 
01591 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01592 {
01593   TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
01594   TrackdirBits red_signals = TRACKDIR_BIT_NONE; // Crossing barred or red traffic light.
01595   switch (mode) {
01596     case TRANSPORT_RAIL:
01597       if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
01598       break;
01599 
01600     case TRANSPORT_ROAD:
01601       if ((GetRoadTypes(tile) & sub_mode) == 0) break;
01602       switch (GetRoadTileType(tile)) {
01603         case ROAD_TILE_NORMAL: {
01604           const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
01605           RoadType rt = (RoadType)FindFirstBit(sub_mode);
01606           RoadBits bits = GetRoadBits(tile, rt);
01607 
01608           /* no roadbit at this side of tile, return 0 */
01609           if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
01610 
01611           uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
01612           if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
01613           if (_settings_game.construction.traffic_lights && HasTrafficLights(tile))
01614               red_signals = trackdirbits & GetTrafficLightDisallowedDirections(tile);
01615           break;
01616         }
01617 
01618         case ROAD_TILE_CROSSING: {
01619           Axis axis = GetCrossingRoadAxis(tile);
01620 
01621           if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
01622 
01623           trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
01624           if (IsCrossingBarred(tile)) red_signals = trackdirbits;
01625           if (IsLevelCrossingTile(TileAddByDiagDir(tile, AxisToDiagDir(axis))) &&
01626               IsCrossingBarred(TileAddByDiagDir(tile, AxisToDiagDir(axis)))) {
01627             red_signals &= (TrackdirBits)0x0102; // magic value. I think TRACKBIT_X_SW and TRACKBIT_X_NE should be swapped
01628           }
01629           if (IsLevelCrossingTile(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis)))) &&
01630               IsCrossingBarred(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis))))) {
01631             red_signals &= (TrackdirBits)0x0201; // inverse of above magic value
01632           }
01633           break;
01634         }
01635 
01636         default:
01637         case ROAD_TILE_DEPOT: {
01638           DiagDirection dir = GetRoadDepotDirection(tile);
01639 
01640           if (side != INVALID_DIAGDIR && side != dir) break;
01641 
01642           trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
01643           break;
01644         }
01645       }
01646       break;
01647 
01648     default: break;
01649   }
01650   return CombineTrackStatus(trackdirbits, red_signals);
01651 }
01652 
01653 static const StringID _road_tile_strings[] = {
01654   STR_LAI_ROAD_DESCRIPTION_ROAD,
01655   STR_LAI_ROAD_DESCRIPTION_ROAD,
01656   STR_LAI_ROAD_DESCRIPTION_ROAD,
01657   STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
01658   STR_LAI_ROAD_DESCRIPTION_ROAD,
01659   STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
01660   STR_LAI_ROAD_DESCRIPTION_ROAD,
01661   STR_LAI_ROAD_DESCRIPTION_ROAD,
01662 };
01663 
01664 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
01665 {
01666   Owner rail_owner = INVALID_OWNER;
01667   Owner road_owner = INVALID_OWNER;
01668   Owner tram_owner = INVALID_OWNER;
01669 
01670   switch (GetRoadTileType(tile)) {
01671     case ROAD_TILE_CROSSING: {
01672       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
01673       RoadTypes rts = GetRoadTypes(tile);
01674       rail_owner = GetTileOwner(tile);
01675       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01676       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01677 
01678       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01679       td->rail_speed = rti->max_speed;
01680 
01681       break;
01682     }
01683 
01684     case ROAD_TILE_DEPOT:
01685       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
01686       road_owner = GetTileOwner(tile); // Tile has only one owner, roadtype does not matter
01687       td->build_date = Depot::GetByTile(tile)->build_date;
01688       break;
01689 
01690     default: {
01691       RoadTypes rts = GetRoadTypes(tile);
01692       if (HasTrafficLights(tile)) {
01693         td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_TRAFFIC_LIGHTS;
01694       } else {
01695         td->str = (HasBit(rts, ROADTYPE_ROAD) ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
01696       }
01697       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01698       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01699       break;
01700     }
01701   }
01702 
01703   /* Now we have to discover, if the tile has only one owner or many:
01704    *   - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
01705    *   - Compare the found owner with the other owners, and test if they differ.
01706    * Note: If road exists it will be the first_owner.
01707    */
01708   Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
01709   bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
01710 
01711   if (mixed_owners) {
01712     /* Multiple owners */
01713     td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
01714     td->owner[0] = rail_owner;
01715     td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
01716     td->owner[1] = road_owner;
01717     td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
01718     td->owner[2] = tram_owner;
01719   } else {
01720     /* One to rule them all */
01721     td->owner[0] = first_owner;
01722   }
01723 }
01724 
01729 static const byte _roadveh_enter_depot_dir[4] = {
01730   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
01731 };
01732 
01733 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
01734 {
01735   switch (GetRoadTileType(tile)) {
01736     case ROAD_TILE_DEPOT: {
01737       if (v->type != VEH_ROAD) break;
01738 
01739       RoadVehicle *rv = RoadVehicle::From(v);
01740       if (rv->frame == RVC_DEPOT_STOP_FRAME &&
01741           _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
01742         rv->state = RVSB_IN_DEPOT;
01743         rv->vehstatus |= VS_HIDDEN;
01744         rv->direction = ReverseDir(rv->direction);
01745         if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
01746         rv->tile = tile;
01747 
01748         InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
01749         return VETSB_ENTERED_WORMHOLE;
01750       }
01751       break;
01752     }
01753 
01754     default: break;
01755   }
01756   return VETSB_CONTINUE;
01757 }
01758 
01759 
01760 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
01761 {
01762   if (IsRoadDepot(tile)) {
01763     if (GetTileOwner(tile) == old_owner) {
01764       if (new_owner == INVALID_OWNER) {
01765         DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01766       } else {
01767         /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
01768         RoadType rt = (RoadType)FIND_FIRST_BIT(GetRoadTypes(tile));
01769         Company::Get(old_owner)->road_infrastructure[rt] -= 2;
01770         Company::Get(new_owner)->road_infrastructure[rt] += 2;
01771 
01772         SetTileOwner(tile, new_owner);
01773       }
01774     }
01775     return;
01776   }
01777 
01778   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01779     /* Update all roadtypes, no matter if they are present */
01780     if (GetRoadOwner(tile, rt) == old_owner) {
01781       if (HasTileRoadType(tile, rt)) {
01782         /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
01783         uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
01784         Company::Get(old_owner)->road_infrastructure[rt] -= num_bits;
01785         if (new_owner != INVALID_OWNER) Company::Get(new_owner)->road_infrastructure[rt] += num_bits;
01786       }
01787 
01788       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01789     }
01790   }
01791 
01792   if (IsLevelCrossing(tile)) {
01793     if (GetTileOwner(tile) == old_owner) {
01794       if (new_owner == INVALID_OWNER) {
01795         DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
01796       } else {
01797         /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
01798         Company::Get(old_owner)->rail_infrastructure[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
01799         Company::Get(new_owner)->rail_infrastructure[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
01800 
01801         SetTileOwner(tile, new_owner);
01802       }
01803     }
01804   }
01805 }
01806 
01807 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01808 {
01809   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
01810     switch (GetRoadTileType(tile)) {
01811       case ROAD_TILE_CROSSING:
01812         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]);
01813         break;
01814 
01815       case ROAD_TILE_DEPOT:
01816         if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01817         break;
01818 
01819       case ROAD_TILE_NORMAL: {
01820         RoadBits bits = GetAllRoadBits(tile);
01821         RoadBits bits_copy = bits;
01822         /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
01823         if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
01824           /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
01825           if (bits == bits_copy) {
01826             uint z_old;
01827             Slope tileh_old = GetTileSlope(tile, &z_old);
01828 
01829             /* Get the slope on top of the foundation */
01830             z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
01831             z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
01832 
01833             /* The surface slope must not be changed */
01834             if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01835           }
01836         }
01837         break;
01838       }
01839 
01840       default: NOT_REACHED();
01841     }
01842   }
01843 
01844   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01845 }
01846 
01848 extern const TileTypeProcs _tile_type_road_procs = {
01849   DrawTile_Road,           // draw_tile_proc
01850   GetSlopeZ_Road,          // get_slope_z_proc
01851   ClearTile_Road,          // clear_tile_proc
01852   NULL,                    // add_accepted_cargo_proc
01853   GetTileDesc_Road,        // get_tile_desc_proc
01854   GetTileTrackStatus_Road, // get_tile_track_status_proc
01855   ClickTile_Road,          // click_tile_proc
01856   AnimateTile_Road,        // animate_tile_proc
01857   TileLoop_Road,           // tile_loop_clear
01858   ChangeTileOwner_Road,    // change_tile_owner_clear
01859   NULL,                    // add_produced_cargo_proc
01860   VehicleEnter_Road,       // vehicle_enter_tile_proc
01861   GetFoundation_Road,      // get_foundation_proc
01862   TerraformTile_Road,      // terraform_tile_proc
01863 };