tunnelbridge_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: tunnelbridge_cmd.cpp 18477 2009-12-13 00:24:53Z rubidium $ */
00002 
00008 #include "stdafx.h"
00009 #include "openttd.h"
00010 #include "rail_map.h"
00011 #include "landscape.h"
00012 #include "unmovable_map.h"
00013 #include "viewport_func.h"
00014 #include "command_func.h"
00015 #include "town.h"
00016 #include "variables.h"
00017 #include "train.h"
00018 #include "water_map.h"
00019 #include "yapf/yapf.h"
00020 #include "newgrf_sound.h"
00021 #include "autoslope.h"
00022 #include "tunnelbridge_map.h"
00023 #include "strings_func.h"
00024 #include "date_func.h"
00025 #include "functions.h"
00026 #include "vehicle_func.h"
00027 #include "sound_func.h"
00028 #include "tunnelbridge.h"
00029 #include "engine_base.h"
00030 #include "cheat_type.h"
00031 #include "elrail_func.h"
00032 #include "landscape_type.h"
00033 
00034 #include "table/sprites.h"
00035 #include "table/strings.h"
00036 #include "table/bridge_land.h"
00037 
00038 BridgeSpec _bridge[MAX_BRIDGES];
00039 TileIndex _build_tunnel_endtile;
00040 
00042 void ResetBridges()
00043 {
00044   /* First, free sprite table data */
00045   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
00046     if (_bridge[i].sprite_table != NULL) {
00047       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
00048       free(_bridge[i].sprite_table);
00049     }
00050   }
00051 
00052   /* Then, wipe out current bidges */
00053   memset(&_bridge, 0, sizeof(_bridge));
00054   /* And finally, reinstall default data */
00055   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
00056 }
00057 
00061 int CalcBridgeLenCostFactor(int x)
00062 {
00063   int n;
00064   int r;
00065 
00066   if (x < 2) return x;
00067   x -= 2;
00068   for (n = 0, r = 2;; n++) {
00069     if (x <= n) return r + x * n;
00070     r += n * n;
00071     x -= n;
00072   }
00073 }
00074 
00075 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
00076 {
00077   if ((tileh == SLOPE_FLAT) ||
00078       (((tileh == SLOPE_NE) || (tileh == SLOPE_SW)) && (axis == AXIS_X)) ||
00079       (((tileh == SLOPE_NW) || (tileh == SLOPE_SE)) && (axis == AXIS_Y))) return FOUNDATION_NONE;
00080 
00081   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
00082 }
00083 
00091 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
00092 {
00093   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
00094   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
00095   return (tileh != SLOPE_FLAT);
00096 }
00097 
00098 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
00099 {
00100   const BridgeSpec *bridge = GetBridgeSpec(index);
00101   assert(table < BRIDGE_PIECE_INVALID);
00102   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
00103     return _bridge_sprite_table[index][table];
00104   } else {
00105     return bridge->sprite_table[table];
00106   }
00107 }
00108 
00109 
00118 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
00119 {
00120   Foundation f = GetBridgeFoundation(*tileh, axis);
00121   *z += ApplyFoundationToSlope(f, tileh);
00122 
00123   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
00124   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00125 
00126   if (f == FOUNDATION_NONE) return CommandCost();
00127 
00128   return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
00129 }
00130 
00139 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
00140 {
00141   Foundation f = GetBridgeFoundation(*tileh, axis);
00142   *z += ApplyFoundationToSlope(f, tileh);
00143 
00144   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
00145   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00146 
00147   if (f == FOUNDATION_NONE) return CommandCost();
00148 
00149   return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
00150 }
00151 
00152 bool CheckBridge_Stuff(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
00153 {
00154   if (flags & DC_QUERY_COST) {
00155     return bridge_len <= (_settings_game.construction.longbridges ? 100U : 16U);
00156   }
00157 
00158   if (bridge_type >= MAX_BRIDGES) return false;
00159 
00160   const BridgeSpec *b = GetBridgeSpec(bridge_type);
00161   if (b->avail_year > _cur_year) return false;
00162 
00163   uint max = b->max_length;
00164   if (max >= 16 && _settings_game.construction.longbridges) max = 100;
00165 
00166   return b->min_length <= bridge_len && bridge_len <= max;
00167 }
00168 
00178 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00179 {
00180   BridgeType bridge_type;
00181   RailType railtype = INVALID_RAILTYPE;
00182   RoadTypes roadtypes = ROADTYPES_NONE;
00183   uint x;
00184   uint y;
00185   uint sx;
00186   uint sy;
00187   TileIndex tile_start;
00188   TileIndex tile_end;
00189   Slope tileh_start;
00190   Slope tileh_end;
00191   uint z_start;
00192   uint z_end;
00193   TileIndex tile;
00194   TileIndexDiff delta;
00195   uint bridge_len;
00196   Axis direction;
00197   CommandCost cost(EXPENSES_CONSTRUCTION);
00198   CommandCost ret;
00199   bool replace_bridge = false;
00200   BridgeType replaced_bridge_type;
00201   TransportType transport_type;
00202 
00203   /* unpack parameters */
00204   bridge_type = GB(p2, 0, 8);
00205 
00206   if (p1 >= MapSize()) return CMD_ERROR;
00207 
00208   transport_type = (TransportType)GB(p2, 15, 2);
00209 
00210   /* type of bridge */
00211   switch (transport_type) {
00212     case TRANSPORT_ROAD:
00213       roadtypes = (RoadTypes)GB(p2, 8, 2);
00214       if (!AreValidRoadTypes(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
00215       break;
00216 
00217     case TRANSPORT_RAIL:
00218       railtype = (RailType)GB(p2, 8, 7);
00219       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00220       break;
00221 
00222     case TRANSPORT_WATER:
00223       break;
00224 
00225     default:
00226       /* Airports don't have tunnels. */
00227       return CMD_ERROR;
00228   }
00229 
00230   x = TileX(end_tile);
00231   y = TileY(end_tile);
00232   sx = TileX(p1);
00233   sy = TileY(p1);
00234 
00235   /* check if valid, and make sure that (x,y) are smaller than (sx,sy) */
00236   if (x == sx) {
00237     if (y == sy) return_cmd_error(STR_5008_CANNOT_START_AND_END_ON);
00238     direction = AXIS_Y;
00239     if (y > sy) Swap(y, sy);
00240   } else if (y == sy) {
00241     direction = AXIS_X;
00242     if (x > sx) Swap(x, sx);
00243   } else {
00244     return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN);
00245   }
00246 
00247   bridge_len = sx + sy - x - y - 1;
00248   if (transport_type != TRANSPORT_WATER) {
00249     /* set and test bridge length, availability */
00250     if (!CheckBridge_Stuff(bridge_type, bridge_len, flags)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
00251   } else {
00252     if (bridge_len > (_settings_game.construction.longbridges ? 100U : 16U)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
00253   }
00254 
00255   /* retrieve landscape height and ensure it's on land */
00256   tile_start = TileXY(x, y);
00257   tile_end = TileXY(sx, sy);
00258   if (IsWaterTile(tile_start) || IsWaterTile(tile_end)) {
00259     return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
00260   }
00261 
00262   tileh_start = GetTileSlope(tile_start, &z_start);
00263   tileh_end = GetTileSlope(tile_end, &z_end);
00264 
00265   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
00266   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
00267 
00268   if (z_start != z_end) return_cmd_error(STR_BRIDGEHEADS_NOT_SAME_HEIGHT);
00269 
00270   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
00271       GetOtherBridgeEnd(tile_start) == tile_end &&
00272       GetTunnelBridgeTransportType(tile_start) == transport_type) {
00273     /* Replace a current bridge. */
00274 
00275     /* If this is a railway bridge, make sure the railtypes match. */
00276     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
00277       return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
00278     }
00279 
00280     /* Do not replace town bridges with lower speed bridges. */
00281     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
00282         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
00283       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
00284 
00285       if (t == NULL) {
00286         return CMD_ERROR;
00287       } else {
00288         SetDParam(0, t->index);
00289         return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00290       }
00291     }
00292 
00293     /* Do not replace the bridge with the same bridge type. */
00294     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
00295       return_cmd_error(STR_1007_ALREADY_BUILT);
00296     }
00297 
00298     /* Do not allow replacing another company's bridges. */
00299     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
00300       return_cmd_error(STR_1024_AREA_IS_OWNED_BY_ANOTHER);
00301     }
00302 
00303     cost.AddCost((bridge_len + 1) * _price.clear_bridge); // The cost of clearing the current bridge.
00304     replace_bridge = true;
00305     replaced_bridge_type = GetBridgeType(tile_start);
00306 
00307     /* Do not remove road types when upgrading a bridge */
00308     roadtypes |= GetRoadTypes(tile_start);
00309   } else {
00310     /* Build a new bridge. */
00311 
00312     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
00313 
00314     /* Try and clear the start landscape */
00315     ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00316     if (CmdFailed(ret)) return ret;
00317     cost = ret;
00318 
00319     if (CmdFailed(terraform_cost_north) || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes))
00320       return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
00321     cost.AddCost(terraform_cost_north);
00322 
00323     /* Try and clear the end landscape */
00324     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00325     if (CmdFailed(ret)) return ret;
00326     cost.AddCost(ret);
00327 
00328     /* false - end tile slope check */
00329     if (CmdFailed(terraform_cost_south) || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes))
00330       return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
00331     cost.AddCost(terraform_cost_south);
00332 
00333     if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_1000_LAND_SLOPED_IN_WRONG_DIRECTION);
00334   }
00335 
00336   if (!replace_bridge) {
00337     TileIndex Heads[] = {tile_start, tile_end};
00338     int i;
00339 
00340     for (i = 0; i < 2; i++) {
00341       if (MayHaveBridgeAbove(Heads[i])) {
00342         if (IsBridgeAbove(Heads[i])) {
00343           TileIndex north_head = GetNorthernBridgeEnd(Heads[i]);
00344 
00345           if (direction == GetBridgeAxis(Heads[i])) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
00346 
00347           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
00348             return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
00349           }
00350         }
00351       }
00352     }
00353   }
00354 
00355   /* do the drill? */
00356   if (flags & DC_EXEC) {
00357     DiagDirection dir = AxisToDiagDir(direction);
00358     Owner owner = replace_bridge ? GetTileOwner(tile_start) : _current_company;
00359 
00360     switch (transport_type) {
00361       case TRANSPORT_RAIL:
00362         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
00363         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
00364         break;
00365 
00366       case TRANSPORT_ROAD:
00367         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
00368         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
00369         break;
00370 
00371       case TRANSPORT_WATER:
00372         MakeAqueductBridgeRamp(tile_start, owner, dir);
00373         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
00374         break;
00375 
00376       default:
00377         NOT_REACHED();
00378         break;
00379     }
00380     MarkTileDirtyByTile(tile_start);
00381     MarkTileDirtyByTile(tile_end);
00382   }
00383 
00384   delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00385   for (tile = tile_start + delta; tile != tile_end; tile += delta) {
00386     if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_BRIDGE_TOO_LOW_FOR_TERRAIN);
00387 
00388     if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) && !replace_bridge) {
00389       /* Disallow crossing bridges for the time being */
00390       return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
00391     }
00392 
00393     switch (GetTileType(tile)) {
00394       case MP_WATER:
00395         if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
00396         break;
00397 
00398       case MP_RAILWAY:
00399         if (!IsPlainRail(tile)) goto not_valid_below;
00400         break;
00401 
00402       case MP_ROAD:
00403         if (IsRoadDepot(tile)) goto not_valid_below;
00404         break;
00405 
00406       case MP_TUNNELBRIDGE:
00407         if (IsTunnel(tile)) break;
00408         if (replace_bridge) break;
00409         if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
00410         if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
00411         break;
00412 
00413       case MP_UNMOVABLE:
00414         if (!IsOwnedLand(tile)) goto not_valid_below;
00415         break;
00416 
00417       case MP_CLEAR:
00418         break;
00419 
00420       default:
00421 not_valid_below:;
00422         /* try and clear the middle landscape */
00423         ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00424         if (CmdFailed(ret)) return ret;
00425         cost.AddCost(ret);
00426         break;
00427     }
00428 
00429     if (flags & DC_EXEC) {
00430       SetBridgeMiddle(tile, direction);
00431       MarkTileDirtyByTile(tile);
00432     }
00433   }
00434 
00435   if (flags & DC_EXEC && transport_type == TRANSPORT_RAIL) {
00436     Track track = AxisToTrack(direction);
00437     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
00438     YapfNotifyTrackLayoutChange(tile_start, track);
00439   }
00440 
00441   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
00442    * It's unnecessary to execute this command every time for every bridge. So it is done only
00443    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
00444    */
00445   if (!(flags & DC_QUERY_COST) || (IsValidCompanyID(_current_company) && GetCompany(_current_company)->is_ai)) {
00446     bridge_len += 2; // begin and end tiles/ramps
00447 
00448     if (IsValidCompanyID(_current_company))
00449       bridge_len = CalcBridgeLenCostFactor(bridge_len);
00450 
00451     cost.AddCost((int64)bridge_len * _price.build_bridge * GetBridgeSpec(bridge_type)->price >> 8);
00452 
00453     /* Aqueducts are a little more expensive. */
00454     if (transport_type == TRANSPORT_WATER) cost.AddCost((int64)bridge_len * _price.clear_water);
00455   }
00456 
00457   return cost;
00458 }
00459 
00460 
00467 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00468 {
00469   TileIndexDiff delta;
00470   TileIndex end_tile;
00471   DiagDirection direction;
00472   Slope start_tileh;
00473   Slope end_tileh;
00474   TransportType transport_type = (TransportType)GB(p1, 9, 1);
00475   uint start_z;
00476   uint end_z;
00477   CommandCost cost(EXPENSES_CONSTRUCTION);
00478   CommandCost ret;
00479 
00480   _build_tunnel_endtile = 0;
00481   if (transport_type == TRANSPORT_RAIL) {
00482     if (!ValParamRailtype((RailType)p1)) return CMD_ERROR;
00483   } else {
00484     const RoadTypes rts = (RoadTypes)GB(p1, 0, 2);
00485     if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
00486   }
00487 
00488   start_tileh = GetTileSlope(start_tile, &start_z);
00489   direction = GetInclinedSlopeDirection(start_tileh);
00490   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_500B_SITE_UNSUITABLE_FOR_TUNNEL);
00491 
00492   if (IsWaterTile(start_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
00493 
00494   ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00495   if (CmdFailed(ret)) return ret;
00496 
00497   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
00498    * for the clearing of the entrance of the tunnel. Assigning it to
00499    * cost before the loop will yield different costs depending on start-
00500    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
00501 
00502   delta = TileOffsByDiagDir(direction);
00503   DiagDirection tunnel_in_way_dir;
00504   if (DiagDirToAxis(direction) == AXIS_Y) {
00505     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
00506   } else {
00507     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
00508   }
00509 
00510   end_tile = start_tile;
00511 
00513   int tiles_coef = 3;
00515   int tiles = 0;
00517   int tiles_bump = 25;
00518 
00519   for (;;) {
00520     end_tile += delta;
00521     if (!IsValidTile(end_tile)) return_cmd_error(STR_TUNNEL_THROUGH_MAP_BORDER);
00522     end_tileh = GetTileSlope(end_tile, &end_z);
00523 
00524     if (start_z == end_z) break;
00525 
00526     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
00527       return_cmd_error(STR_5003_ANOTHER_TUNNEL_IN_THE_WAY);
00528     }
00529 
00530     tiles++;
00531     if (tiles == tiles_bump) {
00532       tiles_coef++;
00533       tiles_bump *= 2;
00534     }
00535 
00536     cost.AddCost(_price.build_tunnel);
00537     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
00538   }
00539 
00540   /* Add the cost of the entrance */
00541   cost.AddCost(_price.build_tunnel);
00542   cost.AddCost(ret);
00543 
00544   /* if the command fails from here on we want the end tile to be highlighted */
00545   _build_tunnel_endtile = end_tile;
00546 
00547   if (IsWaterTile(end_tile)) return_cmd_error(STR_3807_CAN_T_BUILD_ON_WATER);
00548 
00549   /* slope of end tile must be complementary to the slope of the start tile */
00550   if (end_tileh != ComplementSlope(start_tileh)) {
00551     /* Check if there is a structure on the terraformed tile. Do not add the cost, that will be done by the terraforming
00552      * Note: Currently the town rating is also affected by this clearing-test. So effectivly the player is punished twice for clearing
00553      *       the tree on end_tile.
00554      */
00555     ret = DoCommand(end_tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR);
00556     if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
00557 
00558     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
00559     if (CmdFailed(ret)) return_cmd_error(STR_5005_UNABLE_TO_EXCAVATE_LAND);
00560   } else {
00561     ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00562     if (CmdFailed(ret)) return ret;
00563   }
00564   cost.AddCost(_price.build_tunnel);
00565   cost.AddCost(ret);
00566 
00567   if (flags & DC_EXEC) {
00568     if (transport_type == TRANSPORT_RAIL) {
00569       MakeRailTunnel(start_tile, _current_company, direction,                 (RailType)GB(p1, 0, 4));
00570       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4));
00571       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
00572       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
00573     } else {
00574       MakeRoadTunnel(start_tile, _current_company, direction,                 (RoadTypes)GB(p1, 0, 2));
00575       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), (RoadTypes)GB(p1, 0, 2));
00576     }
00577   }
00578 
00579   return cost;
00580 }
00581 
00582 
00583 static inline bool CheckAllowRemoveTunnelBridge(TileIndex tile)
00584 {
00585   /* Floods can remove anything as well as the scenario editor */
00586   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return true;
00587 
00588   switch (GetTunnelBridgeTransportType(tile)) {
00589     case TRANSPORT_ROAD: {
00590       RoadTypes rts = GetRoadTypes(tile);
00591       Owner road_owner = _current_company;
00592       Owner tram_owner = _current_company;
00593 
00594       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00595       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
00596 
00597       /* We can remove unowned road and if the town allows it */
00598       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) return CheckTileOwnership(tile);
00599       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
00600       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
00601 
00602       return CheckOwnership(road_owner) && CheckOwnership(tram_owner);
00603     }
00604 
00605     case TRANSPORT_RAIL:
00606     case TRANSPORT_WATER:
00607       return CheckOwnership(GetTileOwner(tile));
00608 
00609     default: NOT_REACHED();
00610   }
00611 }
00612 
00613 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
00614 {
00615   Town *t = NULL;
00616   TileIndex endtile;
00617 
00618   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
00619 
00620   endtile = GetOtherTunnelEnd(tile);
00621 
00622   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
00623 
00624   _build_tunnel_endtile = endtile;
00625 
00626   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00627     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00628 
00629     /* Check if you are allowed to remove the tunnel owned by a town
00630      * Removal depends on difficulty settings */
00631     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
00632       SetDParam(0, t->index);
00633       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00634     }
00635   }
00636 
00637   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00638    * you have a "Poor" (0) town rating */
00639   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00640     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00641   }
00642 
00643   if (flags & DC_EXEC) {
00644     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
00645       /* We first need to request values before calling DoClearSquare */
00646       DiagDirection dir = GetTunnelBridgeDirection(tile);
00647       Track track = DiagDirToDiagTrack(dir);
00648       Owner owner = GetTileOwner(tile);
00649 
00650       Vehicle *v = NULL;
00651       if (GetTunnelBridgeReservation(tile)) {
00652         v = GetTrainForReservation(tile, track);
00653         if (v != NULL) FreeTrainTrackReservation(v);
00654       }
00655 
00656       DoClearSquare(tile);
00657       DoClearSquare(endtile);
00658 
00659       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
00660       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
00661       AddSideToSignalBuffer(endtile, dir,                 owner);
00662 
00663       YapfNotifyTrackLayoutChange(tile,    track);
00664       YapfNotifyTrackLayoutChange(endtile, track);
00665 
00666       if (v != NULL) TryPathReserve(v);
00667     } else {
00668       DoClearSquare(tile);
00669       DoClearSquare(endtile);
00670     }
00671   }
00672   return CommandCost(EXPENSES_CONSTRUCTION, _price.clear_tunnel * (GetTunnelBridgeLength(tile, endtile) + 2));
00673 }
00674 
00675 
00676 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
00677 {
00678   DiagDirection direction;
00679   TileIndexDiff delta;
00680   TileIndex endtile;
00681   Town *t = NULL;
00682 
00683   if (!CheckAllowRemoveTunnelBridge(tile)) return CMD_ERROR;
00684 
00685   endtile = GetOtherBridgeEnd(tile);
00686 
00687   if (HasVehicleOnTunnelBridge(tile, endtile)) return CMD_ERROR;
00688 
00689   direction = GetTunnelBridgeDirection(tile);
00690   delta = TileOffsByDiagDir(direction);
00691 
00692   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00693     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00694 
00695     /* Check if you are allowed to remove the bridge owned by a town
00696      * Removal depends on difficulty settings */
00697     if (!CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE)) {
00698       SetDParam(0, t->index);
00699       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00700     }
00701   }
00702 
00703   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00704    * you have a "Poor" (0) town rating */
00705   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00706     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00707   }
00708 
00709   if (flags & DC_EXEC) {
00710     /* read this value before actual removal of bridge */
00711     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
00712     Owner owner = GetTileOwner(tile);
00713     uint height = GetBridgeHeight(tile);
00714     Vehicle *v = NULL;
00715 
00716     if (rail && GetTunnelBridgeReservation(tile)) {
00717       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
00718       if (v != NULL) FreeTrainTrackReservation(v);
00719     }
00720 
00721     DoClearSquare(tile);
00722     DoClearSquare(endtile);
00723     for (TileIndex c = tile + delta; c != endtile; c += delta) {
00724       /* do not let trees appear from 'nowhere' after removing bridge */
00725       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
00726         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
00727         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
00728       }
00729       ClearBridgeMiddle(c);
00730       MarkTileDirtyByTile(c);
00731     }
00732 
00733     if (rail) {
00734       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
00735       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
00736       AddSideToSignalBuffer(endtile, direction,                 owner);
00737 
00738       Track track = DiagDirToDiagTrack(direction);
00739       YapfNotifyTrackLayoutChange(tile,    track);
00740       YapfNotifyTrackLayoutChange(endtile, track);
00741 
00742       if (v != NULL) TryPathReserve(v, true);
00743     }
00744   }
00745 
00746   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * _price.clear_bridge);
00747 }
00748 
00749 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
00750 {
00751   if (IsTunnel(tile)) {
00752     if (flags & DC_AUTO) return_cmd_error(STR_5006_MUST_DEMOLISH_TUNNEL_FIRST);
00753     return DoClearTunnel(tile, flags);
00754   } else { // IsBridge(tile)
00755     if (flags & DC_AUTO) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
00756     return DoClearBridge(tile, flags);
00757   }
00758 
00759   return CMD_ERROR;
00760 }
00761 
00773 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
00774 {
00775   /* Do not draw bridge pillars if they are invisible */
00776   if (IsInvisibilitySet(TO_BRIDGES)) return;
00777 
00778   SpriteID image = psid->sprite;
00779 
00780   if (image != 0) {
00781     /* "side" specifies the side the pillars stand on.
00782      * The length of the pillars is then set to the height of the bridge over the corners of this edge.
00783      *
00784      *                axis==AXIS_X  axis==AXIS_Y
00785      *   side==false      SW            NW
00786      *   side==true       NE            SE
00787      *
00788      * I have no clue, why this was done this way.
00789      */
00790     bool side = HasBit(image, 0);
00791 
00792     /* "dir" means the edge the pillars stand on */
00793     DiagDirection dir = AxisToDiagDir(axis);
00794     if (side != (axis == AXIS_Y)) dir = ReverseDiagDir(dir);
00795 
00796     /* Determine ground height under pillars */
00797     int front_height = ti->z;
00798     int back_height = ti->z;
00799     GetSlopeZOnEdge(ti->tileh, dir, &front_height, &back_height);
00800 
00801     /* x and y size of bounding-box of pillars */
00802     int w = (axis == AXIS_X ? 16 : 2);
00803     int h = (axis == AXIS_X ? 2 : 16);
00804     /* sprite position of back facing pillar */
00805     int x_back = x - (axis == AXIS_X ? 0 : 9);
00806     int y_back = y - (axis == AXIS_X ? 9 : 0);
00807 
00808     for (int cur_z = z_bridge; cur_z >= front_height || cur_z >= back_height; cur_z -= TILE_HEIGHT) {
00809       /* Draw front facing pillar */
00810       if (cur_z >= front_height) {
00811         AddSortableSpriteToDraw(image, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
00812       }
00813 
00814       /* Draw back facing pillar, but not the highest part directly under the bridge-floor */
00815       if (drawfarpillar && cur_z >= back_height && cur_z < z_bridge - TILE_HEIGHT) {
00816         AddSortableSpriteToDraw(image, psid->pal, x_back, y_back, w, h, BB_HEIGHT_UNDER_BRIDGE - 5, cur_z, IsTransparencySet(TO_BRIDGES), 0, 0, -5);
00817       }
00818     }
00819   }
00820 }
00821 
00831 static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
00832 {
00833   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
00834   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
00835   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
00836 
00837   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
00838   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
00839   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
00840   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
00841 
00842   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
00843    * The bounding boxes here are the same as for bridge front/roof */
00844   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
00845     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
00846       x, y, size_x[offset], size_y[offset], 0x28, z,
00847       !head && IsTransparencySet(TO_BRIDGES));
00848   }
00849 
00850   /* Do not draw catenary if it is set invisible */
00851   if (!IsInvisibilitySet(TO_CATENARY)) {
00852     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
00853       x, y, size_x[offset], size_y[offset], 0x28, z,
00854       IsTransparencySet(TO_CATENARY));
00855   }
00856 
00857   /* Start a new SpriteCombine for the front part */
00858   EndSpriteCombine();
00859   StartSpriteCombine();
00860 
00861   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
00862   if (!IsInvisibilitySet(TO_CATENARY)) {
00863     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
00864       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
00865       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
00866   }
00867 }
00868 
00882 static void DrawTile_TunnelBridge(TileInfo *ti)
00883 {
00884   SpriteID image;
00885   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
00886   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
00887 
00888   if (IsTunnel(ti->tile)) {
00889     /* Front view of tunnel bounding boxes:
00890      *
00891      *   122223  <- BB_Z_SEPARATOR
00892      *   1    3
00893      *   1    3                1,3 = empty helper BB
00894      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
00895      *
00896      */
00897 
00898     static const int _tunnel_BB[4][12] = {
00899       /*  tunnnel-roof  |  Z-separator  | tram-catenary
00900        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
00901       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
00902       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
00903       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
00904       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
00905     };
00906     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
00907 
00908     bool catenary = false;
00909 
00910     if (transport_type == TRANSPORT_RAIL) {
00911       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
00912     } else {
00913       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
00914     }
00915 
00916     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
00917 
00918     image += tunnelbridge_direction * 2;
00919     DrawGroundSprite(image, PAL_NONE);
00920 
00921     /* PBS debugging, draw reserved tracks darker */
00922     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile))) {
00923       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
00924       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH);
00925     }
00926 
00927     if (transport_type == TRANSPORT_ROAD) {
00928       RoadTypes rts = GetRoadTypes(ti->tile);
00929 
00930       if (HasBit(rts, ROADTYPE_TRAM)) {
00931         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
00932 
00933         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
00934 
00935         /* Do not draw wires if they are invisible */
00936         if (!IsInvisibilitySet(TO_CATENARY)) {
00937           catenary = true;
00938           StartSpriteCombine();
00939           AddSortableSpriteToDraw(SPR_TRAMWAY_TUNNEL_WIRES + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, BB_data[10], BB_data[11], TILE_HEIGHT, ti->z, IsTransparencySet(TO_CATENARY), BB_data[8], BB_data[9], BB_Z_SEPARATOR);
00940         }
00941       }
00942     } else if (HasCatenaryDrawn(GetRailType(ti->tile))) {
00943       /* Maybe draw pylons on the entry side */
00944       DrawCatenary(ti);
00945 
00946       catenary = true;
00947       StartSpriteCombine();
00948       /* Draw wire above the ramp */
00949       DrawCatenaryOnTunnel(ti);
00950     }
00951 
00952     AddSortableSpriteToDraw(image + 1, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
00953 
00954     if (catenary) EndSpriteCombine();
00955 
00956     /* Add helper BB for sprite sorting, that separate the tunnel from things beside of it */
00957     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x             , ti->y             , BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
00958     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x + BB_data[4], ti->y + BB_data[5], BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
00959 
00960     DrawBridgeMiddle(ti);
00961   } else { // IsBridge(ti->tile)
00962     const PalSpriteID *psid;
00963     int base_offset;
00964     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
00965 
00966     if (transport_type == TRANSPORT_RAIL) {
00967       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
00968       assert(base_offset != 8); // This one is used for roads
00969     } else {
00970       base_offset = 8;
00971     }
00972 
00973     /* as the lower 3 bits are used for other stuff, make sure they are clear */
00974     assert( (base_offset & 0x07) == 0x00);
00975 
00976     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
00977 
00978     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
00979     base_offset += (6 - tunnelbridge_direction) % 4;
00980 
00981     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
00982 
00983     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
00984     if (transport_type != TRANSPORT_WATER) {
00985       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
00986     } else {
00987       psid = _aqueduct_sprites + base_offset;
00988     }
00989 
00990     if (!ice) {
00991       DrawClearLandTile(ti, 3);
00992     } else {
00993       DrawGroundSprite(SPR_FLAT_SNOWY_TILE + _tileh_to_sprite[ti->tileh], PAL_NONE);
00994     }
00995 
00996     /* draw ramp */
00997 
00998     /* Draw Trambits and PBS Reservation as SpriteCombine */
00999     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01000 
01001     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
01002      * it doesn't disappear behind it
01003      */
01004     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
01005     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
01006 
01007     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && transport_type == TRANSPORT_RAIL && GetTunnelBridgeReservation(ti->tile)) {
01008       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01009       if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01010         AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_y : rti->base_sprites.single_x, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01011       } else {
01012         AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
01013       }
01014     }
01015 
01016     if (transport_type == TRANSPORT_ROAD) {
01017       RoadTypes rts = GetRoadTypes(ti->tile);
01018 
01019       if (HasBit(rts, ROADTYPE_TRAM)) {
01020         uint offset = tunnelbridge_direction;
01021         uint z = ti->z;
01022         if (ti->tileh != SLOPE_FLAT) {
01023           offset = (offset + 1) & 1;
01024           z += TILE_HEIGHT;
01025         } else {
01026           offset += 2;
01027         }
01028         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01029         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
01030       }
01031       EndSpriteCombine();
01032     } else if (transport_type == TRANSPORT_RAIL) {
01033       EndSpriteCombine();
01034       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01035         DrawCatenary(ti);
01036       }
01037     }
01038 
01039     DrawBridgeMiddle(ti);
01040   }
01041 }
01042 
01043 
01061 static BridgePieces CalcBridgePiece(uint north, uint south)
01062 {
01063   if (north == 1) {
01064     return BRIDGE_PIECE_NORTH;
01065   } else if (south == 1) {
01066     return BRIDGE_PIECE_SOUTH;
01067   } else if (north < south) {
01068     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01069   } else if (north > south) {
01070     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01071   } else {
01072     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01073   }
01074 }
01075 
01076 
01077 void DrawBridgeMiddle(const TileInfo *ti)
01078 {
01079   /* Sectional view of bridge bounding boxes:
01080    *
01081    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01082    *  1           2                                  3 = empty helper BB
01083    *  1     7     2                                4,5 = pillars under higher bridges
01084    *  1 6 88888 6 2                                  6 = elrail-pylons
01085    *  1 6 88888 6 2                                  7 = elrail-wire
01086    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01087    *  3333333333333  <- BB_Z_SEPARATOR
01088    *                 <- unused
01089    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01090    *    4       5
01091    *    4       5
01092    *
01093    */
01094 
01095   /* Z position of the bridge sprites relative to bridge height (downwards) */
01096   static const int BRIDGE_Z_START = 3;
01097 
01098   if (!IsBridgeAbove(ti->tile)) return;
01099 
01100   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01101   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01102   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01103 
01104   Axis axis = GetBridgeAxis(ti->tile);
01105   BridgePieces piece = CalcBridgePiece(
01106     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01107     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01108   );
01109 
01110   const PalSpriteID *psid;
01111   bool drawfarpillar;
01112   if (transport_type != TRANSPORT_WATER) {
01113     BridgeType type =  GetBridgeType(rampsouth);
01114     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01115 
01116     uint base_offset;
01117     if (transport_type == TRANSPORT_RAIL) {
01118       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01119     } else {
01120       base_offset = 8;
01121     }
01122 
01123     psid = base_offset + GetBridgeSpriteTable(type, piece);
01124   } else {
01125     drawfarpillar = true;
01126     psid = _aqueduct_sprites;
01127   }
01128 
01129   if (axis != AXIS_X) psid += 4;
01130 
01131   int x = ti->x;
01132   int y = ti->y;
01133   uint bridge_z = GetBridgeHeight(rampsouth);
01134   uint z = bridge_z - BRIDGE_Z_START;
01135 
01136   /* Add a bounding box, that separates the bridge from things below it. */
01137   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01138 
01139   /* Draw Trambits as SpriteCombine */
01140   if (transport_type == TRANSPORT_ROAD) StartSpriteCombine();
01141 
01142   /* Draw floor and far part of bridge*/
01143   if (!IsInvisibilitySet(TO_BRIDGES)) {
01144     if (axis == AXIS_X) {
01145       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01146     } else {
01147       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01148     }
01149   }
01150 
01151   psid++;
01152 
01153   if (transport_type == TRANSPORT_ROAD) {
01154     RoadTypes rts = GetRoadTypes(rampsouth);
01155 
01156     if (HasBit(rts, ROADTYPE_TRAM)) {
01157       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01158       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01159     } else {
01160       EndSpriteCombine();
01161       StartSpriteCombine();
01162     }
01163   } else if (transport_type == TRANSPORT_RAIL) {
01164     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01165       DrawCatenaryOnBridge(ti);
01166     }
01167   }
01168 
01169   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01170   if (!IsInvisibilitySet(TO_BRIDGES)) {
01171     if (axis == AXIS_X) {
01172       y += 12;
01173       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01174     } else {
01175       x += 12;
01176       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01177     }
01178   }
01179 
01180   /* Draw TramFront as SpriteCombine */
01181   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01182 
01183   /* Do not draw anything more if bridges are invisible */
01184   if (IsInvisibilitySet(TO_BRIDGES)) return;
01185 
01186   psid++;
01187   if (ti->z + 5 == z) {
01188     /* draw poles below for small bridges */
01189     if (psid->sprite != 0) {
01190       SpriteID image = psid->sprite;
01191       SpriteID pal   = psid->pal;
01192       if (IsTransparencySet(TO_BRIDGES)) {
01193         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01194         pal = PALETTE_TO_TRANSPARENT;
01195       }
01196 
01197       DrawGroundSpriteAt(image, pal, x, y, z);
01198     }
01199   } else if (_settings_client.gui.bridge_pillars) {
01200     /* draw pillars below for high bridges */
01201     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01202   }
01203 }
01204 
01205 
01206 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
01207 {
01208   uint z;
01209   Slope tileh = GetTileSlope(tile, &z);
01210 
01211   x &= 0xF;
01212   y &= 0xF;
01213 
01214   if (IsTunnel(tile)) {
01215     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01216 
01217     /* In the tunnel entrance? */
01218     if (5 <= pos && pos <= 10) return z;
01219   } else { // IsBridge(tile)
01220     DiagDirection dir = GetTunnelBridgeDirection(tile);
01221     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01222 
01223     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01224 
01225     /* On the bridge ramp? */
01226     if (5 <= pos && pos <= 10) {
01227       uint delta;
01228 
01229       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01230 
01231       switch (dir) {
01232         default: NOT_REACHED();
01233         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01234         case DIAGDIR_SE: delta = y / 2; break;
01235         case DIAGDIR_SW: delta = x / 2; break;
01236         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01237       }
01238       return z + 1 + delta;
01239     }
01240   }
01241 
01242   return z + GetPartialZ(x, y, tileh);
01243 }
01244 
01245 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01246 {
01247   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01248 }
01249 
01250 
01251 static void GetAcceptedCargo_TunnelBridge(TileIndex tile, AcceptedCargo ac)
01252 {
01253   /* not used */
01254 }
01255 
01256 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01257 {
01258   TransportType tt = GetTunnelBridgeTransportType(tile);
01259 
01260   if (IsTunnel(tile)) {
01261     td->str = (tt == TRANSPORT_RAIL) ? STR_5017_RAILROAD_TUNNEL : STR_5018_ROAD_TUNNEL;
01262   } else { // IsBridge(tile)
01263     td->str = (tt == TRANSPORT_WATER) ? STR_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01264   }
01265   td->owner[0] = GetTileOwner(tile);
01266 
01267   Owner road_owner = INVALID_OWNER;
01268   Owner tram_owner = INVALID_OWNER;
01269   RoadTypes rts = GetRoadTypes(tile);
01270   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01271   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01272 
01273   /* Is there a mix of owners? */
01274   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01275       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01276     uint i = 1;
01277     if (road_owner != INVALID_OWNER) {
01278       td->owner_type[i] = STR_ROAD_OWNER;
01279       td->owner[i] = road_owner;
01280       i++;
01281     }
01282     if (tram_owner != INVALID_OWNER) {
01283       td->owner_type[i] = STR_TRAM_OWNER;
01284       td->owner[i] = tram_owner;
01285     }
01286   }
01287 }
01288 
01289 
01290 static void TileLoop_TunnelBridge(TileIndex tile)
01291 {
01292   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01293   switch (_settings_game.game_creation.landscape) {
01294     case LT_ARCTIC:
01295       if (snow_or_desert != (GetTileZ(tile) > GetSnowLine())) {
01296         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01297         MarkTileDirtyByTile(tile);
01298       }
01299       break;
01300 
01301     case LT_TROPIC:
01302       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01303         SetTunnelBridgeSnowOrDesert(tile, true);
01304         MarkTileDirtyByTile(tile);
01305       }
01306       break;
01307 
01308     default:
01309       break;
01310   }
01311 }
01312 
01313 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01314 {
01315   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01316   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01317 
01318   DiagDirection dir = GetTunnelBridgeDirection(tile);
01319   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01320   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01321 }
01322 
01323 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01324 {
01325   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01326     /* Update all roadtypes, no matter if they are present */
01327     if (GetRoadOwner(tile, rt) == old_owner) {
01328       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01329     }
01330   }
01331 
01332   if (!IsTileOwner(tile, old_owner)) return;
01333 
01334   if (new_owner != INVALID_OWNER) {
01335     SetTileOwner(tile, new_owner);
01336   } else {
01337     if (CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR))) {
01338       /* When clearing the bridge/tunnel failed there are still vehicles on/in
01339        * the bridge/tunnel. As all *our* vehicles are already removed, they
01340        * must be of another owner. Therefore this can't be rail tunnel/bridge.
01341        * In that case we can safely reassign the ownership to OWNER_NONE. */
01342       assert(GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL);
01343       SetTileOwner(tile, OWNER_NONE);
01344     }
01345   }
01346 }
01347 
01348 
01349 static const byte _tunnel_fractcoord_1[4]    = {0x8E, 0x18, 0x81, 0xE8};
01350 static const byte _tunnel_fractcoord_2[4]    = {0x81, 0x98, 0x87, 0x38};
01351 static const byte _tunnel_fractcoord_3[4]    = {0x82, 0x88, 0x86, 0x48};
01352 static const byte _exit_tunnel_track[4]      = {1, 2, 1, 2};
01353 
01355 static const Trackdir _road_exit_tunnel_state[DIAGDIR_END] = {
01356   TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
01357 };
01358 static const byte _road_exit_tunnel_frame[4] = {2, 7, 9, 4};
01359 
01360 static const byte _tunnel_fractcoord_4[4]    = {0x52, 0x85, 0x98, 0x29};
01361 static const byte _tunnel_fractcoord_5[4]    = {0x92, 0x89, 0x58, 0x25};
01362 static const byte _tunnel_fractcoord_6[4]    = {0x92, 0x89, 0x56, 0x45};
01363 static const byte _tunnel_fractcoord_7[4]    = {0x52, 0x85, 0x96, 0x49};
01364 
01365 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01366 {
01367   int z = GetSlopeZ(x, y) - v->z_pos;
01368 
01369   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01370   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01371 
01372   if (IsTunnel(tile)) {
01373     byte fc;
01374     DiagDirection vdir;
01375 
01376     if (v->type == VEH_TRAIN) {
01377       fc = (x & 0xF) + (y << 4);
01378 
01379       vdir = DirToDiagDir(v->direction);
01380 
01381       if (v->u.rail.track != TRACK_BIT_WORMHOLE && dir == vdir) {
01382         if (IsFrontEngine(v) && fc == _tunnel_fractcoord_1[dir]) {
01383           if (!PlayVehicleSound(v, VSE_TUNNEL) && RailVehInfo(v->engine_type)->engclass == 0) {
01384             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01385           }
01386           return VETSB_CONTINUE;
01387         }
01388         if (fc == _tunnel_fractcoord_2[dir]) {
01389           v->tile = tile;
01390           v->u.rail.track = TRACK_BIT_WORMHOLE;
01391           v->vehstatus |= VS_HIDDEN;
01392           return VETSB_ENTERED_WORMHOLE;
01393         }
01394       }
01395 
01396       if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
01397         /* We're at the tunnel exit ?? */
01398         v->tile = tile;
01399         v->u.rail.track = (TrackBits)_exit_tunnel_track[dir];
01400         assert(v->u.rail.track);
01401         v->vehstatus &= ~VS_HIDDEN;
01402         return VETSB_ENTERED_WORMHOLE;
01403       }
01404     } else if (v->type == VEH_ROAD) {
01405       fc = (x & 0xF) + (y << 4);
01406       vdir = DirToDiagDir(v->direction);
01407 
01408       /* Enter tunnel? */
01409       if (v->u.road.state != RVSB_WORMHOLE && dir == vdir) {
01410         if (fc == _tunnel_fractcoord_4[dir] ||
01411             fc == _tunnel_fractcoord_5[dir]) {
01412           v->tile = tile;
01413           v->u.road.state = RVSB_WORMHOLE;
01414           v->vehstatus |= VS_HIDDEN;
01415           return VETSB_ENTERED_WORMHOLE;
01416         } else {
01417           return VETSB_CONTINUE;
01418         }
01419       }
01420 
01421       if (dir == ReverseDiagDir(vdir) && (
01422             /* We're at the tunnel exit ?? */
01423             fc == _tunnel_fractcoord_6[dir] ||
01424             fc == _tunnel_fractcoord_7[dir]
01425           ) &&
01426           z == 0) {
01427         v->tile = tile;
01428         v->u.road.state = _road_exit_tunnel_state[dir];
01429         v->u.road.frame = _road_exit_tunnel_frame[dir];
01430         v->vehstatus &= ~VS_HIDDEN;
01431         return VETSB_ENTERED_WORMHOLE;
01432       }
01433     }
01434   } else { // IsBridge(tile)
01435 
01436     if (v->IsPrimaryVehicle() && v->type != VEH_SHIP) {
01437       /* modify speed of vehicle */
01438       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01439 
01440       if (v->type == VEH_ROAD) spd *= 2;
01441       if (v->cur_speed > spd) v->cur_speed = spd;
01442     }
01443 
01444     if (DirToDiagDir(v->direction) == dir) {
01445       switch (dir) {
01446         default: NOT_REACHED();
01447         case DIAGDIR_NE: if ((x & 0xF) != 0)             return VETSB_CONTINUE; break;
01448         case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
01449         case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
01450         case DIAGDIR_NW: if ((y & 0xF) != 0)             return VETSB_CONTINUE; break;
01451       }
01452       switch (v->type) {
01453         case VEH_TRAIN:
01454           v->u.rail.track = TRACK_BIT_WORMHOLE;
01455           ClrBit(v->u.rail.flags, VRF_GOINGUP);
01456           ClrBit(v->u.rail.flags, VRF_GOINGDOWN);
01457           break;
01458 
01459         case VEH_ROAD:
01460           v->u.road.state = RVSB_WORMHOLE;
01461           break;
01462 
01463         case VEH_SHIP:
01464           v->u.ship.state = TRACK_BIT_WORMHOLE;
01465           break;
01466 
01467         default: NOT_REACHED();
01468       }
01469       return VETSB_ENTERED_WORMHOLE;
01470     } else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
01471       v->tile = tile;
01472       switch (v->type) {
01473         case VEH_TRAIN:
01474           if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
01475             v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
01476             return VETSB_ENTERED_WORMHOLE;
01477           }
01478           break;
01479 
01480         case VEH_ROAD:
01481           if (v->u.road.state == RVSB_WORMHOLE) {
01482             v->u.road.state = _road_exit_tunnel_state[dir];
01483             v->u.road.frame = 0;
01484             return VETSB_ENTERED_WORMHOLE;
01485           }
01486           break;
01487 
01488         case VEH_SHIP:
01489           if (v->u.ship.state == TRACK_BIT_WORMHOLE) {
01490             v->u.ship.state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
01491             return VETSB_ENTERED_WORMHOLE;
01492           }
01493           break;
01494 
01495         default: NOT_REACHED();
01496       }
01497     }
01498   }
01499   return VETSB_CONTINUE;
01500 }
01501 
01502 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01503 {
01504   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01505     DiagDirection direction = GetTunnelBridgeDirection(tile);
01506     Axis axis = DiagDirToAxis(direction);
01507     CommandCost res;
01508     uint z_old;
01509     Slope tileh_old = GetTileSlope(tile, &z_old);
01510 
01511     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01512     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01513       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01514       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01515     } else {
01516       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01517       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01518     }
01519 
01520     /* Surface slope is valid and remains unchanged? */
01521     if (!CmdFailed(res) && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
01522   }
01523 
01524   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01525 }
01526 
01527 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01528   DrawTile_TunnelBridge,           // draw_tile_proc
01529   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
01530   ClearTile_TunnelBridge,          // clear_tile_proc
01531   GetAcceptedCargo_TunnelBridge,   // get_accepted_cargo_proc
01532   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01533   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01534   NULL,                            // click_tile_proc
01535   NULL,                            // animate_tile_proc
01536   TileLoop_TunnelBridge,           // tile_loop_clear
01537   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
01538   NULL,                            // get_produced_cargo_proc
01539   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01540   GetFoundation_TunnelBridge,      // get_foundation_proc
01541   TerraformTile_TunnelBridge,      // terraform_tile_proc
01542 };

Generated on Mon Dec 14 21:00:04 2009 for OpenTTD by  doxygen 1.5.6