# waypoint_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
    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
    00110 static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile, StringID str)
    00111 {
    00112   Waypoint *wp, *best = NULL;
    00113   uint thres = 8;
    00114
    00115   FOR_ALL_WAYPOINTS(wp) {
    00116     if (!wp->IsInUse() && wp->string_id == str && (wp->owner == _current_company || wp->owner == OWNER_NONE)) {
    00117       uint cur_dist = DistanceManhattan(tile, wp->xy);
    00118
    00119       if (cur_dist < thres) {
    00120         thres = cur_dist;
    00121         best = wp;
    00122       }
    00123     }
    00124   }
    00125
    00126   return best;
    00127 }
    00128
    00136 Axis GetAxisForNewWaypoint(TileIndex tile)
    00137 {
    00138   /* The axis for rail waypoints is easy. */
    00139   if (IsRailWaypointTile(tile)) return GetRailStationAxis(tile);
    00140
    00141   /* Non-plain rail type, no valid axis for waypoints. */
    00142   if (!IsTileType(tile, MP_RAILWAY) || GetRailTileType(tile) != RAIL_TILE_NORMAL) return INVALID_AXIS;
    00143
    00144   switch (GetTrackBits(tile)) {
    00145     case TRACK_BIT_X: return AXIS_X;
    00146     case TRACK_BIT_Y: return AXIS_Y;
    00147     default:          return INVALID_AXIS;
    00148   }
    00149 }
    00150
    00151 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
    00152
    00159 static CommandCost IsValidTileForWaypoint(TileIndex tile, Axis axis, StationID *waypoint)
    00160 {
    00161   /* if waypoint is set, then we have special handling to allow building on top of already existing waypoints.
    00162    * so waypoint points to INVALID_STATION if we can build on any waypoint.
    00163    * Or it points to a waypoint if we're only allowed to build on exactly that waypoint. */
    00164   if (waypoint != NULL && IsTileType(tile, MP_STATION)) {
    00165     if (!IsRailWaypoint(tile)) {
    00166       return ClearTile_Station(tile, DC_AUTO); // get error message
    00167     } else {
    00168       StationID wp = GetStationIndex(tile);
    00169       if (*waypoint == INVALID_STATION) {
    00170         *waypoint = wp;
    00171       } else if (*waypoint != wp) {
    00172         return_cmd_error(STR_ERROR_WAYPOINT_ADJOINS_MORE_THAN_ONE_EXISTING);
    00173       }
    00174     }
    00175   }
    00176
    00177   if (GetAxisForNewWaypoint(tile) != axis) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
    00178
    00179   Owner owner = GetTileOwner(tile);
    00180   if (!CheckOwnership(owner)) return CMD_ERROR;
    00181   if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    00182
    00183   Slope tileh = GetTileSlope(tile, NULL);
    00184   if (tileh != SLOPE_FLAT &&
    00185       (!_settings_game.construction.build_on_slopes || IsSteepSlope(tileh) || !(tileh & (0x3 << axis)) || !(tileh & ~(0x3 << axis)))) {
    00186     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
    00187   }
    00188
    00189   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00190
    00191   return CommandCost();
    00192 }
    00193
    00194 extern void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec);
    00195 extern CommandCost FindJoiningWaypoint(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Waypoint **wp);
    00196 extern bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis);
    00197
    00213 CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00214 {
    00215   /* Unpack parameters */
    00216   Axis axis      = (Axis)GB(p1,  4, 1);
    00217   byte width     = GB(p1,  8, 8);
    00218   byte height    = GB(p1, 16, 8);
    00219   bool adjacent  = HasBit(p1, 24);
    00220
    00221   StationClassID spec_class = (StationClassID)GB(p2, 0, 8);
    00222   byte spec_index           = GB(p2, 8, 8);
    00223   StationID station_to_join = GB(p2, 16, 16);
    00224
    00225   /* Check if the given station class is valid */
    00226   if (spec_class != STAT_CLASS_WAYP) return CMD_ERROR;
    00227   if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
    00228
    00229   /* The number of parts to build */
    00230   byte count = axis == AXIS_X ? height : width;
    00231
    00232   if ((axis == AXIS_X ? width : height) != 1) return CMD_ERROR;
    00233   if (count == 0 || count > _settings_game.station.station_spread) return CMD_ERROR;
    00234
    00235   bool reuse = (station_to_join != NEW_STATION);
    00236   if (!reuse) station_to_join = INVALID_STATION;
    00237   bool distant_join = (station_to_join != INVALID_STATION);
    00238
    00239   if (distant_join && (!_settings_game.station.distant_join_stations || !Waypoint::IsValidID(station_to_join))) return CMD_ERROR;
    00240
    00241   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
    00242   StationID est = INVALID_STATION;
    00243
    00244   /* Check whether the tiles we're building on are valid rail or not. */
    00245   TileIndexDiff offset = TileOffsByDiagDir(AxisToDiagDir(OtherAxis(axis)));
    00246   for (int i = 0; i < count; i++) {
    00247     TileIndex tile = start_tile + i * offset;
    00248     CommandCost ret = IsValidTileForWaypoint(tile, axis, _settings_game.station.nonuniform_stations ? &est : NULL);
    00249     if (ret.Failed()) return ret;
    00250   }
    00251
    00252   Waypoint *wp = NULL;
    00253   TileArea new_location(TileArea(start_tile, width, height));
    00254   CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp);
    00255   if (ret.Failed()) return ret;
    00256
    00257   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00258   TileIndex center_tile = start_tile + (count / 2) * offset;
    00259   if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT);
    00260
    00261   if (wp != NULL) {
    00262     /* Reuse an existing station. */
    00263     if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT);
    00264
    00265     /* check if we want to expanding an already existing station? */
    00266     if (wp->train_station.tile != INVALID_TILE && !CanExpandRailStation(wp, new_location, axis)) return CMD_ERROR;
    00267
    00268     if (!wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TEST)) return CMD_ERROR;
    00269   } else {
    00270     /* allocate and initialize new station */
    00271     if (!Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00272   }
    00273
    00274   if (flags & DC_EXEC) {
    00275     if (wp == NULL) {
    00276       wp = new Waypoint(start_tile);
    00277     } else if (!wp->IsInUse()) {
    00278       /* Move existing (recently deleted) waypoint to the new location */
    00279       wp->xy = start_tile;
    00280     }
    00281     wp->owner = GetTileOwner(start_tile);
    00282
    00283     wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TRY);
    00284
    00285     wp->delete_ctr = 0;
    00286     wp->facilities |= FACIL_TRAIN;
    00287     wp->build_date = _date;
    00288     wp->string_id = STR_SV_STNAME_WAYPOINT;
    00289     wp->train_station = new_location;
    00290
    00291     if (wp->town == NULL) MakeDefaultWaypointName(wp);
    00292
    00293     wp->UpdateVirtCoord();
    00294
    00295     const StationSpec *spec = GetCustomStationSpec(spec_class, spec_index);
    00296     byte *layout_ptr = AllocaM(byte, count);
    00297     if (spec == NULL) {
    00298       /* The layout must be 0 for the 'normal' waypoints by design. */
    00299       memset(layout_ptr, 0, count);
    00300     } else {
    00301       /* But for NewGRF waypoints we like to have their style. */
    00302       GetStationLayout(layout_ptr, count, 1, spec);
    00303     }
    00304     byte map_spec_index = AllocateSpecToStation(spec, wp, true);
    00305
    00306     for (int i = 0; i < count; i++) {
    00307       TileIndex tile = start_tile + i * offset;
    00308       byte old_specindex = IsTileType(tile, MP_STATION) ? GetCustomStationSpecIndex(tile) : 0;
    00309       bool reserved = IsTileType(tile, MP_RAILWAY) ?
    00310           HasBit(GetRailReservationTrackBits(tile), AxisToTrack(axis)) :
    00311           HasStationReservation(tile);
    00312       MakeRailWaypoint(tile, wp->owner, wp->index, axis, layout_ptr[i], GetRailType(tile));
    00313       SetCustomStationSpecIndex(tile, map_spec_index);
    00314       SetRailStationReservation(tile, reserved);
    00315       MarkTileDirtyByTile(tile);
    00316
    00317       DeallocateSpecFromStation(wp, old_specindex);
    00318       YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
    00319     }
    00320   }
    00321
    00322   return CommandCost(EXPENSES_CONSTRUCTION, count * _price[PR_BUILD_WAYPOINT_RAIL]);
    00323 }
    00324
    00333 CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00334 {
    00335   if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00336   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
    00337
    00338   if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    00339
    00340   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
    00341   Waypoint *wp = FindDeletedWaypointCloseTo(tile, STR_SV_STNAME_BUOY);
    00342   if (wp == NULL && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
    00343
    00344   if (flags & DC_EXEC) {
    00345     if (wp == NULL) {
    00346       wp = new Waypoint(tile);
    00347     } else {
    00348       /* Move existing (recently deleted) buoy to the new location */
    00349       wp->xy = tile;
    00350       InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00351     }
    00352     wp->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
    00353
    00354     wp->string_id = STR_SV_STNAME_BUOY;
    00355
    00356     wp->facilities |= FACIL_DOCK;
    00357     wp->owner = OWNER_NONE;
    00358
    00359     wp->build_date = _date;
    00360
    00361     if (wp->town == NULL) MakeDefaultWaypointName(wp);
    00362
    00363     MakeBuoy(tile, wp->index, GetWaterClass(tile));
    00364
    00365     wp->UpdateVirtCoord();
    00366     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00367   }
    00368
    00369   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_WAYPOINT_BUOY]);
    00370 }
    00371
    00379 CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
    00380 {
    00381   /* XXX: strange stuff, allow clearing as invalid company when clearing landscape */
    00382   if (!Company::IsValidID(_current_company) && !(flags & DC_BANKRUPT)) return_cmd_error(INVALID_STRING_ID);
    00383
    00384   Waypoint *wp = Waypoint::GetByTile(tile);
    00385
    00386   if (HasStationInUse(wp->index, INVALID_COMPANY)) return_cmd_error(STR_ERROR_BUOY_IS_IN_USE);
    00387   /* remove the buoy if there is a ship on tile when company goes bankrupt... */
    00388   if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
    00389
    00390   if (flags & DC_EXEC) {
    00391     wp->facilities &= ~FACIL_DOCK;
    00392
    00393     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
    00394
    00395     /* We have to set the water tile's state to the same state as before the
    00396      * buoy was placed. Otherwise one could plant a buoy on a canal edge,
    00397      * remove it and flood the land (if the canal edge is at level 0) */
    00398     MakeWaterKeepingClass(tile, GetTileOwner(tile));
    00399     MarkTileDirtyByTile(tile);
    00400
    00401     wp->rect.AfterRemoveTile(wp, tile);
    00402
    00403     wp->UpdateVirtCoord();
    00404     wp->delete_ctr = 0;
    00405   }
    00406
    00407   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_WAYPOINT_BUOY]);
    00408 }
    00409
    00410
    00411 static bool IsUniqueWaypointName(const char *name)
    00412 {
    00413   const Waypoint *wp;
    00414
    00415   FOR_ALL_WAYPOINTS(wp) {
    00416     if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
    00417   }
    00418
    00419   return true;
    00420 }
    00421
    00431 CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00432 {
    00433   Waypoint *wp = Waypoint::GetIfValid(p1);
    00434   if (wp == NULL || !(CheckOwnership(wp->owner) || wp->owner == OWNER_NONE)) return CMD_ERROR;
    00435
    00436   bool reset = StrEmpty(text);
    00437
    00438   if (!reset) {
    00439     if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
    00440     if (!IsUniqueWaypointName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    00441   }
    00442
    00443   if (flags & DC_EXEC) {
    00444     free(wp->name);
    00445
    00446     if (reset) {
    00447       MakeDefaultWaypointName(wp); // sets wp->name = NULL
    00448     } else {
    00449       wp->name = strdup(text);
    00450     }
    00451
    00452     wp->UpdateVirtCoord();
    00453   }
    00454   return CommandCost();
    00455 }