00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "aircraft.h"
00014 #include "bridge_map.h"
00015 #include "cmd_helper.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "town.h"
00019 #include "news_func.h"
00020 #include "train.h"
00021 #include "roadveh.h"
00022 #include "industry.h"
00023 #include "newgrf_cargo.h"
00024 #include "newgrf_debug.h"
00025 #include "newgrf_station.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "road_internal.h"
00028 #include "autoslope.h"
00029 #include "water.h"
00030 #include "station_gui.h"
00031 #include "strings_func.h"
00032 #include "functions.h"
00033 #include "window_func.h"
00034 #include "date_func.h"
00035 #include "vehicle_func.h"
00036 #include "string_func.h"
00037 #include "animated_tile_func.h"
00038 #include "elrail_func.h"
00039 #include "station_base.h"
00040 #include "roadstop_base.h"
00041 #include "newgrf_railtype.h"
00042 #include "waypoint_base.h"
00043 #include "waypoint_func.h"
00044 #include "pbs.h"
00045 #include "debug.h"
00046 #include "core/random_func.hpp"
00047 #include "company_base.h"
00048 #include "table/airporttile_ids.h"
00049 #include "newgrf_airporttiles.h"
00050 #include "order_backup.h"
00051
00052 #include "table/strings.h"
00053
00060 bool IsHangar(TileIndex t)
00061 {
00062 assert(IsTileType(t, MP_STATION));
00063
00064
00065 if (!IsAirport(t)) return false;
00066
00067 const Station *st = Station::GetByTile(t);
00068 const AirportSpec *as = st->airport.GetSpec();
00069
00070 for (uint i = 0; i < as->nof_depots; i++) {
00071 if (st->airport.GetHangarTile(i) == t) return true;
00072 }
00073
00074 return false;
00075 }
00076
00084 template <class T>
00085 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00086 {
00087 ta.tile -= TileDiffXY(1, 1);
00088 ta.w += 2;
00089 ta.h += 2;
00090
00091
00092 TILE_AREA_LOOP(tile_cur, ta) {
00093 if (IsTileType(tile_cur, MP_STATION)) {
00094 StationID t = GetStationIndex(tile_cur);
00095
00096 if (closest_station == INVALID_STATION) {
00097 if (T::IsValidID(t)) closest_station = t;
00098 } else if (closest_station != t) {
00099 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00100 }
00101 }
00102 }
00103 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00104 return CommandCost();
00105 }
00106
00112 typedef bool (*CMSAMatcher)(TileIndex tile);
00113
00120 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00121 {
00122 int num = 0;
00123
00124 for (int dx = -3; dx <= 3; dx++) {
00125 for (int dy = -3; dy <= 3; dy++) {
00126 TileIndex t = TileAddWrap(tile, dx, dy);
00127 if (t != INVALID_TILE && cmp(t)) num++;
00128 }
00129 }
00130
00131 return num;
00132 }
00133
00139 static bool CMSAMine(TileIndex tile)
00140 {
00141
00142 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00143
00144 const Industry *ind = Industry::GetByTile(tile);
00145
00146
00147 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00148
00149 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00150
00151
00152 if (ind->produced_cargo[i] != CT_INVALID &&
00153 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00154 return true;
00155 }
00156 }
00157
00158 return false;
00159 }
00160
00166 static bool CMSAWater(TileIndex tile)
00167 {
00168 return IsTileType(tile, MP_WATER) && IsWater(tile);
00169 }
00170
00176 static bool CMSATree(TileIndex tile)
00177 {
00178 return IsTileType(tile, MP_TREES);
00179 }
00180
00186 static bool CMSAForest(TileIndex tile)
00187 {
00188
00189 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00190
00191 const Industry *ind = Industry::GetByTile(tile);
00192
00193
00194 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
00195
00196 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00197
00198 if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
00199 }
00200
00201 return false;
00202 }
00203
00204 #define M(x) ((x) - STR_SV_STNAME)
00205
00206 enum StationNaming {
00207 STATIONNAMING_RAIL,
00208 STATIONNAMING_ROAD,
00209 STATIONNAMING_AIRPORT,
00210 STATIONNAMING_OILRIG,
00211 STATIONNAMING_DOCK,
00212 STATIONNAMING_HELIPORT,
00213 };
00214
00216 struct StationNameInformation {
00217 uint32 free_names;
00218 bool *indtypes;
00219 };
00220
00229 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00230 {
00231
00232 StationNameInformation *sni = (StationNameInformation*)user_data;
00233 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00234
00235
00236 IndustryType indtype = GetIndustryType(tile);
00237 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00238
00239
00240
00241 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00242 return !sni->indtypes[indtype];
00243 }
00244
00245 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00246 {
00247 static const uint32 _gen_station_name_bits[] = {
00248 0,
00249 0,
00250 1U << M(STR_SV_STNAME_AIRPORT),
00251 1U << M(STR_SV_STNAME_OILFIELD),
00252 1U << M(STR_SV_STNAME_DOCKS),
00253 1U << M(STR_SV_STNAME_HELIPORT),
00254 };
00255
00256 const Town *t = st->town;
00257 uint32 free_names = UINT32_MAX;
00258
00259 bool indtypes[NUM_INDUSTRYTYPES];
00260 memset(indtypes, 0, sizeof(indtypes));
00261
00262 const Station *s;
00263 FOR_ALL_STATIONS(s) {
00264 if (s != st && s->town == t) {
00265 if (s->indtype != IT_INVALID) {
00266 indtypes[s->indtype] = true;
00267 continue;
00268 }
00269 uint str = M(s->string_id);
00270 if (str <= 0x20) {
00271 if (str == M(STR_SV_STNAME_FOREST)) {
00272 str = M(STR_SV_STNAME_WOODS);
00273 }
00274 ClrBit(free_names, str);
00275 }
00276 }
00277 }
00278
00279 TileIndex indtile = tile;
00280 StationNameInformation sni = { free_names, indtypes };
00281 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00282
00283 IndustryType indtype = GetIndustryType(indtile);
00284 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00285
00286 if (indsp->station_name != STR_NULL) {
00287 st->indtype = indtype;
00288 return STR_SV_STNAME_FALLBACK;
00289 }
00290 }
00291
00292
00293 free_names = sni.free_names;
00294
00295
00296 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00297 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00298
00299
00300 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00301 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00302 return STR_SV_STNAME_MINES;
00303 }
00304 }
00305
00306
00307 if (DistanceMax(tile, t->xy) < 8) {
00308 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00309
00310 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00311 }
00312
00313
00314 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00315 DistanceFromEdge(tile) < 20 &&
00316 CountMapSquareAround(tile, CMSAWater) >= 5) {
00317 return STR_SV_STNAME_LAKESIDE;
00318 }
00319
00320
00321 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00322 CountMapSquareAround(tile, CMSATree) >= 8 ||
00323 CountMapSquareAround(tile, CMSAForest) >= 2)
00324 ) {
00325 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00326 }
00327
00328
00329 uint z = GetTileZ(tile);
00330 uint z2 = GetTileZ(t->xy);
00331 if (z < z2) {
00332 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00333 } else if (z > z2) {
00334 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00335 }
00336
00337
00338 static const int8 _direction_and_table[] = {
00339 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00340 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00341 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00342 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00343 };
00344
00345 free_names &= _direction_and_table[
00346 (TileX(tile) < TileX(t->xy)) +
00347 (TileY(tile) < TileY(t->xy)) * 2];
00348
00349 tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
00350 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00351 }
00352 #undef M
00353
00359 static Station *GetClosestDeletedStation(TileIndex tile)
00360 {
00361 uint threshold = 8;
00362 Station *best_station = NULL;
00363 Station *st;
00364
00365 FOR_ALL_STATIONS(st) {
00366 if (!st->IsInUse() && st->owner == _current_company) {
00367 uint cur_dist = DistanceManhattan(tile, st->xy);
00368
00369 if (cur_dist < threshold) {
00370 threshold = cur_dist;
00371 best_station = st;
00372 }
00373 }
00374 }
00375
00376 return best_station;
00377 }
00378
00379
00380 void Station::GetTileArea(TileArea *ta, StationType type) const
00381 {
00382 switch (type) {
00383 case STATION_RAIL:
00384 *ta = this->train_station;
00385 return;
00386
00387 case STATION_AIRPORT:
00388 *ta = this->airport;
00389 return;
00390
00391 case STATION_TRUCK:
00392 *ta = this->truck_station;
00393 return;
00394
00395 case STATION_BUS:
00396 *ta = this->bus_station;
00397 return;
00398
00399 case STATION_DOCK:
00400 case STATION_OILRIG:
00401 ta->tile = this->dock_tile;
00402 break;
00403
00404 default: NOT_REACHED();
00405 }
00406
00407 ta->w = 1;
00408 ta->h = 1;
00409 }
00410
00414 void Station::UpdateVirtCoord()
00415 {
00416 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00417
00418 pt.y -= 32;
00419 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16;
00420
00421 SetDParam(0, this->index);
00422 SetDParam(1, this->facilities);
00423 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00424
00425 SetWindowDirty(WC_STATION_VIEW, this->index);
00426 }
00427
00429 void UpdateAllStationVirtCoords()
00430 {
00431 BaseStation *st;
00432
00433 FOR_ALL_BASE_STATIONS(st) {
00434 st->UpdateVirtCoord();
00435 }
00436 }
00437
00443 static uint GetAcceptanceMask(const Station *st)
00444 {
00445 uint mask = 0;
00446
00447 for (CargoID i = 0; i < NUM_CARGO; i++) {
00448 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
00449 }
00450 return mask;
00451 }
00452
00457 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00458 {
00459 for (uint i = 0; i < num_items; i++) {
00460 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00461 }
00462
00463 SetDParam(0, st->index);
00464 AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00465 }
00466
00474 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00475 {
00476 CargoArray produced;
00477
00478 int x = TileX(tile);
00479 int y = TileY(tile);
00480
00481
00482
00483 int x2 = min(x + w + rad, MapSizeX());
00484 int x1 = max(x - rad, 0);
00485
00486 int y2 = min(y + h + rad, MapSizeY());
00487 int y1 = max(y - rad, 0);
00488
00489 assert(x1 < x2);
00490 assert(y1 < y2);
00491 assert(w > 0);
00492 assert(h > 0);
00493
00494 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00495
00496
00497
00498 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00499
00500
00501
00502
00503
00504
00505
00506 const Industry *i;
00507 FOR_ALL_INDUSTRIES(i) {
00508 if (!ta.Intersects(i->location)) continue;
00509
00510 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00511 CargoID cargo = i->produced_cargo[j];
00512 if (cargo != CT_INVALID) produced[cargo]++;
00513 }
00514 }
00515
00516 return produced;
00517 }
00518
00527 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00528 {
00529 CargoArray acceptance;
00530 if (always_accepted != NULL) *always_accepted = 0;
00531
00532 int x = TileX(tile);
00533 int y = TileY(tile);
00534
00535
00536
00537 int x2 = min(x + w + rad, MapSizeX());
00538 int y2 = min(y + h + rad, MapSizeY());
00539 int x1 = max(x - rad, 0);
00540 int y1 = max(y - rad, 0);
00541
00542 assert(x1 < x2);
00543 assert(y1 < y2);
00544 assert(w > 0);
00545 assert(h > 0);
00546
00547 for (int yc = y1; yc != y2; yc++) {
00548 for (int xc = x1; xc != x2; xc++) {
00549 TileIndex tile = TileXY(xc, yc);
00550 AddAcceptedCargo(tile, acceptance, always_accepted);
00551 }
00552 }
00553
00554 return acceptance;
00555 }
00556
00562 void UpdateStationAcceptance(Station *st, bool show_msg)
00563 {
00564
00565 uint old_acc = GetAcceptanceMask(st);
00566
00567
00568 CargoArray acceptance;
00569 if (!st->rect.IsEmpty()) {
00570 acceptance = GetAcceptanceAroundTiles(
00571 TileXY(st->rect.left, st->rect.top),
00572 st->rect.right - st->rect.left + 1,
00573 st->rect.bottom - st->rect.top + 1,
00574 st->GetCatchmentRadius(),
00575 &st->always_accepted
00576 );
00577 }
00578
00579
00580 for (CargoID i = 0; i < NUM_CARGO; i++) {
00581 uint amt = min(acceptance[i], 15);
00582
00583
00584 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00585 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00586 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00587 amt = 0;
00588 }
00589
00590 SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
00591 }
00592
00593
00594 uint new_acc = GetAcceptanceMask(st);
00595 if (old_acc == new_acc) return;
00596
00597
00598 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00599
00600
00601 static const StringID accept_msg[] = {
00602 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00603 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00604 };
00605 static const StringID reject_msg[] = {
00606 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00607 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00608 };
00609
00610
00611 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00612 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00613 uint num_acc = 0;
00614 uint num_rej = 0;
00615
00616
00617 for (CargoID i = 0; i < NUM_CARGO; i++) {
00618 if (HasBit(new_acc, i)) {
00619 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00620
00621 accepts[num_acc++] = i;
00622 }
00623 } else {
00624 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00625
00626 rejects[num_rej++] = i;
00627 }
00628 }
00629 }
00630
00631
00632 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00633 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00634 }
00635
00636
00637 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
00638 }
00639
00640 static void UpdateStationSignCoord(BaseStation *st)
00641 {
00642 const StationRect *r = &st->rect;
00643
00644 if (r->IsEmpty()) return;
00645
00646
00647 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00648 st->UpdateVirtCoord();
00649 }
00650
00657 static void DeleteStationIfEmpty(BaseStation *st)
00658 {
00659 if (!st->IsInUse()) {
00660 st->delete_ctr = 0;
00661 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00662 }
00663
00664 UpdateStationSignCoord(st);
00665 }
00666
00667 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00668
00677 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool check_bridge = true)
00678 {
00679 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00680 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00681 }
00682
00683 CommandCost ret = EnsureNoVehicleOnGround(tile);
00684 if (ret.Failed()) return ret;
00685
00686 uint z;
00687 Slope tileh = GetTileSlope(tile, &z);
00688
00689
00690
00691
00692
00693 if (IsSteepSlope(tileh) ||
00694 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00695 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00696 }
00697
00698 CommandCost cost(EXPENSES_CONSTRUCTION);
00699 int flat_z = z;
00700 if (tileh != SLOPE_FLAT) {
00701
00702 if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
00703 (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
00704 (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
00705 (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
00706 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00707 }
00708 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00709 flat_z += TILE_HEIGHT;
00710 }
00711
00712
00713 if (allowed_z < 0) {
00714
00715 allowed_z = flat_z;
00716 } else if (allowed_z != flat_z) {
00717 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00718 }
00719
00720 return cost;
00721 }
00722
00729 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00730 {
00731 CommandCost cost(EXPENSES_CONSTRUCTION);
00732 int allowed_z = -1;
00733
00734 TILE_AREA_LOOP(tile_cur, tile_area) {
00735 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z);
00736 if (ret.Failed()) return ret;
00737 cost.AddCost(ret);
00738
00739 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00740 if (ret.Failed()) return ret;
00741 cost.AddCost(ret);
00742 }
00743
00744 return cost;
00745 }
00746
00757 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles)
00758 {
00759 CommandCost cost(EXPENSES_CONSTRUCTION);
00760 int allowed_z = -1;
00761
00762 TILE_AREA_LOOP(tile_cur, tile_area) {
00763 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z);
00764 if (ret.Failed()) return ret;
00765 cost.AddCost(ret);
00766
00767
00768
00769
00770 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00771 if (!IsRailStation(tile_cur)) {
00772 return ClearTile_Station(tile_cur, DC_AUTO);
00773 } else {
00774 StationID st = GetStationIndex(tile_cur);
00775 if (*station == INVALID_STATION) {
00776 *station = st;
00777 } else if (*station != st) {
00778 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00779 }
00780 }
00781 } else {
00782
00783
00784 if (rt != INVALID_RAILTYPE &&
00785 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00786 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00787
00788
00789
00790
00791
00792
00793 TrackBits tracks = GetTrackBits(tile_cur);
00794 Track track = RemoveFirstTrack(&tracks);
00795 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00796
00797 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00798
00799 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00800 Train *v = GetTrainForReservation(tile_cur, track);
00801 if (v != NULL) {
00802 *affected_vehicles.Append() = v;
00803 }
00804 }
00805 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00806 if (ret.Failed()) return ret;
00807 cost.AddCost(ret);
00808
00809 continue;
00810 }
00811 }
00812 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00813 if (ret.Failed()) return ret;
00814 cost.AddCost(ret);
00815 }
00816 }
00817
00818 return cost;
00819 }
00820
00833 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
00834 {
00835 CommandCost cost(EXPENSES_CONSTRUCTION);
00836 int allowed_z = -1;
00837
00838 TILE_AREA_LOOP(cur_tile, tile_area) {
00839 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z);
00840 if (ret.Failed()) return ret;
00841 cost.AddCost(ret);
00842
00843
00844
00845
00846 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00847 if (!IsRoadStop(cur_tile)) {
00848 return ClearTile_Station(cur_tile, DC_AUTO);
00849 } else {
00850 if (is_truck_stop != IsTruckStop(cur_tile) ||
00851 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00852 return ClearTile_Station(cur_tile, DC_AUTO);
00853 }
00854
00855 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00856 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00857 }
00858 StationID st = GetStationIndex(cur_tile);
00859 if (*station == INVALID_STATION) {
00860 *station = st;
00861 } else if (*station != st) {
00862 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00863 }
00864 }
00865 } else {
00866 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00867
00868 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00869 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00870
00871 switch (CountBits(rb)) {
00872 case 1:
00873 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00874
00875 case 2:
00876 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00877 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00878
00879 default:
00880 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00881 }
00882 }
00883
00884 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00885 uint num_roadbits = 0;
00886 if (build_over_road) {
00887
00888 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00889 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00890 if (road_owner == OWNER_TOWN) {
00891 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00892 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00893 CommandCost ret = CheckOwnership(road_owner);
00894 if (ret.Failed()) return ret;
00895 }
00896 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00897 }
00898
00899
00900 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00901 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00902 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00903 CommandCost ret = CheckOwnership(tram_owner);
00904 if (ret.Failed()) return ret;
00905 }
00906 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00907 }
00908
00909
00910 rts |= cur_rts;
00911 } else {
00912 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00913 if (ret.Failed()) return ret;
00914 cost.AddCost(ret);
00915 }
00916
00917 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00918 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00919 }
00920 }
00921
00922 return cost;
00923 }
00924
00932 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00933 {
00934 TileArea cur_ta = st->train_station;
00935
00936
00937 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00938 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00939 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00940 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00941 new_ta.tile = TileXY(x, y);
00942
00943
00944 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00945 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00946 }
00947
00948 return CommandCost();
00949 }
00950
00951 static inline byte *CreateSingle(byte *layout, int n)
00952 {
00953 int i = n;
00954 do *layout++ = 0; while (--i);
00955 layout[((n - 1) >> 1) - n] = 2;
00956 return layout;
00957 }
00958
00959 static inline byte *CreateMulti(byte *layout, int n, byte b)
00960 {
00961 int i = n;
00962 do *layout++ = b; while (--i);
00963 if (n > 4) {
00964 layout[0 - n] = 0;
00965 layout[n - 1 - n] = 0;
00966 }
00967 return layout;
00968 }
00969
00970 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00971 {
00972 if (statspec != NULL && statspec->lengths >= plat_len &&
00973 statspec->platforms[plat_len - 1] >= numtracks &&
00974 statspec->layouts[plat_len - 1][numtracks - 1]) {
00975
00976 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00977 plat_len * numtracks);
00978 return;
00979 }
00980
00981 if (plat_len == 1) {
00982 CreateSingle(layout, numtracks);
00983 } else {
00984 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00985 numtracks >>= 1;
00986
00987 while (--numtracks >= 0) {
00988 layout = CreateMulti(layout, plat_len, 4);
00989 layout = CreateMulti(layout, plat_len, 6);
00990 }
00991 }
00992 }
00993
01005 template <class T, StringID error_message>
01006 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01007 {
01008 assert(*st == NULL);
01009 bool check_surrounding = true;
01010
01011 if (_settings_game.station.adjacent_stations) {
01012 if (existing_station != INVALID_STATION) {
01013 if (adjacent && existing_station != station_to_join) {
01014
01015
01016 return_cmd_error(error_message);
01017 } else {
01018
01019
01020 *st = T::GetIfValid(existing_station);
01021 check_surrounding = (*st == NULL);
01022 }
01023 } else {
01024
01025
01026 if (adjacent) check_surrounding = false;
01027 }
01028 }
01029
01030 if (check_surrounding) {
01031
01032 CommandCost ret = GetStationAround(ta, existing_station, st);
01033 if (ret.Failed()) return ret;
01034 }
01035
01036
01037 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01038
01039 return CommandCost();
01040 }
01041
01051 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01052 {
01053 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01054 }
01055
01065 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01066 {
01067 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01068 }
01069
01087 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01088 {
01089
01090 RailType rt = Extract<RailType, 0, 4>(p1);
01091 Axis axis = Extract<Axis, 4, 1>(p1);
01092 byte numtracks = GB(p1, 8, 8);
01093 byte plat_len = GB(p1, 16, 8);
01094 bool adjacent = HasBit(p1, 24);
01095
01096 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01097 byte spec_index = GB(p2, 8, 8);
01098 StationID station_to_join = GB(p2, 16, 16);
01099
01100
01101 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01102 if (ret.Failed()) return ret;
01103
01104 if (!ValParamRailtype(rt)) return CMD_ERROR;
01105
01106
01107 if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01108 if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01109 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01110
01111 int w_org, h_org;
01112 if (axis == AXIS_X) {
01113 w_org = plat_len;
01114 h_org = numtracks;
01115 } else {
01116 h_org = plat_len;
01117 w_org = numtracks;
01118 }
01119
01120 bool reuse = (station_to_join != NEW_STATION);
01121 if (!reuse) station_to_join = INVALID_STATION;
01122 bool distant_join = (station_to_join != INVALID_STATION);
01123
01124 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01125
01126 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01127
01128
01129 TileArea new_location(tile_org, w_org, h_org);
01130
01131
01132 StationID est = INVALID_STATION;
01133 SmallVector<Train *, 4> affected_vehicles;
01134
01135 CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, 5 << axis, &est, rt, affected_vehicles);
01136 if (cost.Failed()) return cost;
01137
01138 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01139 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01140
01141 Station *st = NULL;
01142 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01143 if (ret.Failed()) return ret;
01144
01145
01146 if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01147
01148 if (st != NULL) {
01149
01150 if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01151
01152 if (st->train_station.tile != INVALID_TILE) {
01153 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01154 if (ret.Failed()) return ret;
01155 }
01156
01157
01158 CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01159 if (ret.Failed()) return ret;
01160 } else {
01161
01162 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01163
01164 if (flags & DC_EXEC) {
01165 st = new Station(tile_org);
01166
01167 st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01168 st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01169
01170 if (Company::IsValidID(_current_company)) {
01171 SetBit(st->town->have_ratings, _current_company);
01172 }
01173 }
01174 }
01175
01176
01177 const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01178 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01179 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01180
01181 if (statspec != NULL) {
01182
01183
01184
01185 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01186 return CMD_ERROR;
01187 }
01188
01189
01190 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
01191 return CMD_ERROR;
01192 }
01193 }
01194
01195 if (flags & DC_EXEC) {
01196 TileIndexDiff tile_delta;
01197 byte *layout_ptr;
01198 byte numtracks_orig;
01199 Track track;
01200
01201 st->train_station = new_location;
01202 st->AddFacility(FACIL_TRAIN, new_location.tile);
01203
01204 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01205
01206 if (statspec != NULL) {
01207
01208
01209 st->cached_anim_triggers |= statspec->animation.triggers;
01210 }
01211
01212 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01213 track = AxisToTrack(axis);
01214
01215 layout_ptr = AllocaM(byte, numtracks * plat_len);
01216 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01217
01218 numtracks_orig = numtracks;
01219
01220 do {
01221 TileIndex tile = tile_org;
01222 int w = plat_len;
01223 do {
01224 byte layout = *layout_ptr++;
01225 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01226
01227 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01228 if (v != NULL) {
01229 FreeTrainTrackReservation(v);
01230 *affected_vehicles.Append() = v;
01231 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01232 for (; v->Next() != NULL; v = v->Next()) { }
01233 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01234 }
01235 }
01236
01237
01238 DeleteAnimatedTile(tile);
01239 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01240 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01241
01242 DeallocateSpecFromStation(st, old_specindex);
01243
01244 SetCustomStationSpecIndex(tile, specindex);
01245 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01246 SetAnimationFrame(tile, 0);
01247
01248 if (statspec != NULL) {
01249
01250 uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01251
01252
01253 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01254 if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
01255
01256
01257 TriggerStationAnimation(st, tile, SAT_BUILT);
01258 }
01259
01260 tile += tile_delta;
01261 } while (--w);
01262 AddTrackToSignalBuffer(tile_org, track, _current_company);
01263 YapfNotifyTrackLayoutChange(tile_org, track);
01264 tile_org += tile_delta ^ TileDiffXY(1, 1);
01265 } while (--numtracks);
01266
01267 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01268
01269 Train *v = affected_vehicles[i];
01270 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01271 TryPathReserve(v, true, true);
01272 for (; v->Next() != NULL; v = v->Next()) { }
01273 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01274 }
01275
01276 st->MarkTilesDirty(false);
01277 st->UpdateVirtCoord();
01278 UpdateStationAcceptance(st, false);
01279 st->RecomputeIndustriesNear();
01280 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01281 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01282 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01283 }
01284
01285 return cost;
01286 }
01287
01288 static void MakeRailStationAreaSmaller(BaseStation *st)
01289 {
01290 TileArea ta = st->train_station;
01291
01292 restart:
01293
01294
01295 if (ta.w != 0 && ta.h != 0) {
01296
01297 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01298
01299 if (++i == ta.h) {
01300 ta.tile += TileDiffXY(1, 0);
01301 ta.w--;
01302 goto restart;
01303 }
01304 }
01305
01306
01307 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01308
01309 if (++i == ta.h) {
01310 ta.w--;
01311 goto restart;
01312 }
01313 }
01314
01315
01316 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01317
01318 if (++i == ta.w) {
01319 ta.tile += TileDiffXY(0, 1);
01320 ta.h--;
01321 goto restart;
01322 }
01323 }
01324
01325
01326 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01327
01328 if (++i == ta.w) {
01329 ta.h--;
01330 goto restart;
01331 }
01332 }
01333 } else {
01334 ta.Clear();
01335 }
01336
01337 st->train_station = ta;
01338 }
01339
01350 template <class T>
01351 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01352 {
01353
01354 int quantity = 0;
01355 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01356
01357
01358 TILE_AREA_LOOP(tile, ta) {
01359
01360 if (!HasStationTileRail(tile)) continue;
01361
01362
01363 CommandCost ret = EnsureNoVehicleOnGround(tile);
01364 if (ret.Failed()) continue;
01365
01366
01367 T *st = T::GetByTile(tile);
01368 if (st == NULL) continue;
01369
01370 if (_current_company != OWNER_WATER) {
01371 CommandCost ret = CheckOwnership(st->owner);
01372 if (ret.Failed()) continue;
01373 }
01374
01375
01376 quantity++;
01377
01378 if (keep_rail || IsStationTileBlocked(tile)) {
01379
01380
01381 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01382 }
01383
01384 if (flags & DC_EXEC) {
01385
01386 uint specindex = GetCustomStationSpecIndex(tile);
01387 Track track = GetRailStationTrack(tile);
01388 Owner owner = GetTileOwner(tile);
01389 RailType rt = GetRailType(tile);
01390 Train *v = NULL;
01391
01392 if (HasStationReservation(tile)) {
01393 v = GetTrainForReservation(tile, track);
01394 if (v != NULL) {
01395
01396 FreeTrainTrackReservation(v);
01397 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01398 Vehicle *temp = v;
01399 for (; temp->Next() != NULL; temp = temp->Next()) { }
01400 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01401 }
01402 }
01403
01404 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01405
01406 DoClearSquare(tile);
01407 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01408 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01409
01410 st->rect.AfterRemoveTile(st, tile);
01411 AddTrackToSignalBuffer(tile, track, owner);
01412 YapfNotifyTrackLayoutChange(tile, track);
01413
01414 DeallocateSpecFromStation(st, specindex);
01415
01416 affected_stations.Include(st);
01417
01418 if (v != NULL) {
01419
01420 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01421 TryPathReserve(v, true, true);
01422 for (; v->Next() != NULL; v = v->Next()) { }
01423 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01424 }
01425 }
01426 }
01427
01428 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01429
01430 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01431 T *st = *stp;
01432
01433
01434
01435
01436 MakeRailStationAreaSmaller(st);
01437 UpdateStationSignCoord(st);
01438
01439
01440 if (st->train_station.tile == INVALID_TILE) {
01441 st->facilities &= ~FACIL_TRAIN;
01442 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01443 st->UpdateVirtCoord();
01444 DeleteStationIfEmpty(st);
01445 }
01446 }
01447
01448 total_cost.AddCost(quantity * removal_cost);
01449 return total_cost;
01450 }
01451
01463 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01464 {
01465 TileIndex end = p1 == 0 ? start : p1;
01466 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01467
01468 TileArea ta(start, end);
01469 SmallVector<Station *, 4> affected_stations;
01470
01471 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01472 if (ret.Failed()) return ret;
01473
01474
01475 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01476 Station *st = *stp;
01477
01478 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01479 st->MarkTilesDirty(false);
01480 st->RecomputeIndustriesNear();
01481 }
01482
01483
01484 return ret;
01485 }
01486
01498 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01499 {
01500 TileIndex end = p1 == 0 ? start : p1;
01501 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01502
01503 TileArea ta(start, end);
01504 SmallVector<Waypoint *, 4> affected_stations;
01505
01506 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01507 }
01508
01509
01517 template <class T>
01518 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01519 {
01520
01521 if (_current_company != OWNER_WATER) {
01522 CommandCost ret = CheckOwnership(st->owner);
01523 if (ret.Failed()) return ret;
01524 }
01525
01526
01527 TileArea ta = st->train_station;
01528
01529 assert(ta.w != 0 && ta.h != 0);
01530
01531 CommandCost cost(EXPENSES_CONSTRUCTION);
01532
01533 TILE_AREA_LOOP(tile, ta) {
01534
01535 if (!st->TileBelongsToRailStation(tile)) continue;
01536
01537 CommandCost ret = EnsureNoVehicleOnGround(tile);
01538 if (ret.Failed()) return ret;
01539
01540 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01541 if (flags & DC_EXEC) {
01542
01543 Track track = GetRailStationTrack(tile);
01544 Owner owner = GetTileOwner(tile);
01545 Train *v = NULL;
01546 if (HasStationReservation(tile)) {
01547 v = GetTrainForReservation(tile, track);
01548 if (v != NULL) FreeTrainTrackReservation(v);
01549 }
01550 DoClearSquare(tile);
01551 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01552 AddTrackToSignalBuffer(tile, track, owner);
01553 YapfNotifyTrackLayoutChange(tile, track);
01554 if (v != NULL) TryPathReserve(v, true);
01555 }
01556 }
01557
01558 if (flags & DC_EXEC) {
01559 st->rect.AfterRemoveRect(st, st->train_station);
01560
01561 st->train_station.Clear();
01562
01563 st->facilities &= ~FACIL_TRAIN;
01564
01565 free(st->speclist);
01566 st->num_specs = 0;
01567 st->speclist = NULL;
01568 st->cached_anim_triggers = 0;
01569
01570 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01571 st->UpdateVirtCoord();
01572 DeleteStationIfEmpty(st);
01573 }
01574
01575 return cost;
01576 }
01577
01584 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01585 {
01586
01587 if (_current_company == OWNER_WATER) {
01588 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01589 }
01590
01591 Station *st = Station::GetByTile(tile);
01592 CommandCost cost = RemoveRailStation(st, flags);
01593
01594 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01595
01596 return cost;
01597 }
01598
01605 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01606 {
01607
01608 if (_current_company == OWNER_WATER) {
01609 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01610 }
01611
01612 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01613 }
01614
01615
01621 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01622 {
01623 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01624
01625 if (*primary_stop == NULL) {
01626
01627 return primary_stop;
01628 } else {
01629
01630 RoadStop *stop = *primary_stop;
01631 while (stop->next != NULL) stop = stop->next;
01632 return &stop->next;
01633 }
01634 }
01635
01636 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01637
01647 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01648 {
01649 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01650 }
01651
01667 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01668 {
01669 bool type = HasBit(p2, 0);
01670 bool is_drive_through = HasBit(p2, 1);
01671 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01672 StationID station_to_join = GB(p2, 16, 16);
01673 bool reuse = (station_to_join != NEW_STATION);
01674 if (!reuse) station_to_join = INVALID_STATION;
01675 bool distant_join = (station_to_join != INVALID_STATION);
01676
01677 uint8 width = (uint8)GB(p1, 0, 8);
01678 uint8 lenght = (uint8)GB(p1, 8, 8);
01679
01680
01681 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01682
01683 if (width == 0 || lenght == 0) return CMD_ERROR;
01684
01685 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01686
01687 TileArea roadstop_area(tile, width, lenght);
01688
01689 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01690
01691 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01692
01693
01694 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01695
01696 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01697
01698
01699 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01700
01701 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01702
01703 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01704 if (ret.Failed()) return ret;
01705
01706
01707 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01708 StationID est = INVALID_STATION;
01709 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01710 if (ret.Failed()) return ret;
01711 cost.AddCost(ret);
01712
01713 Station *st = NULL;
01714 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01715 if (ret.Failed()) return ret;
01716
01717
01718 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01719
01720
01721 if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
01722
01723 if (st != NULL) {
01724 if (st->owner != _current_company) {
01725 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01726 }
01727
01728 CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01729 if (ret.Failed()) return ret;
01730 } else {
01731
01732 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01733
01734 if (flags & DC_EXEC) {
01735 st = new Station(tile);
01736
01737 st->town = ClosestTownFromTile(tile, UINT_MAX);
01738 st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01739
01740 if (Company::IsValidID(_current_company)) {
01741 SetBit(st->town->have_ratings, _current_company);
01742 }
01743 }
01744 }
01745
01746 if (flags & DC_EXEC) {
01747
01748 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01749 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01750
01751 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01752 RemoveRoadStop(cur_tile, flags);
01753 }
01754
01755 RoadStop *road_stop = new RoadStop(cur_tile);
01756
01757 RoadStop **currstop = FindRoadStopSpot(type, st);
01758 *currstop = road_stop;
01759
01760 if (type) {
01761 st->truck_station.Add(cur_tile);
01762 } else {
01763 st->bus_station.Add(cur_tile);
01764 }
01765
01766
01767 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01768
01769 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01770
01771 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01772 if (is_drive_through) {
01773 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01774 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01775 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01776 road_stop->MakeDriveThrough();
01777 } else {
01778 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01779 }
01780
01781 MarkTileDirtyByTile(cur_tile);
01782 }
01783 }
01784
01785 if (st != NULL) {
01786 st->UpdateVirtCoord();
01787 UpdateStationAcceptance(st, false);
01788 st->RecomputeIndustriesNear();
01789 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01790 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01791 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01792 }
01793 return cost;
01794 }
01795
01796
01797 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01798 {
01799 if (v->type == VEH_ROAD) {
01800
01801
01802
01803
01804
01805
01806 RoadVehicle *rv = RoadVehicle::From(v);
01807 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01808 }
01809
01810 return NULL;
01811 }
01812
01813
01820 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01821 {
01822 Station *st = Station::GetByTile(tile);
01823
01824 if (_current_company != OWNER_WATER) {
01825 CommandCost ret = CheckOwnership(st->owner);
01826 if (ret.Failed()) return ret;
01827 }
01828
01829 bool is_truck = IsTruckStop(tile);
01830
01831 RoadStop **primary_stop;
01832 RoadStop *cur_stop;
01833 if (is_truck) {
01834 primary_stop = &st->truck_stops;
01835 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01836 } else {
01837 primary_stop = &st->bus_stops;
01838 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01839 }
01840
01841 assert(cur_stop != NULL);
01842
01843
01844 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01845
01846 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01847 } else {
01848 CommandCost ret = EnsureNoVehicleOnGround(tile);
01849 if (ret.Failed()) return ret;
01850 }
01851
01852 if (flags & DC_EXEC) {
01853 if (*primary_stop == cur_stop) {
01854
01855 *primary_stop = cur_stop->next;
01856
01857 if (*primary_stop == NULL) {
01858 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01859 }
01860 } else {
01861
01862 RoadStop *pred = *primary_stop;
01863 while (pred->next != cur_stop) pred = pred->next;
01864 pred->next = cur_stop->next;
01865 }
01866
01867 if (IsDriveThroughStopTile(tile)) {
01868
01869 cur_stop->ClearDriveThrough();
01870 } else {
01871 DoClearSquare(tile);
01872 }
01873
01874 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01875 delete cur_stop;
01876
01877
01878 RoadVehicle *v;
01879 FOR_ALL_ROADVEHICLES(v) {
01880 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01881 v->dest_tile == tile) {
01882 v->dest_tile = v->GetOrderStationLocation(st->index);
01883 }
01884 }
01885
01886 st->rect.AfterRemoveTile(st, tile);
01887
01888 st->UpdateVirtCoord();
01889 st->RecomputeIndustriesNear();
01890 DeleteStationIfEmpty(st);
01891
01892
01893 if (is_truck) {
01894 st->truck_station.Clear();
01895 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01896 } else {
01897 st->bus_station.Clear();
01898 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01899 }
01900 }
01901
01902 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01903 }
01904
01915 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01916 {
01917 uint8 width = (uint8)GB(p1, 0, 8);
01918 uint8 height = (uint8)GB(p1, 8, 8);
01919
01920
01921 if (width == 0 || height == 0) return CMD_ERROR;
01922
01923 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01924
01925 TileArea roadstop_area(tile, width, height);
01926
01927 int quantity = 0;
01928 CommandCost cost(EXPENSES_CONSTRUCTION);
01929 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01930
01931 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01932
01933
01934 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01935 RoadTypes rts = GetRoadTypes(cur_tile);
01936 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01937 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01938 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01939
01940 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01941 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01942 CommandCost ret = RemoveRoadStop(cur_tile, flags);
01943 if (ret.Failed()) return ret;
01944 cost.AddCost(ret);
01945
01946 quantity++;
01947
01948 if ((flags & DC_EXEC) && is_drive_through) {
01949 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
01950 road_owner, tram_owner);
01951 }
01952 }
01953
01954 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01955
01956 return cost;
01957 }
01958
01966 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
01967 {
01968 uint ttx = TileX(town_tile);
01969 uint tty = TileY(town_tile);
01970
01971 uint atx = TileX(airport_tile);
01972 uint aty = TileY(airport_tile);
01973
01974 uint btx = TileX(airport_tile) + as->size_x - 1;
01975 uint bty = TileY(airport_tile) + as->size_y - 1;
01976
01977
01978
01979
01980 uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
01981 uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
01982
01983 return dx + dy;
01984 }
01985
01995 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
01996 {
01997
01998
01999 if (as->noise_level < 2) return as->noise_level;
02000
02001 uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
02002
02003
02004
02005
02006
02007 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02008
02009
02010
02011 uint noise_reduction = distance / town_tolerance_distance;
02012
02013
02014
02015 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02016 }
02017
02025 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
02026 {
02027 Town *t, *nearest = NULL;
02028 uint add = as->size_x + as->size_y - 2;
02029 uint mindist = UINT_MAX - add;
02030 FOR_ALL_TOWNS(t) {
02031 if (DistanceManhattan(t->xy, airport_tile) < mindist + add) {
02032 uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
02033 if (dist < mindist) {
02034 nearest = t;
02035 mindist = dist;
02036 }
02037 }
02038 }
02039
02040 return nearest;
02041 }
02042
02043
02045 void UpdateAirportsNoise()
02046 {
02047 Town *t;
02048 const Station *st;
02049
02050 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02051
02052 FOR_ALL_STATIONS(st) {
02053 if (st->airport.tile != INVALID_TILE) {
02054 const AirportSpec *as = st->airport.GetSpec();
02055 Town *nearest = AirportGetNearestTown(as, st->airport.tile);
02056 nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport.tile);
02057 }
02058 }
02059 }
02060
02074 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02075 {
02076 StationID station_to_join = GB(p2, 16, 16);
02077 bool reuse = (station_to_join != NEW_STATION);
02078 if (!reuse) station_to_join = INVALID_STATION;
02079 bool distant_join = (station_to_join != INVALID_STATION);
02080 byte airport_type = GB(p1, 0, 8);
02081 byte layout = GB(p1, 8, 8);
02082
02083 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02084
02085 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02086
02087 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02088 if (ret.Failed()) return ret;
02089
02090
02091 const AirportSpec *as = AirportSpec::Get(airport_type);
02092 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02093
02094 Direction rotation = as->rotation[layout];
02095 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02096 int w = as->size_x;
02097 int h = as->size_y;
02098 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02099
02100 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02101 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02102 }
02103
02104 CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02105 if (cost.Failed()) return cost;
02106
02107
02108 Town *nearest = AirportGetNearestTown(as, tile);
02109 uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02110
02111
02112 StringID authority_refuse_message = STR_NULL;
02113
02114 if (_settings_game.economy.station_noise_level) {
02115
02116 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02117 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02118 }
02119 } else {
02120 uint num = 0;
02121 const Station *st;
02122 FOR_ALL_STATIONS(st) {
02123 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02124 }
02125 if (num >= 2) {
02126 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02127 }
02128 }
02129
02130 if (authority_refuse_message != STR_NULL) {
02131 SetDParam(0, t->index);
02132 return_cmd_error(authority_refuse_message);
02133 }
02134
02135 Station *st = NULL;
02136 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02137 if (ret.Failed()) return ret;
02138
02139
02140 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02141
02142
02143 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02144
02145 if (st != NULL) {
02146 if (st->owner != _current_company) {
02147 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02148 }
02149
02150 CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02151 if (ret.Failed()) return ret;
02152
02153 if (st->airport.tile != INVALID_TILE) {
02154 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02155 }
02156 } else {
02157
02158 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02159
02160 if (flags & DC_EXEC) {
02161 st = new Station(tile);
02162
02163 st->town = t;
02164 st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02165
02166 if (Company::IsValidID(_current_company)) {
02167 SetBit(st->town->have_ratings, _current_company);
02168 }
02169 }
02170 }
02171
02172 const AirportTileTable *it = as->table[layout];
02173 do {
02174 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02175 } while ((++it)->ti.x != -0x80);
02176
02177 if (flags & DC_EXEC) {
02178
02179 nearest->noise_reached += newnoise_level;
02180
02181 st->AddFacility(FACIL_AIRPORT, tile);
02182 st->airport.type = airport_type;
02183 st->airport.layout = layout;
02184 st->airport.flags = 0;
02185 st->airport.rotation = rotation;
02186
02187 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02188
02189 it = as->table[layout];
02190 do {
02191 TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02192 MakeAirport(cur_tile, st->owner, st->index, it->gfx, WATER_CLASS_INVALID);
02193 SetStationTileRandomBits(cur_tile, GB(Random(), 0, 4));
02194 st->airport.Add(cur_tile);
02195
02196 if (AirportTileSpec::Get(GetTranslatedAirportTileID(it->gfx))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
02197 } while ((++it)->ti.x != -0x80);
02198
02199
02200 it = as->table[layout];
02201 do {
02202 TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02203 AirportTileAnimationTrigger(st, cur_tile, AAT_BUILT);
02204 } while ((++it)->ti.x != -0x80);
02205
02206 UpdateAirplanesOnNewStation(st);
02207
02208 st->UpdateVirtCoord();
02209 UpdateStationAcceptance(st, false);
02210 st->RecomputeIndustriesNear();
02211 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02212 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02213 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02214
02215 if (_settings_game.economy.station_noise_level) {
02216 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02217 }
02218 }
02219
02220 return cost;
02221 }
02222
02229 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02230 {
02231 Station *st = Station::GetByTile(tile);
02232
02233 if (_current_company != OWNER_WATER) {
02234 CommandCost ret = CheckOwnership(st->owner);
02235 if (ret.Failed()) return ret;
02236 }
02237
02238 tile = st->airport.tile;
02239
02240 CommandCost cost(EXPENSES_CONSTRUCTION);
02241
02242 const Aircraft *a;
02243 FOR_ALL_AIRCRAFT(a) {
02244 if (!a->IsNormalAircraft()) continue;
02245 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02246 }
02247
02248 TILE_AREA_LOOP(tile_cur, st->airport) {
02249 if (!st->TileBelongsToAirport(tile_cur)) continue;
02250
02251 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02252 if (ret.Failed()) return ret;
02253
02254 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02255
02256 if (flags & DC_EXEC) {
02257 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02258 DeleteAnimatedTile(tile_cur);
02259 DoClearSquare(tile_cur);
02260 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02261 }
02262 }
02263
02264 if (flags & DC_EXEC) {
02265 const AirportSpec *as = st->airport.GetSpec();
02266 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02267 DeleteWindowById(
02268 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02269 );
02270 }
02271
02272
02273
02274
02275 Town *nearest = AirportGetNearestTown(as, tile);
02276 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02277
02278 st->rect.AfterRemoveRect(st, st->airport);
02279
02280 st->airport.Clear();
02281 st->facilities &= ~FACIL_AIRPORT;
02282
02283 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02284
02285 if (_settings_game.economy.station_noise_level) {
02286 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02287 }
02288
02289 st->UpdateVirtCoord();
02290 st->RecomputeIndustriesNear();
02291 DeleteStationIfEmpty(st);
02292 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02293 }
02294
02295 return cost;
02296 }
02297
02304 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02305 {
02306 const Vehicle *v;
02307 FOR_ALL_VEHICLES(v) {
02308 if ((v->owner == company) == include_company) {
02309 const Order *order;
02310 FOR_VEHICLE_ORDERS(v, order) {
02311 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02312 return true;
02313 }
02314 }
02315 }
02316 }
02317 return false;
02318 }
02319
02320 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02321 {-1, 0},
02322 { 0, 0},
02323 { 0, 0},
02324 { 0, -1}
02325 };
02326 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02327 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02328
02338 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02339 {
02340 StationID station_to_join = GB(p2, 16, 16);
02341 bool reuse = (station_to_join != NEW_STATION);
02342 if (!reuse) station_to_join = INVALID_STATION;
02343 bool distant_join = (station_to_join != INVALID_STATION);
02344
02345 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02346
02347 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
02348 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02349 direction = ReverseDiagDir(direction);
02350
02351
02352 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02353
02354 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02355 if (ret.Failed()) return ret;
02356
02357 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02358
02359 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02360 if (ret.Failed()) return ret;
02361
02362 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02363
02364 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02365 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02366 }
02367
02368 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02369
02370
02371 WaterClass wc = GetWaterClass(tile_cur);
02372
02373 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02374 if (ret.Failed()) return ret;
02375
02376 tile_cur += TileOffsByDiagDir(direction);
02377 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02378 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02379 }
02380
02381
02382 Station *st = NULL;
02383 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02384 TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02385 _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02386 if (ret.Failed()) return ret;
02387
02388
02389 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02390
02391
02392 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02393
02394 if (st != NULL) {
02395 if (st->owner != _current_company) {
02396 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02397 }
02398
02399 CommandCost ret = st->rect.BeforeAddRect(
02400 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02401 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02402 if (ret.Failed()) return ret;
02403
02404 if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02405 } else {
02406
02407 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02408
02409 if (flags & DC_EXEC) {
02410 st = new Station(tile);
02411
02412 st->town = ClosestTownFromTile(tile, UINT_MAX);
02413 st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02414
02415 if (Company::IsValidID(_current_company)) {
02416 SetBit(st->town->have_ratings, _current_company);
02417 }
02418 }
02419 }
02420
02421 if (flags & DC_EXEC) {
02422 st->dock_tile = tile;
02423 st->AddFacility(FACIL_DOCK, tile);
02424
02425 st->rect.BeforeAddRect(
02426 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02427 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02428
02429 MakeDock(tile, st->owner, st->index, direction, wc);
02430
02431 st->UpdateVirtCoord();
02432 UpdateStationAcceptance(st, false);
02433 st->RecomputeIndustriesNear();
02434 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02435 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02436 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02437 }
02438
02439 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02440 }
02441
02448 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02449 {
02450 Station *st = Station::GetByTile(tile);
02451 CommandCost ret = CheckOwnership(st->owner);
02452 if (ret.Failed()) return ret;
02453
02454 TileIndex tile1 = st->dock_tile;
02455 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02456
02457 ret = EnsureNoVehicleOnGround(tile1);
02458 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02459 if (ret.Failed()) return ret;
02460
02461 if (flags & DC_EXEC) {
02462 DoClearSquare(tile1);
02463 MarkTileDirtyByTile(tile1);
02464 MakeWaterKeepingClass(tile2, st->owner);
02465
02466 st->rect.AfterRemoveTile(st, tile1);
02467 st->rect.AfterRemoveTile(st, tile2);
02468
02469 st->dock_tile = INVALID_TILE;
02470 st->facilities &= ~FACIL_DOCK;
02471
02472 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02473 st->UpdateVirtCoord();
02474 st->RecomputeIndustriesNear();
02475 DeleteStationIfEmpty(st);
02476 }
02477
02478 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02479 }
02480
02481 #include "table/station_land.h"
02482
02483 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02484 {
02485 return &_station_display_datas[st][gfx];
02486 }
02487
02488 static void DrawTile_Station(TileInfo *ti)
02489 {
02490 const DrawTileSprites *t = NULL;
02491 RoadTypes roadtypes;
02492 int32 total_offset;
02493 int32 custom_ground_offset;
02494 const RailtypeInfo *rti = NULL;
02495 uint32 relocation = 0;
02496 const BaseStation *st = NULL;
02497 const StationSpec *statspec = NULL;
02498
02499 if (HasStationRail(ti->tile)) {
02500 rti = GetRailTypeInfo(GetRailType(ti->tile));
02501 roadtypes = ROADTYPES_NONE;
02502 total_offset = rti->total_offset;
02503 custom_ground_offset = rti->custom_ground_offset;
02504
02505 if (IsCustomStationSpecIndex(ti->tile)) {
02506
02507 st = BaseStation::GetByTile(ti->tile);
02508 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02509
02510 if (statspec != NULL) {
02511 uint tile = GetStationGfx(ti->tile);
02512
02513 relocation = GetCustomStationRelocation(statspec, st, ti->tile);
02514
02515 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02516 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02517 if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
02518 }
02519
02520
02521 if (statspec->renderdata != NULL) {
02522 t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
02523 }
02524 }
02525 }
02526 } else {
02527 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02528 total_offset = 0;
02529 custom_ground_offset = 0;
02530 }
02531
02532 if (IsAirport(ti->tile)) {
02533 StationGfx gfx = GetAirportGfx(ti->tile);
02534 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02535 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02536 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02537 return;
02538 }
02539
02540
02541 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02542 gfx = ats->grf_prop.subst_id;
02543 }
02544 switch (gfx) {
02545 case APT_RADAR_GRASS_FENCE_SW:
02546 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02547 break;
02548 case APT_GRASS_FENCE_NE_FLAG:
02549 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02550 break;
02551 case APT_RADAR_FENCE_SW:
02552 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02553 break;
02554 case APT_RADAR_FENCE_NE:
02555 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02556 break;
02557 case APT_GRASS_FENCE_NE_FLAG_2:
02558 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02559 break;
02560 }
02561 }
02562
02563 Owner owner = GetTileOwner(ti->tile);
02564
02565 PaletteID palette;
02566 if (Company::IsValidID(owner)) {
02567 palette = COMPANY_SPRITE_COLOUR(owner);
02568 } else {
02569
02570 palette = PALETTE_TO_GREY;
02571 }
02572
02573 if (t == NULL || t->seq == NULL) t = GetStationTileLayout(GetStationType(ti->tile), GetStationGfx(ti->tile));
02574
02575
02576 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02577 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02578
02579 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
02580
02581 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02582
02583
02584 static const uint8 foundation_parts[] = {
02585 0, 0, 0, 0,
02586 0, 1, 2, 3,
02587 0, 4, 5, 6,
02588 7, 8, 9
02589 };
02590
02591 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02592 } else {
02593
02594
02595
02596
02597 static const uint8 composite_foundation_parts[] = {
02598
02599 0x00, 0xD1, 0xE4, 0xE0,
02600
02601 0xCA, 0xC9, 0xC4, 0xC0,
02602
02603 0xD2, 0x91, 0xE4, 0xA0,
02604
02605 0x4A, 0x09, 0x44
02606 };
02607
02608 uint8 parts = composite_foundation_parts[ti->tileh];
02609
02610
02611
02612 uint z;
02613 Slope slope = GetFoundationSlope(ti->tile, &z);
02614 if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
02615 if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
02616
02617 if (parts == 0) {
02618
02619
02620
02621 goto draw_default_foundation;
02622 }
02623
02624 StartSpriteCombine();
02625 for (int i = 0; i < 8; i++) {
02626 if (HasBit(parts, i)) {
02627 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02628 }
02629 }
02630 EndSpriteCombine();
02631 }
02632
02633 OffsetGroundSprite(31, 1);
02634 ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02635 } else {
02636 draw_default_foundation:
02637 DrawFoundation(ti, FOUNDATION_LEVELED);
02638 }
02639 }
02640
02641 if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02642 if (ti->tileh == SLOPE_FLAT) {
02643 DrawWaterClassGround(ti);
02644 } else {
02645 assert(IsDock(ti->tile));
02646 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02647 WaterClass wc = GetWaterClass(water_tile);
02648 if (wc == WATER_CLASS_SEA) {
02649 DrawShoreTile(ti->tileh);
02650 } else {
02651 DrawClearLandTile(ti, 3);
02652 }
02653 }
02654 } else {
02655 SpriteID image = t->ground.sprite;
02656 PaletteID pal = t->ground.pal;
02657 if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02658 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02659 DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02660 DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02661
02662 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02663 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02664 DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02665 }
02666 } else {
02667 if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
02668 image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
02669 image += custom_ground_offset;
02670 } else {
02671 image += total_offset;
02672 }
02673 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02674
02675
02676 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02677 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02678 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02679 }
02680 }
02681 }
02682
02683 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02684
02685 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02686 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02687 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02688 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02689 }
02690
02691 if (IsRailWaypoint(ti->tile)) {
02692
02693 total_offset = 0;
02694 }
02695
02696 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02697 }
02698
02699 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02700 {
02701 int32 total_offset = 0;
02702 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02703 const DrawTileSprites *t = GetStationTileLayout(st, image);
02704 const RailtypeInfo *rti = NULL;
02705
02706 if (railtype != INVALID_RAILTYPE) {
02707 rti = GetRailTypeInfo(railtype);
02708 total_offset = rti->total_offset;
02709 }
02710
02711 SpriteID img = t->ground.sprite;
02712 if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02713 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02714 DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02715 DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02716 } else {
02717 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02718 }
02719
02720 if (roadtype == ROADTYPE_TRAM) {
02721 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02722 }
02723
02724
02725 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02726 }
02727
02728 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
02729 {
02730 return GetTileMaxZ(tile);
02731 }
02732
02733 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02734 {
02735 return FlatteningFoundation(tileh);
02736 }
02737
02738 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02739 {
02740 td->owner[0] = GetTileOwner(tile);
02741 if (IsDriveThroughStopTile(tile)) {
02742 Owner road_owner = INVALID_OWNER;
02743 Owner tram_owner = INVALID_OWNER;
02744 RoadTypes rts = GetRoadTypes(tile);
02745 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02746 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02747
02748
02749 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02750 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02751 uint i = 1;
02752 if (road_owner != INVALID_OWNER) {
02753 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02754 td->owner[i] = road_owner;
02755 i++;
02756 }
02757 if (tram_owner != INVALID_OWNER) {
02758 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02759 td->owner[i] = tram_owner;
02760 }
02761 }
02762 }
02763 td->build_date = BaseStation::GetByTile(tile)->build_date;
02764
02765 if (HasStationTileRail(tile)) {
02766 const StationSpec *spec = GetStationSpec(tile);
02767
02768 if (spec != NULL) {
02769 td->station_class = StationClass::GetName(spec->cls_id);
02770 td->station_name = spec->name;
02771
02772 if (spec->grf_prop.grffile != NULL) {
02773 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02774 td->grf = gc->GetName();
02775 }
02776 }
02777
02778 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02779 td->rail_speed = rti->max_speed;
02780 }
02781
02782 if (IsAirport(tile)) {
02783 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02784 td->airport_class = AirportClass::GetName(as->cls_id);
02785 td->airport_name = as->name;
02786
02787 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02788 td->airport_tile_name = ats->name;
02789
02790 if (as->grf_prop.grffile != NULL) {
02791 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02792 td->grf = gc->GetName();
02793 } else if (ats->grf_prop.grffile != NULL) {
02794 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02795 td->grf = gc->GetName();
02796 }
02797 }
02798
02799 StringID str;
02800 switch (GetStationType(tile)) {
02801 default: NOT_REACHED();
02802 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02803 case STATION_AIRPORT:
02804 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02805 break;
02806 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02807 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02808 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
02809 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02810 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02811 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02812 }
02813 td->str = str;
02814 }
02815
02816
02817 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02818 {
02819 TrackBits trackbits = TRACK_BIT_NONE;
02820
02821 switch (mode) {
02822 case TRANSPORT_RAIL:
02823 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02824 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02825 }
02826 break;
02827
02828 case TRANSPORT_WATER:
02829
02830 if (IsBuoy(tile)) {
02831 trackbits = TRACK_BIT_ALL;
02832
02833 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02834
02835 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02836 }
02837 break;
02838
02839 case TRANSPORT_ROAD:
02840 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02841 DiagDirection dir = GetRoadStopDir(tile);
02842 Axis axis = DiagDirToAxis(dir);
02843
02844 if (side != INVALID_DIAGDIR) {
02845 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02846 }
02847
02848 trackbits = AxisToTrackBits(axis);
02849 }
02850 break;
02851
02852 default:
02853 break;
02854 }
02855
02856 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02857 }
02858
02859
02860 static void TileLoop_Station(TileIndex tile)
02861 {
02862
02863
02864 switch (GetStationType(tile)) {
02865 case STATION_AIRPORT:
02866 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02867 break;
02868
02869 case STATION_DOCK:
02870 if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break;
02871
02872 case STATION_OILRIG:
02873 case STATION_BUOY:
02874 TileLoop_Water(tile);
02875 break;
02876
02877 default: break;
02878 }
02879 }
02880
02881
02882 static void AnimateTile_Station(TileIndex tile)
02883 {
02884 if (HasStationRail(tile)) {
02885 AnimateStationTile(tile);
02886 return;
02887 }
02888
02889 if (IsAirport(tile)) {
02890 AnimateAirportTile(tile);
02891 }
02892 }
02893
02894
02895 static bool ClickTile_Station(TileIndex tile)
02896 {
02897 const BaseStation *bst = BaseStation::GetByTile(tile);
02898
02899 if (bst->facilities & FACIL_WAYPOINT) {
02900 ShowWaypointWindow(Waypoint::From(bst));
02901 } else if (IsHangar(tile)) {
02902 const Station *st = Station::From(bst);
02903 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
02904 } else {
02905 ShowStationViewWindow(bst->index);
02906 }
02907 return true;
02908 }
02909
02910 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
02911 {
02912 if (v->type == VEH_TRAIN) {
02913 StationID station_id = GetStationIndex(tile);
02914 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
02915 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
02916
02917 int station_ahead;
02918 int station_length;
02919 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
02920
02921
02922
02923
02924
02925 if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
02926
02927 DiagDirection dir = DirToDiagDir(v->direction);
02928
02929 x &= 0xF;
02930 y &= 0xF;
02931
02932 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
02933 if (y == TILE_SIZE / 2) {
02934 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
02935 stop &= TILE_SIZE - 1;
02936
02937 if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
02938 if (x < stop) {
02939 uint16 spd;
02940
02941 v->vehstatus |= VS_TRAIN_SLOWING;
02942 spd = max(0, (stop - x) * 20 - 15);
02943 if (spd < v->cur_speed) v->cur_speed = spd;
02944 }
02945 }
02946 } else if (v->type == VEH_ROAD) {
02947 RoadVehicle *rv = RoadVehicle::From(v);
02948 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
02949 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
02950
02951 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
02952 }
02953 }
02954 }
02955
02956 return VETSB_CONTINUE;
02957 }
02958
02965 static bool StationHandleBigTick(BaseStation *st)
02966 {
02967 if (!st->IsInUse() && ++st->delete_ctr >= 8) {
02968 delete st;
02969 return false;
02970 }
02971
02972 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
02973
02974 return true;
02975 }
02976
02977 static inline void byte_inc_sat(byte *p)
02978 {
02979 byte b = *p + 1;
02980 if (b != 0) *p = b;
02981 }
02982
02983 static void UpdateStationRating(Station *st)
02984 {
02985 bool waiting_changed = false;
02986
02987 byte_inc_sat(&st->time_since_load);
02988 byte_inc_sat(&st->time_since_unload);
02989
02990 const CargoSpec *cs;
02991 FOR_ALL_CARGOSPECS(cs) {
02992 GoodsEntry *ge = &st->goods[cs->Index()];
02993
02994
02995
02996 if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
02997 ge->rating++;
02998 }
02999
03000
03001 if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
03002 byte_inc_sat(&ge->days_since_pickup);
03003
03004 bool skip = false;
03005 int rating = 0;
03006 uint waiting = ge->cargo.Count();
03007
03008 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03009
03010
03011
03012
03013 uint last_speed = ge->last_speed;
03014 if (last_speed == 0) last_speed = 0xFF;
03015
03016 uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03017
03018 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03019 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03020 if (callback != CALLBACK_FAILED) {
03021 skip = true;
03022 rating = GB(callback, 0, 14);
03023
03024
03025 if (HasBit(callback, 14)) rating -= 0x4000;
03026 }
03027 }
03028
03029 if (!skip) {
03030 int b = ge->last_speed - 85;
03031 if (b >= 0) rating += b >> 2;
03032
03033 byte days = ge->days_since_pickup;
03034 if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03035 (days > 21) ||
03036 (rating += 25, days > 12) ||
03037 (rating += 25, days > 6) ||
03038 (rating += 45, days > 3) ||
03039 (rating += 35, true);
03040
03041 (rating -= 90, waiting > 1500) ||
03042 (rating += 55, waiting > 1000) ||
03043 (rating += 35, waiting > 600) ||
03044 (rating += 10, waiting > 300) ||
03045 (rating += 20, waiting > 100) ||
03046 (rating += 10, true);
03047 }
03048
03049 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03050
03051 byte age = ge->last_age;
03052 (age >= 3) ||
03053 (rating += 10, age >= 2) ||
03054 (rating += 10, age >= 1) ||
03055 (rating += 13, true);
03056
03057 {
03058 int or_ = ge->rating;
03059
03060
03061 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03062
03063
03064
03065 if (rating <= 64 && waiting >= 200) {
03066 int dec = Random() & 0x1F;
03067 if (waiting < 400) dec &= 7;
03068 waiting -= dec + 1;
03069 waiting_changed = true;
03070 }
03071
03072
03073 if (rating <= 127 && waiting != 0) {
03074 uint32 r = Random();
03075 if (rating <= (int)GB(r, 0, 7)) {
03076
03077 waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
03078 waiting_changed = true;
03079 }
03080 }
03081
03082
03083
03084
03085 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03086 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03087 static const uint MAX_WAITING_CARGO = 1 << 15;
03088
03089 if (waiting > WAITING_CARGO_THRESHOLD) {
03090 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03091 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03092
03093 waiting = min(waiting, MAX_WAITING_CARGO);
03094 waiting_changed = true;
03095 }
03096
03097 if (waiting_changed) ge->cargo.Truncate(waiting);
03098 }
03099 }
03100 }
03101
03102 StationID index = st->index;
03103 if (waiting_changed) {
03104 SetWindowDirty(WC_STATION_VIEW, index);
03105 } else {
03106 SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST);
03107 }
03108 }
03109
03110
03111 static void StationHandleSmallTick(BaseStation *st)
03112 {
03113 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03114
03115 byte b = st->delete_ctr + 1;
03116 if (b >= 185) b = 0;
03117 st->delete_ctr = b;
03118
03119 if (b == 0) UpdateStationRating(Station::From(st));
03120 }
03121
03122 void OnTick_Station()
03123 {
03124 if (_game_mode == GM_EDITOR) return;
03125
03126 BaseStation *st;
03127 FOR_ALL_BASE_STATIONS(st) {
03128 StationHandleSmallTick(st);
03129
03130
03131
03132
03133 if ((_tick_counter + st->index) % 250 == 0) {
03134
03135 if (!StationHandleBigTick(st)) continue;
03136 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03137 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03138 }
03139 }
03140 }
03141
03142 void StationMonthlyLoop()
03143 {
03144
03145 }
03146
03147
03148 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03149 {
03150 Station *st;
03151
03152 FOR_ALL_STATIONS(st) {
03153 if (st->owner == owner &&
03154 DistanceManhattan(tile, st->xy) <= radius) {
03155 for (CargoID i = 0; i < NUM_CARGO; i++) {
03156 GoodsEntry *ge = &st->goods[i];
03157
03158 if (ge->acceptance_pickup != 0) {
03159 ge->rating = Clamp(ge->rating + amount, 0, 255);
03160 }
03161 }
03162 }
03163 }
03164 }
03165
03166 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03167 {
03168 GoodsEntry &ge = st->goods[type];
03169 amount += ge.amount_fract;
03170 ge.amount_fract = GB(amount, 0, 8);
03171
03172 amount >>= 8;
03173
03174 if (amount == 0) return 0;
03175
03176 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03177
03178 if (!HasBit(ge.acceptance_pickup, GoodsEntry::PICKUP)) {
03179 InvalidateWindowData(WC_STATION_LIST, st->index);
03180 SetBit(ge.acceptance_pickup, GoodsEntry::PICKUP);
03181 }
03182
03183 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03184 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03185
03186 SetWindowDirty(WC_STATION_VIEW, st->index);
03187 st->MarkTilesDirty(true);
03188 return amount;
03189 }
03190
03191 static bool IsUniqueStationName(const char *name)
03192 {
03193 const Station *st;
03194
03195 FOR_ALL_STATIONS(st) {
03196 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03197 }
03198
03199 return true;
03200 }
03201
03211 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03212 {
03213 Station *st = Station::GetIfValid(p1);
03214 if (st == NULL) return CMD_ERROR;
03215
03216 CommandCost ret = CheckOwnership(st->owner);
03217 if (ret.Failed()) return ret;
03218
03219 bool reset = StrEmpty(text);
03220
03221 if (!reset) {
03222 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03223 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03224 }
03225
03226 if (flags & DC_EXEC) {
03227 free(st->name);
03228 st->name = reset ? NULL : strdup(text);
03229
03230 st->UpdateVirtCoord();
03231 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03232 }
03233
03234 return CommandCost();
03235 }
03236
03243 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03244 {
03245
03246 int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03247
03248 for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
03249 for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
03250 TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
03251 if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
03252
03253 Station *st = Station::GetByTile(cur_tile);
03254 if (st == NULL) continue;
03255
03256 if (_settings_game.station.modified_catchment) {
03257 int rad = st->GetCatchmentRadius();
03258 if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
03259 }
03260
03261
03262
03263
03264 stations->Include(st);
03265 }
03266 }
03267 }
03268
03273 const StationList *StationFinder::GetStations()
03274 {
03275 if (this->tile != INVALID_TILE) {
03276 FindStationsAroundTiles(*this, &this->stations);
03277 this->tile = INVALID_TILE;
03278 }
03279 return &this->stations;
03280 }
03281
03282 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03283 {
03284
03285 if (amount == 0) return 0;
03286
03287 Station *st1 = NULL;
03288 Station *st2 = NULL;
03289 uint best_rating1 = 0;
03290 uint best_rating2 = 0;
03291
03292 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03293 Station *st = *st_iter;
03294
03295
03296 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03297
03298 if (st->goods[type].rating == 0) continue;
03299
03300 if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue;
03301
03302 if (IsCargoInClass(type, CC_PASSENGERS)) {
03303 if (st->facilities == FACIL_TRUCK_STOP) continue;
03304 } else {
03305 if (st->facilities == FACIL_BUS_STOP) continue;
03306 }
03307
03308
03309 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03310 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03311 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03312 st2 = st; best_rating2 = st->goods[type].rating;
03313 }
03314 }
03315
03316
03317 if (st1 == NULL) return 0;
03318
03319
03320
03321 amount *= best_rating1 + 1;
03322
03323 if (st2 == NULL) {
03324
03325 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03326 }
03327
03328
03329 assert(st1 != NULL);
03330 assert(st2 != NULL);
03331 assert(best_rating1 != 0 || best_rating2 != 0);
03332
03333
03334
03335
03336
03337
03338 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03339 assert(worst_cargo <= (amount - worst_cargo));
03340
03341
03342 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03343
03344
03345 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03346 }
03347
03348 void BuildOilRig(TileIndex tile)
03349 {
03350 if (!Station::CanAllocateItem()) {
03351 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03352 return;
03353 }
03354
03355 Station *st = new Station(tile);
03356 st->town = ClosestTownFromTile(tile, UINT_MAX);
03357
03358 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03359
03360 assert(IsTileType(tile, MP_INDUSTRY));
03361 DeleteAnimatedTile(tile);
03362 MakeOilrig(tile, st->index, GetWaterClass(tile));
03363
03364 st->owner = OWNER_NONE;
03365 st->airport.type = AT_OILRIG;
03366 st->airport.Add(tile);
03367 st->dock_tile = tile;
03368 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03369 st->build_date = _date;
03370
03371 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03372
03373 for (CargoID j = 0; j < NUM_CARGO; j++) {
03374 st->goods[j].acceptance_pickup = 0;
03375 st->goods[j].days_since_pickup = 255;
03376 st->goods[j].rating = INITIAL_STATION_RATING;
03377 st->goods[j].last_speed = 0;
03378 st->goods[j].last_age = 255;
03379 }
03380
03381 st->UpdateVirtCoord();
03382 UpdateStationAcceptance(st, false);
03383 st->RecomputeIndustriesNear();
03384 }
03385
03386 void DeleteOilRig(TileIndex tile)
03387 {
03388 Station *st = Station::GetByTile(tile);
03389
03390 MakeWaterKeepingClass(tile, OWNER_NONE);
03391
03392 st->dock_tile = INVALID_TILE;
03393 st->airport.Clear();
03394 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03395 st->airport.flags = 0;
03396
03397 st->rect.AfterRemoveTile(st, tile);
03398
03399 st->UpdateVirtCoord();
03400 st->RecomputeIndustriesNear();
03401 if (!st->IsInUse()) delete st;
03402 }
03403
03404 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03405 {
03406 if (IsDriveThroughStopTile(tile)) {
03407 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03408
03409 if (GetRoadOwner(tile, rt) == old_owner) {
03410 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03411 }
03412 }
03413 }
03414
03415 if (!IsTileOwner(tile, old_owner)) return;
03416
03417 if (new_owner != INVALID_OWNER) {
03418
03419 SetTileOwner(tile, new_owner);
03420 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03421 } else {
03422 if (IsDriveThroughStopTile(tile)) {
03423
03424 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03425 assert(IsTileType(tile, MP_ROAD));
03426
03427 ChangeTileOwner(tile, old_owner, new_owner);
03428 } else {
03429 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03430
03431
03432
03433 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03434 }
03435 }
03436 }
03437
03446 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03447 {
03448
03449 if (_current_company == OWNER_WATER) return true;
03450
03451 Owner road_owner = _current_company;
03452 Owner tram_owner = _current_company;
03453
03454 RoadTypes rts = GetRoadTypes(tile);
03455 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03456 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03457
03458 if ((road_owner != OWNER_TOWN && CheckOwnership(road_owner).Failed()) || CheckOwnership(tram_owner).Failed()) return false;
03459
03460 return road_owner != OWNER_TOWN || CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Succeeded();
03461 }
03462
03463 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03464 {
03465 if (flags & DC_AUTO) {
03466 switch (GetStationType(tile)) {
03467 default: break;
03468 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03469 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03470 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03471 case STATION_TRUCK: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03472 case STATION_BUS: return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03473 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03474 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03475 case STATION_OILRIG:
03476 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03477 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03478 }
03479 }
03480
03481 switch (GetStationType(tile)) {
03482 case STATION_RAIL: return RemoveRailStation(tile, flags);
03483 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03484 case STATION_AIRPORT: return RemoveAirport(tile, flags);
03485 case STATION_TRUCK:
03486 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03487 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03488 }
03489 return RemoveRoadStop(tile, flags);
03490 case STATION_BUS:
03491 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03492 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03493 }
03494 return RemoveRoadStop(tile, flags);
03495 case STATION_BUOY: return RemoveBuoy(tile, flags);
03496 case STATION_DOCK: return RemoveDock(tile, flags);
03497 default: break;
03498 }
03499
03500 return CMD_ERROR;
03501 }
03502
03503 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03504 {
03505 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03506
03507
03508
03509 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03510 switch (GetStationType(tile)) {
03511 case STATION_WAYPOINT:
03512 case STATION_RAIL: {
03513 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03514 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03515 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03516 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03517 }
03518
03519 case STATION_AIRPORT:
03520 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03521
03522 case STATION_TRUCK:
03523 case STATION_BUS: {
03524 DiagDirection direction = GetRoadStopDir(tile);
03525 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03526 if (IsDriveThroughStopTile(tile)) {
03527 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03528 }
03529 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03530 }
03531
03532 default: break;
03533 }
03534 }
03535 }
03536 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03537 }
03538
03539
03540 extern const TileTypeProcs _tile_type_station_procs = {
03541 DrawTile_Station,
03542 GetSlopeZ_Station,
03543 ClearTile_Station,
03544 NULL,
03545 GetTileDesc_Station,
03546 GetTileTrackStatus_Station,
03547 ClickTile_Station,
03548 AnimateTile_Station,
03549 TileLoop_Station,
03550 ChangeTileOwner_Station,
03551 NULL,
03552 VehicleEnter_Station,
03553 GetFoundation_Station,
03554 TerraformTile_Station,
03555 };