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       TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
00220       /* Pay for *every* tile of the bridge or tunnel */
00221       uint len = GetTunnelBridgeLength(other_end, tile) + 2;
00222       cost.AddCost(len * _price[PR_CLEAR_ROAD]);
00223       if (flags & DC_EXEC) {
00224         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00225         if (c != NULL) {
00226           /* A full diagonal road tile has two road bits. */
00227           c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
00228           DirtyCompanyInfrastructureWindows(c->index);
00229         }
00230 
00231         SetRoadTypes(other_end, GetRoadTypes(other_end) & ~RoadTypeToRoadTypes(rt));
00232         SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
00233 
00234         /* If the owner of the bridge sells all its road, also move the ownership
00235          * to the owner of the other roadtype. */
00236         RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
00237         Owner other_owner = GetRoadOwner(tile, other_rt);
00238         if (other_owner != GetTileOwner(tile)) {
00239           SetTileOwner(tile, other_owner);
00240           SetTileOwner(other_end, other_owner);
00241         }
00242 
00243         /* Mark tiles dirty that have been repaved */
00244         MarkTileDirtyByTile(tile);
00245         MarkTileDirtyByTile(other_end);
00246         if (IsBridge(tile)) {
00247           TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
00248 
00249           for (TileIndex t = tile + delta; t != other_end; t += delta) MarkTileDirtyByTile(t);
00250         }
00251       }
00252     } else {
00253       assert(IsDriveThroughStopTile(tile));
00254       cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
00255       if (flags & DC_EXEC) {
00256         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00257         if (c != NULL) {
00258           /* A full diagonal road tile has two road bits. */
00259           c->infrastructure.road[rt] -= 2;
00260           DirtyCompanyInfrastructureWindows(c->index);
00261         }
00262         SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
00263         MarkTileDirtyByTile(tile);
00264       }
00265     }
00266     return cost;
00267   }
00268 
00269   switch (GetRoadTileType(tile)) {
00270     case ROAD_TILE_NORMAL: {
00271       Slope tileh = GetTileSlope(tile);
00272 
00273       /* Steep slopes behave the same as slopes with one corner raised. */
00274       if (IsSteepSlope(tileh)) {
00275         tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
00276       }
00277 
00278       RoadBits present = GetRoadBits(tile, rt);
00279       const RoadBits other = GetOtherRoadBits(tile, rt);
00280       const Foundation f = GetRoadFoundation(tileh, present);
00281 
00282       if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
00283 
00284       /* Autocomplete to a straight road
00285        * @li if the bits of the other roadtypes result in another foundation
00286        * @li if build on slopes is disabled */
00287       if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
00288           (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
00289         pieces |= MirrorRoadBits(pieces);
00290       }
00291 
00292       /* limit the bits to delete to the existing bits. */
00293       pieces &= present;
00294       if (pieces == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
00295 
00296       /* Now set present what it will be after the remove */
00297       present ^= pieces;
00298 
00299       /* Check for invalid RoadBit combinations on slopes */
00300       if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
00301           (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
00302         return CMD_ERROR;
00303       }
00304 
00305       if (flags & DC_EXEC) {
00306         if (HasRoadWorks(tile)) {
00307           /* flooding tile with road works, don't forget to remove the effect vehicle too */
00308           assert(_current_company == OWNER_WATER);
00309           EffectVehicle *v;
00310           FOR_ALL_EFFECTVEHICLES(v) {
00311             if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
00312               delete v;
00313             }
00314           }
00315         }
00316 
00317         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00318         if (c != NULL) {
00319           c->infrastructure.road[rt] -= CountBits(pieces);
00320           DirtyCompanyInfrastructureWindows(c->index);
00321         }
00322 
00323         if (present == ROAD_NONE) {
00324           RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
00325           if (rts == ROADTYPES_NONE) {
00326             /* Includes MarkTileDirtyByTile() */
00327             DoClearSquare(tile);
00328           } else {
00329             if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
00330               /* Update nearest-town index */
00331               const Town *town = CalcClosestTownFromTile(tile);
00332               SetTownIndex(tile, town == NULL ? (TownID)INVALID_TOWN : town->index);
00333             }
00334             SetRoadBits(tile, ROAD_NONE, rt);
00335             SetRoadTypes(tile, rts);
00336             MarkTileDirtyByTile(tile);
00337           }
00338         } else {
00339           /* When bits are removed, you *always* end up with something that
00340            * is not a complete straight road tile. However, trams do not have
00341            * onewayness, so they cannot remove it either. */
00342           if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
00343           SetRoadBits(tile, present, rt);
00344           MarkTileDirtyByTile(tile);
00345         }
00346       }
00347 
00348       CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
00349       /* If we build a foundation we have to pay for it. */
00350       if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00351 
00352       return cost;
00353     }
00354 
00355     case ROAD_TILE_CROSSING: {
00356       if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
00357         return CMD_ERROR;
00358       }
00359 
00360       /* Don't allow road to be removed from the crossing when there is tram;
00361        * we can't draw the crossing without roadbits ;) */
00362       if (rt == ROADTYPE_ROAD && HasTileRoadType(tile, ROADTYPE_TRAM) && (flags & DC_EXEC || crossing_check)) return CMD_ERROR;
00363 
00364       if (flags & DC_EXEC) {
00365         Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00366         if (c != NULL) {
00367           /* A full diagonal road tile has two road bits. */
00368           c->infrastructure.road[rt] -= 2;
00369           DirtyCompanyInfrastructureWindows(c->index);
00370         }
00371 
00372         Track railtrack = GetCrossingRailTrack(tile);
00373         RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
00374         if (rts == ROADTYPES_NONE) {
00375           TrackBits tracks = GetCrossingRailBits(tile);
00376           bool reserved = HasCrossingReservation(tile);
00377           MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
00378           if (reserved) SetTrackReservation(tile, tracks);
00379 
00380           /* Update rail count for level crossings. The plain track should still be accounted
00381            * for, so only subtract the difference to the level crossing cost. */
00382           c = Company::GetIfValid(GetTileOwner(tile));
00383           if (c != NULL) c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
00384         } else {
00385           SetRoadTypes(tile, rts);
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   /* Steep slopes behave the same as slopes with one corner raised. */
00423   if (IsSteepSlope(tileh)) {
00424     tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
00425   }
00426 
00427   /* Save the merge of all bits of the current type */
00428   RoadBits type_bits = existing | *pieces;
00429 
00430   /* Roads on slopes */
00431   if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
00432 
00433     /* If we add leveling we've got to pay for it */
00434     if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00435 
00436     return CommandCost();
00437   }
00438 
00439   /* Autocomplete uphill roads */
00440   *pieces |= MirrorRoadBits(*pieces);
00441   type_bits = existing | *pieces;
00442 
00443   /* Uphill roads */
00444   if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
00445       (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
00446 
00447     /* Slopes with foundation ? */
00448     if (IsSlopeWithOneCornerRaised(tileh)) {
00449 
00450       /* Prevent build on slopes if it isn't allowed */
00451       if (_settings_game.construction.build_on_slopes) {
00452 
00453         /* If we add foundation we've got to pay for it */
00454         if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00455 
00456         return CommandCost();
00457       }
00458     } else {
00459       if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00460       return CommandCost();
00461     }
00462   }
00463   return CMD_ERROR;
00464 }
00465 
00477 CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00478 {
00479   CompanyID company = _current_company;
00480   CommandCost cost(EXPENSES_CONSTRUCTION);
00481 
00482   RoadBits existing = ROAD_NONE;
00483   RoadBits other_bits = ROAD_NONE;
00484 
00485   /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
00486    * if a non-company is building the road */
00487   if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CMD_ERROR;
00488   if (company != OWNER_TOWN) {
00489     const Town *town = CalcClosestTownFromTile(tile);
00490     p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
00491 
00492     if (company == OWNER_DEITY) {
00493       company = OWNER_TOWN;
00494 
00495       /* If we are not within a town, we are not owned by the town */
00496       if (town == NULL || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
00497         company = OWNER_NONE;
00498       }
00499     }
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);
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(company);
00620         if (c != NULL) {
00621           c->infrastructure.road[rt] += 2;
00622           if (rt != ROADTYPE_ROAD) c->infrastructure.road[ROADTYPE_ROAD] += 2;
00623           DirtyCompanyInfrastructureWindows(company);
00624         }
00625         /* Update rail count for level crossings. The plain track is already
00626          * counted, so only add the difference to the level crossing cost. */
00627         c = Company::GetIfValid(GetTileOwner(tile));
00628         if (c != NULL) c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
00629 
00630         /* Always add road to the roadtypes (can't draw without it) */
00631         bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
00632         MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
00633         SetCrossingReservation(tile, reserved);
00634         UpdateLevelCrossing(tile, false);
00635         MarkTileDirtyByTile(tile);
00636       }
00637       return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
00638     }
00639 
00640     case MP_STATION: {
00641       if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00642       if (!IsDriveThroughStopTile(tile)) goto do_clear;
00643 
00644       RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
00645       if (pieces & ~curbits) goto do_clear;
00646       pieces = curbits; // we need to pay for both roadbits
00647 
00648       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00649       break;
00650     }
00651 
00652     case MP_TUNNELBRIDGE: {
00653       if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
00654       if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
00655       if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
00656       /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
00657       CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
00658       if (ret.Failed()) return ret;
00659       break;
00660     }
00661 
00662     default: {
00663 do_clear:;
00664       need_to_clear = true;
00665       break;
00666     }
00667   }
00668 
00669   if (need_to_clear) {
00670     CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00671     if (ret.Failed()) return ret;
00672     cost.AddCost(ret);
00673   }
00674 
00675   if (other_bits != pieces) {
00676     /* Check the foundation/slopes when adding road/tram bits */
00677     CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
00678     /* Return an error if we need to build a foundation (ret != 0) but the
00679      * current setting is turned off */
00680     if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
00681       return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00682     }
00683     cost.AddCost(ret);
00684   }
00685 
00686   if (!need_to_clear) {
00687     if (IsTileType(tile, MP_ROAD)) {
00688       /* Don't put the pieces that already exist */
00689       pieces &= ComplementRoadBits(existing);
00690 
00691       /* Check if new road bits will have the same foundation as other existing road types */
00692       if (IsNormalRoad(tile)) {
00693         Slope slope = GetTileSlope(tile);
00694         Foundation found_new = GetRoadFoundation(slope, pieces | existing);
00695 
00696         /* Test if all other roadtypes can be built at that foundation */
00697         for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
00698           if (rtest != rt) { // check only other road types
00699             RoadBits bits = GetRoadBits(tile, rtest);
00700             /* do not check if there are not road bits of given type */
00701             if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
00702               return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00703             }
00704           }
00705         }
00706       }
00707     }
00708 
00709     CommandCost ret = EnsureNoVehicleOnGround(tile);
00710     if (ret.Failed()) return ret;
00711 
00712   }
00713 
00714   uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
00715       /* There are 2 pieces on *every* tile of the bridge or tunnel */
00716       2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
00717       /* Count pieces */
00718       CountBits(pieces);
00719 
00720   cost.AddCost(num_pieces * _price[PR_BUILD_ROAD]);
00721 
00722   if (flags & DC_EXEC) {
00723     switch (GetTileType(tile)) {
00724       case MP_ROAD: {
00725         RoadTileType rtt = GetRoadTileType(tile);
00726         if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
00727           SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00728           SetRoadOwner(tile, rt, company);
00729           if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
00730         }
00731         if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
00732         break;
00733       }
00734 
00735       case MP_TUNNELBRIDGE: {
00736         TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
00737 
00738         SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
00739         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00740         SetRoadOwner(other_end, rt, company);
00741         SetRoadOwner(tile, rt, company);
00742 
00743         /* Mark tiles dirty that have been repaved */
00744         MarkTileDirtyByTile(other_end);
00745         MarkTileDirtyByTile(tile);
00746         if (IsBridge(tile)) {
00747           TileIndexDiff delta = TileOffsByDiagDir(GetTunnelBridgeDirection(tile));
00748 
00749           for (TileIndex t = tile + delta; t != other_end; t += delta) MarkTileDirtyByTile(t);
00750         }
00751         break;
00752       }
00753 
00754       case MP_STATION:
00755         assert(IsDriveThroughStopTile(tile));
00756         SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
00757         SetRoadOwner(tile, rt, company);
00758         break;
00759 
00760       default:
00761         MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, company, company);
00762         break;
00763     }
00764 
00765     /* Update company infrastructure count. */
00766     Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
00767     if (c != NULL) {
00768       if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
00769       c->infrastructure.road[rt] += num_pieces;
00770       DirtyCompanyInfrastructureWindows(c->index);
00771     }
00772 
00773     if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
00774       existing |= pieces;
00775       SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
00776           GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
00777     }
00778 
00779     MarkTileDirtyByTile(tile);
00780   }
00781   return cost;
00782 }
00783 
00799 CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00800 {
00801   DisallowedRoadDirections drd = DRD_NORTHBOUND;
00802 
00803   if (p1 >= MapSize()) return CMD_ERROR;
00804 
00805   TileIndex end_tile = p1;
00806   RoadType rt = Extract<RoadType, 3, 2>(p2);
00807   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
00808 
00809   Axis axis = Extract<Axis, 2, 1>(p2);
00810   /* Only drag in X or Y direction dictated by the direction variable */
00811   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
00812   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
00813 
00814   DiagDirection dir = AxisToDiagDir(axis);
00815 
00816   /* Swap direction, also the half-tile drag var (bit 0 and 1) */
00817   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
00818     dir = ReverseDiagDir(dir);
00819     p2 ^= 3;
00820     drd = DRD_SOUTHBOUND;
00821   }
00822 
00823   /* On the X-axis, we have to swap the initial bits, so they
00824    * will be interpreted correctly in the GTTS. Furthermore
00825    * when you just 'click' on one tile to build them. */
00826   if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
00827   /* No disallowed direction bits have to be toggled */
00828   if (!HasBit(p2, 5)) drd = DRD_NONE;
00829 
00830   CommandCost cost(EXPENSES_CONSTRUCTION);
00831   CommandCost last_error = CMD_ERROR;
00832   TileIndex tile = start_tile;
00833   bool had_bridge = false;
00834   bool had_tunnel = false;
00835   bool had_success = false;
00836   /* Start tile is the first tile clicked by the user. */
00837   for (;;) {
00838     RoadBits bits = AxisToRoadBits(axis);
00839 
00840     /* Road parts only have to be built at the start tile or at the end tile. */
00841     if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
00842     if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
00843 
00844     CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits, 0, flags, CMD_BUILD_ROAD);
00845     if (ret.Failed()) {
00846       last_error = ret;
00847       if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
00848         if (HasBit(p2, 6)) return last_error;
00849         break;
00850       }
00851     } else {
00852       had_success = true;
00853       /* Only pay for the upgrade on one side of the bridges and tunnels */
00854       if (IsTileType(tile, MP_TUNNELBRIDGE)) {
00855         if (IsBridge(tile)) {
00856           if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
00857             cost.AddCost(ret);
00858           }
00859           had_bridge = true;
00860         } else { // IsTunnel(tile)
00861           if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
00862             cost.AddCost(ret);
00863           }
00864           had_tunnel = true;
00865         }
00866       } else {
00867         cost.AddCost(ret);
00868       }
00869     }
00870 
00871     if (tile == end_tile) break;
00872 
00873     tile += TileOffsByDiagDir(dir);
00874   }
00875 
00876   return had_success ? cost : last_error;
00877 }
00878 
00892 CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00893 {
00894   CommandCost cost(EXPENSES_CONSTRUCTION);
00895 
00896   if (p1 >= MapSize()) return CMD_ERROR;
00897 
00898   TileIndex end_tile = p1;
00899   RoadType rt = Extract<RoadType, 3, 2>(p2);
00900   if (!IsValidRoadType(rt)) return CMD_ERROR;
00901 
00902   Axis axis = Extract<Axis, 2, 1>(p2);
00903   /* Only drag in X or Y direction dictated by the direction variable */
00904   if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
00905   if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
00906 
00907   /* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
00908   if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
00909     TileIndex t = start_tile;
00910     start_tile = end_tile;
00911     end_tile = t;
00912     p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
00913   }
00914 
00915   Money money = GetAvailableMoneyForCommand();
00916   TileIndex tile = start_tile;
00917   CommandCost last_error = CMD_ERROR;
00918   bool had_success = false;
00919   /* Start tile is the small number. */
00920   for (;;) {
00921     RoadBits bits = AxisToRoadBits(axis);
00922 
00923     if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
00924     if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
00925 
00926     /* try to remove the halves. */
00927     if (bits != 0) {
00928       CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true);
00929       if (ret.Succeeded()) {
00930         if (flags & DC_EXEC) {
00931           money -= ret.GetCost();
00932           if (money < 0) {
00933             _additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
00934             return cost;
00935           }
00936           RemoveRoad(tile, flags, bits, rt, true, false);
00937         }
00938         cost.AddCost(ret);
00939         had_success = true;
00940       } else {
00941         /* Ownership errors are more important. */
00942         if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
00943       }
00944     }
00945 
00946     if (tile == end_tile) break;
00947 
00948     tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
00949   }
00950 
00951   return had_success ? cost : last_error;
00952 }
00953 
00967 CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00968 {
00969   DiagDirection dir = Extract<DiagDirection, 0, 2>(p1);
00970   RoadType rt = Extract<RoadType, 2, 2>(p1);
00971 
00972   if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
00973 
00974   Slope tileh = GetTileSlope(tile);
00975   if (tileh != SLOPE_FLAT && (
00976         !_settings_game.construction.build_on_slopes ||
00977         !CanBuildDepotByTileh(dir, tileh)
00978       )) {
00979     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00980   }
00981 
00982   CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00983   if (cost.Failed()) return cost;
00984 
00985   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00986 
00987   if (!Depot::CanAllocateItem()) return CMD_ERROR;
00988 
00989   if (flags & DC_EXEC) {
00990     Depot *dep = new Depot(tile);
00991     dep->build_date = _date;
00992 
00993     /* A road depot has two road bits. */
00994     Company::Get(_current_company)->infrastructure.road[rt] += 2;
00995     DirtyCompanyInfrastructureWindows(_current_company);
00996 
00997     MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
00998     MarkTileDirtyByTile(tile);
00999     MakeDefaultName(dep);
01000   }
01001   cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
01002   return cost;
01003 }
01004 
01005 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
01006 {
01007   if (_current_company != OWNER_WATER) {
01008     CommandCost ret = CheckTileOwnership(tile);
01009     if (ret.Failed()) return ret;
01010   }
01011 
01012   CommandCost ret = EnsureNoVehicleOnGround(tile);
01013   if (ret.Failed()) return ret;
01014 
01015   if (flags & DC_EXEC) {
01016     Company *c = Company::GetIfValid(GetTileOwner(tile));
01017     if (c != NULL) {
01018       /* A road depot has two road bits. */
01019       c->infrastructure.road[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
01020       DirtyCompanyInfrastructureWindows(c->index);
01021     }
01022 
01023     delete Depot::GetByTile(tile);
01024     DoClearSquare(tile);
01025   }
01026 
01027   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
01028 }
01029 
01030 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
01031 {
01032   switch (GetRoadTileType(tile)) {
01033     case ROAD_TILE_NORMAL: {
01034       RoadBits b = GetAllRoadBits(tile);
01035 
01036       /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
01037       if ((HasExactlyOneBit(b) && GetRoadBits(tile, ROADTYPE_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
01038         CommandCost ret(EXPENSES_CONSTRUCTION);
01039         RoadType rt;
01040         FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01041           CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rt), rt, true);
01042           if (tmp_ret.Failed()) return tmp_ret;
01043           ret.AddCost(tmp_ret);
01044         }
01045         return ret;
01046       }
01047       return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
01048     }
01049 
01050     case ROAD_TILE_CROSSING: {
01051       RoadTypes rts = GetRoadTypes(tile);
01052       CommandCost ret(EXPENSES_CONSTRUCTION);
01053 
01054       if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
01055 
01056       /* Must iterate over the roadtypes in a reverse manner because
01057        * tram tracks must be removed before the road bits. */
01058       RoadType rt = ROADTYPE_TRAM;
01059       do {
01060         if (HasBit(rts, rt)) {
01061           CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rt, false);
01062           if (tmp_ret.Failed()) return tmp_ret;
01063           ret.AddCost(tmp_ret);
01064         }
01065       } while (rt-- != ROADTYPE_ROAD);
01066 
01067       if (flags & DC_EXEC) {
01068         DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01069       }
01070       return ret;
01071     }
01072 
01073     default:
01074     case ROAD_TILE_DEPOT:
01075       if (flags & DC_AUTO) {
01076         return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
01077       }
01078       return RemoveRoadDepot(tile, flags);
01079   }
01080 }
01081 
01082 
01083 struct DrawRoadTileStruct {
01084   uint16 image;
01085   byte subcoord_x;
01086   byte subcoord_y;
01087 };
01088 
01089 #include "table/road_land.h"
01090 
01098 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
01099 {
01100   /* Flat land and land without a road doesn't require a foundation */
01101   if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
01102 
01103   /* Steep slopes behave the same as slopes with one corner raised. */
01104   if (IsSteepSlope(tileh)) {
01105     tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
01106   }
01107 
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   /* Roads on steep Slopes or on Slopes with one corner raised */
01117   return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
01118 }
01119 
01120 const byte _road_sloped_sprites[14] = {
01121   0,  0,  2,  0,
01122   0,  1,  0,  0,
01123   3,  0,  0,  0,
01124   0,  0
01125 };
01126 
01137 static bool AlwaysDrawUnpavedRoads(TileIndex tile, Roadside roadside)
01138 {
01139   return (IsOnSnow(tile) &&
01140       !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
01141         roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
01142 }
01143 
01149 void DrawTramCatenary(const TileInfo *ti, RoadBits tram)
01150 {
01151   /* Do not draw catenary if it is invisible */
01152   if (IsInvisibilitySet(TO_CATENARY)) return;
01153 
01154   /* Don't draw the catenary under a low bridge */
01155   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
01156     int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
01157 
01158     if (height <= GetTileMaxZ(ti->tile) + 1) return;
01159   }
01160 
01161   SpriteID front;
01162   SpriteID back;
01163 
01164   if (ti->tileh != SLOPE_FLAT) {
01165     back  = SPR_TRAMWAY_BACK_WIRES_SLOPED  + _road_sloped_sprites[ti->tileh - 1];
01166     front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
01167   } else {
01168     back  = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[tram];
01169     front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
01170   }
01171 
01172   AddSortableSpriteToDraw(back,  PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
01173   AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, TILE_HEIGHT + BB_HEIGHT_UNDER_BRIDGE, ti->z, IsTransparencySet(TO_CATENARY));
01174 }
01175 
01184 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h)
01185 {
01186   int x = ti->x | dx;
01187   int y = ti->y | dy;
01188   int z = ti->z;
01189   if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
01190   AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z);
01191 }
01192 
01197 static void DrawRoadBits(TileInfo *ti)
01198 {
01199   RoadBits road = GetRoadBits(ti->tile, ROADTYPE_ROAD);
01200   RoadBits tram = GetRoadBits(ti->tile, ROADTYPE_TRAM);
01201 
01202   SpriteID image = 0;
01203   PaletteID pal = PAL_NONE;
01204 
01205   if (ti->tileh != SLOPE_FLAT) {
01206     DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
01207 
01208     /* DrawFoundation() modifies ti.
01209      * Default sloped sprites.. */
01210     if (ti->tileh != SLOPE_FLAT) image = _road_sloped_sprites[ti->tileh - 1] + SPR_ROAD_SLOPE_START;
01211   }
01212 
01213   if (image == 0) image = _road_tile_sprites_1[road != ROAD_NONE ? road : tram];
01214 
01215   Roadside roadside = GetRoadside(ti->tile);
01216 
01217   if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01218     image += 19;
01219   } else {
01220     switch (roadside) {
01221       case ROADSIDE_BARREN:           pal = PALETTE_TO_BARE_LAND; break;
01222       case ROADSIDE_GRASS:            break;
01223       case ROADSIDE_GRASS_ROAD_WORKS: break;
01224       default:                        image -= 19; break; // Paved
01225     }
01226   }
01227 
01228   DrawGroundSprite(image, pal);
01229 
01230   /* For tram we overlay the road graphics with either tram tracks only
01231    * (when there is actual road beneath the trams) or with tram tracks
01232    * and some dirts which hides the road graphics */
01233   if (tram != ROAD_NONE) {
01234     if (ti->tileh != SLOPE_FLAT) {
01235       image = _road_sloped_sprites[ti->tileh - 1] + SPR_TRAMWAY_SLOPED_OFFSET;
01236     } else {
01237       image = _road_tile_sprites_1[tram] - SPR_ROAD_Y;
01238     }
01239     image += (road == ROAD_NONE) ? SPR_TRAMWAY_TRAM : SPR_TRAMWAY_OVERLAY;
01240     DrawGroundSprite(image, pal);
01241   }
01242 
01243   if (road != ROAD_NONE) {
01244     DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
01245     if (drd != DRD_NONE) {
01246       DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
01247     }
01248   }
01249 
01250   if (HasRoadWorks(ti->tile)) {
01251     /* Road works */
01252     DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
01253     return;
01254   }
01255 
01256   if (tram != ROAD_NONE) DrawTramCatenary(ti, tram);
01257 
01258   /* Return if full detail is disabled, or we are zoomed fully out. */
01259   if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
01260 
01261   /* Do not draw details (street lights, trees) under low bridge */
01262   if (MayHaveBridgeAbove(ti->tile) && IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
01263     int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
01264     int minz = GetTileMaxZ(ti->tile) + 2;
01265 
01266     if (roadside == ROADSIDE_TREES) minz++;
01267 
01268     if (height < minz) return;
01269   }
01270 
01271   /* If there are no road bits, return, as there is nothing left to do */
01272   if (HasAtMostOneBit(road)) return;
01273 
01274   /* Draw extra details. */
01275   for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
01276     DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10);
01277   }
01278 }
01279 
01281 static void DrawTile_Road(TileInfo *ti)
01282 {
01283   switch (GetRoadTileType(ti->tile)) {
01284     case ROAD_TILE_NORMAL:
01285       DrawRoadBits(ti);
01286       break;
01287 
01288     case ROAD_TILE_CROSSING: {
01289       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
01290 
01291       PaletteID pal = PAL_NONE;
01292       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01293 
01294       if (rti->UsesOverlay()) {
01295         Axis axis = GetCrossingRailAxis(ti->tile);
01296         SpriteID road = SPR_ROAD_Y + axis;
01297 
01298         Roadside roadside = GetRoadside(ti->tile);
01299 
01300         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01301           road += 19;
01302         } else {
01303           switch (roadside) {
01304             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
01305             case ROADSIDE_GRASS:  break;
01306             default:              road -= 19; break; // Paved
01307           }
01308         }
01309 
01310         DrawGroundSprite(road, pal);
01311 
01312         SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
01313         /* Draw tracks, but draw PBS reserved tracks darker. */
01314         pal = (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) ? PALETTE_CRASH : PAL_NONE;
01315         DrawGroundSprite(rail, pal);
01316 
01317         DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
01318       } else {
01319         SpriteID image = rti->base_sprites.crossing;
01320 
01321         if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
01322         if (IsCrossingBarred(ti->tile)) image += 2;
01323 
01324         Roadside roadside = GetRoadside(ti->tile);
01325 
01326         if (AlwaysDrawUnpavedRoads(ti->tile, roadside)) {
01327           image += 8;
01328         } else {
01329           switch (roadside) {
01330             case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
01331             case ROADSIDE_GRASS:  break;
01332             default:              image += 4; break; // Paved
01333           }
01334         }
01335 
01336         DrawGroundSprite(image, pal);
01337 
01338         /* PBS debugging, draw reserved tracks darker */
01339         if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile)) {
01340           DrawGroundSprite(GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y, PALETTE_CRASH);
01341         }
01342       }
01343 
01344       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
01345         DrawGroundSprite(SPR_TRAMWAY_OVERLAY + (GetCrossingRoadAxis(ti->tile) ^ 1), pal);
01346         DrawTramCatenary(ti, GetCrossingRoadBits(ti->tile));
01347       }
01348       if (HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
01349       break;
01350     }
01351 
01352     default:
01353     case ROAD_TILE_DEPOT: {
01354       if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
01355 
01356       PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
01357 
01358       const DrawTileSprites *dts;
01359       if (HasTileRoadType(ti->tile, ROADTYPE_TRAM)) {
01360         dts =  &_tram_depot[GetRoadDepotDirection(ti->tile)];
01361       } else {
01362         dts =  &_road_depot[GetRoadDepotDirection(ti->tile)];
01363       }
01364 
01365       DrawGroundSprite(dts->ground.sprite, PAL_NONE);
01366       DrawOrigTileSeq(ti, dts, TO_BUILDINGS, palette);
01367       break;
01368     }
01369   }
01370   DrawBridgeMiddle(ti);
01371 }
01372 
01380 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
01381 {
01382   PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
01383   const DrawTileSprites *dts = (rt == ROADTYPE_TRAM) ? &_tram_depot[dir] : &_road_depot[dir];
01384 
01385   x += 33;
01386   y += 17;
01387 
01388   DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
01389   DrawOrigTileSeqInGUI(x, y, dts, palette);
01390 }
01391 
01397 void UpdateNearestTownForRoadTiles(bool invalidate)
01398 {
01399   assert(!invalidate || _generating_world);
01400 
01401   for (TileIndex t = 0; t < MapSize(); t++) {
01402     if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
01403       TownID tid = (TownID)INVALID_TOWN;
01404       if (!invalidate) {
01405         const Town *town = CalcClosestTownFromTile(t);
01406         if (town != NULL) tid = town->index;
01407       }
01408       SetTownIndex(t, tid);
01409     }
01410   }
01411 }
01412 
01413 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
01414 {
01415 
01416   if (IsNormalRoad(tile)) {
01417     int z;
01418     Slope tileh = GetTilePixelSlope(tile, &z);
01419     if (tileh == SLOPE_FLAT) return z;
01420 
01421     Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
01422     z += ApplyPixelFoundationToSlope(f, &tileh);
01423     return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
01424   } else {
01425     return GetTileMaxPixelZ(tile);
01426   }
01427 }
01428 
01429 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
01430 {
01431   if (IsNormalRoad(tile)) {
01432     return GetRoadFoundation(tileh, GetAllRoadBits(tile));
01433   } else {
01434     return FlatteningFoundation(tileh);
01435   }
01436 }
01437 
01438 static const Roadside _town_road_types[][2] = {
01439   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
01440   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01441   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01442   { ROADSIDE_TREES,         ROADSIDE_TREES },
01443   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
01444 };
01445 
01446 static const Roadside _town_road_types_2[][2] = {
01447   { ROADSIDE_GRASS,         ROADSIDE_GRASS },
01448   { ROADSIDE_PAVED,         ROADSIDE_PAVED },
01449   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
01450   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
01451   { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
01452 };
01453 
01454 
01455 static void TileLoop_Road(TileIndex tile)
01456 {
01457   switch (_settings_game.game_creation.landscape) {
01458     case LT_ARCTIC:
01459       if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
01460         ToggleSnow(tile);
01461         MarkTileDirtyByTile(tile);
01462       }
01463       break;
01464 
01465     case LT_TROPIC:
01466       if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
01467         ToggleDesert(tile);
01468         MarkTileDirtyByTile(tile);
01469       }
01470       break;
01471   }
01472 
01473   if (IsRoadDepot(tile)) return;
01474 
01475   const Town *t = ClosestTownFromTile(tile, UINT_MAX);
01476   if (!HasRoadWorks(tile)) {
01477     HouseZonesBits grp = HZB_TOWN_EDGE;
01478 
01479     if (t != NULL) {
01480       grp = GetTownRadiusGroup(t, tile);
01481 
01482       /* Show an animation to indicate road work */
01483       if (t->road_build_months != 0 &&
01484           (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
01485           IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
01486         if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
01487           StartRoadWorks(tile);
01488 
01489           SndPlayTileFx(SND_21_JACKHAMMER, tile);
01490           CreateEffectVehicleAbove(
01491             TileX(tile) * TILE_SIZE + 7,
01492             TileY(tile) * TILE_SIZE + 7,
01493             0,
01494             EV_BULLDOZER);
01495           MarkTileDirtyByTile(tile);
01496           return;
01497         }
01498       }
01499     }
01500 
01501     {
01502       /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
01503       const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
01504       Roadside cur_rs = GetRoadside(tile);
01505 
01506       /* We have our desired type, do nothing */
01507       if (cur_rs == new_rs[0]) return;
01508 
01509       /* We have the pre-type of the desired type, switch to the desired type */
01510       if (cur_rs == new_rs[1]) {
01511         cur_rs = new_rs[0];
01512       /* We have barren land, install the pre-type */
01513       } else if (cur_rs == ROADSIDE_BARREN) {
01514         cur_rs = new_rs[1];
01515       /* We're totally off limits, remove any installation and make barren land */
01516       } else {
01517         cur_rs = ROADSIDE_BARREN;
01518       }
01519       SetRoadside(tile, cur_rs);
01520       MarkTileDirtyByTile(tile);
01521     }
01522   } else if (IncreaseRoadWorksCounter(tile)) {
01523     TerminateRoadWorks(tile);
01524 
01525     if (_settings_game.economy.mod_road_rebuild) {
01526       /* Generate a nicer town surface */
01527       const RoadBits old_rb = GetAnyRoadBits(tile, ROADTYPE_ROAD);
01528       const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
01529 
01530       if (old_rb != new_rb) {
01531         RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), ROADTYPE_ROAD, true);
01532       }
01533     }
01534 
01535     MarkTileDirtyByTile(tile);
01536   }
01537 }
01538 
01539 static bool ClickTile_Road(TileIndex tile)
01540 {
01541   if (!IsRoadDepot(tile)) return false;
01542 
01543   ShowDepotWindow(tile, VEH_ROAD);
01544   return true;
01545 }
01546 
01547 /* Converts RoadBits to TrackBits */
01548 static const TrackBits _road_trackbits[16] = {
01549   TRACK_BIT_NONE,                                  // ROAD_NONE
01550   TRACK_BIT_NONE,                                  // ROAD_NW
01551   TRACK_BIT_NONE,                                  // ROAD_SW
01552   TRACK_BIT_LEFT,                                  // ROAD_W
01553   TRACK_BIT_NONE,                                  // ROAD_SE
01554   TRACK_BIT_Y,                                     // ROAD_Y
01555   TRACK_BIT_LOWER,                                 // ROAD_S
01556   TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y,  // ROAD_Y | ROAD_SW
01557   TRACK_BIT_NONE,                                  // ROAD_NE
01558   TRACK_BIT_UPPER,                                 // ROAD_N
01559   TRACK_BIT_X,                                     // ROAD_X
01560   TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X,  // ROAD_X | ROAD_NW
01561   TRACK_BIT_RIGHT,                                 // ROAD_E
01562   TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
01563   TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
01564   TRACK_BIT_ALL,                                   // ROAD_ALL
01565 };
01566 
01567 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01568 {
01569   TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
01570   TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
01571   switch (mode) {
01572     case TRANSPORT_RAIL:
01573       if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
01574       break;
01575 
01576     case TRANSPORT_ROAD:
01577       if ((GetRoadTypes(tile) & sub_mode) == 0) break;
01578       switch (GetRoadTileType(tile)) {
01579         case ROAD_TILE_NORMAL: {
01580           const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
01581           RoadType rt = (RoadType)FindFirstBit(sub_mode);
01582           RoadBits bits = GetRoadBits(tile, rt);
01583 
01584           /* no roadbit at this side of tile, return 0 */
01585           if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
01586 
01587           uint multiplier = drd_to_multiplier[rt == ROADTYPE_TRAM ? DRD_NONE : GetDisallowedRoadDirections(tile)];
01588           if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
01589           break;
01590         }
01591 
01592         case ROAD_TILE_CROSSING: {
01593           Axis axis = GetCrossingRoadAxis(tile);
01594 
01595           if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
01596 
01597           trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
01598           if (IsCrossingBarred(tile)) red_signals = trackdirbits;
01599           break;
01600         }
01601 
01602         default:
01603         case ROAD_TILE_DEPOT: {
01604           DiagDirection dir = GetRoadDepotDirection(tile);
01605 
01606           if (side != INVALID_DIAGDIR && side != dir) break;
01607 
01608           trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
01609           break;
01610         }
01611       }
01612       break;
01613 
01614     default: break;
01615   }
01616   return CombineTrackStatus(trackdirbits, red_signals);
01617 }
01618 
01619 static const StringID _road_tile_strings[] = {
01620   STR_LAI_ROAD_DESCRIPTION_ROAD,
01621   STR_LAI_ROAD_DESCRIPTION_ROAD,
01622   STR_LAI_ROAD_DESCRIPTION_ROAD,
01623   STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
01624   STR_LAI_ROAD_DESCRIPTION_ROAD,
01625   STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
01626   STR_LAI_ROAD_DESCRIPTION_ROAD,
01627   STR_LAI_ROAD_DESCRIPTION_ROAD,
01628 };
01629 
01630 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
01631 {
01632   Owner rail_owner = INVALID_OWNER;
01633   Owner road_owner = INVALID_OWNER;
01634   Owner tram_owner = INVALID_OWNER;
01635 
01636   switch (GetRoadTileType(tile)) {
01637     case ROAD_TILE_CROSSING: {
01638       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
01639       RoadTypes rts = GetRoadTypes(tile);
01640       rail_owner = GetTileOwner(tile);
01641       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01642       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01643 
01644       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01645       td->rail_speed = rti->max_speed;
01646 
01647       break;
01648     }
01649 
01650     case ROAD_TILE_DEPOT:
01651       td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
01652       road_owner = GetTileOwner(tile); // Tile has only one owner, roadtype does not matter
01653       td->build_date = Depot::GetByTile(tile)->build_date;
01654       break;
01655 
01656     default: {
01657       RoadTypes rts = GetRoadTypes(tile);
01658       td->str = (HasBit(rts, ROADTYPE_ROAD) ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
01659       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01660       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01661       break;
01662     }
01663   }
01664 
01665   /* Now we have to discover, if the tile has only one owner or many:
01666    *   - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
01667    *   - Compare the found owner with the other owners, and test if they differ.
01668    * Note: If road exists it will be the first_owner.
01669    */
01670   Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
01671   bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
01672 
01673   if (mixed_owners) {
01674     /* Multiple owners */
01675     td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
01676     td->owner[0] = rail_owner;
01677     td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
01678     td->owner[1] = road_owner;
01679     td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
01680     td->owner[2] = tram_owner;
01681   } else {
01682     /* One to rule them all */
01683     td->owner[0] = first_owner;
01684   }
01685 }
01686 
01691 static const byte _roadveh_enter_depot_dir[4] = {
01692   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
01693 };
01694 
01695 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
01696 {
01697   switch (GetRoadTileType(tile)) {
01698     case ROAD_TILE_DEPOT: {
01699       if (v->type != VEH_ROAD) break;
01700 
01701       RoadVehicle *rv = RoadVehicle::From(v);
01702       if (rv->frame == RVC_DEPOT_STOP_FRAME &&
01703           _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
01704         rv->state = RVSB_IN_DEPOT;
01705         rv->vehstatus |= VS_HIDDEN;
01706         rv->direction = ReverseDir(rv->direction);
01707         if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
01708         rv->tile = tile;
01709 
01710         InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
01711         return VETSB_ENTERED_WORMHOLE;
01712       }
01713       break;
01714     }
01715 
01716     default: break;
01717   }
01718   return VETSB_CONTINUE;
01719 }
01720 
01721 
01722 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
01723 {
01724   if (IsRoadDepot(tile)) {
01725     if (GetTileOwner(tile) == old_owner) {
01726       if (new_owner == INVALID_OWNER) {
01727         DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01728       } else {
01729         /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
01730         RoadType rt = (RoadType)FIND_FIRST_BIT(GetRoadTypes(tile));
01731         Company::Get(old_owner)->infrastructure.road[rt] -= 2;
01732         Company::Get(new_owner)->infrastructure.road[rt] += 2;
01733 
01734         SetTileOwner(tile, new_owner);
01735       }
01736     }
01737     return;
01738   }
01739 
01740   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01741     /* Update all roadtypes, no matter if they are present */
01742     if (GetRoadOwner(tile, rt) == old_owner) {
01743       if (HasTileRoadType(tile, rt)) {
01744         /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
01745         uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rt));
01746         Company::Get(old_owner)->infrastructure.road[rt] -= num_bits;
01747         if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_bits;
01748       }
01749 
01750       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01751     }
01752   }
01753 
01754   if (IsLevelCrossing(tile)) {
01755     if (GetTileOwner(tile) == old_owner) {
01756       if (new_owner == INVALID_OWNER) {
01757         DoCommand(tile, 0, GetCrossingRailTrack(tile), DC_EXEC | DC_BANKRUPT, CMD_REMOVE_SINGLE_RAIL);
01758       } else {
01759         /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
01760         Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
01761         Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
01762 
01763         SetTileOwner(tile, new_owner);
01764       }
01765     }
01766   }
01767 }
01768 
01769 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
01770 {
01771   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
01772     switch (GetRoadTileType(tile)) {
01773       case ROAD_TILE_CROSSING:
01774         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]);
01775         break;
01776 
01777       case ROAD_TILE_DEPOT:
01778         if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01779         break;
01780 
01781       case ROAD_TILE_NORMAL: {
01782         RoadBits bits = GetAllRoadBits(tile);
01783         RoadBits bits_copy = bits;
01784         /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
01785         if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
01786           /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
01787           if (bits == bits_copy) {
01788             int z_old;
01789             Slope tileh_old = GetTileSlope(tile, &z_old);
01790 
01791             /* Get the slope on top of the foundation */
01792             z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
01793             z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
01794 
01795             /* The surface slope must not be changed */
01796             if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01797           }
01798         }
01799         break;
01800       }
01801 
01802       default: NOT_REACHED();
01803     }
01804   }
01805 
01806   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01807 }
01808 
01810 extern const TileTypeProcs _tile_type_road_procs = {
01811   DrawTile_Road,           // draw_tile_proc
01812   GetSlopePixelZ_Road,     // get_slope_z_proc
01813   ClearTile_Road,          // clear_tile_proc
01814   NULL,                    // add_accepted_cargo_proc
01815   GetTileDesc_Road,        // get_tile_desc_proc
01816   GetTileTrackStatus_Road, // get_tile_track_status_proc
01817   ClickTile_Road,          // click_tile_proc
01818   NULL,                    // animate_tile_proc
01819   TileLoop_Road,           // tile_loop_proc
01820   ChangeTileOwner_Road,    // change_tile_owner_proc
01821   NULL,                    // add_produced_cargo_proc
01822   VehicleEnter_Road,       // vehicle_enter_tile_proc
01823   GetFoundation_Road,      // get_foundation_proc
01824   TerraformTile_Road,      // terraform_tile_proc
01825 };