00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "aircraft.h"
00014 #include "bridge_map.h"
00015 #include "cmd_helper.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "town.h"
00019 #include "news_func.h"
00020 #include "train.h"
00021 #include "ship.h"
00022 #include "roadveh.h"
00023 #include "industry.h"
00024 #include "newgrf_cargo.h"
00025 #include "newgrf_debug.h"
00026 #include "newgrf_station.h"
00027 #include "newgrf_canal.h"
00028 #include "pathfinder/yapf/yapf_cache.h"
00029 #include "road_internal.h"
00030 #include "autoslope.h"
00031 #include "water.h"
00032 #include "strings_func.h"
00033 #include "clear_func.h"
00034 #include "date_func.h"
00035 #include "vehicle_func.h"
00036 #include "string_func.h"
00037 #include "animated_tile_func.h"
00038 #include "elrail_func.h"
00039 #include "station_base.h"
00040 #include "roadstop_base.h"
00041 #include "newgrf_railtype.h"
00042 #include "waypoint_base.h"
00043 #include "waypoint_func.h"
00044 #include "pbs.h"
00045 #include "debug.h"
00046 #include "core/random_func.hpp"
00047 #include "company_base.h"
00048 #include "table/airporttile_ids.h"
00049 #include "newgrf_airporttiles.h"
00050 #include "order_backup.h"
00051 #include "newgrf_house.h"
00052 #include "company_gui.h"
00053 #include "linkgraph/linkgraph_base.h"
00054 #include "linkgraph/refresh.h"
00055 #include "widgets/station_widget.h"
00056
00057 #include "table/strings.h"
00058
00065 bool IsHangar(TileIndex t)
00066 {
00067 assert(IsTileType(t, MP_STATION));
00068
00069
00070 if (!IsAirport(t)) return false;
00071
00072 const Station *st = Station::GetByTile(t);
00073 const AirportSpec *as = st->airport.GetSpec();
00074
00075 for (uint i = 0; i < as->nof_depots; i++) {
00076 if (st->airport.GetHangarTile(i) == t) return true;
00077 }
00078
00079 return false;
00080 }
00081
00089 template <class T>
00090 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
00091 {
00092 ta.tile -= TileDiffXY(1, 1);
00093 ta.w += 2;
00094 ta.h += 2;
00095
00096
00097 TILE_AREA_LOOP(tile_cur, ta) {
00098 if (IsTileType(tile_cur, MP_STATION)) {
00099 StationID t = GetStationIndex(tile_cur);
00100 if (!T::IsValidID(t)) continue;
00101
00102 if (closest_station == INVALID_STATION) {
00103 closest_station = t;
00104 } else if (closest_station != t) {
00105 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00106 }
00107 }
00108 }
00109 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
00110 return CommandCost();
00111 }
00112
00118 typedef bool (*CMSAMatcher)(TileIndex tile);
00119
00126 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
00127 {
00128 int num = 0;
00129
00130 for (int dx = -3; dx <= 3; dx++) {
00131 for (int dy = -3; dy <= 3; dy++) {
00132 TileIndex t = TileAddWrap(tile, dx, dy);
00133 if (t != INVALID_TILE && cmp(t)) num++;
00134 }
00135 }
00136
00137 return num;
00138 }
00139
00145 static bool CMSAMine(TileIndex tile)
00146 {
00147
00148 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00149
00150 const Industry *ind = Industry::GetByTile(tile);
00151
00152
00153 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
00154
00155 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
00156
00157
00158 if (ind->produced_cargo[i] != CT_INVALID &&
00159 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
00160 return true;
00161 }
00162 }
00163
00164 return false;
00165 }
00166
00172 static bool CMSAWater(TileIndex tile)
00173 {
00174 return IsTileType(tile, MP_WATER) && IsWater(tile);
00175 }
00176
00182 static bool CMSATree(TileIndex tile)
00183 {
00184 return IsTileType(tile, MP_TREES);
00185 }
00186
00187 #define M(x) ((x) - STR_SV_STNAME)
00188
00189 enum StationNaming {
00190 STATIONNAMING_RAIL,
00191 STATIONNAMING_ROAD,
00192 STATIONNAMING_AIRPORT,
00193 STATIONNAMING_OILRIG,
00194 STATIONNAMING_DOCK,
00195 STATIONNAMING_HELIPORT,
00196 };
00197
00199 struct StationNameInformation {
00200 uint32 free_names;
00201 bool *indtypes;
00202 };
00203
00212 static bool FindNearIndustryName(TileIndex tile, void *user_data)
00213 {
00214
00215 StationNameInformation *sni = (StationNameInformation*)user_data;
00216 if (!IsTileType(tile, MP_INDUSTRY)) return false;
00217
00218
00219 IndustryType indtype = GetIndustryType(tile);
00220 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
00221
00222
00223
00224 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
00225 return !sni->indtypes[indtype];
00226 }
00227
00228 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
00229 {
00230 static const uint32 _gen_station_name_bits[] = {
00231 0,
00232 0,
00233 1U << M(STR_SV_STNAME_AIRPORT),
00234 1U << M(STR_SV_STNAME_OILFIELD),
00235 1U << M(STR_SV_STNAME_DOCKS),
00236 1U << M(STR_SV_STNAME_HELIPORT),
00237 };
00238
00239 const Town *t = st->town;
00240 uint32 free_names = UINT32_MAX;
00241
00242 bool indtypes[NUM_INDUSTRYTYPES];
00243 memset(indtypes, 0, sizeof(indtypes));
00244
00245 const Station *s;
00246 FOR_ALL_STATIONS(s) {
00247 if (s != st && s->town == t) {
00248 if (s->indtype != IT_INVALID) {
00249 indtypes[s->indtype] = true;
00250 StringID name = GetIndustrySpec(s->indtype)->station_name;
00251 if (name != STR_UNDEFINED) {
00252
00253 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
00254 const IndustrySpec *indsp = GetIndustrySpec(it);
00255 if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
00256 }
00257 }
00258 continue;
00259 }
00260 uint str = M(s->string_id);
00261 if (str <= 0x20) {
00262 if (str == M(STR_SV_STNAME_FOREST)) {
00263 str = M(STR_SV_STNAME_WOODS);
00264 }
00265 ClrBit(free_names, str);
00266 }
00267 }
00268 }
00269
00270 TileIndex indtile = tile;
00271 StationNameInformation sni = { free_names, indtypes };
00272 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
00273
00274 IndustryType indtype = GetIndustryType(indtile);
00275 const IndustrySpec *indsp = GetIndustrySpec(indtype);
00276
00277 if (indsp->station_name != STR_NULL) {
00278 st->indtype = indtype;
00279 return STR_SV_STNAME_FALLBACK;
00280 }
00281 }
00282
00283
00284 free_names = sni.free_names;
00285
00286
00287 uint32 tmp = free_names & _gen_station_name_bits[name_class];
00288 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
00289
00290
00291 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
00292 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
00293 return STR_SV_STNAME_MINES;
00294 }
00295 }
00296
00297
00298 if (DistanceMax(tile, t->xy) < 8) {
00299 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
00300
00301 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
00302 }
00303
00304
00305 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
00306 DistanceFromEdge(tile) < 20 &&
00307 CountMapSquareAround(tile, CMSAWater) >= 5) {
00308 return STR_SV_STNAME_LAKESIDE;
00309 }
00310
00311
00312 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
00313 CountMapSquareAround(tile, CMSATree) >= 8 ||
00314 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
00315 ) {
00316 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
00317 }
00318
00319
00320 int z = GetTileZ(tile);
00321 int z2 = GetTileZ(t->xy);
00322 if (z < z2) {
00323 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
00324 } else if (z > z2) {
00325 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
00326 }
00327
00328
00329 static const int8 _direction_and_table[] = {
00330 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00331 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00332 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
00333 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
00334 };
00335
00336 free_names &= _direction_and_table[
00337 (TileX(tile) < TileX(t->xy)) +
00338 (TileY(tile) < TileY(t->xy)) * 2];
00339
00340 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));
00341 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
00342 }
00343 #undef M
00344
00350 static Station *GetClosestDeletedStation(TileIndex tile)
00351 {
00352 uint threshold = 8;
00353 Station *best_station = NULL;
00354 Station *st;
00355
00356 FOR_ALL_STATIONS(st) {
00357 if (!st->IsInUse() && st->owner == _current_company) {
00358 uint cur_dist = DistanceManhattan(tile, st->xy);
00359
00360 if (cur_dist < threshold) {
00361 threshold = cur_dist;
00362 best_station = st;
00363 }
00364 }
00365 }
00366
00367 return best_station;
00368 }
00369
00370
00371 void Station::GetTileArea(TileArea *ta, StationType type) const
00372 {
00373 switch (type) {
00374 case STATION_RAIL:
00375 *ta = this->train_station;
00376 return;
00377
00378 case STATION_AIRPORT:
00379 *ta = this->airport;
00380 return;
00381
00382 case STATION_TRUCK:
00383 *ta = this->truck_station;
00384 return;
00385
00386 case STATION_BUS:
00387 *ta = this->bus_station;
00388 return;
00389
00390 case STATION_DOCK:
00391 case STATION_OILRIG:
00392 ta->tile = this->dock_tile;
00393 break;
00394
00395 default: NOT_REACHED();
00396 }
00397
00398 ta->w = 1;
00399 ta->h = 1;
00400 }
00401
00405 void Station::UpdateVirtCoord()
00406 {
00407 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00408
00409 pt.y -= 32 * ZOOM_LVL_BASE;
00410 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
00411
00412 SetDParam(0, this->index);
00413 SetDParam(1, this->facilities);
00414 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
00415
00416 SetWindowDirty(WC_STATION_VIEW, this->index);
00417 }
00418
00420 void UpdateAllStationVirtCoords()
00421 {
00422 BaseStation *st;
00423
00424 FOR_ALL_BASE_STATIONS(st) {
00425 st->UpdateVirtCoord();
00426 }
00427 }
00428
00434 static uint GetAcceptanceMask(const Station *st)
00435 {
00436 uint mask = 0;
00437
00438 for (CargoID i = 0; i < NUM_CARGO; i++) {
00439 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
00440 }
00441 return mask;
00442 }
00443
00448 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
00449 {
00450 for (uint i = 0; i < num_items; i++) {
00451 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
00452 }
00453
00454 SetDParam(0, st->index);
00455 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
00456 }
00457
00465 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
00466 {
00467 CargoArray produced;
00468
00469 int x = TileX(tile);
00470 int y = TileY(tile);
00471
00472
00473
00474 int x2 = min(x + w + rad, MapSizeX());
00475 int x1 = max(x - rad, 0);
00476
00477 int y2 = min(y + h + rad, MapSizeY());
00478 int y1 = max(y - rad, 0);
00479
00480 assert(x1 < x2);
00481 assert(y1 < y2);
00482 assert(w > 0);
00483 assert(h > 0);
00484
00485 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
00486
00487
00488
00489 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
00490
00491
00492
00493
00494
00495
00496
00497 const Industry *i;
00498 FOR_ALL_INDUSTRIES(i) {
00499 if (!ta.Intersects(i->location)) continue;
00500
00501 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00502 CargoID cargo = i->produced_cargo[j];
00503 if (cargo != CT_INVALID) produced[cargo]++;
00504 }
00505 }
00506
00507 return produced;
00508 }
00509
00518 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
00519 {
00520 CargoArray acceptance;
00521 if (always_accepted != NULL) *always_accepted = 0;
00522
00523 int x = TileX(tile);
00524 int y = TileY(tile);
00525
00526
00527
00528 int x2 = min(x + w + rad, MapSizeX());
00529 int y2 = min(y + h + rad, MapSizeY());
00530 int x1 = max(x - rad, 0);
00531 int y1 = max(y - rad, 0);
00532
00533 assert(x1 < x2);
00534 assert(y1 < y2);
00535 assert(w > 0);
00536 assert(h > 0);
00537
00538 for (int yc = y1; yc != y2; yc++) {
00539 for (int xc = x1; xc != x2; xc++) {
00540 TileIndex tile = TileXY(xc, yc);
00541 AddAcceptedCargo(tile, acceptance, always_accepted);
00542 }
00543 }
00544
00545 return acceptance;
00546 }
00547
00553 void UpdateStationAcceptance(Station *st, bool show_msg)
00554 {
00555
00556 uint old_acc = GetAcceptanceMask(st);
00557
00558
00559 CargoArray acceptance;
00560 if (!st->rect.IsEmpty()) {
00561 acceptance = GetAcceptanceAroundTiles(
00562 TileXY(st->rect.left, st->rect.top),
00563 st->rect.right - st->rect.left + 1,
00564 st->rect.bottom - st->rect.top + 1,
00565 st->GetCatchmentRadius(),
00566 &st->always_accepted
00567 );
00568 }
00569
00570
00571 for (CargoID i = 0; i < NUM_CARGO; i++) {
00572 uint amt = acceptance[i];
00573
00574
00575 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
00576 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
00577 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
00578 amt = 0;
00579 }
00580
00581 GoodsEntry &ge = st->goods[i];
00582 SB(ge.acceptance_pickup, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
00583 if (LinkGraph::IsValidID(ge.link_graph)) {
00584 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
00585 }
00586 }
00587
00588
00589 uint new_acc = GetAcceptanceMask(st);
00590 if (old_acc == new_acc) return;
00591
00592
00593 if (show_msg && st->owner == _local_company && st->IsInUse()) {
00594
00595
00596 static const StringID accept_msg[] = {
00597 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
00598 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
00599 };
00600 static const StringID reject_msg[] = {
00601 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
00602 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
00603 };
00604
00605
00606 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
00607 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
00608 uint num_acc = 0;
00609 uint num_rej = 0;
00610
00611
00612 for (CargoID i = 0; i < NUM_CARGO; i++) {
00613 if (HasBit(new_acc, i)) {
00614 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
00615
00616 accepts[num_acc++] = i;
00617 }
00618 } else {
00619 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
00620
00621 rejects[num_rej++] = i;
00622 }
00623 }
00624 }
00625
00626
00627 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
00628 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
00629 }
00630
00631
00632 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
00633 }
00634
00635 static void UpdateStationSignCoord(BaseStation *st)
00636 {
00637 const StationRect *r = &st->rect;
00638
00639 if (r->IsEmpty()) return;
00640
00641
00642 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
00643 st->UpdateVirtCoord();
00644 }
00645
00655 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
00656 {
00657
00658 if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
00659
00660 if (*st != NULL) {
00661 if ((*st)->owner != _current_company) {
00662 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
00663 }
00664
00665 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
00666 if (ret.Failed()) return ret;
00667 } else {
00668
00669 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00670
00671 if (flags & DC_EXEC) {
00672 *st = new Station(area.tile);
00673
00674 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
00675 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
00676
00677 if (Company::IsValidID(_current_company)) {
00678 SetBit((*st)->town->have_ratings, _current_company);
00679 }
00680 }
00681 }
00682 return CommandCost();
00683 }
00684
00691 static void DeleteStationIfEmpty(BaseStation *st)
00692 {
00693 if (!st->IsInUse()) {
00694 st->delete_ctr = 0;
00695 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00696 }
00697
00698 UpdateStationSignCoord(st);
00699 }
00700
00701 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00702
00712 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00713 {
00714 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00715 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00716 }
00717
00718 CommandCost ret = EnsureNoVehicleOnGround(tile);
00719 if (ret.Failed()) return ret;
00720
00721 int z;
00722 Slope tileh = GetTileSlope(tile, &z);
00723
00724
00725
00726
00727
00728 if ((!allow_steep && IsSteepSlope(tileh)) ||
00729 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00730 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00731 }
00732
00733 CommandCost cost(EXPENSES_CONSTRUCTION);
00734 int flat_z = z + GetSlopeMaxZ(tileh);
00735 if (tileh != SLOPE_FLAT) {
00736
00737 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00738 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00739 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00740 }
00741 }
00742 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00743 }
00744
00745
00746 if (allowed_z < 0) {
00747
00748 allowed_z = flat_z;
00749 } else if (allowed_z != flat_z) {
00750 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00751 }
00752
00753 return cost;
00754 }
00755
00762 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00763 {
00764 CommandCost cost(EXPENSES_CONSTRUCTION);
00765 int allowed_z = -1;
00766
00767 TILE_AREA_LOOP(tile_cur, tile_area) {
00768 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00769 if (ret.Failed()) return ret;
00770 cost.AddCost(ret);
00771
00772 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00773 if (ret.Failed()) return ret;
00774 cost.AddCost(ret);
00775 }
00776
00777 return cost;
00778 }
00779
00794 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, SmallVector<Train *, 4> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
00795 {
00796 CommandCost cost(EXPENSES_CONSTRUCTION);
00797 int allowed_z = -1;
00798 uint invalid_dirs = 5 << axis;
00799
00800 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
00801 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00802
00803 TILE_AREA_LOOP(tile_cur, tile_area) {
00804 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00805 if (ret.Failed()) return ret;
00806 cost.AddCost(ret);
00807
00808 if (slope_cb) {
00809
00810 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00811 if (ret.Failed()) return ret;
00812 }
00813
00814
00815
00816
00817 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00818 if (!IsRailStation(tile_cur)) {
00819 return ClearTile_Station(tile_cur, DC_AUTO);
00820 } else {
00821 StationID st = GetStationIndex(tile_cur);
00822 if (*station == INVALID_STATION) {
00823 *station = st;
00824 } else if (*station != st) {
00825 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00826 }
00827 }
00828 } else {
00829
00830
00831 if (rt != INVALID_RAILTYPE &&
00832 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00833 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00834
00835
00836
00837
00838
00839
00840 TrackBits tracks = GetTrackBits(tile_cur);
00841 Track track = RemoveFirstTrack(&tracks);
00842 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00843
00844 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00845
00846 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00847 Train *v = GetTrainForReservation(tile_cur, track);
00848 if (v != NULL) {
00849 *affected_vehicles.Append() = v;
00850 }
00851 }
00852 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00853 if (ret.Failed()) return ret;
00854 cost.AddCost(ret);
00855
00856 continue;
00857 }
00858 }
00859 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00860 if (ret.Failed()) return ret;
00861 cost.AddCost(ret);
00862 }
00863 }
00864
00865 return cost;
00866 }
00867
00880 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadTypes rts)
00881 {
00882 CommandCost cost(EXPENSES_CONSTRUCTION);
00883 int allowed_z = -1;
00884
00885 TILE_AREA_LOOP(cur_tile, tile_area) {
00886 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00887 if (ret.Failed()) return ret;
00888 cost.AddCost(ret);
00889
00890
00891
00892
00893 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00894 if (!IsRoadStop(cur_tile)) {
00895 return ClearTile_Station(cur_tile, DC_AUTO);
00896 } else {
00897 if (is_truck_stop != IsTruckStop(cur_tile) ||
00898 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00899 return ClearTile_Station(cur_tile, DC_AUTO);
00900 }
00901
00902 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00903 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00904 }
00905 StationID st = GetStationIndex(cur_tile);
00906 if (*station == INVALID_STATION) {
00907 *station = st;
00908 } else if (*station != st) {
00909 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00910 }
00911 }
00912 } else {
00913 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00914
00915 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00916 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00917
00918 switch (CountBits(rb)) {
00919 case 1:
00920 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00921
00922 case 2:
00923 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00924 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00925
00926 default:
00927 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00928 }
00929 }
00930
00931 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00932 uint num_roadbits = 0;
00933 if (build_over_road) {
00934
00935 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00936 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00937 if (road_owner == OWNER_TOWN) {
00938 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00939 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00940 CommandCost ret = CheckOwnership(road_owner);
00941 if (ret.Failed()) return ret;
00942 }
00943 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00944 }
00945
00946
00947 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00948 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00949 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00950 CommandCost ret = CheckOwnership(tram_owner);
00951 if (ret.Failed()) return ret;
00952 }
00953 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00954 }
00955
00956
00957 rts |= cur_rts;
00958 } else {
00959 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00960 if (ret.Failed()) return ret;
00961 cost.AddCost(ret);
00962 }
00963
00964 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00965 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00966 }
00967 }
00968
00969 return cost;
00970 }
00971
00979 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00980 {
00981 TileArea cur_ta = st->train_station;
00982
00983
00984 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00985 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00986 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00987 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00988 new_ta.tile = TileXY(x, y);
00989
00990
00991 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00992 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00993 }
00994
00995 return CommandCost();
00996 }
00997
00998 static inline byte *CreateSingle(byte *layout, int n)
00999 {
01000 int i = n;
01001 do *layout++ = 0; while (--i);
01002 layout[((n - 1) >> 1) - n] = 2;
01003 return layout;
01004 }
01005
01006 static inline byte *CreateMulti(byte *layout, int n, byte b)
01007 {
01008 int i = n;
01009 do *layout++ = b; while (--i);
01010 if (n > 4) {
01011 layout[0 - n] = 0;
01012 layout[n - 1 - n] = 0;
01013 }
01014 return layout;
01015 }
01016
01024 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
01025 {
01026 if (statspec != NULL && statspec->lengths >= plat_len &&
01027 statspec->platforms[plat_len - 1] >= numtracks &&
01028 statspec->layouts[plat_len - 1][numtracks - 1]) {
01029
01030 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
01031 plat_len * numtracks);
01032 return;
01033 }
01034
01035 if (plat_len == 1) {
01036 CreateSingle(layout, numtracks);
01037 } else {
01038 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
01039 numtracks >>= 1;
01040
01041 while (--numtracks >= 0) {
01042 layout = CreateMulti(layout, plat_len, 4);
01043 layout = CreateMulti(layout, plat_len, 6);
01044 }
01045 }
01046 }
01047
01059 template <class T, StringID error_message>
01060 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01061 {
01062 assert(*st == NULL);
01063 bool check_surrounding = true;
01064
01065 if (_settings_game.station.adjacent_stations) {
01066 if (existing_station != INVALID_STATION) {
01067 if (adjacent && existing_station != station_to_join) {
01068
01069
01070 return_cmd_error(error_message);
01071 } else {
01072
01073
01074 *st = T::GetIfValid(existing_station);
01075 check_surrounding = (*st == NULL);
01076 }
01077 } else {
01078
01079
01080 if (adjacent) check_surrounding = false;
01081 }
01082 }
01083
01084 if (check_surrounding) {
01085
01086 CommandCost ret = GetStationAround(ta, existing_station, st);
01087 if (ret.Failed()) return ret;
01088 }
01089
01090
01091 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01092
01093 return CommandCost();
01094 }
01095
01105 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01106 {
01107 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01108 }
01109
01119 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01120 {
01121 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01122 }
01123
01141 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01142 {
01143
01144 RailType rt = Extract<RailType, 0, 4>(p1);
01145 Axis axis = Extract<Axis, 4, 1>(p1);
01146 byte numtracks = GB(p1, 8, 8);
01147 byte plat_len = GB(p1, 16, 8);
01148 bool adjacent = HasBit(p1, 24);
01149
01150 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01151 byte spec_index = GB(p2, 8, 8);
01152 StationID station_to_join = GB(p2, 16, 16);
01153
01154
01155 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01156 if (ret.Failed()) return ret;
01157
01158 if (!ValParamRailtype(rt)) return CMD_ERROR;
01159
01160
01161 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01162 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
01163 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01164
01165 int w_org, h_org;
01166 if (axis == AXIS_X) {
01167 w_org = plat_len;
01168 h_org = numtracks;
01169 } else {
01170 h_org = plat_len;
01171 w_org = numtracks;
01172 }
01173
01174 bool reuse = (station_to_join != NEW_STATION);
01175 if (!reuse) station_to_join = INVALID_STATION;
01176 bool distant_join = (station_to_join != INVALID_STATION);
01177
01178 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01179
01180 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01181
01182
01183 TileArea new_location(tile_org, w_org, h_org);
01184
01185
01186 StationID est = INVALID_STATION;
01187 SmallVector<Train *, 4> affected_vehicles;
01188
01189 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01190 if (cost.Failed()) return cost;
01191
01192 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01193 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01194
01195 Station *st = NULL;
01196 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01197 if (ret.Failed()) return ret;
01198
01199 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
01200 if (ret.Failed()) return ret;
01201
01202 if (st != NULL && st->train_station.tile != INVALID_TILE) {
01203 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01204 if (ret.Failed()) return ret;
01205 }
01206
01207
01208 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
01209 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01210 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01211
01212 if (statspec != NULL) {
01213
01214
01215
01216 if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
01217 return CMD_ERROR;
01218 }
01219
01220
01221 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01222 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01223 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01224 }
01225 }
01226
01227 if (flags & DC_EXEC) {
01228 TileIndexDiff tile_delta;
01229 byte *layout_ptr;
01230 byte numtracks_orig;
01231 Track track;
01232
01233 st->train_station = new_location;
01234 st->AddFacility(FACIL_TRAIN, new_location.tile);
01235
01236 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01237
01238 if (statspec != NULL) {
01239
01240
01241 st->cached_anim_triggers |= statspec->animation.triggers;
01242 }
01243
01244 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01245 track = AxisToTrack(axis);
01246
01247 layout_ptr = AllocaM(byte, numtracks * plat_len);
01248 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01249
01250 numtracks_orig = numtracks;
01251
01252 Company *c = Company::Get(st->owner);
01253 TileIndex tile_track = tile_org;
01254 do {
01255 TileIndex tile = tile_track;
01256 int w = plat_len;
01257 do {
01258 byte layout = *layout_ptr++;
01259 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01260
01261 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01262 if (v != NULL) {
01263 FreeTrainTrackReservation(v);
01264 *affected_vehicles.Append() = v;
01265 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01266 for (; v->Next() != NULL; v = v->Next()) { }
01267 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01268 }
01269 }
01270
01271
01272 if (IsRailStationTile(tile)) {
01273 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01274 c->infrastructure.station--;
01275 }
01276
01277
01278 DeleteAnimatedTile(tile);
01279 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01280 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01281
01282 DeallocateSpecFromStation(st, old_specindex);
01283
01284 SetCustomStationSpecIndex(tile, specindex);
01285 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01286 SetAnimationFrame(tile, 0);
01287
01288 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01289 c->infrastructure.station++;
01290
01291 if (statspec != NULL) {
01292
01293 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01294
01295
01296 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01297 if (callback != CALLBACK_FAILED) {
01298 if (callback < 8) {
01299 SetStationGfx(tile, (callback & ~1) + axis);
01300 } else {
01301 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01302 }
01303 }
01304
01305
01306 TriggerStationAnimation(st, tile, SAT_BUILT);
01307 }
01308
01309 tile += tile_delta;
01310 } while (--w);
01311 AddTrackToSignalBuffer(tile_track, track, _current_company);
01312 YapfNotifyTrackLayoutChange(tile_track, track);
01313 tile_track += tile_delta ^ TileDiffXY(1, 1);
01314 } while (--numtracks);
01315
01316 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01317
01318 Train *v = affected_vehicles[i];
01319 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01320 TryPathReserve(v, true, true);
01321 for (; v->Next() != NULL; v = v->Next()) { }
01322 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01323 }
01324
01325
01326 TileArea update_reservation_area;
01327 if (axis == AXIS_X) {
01328 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
01329 } else {
01330 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
01331 }
01332
01333 TILE_AREA_LOOP(tile, update_reservation_area) {
01334
01335 if (IsStationTileBlocked(tile)) continue;
01336
01337 DiagDirection dir = AxisToDiagDir(axis);
01338 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
01339 TileIndex platform_begin = tile;
01340 TileIndex platform_end = tile;
01341
01342
01343 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
01344 platform_begin = next_tile;
01345 }
01346 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
01347 platform_end = next_tile;
01348 }
01349
01350
01351 bool reservation = false;
01352 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
01353 reservation = HasStationReservation(t);
01354 }
01355
01356 if (reservation) {
01357 SetRailStationPlatformReservation(platform_begin, dir, true);
01358 }
01359 }
01360
01361 st->MarkTilesDirty(false);
01362 st->UpdateVirtCoord();
01363 UpdateStationAcceptance(st, false);
01364 st->RecomputeIndustriesNear();
01365 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01366 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01367 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01368 DirtyCompanyInfrastructureWindows(st->owner);
01369 }
01370
01371 return cost;
01372 }
01373
01374 static void MakeRailStationAreaSmaller(BaseStation *st)
01375 {
01376 TileArea ta = st->train_station;
01377
01378 restart:
01379
01380
01381 if (ta.w != 0 && ta.h != 0) {
01382
01383 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01384
01385 if (++i == ta.h) {
01386 ta.tile += TileDiffXY(1, 0);
01387 ta.w--;
01388 goto restart;
01389 }
01390 }
01391
01392
01393 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01394
01395 if (++i == ta.h) {
01396 ta.w--;
01397 goto restart;
01398 }
01399 }
01400
01401
01402 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01403
01404 if (++i == ta.w) {
01405 ta.tile += TileDiffXY(0, 1);
01406 ta.h--;
01407 goto restart;
01408 }
01409 }
01410
01411
01412 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01413
01414 if (++i == ta.w) {
01415 ta.h--;
01416 goto restart;
01417 }
01418 }
01419 } else {
01420 ta.Clear();
01421 }
01422
01423 st->train_station = ta;
01424 }
01425
01436 template <class T>
01437 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01438 {
01439
01440 int quantity = 0;
01441 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01442
01443
01444
01445 CommandCost error;
01446
01447
01448 TILE_AREA_LOOP(tile, ta) {
01449
01450 if (!HasStationTileRail(tile)) continue;
01451
01452
01453 CommandCost ret = EnsureNoVehicleOnGround(tile);
01454 error.AddCost(ret);
01455 if (ret.Failed()) continue;
01456
01457
01458 T *st = T::GetByTile(tile);
01459 if (st == NULL) continue;
01460
01461 if (_current_company != OWNER_WATER) {
01462 CommandCost ret = CheckOwnership(st->owner);
01463 error.AddCost(ret);
01464 if (ret.Failed()) continue;
01465 }
01466
01467
01468 quantity++;
01469
01470 if (keep_rail || IsStationTileBlocked(tile)) {
01471
01472
01473 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01474 }
01475
01476 if (flags & DC_EXEC) {
01477
01478 uint specindex = GetCustomStationSpecIndex(tile);
01479 Track track = GetRailStationTrack(tile);
01480 Owner owner = GetTileOwner(tile);
01481 RailType rt = GetRailType(tile);
01482 Train *v = NULL;
01483
01484 if (HasStationReservation(tile)) {
01485 v = GetTrainForReservation(tile, track);
01486 if (v != NULL) {
01487
01488 FreeTrainTrackReservation(v);
01489 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01490 Vehicle *temp = v;
01491 for (; temp->Next() != NULL; temp = temp->Next()) { }
01492 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01493 }
01494 }
01495
01496 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01497 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01498
01499 DoClearSquare(tile);
01500 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01501 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01502 Company::Get(owner)->infrastructure.station--;
01503 DirtyCompanyInfrastructureWindows(owner);
01504
01505 st->rect.AfterRemoveTile(st, tile);
01506 AddTrackToSignalBuffer(tile, track, owner);
01507 YapfNotifyTrackLayoutChange(tile, track);
01508
01509 DeallocateSpecFromStation(st, specindex);
01510
01511 affected_stations.Include(st);
01512
01513 if (v != NULL) {
01514
01515 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01516 TryPathReserve(v, true, true);
01517 for (; v->Next() != NULL; v = v->Next()) { }
01518 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01519 }
01520 }
01521 }
01522
01523 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
01524
01525 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01526 T *st = *stp;
01527
01528
01529
01530
01531 MakeRailStationAreaSmaller(st);
01532 UpdateStationSignCoord(st);
01533
01534
01535 if (st->train_station.tile == INVALID_TILE) {
01536 st->facilities &= ~FACIL_TRAIN;
01537 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01538 st->UpdateVirtCoord();
01539 DeleteStationIfEmpty(st);
01540 }
01541 }
01542
01543 total_cost.AddCost(quantity * removal_cost);
01544 return total_cost;
01545 }
01546
01558 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01559 {
01560 TileIndex end = p1 == 0 ? start : p1;
01561 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01562
01563 TileArea ta(start, end);
01564 SmallVector<Station *, 4> affected_stations;
01565
01566 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01567 if (ret.Failed()) return ret;
01568
01569
01570 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01571 Station *st = *stp;
01572
01573 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01574 st->MarkTilesDirty(false);
01575 st->RecomputeIndustriesNear();
01576 }
01577
01578
01579 return ret;
01580 }
01581
01593 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01594 {
01595 TileIndex end = p1 == 0 ? start : p1;
01596 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01597
01598 TileArea ta(start, end);
01599 SmallVector<Waypoint *, 4> affected_stations;
01600
01601 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01602 }
01603
01604
01612 template <class T>
01613 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01614 {
01615
01616 if (_current_company != OWNER_WATER) {
01617 CommandCost ret = CheckOwnership(st->owner);
01618 if (ret.Failed()) return ret;
01619 }
01620
01621
01622 TileArea ta = st->train_station;
01623
01624 assert(ta.w != 0 && ta.h != 0);
01625
01626 CommandCost cost(EXPENSES_CONSTRUCTION);
01627
01628 TILE_AREA_LOOP(tile, ta) {
01629
01630 if (!st->TileBelongsToRailStation(tile)) continue;
01631
01632 CommandCost ret = EnsureNoVehicleOnGround(tile);
01633 if (ret.Failed()) return ret;
01634
01635 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01636 if (flags & DC_EXEC) {
01637
01638 Track track = GetRailStationTrack(tile);
01639 Owner owner = GetTileOwner(tile);
01640 Train *v = NULL;
01641 if (HasStationReservation(tile)) {
01642 v = GetTrainForReservation(tile, track);
01643 if (v != NULL) FreeTrainTrackReservation(v);
01644 }
01645 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01646 Company::Get(owner)->infrastructure.station--;
01647 DoClearSquare(tile);
01648 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01649 AddTrackToSignalBuffer(tile, track, owner);
01650 YapfNotifyTrackLayoutChange(tile, track);
01651 if (v != NULL) TryPathReserve(v, true);
01652 }
01653 }
01654
01655 if (flags & DC_EXEC) {
01656 st->rect.AfterRemoveRect(st, st->train_station);
01657
01658 st->train_station.Clear();
01659
01660 st->facilities &= ~FACIL_TRAIN;
01661
01662 free(st->speclist);
01663 st->num_specs = 0;
01664 st->speclist = NULL;
01665 st->cached_anim_triggers = 0;
01666
01667 DirtyCompanyInfrastructureWindows(st->owner);
01668 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01669 st->UpdateVirtCoord();
01670 DeleteStationIfEmpty(st);
01671 }
01672
01673 return cost;
01674 }
01675
01682 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01683 {
01684
01685 if (_current_company == OWNER_WATER) {
01686 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01687 }
01688
01689 Station *st = Station::GetByTile(tile);
01690 CommandCost cost = RemoveRailStation(st, flags);
01691
01692 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01693
01694 return cost;
01695 }
01696
01703 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01704 {
01705
01706 if (_current_company == OWNER_WATER) {
01707 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01708 }
01709
01710 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01711 }
01712
01713
01719 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01720 {
01721 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01722
01723 if (*primary_stop == NULL) {
01724
01725 return primary_stop;
01726 } else {
01727
01728 RoadStop *stop = *primary_stop;
01729 while (stop->next != NULL) stop = stop->next;
01730 return &stop->next;
01731 }
01732 }
01733
01734 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01735
01745 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01746 {
01747 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01748 }
01749
01766 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01767 {
01768 bool type = HasBit(p2, 0);
01769 bool is_drive_through = HasBit(p2, 1);
01770 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01771 StationID station_to_join = GB(p2, 16, 16);
01772 bool reuse = (station_to_join != NEW_STATION);
01773 if (!reuse) station_to_join = INVALID_STATION;
01774 bool distant_join = (station_to_join != INVALID_STATION);
01775
01776 uint8 width = (uint8)GB(p1, 0, 8);
01777 uint8 lenght = (uint8)GB(p1, 8, 8);
01778
01779
01780 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01781
01782 if (width == 0 || lenght == 0) return CMD_ERROR;
01783
01784 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01785
01786 TileArea roadstop_area(tile, width, lenght);
01787
01788 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01789
01790 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01791
01792
01793 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01794
01795 DiagDirection ddir;
01796 Axis axis;
01797 if (is_drive_through) {
01798
01799 axis = Extract<Axis, 6, 1>(p2);
01800 ddir = AxisToDiagDir(axis);
01801 } else {
01802
01803 ddir = Extract<DiagDirection, 6, 2>(p2);
01804 axis = DiagDirToAxis(ddir);
01805 }
01806
01807 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01808 if (ret.Failed()) return ret;
01809
01810
01811 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01812 StationID est = INVALID_STATION;
01813 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rts);
01814 if (ret.Failed()) return ret;
01815 cost.AddCost(ret);
01816
01817 Station *st = NULL;
01818 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01819 if (ret.Failed()) return ret;
01820
01821
01822 if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
01823
01824 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
01825 if (ret.Failed()) return ret;
01826
01827 if (flags & DC_EXEC) {
01828
01829 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01830 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01831 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01832 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01833
01834 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01835 RemoveRoadStop(cur_tile, flags);
01836 }
01837
01838 RoadStop *road_stop = new RoadStop(cur_tile);
01839
01840 RoadStop **currstop = FindRoadStopSpot(type, st);
01841 *currstop = road_stop;
01842
01843 if (type) {
01844 st->truck_station.Add(cur_tile);
01845 } else {
01846 st->bus_station.Add(cur_tile);
01847 }
01848
01849
01850 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01851
01852 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01853
01854 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01855 if (is_drive_through) {
01856
01857
01858 RoadType rt;
01859 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01860 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01861 if (c != NULL) {
01862 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01863 DirtyCompanyInfrastructureWindows(c->index);
01864 }
01865 }
01866
01867 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, axis);
01868 road_stop->MakeDriveThrough();
01869 } else {
01870
01871 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01872 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01873 }
01874 Company::Get(st->owner)->infrastructure.station++;
01875 DirtyCompanyInfrastructureWindows(st->owner);
01876
01877 MarkTileDirtyByTile(cur_tile);
01878 }
01879 }
01880
01881 if (st != NULL) {
01882 st->UpdateVirtCoord();
01883 UpdateStationAcceptance(st, false);
01884 st->RecomputeIndustriesNear();
01885 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01886 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01887 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01888 }
01889 return cost;
01890 }
01891
01892
01893 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01894 {
01895 if (v->type == VEH_ROAD) {
01896
01897
01898
01899
01900
01901
01902 RoadVehicle *rv = RoadVehicle::From(v);
01903 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01904 }
01905
01906 return NULL;
01907 }
01908
01909
01916 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01917 {
01918 Station *st = Station::GetByTile(tile);
01919
01920 if (_current_company != OWNER_WATER) {
01921 CommandCost ret = CheckOwnership(st->owner);
01922 if (ret.Failed()) return ret;
01923 }
01924
01925 bool is_truck = IsTruckStop(tile);
01926
01927 RoadStop **primary_stop;
01928 RoadStop *cur_stop;
01929 if (is_truck) {
01930 primary_stop = &st->truck_stops;
01931 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01932 } else {
01933 primary_stop = &st->bus_stops;
01934 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01935 }
01936
01937 assert(cur_stop != NULL);
01938
01939
01940 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01941
01942 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01943 } else {
01944 CommandCost ret = EnsureNoVehicleOnGround(tile);
01945 if (ret.Failed()) return ret;
01946 }
01947
01948 if (flags & DC_EXEC) {
01949 if (*primary_stop == cur_stop) {
01950
01951 *primary_stop = cur_stop->next;
01952
01953 if (*primary_stop == NULL) {
01954 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01955 }
01956 } else {
01957
01958 RoadStop *pred = *primary_stop;
01959 while (pred->next != cur_stop) pred = pred->next;
01960 pred->next = cur_stop->next;
01961 }
01962
01963
01964 RoadType rt;
01965 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01966 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01967 if (c != NULL) {
01968 c->infrastructure.road[rt] -= 2;
01969 DirtyCompanyInfrastructureWindows(c->index);
01970 }
01971 }
01972 Company::Get(st->owner)->infrastructure.station--;
01973
01974 if (IsDriveThroughStopTile(tile)) {
01975
01976 cur_stop->ClearDriveThrough();
01977 } else {
01978 DoClearSquare(tile);
01979 }
01980
01981 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01982 delete cur_stop;
01983
01984
01985 RoadVehicle *v;
01986 FOR_ALL_ROADVEHICLES(v) {
01987 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01988 v->dest_tile == tile) {
01989 v->dest_tile = v->GetOrderStationLocation(st->index);
01990 }
01991 }
01992
01993 st->rect.AfterRemoveTile(st, tile);
01994
01995 st->UpdateVirtCoord();
01996 st->RecomputeIndustriesNear();
01997 DeleteStationIfEmpty(st);
01998
01999
02000 if (is_truck) {
02001 st->truck_station.Clear();
02002 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
02003 } else {
02004 st->bus_station.Clear();
02005 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
02006 }
02007 }
02008
02009 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
02010 }
02011
02022 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02023 {
02024 uint8 width = (uint8)GB(p1, 0, 8);
02025 uint8 height = (uint8)GB(p1, 8, 8);
02026
02027
02028 if (width == 0 || height == 0) return CMD_ERROR;
02029
02030 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
02031
02032 TileArea roadstop_area(tile, width, height);
02033
02034 int quantity = 0;
02035 CommandCost cost(EXPENSES_CONSTRUCTION);
02036 TILE_AREA_LOOP(cur_tile, roadstop_area) {
02037
02038 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
02039
02040
02041 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
02042 RoadTypes rts = GetRoadTypes(cur_tile);
02043 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
02044 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
02045 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
02046
02047 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
02048 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
02049 CommandCost ret = RemoveRoadStop(cur_tile, flags);
02050 if (ret.Failed()) return ret;
02051 cost.AddCost(ret);
02052
02053 quantity++;
02054
02055 if ((flags & DC_EXEC) && is_drive_through) {
02056 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
02057 road_owner, tram_owner);
02058
02059
02060 RoadType rt;
02061 FOR_EACH_SET_ROADTYPE(rt, rts) {
02062 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02063 if (c != NULL) {
02064 c->infrastructure.road[rt] += CountBits(road_bits);
02065 DirtyCompanyInfrastructureWindows(c->index);
02066 }
02067 }
02068 }
02069 }
02070
02071 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02072
02073 return cost;
02074 }
02075
02082 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02083 {
02084 uint mindist = UINT_MAX;
02085
02086 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02087 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02088 }
02089
02090 return mindist;
02091 }
02092
02102 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02103 {
02104
02105
02106 if (as->noise_level < 2) return as->noise_level;
02107
02108 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02109
02110
02111
02112
02113
02114 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02115
02116
02117
02118 uint noise_reduction = distance / town_tolerance_distance;
02119
02120
02121
02122 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02123 }
02124
02132 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02133 {
02134 Town *t, *nearest = NULL;
02135 uint add = as->size_x + as->size_y - 2;
02136 uint mindist = UINT_MAX - add;
02137 FOR_ALL_TOWNS(t) {
02138 if (DistanceManhattan(t->xy, it) < mindist + add) {
02139 TileIterator *copy = it.Clone();
02140 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02141 delete copy;
02142 if (dist < mindist) {
02143 nearest = t;
02144 mindist = dist;
02145 }
02146 }
02147 }
02148
02149 return nearest;
02150 }
02151
02152
02154 void UpdateAirportsNoise()
02155 {
02156 Town *t;
02157 const Station *st;
02158
02159 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02160
02161 FOR_ALL_STATIONS(st) {
02162 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02163 const AirportSpec *as = st->airport.GetSpec();
02164 AirportTileIterator it(st);
02165 Town *nearest = AirportGetNearestTown(as, it);
02166 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02167 }
02168 }
02169 }
02170
02184 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02185 {
02186 StationID station_to_join = GB(p2, 16, 16);
02187 bool reuse = (station_to_join != NEW_STATION);
02188 if (!reuse) station_to_join = INVALID_STATION;
02189 bool distant_join = (station_to_join != INVALID_STATION);
02190 byte airport_type = GB(p1, 0, 8);
02191 byte layout = GB(p1, 8, 8);
02192
02193 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02194
02195 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02196
02197 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02198 if (ret.Failed()) return ret;
02199
02200
02201 const AirportSpec *as = AirportSpec::Get(airport_type);
02202 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02203
02204 Direction rotation = as->rotation[layout];
02205 int w = as->size_x;
02206 int h = as->size_y;
02207 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02208 TileArea airport_area = TileArea(tile, w, h);
02209
02210 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02211 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02212 }
02213
02214 CommandCost cost = CheckFlatLand(airport_area, flags);
02215 if (cost.Failed()) return cost;
02216
02217
02218 AirportTileTableIterator iter(as->table[layout], tile);
02219 Town *nearest = AirportGetNearestTown(as, iter);
02220 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02221
02222
02223 StringID authority_refuse_message = STR_NULL;
02224 Town *authority_refuse_town = NULL;
02225
02226 if (_settings_game.economy.station_noise_level) {
02227
02228 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02229 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02230 authority_refuse_town = nearest;
02231 }
02232 } else {
02233 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02234 uint num = 0;
02235 const Station *st;
02236 FOR_ALL_STATIONS(st) {
02237 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02238 }
02239 if (num >= 2) {
02240 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02241 authority_refuse_town = t;
02242 }
02243 }
02244
02245 if (authority_refuse_message != STR_NULL) {
02246 SetDParam(0, authority_refuse_town->index);
02247 return_cmd_error(authority_refuse_message);
02248 }
02249
02250 Station *st = NULL;
02251 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
02252 if (ret.Failed()) return ret;
02253
02254
02255 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02256
02257 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
02258 if (ret.Failed()) return ret;
02259
02260 if (st != NULL && st->airport.tile != INVALID_TILE) {
02261 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02262 }
02263
02264 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02265 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
02266 }
02267
02268 if (flags & DC_EXEC) {
02269
02270 nearest->noise_reached += newnoise_level;
02271
02272 st->AddFacility(FACIL_AIRPORT, tile);
02273 st->airport.type = airport_type;
02274 st->airport.layout = layout;
02275 st->airport.flags = 0;
02276 st->airport.rotation = rotation;
02277
02278 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
02279
02280 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02281 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
02282 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
02283 st->airport.Add(iter);
02284
02285 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
02286 }
02287
02288
02289 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
02290 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
02291 }
02292
02293 UpdateAirplanesOnNewStation(st);
02294
02295 Company::Get(st->owner)->infrastructure.airport++;
02296 DirtyCompanyInfrastructureWindows(st->owner);
02297
02298 st->UpdateVirtCoord();
02299 UpdateStationAcceptance(st, false);
02300 st->RecomputeIndustriesNear();
02301 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02302 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02303 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02304
02305 if (_settings_game.economy.station_noise_level) {
02306 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02307 }
02308 }
02309
02310 return cost;
02311 }
02312
02319 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
02320 {
02321 Station *st = Station::GetByTile(tile);
02322
02323 if (_current_company != OWNER_WATER) {
02324 CommandCost ret = CheckOwnership(st->owner);
02325 if (ret.Failed()) return ret;
02326 }
02327
02328 tile = st->airport.tile;
02329
02330 CommandCost cost(EXPENSES_CONSTRUCTION);
02331
02332 const Aircraft *a;
02333 FOR_ALL_AIRCRAFT(a) {
02334 if (!a->IsNormalAircraft()) continue;
02335 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
02336 }
02337
02338 if (flags & DC_EXEC) {
02339 const AirportSpec *as = st->airport.GetSpec();
02340
02341
02342
02343 AirportTileIterator it(st);
02344 Town *nearest = AirportGetNearestTown(as, it);
02345 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
02346 }
02347
02348 TILE_AREA_LOOP(tile_cur, st->airport) {
02349 if (!st->TileBelongsToAirport(tile_cur)) continue;
02350
02351 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
02352 if (ret.Failed()) return ret;
02353
02354 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
02355
02356 if (flags & DC_EXEC) {
02357 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
02358 DeleteAnimatedTile(tile_cur);
02359 DoClearSquare(tile_cur);
02360 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
02361 }
02362 }
02363
02364 if (flags & DC_EXEC) {
02365
02366 delete st->airport.psa;
02367
02368 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
02369 DeleteWindowById(
02370 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
02371 );
02372 }
02373
02374 st->rect.AfterRemoveRect(st, st->airport);
02375
02376 st->airport.Clear();
02377 st->facilities &= ~FACIL_AIRPORT;
02378
02379 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
02380
02381 if (_settings_game.economy.station_noise_level) {
02382 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
02383 }
02384
02385 Company::Get(st->owner)->infrastructure.airport--;
02386 DirtyCompanyInfrastructureWindows(st->owner);
02387
02388 st->UpdateVirtCoord();
02389 st->RecomputeIndustriesNear();
02390 DeleteStationIfEmpty(st);
02391 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
02392 }
02393
02394 return cost;
02395 }
02396
02406 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02407 {
02408 if (!Station::IsValidID(p1)) return CMD_ERROR;
02409 Station *st = Station::Get(p1);
02410
02411 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
02412
02413 CommandCost ret = CheckOwnership(st->owner);
02414 if (ret.Failed()) return ret;
02415
02416 if (flags & DC_EXEC) {
02417 st->airport.flags ^= AIRPORT_CLOSED_block;
02418 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
02419 }
02420 return CommandCost();
02421 }
02422
02429 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02430 {
02431 const Vehicle *v;
02432 FOR_ALL_VEHICLES(v) {
02433 if ((v->owner == company) == include_company) {
02434 const Order *order;
02435 FOR_VEHICLE_ORDERS(v, order) {
02436 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02437 return true;
02438 }
02439 }
02440 }
02441 }
02442 return false;
02443 }
02444
02445 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02446 {-1, 0},
02447 { 0, 0},
02448 { 0, 0},
02449 { 0, -1}
02450 };
02451 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02452 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02453
02463 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02464 {
02465 StationID station_to_join = GB(p2, 16, 16);
02466 bool reuse = (station_to_join != NEW_STATION);
02467 if (!reuse) station_to_join = INVALID_STATION;
02468 bool distant_join = (station_to_join != INVALID_STATION);
02469
02470 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02471
02472 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02473 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02474 direction = ReverseDiagDir(direction);
02475
02476
02477 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02478
02479 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02480 if (ret.Failed()) return ret;
02481
02482 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02483
02484 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02485 if (ret.Failed()) return ret;
02486
02487 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02488
02489 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
02490 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02491 }
02492
02493 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02494
02495
02496 WaterClass wc = GetWaterClass(tile_cur);
02497
02498 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02499 if (ret.Failed()) return ret;
02500
02501 tile_cur += TileOffsByDiagDir(direction);
02502 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
02503 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02504 }
02505
02506 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02507 _dock_w_chk[direction], _dock_h_chk[direction]);
02508
02509
02510 Station *st = NULL;
02511 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
02512 if (ret.Failed()) return ret;
02513
02514
02515 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02516
02517 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
02518 if (ret.Failed()) return ret;
02519
02520 if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02521
02522 if (flags & DC_EXEC) {
02523 st->dock_tile = tile;
02524 st->AddFacility(FACIL_DOCK, tile);
02525
02526 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
02527
02528
02529
02530 if (wc == WATER_CLASS_CANAL) {
02531 Company::Get(st->owner)->infrastructure.water++;
02532 }
02533 Company::Get(st->owner)->infrastructure.station += 2;
02534 DirtyCompanyInfrastructureWindows(st->owner);
02535
02536 MakeDock(tile, st->owner, st->index, direction, wc);
02537
02538 st->UpdateVirtCoord();
02539 UpdateStationAcceptance(st, false);
02540 st->RecomputeIndustriesNear();
02541 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
02542 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
02543 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02544 }
02545
02546 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
02547 }
02548
02555 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
02556 {
02557 Station *st = Station::GetByTile(tile);
02558 CommandCost ret = CheckOwnership(st->owner);
02559 if (ret.Failed()) return ret;
02560
02561 TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
02562
02563 TileIndex tile1 = st->dock_tile;
02564 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
02565
02566 ret = EnsureNoVehicleOnGround(tile1);
02567 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
02568 if (ret.Failed()) return ret;
02569
02570 if (flags & DC_EXEC) {
02571 DoClearSquare(tile1);
02572 MarkTileDirtyByTile(tile1);
02573 MakeWaterKeepingClass(tile2, st->owner);
02574
02575 st->rect.AfterRemoveTile(st, tile1);
02576 st->rect.AfterRemoveTile(st, tile2);
02577
02578 st->dock_tile = INVALID_TILE;
02579 st->facilities &= ~FACIL_DOCK;
02580
02581 Company::Get(st->owner)->infrastructure.station -= 2;
02582 DirtyCompanyInfrastructureWindows(st->owner);
02583
02584 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
02585 st->UpdateVirtCoord();
02586 st->RecomputeIndustriesNear();
02587 DeleteStationIfEmpty(st);
02588
02589
02590
02591
02592
02593 Ship *s;
02594 FOR_ALL_SHIPS(s) {
02595 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
02596 s->LeaveStation();
02597 }
02598
02599 if (s->dest_tile == docking_location) {
02600 s->dest_tile = 0;
02601 s->current_order.Free();
02602 }
02603 }
02604 }
02605
02606 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
02607 }
02608
02609 #include "table/station_land.h"
02610
02611 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
02612 {
02613 return &_station_display_datas[st][gfx];
02614 }
02615
02625 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
02626 {
02627 bool snow_desert;
02628 switch (*ground) {
02629 case SPR_RAIL_TRACK_X:
02630 snow_desert = false;
02631 *overlay_offset = RTO_X;
02632 break;
02633
02634 case SPR_RAIL_TRACK_Y:
02635 snow_desert = false;
02636 *overlay_offset = RTO_Y;
02637 break;
02638
02639 case SPR_RAIL_TRACK_X_SNOW:
02640 snow_desert = true;
02641 *overlay_offset = RTO_X;
02642 break;
02643
02644 case SPR_RAIL_TRACK_Y_SNOW:
02645 snow_desert = true;
02646 *overlay_offset = RTO_Y;
02647 break;
02648
02649 default:
02650 return false;
02651 }
02652
02653 if (ti != NULL) {
02654
02655 switch (_settings_game.game_creation.landscape) {
02656 case LT_ARCTIC:
02657 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
02658 break;
02659
02660 case LT_TROPIC:
02661 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
02662 break;
02663
02664 default:
02665 break;
02666 }
02667 }
02668
02669 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
02670 return true;
02671 }
02672
02673 static void DrawTile_Station(TileInfo *ti)
02674 {
02675 const NewGRFSpriteLayout *layout = NULL;
02676 DrawTileSprites tmp_rail_layout;
02677 const DrawTileSprites *t = NULL;
02678 RoadTypes roadtypes;
02679 int32 total_offset;
02680 const RailtypeInfo *rti = NULL;
02681 uint32 relocation = 0;
02682 uint32 ground_relocation = 0;
02683 BaseStation *st = NULL;
02684 const StationSpec *statspec = NULL;
02685 uint tile_layout = 0;
02686
02687 if (HasStationRail(ti->tile)) {
02688 rti = GetRailTypeInfo(GetRailType(ti->tile));
02689 roadtypes = ROADTYPES_NONE;
02690 total_offset = rti->GetRailtypeSpriteOffset();
02691
02692 if (IsCustomStationSpecIndex(ti->tile)) {
02693
02694 st = BaseStation::GetByTile(ti->tile);
02695 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02696
02697 if (statspec != NULL) {
02698 tile_layout = GetStationGfx(ti->tile);
02699
02700 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02701 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02702 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02703 }
02704
02705
02706 if (statspec->renderdata != NULL) {
02707 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02708 if (!layout->NeedsPreprocessing()) {
02709 t = layout;
02710 layout = NULL;
02711 }
02712 }
02713 }
02714 }
02715 } else {
02716 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02717 total_offset = 0;
02718 }
02719
02720 StationGfx gfx = GetStationGfx(ti->tile);
02721 if (IsAirport(ti->tile)) {
02722 gfx = GetAirportGfx(ti->tile);
02723 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02724 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02725 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02726 return;
02727 }
02728
02729
02730 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02731 gfx = ats->grf_prop.subst_id;
02732 }
02733 switch (gfx) {
02734 case APT_RADAR_GRASS_FENCE_SW:
02735 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02736 break;
02737 case APT_GRASS_FENCE_NE_FLAG:
02738 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02739 break;
02740 case APT_RADAR_FENCE_SW:
02741 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02742 break;
02743 case APT_RADAR_FENCE_NE:
02744 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02745 break;
02746 case APT_GRASS_FENCE_NE_FLAG_2:
02747 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02748 break;
02749 }
02750 }
02751
02752 Owner owner = GetTileOwner(ti->tile);
02753
02754 PaletteID palette;
02755 if (Company::IsValidID(owner)) {
02756 palette = COMPANY_SPRITE_COLOUR(owner);
02757 } else {
02758
02759 palette = PALETTE_TO_GREY;
02760 }
02761
02762 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02763
02764
02765 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02766 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02767
02768
02769 uint edge_info = 0;
02770 int z;
02771 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02772 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02773 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02774 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02775 if (image == 0) goto draw_default_foundation;
02776
02777 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02778
02779
02780 static const uint8 foundation_parts[] = {
02781 0, 0, 0, 0,
02782 0, 1, 2, 3,
02783 0, 4, 5, 6,
02784 7, 8, 9
02785 };
02786
02787 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02788 } else {
02789
02790
02791
02792
02793 static const uint8 composite_foundation_parts[] = {
02794
02795 0x00, 0xD1, 0xE4, 0xE0,
02796
02797 0xCA, 0xC9, 0xC4, 0xC0,
02798
02799 0xD2, 0x91, 0xE4, 0xA0,
02800
02801 0x4A, 0x09, 0x44
02802 };
02803
02804 uint8 parts = composite_foundation_parts[ti->tileh];
02805
02806
02807
02808 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02809 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02810
02811 if (parts == 0) {
02812
02813
02814
02815 goto draw_default_foundation;
02816 }
02817
02818 StartSpriteCombine();
02819 for (int i = 0; i < 8; i++) {
02820 if (HasBit(parts, i)) {
02821 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02822 }
02823 }
02824 EndSpriteCombine();
02825 }
02826
02827 OffsetGroundSprite(31, 1);
02828 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02829 } else {
02830 draw_default_foundation:
02831 DrawFoundation(ti, FOUNDATION_LEVELED);
02832 }
02833 }
02834
02835 if (IsBuoy(ti->tile)) {
02836 DrawWaterClassGround(ti);
02837 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02838 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02839 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02840 if (ti->tileh == SLOPE_FLAT) {
02841 DrawWaterClassGround(ti);
02842 } else {
02843 assert(IsDock(ti->tile));
02844 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02845 WaterClass wc = GetWaterClass(water_tile);
02846 if (wc == WATER_CLASS_SEA) {
02847 DrawShoreTile(ti->tileh);
02848 } else {
02849 DrawClearLandTile(ti, 3);
02850 }
02851 }
02852 } else {
02853 if (layout != NULL) {
02854
02855 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02856 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02857 uint8 var10;
02858 FOR_EACH_SET_BIT(var10, var10_values) {
02859 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02860 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02861 }
02862 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02863 t = &tmp_rail_layout;
02864 total_offset = 0;
02865 } else if (statspec != NULL) {
02866
02867 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02868 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02869 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02870 }
02871 ground_relocation += rti->fallback_railtype;
02872 }
02873
02874 SpriteID image = t->ground.sprite;
02875 PaletteID pal = t->ground.pal;
02876 RailTrackOffset overlay_offset;
02877 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
02878 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02879 DrawGroundSprite(image, PAL_NONE);
02880 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
02881
02882 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02883 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02884 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
02885 }
02886 } else {
02887 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02888 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02889 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02890
02891
02892 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02893 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02894 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02895 }
02896 }
02897 }
02898
02899 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
02900
02901 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02902 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02903 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02904 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02905 }
02906
02907 if (IsRailWaypoint(ti->tile)) {
02908
02909 total_offset = 0;
02910 }
02911
02912 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02913 }
02914
02915 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02916 {
02917 int32 total_offset = 0;
02918 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02919 const DrawTileSprites *t = GetStationTileLayout(st, image);
02920 const RailtypeInfo *rti = NULL;
02921
02922 if (railtype != INVALID_RAILTYPE) {
02923 rti = GetRailTypeInfo(railtype);
02924 total_offset = rti->GetRailtypeSpriteOffset();
02925 }
02926
02927 SpriteID img = t->ground.sprite;
02928 RailTrackOffset overlay_offset;
02929 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
02930 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02931 DrawSprite(img, PAL_NONE, x, y);
02932 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
02933 } else {
02934 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02935 }
02936
02937 if (roadtype == ROADTYPE_TRAM) {
02938 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02939 }
02940
02941
02942 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02943 }
02944
02945 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02946 {
02947 return GetTileMaxPixelZ(tile);
02948 }
02949
02950 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02951 {
02952 return FlatteningFoundation(tileh);
02953 }
02954
02955 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02956 {
02957 td->owner[0] = GetTileOwner(tile);
02958 if (IsDriveThroughStopTile(tile)) {
02959 Owner road_owner = INVALID_OWNER;
02960 Owner tram_owner = INVALID_OWNER;
02961 RoadTypes rts = GetRoadTypes(tile);
02962 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02963 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02964
02965
02966 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02967 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02968 uint i = 1;
02969 if (road_owner != INVALID_OWNER) {
02970 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02971 td->owner[i] = road_owner;
02972 i++;
02973 }
02974 if (tram_owner != INVALID_OWNER) {
02975 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02976 td->owner[i] = tram_owner;
02977 }
02978 }
02979 }
02980 td->build_date = BaseStation::GetByTile(tile)->build_date;
02981
02982 if (HasStationTileRail(tile)) {
02983 const StationSpec *spec = GetStationSpec(tile);
02984
02985 if (spec != NULL) {
02986 td->station_class = StationClass::Get(spec->cls_id)->name;
02987 td->station_name = spec->name;
02988
02989 if (spec->grf_prop.grffile != NULL) {
02990 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02991 td->grf = gc->GetName();
02992 }
02993 }
02994
02995 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02996 td->rail_speed = rti->max_speed;
02997 }
02998
02999 if (IsAirport(tile)) {
03000 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
03001 td->airport_class = AirportClass::Get(as->cls_id)->name;
03002 td->airport_name = as->name;
03003
03004 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
03005 td->airport_tile_name = ats->name;
03006
03007 if (as->grf_prop.grffile != NULL) {
03008 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
03009 td->grf = gc->GetName();
03010 } else if (ats->grf_prop.grffile != NULL) {
03011 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
03012 td->grf = gc->GetName();
03013 }
03014 }
03015
03016 StringID str;
03017 switch (GetStationType(tile)) {
03018 default: NOT_REACHED();
03019 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
03020 case STATION_AIRPORT:
03021 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
03022 break;
03023 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
03024 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
03025 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
03026 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
03027 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
03028 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
03029 }
03030 td->str = str;
03031 }
03032
03033
03034 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
03035 {
03036 TrackBits trackbits = TRACK_BIT_NONE;
03037
03038 switch (mode) {
03039 case TRANSPORT_RAIL:
03040 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
03041 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
03042 }
03043 break;
03044
03045 case TRANSPORT_WATER:
03046
03047 if (IsBuoy(tile)) {
03048 trackbits = TRACK_BIT_ALL;
03049
03050 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
03051
03052 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
03053 }
03054 break;
03055
03056 case TRANSPORT_ROAD:
03057 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
03058 DiagDirection dir = GetRoadStopDir(tile);
03059 Axis axis = DiagDirToAxis(dir);
03060
03061 if (side != INVALID_DIAGDIR) {
03062 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
03063 }
03064
03065 trackbits = AxisToTrackBits(axis);
03066 }
03067 break;
03068
03069 default:
03070 break;
03071 }
03072
03073 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
03074 }
03075
03076
03077 static void TileLoop_Station(TileIndex tile)
03078 {
03079
03080
03081 switch (GetStationType(tile)) {
03082 case STATION_AIRPORT:
03083 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
03084 break;
03085
03086 case STATION_DOCK:
03087 if (!IsTileFlat(tile)) break;
03088
03089 case STATION_OILRIG:
03090 case STATION_BUOY:
03091 TileLoop_Water(tile);
03092 break;
03093
03094 default: break;
03095 }
03096 }
03097
03098
03099 static void AnimateTile_Station(TileIndex tile)
03100 {
03101 if (HasStationRail(tile)) {
03102 AnimateStationTile(tile);
03103 return;
03104 }
03105
03106 if (IsAirport(tile)) {
03107 AnimateAirportTile(tile);
03108 }
03109 }
03110
03111
03112 static bool ClickTile_Station(TileIndex tile)
03113 {
03114 const BaseStation *bst = BaseStation::GetByTile(tile);
03115
03116 if (bst->facilities & FACIL_WAYPOINT) {
03117 ShowWaypointWindow(Waypoint::From(bst));
03118 } else if (IsHangar(tile)) {
03119 const Station *st = Station::From(bst);
03120 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03121 } else {
03122 ShowStationViewWindow(bst->index);
03123 }
03124 return true;
03125 }
03126
03127 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03128 {
03129 if (v->type == VEH_TRAIN) {
03130 StationID station_id = GetStationIndex(tile);
03131 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03132 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03133
03134 int station_ahead;
03135 int station_length;
03136 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03137
03138
03139
03140
03141
03142 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
03143
03144 DiagDirection dir = DirToDiagDir(v->direction);
03145
03146 x &= 0xF;
03147 y &= 0xF;
03148
03149 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03150 if (y == TILE_SIZE / 2) {
03151 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03152 stop &= TILE_SIZE - 1;
03153
03154 if (x == stop) {
03155 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
03156 } else if (x < stop) {
03157 v->vehstatus |= VS_TRAIN_SLOWING;
03158 uint16 spd = max(0, (stop - x) * 20 - 15);
03159 if (spd < v->cur_speed) v->cur_speed = spd;
03160 }
03161 }
03162 } else if (v->type == VEH_ROAD) {
03163 RoadVehicle *rv = RoadVehicle::From(v);
03164 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03165 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03166
03167 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03168 }
03169 }
03170 }
03171
03172 return VETSB_CONTINUE;
03173 }
03174
03179 void TriggerWatchedCargoCallbacks(Station *st)
03180 {
03181
03182 uint cargoes = 0;
03183 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03184 if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03185 }
03186
03187
03188 if (cargoes == 0) return;
03189
03190
03191 Rect r = st->GetCatchmentRect();
03192 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03193 TILE_AREA_LOOP(tile, ta) {
03194 if (IsTileType(tile, MP_HOUSE)) {
03195 WatchedCargoCallback(tile, cargoes);
03196 }
03197 }
03198 }
03199
03206 static bool StationHandleBigTick(BaseStation *st)
03207 {
03208 if (!st->IsInUse()) {
03209 if (++st->delete_ctr >= 8) delete st;
03210 return false;
03211 }
03212
03213 if (Station::IsExpected(st)) {
03214 TriggerWatchedCargoCallbacks(Station::From(st));
03215
03216 for (CargoID i = 0; i < NUM_CARGO; i++) {
03217 ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03218 }
03219 }
03220
03221
03222 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03223
03224 return true;
03225 }
03226
03227 static inline void byte_inc_sat(byte *p)
03228 {
03229 byte b = *p + 1;
03230 if (b != 0) *p = b;
03231 }
03232
03233 static void UpdateStationRating(Station *st)
03234 {
03235 bool waiting_changed = false;
03236
03237 byte_inc_sat(&st->time_since_load);
03238 byte_inc_sat(&st->time_since_unload);
03239
03240 const CargoSpec *cs;
03241 FOR_ALL_CARGOSPECS(cs) {
03242 GoodsEntry *ge = &st->goods[cs->Index()];
03243
03244
03245
03246 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
03247 ge->rating++;
03248 }
03249
03250
03251 if (ge->HasRating()) {
03252 byte_inc_sat(&ge->time_since_pickup);
03253
03254 bool skip = false;
03255 int rating = 0;
03256 uint waiting = ge->cargo.TotalCount();
03257
03258
03259
03260
03261 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
03262
03263
03264
03265
03266
03267
03268
03269 uint waiting_avg = waiting / (num_dests + 1);
03270
03271 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03272
03273
03274
03275
03276 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
03277
03278 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03279
03280 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03281 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03282 if (callback != CALLBACK_FAILED) {
03283 skip = true;
03284 rating = GB(callback, 0, 14);
03285
03286
03287 if (HasBit(callback, 14)) rating -= 0x4000;
03288 }
03289 }
03290
03291 if (!skip) {
03292 int b = ge->last_speed - 85;
03293 if (b >= 0) rating += b >> 2;
03294
03295 byte waittime = ge->time_since_pickup;
03296 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
03297 (waittime > 21) ||
03298 (rating += 25, waittime > 12) ||
03299 (rating += 25, waittime > 6) ||
03300 (rating += 45, waittime > 3) ||
03301 (rating += 35, true);
03302
03303 (rating -= 90, ge->max_waiting_cargo > 1500) ||
03304 (rating += 55, ge->max_waiting_cargo > 1000) ||
03305 (rating += 35, ge->max_waiting_cargo > 600) ||
03306 (rating += 10, ge->max_waiting_cargo > 300) ||
03307 (rating += 20, ge->max_waiting_cargo > 100) ||
03308 (rating += 10, true);
03309 }
03310
03311 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03312
03313 byte age = ge->last_age;
03314 (age >= 3) ||
03315 (rating += 10, age >= 2) ||
03316 (rating += 10, age >= 1) ||
03317 (rating += 13, true);
03318
03319 {
03320 int or_ = ge->rating;
03321
03322
03323 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03324
03325
03326
03327 if (rating <= 64 && waiting_avg >= 100) {
03328 int dec = Random() & 0x1F;
03329 if (waiting_avg < 200) dec &= 7;
03330 waiting -= (dec + 1) * num_dests;
03331 waiting_changed = true;
03332 }
03333
03334
03335 if (rating <= 127 && waiting != 0) {
03336 uint32 r = Random();
03337 if (rating <= (int)GB(r, 0, 7)) {
03338
03339 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
03340 waiting_changed = true;
03341 }
03342 }
03343
03344
03345
03346
03347 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03348 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03349 static const uint MAX_WAITING_CARGO = 1 << 15;
03350
03351 if (waiting > WAITING_CARGO_THRESHOLD) {
03352 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03353 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03354
03355 waiting = min(waiting, MAX_WAITING_CARGO);
03356 waiting_changed = true;
03357 }
03358
03359
03360
03361 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
03362
03363
03364 ge->max_waiting_cargo = 0;
03365
03366
03367
03368
03369 StationCargoAmountMap waiting_per_source;
03370 ge->cargo.Truncate(ge->cargo.AvailableCount() - waiting, &waiting_per_source);
03371 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
03372 Station *source_station = Station::GetIfValid(i->first);
03373 if (source_station == NULL) continue;
03374
03375 GoodsEntry &source_ge = source_station->goods[cs->Index()];
03376 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
03377 }
03378 } else {
03379
03380 ge->max_waiting_cargo = waiting_avg;
03381 }
03382 }
03383 }
03384 }
03385
03386 StationID index = st->index;
03387 if (waiting_changed) {
03388 SetWindowDirty(WC_STATION_VIEW, index);
03389 } else {
03390 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST);
03391 }
03392 }
03393
03402 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
03403 {
03404 GoodsEntry &ge = st->goods[c];
03405
03406
03407 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
03408
03409
03410 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
03411 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
03412 if (v->cargo_type != c) continue;
03413 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
03414 }
03415 }
03416 }
03417
03426 void DeleteStaleLinks(Station *from)
03427 {
03428 for (CargoID c = 0; c < NUM_CARGO; ++c) {
03429 GoodsEntry &ge = from->goods[c];
03430 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
03431 if (lg == NULL) continue;
03432 Node node = (*lg)[ge.node];
03433 for (EdgeIterator it(node.Begin()); it != node.End();) {
03434 Edge edge = it->second;
03435 Station *to = Station::Get((*lg)[it->first].Station());
03436 assert(to->goods[c].node == it->first);
03437 ++it;
03438 assert(_date >= edge.LastUpdate());
03439 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
03440 if ((uint)(_date - edge.LastUpdate()) > timeout) {
03441
03442
03443 bool updated = false;
03444 OrderList *l;
03445 FOR_ALL_ORDER_LISTS(l) {
03446 bool found_from = false;
03447 bool found_to = false;
03448 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
03449 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
03450 if (order->GetDestination() == from->index) {
03451 found_from = true;
03452 if (found_to) break;
03453 } else if (order->GetDestination() == to->index) {
03454 found_to = true;
03455 if (found_from) break;
03456 }
03457 }
03458 if (!found_to || !found_from) continue;
03459 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
03460
03461
03462
03463
03464
03465
03466 LinkRefresher::Run(v, false);
03467 if (edge.LastUpdate() == _date) updated = true;
03468 }
03469 if (updated) break;
03470 }
03471 if (!updated) {
03472
03473 node.RemoveEdge(to->goods[c].node);
03474 ge.flows.DeleteFlows(to->index);
03475 RerouteCargo(from, c, to->index, from->index);
03476 }
03477 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
03478 edge.Restrict();
03479 ge.flows.RestrictFlows(to->index);
03480 RerouteCargo(from, c, to->index, from->index);
03481 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
03482 edge.Release();
03483 }
03484 }
03485 assert(_date >= lg->LastCompression());
03486 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
03487 lg->Compress();
03488 }
03489 }
03490 }
03491
03500 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage)
03501 {
03502 GoodsEntry &ge1 = st->goods[cargo];
03503 Station *st2 = Station::Get(next_station_id);
03504 GoodsEntry &ge2 = st2->goods[cargo];
03505 LinkGraph *lg = NULL;
03506 if (ge1.link_graph == INVALID_LINK_GRAPH) {
03507 if (ge2.link_graph == INVALID_LINK_GRAPH) {
03508 if (LinkGraph::CanAllocateItem()) {
03509 lg = new LinkGraph(cargo);
03510 LinkGraphSchedule::Instance()->Queue(lg);
03511 ge2.link_graph = lg->index;
03512 ge2.node = lg->AddNode(st2);
03513 } else {
03514 DEBUG(misc, 0, "Can't allocate link graph");
03515 }
03516 } else {
03517 lg = LinkGraph::Get(ge2.link_graph);
03518 }
03519 if (lg) {
03520 ge1.link_graph = lg->index;
03521 ge1.node = lg->AddNode(st);
03522 }
03523 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
03524 lg = LinkGraph::Get(ge1.link_graph);
03525 ge2.link_graph = lg->index;
03526 ge2.node = lg->AddNode(st2);
03527 } else {
03528 lg = LinkGraph::Get(ge1.link_graph);
03529 if (ge1.link_graph != ge2.link_graph) {
03530 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
03531 if (lg->Size() < lg2->Size()) {
03532 LinkGraphSchedule::Instance()->Unqueue(lg);
03533 lg2->Merge(lg);
03534 lg = lg2;
03535 } else {
03536 LinkGraphSchedule::Instance()->Unqueue(lg2);
03537 lg->Merge(lg2);
03538 }
03539 }
03540 }
03541 if (lg != NULL) {
03542 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage);
03543 }
03544 }
03545
03552 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
03553 {
03554 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
03555 if (v->refit_cap > 0) {
03556
03557
03558
03559
03560
03561
03562 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
03563 min(v->refit_cap, v->cargo.StoredCount()));
03564 }
03565 }
03566 }
03567
03568
03569 static void StationHandleSmallTick(BaseStation *st)
03570 {
03571 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03572
03573 byte b = st->delete_ctr + 1;
03574 if (b >= STATION_RATING_TICKS) b = 0;
03575 st->delete_ctr = b;
03576
03577 if (b == 0) UpdateStationRating(Station::From(st));
03578 }
03579
03580 void OnTick_Station()
03581 {
03582 if (_game_mode == GM_EDITOR) return;
03583
03584 BaseStation *st;
03585 FOR_ALL_BASE_STATIONS(st) {
03586 StationHandleSmallTick(st);
03587
03588
03589 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
03590 DeleteStaleLinks(Station::From(st));
03591 };
03592
03593
03594
03595
03596 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03597
03598 if (!StationHandleBigTick(st)) continue;
03599 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03600 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03601 }
03602 }
03603 }
03604
03606 void StationMonthlyLoop()
03607 {
03608 Station *st;
03609
03610 FOR_ALL_STATIONS(st) {
03611 for (CargoID i = 0; i < NUM_CARGO; i++) {
03612 GoodsEntry *ge = &st->goods[i];
03613 SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03614 ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03615 }
03616 }
03617 }
03618
03619
03620 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03621 {
03622 Station *st;
03623
03624 FOR_ALL_STATIONS(st) {
03625 if (st->owner == owner &&
03626 DistanceManhattan(tile, st->xy) <= radius) {
03627 for (CargoID i = 0; i < NUM_CARGO; i++) {
03628 GoodsEntry *ge = &st->goods[i];
03629
03630 if (ge->acceptance_pickup != 0) {
03631 ge->rating = Clamp(ge->rating + amount, 0, 255);
03632 }
03633 }
03634 }
03635 }
03636 }
03637
03638 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03639 {
03640
03641
03642 if (!CargoPacket::CanAllocateItem()) return 0;
03643
03644 GoodsEntry &ge = st->goods[type];
03645 amount += ge.amount_fract;
03646 ge.amount_fract = GB(amount, 0, 8);
03647
03648 amount >>= 8;
03649
03650 if (amount == 0) return 0;
03651
03652 StationID next = ge.GetVia(st->index);
03653 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
03654 LinkGraph *lg = NULL;
03655 if (ge.link_graph == INVALID_LINK_GRAPH) {
03656 if (LinkGraph::CanAllocateItem()) {
03657 lg = new LinkGraph(type);
03658 LinkGraphSchedule::Instance()->Queue(lg);
03659 ge.link_graph = lg->index;
03660 ge.node = lg->AddNode(st);
03661 } else {
03662 DEBUG(misc, 0, "Can't allocate link graph");
03663 }
03664 } else {
03665 lg = LinkGraph::Get(ge.link_graph);
03666 }
03667 if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
03668
03669 if (!ge.HasRating()) {
03670 InvalidateWindowData(WC_STATION_LIST, st->index);
03671 SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03672 }
03673
03674 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
03675 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03676 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03677
03678 SetWindowDirty(WC_STATION_VIEW, st->index);
03679 st->MarkTilesDirty(true);
03680 return amount;
03681 }
03682
03683 static bool IsUniqueStationName(const char *name)
03684 {
03685 const Station *st;
03686
03687 FOR_ALL_STATIONS(st) {
03688 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03689 }
03690
03691 return true;
03692 }
03693
03703 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03704 {
03705 Station *st = Station::GetIfValid(p1);
03706 if (st == NULL) return CMD_ERROR;
03707
03708 CommandCost ret = CheckOwnership(st->owner);
03709 if (ret.Failed()) return ret;
03710
03711 bool reset = StrEmpty(text);
03712
03713 if (!reset) {
03714 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03715 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03716 }
03717
03718 if (flags & DC_EXEC) {
03719 free(st->name);
03720 st->name = reset ? NULL : strdup(text);
03721
03722 st->UpdateVirtCoord();
03723 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03724 }
03725
03726 return CommandCost();
03727 }
03728
03735 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03736 {
03737
03738 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03739
03740 uint x = TileX(location.tile);
03741 uint y = TileY(location.tile);
03742
03743 uint min_x = (x > max_rad) ? x - max_rad : 0;
03744 uint max_x = x + location.w + max_rad;
03745 uint min_y = (y > max_rad) ? y - max_rad : 0;
03746 uint max_y = y + location.h + max_rad;
03747
03748 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03749 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03750 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03751 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03752
03753 for (uint cy = min_y; cy < max_y; cy++) {
03754 for (uint cx = min_x; cx < max_x; cx++) {
03755 TileIndex cur_tile = TileXY(cx, cy);
03756 if (!IsTileType(cur_tile, MP_STATION)) continue;
03757
03758 Station *st = Station::GetByTile(cur_tile);
03759
03760 if (st == NULL) continue;
03761
03762 if (_settings_game.station.modified_catchment) {
03763 int rad = st->GetCatchmentRadius();
03764 int rad_x = cx - x;
03765 int rad_y = cy - y;
03766
03767 if (rad_x < -rad || rad_x >= rad + location.w) continue;
03768 if (rad_y < -rad || rad_y >= rad + location.h) continue;
03769 }
03770
03771
03772
03773
03774 stations->Include(st);
03775 }
03776 }
03777 }
03778
03783 const StationList *StationFinder::GetStations()
03784 {
03785 if (this->tile != INVALID_TILE) {
03786 FindStationsAroundTiles(*this, &this->stations);
03787 this->tile = INVALID_TILE;
03788 }
03789 return &this->stations;
03790 }
03791
03792 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03793 {
03794
03795 if (amount == 0) return 0;
03796
03797 Station *st1 = NULL;
03798 Station *st2 = NULL;
03799 uint best_rating1 = 0;
03800 uint best_rating2 = 0;
03801
03802 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03803 Station *st = *st_iter;
03804
03805
03806 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03807
03808 if (st->goods[type].rating == 0) continue;
03809
03810 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue;
03811
03812 if (IsCargoInClass(type, CC_PASSENGERS)) {
03813 if (st->facilities == FACIL_TRUCK_STOP) continue;
03814 } else {
03815 if (st->facilities == FACIL_BUS_STOP) continue;
03816 }
03817
03818
03819 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03820 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03821 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03822 st2 = st; best_rating2 = st->goods[type].rating;
03823 }
03824 }
03825
03826
03827 if (st1 == NULL) return 0;
03828
03829
03830
03831 amount *= best_rating1 + 1;
03832
03833 if (st2 == NULL) {
03834
03835 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03836 }
03837
03838
03839 assert(st1 != NULL);
03840 assert(st2 != NULL);
03841 assert(best_rating1 != 0 || best_rating2 != 0);
03842
03843
03844
03845
03846
03847
03848 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03849 assert(worst_cargo <= (amount - worst_cargo));
03850
03851
03852 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03853
03854
03855 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03856 }
03857
03858 void BuildOilRig(TileIndex tile)
03859 {
03860 if (!Station::CanAllocateItem()) {
03861 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03862 return;
03863 }
03864
03865 Station *st = new Station(tile);
03866 st->town = ClosestTownFromTile(tile, UINT_MAX);
03867
03868 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03869
03870 assert(IsTileType(tile, MP_INDUSTRY));
03871 DeleteAnimatedTile(tile);
03872 MakeOilrig(tile, st->index, GetWaterClass(tile));
03873
03874 st->owner = OWNER_NONE;
03875 st->airport.type = AT_OILRIG;
03876 st->airport.Add(tile);
03877 st->dock_tile = tile;
03878 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03879 st->build_date = _date;
03880
03881 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03882
03883 st->UpdateVirtCoord();
03884 UpdateStationAcceptance(st, false);
03885 st->RecomputeIndustriesNear();
03886 }
03887
03888 void DeleteOilRig(TileIndex tile)
03889 {
03890 Station *st = Station::GetByTile(tile);
03891
03892 MakeWaterKeepingClass(tile, OWNER_NONE);
03893
03894 st->dock_tile = INVALID_TILE;
03895 st->airport.Clear();
03896 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03897 st->airport.flags = 0;
03898
03899 st->rect.AfterRemoveTile(st, tile);
03900
03901 st->UpdateVirtCoord();
03902 st->RecomputeIndustriesNear();
03903 if (!st->IsInUse()) delete st;
03904 }
03905
03906 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03907 {
03908 if (IsRoadStopTile(tile)) {
03909 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03910
03911 if (GetRoadOwner(tile, rt) == old_owner) {
03912 if (HasTileRoadType(tile, rt)) {
03913
03914 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03915 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03916 }
03917 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03918 }
03919 }
03920 }
03921
03922 if (!IsTileOwner(tile, old_owner)) return;
03923
03924 if (new_owner != INVALID_OWNER) {
03925
03926
03927
03928
03929 Company *old_company = Company::Get(old_owner);
03930 Company *new_company = Company::Get(new_owner);
03931
03932
03933 switch (GetStationType(tile)) {
03934 case STATION_RAIL:
03935 case STATION_WAYPOINT:
03936 if (!IsStationTileBlocked(tile)) {
03937 old_company->infrastructure.rail[GetRailType(tile)]--;
03938 new_company->infrastructure.rail[GetRailType(tile)]++;
03939 }
03940 break;
03941
03942 case STATION_BUS:
03943 case STATION_TRUCK:
03944
03945 break;
03946
03947 case STATION_BUOY:
03948 case STATION_DOCK:
03949 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03950 old_company->infrastructure.water--;
03951 new_company->infrastructure.water++;
03952 }
03953 break;
03954
03955 default:
03956 break;
03957 }
03958
03959
03960 if (!IsBuoy(tile) && !IsAirport(tile)) {
03961 old_company->infrastructure.station--;
03962 new_company->infrastructure.station++;
03963 }
03964
03965
03966 SetTileOwner(tile, new_owner);
03967 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03968 } else {
03969 if (IsDriveThroughStopTile(tile)) {
03970
03971 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03972 assert(IsTileType(tile, MP_ROAD));
03973
03974 ChangeTileOwner(tile, old_owner, new_owner);
03975 } else {
03976 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03977
03978
03979
03980 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03981 }
03982 }
03983 }
03984
03993 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03994 {
03995
03996 if (_current_company == OWNER_WATER) return true;
03997
03998 RoadTypes rts = GetRoadTypes(tile);
03999 if (HasBit(rts, ROADTYPE_TRAM)) {
04000 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
04001 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
04002 }
04003 if (HasBit(rts, ROADTYPE_ROAD)) {
04004 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
04005 if (road_owner != OWNER_TOWN) {
04006 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
04007 } else {
04008 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
04009 }
04010 }
04011
04012 return true;
04013 }
04014
04021 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
04022 {
04023 if (flags & DC_AUTO) {
04024 switch (GetStationType(tile)) {
04025 default: break;
04026 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
04027 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
04028 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
04029 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);
04030 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);
04031 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
04032 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
04033 case STATION_OILRIG:
04034 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
04035 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
04036 }
04037 }
04038
04039 switch (GetStationType(tile)) {
04040 case STATION_RAIL: return RemoveRailStation(tile, flags);
04041 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
04042 case STATION_AIRPORT: return RemoveAirport(tile, flags);
04043 case STATION_TRUCK:
04044 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
04045 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
04046 }
04047 return RemoveRoadStop(tile, flags);
04048 case STATION_BUS:
04049 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
04050 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
04051 }
04052 return RemoveRoadStop(tile, flags);
04053 case STATION_BUOY: return RemoveBuoy(tile, flags);
04054 case STATION_DOCK: return RemoveDock(tile, flags);
04055 default: break;
04056 }
04057
04058 return CMD_ERROR;
04059 }
04060
04061 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
04062 {
04063 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
04064
04065
04066
04067 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
04068 switch (GetStationType(tile)) {
04069 case STATION_WAYPOINT:
04070 case STATION_RAIL: {
04071 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
04072 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
04073 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
04074 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04075 }
04076
04077 case STATION_AIRPORT:
04078 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04079
04080 case STATION_TRUCK:
04081 case STATION_BUS: {
04082 DiagDirection direction = GetRoadStopDir(tile);
04083 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
04084 if (IsDriveThroughStopTile(tile)) {
04085 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
04086 }
04087 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
04088 }
04089
04090 default: break;
04091 }
04092 }
04093 }
04094 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
04095 }
04096
04102 uint FlowStat::GetShare(StationID st) const
04103 {
04104 uint32 prev = 0;
04105 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
04106 if (it->second == st) {
04107 return it->first - prev;
04108 } else {
04109 prev = it->first;
04110 }
04111 }
04112 return 0;
04113 }
04114
04121 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
04122 {
04123 if (this->unrestricted == 0) return INVALID_STATION;
04124 assert(!this->shares.empty());
04125 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
04126 assert(it != this->shares.end() && it->first <= this->unrestricted);
04127 if (it->second != excluded && it->second != excluded2) return it->second;
04128
04129
04130
04131
04132 uint end = it->first;
04133 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
04134 uint interval = end - begin;
04135 if (interval >= this->unrestricted) return INVALID_STATION;
04136 uint new_max = this->unrestricted - interval;
04137 uint rand = RandomRange(new_max);
04138 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
04139 this->shares.upper_bound(rand + interval);
04140 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
04141 if (it2->second != excluded && it2->second != excluded2) return it2->second;
04142
04143
04144
04145
04146 uint end2 = it2->first;
04147 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
04148 uint interval2 = end2 - begin2;
04149 if (interval2 >= new_max) return INVALID_STATION;
04150 new_max -= interval2;
04151 if (begin > begin2) {
04152 Swap(begin, begin2);
04153 Swap(end, end2);
04154 Swap(interval, interval2);
04155 }
04156 rand = RandomRange(new_max);
04157 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
04158 if (rand < begin) {
04159 it3 = this->shares.upper_bound(rand);
04160 } else if (rand < begin2 - interval) {
04161 it3 = this->shares.upper_bound(rand + interval);
04162 } else {
04163 it3 = this->shares.upper_bound(rand + interval + interval2);
04164 }
04165 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
04166 return it3->second;
04167 }
04168
04174 void FlowStat::Invalidate()
04175 {
04176 assert(!this->shares.empty());
04177 SharesMap new_shares;
04178 uint i = 0;
04179 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04180 new_shares[++i] = it->second;
04181 if (it->first == this->unrestricted) this->unrestricted = i;
04182 }
04183 this->shares.swap(new_shares);
04184 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
04185 }
04186
04193 void FlowStat::ChangeShare(StationID st, int flow)
04194 {
04195
04196
04197 assert(!this->shares.empty());
04198
04199 uint removed_shares = 0;
04200 uint added_shares = 0;
04201 uint last_share = 0;
04202 SharesMap new_shares;
04203 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04204 if (it->second == st) {
04205 if (flow < 0) {
04206 uint share = it->first - last_share;
04207 if (flow == INT_MIN || (uint)(-flow) >= share) {
04208 removed_shares += share;
04209 if (it->first <= this->unrestricted) this->unrestricted -= share;
04210 if (flow != INT_MIN) flow += share;
04211 last_share = it->first;
04212 continue;
04213 }
04214 removed_shares += (uint)(-flow);
04215 } else {
04216 added_shares += (uint)(flow);
04217 }
04218 if (it->first <= this->unrestricted) this->unrestricted += flow;
04219
04220
04221
04222 flow = 0;
04223 }
04224 new_shares[it->first + added_shares - removed_shares] = it->second;
04225 last_share = it->first;
04226 }
04227 if (flow > 0) {
04228 new_shares[last_share + (uint)flow] = st;
04229 if (this->unrestricted < last_share) {
04230 this->ReleaseShare(st);
04231 } else {
04232 this->unrestricted += flow;
04233 }
04234 }
04235 this->shares.swap(new_shares);
04236 }
04237
04243 void FlowStat::RestrictShare(StationID st)
04244 {
04245 assert(!this->shares.empty());
04246 uint flow = 0;
04247 uint last_share = 0;
04248 SharesMap new_shares;
04249 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04250 if (flow == 0) {
04251 if (it->first > this->unrestricted) return;
04252 if (it->second == st) {
04253 flow = it->first - last_share;
04254 this->unrestricted -= flow;
04255 } else {
04256 new_shares[it->first] = it->second;
04257 }
04258 } else {
04259 new_shares[it->first - flow] = it->second;
04260 }
04261 last_share = it->first;
04262 }
04263 if (flow == 0) return;
04264 new_shares[last_share + flow] = st;
04265 this->shares.swap(new_shares);
04266 assert(!this->shares.empty());
04267 }
04268
04274 void FlowStat::ReleaseShare(StationID st)
04275 {
04276 assert(!this->shares.empty());
04277 uint flow = 0;
04278 uint next_share = 0;
04279 bool found = false;
04280 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
04281 if (it->first < this->unrestricted) return;
04282 if (found) {
04283 flow = next_share - it->first;
04284 this->unrestricted += flow;
04285 break;
04286 } else {
04287 if (it->first == this->unrestricted) return;
04288 if (it->second == st) found = true;
04289 }
04290 next_share = it->first;
04291 }
04292 if (flow == 0) return;
04293 SharesMap new_shares;
04294 new_shares[flow] = st;
04295 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
04296 if (it->second != st) {
04297 new_shares[flow + it->first] = it->second;
04298 } else {
04299 flow = 0;
04300 }
04301 }
04302 this->shares.swap(new_shares);
04303 assert(!this->shares.empty());
04304 }
04305
04310 void FlowStat::ScaleToMonthly(uint runtime)
04311 {
04312 SharesMap new_shares;
04313 uint share = 0;
04314 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
04315 share = max(share + 1, i->first * 30 / runtime);
04316 new_shares[share] = i->second;
04317 if (this->unrestricted == i->first) this->unrestricted = share;
04318 }
04319 this->shares.swap(new_shares);
04320 }
04321
04328 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
04329 {
04330 FlowStatMap::iterator origin_it = this->find(origin);
04331 if (origin_it == this->end()) {
04332 this->insert(std::make_pair(origin, FlowStat(via, flow)));
04333 } else {
04334 origin_it->second.ChangeShare(via, flow);
04335 assert(!origin_it->second.GetShares()->empty());
04336 }
04337 }
04338
04347 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
04348 {
04349 FlowStatMap::iterator prev_it = this->find(origin);
04350 if (prev_it == this->end()) {
04351 FlowStat fs(via, flow);
04352 fs.AppendShare(INVALID_STATION, flow);
04353 this->insert(std::make_pair(origin, fs));
04354 } else {
04355 prev_it->second.ChangeShare(via, flow);
04356 prev_it->second.ChangeShare(INVALID_STATION, flow);
04357 assert(!prev_it->second.GetShares()->empty());
04358 }
04359 }
04360
04365 void FlowStatMap::FinalizeLocalConsumption(StationID self)
04366 {
04367 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
04368 FlowStat &fs = i->second;
04369 uint local = fs.GetShare(INVALID_STATION);
04370 if (local > INT_MAX) {
04371 fs.ChangeShare(self, -INT_MAX);
04372 fs.ChangeShare(INVALID_STATION, -INT_MAX);
04373 local -= INT_MAX;
04374 }
04375 fs.ChangeShare(self, -(int)local);
04376 fs.ChangeShare(INVALID_STATION, -(int)local);
04377
04378
04379
04380 assert(!fs.GetShares()->empty());
04381 }
04382 }
04383
04390 StationIDStack FlowStatMap::DeleteFlows(StationID via)
04391 {
04392 StationIDStack ret;
04393 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
04394 FlowStat &s_flows = f_it->second;
04395 s_flows.ChangeShare(via, INT_MIN);
04396 if (s_flows.GetShares()->empty()) {
04397 ret.Push(f_it->first);
04398 this->erase(f_it++);
04399 } else {
04400 ++f_it;
04401 }
04402 }
04403 return ret;
04404 }
04405
04410 void FlowStatMap::RestrictFlows(StationID via)
04411 {
04412 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
04413 it->second.RestrictShare(via);
04414 }
04415 }
04416
04421 void FlowStatMap::ReleaseFlows(StationID via)
04422 {
04423 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
04424 it->second.ReleaseShare(via);
04425 }
04426 }
04427
04433 uint GoodsEntry::GetSumFlowVia(StationID via) const
04434 {
04435 uint ret = 0;
04436 for (FlowStatMap::const_iterator i = this->flows.begin(); i != this->flows.end(); ++i) {
04437 ret += i->second.GetShare(via);
04438 }
04439 return ret;
04440 }
04441
04442 extern const TileTypeProcs _tile_type_station_procs = {
04443 DrawTile_Station,
04444 GetSlopePixelZ_Station,
04445 ClearTile_Station,
04446 NULL,
04447 GetTileDesc_Station,
04448 GetTileTrackStatus_Station,
04449 ClickTile_Station,
04450 AnimateTile_Station,
04451 TileLoop_Station,
04452 ChangeTileOwner_Station,
04453 NULL,
04454 VehicleEnter_Station,
04455 GetFoundation_Station,
04456 TerraformTile_Station,
04457 };