/
station_cmd.cpp
5113 lines (4380 loc) · 173 KB
/
station_cmd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file station_cmd.cpp Handling of station tiles. */
#include "stdafx.h"
#include "aircraft.h"
#include "bridge_map.h"
#include "cmd_helper.h"
#include "viewport_func.h"
#include "viewport_kdtree.h"
#include "command_func.h"
#include "town.h"
#include "news_func.h"
#include "train.h"
#include "ship.h"
#include "roadveh.h"
#include "industry.h"
#include "newgrf_cargo.h"
#include "newgrf_debug.h"
#include "newgrf_station.h"
#include "newgrf_canal.h" /* For the buoy */
#include "pathfinder/yapf/yapf_cache.h"
#include "road_internal.h" /* For drawing catenary/checking road removal */
#include "autoslope.h"
#include "water.h"
#include "strings_func.h"
#include "clear_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "animated_tile_func.h"
#include "elrail_func.h"
#include "station_base.h"
#include "station_kdtree.h"
#include "roadstop_base.h"
#include "newgrf_railtype.h"
#include "newgrf_roadtype.h"
#include "waypoint_base.h"
#include "waypoint_func.h"
#include "pbs.h"
#include "debug.h"
#include "core/random_func.hpp"
#include "company_base.h"
#include "table/airporttile_ids.h"
#include "newgrf_airporttiles.h"
#include "order_backup.h"
#include "newgrf_house.h"
#include "company_gui.h"
#include "linkgraph/linkgraph_base.h"
#include "linkgraph/refresh.h"
#include "widgets/station_widget.h"
#include "zoning.h"
#include "tunnelbridge_map.h"
#include "table/strings.h"
#include "safeguards.h"
/**
* Check whether the given tile is a hangar.
* @param t the tile to of whether it is a hangar.
* @pre IsTileType(t, MP_STATION)
* @return true if and only if the tile is a hangar.
*/
bool IsHangar(TileIndex t)
{
assert_tile(IsTileType(t, MP_STATION), t);
/* If the tile isn't an airport there's no chance it's a hangar. */
if (!IsAirport(t)) return false;
const Station *st = Station::GetByTile(t);
const AirportSpec *as = st->airport.GetSpec();
for (uint i = 0; i < as->nof_depots; i++) {
if (st->airport.GetHangarTile(i) == t) return true;
}
return false;
}
/**
* Look for a station owned by the given company around the given tile area.
* @param ta the area to search over
* @param closest_station the closest owned station found so far
* @param company the company whose stations to look for
* @param st to 'return' the found station
* @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
*/
template <class T>
CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
{
ta.Expand(1);
/* check around to see if there are any stations there owned by the company */
TILE_AREA_LOOP(tile_cur, ta) {
if (IsTileType(tile_cur, MP_STATION)) {
StationID t = GetStationIndex(tile_cur);
if (!T::IsValidID(t) || Station::Get(t)->owner != company) continue;
if (closest_station == INVALID_STATION) {
closest_station = t;
} else if (closest_station != t) {
return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
}
}
}
*st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
return CommandCost();
}
/**
* Function to check whether the given tile matches some criterion.
* @param tile the tile to check
* @return true if it matches, false otherwise
*/
typedef bool (*CMSAMatcher)(TileIndex tile);
/**
* Counts the numbers of tiles matching a specific type in the area around
* @param tile the center tile of the 'count area'
* @param cmp the comparator/matcher (@see CMSAMatcher)
* @return the number of matching tiles around
*/
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
{
int num = 0;
for (int dx = -3; dx <= 3; dx++) {
for (int dy = -3; dy <= 3; dy++) {
TileIndex t = TileAddWrap(tile, dx, dy);
if (t != INVALID_TILE && cmp(t)) num++;
}
}
return num;
}
/**
* Check whether the tile is a mine.
* @param tile the tile to investigate.
* @return true if and only if the tile is a mine
*/
static bool CMSAMine(TileIndex tile)
{
/* No industry */
if (!IsTileType(tile, MP_INDUSTRY)) return false;
const Industry *ind = Industry::GetByTile(tile);
/* No extractive industry */
if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
/* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
* Also the production of passengers and mail is ignored. */
if (ind->produced_cargo[i] != CT_INVALID &&
(CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
return true;
}
}
return false;
}
/**
* Check whether the tile is water.
* @param tile the tile to investigate.
* @return true if and only if the tile is a water tile
*/
static bool CMSAWater(TileIndex tile)
{
return IsTileType(tile, MP_WATER) && IsWater(tile);
}
/**
* Check whether the tile is a tree.
* @param tile the tile to investigate.
* @return true if and only if the tile is a tree tile
*/
static bool CMSATree(TileIndex tile)
{
return IsTileType(tile, MP_TREES);
}
#define M(x) ((x) - STR_SV_STNAME)
enum StationNaming {
STATIONNAMING_RAIL,
STATIONNAMING_ROAD,
STATIONNAMING_AIRPORT,
STATIONNAMING_OILRIG,
STATIONNAMING_DOCK,
STATIONNAMING_HELIPORT,
};
/** Information to handle station action 0 property 24 correctly */
struct StationNameInformation {
uint32 free_names; ///< Current bitset of free names (we can remove names).
bool *indtypes; ///< Array of bools telling whether an industry type has been found.
};
/**
* Find a station action 0 property 24 station name, or reduce the
* free_names if needed.
* @param tile the tile to search
* @param user_data the StationNameInformation to base the search on
* @return true if the tile contains an industry that has not given
* its name to one of the other stations in town.
*/
static bool FindNearIndustryName(TileIndex tile, void *user_data)
{
/* All already found industry types */
StationNameInformation *sni = (StationNameInformation*)user_data;
if (!IsTileType(tile, MP_INDUSTRY)) return false;
/* If the station name is undefined it means that it doesn't name a station */
IndustryType indtype = GetIndustryType(tile);
if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
/* In all cases if an industry that provides a name is found two of
* the standard names will be disabled. */
sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
return !sni->indtypes[indtype];
}
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
{
static const uint32 _gen_station_name_bits[] = {
0, // STATIONNAMING_RAIL
0, // STATIONNAMING_ROAD
1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
};
const Town *t = st->town;
uint32 free_names = UINT32_MAX;
bool indtypes[NUM_INDUSTRYTYPES];
memset(indtypes, 0, sizeof(indtypes));
for (const Station *s : Station::Iterate()) {
if (s != st && s->town == t) {
if (s->indtype != IT_INVALID) {
indtypes[s->indtype] = true;
StringID name = GetIndustrySpec(s->indtype)->station_name;
if (name != STR_UNDEFINED) {
/* Filter for other industrytypes with the same name */
for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
const IndustrySpec *indsp = GetIndustrySpec(it);
if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
}
}
continue;
}
uint str = M(s->string_id);
if (str <= 0x20) {
if (str == M(STR_SV_STNAME_FOREST)) {
str = M(STR_SV_STNAME_WOODS);
}
ClrBit(free_names, str);
}
}
}
TileIndex indtile = tile;
StationNameInformation sni = { free_names, indtypes };
if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
/* An industry has been found nearby */
IndustryType indtype = GetIndustryType(indtile);
const IndustrySpec *indsp = GetIndustrySpec(indtype);
/* STR_NULL means it only disables oil rig/mines */
if (indsp->station_name != STR_NULL) {
st->indtype = indtype;
return STR_SV_STNAME_FALLBACK;
}
}
/* Oil rigs/mines name could be marked not free by looking for a near by industry. */
free_names = sni.free_names;
/* check default names */
uint32 tmp = free_names & _gen_station_name_bits[name_class];
if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
/* check mine? */
if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
if (CountMapSquareAround(tile, CMSAMine) >= 2) {
return STR_SV_STNAME_MINES;
}
}
/* check close enough to town to get central as name? */
if (DistanceMax(tile, t->xy) < 8) {
if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
}
/* Check lakeside */
if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
DistanceFromEdge(tile) < 20 &&
CountMapSquareAround(tile, CMSAWater) >= 5) {
return STR_SV_STNAME_LAKESIDE;
}
/* Check woods */
if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
CountMapSquareAround(tile, CMSATree) >= 8 ||
CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
) {
return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
}
/* check elevation compared to town */
int z = GetTileZ(tile);
int z2 = GetTileZ(t->xy);
if (z < z2) {
if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
} else if (z > z2) {
if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
}
/* check direction compared to town */
static const int8 _direction_and_table[] = {
~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
};
free_names &= _direction_and_table[
(TileX(tile) < TileX(t->xy)) +
(TileY(tile) < TileY(t->xy)) * 2];
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));
return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
}
#undef M
/**
* Find the closest deleted station of the current company
* @param tile the tile to search from.
* @return the closest station or nullptr if too far.
*/
static Station *GetClosestDeletedStation(TileIndex tile)
{
uint threshold = 8;
Station *best_station = nullptr;
ForAllStationsRadius(tile, threshold, [&](Station *st) {
if (!st->IsInUse() && st->owner == _current_company) {
uint cur_dist = DistanceManhattan(tile, st->xy);
if (cur_dist < threshold) {
threshold = cur_dist;
best_station = st;
} else if (cur_dist == threshold && best_station != nullptr) {
/* In case of a tie, lowest station ID wins */
if (st->index < best_station->index) best_station = st;
}
}
});
return best_station;
}
void Station::GetTileArea(TileArea *ta, StationType type) const
{
switch (type) {
case STATION_RAIL:
*ta = this->train_station;
return;
case STATION_AIRPORT:
*ta = this->airport;
return;
case STATION_TRUCK:
*ta = this->truck_station;
return;
case STATION_BUS:
*ta = this->bus_station;
return;
case STATION_DOCK:
case STATION_OILRIG:
*ta = this->docking_station;
return;
default: NOT_REACHED();
}
}
/**
* Update the virtual coords needed to draw the station sign.
*/
void Station::UpdateVirtCoord()
{
Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
pt.y -= 32 * ZOOM_LVL_BASE;
if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
if (_viewport_sign_kdtree_valid && this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
SetDParam(0, this->index);
SetDParam(1, this->facilities);
bool shown = HasBit(_display_opt, DO_SHOW_STATION_NAMES) && !(_local_company != this->owner && this->owner != OWNER_NONE && !HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS));
this->sign.UpdatePosition(shown ? ZOOM_LVL_DRAW_SPR : ZOOM_LVL_END, pt.x, pt.y, STR_VIEWPORT_STATION);
if (_viewport_sign_kdtree_valid) _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
SetWindowDirty(WC_STATION_VIEW, this->index);
}
/**
* Move the station main coordinate somewhere else.
* @param new_xy new tile location of the sign
*/
void Station::MoveSign(TileIndex new_xy)
{
if (this->xy == new_xy) return;
_station_kdtree.Remove(this->index);
this->BaseStation::MoveSign(new_xy);
_station_kdtree.Insert(this->index);
}
/** Update the virtual coords needed to draw the station sign for all stations. */
void UpdateAllStationVirtCoords()
{
for (BaseStation *st : BaseStation::Iterate()) {
st->UpdateVirtCoord();
}
}
void BaseStation::FillCachedName() const
{
char buf[MAX_LENGTH_STATION_NAME_CHARS * MAX_CHAR_LENGTH];
int64 args_array[] = { this->index };
StringParameters tmp_params(args_array);
char *end = GetStringWithArgs(buf, Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, &tmp_params, lastof(buf));
this->cached_name.assign(buf, end);
}
void ClearAllStationCachedNames()
{
for (BaseStation *st : BaseStation::Iterate()) {
st->cached_name.clear();
}
}
/**
* Get a mask of the cargo types that the station accepts.
* @param st Station to query
* @return the expected mask
*/
static CargoTypes GetAcceptanceMask(const Station *st)
{
CargoTypes mask = 0;
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, i);
}
return mask;
}
/**
* Items contains the two cargo names that are to be accepted or rejected.
* msg is the string id of the message to display.
*/
static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
{
for (uint i = 0; i < num_items; i++) {
SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
}
SetDParam(0, st->index);
AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
}
/**
* Get the cargo types being produced around the tile (in a rectangle).
* @param tile Northtile of area
* @param w X extent of the area
* @param h Y extent of the area
* @param rad Search radius in addition to the given area
*/
CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
{
CargoArray produced;
btree::btree_set<IndustryID> industries;
TileArea ta = TileArea(tile, w, h).Expand(rad);
/* Loop over all tiles to get the produced cargo of
* everything except industries */
TILE_AREA_LOOP(tile, ta) {
if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
AddProducedCargo(tile, produced);
}
/* Loop over the seen industries. They produce cargo for
* anything that is within 'rad' of any one of their tiles.
*/
for (IndustryID industry : industries) {
const Industry *i = Industry::Get(industry);
/* Skip industry with neutral station */
if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
CargoID cargo = i->produced_cargo[j];
if (cargo != CT_INVALID) produced[cargo]++;
}
}
return produced;
}
CargoArray GetProductionAroundRect(Rect rect) {
CargoArray produced;
btree::btree_set<IndustryID> industries;
/* Loop over all tiles to get the produced cargo of
* everything except industries */
for (int y = rect.top; y <= rect.bottom; y++) {
for (int x = rect.left; x <= rect.right; x++) {
TileIndex tile = TileXY(x, y);
if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
AddProducedCargo(tile, produced);
}
}
/* Loop over the seen industries. They produce cargo for
* anything that is within 'rad' of any one of their tiles.
*/
for (IndustryID industry : industries) {
const Industry *i = Industry::Get(industry);
/* Skip industry with neutral station */
if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
CargoID cargo = i->produced_cargo[j];
if (cargo != CT_INVALID) produced[cargo]++;
}
}
return produced;
}
/**
* Get the acceptance of cargoes around the tile in 1/8.
* @param tile Center of the search area
* @param w X extent of area
* @param h Y extent of area
* @param rad Search radius in addition to given area
* @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
* @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
*/
CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, CargoTypes *always_accepted)
{
CargoArray acceptance;
if (always_accepted != nullptr) *always_accepted = 0;
TileArea ta = TileArea(tile, w, h).Expand(rad);
TILE_AREA_LOOP(tile, ta) {
/* Ignore industry if it has a neutral station. */
if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
AddAcceptedCargo(tile, acceptance, always_accepted);
}
return acceptance;
}
/**
* Get the acceptance of cargoes around the station in.
* @param st Station to get acceptance of.
* @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
*/
static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
{
CargoArray acceptance;
if (always_accepted != nullptr) *always_accepted = 0;
BitmapTileIterator it(st->catchment_tiles);
for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
AddAcceptedCargo(tile, acceptance, always_accepted);
}
return acceptance;
}
/**
* Update the acceptance for a station.
* @param st Station to update
* @param show_msg controls whether to display a message that acceptance was changed.
*/
void UpdateStationAcceptance(Station *st, bool show_msg)
{
/* old accepted goods types */
CargoTypes old_acc = GetAcceptanceMask(st);
/* And retrieve the acceptance. */
CargoArray acceptance;
if (!st->rect.IsEmpty()) {
acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
}
/* Adjust in case our station only accepts fewer kinds of goods */
for (CargoID i = 0; i < NUM_CARGO; i++) {
uint amt = acceptance[i];
/* Make sure the station can accept the goods type. */
bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
(is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
amt = 0;
}
GoodsEntry &ge = st->goods[i];
SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
if (LinkGraph::IsValidID(ge.link_graph)) {
(*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
}
}
/* Only show a message in case the acceptance was actually changed. */
CargoTypes new_acc = GetAcceptanceMask(st);
if (old_acc == new_acc) return;
/* show a message to report that the acceptance was changed? */
if (show_msg && st->owner == _local_company && st->IsInUse()) {
/* List of accept and reject strings for different number of
* cargo types */
static const StringID accept_msg[] = {
STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
};
static const StringID reject_msg[] = {
STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
};
/* Array of accepted and rejected cargo types */
CargoID accepts[2] = { CT_INVALID, CT_INVALID };
CargoID rejects[2] = { CT_INVALID, CT_INVALID };
uint num_acc = 0;
uint num_rej = 0;
/* Test each cargo type to see if its acceptance has changed */
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (HasBit(new_acc, i)) {
if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
/* New cargo is accepted */
accepts[num_acc++] = i;
}
} else {
if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
/* Old cargo is no longer accepted */
rejects[num_rej++] = i;
}
}
}
/* Show news message if there are any changes */
if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
}
/* redraw the station view since acceptance changed */
SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
}
static void UpdateStationSignCoord(BaseStation *st)
{
const StationRect *r = &st->rect;
if (r->IsEmpty()) return; // no tiles belong to this station
/* clamp sign coord to be inside the station rect */
TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
st->MoveSign(new_xy);
if (!Station::IsExpected(st)) return;
Station *full_station = Station::From(st);
for (CargoID c = 0; c < NUM_CARGO; ++c) {
LinkGraphID lg = full_station->goods[c].link_graph;
if (!LinkGraph::IsValidID(lg)) continue;
(*LinkGraph::Get(lg))[full_station->goods[c].node].UpdateLocation(st->xy);
}
}
/**
* Common part of building various station parts and possibly attaching them to an existing one.
* @param[in,out] st Station to attach to
* @param flags Command flags
* @param reuse Whether to try to reuse a deleted station (gray sign) if possible
* @param area Area occupied by the new part
* @param name_class Station naming class to use to generate the new station's name
* @return Command error that occurred, if any
*/
static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
{
/* Find a deleted station close to us */
if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
if (*st != nullptr) {
if ((*st)->owner != _current_company) {
return_cmd_error(CMD_ERROR);
}
CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
if (ret.Failed()) return ret;
} else {
/* allocate and initialize new station */
if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
if (flags & DC_EXEC) {
*st = new Station(area.tile);
_station_kdtree.Insert((*st)->index);
(*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
(*st)->string_id = GenerateStationName(*st, area.tile, name_class);
if (Company::IsValidID(_current_company)) {
if (_local_company == _current_company && !HasBit((*st)->town->have_ratings, _current_company)) {
ZoningTownAuthorityRatingChange();
}
SetBit((*st)->town->have_ratings, _current_company);
}
}
}
return CommandCost();
}
/**
* This is called right after a station was deleted.
* It checks if the whole station is free of substations, and if so, the station will be
* deleted after a little while.
* @param st Station
*/
static void DeleteStationIfEmpty(BaseStation *st)
{
if (!st->IsInUse()) {
st->delete_ctr = 0;
InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
}
/* station remains but it probably lost some parts - station sign should stay in the station boundaries */
UpdateStationSignCoord(st);
}
/**
* After adding/removing tiles to station, update some station-related stuff.
* @param adding True if adding tiles, false if removing them.
* @param type StationType being modified.
*/
void Station::AfterStationTileSetChange(bool adding, StationType type)
{
this->UpdateVirtCoord();
this->RecomputeCatchment();
DirtyCompanyInfrastructureWindows(this->owner);
if (adding) InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
switch (type) {
case STATION_RAIL:
SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
break;
case STATION_AIRPORT:
break;
case STATION_TRUCK:
case STATION_BUS:
SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
break;
case STATION_DOCK:
SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
break;
default: NOT_REACHED();
}
if (adding) {
UpdateStationAcceptance(this, false);
InvalidateWindowData(WC_SELECT_STATION, 0, 0);
} else {
DeleteStationIfEmpty(this);
}
}
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
/**
* Checks if the given tile is buildable, flat and has a certain height.
* @param tile TileIndex to check.
* @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
* @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
* @param allow_steep Whether steep slopes are allowed.
* @param check_bridge Check for the existence of a bridge.
* @return The cost in case of success, or an error code if it failed.
*/
CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge)
{
if (check_bridge && IsBridgeAbove(tile)) {
return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
}
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
int z;
Slope tileh = GetTileSlope(tile, &z);
/* Prohibit building if
* 1) The tile is "steep" (i.e. stretches two height levels).
* 2) The tile is non-flat and the build_on_slopes switch is disabled.
*/
if ((!allow_steep && IsSteepSlope(tileh)) ||
((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
}
CommandCost cost(EXPENSES_CONSTRUCTION);
int flat_z = z + GetSlopeMaxZ(tileh);
if (tileh != SLOPE_FLAT) {
/* Forbid building if the tile faces a slope in a invalid direction. */
for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
}
}
cost.AddCost(_price[PR_BUILD_FOUNDATION]);
}
/* The level of this tile must be equal to allowed_z. */
if (allowed_z < 0) {
/* First tile. */
allowed_z = flat_z;
} else if (allowed_z != flat_z) {
return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
}
return cost;
}
CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *statspec, byte layout, TileIndex northern_bridge_end, TileIndex southern_bridge_end, int bridge_height,
BridgeType bridge_type, TransportType bridge_transport_type)
{
assert(layout < 8);
if (statspec && HasBit(statspec->internal_flags, SSIF_BRIDGE_HEIGHTS_SET)) {
if (statspec->bridge_height[layout] == 0) return CommandCost(INVALID_STRING_ID);
if (GetTileMaxZ(tile) + statspec->bridge_height[layout] > bridge_height) {
return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
}
} else if (!statspec) {
// default stations/waypoints
const int height = layout < 4 ? 2 : 5;
if (GetTileMaxZ(tile) + height > bridge_height) return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
} else {
if (!_settings_game.construction.allow_stations_under_bridges) return CommandCost(INVALID_STRING_ID);
}
BridgePiecePillarFlags disallowed_pillar_flags;
if (statspec && HasBit(statspec->internal_flags, SSIF_BRIDGE_DISALLOWED_PILLARS_SET)) {
// pillar flags set by NewGRF
disallowed_pillar_flags = (BridgePiecePillarFlags) statspec->bridge_disallowed_pillars[layout];
} else if (!statspec) {
// default stations/waypoints
static const uint8 st_flags[8] = { 0x50, 0xA0, 0x50, 0xA0, 0x50 | 0x26, 0xA0 | 0x1C, 0x50 | 0x89, 0xA0 | 0x43 };
disallowed_pillar_flags = (BridgePiecePillarFlags) st_flags[layout];
} else if (HasBit(statspec->blocked, layout)) {
// non-track station tiles
disallowed_pillar_flags = (BridgePiecePillarFlags) 0;
} else {
// tracked station tiles
const Axis axis = HasBit(layout, 0) ? AXIS_Y : AXIS_X;
disallowed_pillar_flags = (BridgePiecePillarFlags) (axis == AXIS_X ? 0x50 : 0xA0);
}
if ((GetBridgeTilePillarFlags(tile, northern_bridge_end, southern_bridge_end, bridge_type, bridge_transport_type) & disallowed_pillar_flags) == 0) {
return CommandCost();
} else {
return CommandCost(STR_ERROR_BRIDGE_PILLARS_OBSTRUCT_STATION);
}
}
CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *statspec, byte layout)
{
if (!IsBridgeAbove(tile)) return CommandCost();
TileIndex southern_bridge_end = GetSouthernBridgeEnd(tile);
TileIndex northern_bridge_end = GetNorthernBridgeEnd(tile);
return IsRailStationBridgeAboveOk(tile, statspec, layout, northern_bridge_end, southern_bridge_end, GetBridgeHeight(southern_bridge_end),
GetBridgeType(southern_bridge_end), GetTunnelBridgeTransportType(southern_bridge_end));
}
CommandCost IsRoadStopBridgeAboveOK(TileIndex tile, bool drive_through, DiagDirection entrance,
TileIndex northern_bridge_end, TileIndex southern_bridge_end, int bridge_height,
BridgeType bridge_type, TransportType bridge_transport_type)
{
if (!_settings_game.construction.allow_road_stops_under_bridges) return CommandCost(INVALID_STRING_ID);
if (GetTileMaxZ(tile) + (drive_through ? 1 : 2) > bridge_height) {
return CommandCost(STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION);
}
BridgePiecePillarFlags disallowed_pillar_flags = (BridgePiecePillarFlags) 0;
if (drive_through) {
disallowed_pillar_flags = (BridgePiecePillarFlags) (DiagDirToAxis(entrance) == AXIS_X ? 0x50 : 0xA0);
} else {
SetBit(disallowed_pillar_flags, 4 + entrance);
}
if ((GetBridgeTilePillarFlags(tile, northern_bridge_end, southern_bridge_end, bridge_type, bridge_transport_type) & disallowed_pillar_flags) == 0) {
return CommandCost();
} else {
return CommandCost(STR_ERROR_BRIDGE_PILLARS_OBSTRUCT_STATION);
}
}
/**
* Checks if a rail station can be built at the given area.
* @param tile_area Area to check.
* @param flags Operation to perform.
* @param axis Rail station axis.
* @param station StationID to be queried and returned if available.
* @param rt The rail type to check for (overbuilding rail stations over rail).
* @param affected_vehicles List of trains with PBS reservations on the tiles
* @param spec_class Station class.
* @param spec_index Index into the station class.
* @param plat_len Platform length.
* @param numtracks Number of platforms.
* @return The cost in case of success, or an error code if it failed.
*/
static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
int allowed_z = -1;
uint invalid_dirs = 5 << axis;
const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
TILE_AREA_LOOP(tile_cur, tile_area) {
CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false, false);
if (ret.Failed()) return ret;
cost.AddCost(ret);
if (slope_cb) {
/* Do slope check if requested. */
ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, rt, statspec, axis, plat_len, numtracks);
if (ret.Failed()) return ret;
}
/* if station is set, then we have special handling to allow building on top of already existing stations.
* so station points to INVALID_STATION if we can build on any station.
* Or it points to a station if we're only allowed to build on exactly that station. */
if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
if (!IsRailStation(tile_cur)) {
return ClearTile_Station(tile_cur, DC_AUTO); // get error message
} else {
StationID st = GetStationIndex(tile_cur);
if (*station == INVALID_STATION) {
*station = st;
} else if (*station != st) {
return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
}
}
} else {
/* Rail type is only valid when building a railway station; if station to
* build isn't a rail station it's INVALID_RAILTYPE. */
if (rt != INVALID_RAILTYPE &&
IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
HasPowerOnRail(GetRailType(tile_cur), rt)) {
/* Allow overbuilding if the tile:
* - has rail, but no signals
* - it has exactly one track
* - the track is in line with the station
* - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
*/
TrackBits tracks = GetTrackBits(tile_cur);
Track track = RemoveFirstTrack(&tracks);
Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
if (tracks == TRACK_BIT_NONE && track == expected_track) {
/* Check for trains having a reservation for this tile. */
if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
Train *v = GetTrainForReservation(tile_cur, track);