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, NS_ACCEPTANCE, 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
00638 static void DeleteStationIfEmpty(BaseStation *st)
00639 {
00640 if (!st->IsInUse()) {
00641 st->delete_ctr = 0;
00642 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
00643 }
00644
00645 UpdateStationSignCoord(st);
00646 }
00647
00648 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00649
00659 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
00660 {
00661 if (check_bridge && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00662 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00663 }
00664
00665 CommandCost ret = EnsureNoVehicleOnGround(tile);
00666 if (ret.Failed()) return ret;
00667
00668 int z;
00669 Slope tileh = GetTileSlope(tile, &z);
00670
00671
00672
00673
00674
00675 if ((!allow_steep && IsSteepSlope(tileh)) ||
00676 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
00677 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00678 }
00679
00680 CommandCost cost(EXPENSES_CONSTRUCTION);
00681 int flat_z = z + GetSlopeMaxZ(tileh);
00682 if (tileh != SLOPE_FLAT) {
00683
00684 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
00685 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
00686 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00687 }
00688 }
00689 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
00690 }
00691
00692
00693 if (allowed_z < 0) {
00694
00695 allowed_z = flat_z;
00696 } else if (allowed_z != flat_z) {
00697 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00698 }
00699
00700 return cost;
00701 }
00702
00709 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
00710 {
00711 CommandCost cost(EXPENSES_CONSTRUCTION);
00712 int allowed_z = -1;
00713
00714 TILE_AREA_LOOP(tile_cur, tile_area) {
00715 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
00716 if (ret.Failed()) return ret;
00717 cost.AddCost(ret);
00718
00719 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00720 if (ret.Failed()) return ret;
00721 cost.AddCost(ret);
00722 }
00723
00724 return cost;
00725 }
00726
00741 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)
00742 {
00743 CommandCost cost(EXPENSES_CONSTRUCTION);
00744 int allowed_z = -1;
00745 uint invalid_dirs = 5 << axis;
00746
00747 const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
00748 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
00749
00750 TILE_AREA_LOOP(tile_cur, tile_area) {
00751 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
00752 if (ret.Failed()) return ret;
00753 cost.AddCost(ret);
00754
00755 if (slope_cb) {
00756
00757 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
00758 if (ret.Failed()) return ret;
00759 }
00760
00761
00762
00763
00764 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
00765 if (!IsRailStation(tile_cur)) {
00766 return ClearTile_Station(tile_cur, DC_AUTO);
00767 } else {
00768 StationID st = GetStationIndex(tile_cur);
00769 if (*station == INVALID_STATION) {
00770 *station = st;
00771 } else if (*station != st) {
00772 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00773 }
00774 }
00775 } else {
00776
00777
00778 if (rt != INVALID_RAILTYPE &&
00779 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
00780 HasPowerOnRail(GetRailType(tile_cur), rt)) {
00781
00782
00783
00784
00785
00786
00787 TrackBits tracks = GetTrackBits(tile_cur);
00788 Track track = RemoveFirstTrack(&tracks);
00789 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
00790
00791 if (tracks == TRACK_BIT_NONE && track == expected_track) {
00792
00793 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
00794 Train *v = GetTrainForReservation(tile_cur, track);
00795 if (v != NULL) {
00796 *affected_vehicles.Append() = v;
00797 }
00798 }
00799 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
00800 if (ret.Failed()) return ret;
00801 cost.AddCost(ret);
00802
00803 continue;
00804 }
00805 }
00806 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00807 if (ret.Failed()) return ret;
00808 cost.AddCost(ret);
00809 }
00810 }
00811
00812 return cost;
00813 }
00814
00827 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)
00828 {
00829 CommandCost cost(EXPENSES_CONSTRUCTION);
00830 int allowed_z = -1;
00831
00832 TILE_AREA_LOOP(cur_tile, tile_area) {
00833 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
00834 if (ret.Failed()) return ret;
00835 cost.AddCost(ret);
00836
00837
00838
00839
00840 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
00841 if (!IsRoadStop(cur_tile)) {
00842 return ClearTile_Station(cur_tile, DC_AUTO);
00843 } else {
00844 if (is_truck_stop != IsTruckStop(cur_tile) ||
00845 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
00846 return ClearTile_Station(cur_tile, DC_AUTO);
00847 }
00848
00849 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
00850 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00851 }
00852 StationID st = GetStationIndex(cur_tile);
00853 if (*station == INVALID_STATION) {
00854 *station = st;
00855 } else if (*station != st) {
00856 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
00857 }
00858 }
00859 } else {
00860 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
00861
00862 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
00863 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
00864
00865 switch (CountBits(rb)) {
00866 case 1:
00867 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00868
00869 case 2:
00870 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
00871 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
00872
00873 default:
00874 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
00875 }
00876 }
00877
00878 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
00879 uint num_roadbits = 0;
00880 if (build_over_road) {
00881
00882 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
00883 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
00884 if (road_owner == OWNER_TOWN) {
00885 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
00886 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
00887 CommandCost ret = CheckOwnership(road_owner);
00888 if (ret.Failed()) return ret;
00889 }
00890 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
00891 }
00892
00893
00894 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
00895 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
00896 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
00897 CommandCost ret = CheckOwnership(tram_owner);
00898 if (ret.Failed()) return ret;
00899 }
00900 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
00901 }
00902
00903
00904 rts |= cur_rts;
00905 } else {
00906 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00907 if (ret.Failed()) return ret;
00908 cost.AddCost(ret);
00909 }
00910
00911 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
00912 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
00913 }
00914 }
00915
00916 return cost;
00917 }
00918
00926 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
00927 {
00928 TileArea cur_ta = st->train_station;
00929
00930
00931 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
00932 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
00933 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
00934 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
00935 new_ta.tile = TileXY(x, y);
00936
00937
00938 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
00939 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
00940 }
00941
00942 return CommandCost();
00943 }
00944
00945 static inline byte *CreateSingle(byte *layout, int n)
00946 {
00947 int i = n;
00948 do *layout++ = 0; while (--i);
00949 layout[((n - 1) >> 1) - n] = 2;
00950 return layout;
00951 }
00952
00953 static inline byte *CreateMulti(byte *layout, int n, byte b)
00954 {
00955 int i = n;
00956 do *layout++ = b; while (--i);
00957 if (n > 4) {
00958 layout[0 - n] = 0;
00959 layout[n - 1 - n] = 0;
00960 }
00961 return layout;
00962 }
00963
00971 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
00972 {
00973 if (statspec != NULL && statspec->lengths >= plat_len &&
00974 statspec->platforms[plat_len - 1] >= numtracks &&
00975 statspec->layouts[plat_len - 1][numtracks - 1]) {
00976
00977 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
00978 plat_len * numtracks);
00979 return;
00980 }
00981
00982 if (plat_len == 1) {
00983 CreateSingle(layout, numtracks);
00984 } else {
00985 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
00986 numtracks >>= 1;
00987
00988 while (--numtracks >= 0) {
00989 layout = CreateMulti(layout, plat_len, 4);
00990 layout = CreateMulti(layout, plat_len, 6);
00991 }
00992 }
00993 }
00994
01006 template <class T, StringID error_message>
01007 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
01008 {
01009 assert(*st == NULL);
01010 bool check_surrounding = true;
01011
01012 if (_settings_game.station.adjacent_stations) {
01013 if (existing_station != INVALID_STATION) {
01014 if (adjacent && existing_station != station_to_join) {
01015
01016
01017 return_cmd_error(error_message);
01018 } else {
01019
01020
01021 *st = T::GetIfValid(existing_station);
01022 check_surrounding = (*st == NULL);
01023 }
01024 } else {
01025
01026
01027 if (adjacent) check_surrounding = false;
01028 }
01029 }
01030
01031 if (check_surrounding) {
01032
01033 CommandCost ret = GetStationAround(ta, existing_station, st);
01034 if (ret.Failed()) return ret;
01035 }
01036
01037
01038 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
01039
01040 return CommandCost();
01041 }
01042
01052 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01053 {
01054 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
01055 }
01056
01066 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
01067 {
01068 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
01069 }
01070
01088 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01089 {
01090
01091 RailType rt = Extract<RailType, 0, 4>(p1);
01092 Axis axis = Extract<Axis, 4, 1>(p1);
01093 byte numtracks = GB(p1, 8, 8);
01094 byte plat_len = GB(p1, 16, 8);
01095 bool adjacent = HasBit(p1, 24);
01096
01097 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
01098 byte spec_index = GB(p2, 8, 8);
01099 StationID station_to_join = GB(p2, 16, 16);
01100
01101
01102 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
01103 if (ret.Failed()) return ret;
01104
01105 if (!ValParamRailtype(rt)) return CMD_ERROR;
01106
01107
01108 if ((uint)spec_class >= StationClass::GetCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
01109 if (spec_index >= StationClass::GetCount(spec_class)) return CMD_ERROR;
01110 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
01111
01112 int w_org, h_org;
01113 if (axis == AXIS_X) {
01114 w_org = plat_len;
01115 h_org = numtracks;
01116 } else {
01117 h_org = plat_len;
01118 w_org = numtracks;
01119 }
01120
01121 bool reuse = (station_to_join != NEW_STATION);
01122 if (!reuse) station_to_join = INVALID_STATION;
01123 bool distant_join = (station_to_join != INVALID_STATION);
01124
01125 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01126
01127 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
01128
01129
01130 TileArea new_location(tile_org, w_org, h_org);
01131
01132
01133 StationID est = INVALID_STATION;
01134 SmallVector<Train *, 4> affected_vehicles;
01135
01136 CommandCost cost = CheckFlatLandRailStation(TileArea(tile_org, w_org, h_org), flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
01137 if (cost.Failed()) return cost;
01138
01139 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
01140 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
01141
01142 Station *st = NULL;
01143 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
01144 if (ret.Failed()) return ret;
01145
01146
01147 if (st == NULL && reuse) st = GetClosestDeletedStation(tile_org);
01148
01149 if (st != NULL) {
01150
01151 if (st->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01152
01153 if (st->train_station.tile != INVALID_TILE) {
01154 CommandCost ret = CanExpandRailStation(st, new_location, axis);
01155 if (ret.Failed()) return ret;
01156 }
01157
01158
01159 CommandCost ret = st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST);
01160 if (ret.Failed()) return ret;
01161 } else {
01162
01163 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01164
01165 if (flags & DC_EXEC) {
01166 st = new Station(tile_org);
01167
01168 st->town = ClosestTownFromTile(tile_org, UINT_MAX);
01169 st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);
01170
01171 if (Company::IsValidID(_current_company)) {
01172 SetBit(st->town->have_ratings, _current_company);
01173 }
01174 }
01175 }
01176
01177
01178 const StationSpec *statspec = StationClass::Get(spec_class, spec_index);
01179 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
01180 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
01181
01182 if (statspec != NULL) {
01183
01184
01185
01186 if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
01187 return CMD_ERROR;
01188 }
01189
01190
01191 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
01192 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
01193 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
01194 }
01195 }
01196
01197 if (flags & DC_EXEC) {
01198 TileIndexDiff tile_delta;
01199 byte *layout_ptr;
01200 byte numtracks_orig;
01201 Track track;
01202
01203 st->train_station = new_location;
01204 st->AddFacility(FACIL_TRAIN, new_location.tile);
01205
01206 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
01207
01208 if (statspec != NULL) {
01209
01210
01211 st->cached_anim_triggers |= statspec->animation.triggers;
01212 }
01213
01214 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
01215 track = AxisToTrack(axis);
01216
01217 layout_ptr = AllocaM(byte, numtracks * plat_len);
01218 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
01219
01220 numtracks_orig = numtracks;
01221
01222 Company *c = Company::Get(st->owner);
01223 do {
01224 TileIndex tile = tile_org;
01225 int w = plat_len;
01226 do {
01227 byte layout = *layout_ptr++;
01228 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
01229
01230 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
01231 if (v != NULL) {
01232 FreeTrainTrackReservation(v);
01233 *affected_vehicles.Append() = v;
01234 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01235 for (; v->Next() != NULL; v = v->Next()) { }
01236 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
01237 }
01238 }
01239
01240
01241 if (IsRailStationTile(tile)) {
01242 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
01243 c->infrastructure.station--;
01244 }
01245
01246
01247 DeleteAnimatedTile(tile);
01248 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
01249 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
01250
01251 DeallocateSpecFromStation(st, old_specindex);
01252
01253 SetCustomStationSpecIndex(tile, specindex);
01254 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
01255 SetAnimationFrame(tile, 0);
01256
01257 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
01258 c->infrastructure.station++;
01259
01260 if (statspec != NULL) {
01261
01262 uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
01263
01264
01265 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
01266 if (callback != CALLBACK_FAILED) {
01267 if (callback < 8) {
01268 SetStationGfx(tile, (callback & ~1) + axis);
01269 } else {
01270 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
01271 }
01272 }
01273
01274
01275 TriggerStationAnimation(st, tile, SAT_BUILT);
01276 }
01277
01278 tile += tile_delta;
01279 } while (--w);
01280 AddTrackToSignalBuffer(tile_org, track, _current_company);
01281 YapfNotifyTrackLayoutChange(tile_org, track);
01282 tile_org += tile_delta ^ TileDiffXY(1, 1);
01283 } while (--numtracks);
01284
01285 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
01286
01287 Train *v = affected_vehicles[i];
01288 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01289 TryPathReserve(v, true, true);
01290 for (; v->Next() != NULL; v = v->Next()) { }
01291 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01292 }
01293
01294 st->MarkTilesDirty(false);
01295 st->UpdateVirtCoord();
01296 UpdateStationAcceptance(st, false);
01297 st->RecomputeIndustriesNear();
01298 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01299 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01300 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01301 DirtyCompanyInfrastructureWindows(st->owner);
01302 }
01303
01304 return cost;
01305 }
01306
01307 static void MakeRailStationAreaSmaller(BaseStation *st)
01308 {
01309 TileArea ta = st->train_station;
01310
01311 restart:
01312
01313
01314 if (ta.w != 0 && ta.h != 0) {
01315
01316 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
01317
01318 if (++i == ta.h) {
01319 ta.tile += TileDiffXY(1, 0);
01320 ta.w--;
01321 goto restart;
01322 }
01323 }
01324
01325
01326 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
01327
01328 if (++i == ta.h) {
01329 ta.w--;
01330 goto restart;
01331 }
01332 }
01333
01334
01335 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
01336
01337 if (++i == ta.w) {
01338 ta.tile += TileDiffXY(0, 1);
01339 ta.h--;
01340 goto restart;
01341 }
01342 }
01343
01344
01345 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
01346
01347 if (++i == ta.w) {
01348 ta.h--;
01349 goto restart;
01350 }
01351 }
01352 } else {
01353 ta.Clear();
01354 }
01355
01356 st->train_station = ta;
01357 }
01358
01369 template <class T>
01370 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
01371 {
01372
01373 int quantity = 0;
01374 CommandCost total_cost(EXPENSES_CONSTRUCTION);
01375
01376
01377 TILE_AREA_LOOP(tile, ta) {
01378
01379 if (!HasStationTileRail(tile)) continue;
01380
01381
01382 CommandCost ret = EnsureNoVehicleOnGround(tile);
01383 if (ret.Failed()) continue;
01384
01385
01386 T *st = T::GetByTile(tile);
01387 if (st == NULL) continue;
01388
01389 if (_current_company != OWNER_WATER) {
01390 CommandCost ret = CheckOwnership(st->owner);
01391 if (ret.Failed()) continue;
01392 }
01393
01394
01395 quantity++;
01396
01397 if (keep_rail || IsStationTileBlocked(tile)) {
01398
01399
01400 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
01401 }
01402
01403 if (flags & DC_EXEC) {
01404
01405 uint specindex = GetCustomStationSpecIndex(tile);
01406 Track track = GetRailStationTrack(tile);
01407 Owner owner = GetTileOwner(tile);
01408 RailType rt = GetRailType(tile);
01409 Train *v = NULL;
01410
01411 if (HasStationReservation(tile)) {
01412 v = GetTrainForReservation(tile, track);
01413 if (v != NULL) {
01414
01415 FreeTrainTrackReservation(v);
01416 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
01417 Vehicle *temp = v;
01418 for (; temp->Next() != NULL; temp = temp->Next()) { }
01419 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
01420 }
01421 }
01422
01423 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
01424 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
01425
01426 DoClearSquare(tile);
01427 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01428 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
01429 Company::Get(owner)->infrastructure.station--;
01430 DirtyCompanyInfrastructureWindows(owner);
01431
01432 st->rect.AfterRemoveTile(st, tile);
01433 AddTrackToSignalBuffer(tile, track, owner);
01434 YapfNotifyTrackLayoutChange(tile, track);
01435
01436 DeallocateSpecFromStation(st, specindex);
01437
01438 affected_stations.Include(st);
01439
01440 if (v != NULL) {
01441
01442 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
01443 TryPathReserve(v, true, true);
01444 for (; v->Next() != NULL; v = v->Next()) { }
01445 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
01446 }
01447 }
01448 }
01449
01450 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
01451
01452 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01453 T *st = *stp;
01454
01455
01456
01457
01458 MakeRailStationAreaSmaller(st);
01459 UpdateStationSignCoord(st);
01460
01461
01462 if (st->train_station.tile == INVALID_TILE) {
01463 st->facilities &= ~FACIL_TRAIN;
01464 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01465 st->UpdateVirtCoord();
01466 DeleteStationIfEmpty(st);
01467 }
01468 }
01469
01470 total_cost.AddCost(quantity * removal_cost);
01471 return total_cost;
01472 }
01473
01485 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01486 {
01487 TileIndex end = p1 == 0 ? start : p1;
01488 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01489
01490 TileArea ta(start, end);
01491 SmallVector<Station *, 4> affected_stations;
01492
01493 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
01494 if (ret.Failed()) return ret;
01495
01496
01497 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
01498 Station *st = *stp;
01499
01500 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01501 st->MarkTilesDirty(false);
01502 st->RecomputeIndustriesNear();
01503 }
01504
01505
01506 return ret;
01507 }
01508
01520 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01521 {
01522 TileIndex end = p1 == 0 ? start : p1;
01523 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
01524
01525 TileArea ta(start, end);
01526 SmallVector<Waypoint *, 4> affected_stations;
01527
01528 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
01529 }
01530
01531
01539 template <class T>
01540 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
01541 {
01542
01543 if (_current_company != OWNER_WATER) {
01544 CommandCost ret = CheckOwnership(st->owner);
01545 if (ret.Failed()) return ret;
01546 }
01547
01548
01549 TileArea ta = st->train_station;
01550
01551 assert(ta.w != 0 && ta.h != 0);
01552
01553 CommandCost cost(EXPENSES_CONSTRUCTION);
01554
01555 TILE_AREA_LOOP(tile, ta) {
01556
01557 if (!st->TileBelongsToRailStation(tile)) continue;
01558
01559 CommandCost ret = EnsureNoVehicleOnGround(tile);
01560 if (ret.Failed()) return ret;
01561
01562 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
01563 if (flags & DC_EXEC) {
01564
01565 Track track = GetRailStationTrack(tile);
01566 Owner owner = GetTileOwner(tile);
01567 Train *v = NULL;
01568 if (HasStationReservation(tile)) {
01569 v = GetTrainForReservation(tile, track);
01570 if (v != NULL) FreeTrainTrackReservation(v);
01571 }
01572 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
01573 Company::Get(owner)->infrastructure.station--;
01574 DoClearSquare(tile);
01575 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
01576 AddTrackToSignalBuffer(tile, track, owner);
01577 YapfNotifyTrackLayoutChange(tile, track);
01578 if (v != NULL) TryPathReserve(v, true);
01579 }
01580 }
01581
01582 if (flags & DC_EXEC) {
01583 st->rect.AfterRemoveRect(st, st->train_station);
01584
01585 st->train_station.Clear();
01586
01587 st->facilities &= ~FACIL_TRAIN;
01588
01589 free(st->speclist);
01590 st->num_specs = 0;
01591 st->speclist = NULL;
01592 st->cached_anim_triggers = 0;
01593
01594 DirtyCompanyInfrastructureWindows(st->owner);
01595 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
01596 st->UpdateVirtCoord();
01597 DeleteStationIfEmpty(st);
01598 }
01599
01600 return cost;
01601 }
01602
01609 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
01610 {
01611
01612 if (_current_company == OWNER_WATER) {
01613 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
01614 }
01615
01616 Station *st = Station::GetByTile(tile);
01617 CommandCost cost = RemoveRailStation(st, flags);
01618
01619 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
01620
01621 return cost;
01622 }
01623
01630 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
01631 {
01632
01633 if (_current_company == OWNER_WATER) {
01634 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
01635 }
01636
01637 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
01638 }
01639
01640
01646 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
01647 {
01648 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
01649
01650 if (*primary_stop == NULL) {
01651
01652 return primary_stop;
01653 } else {
01654
01655 RoadStop *stop = *primary_stop;
01656 while (stop->next != NULL) stop = stop->next;
01657 return &stop->next;
01658 }
01659 }
01660
01661 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
01662
01672 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
01673 {
01674 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
01675 }
01676
01692 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01693 {
01694 bool type = HasBit(p2, 0);
01695 bool is_drive_through = HasBit(p2, 1);
01696 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
01697 StationID station_to_join = GB(p2, 16, 16);
01698 bool reuse = (station_to_join != NEW_STATION);
01699 if (!reuse) station_to_join = INVALID_STATION;
01700 bool distant_join = (station_to_join != INVALID_STATION);
01701
01702 uint8 width = (uint8)GB(p1, 0, 8);
01703 uint8 lenght = (uint8)GB(p1, 8, 8);
01704
01705
01706 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
01707
01708 if (width == 0 || lenght == 0) return CMD_ERROR;
01709
01710 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
01711
01712 TileArea roadstop_area(tile, width, lenght);
01713
01714 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
01715
01716 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
01717
01718
01719 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
01720
01721 DiagDirection ddir = Extract<DiagDirection, 6, 2>(p2);
01722
01723
01724 if (!IsValidDiagDirection(ddir)) return CMD_ERROR;
01725
01726 if (is_drive_through && !IsValidAxis((Axis)ddir)) return CMD_ERROR;
01727
01728 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
01729 if (ret.Failed()) return ret;
01730
01731
01732 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
01733 StationID est = INVALID_STATION;
01734 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << ddir : 1 << ddir, is_drive_through, type, DiagDirToAxis(ddir), &est, rts);
01735 if (ret.Failed()) return ret;
01736 cost.AddCost(ret);
01737
01738 Station *st = NULL;
01739 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
01740 if (ret.Failed()) return ret;
01741
01742
01743 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
01744
01745
01746 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);
01747
01748 if (st != NULL) {
01749 if (st->owner != _current_company) {
01750 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
01751 }
01752
01753 CommandCost ret = st->rect.BeforeAddRect(roadstop_area.tile, roadstop_area.w, roadstop_area.h, StationRect::ADD_TEST);
01754 if (ret.Failed()) return ret;
01755 } else {
01756
01757 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
01758
01759 if (flags & DC_EXEC) {
01760 st = new Station(tile);
01761
01762 st->town = ClosestTownFromTile(tile, UINT_MAX);
01763 st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);
01764
01765 if (Company::IsValidID(_current_company)) {
01766 SetBit(st->town->have_ratings, _current_company);
01767 }
01768 }
01769 }
01770
01771 if (flags & DC_EXEC) {
01772
01773 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01774 RoadTypes cur_rts = GetRoadTypes(cur_tile);
01775 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
01776 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
01777
01778 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
01779 RemoveRoadStop(cur_tile, flags);
01780 }
01781
01782 RoadStop *road_stop = new RoadStop(cur_tile);
01783
01784 RoadStop **currstop = FindRoadStopSpot(type, st);
01785 *currstop = road_stop;
01786
01787 if (type) {
01788 st->truck_station.Add(cur_tile);
01789 } else {
01790 st->bus_station.Add(cur_tile);
01791 }
01792
01793
01794 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
01795
01796 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
01797
01798 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
01799 if (is_drive_through) {
01800
01801
01802 RoadType rt;
01803 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
01804 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
01805 if (c != NULL) {
01806 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
01807 DirtyCompanyInfrastructureWindows(c->index);
01808 }
01809 }
01810
01811 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, DiagDirToAxis(ddir));
01812 road_stop->MakeDriveThrough();
01813 } else {
01814
01815 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
01816 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
01817 }
01818 Company::Get(st->owner)->infrastructure.station++;
01819 DirtyCompanyInfrastructureWindows(st->owner);
01820
01821 MarkTileDirtyByTile(cur_tile);
01822 }
01823 }
01824
01825 if (st != NULL) {
01826 st->UpdateVirtCoord();
01827 UpdateStationAcceptance(st, false);
01828 st->RecomputeIndustriesNear();
01829 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
01830 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
01831 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01832 }
01833 return cost;
01834 }
01835
01836
01837 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
01838 {
01839 if (v->type == VEH_ROAD) {
01840
01841
01842
01843
01844
01845
01846 RoadVehicle *rv = RoadVehicle::From(v);
01847 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
01848 }
01849
01850 return NULL;
01851 }
01852
01853
01860 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
01861 {
01862 Station *st = Station::GetByTile(tile);
01863
01864 if (_current_company != OWNER_WATER) {
01865 CommandCost ret = CheckOwnership(st->owner);
01866 if (ret.Failed()) return ret;
01867 }
01868
01869 bool is_truck = IsTruckStop(tile);
01870
01871 RoadStop **primary_stop;
01872 RoadStop *cur_stop;
01873 if (is_truck) {
01874 primary_stop = &st->truck_stops;
01875 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
01876 } else {
01877 primary_stop = &st->bus_stops;
01878 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
01879 }
01880
01881 assert(cur_stop != NULL);
01882
01883
01884 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
01885
01886 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
01887 } else {
01888 CommandCost ret = EnsureNoVehicleOnGround(tile);
01889 if (ret.Failed()) return ret;
01890 }
01891
01892 if (flags & DC_EXEC) {
01893 if (*primary_stop == cur_stop) {
01894
01895 *primary_stop = cur_stop->next;
01896
01897 if (*primary_stop == NULL) {
01898 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
01899 }
01900 } else {
01901
01902 RoadStop *pred = *primary_stop;
01903 while (pred->next != cur_stop) pred = pred->next;
01904 pred->next = cur_stop->next;
01905 }
01906
01907
01908 RoadType rt;
01909 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
01910 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
01911 if (c != NULL) {
01912 c->infrastructure.road[rt] -= 2;
01913 DirtyCompanyInfrastructureWindows(c->index);
01914 }
01915 }
01916 Company::Get(st->owner)->infrastructure.station--;
01917
01918 if (IsDriveThroughStopTile(tile)) {
01919
01920 cur_stop->ClearDriveThrough();
01921 } else {
01922 DoClearSquare(tile);
01923 }
01924
01925 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
01926 delete cur_stop;
01927
01928
01929 RoadVehicle *v;
01930 FOR_ALL_ROADVEHICLES(v) {
01931 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
01932 v->dest_tile == tile) {
01933 v->dest_tile = v->GetOrderStationLocation(st->index);
01934 }
01935 }
01936
01937 st->rect.AfterRemoveTile(st, tile);
01938
01939 st->UpdateVirtCoord();
01940 st->RecomputeIndustriesNear();
01941 DeleteStationIfEmpty(st);
01942
01943
01944 if (is_truck) {
01945 st->truck_station.Clear();
01946 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
01947 } else {
01948 st->bus_station.Clear();
01949 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
01950 }
01951 }
01952
01953 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
01954 }
01955
01966 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01967 {
01968 uint8 width = (uint8)GB(p1, 0, 8);
01969 uint8 height = (uint8)GB(p1, 8, 8);
01970
01971
01972 if (width == 0 || height == 0) return CMD_ERROR;
01973
01974 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
01975
01976 TileArea roadstop_area(tile, width, height);
01977
01978 int quantity = 0;
01979 CommandCost cost(EXPENSES_CONSTRUCTION);
01980 TILE_AREA_LOOP(cur_tile, roadstop_area) {
01981
01982 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
01983
01984
01985 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
01986 RoadTypes rts = GetRoadTypes(cur_tile);
01987 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
01988 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
01989 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
01990
01991 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
01992 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
01993 CommandCost ret = RemoveRoadStop(cur_tile, flags);
01994 if (ret.Failed()) return ret;
01995 cost.AddCost(ret);
01996
01997 quantity++;
01998
01999 if ((flags & DC_EXEC) && is_drive_through) {
02000 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
02001 road_owner, tram_owner);
02002
02003
02004 RoadType rt;
02005 FOR_EACH_SET_ROADTYPE(rt, rts) {
02006 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
02007 if (c != NULL) {
02008 c->infrastructure.road[rt] += CountBits(road_bits);
02009 DirtyCompanyInfrastructureWindows(c->index);
02010 }
02011 }
02012 }
02013 }
02014
02015 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
02016
02017 return cost;
02018 }
02019
02026 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
02027 {
02028 uint mindist = UINT_MAX;
02029
02030 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
02031 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
02032 }
02033
02034 return mindist;
02035 }
02036
02046 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
02047 {
02048
02049
02050 if (as->noise_level < 2) return as->noise_level;
02051
02052 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
02053
02054
02055
02056
02057
02058 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
02059
02060
02061
02062 uint noise_reduction = distance / town_tolerance_distance;
02063
02064
02065
02066 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
02067 }
02068
02076 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
02077 {
02078 Town *t, *nearest = NULL;
02079 uint add = as->size_x + as->size_y - 2;
02080 uint mindist = UINT_MAX - add;
02081 FOR_ALL_TOWNS(t) {
02082 if (DistanceManhattan(t->xy, it) < mindist + add) {
02083 TileIterator *copy = it.Clone();
02084 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
02085 delete copy;
02086 if (dist < mindist) {
02087 nearest = t;
02088 mindist = dist;
02089 }
02090 }
02091 }
02092
02093 return nearest;
02094 }
02095
02096
02098 void UpdateAirportsNoise()
02099 {
02100 Town *t;
02101 const Station *st;
02102
02103 FOR_ALL_TOWNS(t) t->noise_reached = 0;
02104
02105 FOR_ALL_STATIONS(st) {
02106 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
02107 const AirportSpec *as = st->airport.GetSpec();
02108 AirportTileIterator it(st);
02109 Town *nearest = AirportGetNearestTown(as, it);
02110 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
02111 }
02112 }
02113 }
02114
02128 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02129 {
02130 StationID station_to_join = GB(p2, 16, 16);
02131 bool reuse = (station_to_join != NEW_STATION);
02132 if (!reuse) station_to_join = INVALID_STATION;
02133 bool distant_join = (station_to_join != INVALID_STATION);
02134 byte airport_type = GB(p1, 0, 8);
02135 byte layout = GB(p1, 8, 8);
02136
02137 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02138
02139 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
02140
02141 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02142 if (ret.Failed()) return ret;
02143
02144
02145 const AirportSpec *as = AirportSpec::Get(airport_type);
02146 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
02147
02148 Direction rotation = as->rotation[layout];
02149 Town *t = ClosestTownFromTile(tile, UINT_MAX);
02150 int w = as->size_x;
02151 int h = as->size_y;
02152 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
02153
02154 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
02155 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
02156 }
02157
02158 CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
02159 if (cost.Failed()) return cost;
02160
02161
02162 AirportTileTableIterator iter(as->table[layout], tile);
02163 Town *nearest = AirportGetNearestTown(as, iter);
02164 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
02165
02166
02167 StringID authority_refuse_message = STR_NULL;
02168
02169 if (_settings_game.economy.station_noise_level) {
02170
02171 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
02172 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
02173 }
02174 } else {
02175 uint num = 0;
02176 const Station *st;
02177 FOR_ALL_STATIONS(st) {
02178 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
02179 }
02180 if (num >= 2) {
02181 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
02182 }
02183 }
02184
02185 if (authority_refuse_message != STR_NULL) {
02186 SetDParam(0, t->index);
02187 return_cmd_error(authority_refuse_message);
02188 }
02189
02190 Station *st = NULL;
02191 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
02192 if (ret.Failed()) return ret;
02193
02194
02195 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02196
02197
02198 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02199
02200 if (st != NULL) {
02201 if (st->owner != _current_company) {
02202 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02203 }
02204
02205 CommandCost ret = st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST);
02206 if (ret.Failed()) return ret;
02207
02208 if (st->airport.tile != INVALID_TILE) {
02209 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
02210 }
02211 } else {
02212
02213 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02214
02215 if (flags & DC_EXEC) {
02216 st = new Station(tile);
02217
02218 st->town = t;
02219 st->string_id = GenerateStationName(st, tile, !(GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
02220
02221 if (Company::IsValidID(_current_company)) {
02222 SetBit(st->town->have_ratings, _current_company);
02223 }
02224 }
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 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
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 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_PLANES);
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
02366 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
02367 {
02368 const Vehicle *v;
02369 FOR_ALL_VEHICLES(v) {
02370 if ((v->owner == company) == include_company) {
02371 const Order *order;
02372 FOR_VEHICLE_ORDERS(v, order) {
02373 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
02374 return true;
02375 }
02376 }
02377 }
02378 }
02379 return false;
02380 }
02381
02382 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
02383 {-1, 0},
02384 { 0, 0},
02385 { 0, 0},
02386 { 0, -1}
02387 };
02388 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
02389 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
02390
02400 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02401 {
02402 StationID station_to_join = GB(p2, 16, 16);
02403 bool reuse = (station_to_join != NEW_STATION);
02404 if (!reuse) station_to_join = INVALID_STATION;
02405 bool distant_join = (station_to_join != INVALID_STATION);
02406
02407 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
02408
02409 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
02410 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02411 direction = ReverseDiagDir(direction);
02412
02413
02414 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02415
02416 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
02417 if (ret.Failed()) return ret;
02418
02419 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02420
02421 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02422 if (ret.Failed()) return ret;
02423
02424 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
02425
02426 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02427 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02428 }
02429
02430 if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
02431
02432
02433 WaterClass wc = GetWaterClass(tile_cur);
02434
02435 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02436 if (ret.Failed()) return ret;
02437
02438 tile_cur += TileOffsByDiagDir(direction);
02439 if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur) != SLOPE_FLAT) {
02440 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
02441 }
02442
02443
02444 Station *st = NULL;
02445 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
02446 TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02447 _dock_w_chk[direction], _dock_h_chk[direction]), &st);
02448 if (ret.Failed()) return ret;
02449
02450
02451 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
02452
02453
02454 if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
02455
02456 if (st != NULL) {
02457 if (st->owner != _current_company) {
02458 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
02459 }
02460
02461 CommandCost ret = st->rect.BeforeAddRect(
02462 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02463 _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST);
02464 if (ret.Failed()) return ret;
02465
02466 if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
02467 } else {
02468
02469 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
02470
02471 if (flags & DC_EXEC) {
02472 st = new Station(tile);
02473
02474 st->town = ClosestTownFromTile(tile, UINT_MAX);
02475 st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
02476
02477 if (Company::IsValidID(_current_company)) {
02478 SetBit(st->town->have_ratings, _current_company);
02479 }
02480 }
02481 }
02482
02483 if (flags & DC_EXEC) {
02484 st->dock_tile = tile;
02485 st->AddFacility(FACIL_DOCK, tile);
02486
02487 st->rect.BeforeAddRect(
02488 tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
02489 _dock_w_chk[direction], _dock_h_chk[direction], 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
02579 static void DrawTile_Station(TileInfo *ti)
02580 {
02581 const NewGRFSpriteLayout *layout = NULL;
02582 DrawTileSprites tmp_rail_layout;
02583 const DrawTileSprites *t = NULL;
02584 RoadTypes roadtypes;
02585 int32 total_offset;
02586 const RailtypeInfo *rti = NULL;
02587 uint32 relocation = 0;
02588 uint32 ground_relocation = 0;
02589 BaseStation *st = NULL;
02590 const StationSpec *statspec = NULL;
02591 uint tile_layout = 0;
02592
02593 if (HasStationRail(ti->tile)) {
02594 rti = GetRailTypeInfo(GetRailType(ti->tile));
02595 roadtypes = ROADTYPES_NONE;
02596 total_offset = rti->GetRailtypeSpriteOffset();
02597
02598 if (IsCustomStationSpecIndex(ti->tile)) {
02599
02600 st = BaseStation::GetByTile(ti->tile);
02601 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
02602
02603 if (statspec != NULL) {
02604 tile_layout = GetStationGfx(ti->tile);
02605
02606 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
02607 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
02608 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
02609 }
02610
02611
02612 if (statspec->renderdata != NULL) {
02613 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
02614 if (!layout->NeedsPreprocessing()) {
02615 t = layout;
02616 layout = NULL;
02617 }
02618 }
02619 }
02620 }
02621 } else {
02622 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
02623 total_offset = 0;
02624 }
02625
02626 StationGfx gfx = GetStationGfx(ti->tile);
02627 if (IsAirport(ti->tile)) {
02628 gfx = GetAirportGfx(ti->tile);
02629 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
02630 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
02631 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
02632 return;
02633 }
02634
02635
02636 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
02637 gfx = ats->grf_prop.subst_id;
02638 }
02639 switch (gfx) {
02640 case APT_RADAR_GRASS_FENCE_SW:
02641 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
02642 break;
02643 case APT_GRASS_FENCE_NE_FLAG:
02644 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
02645 break;
02646 case APT_RADAR_FENCE_SW:
02647 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
02648 break;
02649 case APT_RADAR_FENCE_NE:
02650 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
02651 break;
02652 case APT_GRASS_FENCE_NE_FLAG_2:
02653 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
02654 break;
02655 }
02656 }
02657
02658 Owner owner = GetTileOwner(ti->tile);
02659
02660 PaletteID palette;
02661 if (Company::IsValidID(owner)) {
02662 palette = COMPANY_SPRITE_COLOUR(owner);
02663 } else {
02664
02665 palette = PALETTE_TO_GREY;
02666 }
02667
02668 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
02669
02670
02671 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
02672 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
02673
02674
02675 uint edge_info = 0;
02676 int z;
02677 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
02678 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
02679 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
02680 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
02681
02682 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
02683
02684
02685 static const uint8 foundation_parts[] = {
02686 0, 0, 0, 0,
02687 0, 1, 2, 3,
02688 0, 4, 5, 6,
02689 7, 8, 9
02690 };
02691
02692 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02693 } else {
02694
02695
02696
02697
02698 static const uint8 composite_foundation_parts[] = {
02699
02700 0x00, 0xD1, 0xE4, 0xE0,
02701
02702 0xCA, 0xC9, 0xC4, 0xC0,
02703
02704 0xD2, 0x91, 0xE4, 0xA0,
02705
02706 0x4A, 0x09, 0x44
02707 };
02708
02709 uint8 parts = composite_foundation_parts[ti->tileh];
02710
02711
02712
02713 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
02714 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
02715
02716 if (parts == 0) {
02717
02718
02719
02720 goto draw_default_foundation;
02721 }
02722
02723 StartSpriteCombine();
02724 for (int i = 0; i < 8; i++) {
02725 if (HasBit(parts, i)) {
02726 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
02727 }
02728 }
02729 EndSpriteCombine();
02730 }
02731
02732 OffsetGroundSprite(31, 1);
02733 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
02734 } else {
02735 draw_default_foundation:
02736 DrawFoundation(ti, FOUNDATION_LEVELED);
02737 }
02738 }
02739
02740 if (IsBuoy(ti->tile)) {
02741 DrawWaterClassGround(ti);
02742 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
02743 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
02744 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
02745 if (ti->tileh == SLOPE_FLAT) {
02746 DrawWaterClassGround(ti);
02747 } else {
02748 assert(IsDock(ti->tile));
02749 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
02750 WaterClass wc = GetWaterClass(water_tile);
02751 if (wc == WATER_CLASS_SEA) {
02752 DrawShoreTile(ti->tileh);
02753 } else {
02754 DrawClearLandTile(ti, 3);
02755 }
02756 }
02757 } else {
02758 if (layout != NULL) {
02759
02760 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
02761 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
02762 uint8 var10;
02763 FOR_EACH_SET_BIT(var10, var10_values) {
02764 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
02765 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
02766 }
02767 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
02768 t = &tmp_rail_layout;
02769 total_offset = 0;
02770 } else if (statspec != NULL) {
02771
02772 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
02773 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
02774 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
02775 }
02776 ground_relocation += rti->fallback_railtype;
02777 }
02778
02779 SpriteID image = t->ground.sprite;
02780 PaletteID pal = t->ground.pal;
02781 if (rti != NULL && rti->UsesOverlay() && (image == SPR_RAIL_TRACK_X || image == SPR_RAIL_TRACK_Y)) {
02782 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
02783 DrawGroundSprite(SPR_FLAT_GRASS_TILE, PAL_NONE);
02784 DrawGroundSprite(ground + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE);
02785
02786 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
02787 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
02788 DrawGroundSprite(overlay + (image == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PALETTE_CRASH);
02789 }
02790 } else {
02791 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
02792 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
02793 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
02794
02795
02796 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
02797 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
02798 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
02799 }
02800 }
02801 }
02802
02803 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);
02804
02805 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
02806 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
02807 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
02808 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
02809 }
02810
02811 if (IsRailWaypoint(ti->tile)) {
02812
02813 total_offset = 0;
02814 }
02815
02816 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
02817 }
02818
02819 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
02820 {
02821 int32 total_offset = 0;
02822 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
02823 const DrawTileSprites *t = GetStationTileLayout(st, image);
02824 const RailtypeInfo *rti = NULL;
02825
02826 if (railtype != INVALID_RAILTYPE) {
02827 rti = GetRailTypeInfo(railtype);
02828 total_offset = rti->GetRailtypeSpriteOffset();
02829 }
02830
02831 SpriteID img = t->ground.sprite;
02832 if ((img == SPR_RAIL_TRACK_X || img == SPR_RAIL_TRACK_Y) && rti->UsesOverlay()) {
02833 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
02834 DrawSprite(SPR_FLAT_GRASS_TILE, PAL_NONE, x, y);
02835 DrawSprite(ground + (img == SPR_RAIL_TRACK_X ? RTO_X : RTO_Y), PAL_NONE, x, y);
02836 } else {
02837 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
02838 }
02839
02840 if (roadtype == ROADTYPE_TRAM) {
02841 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
02842 }
02843
02844
02845 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
02846 }
02847
02848 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
02849 {
02850 return GetTileMaxPixelZ(tile);
02851 }
02852
02853 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
02854 {
02855 return FlatteningFoundation(tileh);
02856 }
02857
02858 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
02859 {
02860 td->owner[0] = GetTileOwner(tile);
02861 if (IsDriveThroughStopTile(tile)) {
02862 Owner road_owner = INVALID_OWNER;
02863 Owner tram_owner = INVALID_OWNER;
02864 RoadTypes rts = GetRoadTypes(tile);
02865 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
02866 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
02867
02868
02869 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
02870 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
02871 uint i = 1;
02872 if (road_owner != INVALID_OWNER) {
02873 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
02874 td->owner[i] = road_owner;
02875 i++;
02876 }
02877 if (tram_owner != INVALID_OWNER) {
02878 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
02879 td->owner[i] = tram_owner;
02880 }
02881 }
02882 }
02883 td->build_date = BaseStation::GetByTile(tile)->build_date;
02884
02885 if (HasStationTileRail(tile)) {
02886 const StationSpec *spec = GetStationSpec(tile);
02887
02888 if (spec != NULL) {
02889 td->station_class = StationClass::GetName(spec->cls_id);
02890 td->station_name = spec->name;
02891
02892 if (spec->grf_prop.grffile != NULL) {
02893 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
02894 td->grf = gc->GetName();
02895 }
02896 }
02897
02898 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
02899 td->rail_speed = rti->max_speed;
02900 }
02901
02902 if (IsAirport(tile)) {
02903 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
02904 td->airport_class = AirportClass::GetName(as->cls_id);
02905 td->airport_name = as->name;
02906
02907 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
02908 td->airport_tile_name = ats->name;
02909
02910 if (as->grf_prop.grffile != NULL) {
02911 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
02912 td->grf = gc->GetName();
02913 } else if (ats->grf_prop.grffile != NULL) {
02914 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
02915 td->grf = gc->GetName();
02916 }
02917 }
02918
02919 StringID str;
02920 switch (GetStationType(tile)) {
02921 default: NOT_REACHED();
02922 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
02923 case STATION_AIRPORT:
02924 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
02925 break;
02926 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
02927 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
02928 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
02929 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
02930 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
02931 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
02932 }
02933 td->str = str;
02934 }
02935
02936
02937 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
02938 {
02939 TrackBits trackbits = TRACK_BIT_NONE;
02940
02941 switch (mode) {
02942 case TRANSPORT_RAIL:
02943 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
02944 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
02945 }
02946 break;
02947
02948 case TRANSPORT_WATER:
02949
02950 if (IsBuoy(tile)) {
02951 trackbits = TRACK_BIT_ALL;
02952
02953 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
02954
02955 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
02956 }
02957 break;
02958
02959 case TRANSPORT_ROAD:
02960 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
02961 DiagDirection dir = GetRoadStopDir(tile);
02962 Axis axis = DiagDirToAxis(dir);
02963
02964 if (side != INVALID_DIAGDIR) {
02965 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
02966 }
02967
02968 trackbits = AxisToTrackBits(axis);
02969 }
02970 break;
02971
02972 default:
02973 break;
02974 }
02975
02976 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
02977 }
02978
02979
02980 static void TileLoop_Station(TileIndex tile)
02981 {
02982
02983
02984 switch (GetStationType(tile)) {
02985 case STATION_AIRPORT:
02986 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
02987 break;
02988
02989 case STATION_DOCK:
02990 if (GetTileSlope(tile) != SLOPE_FLAT) break;
02991
02992 case STATION_OILRIG:
02993 case STATION_BUOY:
02994 TileLoop_Water(tile);
02995 break;
02996
02997 default: break;
02998 }
02999 }
03000
03001
03002 static void AnimateTile_Station(TileIndex tile)
03003 {
03004 if (HasStationRail(tile)) {
03005 AnimateStationTile(tile);
03006 return;
03007 }
03008
03009 if (IsAirport(tile)) {
03010 AnimateAirportTile(tile);
03011 }
03012 }
03013
03014
03015 static bool ClickTile_Station(TileIndex tile)
03016 {
03017 const BaseStation *bst = BaseStation::GetByTile(tile);
03018
03019 if (bst->facilities & FACIL_WAYPOINT) {
03020 ShowWaypointWindow(Waypoint::From(bst));
03021 } else if (IsHangar(tile)) {
03022 const Station *st = Station::From(bst);
03023 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
03024 } else {
03025 ShowStationViewWindow(bst->index);
03026 }
03027 return true;
03028 }
03029
03030 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
03031 {
03032 if (v->type == VEH_TRAIN) {
03033 StationID station_id = GetStationIndex(tile);
03034 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
03035 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
03036
03037 int station_ahead;
03038 int station_length;
03039 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
03040
03041
03042
03043
03044
03045 if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
03046
03047 DiagDirection dir = DirToDiagDir(v->direction);
03048
03049 x &= 0xF;
03050 y &= 0xF;
03051
03052 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
03053 if (y == TILE_SIZE / 2) {
03054 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
03055 stop &= TILE_SIZE - 1;
03056
03057 if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET);
03058 if (x < stop) {
03059 uint16 spd;
03060
03061 v->vehstatus |= VS_TRAIN_SLOWING;
03062 spd = max(0, (stop - x) * 20 - 15);
03063 if (spd < v->cur_speed) v->cur_speed = spd;
03064 }
03065 }
03066 } else if (v->type == VEH_ROAD) {
03067 RoadVehicle *rv = RoadVehicle::From(v);
03068 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
03069 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
03070
03071 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
03072 }
03073 }
03074 }
03075
03076 return VETSB_CONTINUE;
03077 }
03078
03083 void TriggerWatchedCargoCallbacks(Station *st)
03084 {
03085
03086 uint cargoes = 0;
03087 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
03088 if (HasBit(st->goods[cid].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
03089 }
03090
03091
03092 if (cargoes == 0) return;
03093
03094
03095 Rect r = st->GetCatchmentRect();
03096 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
03097 TILE_AREA_LOOP(tile, ta) {
03098 if (IsTileType(tile, MP_HOUSE)) {
03099 WatchedCargoCallback(tile, cargoes);
03100 }
03101 }
03102 }
03103
03110 static bool StationHandleBigTick(BaseStation *st)
03111 {
03112 if (!st->IsInUse()) {
03113 if (++st->delete_ctr >= 8) delete st;
03114 return false;
03115 }
03116
03117 if (Station::IsExpected(st)) {
03118 TriggerWatchedCargoCallbacks(Station::From(st));
03119
03120 for (CargoID i = 0; i < NUM_CARGO; i++) {
03121 ClrBit(Station::From(st)->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
03122 }
03123 }
03124
03125
03126 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
03127
03128 return true;
03129 }
03130
03131 static inline void byte_inc_sat(byte *p)
03132 {
03133 byte b = *p + 1;
03134 if (b != 0) *p = b;
03135 }
03136
03137 static void UpdateStationRating(Station *st)
03138 {
03139 bool waiting_changed = false;
03140
03141 byte_inc_sat(&st->time_since_load);
03142 byte_inc_sat(&st->time_since_unload);
03143
03144 const CargoSpec *cs;
03145 FOR_ALL_CARGOSPECS(cs) {
03146 GoodsEntry *ge = &st->goods[cs->Index()];
03147
03148
03149
03150 if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP) && ge->rating < INITIAL_STATION_RATING) {
03151 ge->rating++;
03152 }
03153
03154
03155 if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03156 byte_inc_sat(&ge->days_since_pickup);
03157
03158 bool skip = false;
03159 int rating = 0;
03160 uint waiting = ge->cargo.Count();
03161
03162 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
03163
03164
03165
03166
03167 uint last_speed = ge->last_speed;
03168 if (last_speed == 0) last_speed = 0xFF;
03169
03170 uint32 var18 = min(ge->days_since_pickup, 0xFF) | (min(waiting, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
03171
03172 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
03173 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
03174 if (callback != CALLBACK_FAILED) {
03175 skip = true;
03176 rating = GB(callback, 0, 14);
03177
03178
03179 if (HasBit(callback, 14)) rating -= 0x4000;
03180 }
03181 }
03182
03183 if (!skip) {
03184 int b = ge->last_speed - 85;
03185 if (b >= 0) rating += b >> 2;
03186
03187 byte days = ge->days_since_pickup;
03188 if (st->last_vehicle_type == VEH_SHIP) days >>= 2;
03189 (days > 21) ||
03190 (rating += 25, days > 12) ||
03191 (rating += 25, days > 6) ||
03192 (rating += 45, days > 3) ||
03193 (rating += 35, true);
03194
03195 (rating -= 90, waiting > 1500) ||
03196 (rating += 55, waiting > 1000) ||
03197 (rating += 35, waiting > 600) ||
03198 (rating += 10, waiting > 300) ||
03199 (rating += 20, waiting > 100) ||
03200 (rating += 10, true);
03201 }
03202
03203 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
03204
03205 byte age = ge->last_age;
03206 (age >= 3) ||
03207 (rating += 10, age >= 2) ||
03208 (rating += 10, age >= 1) ||
03209 (rating += 13, true);
03210
03211 {
03212 int or_ = ge->rating;
03213
03214
03215 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
03216
03217
03218
03219 if (rating <= 64 && waiting >= 200) {
03220 int dec = Random() & 0x1F;
03221 if (waiting < 400) dec &= 7;
03222 waiting -= dec + 1;
03223 waiting_changed = true;
03224 }
03225
03226
03227 if (rating <= 127 && waiting != 0) {
03228 uint32 r = Random();
03229 if (rating <= (int)GB(r, 0, 7)) {
03230
03231 waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
03232 waiting_changed = true;
03233 }
03234 }
03235
03236
03237
03238
03239 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
03240 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
03241 static const uint MAX_WAITING_CARGO = 1 << 15;
03242
03243 if (waiting > WAITING_CARGO_THRESHOLD) {
03244 uint difference = waiting - WAITING_CARGO_THRESHOLD;
03245 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
03246
03247 waiting = min(waiting, MAX_WAITING_CARGO);
03248 waiting_changed = true;
03249 }
03250
03251 if (waiting_changed) ge->cargo.Truncate(waiting);
03252 }
03253 }
03254 }
03255
03256 StationID index = st->index;
03257 if (waiting_changed) {
03258 SetWindowDirty(WC_STATION_VIEW, index);
03259 } else {
03260 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST);
03261 }
03262 }
03263
03264
03265 static void StationHandleSmallTick(BaseStation *st)
03266 {
03267 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
03268
03269 byte b = st->delete_ctr + 1;
03270 if (b >= STATION_RATING_TICKS) b = 0;
03271 st->delete_ctr = b;
03272
03273 if (b == 0) UpdateStationRating(Station::From(st));
03274 }
03275
03276 void OnTick_Station()
03277 {
03278 if (_game_mode == GM_EDITOR) return;
03279
03280 BaseStation *st;
03281 FOR_ALL_BASE_STATIONS(st) {
03282 StationHandleSmallTick(st);
03283
03284
03285
03286
03287 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
03288
03289 if (!StationHandleBigTick(st)) continue;
03290 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
03291 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
03292 }
03293 }
03294 }
03295
03297 void StationMonthlyLoop()
03298 {
03299 Station *st;
03300
03301 FOR_ALL_STATIONS(st) {
03302 for (CargoID i = 0; i < NUM_CARGO; i++) {
03303 GoodsEntry *ge = &st->goods[i];
03304 SB(ge->acceptance_pickup, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH, 1));
03305 ClrBit(ge->acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
03306 }
03307 }
03308 }
03309
03310
03311 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
03312 {
03313 Station *st;
03314
03315 FOR_ALL_STATIONS(st) {
03316 if (st->owner == owner &&
03317 DistanceManhattan(tile, st->xy) <= radius) {
03318 for (CargoID i = 0; i < NUM_CARGO; i++) {
03319 GoodsEntry *ge = &st->goods[i];
03320
03321 if (ge->acceptance_pickup != 0) {
03322 ge->rating = Clamp(ge->rating + amount, 0, 255);
03323 }
03324 }
03325 }
03326 }
03327 }
03328
03329 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
03330 {
03331
03332
03333 if (!CargoPacket::CanAllocateItem()) return 0;
03334
03335 GoodsEntry &ge = st->goods[type];
03336 amount += ge.amount_fract;
03337 ge.amount_fract = GB(amount, 0, 8);
03338
03339 amount >>= 8;
03340
03341 if (amount == 0) return 0;
03342
03343 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id));
03344
03345 if (!HasBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP)) {
03346 InvalidateWindowData(WC_STATION_LIST, st->index);
03347 SetBit(ge.acceptance_pickup, GoodsEntry::GES_PICKUP);
03348 }
03349
03350 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
03351 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
03352
03353 SetWindowDirty(WC_STATION_VIEW, st->index);
03354 st->MarkTilesDirty(true);
03355 return amount;
03356 }
03357
03358 static bool IsUniqueStationName(const char *name)
03359 {
03360 const Station *st;
03361
03362 FOR_ALL_STATIONS(st) {
03363 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
03364 }
03365
03366 return true;
03367 }
03368
03378 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
03379 {
03380 Station *st = Station::GetIfValid(p1);
03381 if (st == NULL) return CMD_ERROR;
03382
03383 CommandCost ret = CheckOwnership(st->owner);
03384 if (ret.Failed()) return ret;
03385
03386 bool reset = StrEmpty(text);
03387
03388 if (!reset) {
03389 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
03390 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
03391 }
03392
03393 if (flags & DC_EXEC) {
03394 free(st->name);
03395 st->name = reset ? NULL : strdup(text);
03396
03397 st->UpdateVirtCoord();
03398 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
03399 }
03400
03401 return CommandCost();
03402 }
03403
03410 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
03411 {
03412
03413 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
03414
03415 uint x = TileX(location.tile);
03416 uint y = TileY(location.tile);
03417
03418 uint min_x = (x > max_rad) ? x - max_rad : 0;
03419 uint max_x = x + location.w + max_rad;
03420 uint min_y = (y > max_rad) ? y - max_rad : 0;
03421 uint max_y = y + location.h + max_rad;
03422
03423 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
03424 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
03425 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
03426 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
03427
03428 for (uint cy = min_y; cy < max_y; cy++) {
03429 for (uint cx = min_x; cx < max_x; cx++) {
03430 TileIndex cur_tile = TileXY(cx, cy);
03431 if (!IsTileType(cur_tile, MP_STATION)) continue;
03432
03433 Station *st = Station::GetByTile(cur_tile);
03434
03435 if (st == NULL) continue;
03436
03437 if (_settings_game.station.modified_catchment) {
03438 int rad = st->GetCatchmentRadius();
03439 int rad_x = cx - x;
03440 int rad_y = cy - y;
03441
03442 if (rad_x < -rad || rad_x >= rad + location.w) continue;
03443 if (rad_y < -rad || rad_y >= rad + location.h) continue;
03444 }
03445
03446
03447
03448
03449 stations->Include(st);
03450 }
03451 }
03452 }
03453
03458 const StationList *StationFinder::GetStations()
03459 {
03460 if (this->tile != INVALID_TILE) {
03461 FindStationsAroundTiles(*this, &this->stations);
03462 this->tile = INVALID_TILE;
03463 }
03464 return &this->stations;
03465 }
03466
03467 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
03468 {
03469
03470 if (amount == 0) return 0;
03471
03472 Station *st1 = NULL;
03473 Station *st2 = NULL;
03474 uint best_rating1 = 0;
03475 uint best_rating2 = 0;
03476
03477 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
03478 Station *st = *st_iter;
03479
03480
03481 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
03482
03483 if (st->goods[type].rating == 0) continue;
03484
03485 if (_settings_game.order.selectgoods && st->goods[type].last_speed == 0) continue;
03486
03487 if (IsCargoInClass(type, CC_PASSENGERS)) {
03488 if (st->facilities == FACIL_TRUCK_STOP) continue;
03489 } else {
03490 if (st->facilities == FACIL_BUS_STOP) continue;
03491 }
03492
03493
03494 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
03495 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
03496 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
03497 st2 = st; best_rating2 = st->goods[type].rating;
03498 }
03499 }
03500
03501
03502 if (st1 == NULL) return 0;
03503
03504
03505
03506 amount *= best_rating1 + 1;
03507
03508 if (st2 == NULL) {
03509
03510 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
03511 }
03512
03513
03514 assert(st1 != NULL);
03515 assert(st2 != NULL);
03516 assert(best_rating1 != 0 || best_rating2 != 0);
03517
03518
03519
03520
03521
03522
03523 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
03524 assert(worst_cargo <= (amount - worst_cargo));
03525
03526
03527 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
03528
03529
03530 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
03531 }
03532
03533 void BuildOilRig(TileIndex tile)
03534 {
03535 if (!Station::CanAllocateItem()) {
03536 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
03537 return;
03538 }
03539
03540 Station *st = new Station(tile);
03541 st->town = ClosestTownFromTile(tile, UINT_MAX);
03542
03543 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
03544
03545 assert(IsTileType(tile, MP_INDUSTRY));
03546 DeleteAnimatedTile(tile);
03547 MakeOilrig(tile, st->index, GetWaterClass(tile));
03548
03549 st->owner = OWNER_NONE;
03550 st->airport.type = AT_OILRIG;
03551 st->airport.Add(tile);
03552 st->dock_tile = tile;
03553 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
03554 st->build_date = _date;
03555
03556 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
03557
03558 for (CargoID j = 0; j < NUM_CARGO; j++) {
03559 st->goods[j].acceptance_pickup = 0;
03560 st->goods[j].days_since_pickup = 255;
03561 st->goods[j].rating = INITIAL_STATION_RATING;
03562 st->goods[j].last_speed = 0;
03563 st->goods[j].last_age = 255;
03564 }
03565
03566 st->UpdateVirtCoord();
03567 UpdateStationAcceptance(st, false);
03568 st->RecomputeIndustriesNear();
03569 }
03570
03571 void DeleteOilRig(TileIndex tile)
03572 {
03573 Station *st = Station::GetByTile(tile);
03574
03575 MakeWaterKeepingClass(tile, OWNER_NONE);
03576
03577 st->dock_tile = INVALID_TILE;
03578 st->airport.Clear();
03579 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
03580 st->airport.flags = 0;
03581
03582 st->rect.AfterRemoveTile(st, tile);
03583
03584 st->UpdateVirtCoord();
03585 st->RecomputeIndustriesNear();
03586 if (!st->IsInUse()) delete st;
03587 }
03588
03589 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
03590 {
03591 if (IsRoadStopTile(tile)) {
03592 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
03593
03594 if (GetRoadOwner(tile, rt) == old_owner) {
03595 if (HasTileRoadType(tile, rt)) {
03596
03597 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
03598 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
03599 }
03600 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
03601 }
03602 }
03603 }
03604
03605 if (!IsTileOwner(tile, old_owner)) return;
03606
03607 if (new_owner != INVALID_OWNER) {
03608
03609
03610
03611
03612 Company *old_company = Company::Get(old_owner);
03613 Company *new_company = Company::Get(new_owner);
03614
03615
03616 switch (GetStationType(tile)) {
03617 case STATION_RAIL:
03618 case STATION_WAYPOINT:
03619 if (!IsStationTileBlocked(tile)) {
03620 old_company->infrastructure.rail[GetRailType(tile)]--;
03621 new_company->infrastructure.rail[GetRailType(tile)]++;
03622 }
03623 break;
03624
03625 case STATION_BUS:
03626 case STATION_TRUCK:
03627
03628 break;
03629
03630 case STATION_BUOY:
03631 case STATION_DOCK:
03632 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
03633 old_company->infrastructure.water--;
03634 new_company->infrastructure.water++;
03635 }
03636 break;
03637
03638 default:
03639 break;
03640 }
03641
03642
03643 if (!IsBuoy(tile) && !IsAirport(tile)) {
03644 old_company->infrastructure.station--;
03645 new_company->infrastructure.station++;
03646 }
03647
03648
03649 SetTileOwner(tile, new_owner);
03650 InvalidateWindowClassesData(WC_STATION_LIST, 0);
03651 } else {
03652 if (IsDriveThroughStopTile(tile)) {
03653
03654 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
03655 assert(IsTileType(tile, MP_ROAD));
03656
03657 ChangeTileOwner(tile, old_owner, new_owner);
03658 } else {
03659 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
03660
03661
03662
03663 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
03664 }
03665 }
03666 }
03667
03676 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
03677 {
03678
03679 if (_current_company == OWNER_WATER) return true;
03680
03681 RoadTypes rts = GetRoadTypes(tile);
03682 if (HasBit(rts, ROADTYPE_TRAM)) {
03683 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
03684 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
03685 }
03686 if (HasBit(rts, ROADTYPE_ROAD)) {
03687 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
03688 if (road_owner != OWNER_TOWN) {
03689 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
03690 } else {
03691 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
03692 }
03693 }
03694
03695 return true;
03696 }
03697
03704 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
03705 {
03706 if (flags & DC_AUTO) {
03707 switch (GetStationType(tile)) {
03708 default: break;
03709 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
03710 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
03711 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
03712 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);
03713 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);
03714 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
03715 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
03716 case STATION_OILRIG:
03717 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
03718 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
03719 }
03720 }
03721
03722 switch (GetStationType(tile)) {
03723 case STATION_RAIL: return RemoveRailStation(tile, flags);
03724 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
03725 case STATION_AIRPORT: return RemoveAirport(tile, flags);
03726 case STATION_TRUCK:
03727 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03728 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
03729 }
03730 return RemoveRoadStop(tile, flags);
03731 case STATION_BUS:
03732 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
03733 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
03734 }
03735 return RemoveRoadStop(tile, flags);
03736 case STATION_BUOY: return RemoveBuoy(tile, flags);
03737 case STATION_DOCK: return RemoveDock(tile, flags);
03738 default: break;
03739 }
03740
03741 return CMD_ERROR;
03742 }
03743
03744 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03745 {
03746 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
03747
03748
03749
03750 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
03751 switch (GetStationType(tile)) {
03752 case STATION_WAYPOINT:
03753 case STATION_RAIL: {
03754 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
03755 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03756 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03757 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03758 }
03759
03760 case STATION_AIRPORT:
03761 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03762
03763 case STATION_TRUCK:
03764 case STATION_BUS: {
03765 DiagDirection direction = GetRoadStopDir(tile);
03766 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
03767 if (IsDriveThroughStopTile(tile)) {
03768 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
03769 }
03770 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03771 }
03772
03773 default: break;
03774 }
03775 }
03776 }
03777 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03778 }
03779
03780
03781 extern const TileTypeProcs _tile_type_station_procs = {
03782 DrawTile_Station,
03783 GetSlopePixelZ_Station,
03784 ClearTile_Station,
03785 NULL,
03786 GetTileDesc_Station,
03787 GetTileTrackStatus_Station,
03788 ClickTile_Station,
03789 AnimateTile_Station,
03790 TileLoop_Station,
03791 ChangeTileOwner_Station,
03792 NULL,
03793 VehicleEnter_Station,
03794 GetFoundation_Station,
03795 TerraformTile_Station,
03796 };