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