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 "landscape.h"
00017 #include "viewport_func.h"
00018 #include "command_func.h"
00019 #include "town.h"
00020 #include "news_func.h"
00021 #include "train.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_station.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "road_internal.h"
00028 #include "variables.h"
00029 #include "autoslope.h"
00030 #include "water.h"
00031 #include "station_gui.h"
00032 #include "strings_func.h"
00033 #include "functions.h"
00034 #include "window_func.h"
00035 #include "date_func.h"
00036 #include "vehicle_func.h"
00037 #include "string_func.h"
00038 #include "animated_tile_func.h"
00039 #include "elrail_func.h"
00040 #include "station_base.h"
00041 #include "roadstop_base.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 "newgrf.h"
00049 #include "table/airporttile_ids.h"
00050
00051 #include "table/strings.h"
00052
00059 bool IsHangar(TileIndex t)
00060 {
00061 assert(IsTileType(t, MP_STATION));
00062
00063
00064 if (!IsAirport(t)) return false;
00065
00066 const Station *st = Station::GetByTile(t);
00067 const AirportSpec *as = st->GetAirportSpec();
00068
00069 for (uint i = 0; i < as->nof_depots; i++) {
00070 if (st->GetHangarTile(i) == t) return true;
00071 }
00072
00073 return false;
00074 }
00075
00083 template <class T>
00084 bool GetStationAround(TileArea ta, StationID closest_station, T **st)
00085 {
00086
00087 TILE_LOOP(tile_cur, ta.w + 2, ta.h + 2, ta.tile - TileDiffXY(1, 1)) {
00088 if (IsTileType(tile_cur, MP_STATION)) {
00089 StationID t = GetStationIndex(tile_cur);
00090
00091 if (closest_station == INVALID_STATION) {
00092 if (T::IsValidID(t)) closest_station = t;
00093 } else if (closest_station != t) {
00094 _error_message = STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING;
00095 return false;
00096 }
00097 }
00098 }
00099 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00100 return true;
00101 }
00102
00108 typedef bool (*CMSAMatcher)(TileIndex tile);
00109
00116 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00117 {
00118 int num = 0;
00119
00120 for (int dx = -3; dx <= 3; dx++) {
00121 for (int dy = -3; dy <= 3; dy++) {
00122 TileIndex t = TileAddWrap(tile, dx, dy);
00123 if (t != INVALID_TILE && cmp(t)) num++;
00124 }
00125 }
00126
00127 return num;
00128 }
00129
00135 static bool CMSAMine(TileIndex tile)
00136 {
00137
00138 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00139
00140 const Industry *ind = Industry::GetByTile(tile);
00141
00142
00143 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00144
00145 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00146
00147
00148 if (ind->produced_cargo[i] != CT_INVALID &&
00149 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00150 return true;
00151 }
00152 }
00153
00154 return false;
00155 }
00156
00162 static bool CMSAWater(TileIndex tile)
00163 {
00164 return IsTileType(tile, MP_WATER) && IsWater(tile);
00165 }
00166
00172 static bool CMSATree(TileIndex tile)
00173 {
00174 return IsTileType(tile, MP_TREES);
00175 }
00176
00182 static bool CMSAForest(TileIndex tile)
00183 {
00184
00185 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00186
00187 const Industry *ind = Industry::GetByTile(tile);
00188
00189
00190 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
00191
00192 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00193
00194 if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
00195 }
00196
00197 return false;
00198 }
00199
00200 #define M(x) ((x) - STR_SV_STNAME)
00201
00202 enum StationNaming {
00203 STATIONNAMING_RAIL,
00204 STATIONNAMING_ROAD,
00205 STATIONNAMING_AIRPORT,
00206 STATIONNAMING_OILRIG,
00207 STATIONNAMING_DOCK,
00208 STATIONNAMING_HELIPORT,
00209 };
00210
00212 struct StationNameInformation {
00213 uint32 free_names;
00214 bool *indtypes;
00215 };
00216
00225 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00226 {
00227
00228 StationNameInformation *sni = (StationNameInformation*)user_data;
00229 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00230
00231
00232 IndustryType indtype = GetIndustryType(tile);
00233 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00234
00235
00236
00237 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00238 return !sni->indtypes[indtype];
00239 }
00240
00241 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00242 {
00243 static const uint32 _gen_station_name_bits[] = {
00244 0,
00245 0,
00246 1U << M(STR_SV_STNAME_AIRPORT),
00247 1U << M(STR_SV_STNAME_OILFIELD),
00248 1U << M(STR_SV_STNAME_DOCKS),
00249 1U << M(STR_SV_STNAME_HELIPORT),
00250 };
00251
00252 const Town *t = st->town;
00253 uint32 free_names = UINT32_MAX;
00254
00255 bool indtypes[NUM_INDUSTRYTYPES];
00256 memset(indtypes, 0, sizeof(indtypes));
00257
00258 const Station *s;
00259 FOR_ALL_STATIONS(s) {
00260 if (s != st && s->town == t) {
00261 if (s->indtype != IT_INVALID) {
00262 indtypes[s->indtype] = true;
00263 continue;
00264 }
00265 uint str = M(s->string_id);
00266 if (str <= 0x20) {
00267 if (str == M(STR_SV_STNAME_FOREST)) {
00268 str = M(STR_SV_STNAME_WOODS);
00269 }
00270 ClrBit(free_names, str);
00271 }
00272 }
00273 }
00274
00275 TileIndex indtile = tile;
00276 StationNameInformation sni = { free_names, indtypes };
00277 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00278
00279 IndustryType indtype = GetIndustryType(indtile);
00280 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00281
00282 if (indsp->station_name != STR_NULL) {
00283 st->indtype = indtype;
00284 return STR_SV_STNAME_FALLBACK;
00285 }
00286 }
00287
00288
00289 free_names = sni.free_names;
00290
00291
00292 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00293 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00294
00295
00296 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00297 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00298 return STR_SV_STNAME_MINES;
00299 }
00300 }
00301
00302
00303 if (DistanceMax(tile, t->xy) < 8) {
00304 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00305
00306 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00307 }
00308
00309
00310 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00311 DistanceFromEdge(tile) < 20 &&
00312 CountMapSquareAround(tile, CMSAWater) >= 5) {
00313 return STR_SV_STNAME_LAKESIDE;
00314 }
00315
00316
00317 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00318 CountMapSquareAround(tile, CMSATree) >= 8 ||
00319 CountMapSquareAround(tile, CMSAForest) >= 2)
00320 ) {
00321 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00322 }
00323
00324
00325 uint z = GetTileZ(tile);
00326 uint z2 = GetTileZ(t->xy);
00327 if (z < z2) {
00328 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00329 } else if (z > z2) {
00330 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00331 }
00332
00333
00334 static const int8 _direction_and_table[] = {
00335 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00336 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00337 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00338 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00339 };
00340
00341 free_names &= _direction_and_table[
00342 (TileX(tile) < TileX(t->xy)) +
00343 (TileY(tile) < TileY(t->xy)) * 2];
00344
00345 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));
00346 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00347 }
00348 #undef M
00349
00355 static Station *GetClosestDeletedStation(TileIndex tile)
00356 {
00357 uint threshold = 8;
00358 Station *best_station = NULL;
00359 Station *st;
00360
00361 FOR_ALL_STATIONS(st) {
00362 if (!st->IsInUse() && st->owner == _current_company) {
00363 uint cur_dist = DistanceManhattan(tile, st->xy);
00364
00365 if (cur_dist < threshold) {
00366 threshold = cur_dist;
00367 best_station = st;
00368 }
00369 }
00370 }
00371
00372 return best_station;
00373 }
00374
00375
00376 void Station::GetTileArea(TileArea *ta, StationType type) const
00377 {
00378 switch (type) {
00379 case STATION_RAIL:
00380 *ta = this->train_station;
00381 return;
00382
00383 case STATION_AIRPORT:
00384 ta->tile = this->airport_tile;
00385 ta->w = this->GetAirportSpec()->size_x;
00386 ta->h = this->GetAirportSpec()->size_y;
00387 return;
00388
00389 case STATION_TRUCK:
00390 *ta = this->truck_station;
00391 return;
00392
00393 case STATION_BUS:
00394 *ta = this->bus_station;
00395 return;
00396
00397 case STATION_DOCK:
00398 case STATION_OILRIG:
00399 ta->tile = this->dock_tile;
00400 break;
00401
00402 default: NOT_REACHED();
00403 }
00404
00405 ta->w = 1;
00406 ta->h = 1;
00407 }
00408
00412 void Station::UpdateVirtCoord()
00413 {
00414 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00415
00416 pt.y -= 32;
00417 if ((this->facilities & FACIL_AIRPORT) && this->airport_type == AT_OILRIG) pt.y -= 16;
00418
00419 SetDParam(0, this->index);
00420 SetDParam(1, this->facilities);
00421 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00422
00423 SetWindowDirty(WC_STATION_VIEW, this->index);
00424 }
00425
00427 void UpdateAllStationVirtCoords()
00428 {
00429 BaseStation *st;
00430
00431 FOR_ALL_BASE_STATIONS(st) {
00432 st->UpdateVirtCoord();
00433 }
00434 }
00435
00440 static uint GetAcceptanceMask(const Station *st)
00441 {
00442 uint mask = 0;
00443
00444 for (CargoID i = 0; i < NUM_CARGO; i++) {
00445 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
00446 }
00447 return mask;
00448 }
00449
00453 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00454 {
00455 for (uint i = 0; i < num_items; i++) {
00456 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00457 }
00458
00459 SetDParam(0, st->index);
00460 AddNewsItem(msg, NS_ACCEPTANCE, NR_STATION, st->index);
00461 }
00462
00470 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00471 {
00472 CargoArray produced;
00473
00474 int x = TileX(tile);
00475 int y = TileY(tile);
00476
00477
00478
00479 int x2 = min(x + w + rad, MapSizeX());
00480 int x1 = max(x - rad, 0);
00481
00482 int y2 = min(y + h + rad, MapSizeY());
00483 int y1 = max(y - rad, 0);
00484
00485 assert(x1 < x2);
00486 assert(y1 < y2);
00487 assert(w > 0);
00488 assert(h > 0);
00489
00490 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00491
00492
00493
00494 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00495
00496
00497
00498
00499
00500
00501
00502 const Industry *i;
00503 FOR_ALL_INDUSTRIES(i) {
00504 if (!ta.Intersects(i->location)) continue;
00505
00506 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00507 CargoID cargo = i->produced_cargo[j];
00508 if (cargo != CT_INVALID) produced[cargo]++;
00509 }
00510 }
00511
00512 return produced;
00513 }
00514
00523 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00524 {
00525 CargoArray acceptance;
00526 if (always_accepted != NULL) *always_accepted = 0;
00527
00528 int x = TileX(tile);
00529 int y = TileY(tile);
00530
00531
00532
00533 int x2 = min(x + w + rad, MapSizeX());
00534 int y2 = min(y + h + rad, MapSizeY());
00535 int x1 = max(x - rad, 0);
00536 int y1 = max(y - rad, 0);
00537
00538 assert(x1 < x2);
00539 assert(y1 < y2);
00540 assert(w > 0);
00541 assert(h > 0);
00542
00543 for (int yc = y1; yc != y2; yc++) {
00544 for (int xc = x1; xc != x2; xc++) {
00545 TileIndex tile = TileXY(xc, yc);
00546 AddAcceptedCargo(tile, acceptance, always_accepted);
00547 }
00548 }
00549
00550 return acceptance;
00551 }
00552
00557 void UpdateStationAcceptance(Station *st, bool show_msg)
00558 {
00559
00560 uint old_acc = GetAcceptanceMask(st);
00561
00562
00563 CargoArray acceptance;
00564 if (!st->rect.IsEmpty()) {
00565 acceptance = GetAcceptanceAroundTiles(
00566 TileXY(st->rect.left, st->rect.top),
00567 st->rect.right - st->rect.left + 1,
00568 st->rect.bottom - st->rect.top + 1,
00569 st->GetCatchmentRadius(),
00570 &st->always_accepted
00571 );
00572 }
00573
00574
00575 for (CargoID i = 0; i < NUM_CARGO; i++) {
00576 uint amt = min(acceptance[i], 15);
00577
00578
00579 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00580 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00581 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00582 amt = 0;
00583 }
00584
00585 SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
00586 }
00587
00588
00589 uint new_acc = GetAcceptanceMask(st);
00590 if (old_acc == new_acc) return;
00591
00592
00593 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00594
00595
00596 static const StringID accept_msg[] = {
00597 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00598 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00599 };
00600 static const StringID reject_msg[] = {
00601 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00602 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00603 };
00604
00605
00606 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00607 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00608 uint num_acc = 0;
00609 uint num_rej = 0;
00610
00611
00612 for (CargoID i = 0; i < NUM_CARGO; i++) {
00613 if (HasBit(new_acc, i)) {
00614 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00615
00616 accepts[num_acc++] = i;
00617 }
00618 } else {
00619 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00620
00621 rejects[num_rej++] = i;
00622 }
00623 }
00624 }
00625
00626
00627 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00628 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00629 }
00630
00631
00632 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ACCEPTLIST);
00633 }
00634
00635 static void UpdateStationSignCoord(BaseStation *st)
00636 {
00637 const StationRect *r = &st->rect;
00638
00639 if (r->IsEmpty()) return;
00640
00641
00642 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00643 st->UpdateVirtCoord();
00644 }
00645
00651 static void DeleteStationIfEmpty(BaseStation *st)
00652 {
00653 if (!st->IsInUse()) {
00654 st->delete_ctr = 0;
00655 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00656 }
00657
00658 UpdateStationSignCoord(st);
00659 }
00660
00661 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00662
00674 CommandCost CheckFlatLandBelow(TileIndex tile, uint w, uint h, DoCommandFlag flags, uint invalid_dirs, StationID *station, bool check_clear = true, RailType rt = INVALID_RAILTYPE)
00675 {
00676 CommandCost cost(EXPENSES_CONSTRUCTION);
00677 int allowed_z = -1;
00678
00679 TILE_LOOP(tile_cur, w, h, tile) {
00680 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) {
00681 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00682 }
00683
00684 if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
00685
00686 uint z;
00687 Slope tileh = GetTileSlope(tile_cur, &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 int flat_z = z;
00699 if (tileh != SLOPE_FLAT) {
00700
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 == -1) {
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
00721
00722
00723 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00724 if (!IsRailStation(tile_cur)) {
00725 return ClearTile_Station(tile_cur, DC_AUTO);
00726 } else {
00727 StationID st = GetStationIndex(tile_cur);
00728 if (*station == INVALID_STATION) {
00729 *station = st;
00730 } else if (*station != st) {
00731 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00732 }
00733 }
00734 } else if (check_clear) {
00735
00736
00737 if (rt != INVALID_RAILTYPE &&
00738 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00739 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00740
00741
00742
00743
00744
00745
00746 TrackBits tracks = GetTrackBits(tile_cur);
00747 Track track = RemoveFirstTrack(&tracks);
00748 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00749
00750 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00751 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00752 if (ret.Failed()) return ret;
00753 cost.AddCost(ret);
00754
00755 continue;
00756 }
00757 }
00758 CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00759 if (ret.Failed()) return ret;
00760 cost.AddCost(ret);
00761 }
00762 }
00763
00764 return cost;
00765 }
00766
00774 bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00775 {
00776 TileArea cur_ta = st->train_station;
00777
00778 if (_settings_game.station.nonuniform_stations) {
00779
00780 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00781 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00782 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00783 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00784 new_ta.tile = TileXY(x, y);
00785 } else {
00786
00787
00788 TILE_LOOP(t, cur_ta.w, cur_ta.h, cur_ta.tile) {
00789 if (!st->TileBelongsToRailStation(t)) {
00790 _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00791 return false;
00792 }
00793 }
00794
00795
00796 if (GetRailStationAxis(cur_ta.tile) != axis) {
00797 _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00798 return false;
00799 }
00800
00801
00802 if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile + TileDiffXY(0, new_ta.h)) {
00803
00804 new_ta.h += cur_ta.h;
00805 } else if (cur_ta.w == new_ta.w && cur_ta.tile == new_ta.tile - TileDiffXY(0, cur_ta.h)) {
00806
00807 new_ta.tile = cur_ta.tile;
00808 new_ta.h += new_ta.h;
00809 } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile + TileDiffXY(new_ta.w, 0)) {
00810
00811 new_ta.w += cur_ta.w;
00812 } else if (cur_ta.h == new_ta.h && cur_ta.tile == new_ta.tile - TileDiffXY(cur_ta.w, 0)) {
00813
00814 new_ta.tile = cur_ta.tile;
00815 new_ta.w += cur_ta.w;
00816 } else {
00817 _error_message = STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED;
00818 return false;
00819 }
00820 }
00821
00822 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00823 _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
00824 return false;
00825 }
00826
00827 return true;
00828 }
00829
00830 static inline byte *CreateSingle(byte *layout, int n)
00831 {
00832 int i = n;
00833 do *layout++ = 0; while (--i);
00834 layout[((n - 1) >> 1) - n] = 2;
00835 return layout;
00836 }
00837
00838 static inline byte *CreateMulti(byte *layout, int n, byte b)
00839 {
00840 int i = n;
00841 do *layout++ = b; while (--i);
00842 if (n > 4) {
00843 layout[0 - n] = 0;
00844 layout[n - 1 - n] = 0;
00845 }
00846 return layout;
00847 }
00848
00849 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00850 {
00851 if (statspec != NULL && statspec->lengths >= plat_len &&
00852 statspec->platforms[plat_len - 1] >= numtracks &&
00853 statspec->layouts[plat_len - 1][numtracks - 1]) {
00854
00855 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00856 plat_len * numtracks);
00857 return;
00858 }
00859
00860 if (plat_len == 1) {
00861 CreateSingle(layout, numtracks);
00862 } else {
00863 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00864 numtracks >>= 1;
00865
00866 while (--numtracks >= 0) {
00867 layout = CreateMulti(layout, plat_len, 4);
00868 layout = CreateMulti(layout, plat_len, 6);
00869 }
00870 }
00871 }
00872
00884 template <class T, StringID error_message>
00885 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
00886 {
00887 assert(*st == NULL);
00888 bool check_surrounding = true;
00889
00890 if (_settings_game.station.adjacent_stations) {
00891 if (existing_station != INVALID_STATION) {
00892 if (adjacent && existing_station != station_to_join) {
00893
00894
00895 return_cmd_error(error_message);
00896 } else {
00897
00898
00899 *st = T::GetIfValid(existing_station);
00900 check_surrounding = (*st == NULL);
00901 }
00902 } else {
00903
00904
00905 if (adjacent) check_surrounding = false;
00906 }
00907 }
00908
00909 if (check_surrounding) {
00910
00911 if (!GetStationAround(ta, existing_station, st)) return CMD_ERROR;
00912 }
00913
00914
00915 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
00916
00917 return CommandCost();;
00918 }
00919
00929 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
00930 {
00931 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
00932 }
00933
00943 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
00944 {
00945 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
00946 }
00947
00965 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00966 {
00967
00968 RailType rt = (RailType)GB(p1, 0, 4);
00969 Axis axis = Extract<Axis, 4>(p1);
00970 byte numtracks = GB(p1, 8, 8);
00971 byte plat_len = GB(p1, 16, 8);
00972 bool adjacent = HasBit(p1, 24);
00973
00974 StationClassID spec_class = (StationClassID)GB(p2, 0, 8);
00975 byte spec_index = GB(p2, 8, 8);
00976 StationID station_to_join = GB(p2, 16, 16);
00977
00978
00979 if (!CheckIfAuthorityAllowsNewStation(tile_org, flags)) return CMD_ERROR;
00980 if (!ValParamRailtype(rt)) return CMD_ERROR;
00981
00982
00983 if ((uint)spec_class >= GetNumStationClasses()) return CMD_ERROR;
00984 if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
00985 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
00986
00987 int w_org, h_org;
00988 if (axis == AXIS_X) {
00989 w_org = plat_len;
00990 h_org = numtracks;
00991 } else {
00992 h_org = plat_len;
00993 w_org = numtracks;
00994 }
00995
00996 bool reuse = (station_to_join != NEW_STATION);
00997 if (!reuse) station_to_join = INVALID_STATION;
00998 bool distant_join = (station_to_join != INVALID_STATION);
00999
01000 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01001
01002 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01003
01004
01005 TileArea new_location(tile_org, w_org, h_org);
01006
01007
01008 StationID est = INVALID_STATION;
01009
01010
01011
01012 CommandCost ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL, true, rt);
01013 if (ret.Failed()) return ret;
01014 CommandCost cost(EXPENSES_CONSTRUCTION, ret.GetCost() + (numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01015
01016 Station *st = NULL;
01017 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01018 if (ret.Failed()) return ret;
01019
01020
01021 if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01022
01023 if (st != NULL) {
01024
01025 if (st->owner != _current_company)
01026 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01027
01028 if (st->train_station.tile != INVALID_TILE) {
01029
01030 if (!_settings_game.station.join_stations)
01031 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_RAILROAD);
01032 if (!CanExpandRailStation(st, new_location, axis))
01033 return CMD_ERROR;
01034 }
01035
01036
01037 if (!st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST)) return CMD_ERROR;
01038 } else {
01039
01040 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01041
01042 if (flags & DC_EXEC) {
01043 st = new Station(tile_org);
01044
01045 st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01046 st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01047
01048 if (Company::IsValidID(_current_company)) {
01049 SetBit(st->town->have_ratings, _current_company);
01050 }
01051 }
01052 }
01053
01054
01055 const StationSpec *statspec = GetCustomStationSpec(spec_class, spec_index);
01056 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01057 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01058
01059 if (statspec != NULL) {
01060
01061
01062
01063 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01064 return CMD_ERROR;
01065 }
01066
01067
01068 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
01069 return CMD_ERROR;
01070 }
01071 }
01072
01073 if (flags & DC_EXEC) {
01074 TileIndexDiff tile_delta;
01075 byte *layout_ptr;
01076 byte numtracks_orig;
01077 Track track;
01078
01079
01080
01081
01082 ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << axis, _settings_game.station.nonuniform_stations ? &est : NULL, true, rt);
01083 if (ret.Failed()) return ret;
01084
01085 st->train_station = new_location;
01086 st->AddFacility(FACIL_TRAIN, new_location.tile);
01087
01088 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01089
01090 if (statspec != NULL) {
01091
01092
01093 st->cached_anim_triggers |= statspec->anim_triggers;
01094 }
01095
01096 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01097 track = AxisToTrack(axis);
01098
01099 layout_ptr = AllocaM(byte, numtracks * plat_len);
01100 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01101
01102 numtracks_orig = numtracks;
01103
01104 SmallVector<Train*, 4> affected_vehicles;
01105 do {
01106 TileIndex tile = tile_org;
01107 int w = plat_len;
01108 do {
01109 byte layout = *layout_ptr++;
01110 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01111
01112 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01113 if (v != NULL) {
01114 FreeTrainTrackReservation(v);
01115 *affected_vehicles.Append() = v;
01116 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01117 for (; v->Next() != NULL; v = v->Next()) { }
01118 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01119 }
01120 }
01121
01122
01123 DeleteAnimatedTile(tile);
01124 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01125 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01126
01127 DeallocateSpecFromStation(st, old_specindex);
01128
01129 SetCustomStationSpecIndex(tile, specindex);
01130 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01131 SetStationAnimationFrame(tile, 0);
01132
01133 if (statspec != NULL) {
01134
01135 uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01136
01137
01138 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01139 if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);
01140
01141
01142 StationAnimationTrigger(st, tile, STAT_ANIM_BUILT);
01143 }
01144
01145 tile += tile_delta;
01146 } while (--w);
01147 AddTrackToSignalBuffer(tile_org, track, _current_company);
01148 YapfNotifyTrackLayoutChange(tile_org, track);
01149 tile_org += tile_delta ^ TileDiffXY(1, 1);
01150 } while (--numtracks);
01151
01152 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01153
01154 Train *v = affected_vehicles[i];
01155 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01156 TryPathReserve(v, true, true);
01157 for (; v->Next() != NULL; v = v->Next()) { }
01158 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01159 }
01160
01161 st->MarkTilesDirty(false);
01162 st->UpdateVirtCoord();
01163 UpdateStationAcceptance(st, false);
01164 st->RecomputeIndustriesNear();
01165 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01166 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01167 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01168 }
01169
01170 return cost;
01171 }
01172
01173 static void MakeRailStationAreaSmaller(BaseStation *st)
01174 {
01175 TileArea ta = st->train_station;
01176
01177 restart:
01178
01179
01180 if (ta.w != 0 && ta.h != 0) {
01181
01182 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01183
01184 if (++i == ta.h) {
01185 ta.tile += TileDiffXY(1, 0);
01186 ta.w--;
01187 goto restart;
01188 }
01189 }
01190
01191
01192 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01193
01194 if (++i == ta.h) {
01195 ta.w--;
01196 goto restart;
01197 }
01198 }
01199
01200
01201 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01202
01203 if (++i == ta.w) {
01204 ta.tile += TileDiffXY(0, 1);
01205 ta.h--;
01206 goto restart;
01207 }
01208 }
01209
01210
01211 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01212
01213 if (++i == ta.w) {
01214 ta.h--;
01215 goto restart;
01216 }
01217 }
01218 } else {
01219 ta.Clear();
01220 }
01221
01222 st->train_station = ta;
01223 }
01224
01235 template <class T>
01236 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01237 {
01238
01239 int quantity = 0;
01240 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01241
01242
01243 TILE_AREA_LOOP(tile, ta) {
01244
01245 if (!HasStationTileRail(tile)) continue;
01246
01247
01248 if (!EnsureNoVehicleOnGround(tile)) continue;
01249
01250
01251 T *st = T::GetByTile(tile);
01252 if (st == NULL) continue;
01253 if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) continue;
01254
01255
01256
01257
01258 if (!_settings_game.station.nonuniform_stations) return_cmd_error(STR_ERROR_NONUNIFORM_STATIONS_DISALLOWED);
01259
01260
01261 quantity++;
01262
01263 if (flags & DC_EXEC) {
01264
01265 uint specindex = GetCustomStationSpecIndex(tile);
01266 Track track = GetRailStationTrack(tile);
01267 Owner owner = GetTileOwner(tile);
01268 RailType rt = GetRailType(tile);
01269 Train *v = NULL;
01270
01271 if (HasStationReservation(tile)) {
01272 v = GetTrainForReservation(tile, track);
01273 if (v != NULL) {
01274
01275 FreeTrainTrackReservation(v);
01276 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01277 Vehicle *temp = v;
01278 for (; temp->Next() != NULL; temp = temp->Next()) { }
01279 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01280 }
01281 }
01282
01283 DoClearSquare(tile);
01284 if (keep_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01285
01286 st->rect.AfterRemoveTile(st, tile);
01287 AddTrackToSignalBuffer(tile, track, owner);
01288 YapfNotifyTrackLayoutChange(tile, track);
01289
01290 DeallocateSpecFromStation(st, specindex);
01291
01292 affected_stations.Include(st);
01293
01294 if (v != NULL) {
01295
01296 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01297 TryPathReserve(v, true, true);
01298 for (; v->Next() != NULL; v = v->Next()) { }
01299 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01300 }
01301 }
01302 if (keep_rail) {
01303
01304 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01305 }
01306 }
01307
01308 if (quantity == 0) return CMD_ERROR;
01309
01310 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01311 T *st = *stp;
01312
01313
01314
01315
01316 MakeRailStationAreaSmaller(st);
01317 UpdateStationSignCoord(st);
01318
01319
01320 if (st->train_station.tile == INVALID_TILE) {
01321 st->facilities &= ~FACIL_TRAIN;
01322 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01323 st->UpdateVirtCoord();
01324 DeleteStationIfEmpty(st);
01325 }
01326 }
01327
01328 total_cost.AddCost(quantity * removal_cost);
01329 return total_cost;
01330 }
01331
01342 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01343 {
01344 TileIndex end = p1 == 0 ? start : p1;
01345 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01346
01347 TileArea ta(start, end);
01348 SmallVector<Station *, 4> affected_stations;
01349
01350 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01351 if (ret.Failed()) return ret;
01352
01353
01354 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01355 Station *st = *stp;
01356
01357 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01358 st->MarkTilesDirty(false);
01359 st->RecomputeIndustriesNear();
01360 }
01361
01362
01363 return ret;
01364 }
01365
01376 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01377 {
01378 TileIndex end = p1 == 0 ? start : p1;
01379 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01380
01381 TileArea ta(start, end);
01382 SmallVector<Waypoint *, 4> affected_stations;
01383
01384 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01385 }
01386
01387
01395 template <class T>
01396 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01397 {
01398
01399 if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) return CMD_ERROR;
01400
01401
01402 TileArea ta = st->train_station;
01403
01404 assert(ta.w != 0 && ta.h != 0);
01405
01406 CommandCost cost(EXPENSES_CONSTRUCTION);
01407
01408 TILE_AREA_LOOP(tile, ta) {
01409
01410 if (!st->TileBelongsToRailStation(tile)) continue;
01411
01412 if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01413
01414 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01415 if (flags & DC_EXEC) {
01416
01417 Track track = GetRailStationTrack(tile);
01418 Owner owner = GetTileOwner(tile);
01419 Train *v = NULL;
01420 if (HasStationReservation(tile)) {
01421 v = GetTrainForReservation(tile, track);
01422 if (v != NULL) FreeTrainTrackReservation(v);
01423 }
01424 DoClearSquare(tile);
01425 AddTrackToSignalBuffer(tile, track, owner);
01426 YapfNotifyTrackLayoutChange(tile, track);
01427 if (v != NULL) TryPathReserve(v, true);
01428 }
01429 }
01430
01431 if (flags & DC_EXEC) {
01432 st->rect.AfterRemoveRect(st, st->train_station.tile, st->train_station.w, st->train_station.h);
01433
01434 st->train_station.Clear();
01435
01436 st->facilities &= ~FACIL_TRAIN;
01437
01438 free(st->speclist);
01439 st->num_specs = 0;
01440 st->speclist = NULL;
01441 st->cached_anim_triggers = 0;
01442
01443 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_TRAINS);
01444 st->UpdateVirtCoord();
01445 DeleteStationIfEmpty(st);
01446 }
01447
01448 return cost;
01449 }
01450
01457 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01458 {
01459
01460 if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
01461 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01462 }
01463
01464 Station *st = Station::GetByTile(tile);
01465 CommandCost cost = RemoveRailStation(st, flags);
01466
01467 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01468
01469 return cost;
01470 }
01471
01478 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01479 {
01480
01481 if (_current_company == OWNER_WATER && _settings_game.station.nonuniform_stations) {
01482 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01483 }
01484
01485 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01486 }
01487
01488
01494 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01495 {
01496 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01497
01498 if (*primary_stop == NULL) {
01499
01500 return primary_stop;
01501 } else {
01502
01503 RoadStop *stop = *primary_stop;
01504 while (stop->next != NULL) stop = stop->next;
01505 return &stop->next;
01506 }
01507 }
01508
01521 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01522 {
01523 bool type = HasBit(p2, 0);
01524 bool is_drive_through = HasBit(p2, 1);
01525 bool build_over_road = is_drive_through && IsNormalRoadTile(tile);
01526 RoadTypes rts = (RoadTypes)GB(p2, 2, 2);
01527 StationID station_to_join = GB(p2, 16, 16);
01528 bool reuse = (station_to_join != NEW_STATION);
01529 if (!reuse) station_to_join = INVALID_STATION;
01530 bool distant_join = (station_to_join != INVALID_STATION);
01531 Owner tram_owner = _current_company;
01532 Owner road_owner = _current_company;
01533
01534 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01535
01536 if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01537
01538
01539 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01540
01541
01542 if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
01543
01544 if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
01545
01546 if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
01547
01548 if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
01549
01550 RoadTypes cur_rts = IsNormalRoadTile(tile) ? GetRoadTypes(tile) : ROADTYPES_NONE;
01551 uint num_roadbits = 0;
01552
01553 if (build_over_road) {
01554
01555 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
01556 road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01557 if (road_owner == OWNER_TOWN) {
01558 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
01559 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) {
01560 return CMD_ERROR;
01561 }
01562 num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_ROAD));
01563 }
01564
01565
01566 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
01567 tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01568 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) {
01569 return CMD_ERROR;
01570 }
01571 num_roadbits += CountBits(GetRoadBits(tile, ROADTYPE_TRAM));
01572 }
01573
01574
01575 if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01576
01577
01578 rts |= cur_rts;
01579 }
01580
01581 CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
01582 if (cost.Failed()) return cost;
01583 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
01584 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
01585
01586 Station *st = NULL;
01587 CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 5), TileArea(tile, 1, 1), &st);
01588 if (ret.Failed()) return ret;
01589
01590
01591 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01592
01593
01594 if (!RoadStop::CanAllocateItem()) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
01595
01596 if (st != NULL) {
01597 if (st->owner != _current_company) {
01598 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01599 }
01600
01601 if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
01602 } else {
01603
01604 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01605
01606 if (flags & DC_EXEC) {
01607 st = new Station(tile);
01608
01609 st->town = ClosestTownFromTile(tile, UINT_MAX);
01610 st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01611
01612 if (Company::IsValidID(_current_company)) {
01613 SetBit(st->town->have_ratings, _current_company);
01614 }
01615 }
01616 }
01617
01618 cost.AddCost(_price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01619
01620 if (flags & DC_EXEC) {
01621 RoadStop *road_stop = new RoadStop(tile);
01622
01623 RoadStop **currstop = FindRoadStopSpot(type, st);
01624 *currstop = road_stop;
01625
01626 if (type) {
01627 st->truck_station.Add(tile);
01628 } else {
01629 st->bus_station.Add(tile);
01630 }
01631
01632
01633 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, tile);
01634
01635 st->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
01636
01637 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01638 if (is_drive_through) {
01639 MakeDriveThroughRoadStop(tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts, (Axis)p1);
01640 road_stop->MakeDriveThrough();
01641 } else {
01642 MakeRoadStop(tile, st->owner, st->index, rs_type, rts, (DiagDirection)p1);
01643 }
01644
01645 st->UpdateVirtCoord();
01646 UpdateStationAcceptance(st, false);
01647 st->RecomputeIndustriesNear();
01648 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01649 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01650 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01651 }
01652 return cost;
01653 }
01654
01655
01656 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01657 {
01658 if (v->type == VEH_ROAD) {
01659
01660
01661
01662
01663
01664
01665 RoadVehicle *rv = RoadVehicle::From(v);
01666 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01667 }
01668
01669 return NULL;
01670 }
01671
01672
01679 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01680 {
01681 Station *st = Station::GetByTile(tile);
01682
01683 if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
01684 return CMD_ERROR;
01685 }
01686
01687 bool is_truck = IsTruckStop(tile);
01688
01689 RoadStop **primary_stop;
01690 RoadStop *cur_stop;
01691 if (is_truck) {
01692 primary_stop = &st->truck_stops;
01693 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01694 } else {
01695 primary_stop = &st->bus_stops;
01696 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01697 }
01698
01699 assert(cur_stop != NULL);
01700
01701
01702 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01703
01704 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01705 } else {
01706 if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
01707 }
01708
01709 if (flags & DC_EXEC) {
01710 if (*primary_stop == cur_stop) {
01711
01712 *primary_stop = cur_stop->next;
01713
01714 if (*primary_stop == NULL) {
01715 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01716 }
01717 } else {
01718
01719 RoadStop *pred = *primary_stop;
01720 while (pred->next != cur_stop) pred = pred->next;
01721 pred->next = cur_stop->next;
01722 }
01723
01724 if (IsDriveThroughStopTile(tile)) {
01725
01726 cur_stop->ClearDriveThrough();
01727 } else {
01728 DoClearSquare(tile);
01729 }
01730
01731 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
01732 delete cur_stop;
01733
01734
01735 RoadVehicle *v;
01736 FOR_ALL_ROADVEHICLES(v) {
01737 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01738 v->dest_tile == tile) {
01739 v->dest_tile = v->GetOrderStationLocation(st->index);
01740 }
01741 }
01742
01743 st->rect.AfterRemoveTile(st, tile);
01744
01745 st->UpdateVirtCoord();
01746 st->RecomputeIndustriesNear();
01747 DeleteStationIfEmpty(st);
01748
01749
01750 if (is_truck) {
01751 st->truck_station.Clear();
01752 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01753 } else {
01754 st->bus_station.Clear();
01755 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01756 }
01757 }
01758
01759 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01760 }
01761
01770 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01771 {
01772
01773 if (!IsTileType(tile, MP_STATION) || !IsRoadStop(tile) || (uint32)GetRoadStopType(tile) != GB(p2, 0, 1)) return CMD_ERROR;
01774
01775
01776 bool is_drive_through = IsDriveThroughStopTile(tile);
01777 RoadTypes rts = GetRoadTypes(tile);
01778 RoadBits road_bits = IsDriveThroughStopTile(tile) ?
01779 ((GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01780 DiagDirToRoadBits(GetRoadStopDir(tile));
01781
01782 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01783 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01784 CommandCost ret = RemoveRoadStop(tile, flags);
01785
01786
01787 if ((flags & DC_EXEC) && ret.Succeeded() && is_drive_through) {
01788
01789
01790
01791 MakeRoadNormal(tile, road_bits, rts, ClosestTownFromTile(tile, UINT_MAX)->index,
01792 road_owner, tram_owner);
01793 }
01794
01795 return ret;
01796 }
01797
01805 static uint GetMinimalAirportDistanceToTile(const AirportSpec *as, TileIndex town_tile, TileIndex airport_tile)
01806 {
01807 uint ttx = TileX(town_tile);
01808 uint tty = TileY(town_tile);
01809
01810 uint atx = TileX(airport_tile);
01811 uint aty = TileY(airport_tile);
01812
01813 uint btx = TileX(airport_tile) + as->size_x - 1;
01814 uint bty = TileY(airport_tile) + as->size_y - 1;
01815
01816
01817
01818
01819 uint dx = ttx < atx ? atx - ttx : (ttx <= btx ? 0 : ttx - btx);
01820 uint dy = tty < aty ? aty - tty : (tty <= bty ? 0 : tty - bty);
01821
01822 return dx + dy;
01823 }
01824
01833 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIndex town_tile, TileIndex tile)
01834 {
01835
01836
01837 if (as->noise_level < 2) return as->noise_level;
01838
01839 uint distance = GetMinimalAirportDistanceToTile(as, town_tile, tile);
01840
01841
01842
01843
01844
01845 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
01846
01847
01848
01849 uint noise_reduction = distance / town_tolerance_distance;
01850
01851
01852
01853 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
01854 }
01855
01863 Town *AirportGetNearestTown(const AirportSpec *as, TileIndex airport_tile)
01864 {
01865 Town *t, *nearest = NULL;
01866 uint add = as->size_x + as->size_y - 2;
01867 uint mindist = UINT_MAX - add;
01868 FOR_ALL_TOWNS(t) {
01869 if (DistanceManhattan(t->xy, airport_tile) < mindist + add) {
01870 uint dist = GetMinimalAirportDistanceToTile(as, t->xy, airport_tile);
01871 if (dist < mindist) {
01872 nearest = t;
01873 mindist = dist;
01874 }
01875 }
01876 }
01877
01878 return nearest;
01879 }
01880
01881
01883 void UpdateAirportsNoise()
01884 {
01885 Town *t;
01886 const Station *st;
01887
01888 FOR_ALL_TOWNS(t) t->noise_reached = 0;
01889
01890 FOR_ALL_STATIONS(st) {
01891 if (st->airport_tile != INVALID_TILE) {
01892 const AirportSpec *as = st->GetAirportSpec();
01893 Town *nearest = AirportGetNearestTown(as, st->airport_tile);
01894 nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport_tile);
01895 }
01896 }
01897 }
01898
01909 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01910 {
01911 bool airport_upgrade = true;
01912 StationID station_to_join = GB(p2, 16, 16);
01913 bool reuse = (station_to_join != NEW_STATION);
01914 if (!reuse) station_to_join = INVALID_STATION;
01915 bool distant_join = (station_to_join != INVALID_STATION);
01916
01917 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01918
01919 if (p1 >= NUM_AIRPORTS) return CMD_ERROR;
01920
01921 if (!CheckIfAuthorityAllowsNewStation(tile, flags)) {
01922 return CMD_ERROR;
01923 }
01924
01925
01926 const AirportSpec *as = AirportSpec::Get(p1);
01927 if (!as->IsAvailable()) return CMD_ERROR;
01928
01929 Town *t = ClosestTownFromTile(tile, UINT_MAX);
01930 int w = as->size_x;
01931 int h = as->size_y;
01932
01933 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
01934 _error_message = STR_ERROR_STATION_TOO_SPREAD_OUT;
01935 return CMD_ERROR;
01936 }
01937
01938 CommandCost cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
01939 if (cost.Failed()) return cost;
01940
01941
01942 Town *nearest = AirportGetNearestTown(as, tile);
01943 uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
01944
01945
01946 StringID authority_refuse_message = STR_NULL;
01947
01948 if (_settings_game.economy.station_noise_level) {
01949
01950 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
01951 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
01952 }
01953 } else {
01954 uint num = 0;
01955 const Station *st;
01956 FOR_ALL_STATIONS(st) {
01957 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport_type != AT_OILRIG) num++;
01958 }
01959 if (num >= 2) {
01960 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
01961 }
01962 }
01963
01964 if (authority_refuse_message != STR_NULL) {
01965 SetDParam(0, t->index);
01966 return_cmd_error(authority_refuse_message);
01967 }
01968
01969 Station *st = NULL;
01970 CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
01971 if (ret.Failed()) return ret;
01972
01973
01974 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
01975
01976
01977 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01978
01979 if (st != NULL) {
01980 if (st->owner != _current_company) {
01981 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01982 }
01983
01984 if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
01985
01986 if (st->airport_tile != INVALID_TILE) {
01987 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
01988 }
01989 } else {
01990 airport_upgrade = false;
01991
01992
01993 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01994
01995 if (flags & DC_EXEC) {
01996 st = new Station(tile);
01997
01998 st->town = t;
01999 st->string_id = GenerateStationName(st, tile, !(GetAirport(p1)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02000
02001 if (Company::IsValidID(_current_company)) {
02002 SetBit(st->town->have_ratings, _current_company);
02003 }
02004 }
02005 }
02006
02007 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT] * w * h);
02008
02009 if (flags & DC_EXEC) {
02010
02011 nearest->noise_reached += newnoise_level;
02012
02013 st->airport_tile = tile;
02014 st->AddFacility(FACIL_AIRPORT, tile);
02015 st->airport_type = (byte)p1;
02016 st->airport_flags = 0;
02017
02018 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02019
02020
02021
02022
02023
02024
02025
02026
02027 if (airport_upgrade) UpdateAirplanesOnNewStation(st);
02028
02029 const AirportTileTable *it = as->table[0];
02030 do {
02031 TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
02032 MakeAirport(cur_tile, st->owner, st->index, it->gfx);
02033 } while ((++it)->ti.x != -0x80);
02034
02035 st->UpdateVirtCoord();
02036 UpdateStationAcceptance(st, false);
02037 st->RecomputeIndustriesNear();
02038 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02039 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02040 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02041
02042 if (_settings_game.economy.station_noise_level) {
02043 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02044 }
02045 }
02046
02047 return cost;
02048 }
02049
02056 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02057 {
02058 Station *st = Station::GetByTile(tile);
02059
02060 if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
02061 return CMD_ERROR;
02062 }
02063
02064 tile = st->airport_tile;
02065
02066 const AirportSpec *as = st->GetAirportSpec();
02067 int w = as->size_x;
02068 int h = as->size_y;
02069
02070 CommandCost cost(EXPENSES_CONSTRUCTION);
02071
02072 const Aircraft *a;
02073 FOR_ALL_AIRCRAFT(a) {
02074 if (!a->IsNormalAircraft()) continue;
02075 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02076 }
02077
02078 TILE_LOOP(tile_cur, w, h, tile) {
02079 if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;
02080
02081 if (!st->TileBelongsToAirport(tile_cur)) continue;
02082
02083 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02084
02085 if (flags & DC_EXEC) {
02086 DeleteAnimatedTile(tile_cur);
02087 DoClearSquare(tile_cur);
02088 }
02089 }
02090
02091 if (flags & DC_EXEC) {
02092 for (uint i = 0; i < as->nof_depots; ++i) {
02093 DeleteWindowById(
02094 WC_VEHICLE_DEPOT, st->GetHangarTile(i)
02095 );
02096 }
02097
02098
02099
02100
02101 Town *nearest = AirportGetNearestTown(as, tile);
02102 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
02103
02104 st->rect.AfterRemoveRect(st, tile, w, h);
02105
02106 st->airport_tile = INVALID_TILE;
02107 st->facilities &= ~FACIL_AIRPORT;
02108
02109 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
02110
02111 if (_settings_game.economy.station_noise_level) {
02112 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02113 }
02114
02115 st->UpdateVirtCoord();
02116 st->RecomputeIndustriesNear();
02117 DeleteStationIfEmpty(st);
02118 }
02119
02120 return cost;
02121 }
02122
02129 bool HasStationInUse(StationID station, CompanyID company)
02130 {
02131 const Vehicle *v;
02132 FOR_ALL_VEHICLES(v) {
02133 if (company == INVALID_COMPANY || v->owner == company) {
02134 const Order *order;
02135 FOR_VEHICLE_ORDERS(v, order) {
02136 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02137 return true;
02138 }
02139 }
02140 }
02141 }
02142 return false;
02143 }
02144
02145 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02146 {-1, 0},
02147 { 0, 0},
02148 { 0, 0},
02149 { 0, -1}
02150 };
02151 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02152 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02153
02162 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02163 {
02164 StationID station_to_join = GB(p2, 16, 16);
02165 bool reuse = (station_to_join != NEW_STATION);
02166 if (!reuse) station_to_join = INVALID_STATION;
02167 bool distant_join = (station_to_join != INVALID_STATION);
02168
02169 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02170
02171 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
02172 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02173 direction = ReverseDiagDir(direction);
02174
02175
02176 if (IsWaterTile(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02177
02178 if (!CheckIfAuthorityAllowsNewStation(tile, flags)) return CMD_ERROR;
02179
02180 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02181
02182 if (DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
02183
02184 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02185
02186 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02187 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02188 }
02189
02190 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02191
02192
02193 WaterClass wc = GetWaterClass(tile_cur);
02194
02195 if (DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
02196
02197 tile_cur += TileOffsByDiagDir(direction);
02198 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
02199 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02200 }
02201
02202
02203 Station *st = NULL;
02204 CommandCost ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02205 TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02206 _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02207 if (ret.Failed()) return ret;
02208
02209
02210 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02211
02212
02213 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02214
02215 if (st != NULL) {
02216 if (st->owner != _current_company) {
02217 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02218 }
02219
02220 if (!st->rect.BeforeAddRect(
02221 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02222 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
02223
02224 if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02225 } else {
02226
02227 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02228
02229 if (flags & DC_EXEC) {
02230 st = new Station(tile);
02231
02232 st->town = ClosestTownFromTile(tile, UINT_MAX);
02233 st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02234
02235 if (Company::IsValidID(_current_company)) {
02236 SetBit(st->town->have_ratings, _current_company);
02237 }
02238 }
02239 }
02240
02241 if (flags & DC_EXEC) {
02242 st->dock_tile = tile;
02243 st->AddFacility(FACIL_DOCK, tile);
02244
02245 st->rect.BeforeAddRect(
02246 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02247 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
02248
02249 MakeDock(tile, st->owner, st->index, direction, wc);
02250
02251 st->UpdateVirtCoord();
02252 UpdateStationAcceptance(st, false);
02253 st->RecomputeIndustriesNear();
02254 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02255 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02256 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02257 }
02258
02259 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02260 }
02261
02268 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02269 {
02270 Station *st = Station::GetByTile(tile);
02271 if (!CheckOwnership(st->owner)) return CMD_ERROR;
02272
02273 TileIndex tile1 = st->dock_tile;
02274 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02275
02276 if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
02277 if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;
02278
02279 if (flags & DC_EXEC) {
02280 DoClearSquare(tile1);
02281 MakeWaterKeepingClass(tile2, st->owner);
02282
02283 st->rect.AfterRemoveTile(st, tile1);
02284 st->rect.AfterRemoveTile(st, tile2);
02285
02286 MarkTileDirtyByTile(tile2);
02287
02288 st->dock_tile = INVALID_TILE;
02289 st->facilities &= ~FACIL_DOCK;
02290
02291 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
02292 st->UpdateVirtCoord();
02293 st->RecomputeIndustriesNear();
02294 DeleteStationIfEmpty(st);
02295 }
02296
02297 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02298 }
02299
02300 #include "table/station_land.h"
02301
02302 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02303 {
02304 return &_station_display_datas[st][gfx];
02305 }
02306
02307 static void DrawTile_Station(TileInfo *ti)
02308 {
02309 const DrawTileSprites *t = NULL;
02310 RoadTypes roadtypes;
02311 int32 total_offset;
02312 int32 custom_ground_offset;
02313 uint32 relocation = 0;
02314 const BaseStation *st = NULL;
02315 const StationSpec *statspec = NULL;
02316
02317 if (HasStationRail(ti->tile)) {
02318 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02319 roadtypes = ROADTYPES_NONE;
02320 total_offset = rti->total_offset;
02321 custom_ground_offset = rti->custom_ground_offset;
02322
02323 if (IsCustomStationSpecIndex(ti->tile)) {
02324
02325 st = BaseStation::GetByTile(ti->tile);
02326 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02327
02328 if (statspec != NULL) {
02329 uint tile = GetStationGfx(ti->tile);
02330
02331 relocation = GetCustomStationRelocation(statspec, st, ti->tile);
02332
02333 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02334 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02335 if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
02336 }
02337
02338
02339 if (statspec->renderdata != NULL) {
02340 t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
02341 }
02342 }
02343 }
02344 } else {
02345 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02346 total_offset = 0;
02347 custom_ground_offset = 0;
02348 }
02349
02350 if (IsAirport(ti->tile)) {
02351 switch (GetStationGfx(ti->tile)) {
02352 case APT_RADAR_GRASS_FENCE_SW:
02353 t = &_station_display_datas_airport_radar_grass_fence_sw[GetStationAnimationFrame(ti->tile)];
02354 break;
02355 case APT_GRASS_FENCE_NE_FLAG:
02356 t = &_station_display_datas_airport_flag_grass_fence_ne[GetStationAnimationFrame(ti->tile)];
02357 break;
02358 case APT_RADAR_FENCE_SW:
02359 t = &_station_display_datas_airport_radar_fence_sw[GetStationAnimationFrame(ti->tile)];
02360 break;
02361 case APT_RADAR_FENCE_NE:
02362 t = &_station_display_datas_airport_radar_fence_ne[GetStationAnimationFrame(ti->tile)];
02363 break;
02364 case APT_GRASS_FENCE_NE_FLAG_2:
02365 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetStationAnimationFrame(ti->tile)];
02366 break;
02367 }
02368 }
02369
02370 Owner owner = GetTileOwner(ti->tile);
02371
02372 PaletteID palette;
02373 if (Company::IsValidID(owner)) {
02374 palette = COMPANY_SPRITE_COLOUR(owner);
02375 } else {
02376
02377 palette = PALETTE_TO_GREY;
02378 }
02379
02380 if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];
02381
02382
02383 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02384 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02385
02386 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile);
02387
02388 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02389
02390
02391 static const uint8 foundation_parts[] = {
02392 0, 0, 0, 0,
02393 0, 1, 2, 3,
02394 0, 4, 5, 6,
02395 7, 8, 9
02396 };
02397
02398 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02399 } else {
02400
02401
02402
02403
02404 static const uint8 composite_foundation_parts[] = {
02405
02406 0x00, 0xD1, 0xE4, 0xE0,
02407
02408 0xCA, 0xC9, 0xC4, 0xC0,
02409
02410 0xD2, 0x91, 0xE4, 0xA0,
02411
02412 0x4A, 0x09, 0x44
02413 };
02414
02415 uint8 parts = composite_foundation_parts[ti->tileh];
02416
02417
02418
02419 uint z;
02420 Slope slope = GetFoundationSlope(ti->tile, &z);
02421 if (!HasFoundationNW(ti->tile, slope, z)) ClrBit(parts, 6);
02422 if (!HasFoundationNE(ti->tile, slope, z)) ClrBit(parts, 7);
02423
02424 StartSpriteCombine();
02425 for (int i = 0; i < 8; i++) {
02426 if (HasBit(parts, i)) {
02427 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02428 }
02429 }
02430 EndSpriteCombine();
02431 }
02432
02433 OffsetGroundSprite(31, 1);
02434 ti->z += ApplyFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02435 } else {
02436 DrawFoundation(ti, FOUNDATION_LEVELED);
02437 }
02438 }
02439
02440 if (IsBuoy(ti->tile) || IsDock(ti->tile) || (IsOilRig(ti->tile) && GetWaterClass(ti->tile) != WATER_CLASS_INVALID)) {
02441 if (ti->tileh == SLOPE_FLAT) {
02442 DrawWaterClassGround(ti);
02443 } else {
02444 assert(IsDock(ti->tile));
02445 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02446 WaterClass wc = GetWaterClass(water_tile);
02447 if (wc == WATER_CLASS_SEA) {
02448 DrawShoreTile(ti->tileh);
02449 } else {
02450 DrawClearLandTile(ti, 3);
02451 }
02452 }
02453 } else {
02454 SpriteID image = t->ground.sprite;
02455 PaletteID pal = t->ground.pal;
02456 if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
02457 image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
02458 image += custom_ground_offset;
02459 } else {
02460 image += total_offset;
02461 }
02462 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02463
02464
02465 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02466 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02467 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02468 }
02469 }
02470
02471 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02472
02473 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02474 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02475 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02476 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02477 }
02478
02479 if (IsRailWaypoint(ti->tile)) {
02480
02481 total_offset = 0;
02482 }
02483
02484 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02485 }
02486
02487 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02488 {
02489 int32 total_offset = 0;
02490 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02491 const DrawTileSprites *t = &_station_display_datas[st][image];
02492
02493 if (railtype != INVALID_RAILTYPE) {
02494 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
02495 total_offset = rti->total_offset;
02496 }
02497
02498 SpriteID img = t->ground.sprite;
02499 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02500
02501 if (roadtype == ROADTYPE_TRAM) {
02502 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02503 }
02504
02505
02506 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02507 }
02508
02509 static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
02510 {
02511 return GetTileMaxZ(tile);
02512 }
02513
02514 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02515 {
02516 return FlatteningFoundation(tileh);
02517 }
02518
02519 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02520 {
02521 td->owner[0] = GetTileOwner(tile);
02522 if (IsDriveThroughStopTile(tile)) {
02523 Owner road_owner = INVALID_OWNER;
02524 Owner tram_owner = INVALID_OWNER;
02525 RoadTypes rts = GetRoadTypes(tile);
02526 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02527 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02528
02529
02530 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02531 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02532 uint i = 1;
02533 if (road_owner != INVALID_OWNER) {
02534 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02535 td->owner[i] = road_owner;
02536 i++;
02537 }
02538 if (tram_owner != INVALID_OWNER) {
02539 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02540 td->owner[i] = tram_owner;
02541 }
02542 }
02543 }
02544 td->build_date = BaseStation::GetByTile(tile)->build_date;
02545
02546 if (HasStationTileRail(tile)) {
02547 const StationSpec *spec = GetStationSpec(tile);
02548
02549 if (spec != NULL) {
02550 td->station_class = GetStationClassName(spec->sclass);
02551 td->station_name = spec->name;
02552
02553 if (spec->grffile != NULL) {
02554 const GRFConfig *gc = GetGRFConfig(spec->grffile->grfid);
02555 td->grf = gc->name;
02556 }
02557 }
02558 }
02559
02560 StringID str;
02561 switch (GetStationType(tile)) {
02562 default: NOT_REACHED();
02563 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02564 case STATION_AIRPORT:
02565 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02566 break;
02567 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02568 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02569 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
02570 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02571 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02572 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02573 }
02574 td->str = str;
02575 }
02576
02577
02578 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02579 {
02580 TrackBits trackbits = TRACK_BIT_NONE;
02581
02582 switch (mode) {
02583 case TRANSPORT_RAIL:
02584 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02585 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02586 }
02587 break;
02588
02589 case TRANSPORT_WATER:
02590
02591 if (IsBuoy(tile)) {
02592 trackbits = TRACK_BIT_ALL;
02593
02594 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02595
02596 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02597 }
02598 break;
02599
02600 case TRANSPORT_ROAD:
02601 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02602 DiagDirection dir = GetRoadStopDir(tile);
02603 Axis axis = DiagDirToAxis(dir);
02604
02605 if (side != INVALID_DIAGDIR) {
02606 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02607 }
02608
02609 trackbits = AxisToTrackBits(axis);
02610 }
02611 break;
02612
02613 default:
02614 break;
02615 }
02616
02617 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02618 }
02619
02620
02621 static void TileLoop_Station(TileIndex tile)
02622 {
02623
02624
02625 switch (GetStationType(tile)) {
02626 case STATION_AIRPORT:
02627 if (AirportTileSpec::Get(GetStationGfx(tile))->animation_info != 0xFFFF) {
02628 AddAnimatedTile(tile);
02629 }
02630 break;
02631
02632 case STATION_DOCK:
02633 if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break;
02634
02635 case STATION_OILRIG:
02636 case STATION_BUOY:
02637 TileLoop_Water(tile);
02638 break;
02639
02640 default: break;
02641 }
02642 }
02643
02644
02645 static void AnimateTile_Station(TileIndex tile)
02646 {
02647 if (HasStationRail(tile)) {
02648 AnimateStationTile(tile);
02649 return;
02650 }
02651
02652 if (IsAirport(tile)) {
02653 const AirportTileSpec *ats = AirportTileSpec::Get(GetStationGfx(tile));
02654 uint16 mask = (1 << ats->animation_speed) - 1;
02655 if (ats->animation_info != 0xFFFF && (_tick_counter & mask) == 0) {
02656 uint8 next_frame = GetStationAnimationFrame(tile) + 1;
02657 if (next_frame >= GB(ats->animation_info, 0, 8)) next_frame = 0;
02658 SetStationAnimationFrame(tile, next_frame);
02659 MarkTileDirtyByTile(tile);
02660 }
02661 }
02662 }
02663
02664
02665 static bool ClickTile_Station(TileIndex tile)
02666 {
02667 const BaseStation *st = BaseStation::GetByTile(tile);
02668
02669 if (st->facilities & FACIL_WAYPOINT) {
02670 ShowWaypointWindow(Waypoint::From(st));
02671 } else if (IsHangar(tile)) {
02672 ShowDepotWindow(tile, VEH_AIRCRAFT);
02673 } else {
02674 ShowStationViewWindow(st->index);
02675 }
02676 return true;
02677 }
02678
02679 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
02680 {
02681 if (v->type == VEH_TRAIN) {
02682 StationID station_id = GetStationIndex(tile);
02683 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
02684 if (!IsRailStation(tile) || !Train::From(v)->IsFrontEngine()) return VETSB_CONTINUE;
02685
02686 int station_ahead;
02687 int station_length;
02688 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
02689
02690
02691
02692
02693
02694 if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
02695
02696 DiagDirection dir = DirToDiagDir(v->direction);
02697
02698 x &= 0xF;
02699 y &= 0xF;
02700
02701 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
02702 if (y == TILE_SIZE / 2) {
02703 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
02704 stop &= TILE_SIZE - 1;
02705
02706 if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
02707 if (x < stop) {
02708 uint16 spd;
02709
02710 v->vehstatus |= VS_TRAIN_SLOWING;
02711 spd = max(0, (stop - x) * 20 - 15);
02712 if (spd < v->cur_speed) v->cur_speed = spd;
02713 }
02714 }
02715 } else if (v->type == VEH_ROAD) {
02716 RoadVehicle *rv = RoadVehicle::From(v);
02717 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
02718 if (IsRoadStop(tile) && rv->IsRoadVehFront()) {
02719
02720 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
02721 }
02722 }
02723 }
02724
02725 return VETSB_CONTINUE;
02726 }
02727
02734 static bool StationHandleBigTick(BaseStation *st)
02735 {
02736 if (!st->IsInUse() && ++st->delete_ctr >= 8) {
02737 delete st;
02738 return false;
02739 }
02740
02741 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
02742
02743 return true;
02744 }
02745
02746 static inline void byte_inc_sat(byte *p)
02747 {
02748 byte b = *p + 1;
02749 if (b != 0) *p = b;
02750 }
02751
02752 static void UpdateStationRating(Station *st)
02753 {
02754 bool waiting_changed = false;
02755
02756 byte_inc_sat(&st->time_since_load);
02757 byte_inc_sat(&st->time_since_unload);
02758
02759 const CargoSpec *cs;
02760 FOR_ALL_CARGOSPECS(cs) {
02761 GoodsEntry *ge = &st->goods[cs->Index()];
02762
02763
02764
02765 if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
02766 ge->rating++;
02767 }
02768
02769
02770 if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
02771 byte_inc_sat(&ge->days_since_pickup);
02772
02773 bool skip = false;
02774 int rating = 0;
02775 uint waiting = ge->cargo.Count();
02776
02777 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
02778
02779
02780
02781
02782 uint last_speed = ge->last_speed;
02783 if (last_speed == 0) last_speed = 0xFF;
02784
02785 uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
02786
02787 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
02788 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
02789 if (callback != CALLBACK_FAILED) {
02790 skip = true;
02791 rating = GB(callback, 0, 14);
02792
02793
02794 if (HasBit(callback, 14)) rating -= 0x4000;
02795 }
02796 }
02797
02798 if (!skip) {
02799 int b = ge->last_speed - 85;
02800 if (b >= 0) rating += b >> 2;
02801
02802 byte days = ge->days_since_pickup;
02803 if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
02804 (days > 21) ||
02805 (rating += 25, days > 12) ||
02806 (rating += 25, days > 6) ||
02807 (rating += 45, days > 3) ||
02808 (rating += 35, true);
02809
02810 (rating -= 90, waiting > 1500) ||
02811 (rating += 55, waiting > 1000) ||
02812 (rating += 35, waiting > 600) ||
02813 (rating += 10, waiting > 300) ||
02814 (rating += 20, waiting > 100) ||
02815 (rating += 10, true);
02816 }
02817
02818 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
02819
02820 byte age = ge->last_age;
02821 (age >= 3) ||
02822 (rating += 10, age >= 2) ||
02823 (rating += 10, age >= 1) ||
02824 (rating += 13, true);
02825
02826 {
02827 int or_ = ge->rating;
02828
02829
02830 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
02831
02832
02833
02834 if (rating <= 64 && waiting >= 200) {
02835 int dec = Random() & 0x1F;
02836 if (waiting < 400) dec &= 7;
02837 waiting -= dec + 1;
02838 waiting_changed = true;
02839 }
02840
02841
02842 if (rating <= 127 && waiting != 0) {
02843 uint32 r = Random();
02844 if (rating <= (int)GB(r, 0, 7)) {
02845
02846 waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
02847 waiting_changed = true;
02848 }
02849 }
02850
02851
02852
02853
02854 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
02855 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
02856 static const uint MAX_WAITING_CARGO = 1 << 15;
02857
02858 if (waiting > WAITING_CARGO_THRESHOLD) {
02859 uint difference = waiting - WAITING_CARGO_THRESHOLD;
02860 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
02861
02862 waiting = min(waiting, MAX_WAITING_CARGO);
02863 waiting_changed = true;
02864 }
02865
02866 if (waiting_changed) ge->cargo.Truncate(waiting);
02867 }
02868 }
02869 }
02870
02871 StationID index = st->index;
02872 if (waiting_changed) {
02873 SetWindowDirty(WC_STATION_VIEW, index);
02874 } else {
02875 SetWindowWidgetDirty(WC_STATION_VIEW, index, SVW_RATINGLIST);
02876 }
02877 }
02878
02879
02880 static void StationHandleSmallTick(BaseStation *st)
02881 {
02882 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
02883
02884 byte b = st->delete_ctr + 1;
02885 if (b >= 185) b = 0;
02886 st->delete_ctr = b;
02887
02888 if (b == 0) UpdateStationRating(Station::From(st));
02889 }
02890
02891 void OnTick_Station()
02892 {
02893 if (_game_mode == GM_EDITOR) return;
02894
02895 BaseStation *st;
02896 FOR_ALL_BASE_STATIONS(st) {
02897 StationHandleSmallTick(st);
02898
02899
02900
02901
02902 if ((_tick_counter + st->index) % 250 == 0) {
02903
02904 if (!StationHandleBigTick(st)) continue;
02905 StationAnimationTrigger(st, st->xy, STAT_ANIM_250_TICKS);
02906 }
02907 }
02908 }
02909
02910 void StationMonthlyLoop()
02911 {
02912
02913 }
02914
02915
02916 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
02917 {
02918 Station *st;
02919
02920 FOR_ALL_STATIONS(st) {
02921 if (st->owner == owner &&
02922 DistanceManhattan(tile, st->xy) <= radius) {
02923 for (CargoID i = 0; i < NUM_CARGO; i++) {
02924 GoodsEntry *ge = &st->goods[i];
02925
02926 if (ge->acceptance_pickup != 0) {
02927 ge->rating = Clamp(ge->rating + amount, 0, 255);
02928 }
02929 }
02930 }
02931 }
02932 }
02933
02934 static void UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
02935 {
02936 st->goods[type].cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
02937 SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);
02938
02939 StationAnimationTrigger(st, st->xy, STAT_ANIM_NEW_CARGO, type);
02940
02941 SetWindowDirty(WC_STATION_VIEW, st->index);
02942 st->MarkTilesDirty(true);
02943 }
02944
02945 static bool IsUniqueStationName(const char *name)
02946 {
02947 const Station *st;
02948
02949 FOR_ALL_STATIONS(st) {
02950 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
02951 }
02952
02953 return true;
02954 }
02955
02964 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02965 {
02966 Station *st = Station::GetIfValid(p1);
02967 if (st == NULL || !CheckOwnership(st->owner)) return CMD_ERROR;
02968
02969 bool reset = StrEmpty(text);
02970
02971 if (!reset) {
02972 if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
02973 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02974 }
02975
02976 if (flags & DC_EXEC) {
02977 free(st->name);
02978 st->name = reset ? NULL : strdup(text);
02979
02980 st->UpdateVirtCoord();
02981 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
02982 }
02983
02984 return CommandCost();
02985 }
02986
02993 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
02994 {
02995
02996 int max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
02997
02998 for (int dy = -max_rad; dy < location.h + max_rad; dy++) {
02999 for (int dx = -max_rad; dx < location.w + max_rad; dx++) {
03000 TileIndex cur_tile = TileAddWrap(location.tile, dx, dy);
03001 if (cur_tile == INVALID_TILE || !IsTileType(cur_tile, MP_STATION)) continue;
03002
03003 Station *st = Station::GetByTile(cur_tile);
03004 if (st == NULL) continue;
03005
03006 if (_settings_game.station.modified_catchment) {
03007 int rad = st->GetCatchmentRadius();
03008 if (dx < -rad || dx >= rad + location.w || dy < -rad || dy >= rad + location.h) continue;
03009 }
03010
03011
03012
03013
03014 stations->Include(st);
03015 }
03016 }
03017 }
03018
03023 const StationList *StationFinder::GetStations()
03024 {
03025 if (this->tile != INVALID_TILE) {
03026 FindStationsAroundTiles(*this, &this->stations);
03027 this->tile = INVALID_TILE;
03028 }
03029 return &this->stations;
03030 }
03031
03032 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03033 {
03034
03035 if (amount == 0) return 0;
03036
03037 Station *st1 = NULL;
03038 Station *st2 = NULL;
03039 uint best_rating1 = 0;
03040 uint best_rating2 = 0;
03041
03042 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03043 Station *st = *st_iter;
03044
03045
03046 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03047
03048 if (st->goods[type].rating == 0) continue;
03049
03050 if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue;
03051
03052 if (IsCargoInClass(type, CC_PASSENGERS)) {
03053 if (st->facilities == FACIL_TRUCK_STOP) continue;
03054 } else {
03055 if (st->facilities == FACIL_BUS_STOP) continue;
03056 }
03057
03058
03059 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03060 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03061 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03062 st2 = st; best_rating2 = st->goods[type].rating;
03063 }
03064 }
03065
03066
03067 if (st1 == NULL) return 0;
03068
03069 if (st2 == NULL) {
03070
03071 uint moved = amount * best_rating1 / 256 + 1;
03072 UpdateStationWaiting(st1, type, moved, source_type, source_id);
03073 return moved;
03074 }
03075
03076
03077 assert(st1 != NULL);
03078 assert(st2 != NULL);
03079 assert(best_rating1 != 0 || best_rating2 != 0);
03080
03081
03082 best_rating2 >>= 1;
03083
03084
03085 uint t = (best_rating1 * (amount + 1)) / (best_rating1 + best_rating2);
03086
03087 uint moved = 0;
03088 if (t != 0) {
03089 moved = t * best_rating1 / 256 + 1;
03090 amount -= t;
03091 UpdateStationWaiting(st1, type, moved, source_type, source_id);
03092 }
03093
03094 if (amount != 0) {
03095 amount = amount * best_rating2 / 256 + 1;
03096 moved += amount;
03097 UpdateStationWaiting(st2, type, amount, source_type, source_id);
03098 }
03099
03100 return moved;
03101 }
03102
03103 void BuildOilRig(TileIndex tile)
03104 {
03105 if (!Station::CanAllocateItem()) {
03106 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03107 return;
03108 }
03109
03110 Station *st = new Station(tile);
03111 st->town = ClosestTownFromTile(tile, UINT_MAX);
03112
03113 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03114
03115 assert(IsTileType(tile, MP_INDUSTRY));
03116 DeleteAnimatedTile(tile);
03117 MakeOilrig(tile, st->index, GetWaterClass(tile));
03118
03119 st->owner = OWNER_NONE;
03120 st->airport_type = AT_OILRIG;
03121 st->airport_tile = tile;
03122 st->dock_tile = tile;
03123 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03124 st->build_date = _date;
03125
03126 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03127
03128 for (CargoID j = 0; j < NUM_CARGO; j++) {
03129 st->goods[j].acceptance_pickup = 0;
03130 st->goods[j].days_since_pickup = 255;
03131 st->goods[j].rating = INITIAL_STATION_RATING;
03132 st->goods[j].last_speed = 0;
03133 st->goods[j].last_age = 255;
03134 }
03135
03136 st->UpdateVirtCoord();
03137 UpdateStationAcceptance(st, false);
03138 st->RecomputeIndustriesNear();
03139 }
03140
03141 void DeleteOilRig(TileIndex tile)
03142 {
03143 Station *st = Station::GetByTile(tile);
03144
03145 MakeWaterKeepingClass(tile, OWNER_NONE);
03146 MarkTileDirtyByTile(tile);
03147
03148 st->dock_tile = INVALID_TILE;
03149 st->airport_tile = INVALID_TILE;
03150 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03151 st->airport_flags = 0;
03152
03153 st->rect.AfterRemoveTile(st, tile);
03154
03155 st->UpdateVirtCoord();
03156 st->RecomputeIndustriesNear();
03157 if (!st->IsInUse()) delete st;
03158 }
03159
03160 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03161 {
03162 if (IsDriveThroughStopTile(tile)) {
03163 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03164
03165 if (GetRoadOwner(tile, rt) == old_owner) {
03166 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03167 }
03168 }
03169 }
03170
03171 if (!IsTileOwner(tile, old_owner)) return;
03172
03173 if (new_owner != INVALID_OWNER) {
03174
03175 SetTileOwner(tile, new_owner);
03176 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03177 } else {
03178 if (IsDriveThroughStopTile(tile)) {
03179
03180 DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03181 assert(IsTileType(tile, MP_ROAD));
03182
03183 ChangeTileOwner(tile, old_owner, new_owner);
03184 } else {
03185 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03186
03187
03188
03189 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03190 }
03191 }
03192 }
03193
03202 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03203 {
03204
03205 if (_current_company == OWNER_WATER) return true;
03206
03207 Owner road_owner = _current_company;
03208 Owner tram_owner = _current_company;
03209
03210 RoadTypes rts = GetRoadTypes(tile);
03211 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03212 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03213
03214 if ((road_owner != OWNER_TOWN && !CheckOwnership(road_owner)) || !CheckOwnership(tram_owner)) return false;
03215
03216 return road_owner != OWNER_TOWN || CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags);
03217 }
03218
03219 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03220 {
03221 if (flags & DC_AUTO) {
03222 switch (GetStationType(tile)) {
03223 default: break;
03224 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03225 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03226 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03227 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);
03228 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);
03229 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03230 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03231 case STATION_OILRIG:
03232 SetDParam(0, STR_INDUSTRY_NAME_OIL_RIG);
03233 return_cmd_error(STR_ERROR_UNMOVABLE_OBJECT_IN_THE_WAY);
03234 }
03235 }
03236
03237 switch (GetStationType(tile)) {
03238 case STATION_RAIL: return RemoveRailStation(tile, flags);
03239 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03240 case STATION_AIRPORT: return RemoveAirport(tile, flags);
03241 case STATION_TRUCK:
03242 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
03243 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03244 return RemoveRoadStop(tile, flags);
03245 case STATION_BUS:
03246 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags))
03247 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03248 return RemoveRoadStop(tile, flags);
03249 case STATION_BUOY: return RemoveBuoy(tile, flags);
03250 case STATION_DOCK: return RemoveDock(tile, flags);
03251 default: break;
03252 }
03253
03254 return CMD_ERROR;
03255 }
03256
03257 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03258 {
03259 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03260
03261
03262
03263 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03264 switch (GetStationType(tile)) {
03265 case STATION_WAYPOINT:
03266 case STATION_RAIL: {
03267 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03268 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03269 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03270 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03271 }
03272
03273 case STATION_AIRPORT:
03274 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03275
03276 case STATION_TRUCK:
03277 case STATION_BUS: {
03278 DiagDirection direction = GetRoadStopDir(tile);
03279 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03280 if (IsDriveThroughStopTile(tile)) {
03281 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03282 }
03283 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03284 }
03285
03286 default: break;
03287 }
03288 }
03289 }
03290 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03291 }
03292
03293
03294 extern const TileTypeProcs _tile_type_station_procs = {
03295 DrawTile_Station,
03296 GetSlopeZ_Station,
03297 ClearTile_Station,
03298 NULL,
03299 GetTileDesc_Station,
03300 GetTileTrackStatus_Station,
03301 ClickTile_Station,
03302 AnimateTile_Station,
03303 TileLoop_Station,
03304 ChangeTileOwner_Station,
03305 NULL,
03306 VehicleEnter_Station,
03307 GetFoundation_Station,
03308 TerraformTile_Station,
03309 };