# waypoint_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: waypoint_cmd.cpp 18921 2010-01-26 23:03:47Z yexo $ */
    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
    00014 #include "command_func.h"
    00015 #include "landscape.h"
    00016 #include "bridge_map.h"
    00017 #include "town.h"
    00018 #include "waypoint_base.h"
    00019 #include "pathfinder/yapf/yapf_cache.h"
    00020 #include "strings_func.h"
    00021 #include "functions.h"
    00022 #include "window_func.h"
    00023 #include "date_func.h"
    00024 #include "vehicle_func.h"
    00025 #include "string_func.h"
    00026 #include "company_func.h"
    00027 #include "newgrf_station.h"
    00028 #include "company_base.h"
    00029 #include "water.h"
    00030
    00031 #include "table/strings.h"
    00032
    00036 void Waypoint::UpdateVirtCoord()
    00037 {
    00038   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
    00039   SetDParam(0, this->index);
    00040   this->sign.UpdatePosition(pt.x, pt.y - 0x20, STR_VIEWPORT_WAYPOINT);
    00041   /* Recenter viewport */
    00042   InvalidateWindowData(WC_WAYPOINT_VIEW, this->index);
    00043 }
    00044
    00049 static void MakeDefaultWaypointName(Waypoint *wp)
    00050 {
    00051   uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
    00052   uint32 next = 0; // first waypoint number in the bitmap
    00053   StationID idx = 0; // index where we will stop
    00054
    00055   wp->town = ClosestTownFromTile(wp->xy, UINT_MAX);
    00056
    00057   /* Find first unused waypoint number belonging to this town. This can never fail,
    00058    * as long as there can be at most 65535 waypoints in total.
    00059    *
    00060    * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at most 'n * (1 + ceil(m / 32))'
    00061    * steps (n - number of waypoints in pool, m - number of waypoints near this town).
    00062    * Usually, it needs only 'n' steps.
    00063    *
    00064    * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
    00065    * but this way it is faster */
    00066
    00067   StationID cid = 0; // current index, goes to Waypoint::GetPoolSize()-1, then wraps to 0
    00068   do {
    00069     Waypoint *lwp = Waypoint::GetIfValid(cid);
    00070
    00071     /* check only valid waypoints... */
    00072     if (lwp != NULL && wp != lwp) {
    00073       /* only waypoints with 'generic' name within the same city */
    00074       if (lwp->name == NULL && lwp->town == wp->town && lwp->string_id == wp->string_id) {
    00075         /* if lwp->town_cn < next, uint will overflow to '+inf' */
    00076         uint i = (uint)lwp->town_cn - next;
    00077
    00078         if (i < 32) {
    00079           SetBit(used, i); // update bitmap
    00080           if (i == 0) {
    00081             /* shift bitmap while the lowest bit is '1';
    00082              * increase the base of the bitmap too */
    00083             do {
    00084               used >>= 1;
    00085               next++;
    00086             } while (HasBit(used, 0));
    00087             /* when we are at 'idx' again at end of the loop and
    00088              * 'next' hasn't changed, then no waypoint had town_cn == next,
    00089              * so we can safely use it */
    00090             idx = cid;
    00091           }
    00092         }
    00093       }
    00094     }
    00095
    00096     cid++;
    00097     if (cid == Waypoint::GetPoolSize()) cid = 0; // wrap to zero...
    00098   } while (cid != idx);
    00099
    00100   wp->town_cn = (uint16)next; // set index...
    00101   wp->name = NULL; // ... and use generic name
    00102 }
    00103
    00111 static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile, StringID str, CompanyID cid)
    00112 {
    00113   Waypoint *wp, *best = NULL;
    00114   uint thres = 8;
    00115
    00116   FOR_ALL_WAYPOINTS(wp) {
    00117     if (!wp->IsInUse() && wp->string_id == str && wp->owner == cid) {
    00118       uint cur_dist = DistanceManhattan(tile, wp->xy);
    00119
    00120       if (cur_dist < thres) {
    00121         thres = cur_dist;
    00122         best = wp;
    00123       }
    00124     }
    00125   }
    00126
    00127   return best;
    00128 }
    00129
    00137 Axis GetAxisForNewWaypoint(TileIndex tile)
    00138 {
    00139   /* The axis for rail waypoints is easy. */
    00140   if (IsRailWaypointTile(tile)) return GetRailStationAxis(tile);
    00141
    00142   /* Non-plain rail type, no valid axis for waypoints. */
    00143   if (!IsTileType(tile, MP_RAILWAY) || GetRailTileType(tile) != RAIL_TILE_NORMAL) return INVALID_AXIS;
    00144
    00145   switch (GetTrackBits(tile)) {
    00146     case TRACK_BIT_X: return AXIS_X;
    00147     case TRACK_BIT_Y: return AXIS_Y;
    00148     default:          return INVALID_AXIS;
    00149   }
    00150 }
    00151
    00152 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
    00153
    00160 static CommandCost IsValidTileForWaypoint(TileIndex tile, Axis axis, StationID *waypoint)
    00161 {
    00162   /* if waypoint is set, then we have special handling to allow building on top of already existing waypoints.
    00163    * so waypoint points to INVALID_STATION if we can build on any waypoint.
    00164    * Or it points to a waypoint if we're only allowed to build on exactly that waypoint. */
    00165   if (waypoint != NULL && IsTileType(tile, MP_STATION)) {
    00166     if (!IsRailWaypoint(tile)) {
    00167       return ClearTile_Station(tile, DC_AUTO); // get error message
    00168     } else {
    00169       StationID wp = GetStationIndex(tile);
    00170       if (*waypoint == INVALID_STATION) {
    00171         *waypoint = wp;
    00172       } else if (*waypoint != wp) {
    00173         return_cmd_error(STR_ERROR_WAYPOINT_ADJOINS_MORE_THAN_ONE_EXISTING);
    00174       }
    00175     }
    00176   }
    00177
    00178   if (GetAxisForNewWaypoint(tile) != axis) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
    00179
    00180   Owner owner = GetTileOwner(tile);
    00181   if (!CheckOwnership(owner)) return CMD_ERROR;
    00182   if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    00183
    00184   Slope tileh = GetTileSlope(tile, NULL);
    00185   if (tileh != SLOPE_FLAT &&
    00186       (!_settings_game.construction.build_on_slopes || IsSteepSlope(tileh) || !(tileh & (0x3 << axis)) || !(tileh & ~(0x3 << axis)))) {
    00187     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00188   }
    00189
    00190   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00191
    00192   return CommandCost();
    00193 }
    00194
    00195 extern void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec);
    00196 extern CommandCost FindJoiningWaypoint(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Waypoint **wp);
    00197 extern bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis);
    00198
    00214 CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00215 {
    00216   /* Unpack parameters */
    00217   Axis axis      = (Axis)GB(p1,  4, 1);
    00218   byte width     = GB(p1,  8, 8);
    00219   byte height    = GB(p1, 16, 8);
    00220   bool adjacent  = HasBit(p1, 24);
    00221
    00222   StationClassID spec_class = (StationClassID)GB(p2, 0, 8);
    00223   byte spec_index           = GB(p2, 8, 8);
    00224   StationID station_to_join = GB(p2, 16, 16);
    00225
    00226   /* Check if the given station class is valid */
    00227   if (spec_class != STAT_CLASS_WAYP) return CMD_ERROR;
    00228   if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
    00229
    00230   /* The number of parts to build */
    00231   byte count = axis == AXIS_X ? height : width;
    00232
    00233   if ((axis == AXIS_X ? width : height) != 1) return CMD_ERROR;
    00234   if (count == 0 || count > _settings_game.station.station_spread) return CMD_ERROR;
    00235
    00236   bool reuse = (station_to_join != NEW_STATION);
    00237   if (!reuse) station_to_join = INVALID_STATION;
    00238   bool distant_join = (station_to_join != INVALID_STATION);
    00239
    00240   if (distant_join && (!_settings_game.station.distant_join_stations || !Waypoint::IsValidID(station_to_join))) return CMD_ERROR;
    00241
    00242   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
    00243   StationID est = INVALID_STATION;
    00244
    00245   /* Check whether the tiles we're building on are valid rail or not. */
    00246   TileIndexDiff offset = TileOffsByDiagDir(AxisToDiagDir(OtherAxis(axis)));
    00247   for (int i = 0; i < count; i++) {
    00248     TileIndex tile = start_tile + i * offset;
    00249     CommandCost ret = IsValidTileForWaypoint(tile, axis, _settings_game.station.nonuniform_stations ? &est : NULL);
    00250     if (ret.Failed()) return ret;
    00251   }
    00252
    00253   Waypoint *wp = NULL;
    00254   TileArea new_location(TileArea(start_tile, width, height));
    00255   CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp);
    00256   if (ret.Failed()) return ret;
    00257
    00258   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00259   TileIndex center_tile = start_tile + (count / 2) * offset;
    00260   if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company);
    00261
    00262   if (wp != NULL) {
    00263     /* Reuse an existing waypoint. */
    00264     if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT);
    00265
    00266     /* check if we want to expand an already existing waypoint? */
    00267     if (wp->train_station.tile != INVALID_TILE && !CanExpandRailStation(wp, new_location, axis)) return CMD_ERROR;
    00268
    00269     if (!wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TEST)) return CMD_ERROR;
    00270   } else {
    00271     /* allocate and initialize new waypoint */
    00272     if (!Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00273   }
    00274
    00275   if (flags & DC_EXEC) {
    00276     if (wp == NULL) {
    00277       wp = new Waypoint(start_tile);
    00278     } else if (!wp->IsInUse()) {
    00279       /* Move existing (recently deleted) waypoint to the new location */
    00280       wp->xy = start_tile;
    00281     }
    00282     wp->owner = GetTileOwner(start_tile);
    00283
    00284     wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TRY);
    00285
    00286     wp->delete_ctr = 0;
    00287     wp->facilities |= FACIL_TRAIN;
    00288     wp->build_date = _date;
    00289     wp->string_id = STR_SV_STNAME_WAYPOINT;
    00290     wp->train_station = new_location;
    00291
    00292     if (wp->town == NULL) MakeDefaultWaypointName(wp);
    00293
    00294     wp->UpdateVirtCoord();
    00295
    00296     const StationSpec *spec = GetCustomStationSpec(spec_class, spec_index);
    00297     byte *layout_ptr = AllocaM(byte, count);
    00298     if (spec == NULL) {
    00299       /* The layout must be 0 for the 'normal' waypoints by design. */
    00300       memset(layout_ptr, 0, count);
    00301     } else {
    00302       /* But for NewGRF waypoints we like to have their style. */
    00303       GetStationLayout(layout_ptr, count, 1, spec);
    00304     }
    00305     byte map_spec_index = AllocateSpecToStation(spec, wp, true);
    00306
    00307     for (int i = 0; i < count; i++) {
    00308       TileIndex tile = start_tile + i * offset;
    00309       byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
    00310       bool reserved = IsTileType(tile, MP_RAILWAY) ?
    00311           HasBit(GetRailReservationTrackBits(tile), AxisToTrack(axis)) :
    00312           HasStationReservation(tile);
    00313       MakeRailWaypoint(tile, wp->owner, wp->index, axis, layout_ptr[i], GetRailType(tile));
    00314       SetCustomStationSpecIndex(tile, map_spec_index);
    00315       SetRailStationReservation(tile, reserved);
    00316       MarkTileDirtyByTile(tile);
    00317
    00318       DeallocateSpecFromStation(wp, old_specindex);
    00319       YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
    00320     }
    00321   }
    00322
    00323   return CommandCost(EXPENSES_CONSTRUCTION, count * _price[PR_BUILD_WAYPOINT_RAIL]);
    00324 }
    00325
    00334 CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00335 {
    00336   if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00337   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00338
    00339   if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00340
    00341   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00342   Waypoint *wp = FindDeletedWaypointCloseTo(tile, STR_SV_STNAME_BUOY, OWNER_NONE);
    00343   if (wp == NULL && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00344
    00345   if (flags & DC_EXEC) {
    00346     if (wp == NULL) {
    00347       wp = new Waypoint(tile);
    00348     } else {
    00349       /* Move existing (recently deleted) buoy to the new location */
    00350       wp->xy = tile;
    00351       InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00352     }
    00353     wp->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
    00354
    00355     wp->string_id = STR_SV_STNAME_BUOY;
    00356
    00357     wp->facilities |= FACIL_DOCK;
    00358     wp->owner = OWNER_NONE;
    00359
    00360     wp->build_date = _date;
    00361
    00362     if (wp->town == NULL) MakeDefaultWaypointName(wp);
    00363
    00364     MakeBuoy(tile, wp->index, GetWaterClass(tile));
    00365
    00366     wp->UpdateVirtCoord();
    00367     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00368   }
    00369
    00370   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_WAYPOINT_BUOY]);
    00371 }
    00372
    00380 CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
    00381 {
    00382   /* XXX: strange stuff, allow clearing as invalid company when clearing landscape */
    00383   if (!Company::IsValidID(_current_company) && !(flags & DC_BANKRUPT)) return_cmd_error(INVALID_STRING_ID);
    00384
    00385   Waypoint *wp = Waypoint::GetByTile(tile);
    00386
    00387   if (HasStationInUse(wp->index, INVALID_COMPANY)) return_cmd_error(STR_ERROR_BUOY_IS_IN_USE);
    00388   /* remove the buoy if there is a ship on tile when company goes bankrupt... */
    00389   if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    00390
    00391   if (flags & DC_EXEC) {
    00392     wp->facilities &= ~FACIL_DOCK;
    00393
    00394     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00395
    00396     /* We have to set the water tile's state to the same state as before the
    00397      * buoy was placed. Otherwise one could plant a buoy on a canal edge,
    00398      * remove it and flood the land (if the canal edge is at level 0) */
    00399     MakeWaterKeepingClass(tile, GetTileOwner(tile));
    00400     MarkTileDirtyByTile(tile);
    00401
    00402     wp->rect.AfterRemoveTile(wp, tile);
    00403
    00404     wp->UpdateVirtCoord();
    00405     wp->delete_ctr = 0;
    00406   }
    00407
    00408   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_WAYPOINT_BUOY]);
    00409 }
    00410
    00411
    00412 static bool IsUniqueWaypointName(const char *name)
    00413 {
    00414   const Waypoint *wp;
    00415
    00416   FOR_ALL_WAYPOINTS(wp) {
    00417     if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
    00418   }
    00419
    00420   return true;
    00421 }
    00422
    00432 CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00433 {
    00434   Waypoint *wp = Waypoint::GetIfValid(p1);
    00435   if (wp == NULL || !(CheckOwnership(wp->owner) || wp->owner == OWNER_NONE)) return CMD_ERROR;
    00436
    00437   bool reset = StrEmpty(text);
    00438
    00439   if (!reset) {
    00440     if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
    00441     if (!IsUniqueWaypointName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    00442   }
    00443
    00444   if (flags & DC_EXEC) {
    00445     free(wp->name);
    00446
    00447     if (reset) {
    00448       MakeDefaultWaypointName(wp); // sets wp->name = NULL
    00449     } else {
    00450       wp->name = strdup(text);
    00451     }
    00452
    00453     wp->UpdateVirtCoord();
    00454   }
    00455   return CommandCost();
    00456 }