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