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