OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

station_cmd.cpp
Go to the documentation of this file.
1 /* $Id: station_cmd.cpp 27178 2015-03-07 18:27:01Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
9
12 #include "stdafx.h"
13 #include "aircraft.h"
14 #include "bridge_map.h"
15 #include "cmd_helper.h"
16 #include "viewport_func.h"
17 #include "command_func.h"
18 #include "town.h"
19 #include "news_func.h"
20 #include "train.h"
21 #include "ship.h"
22 #include "roadveh.h"
23 #include "industry.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_debug.h"
26 #include "newgrf_station.h"
27 #include "newgrf_canal.h" /* For the buoy */
28 #include "pathfinder/yapf/yapf_cache.h"
29 #include "road_internal.h" /* For drawing catenary/checking road removal */
30 #include "autoslope.h"
31 #include "water.h"
32 #include "strings_func.h"
33 #include "clear_func.h"
34 #include "date_func.h"
35 #include "vehicle_func.h"
36 #include "string_func.h"
37 #include "animated_tile_func.h"
38 #include "elrail_func.h"
39 #include "station_base.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "waypoint_base.h"
43 #include "waypoint_func.h"
44 #include "pbs.h"
45 #include "debug.h"
46 #include "core/random_func.hpp"
47 #include "company_base.h"
48 #include "table/airporttile_ids.h"
49 #include "newgrf_airporttiles.h"
50 #include "order_backup.h"
51 #include "newgrf_house.h"
52 #include "company_gui.h"
53 #include "linkgraph/linkgraph_base.h"
54 #include "linkgraph/refresh.h"
55 #include "widgets/station_widget.h"
56
57 #include "table/strings.h"
58
59 #include "safeguards.h"
60
66 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
67
74 bool IsHangar(TileIndex t)
75 {
76 assert(IsTileType(t, MP_STATION));
77
78 /* If the tile isn't an airport there's no chance it's a hangar. */
79 if (!IsAirport(t)) return false;
80
81 const Station *st = Station::GetByTile(t);
82 const AirportSpec *as = st->airport.GetSpec();
83
84 for (uint i = 0; i < as->nof_depots; i++) {
85 if (st->airport.GetHangarTile(i) == t) return true;
86 }
87
88 return false;
89 }
90
98 template <class T>
99 CommandCost GetStationAround(TileArea ta, StationID closest_station, T **st)
100 {
101 ta.tile -= TileDiffXY(1, 1);
102 ta.w += 2;
103 ta.h += 2;
104
105 /* check around to see if there's any stations there */
106 TILE_AREA_LOOP(tile_cur, ta) {
107 if (IsTileType(tile_cur, MP_STATION)) {
108 StationID t = GetStationIndex(tile_cur);
109 if (!T::IsValidID(t)) continue;
110
111 if (closest_station == INVALID_STATION) {
112 closest_station = t;
113 } else if (closest_station != t) {
114 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
115 }
116 }
117 }
118 *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
119 return CommandCost();
120 }
121
127 typedef bool (*CMSAMatcher)(TileIndex tile);
128
135 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
136 {
137 int num = 0;
138
139 for (int dx = -3; dx <= 3; dx++) {
140 for (int dy = -3; dy <= 3; dy++) {
141 TileIndex t = TileAddWrap(tile, dx, dy);
142 if (t != INVALID_TILE && cmp(t)) num++;
143 }
144 }
145
146 return num;
147 }
148
154 static bool CMSAMine(TileIndex tile)
155 {
156 /* No industry */
157 if (!IsTileType(tile, MP_INDUSTRY)) return false;
158
159 const Industry *ind = Industry::GetByTile(tile);
160
161 /* No extractive industry */
162 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
163
164 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
165 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
166 * Also the production of passengers and mail is ignored. */
167 if (ind->produced_cargo[i] != CT_INVALID &&
168 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
169 return true;
170 }
171 }
172
173 return false;
174 }
175
181 static bool CMSAWater(TileIndex tile)
182 {
183 return IsTileType(tile, MP_WATER) && IsWater(tile);
184 }
185
191 static bool CMSATree(TileIndex tile)
192 {
193 return IsTileType(tile, MP_TREES);
194 }
195
196 #define M(x) ((x) - STR_SV_STNAME)
197
198 enum StationNaming {
199 STATIONNAMING_RAIL,
200 STATIONNAMING_ROAD,
201 STATIONNAMING_AIRPORT,
202 STATIONNAMING_OILRIG,
203 STATIONNAMING_DOCK,
204 STATIONNAMING_HELIPORT,
205 };
206
208 struct StationNameInformation {
209 uint32 free_names;
210 bool *indtypes;
211 };
212
221 static bool FindNearIndustryName(TileIndex tile, void *user_data)
222 {
223 /* All already found industry types */
224 StationNameInformation *sni = (StationNameInformation*)user_data;
225 if (!IsTileType(tile, MP_INDUSTRY)) return false;
226
227 /* If the station name is undefined it means that it doesn't name a station */
228 IndustryType indtype = GetIndustryType(tile);
229 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
230
231 /* In all cases if an industry that provides a name is found two of
232 * the standard names will be disabled. */
233 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
234 return !sni->indtypes[indtype];
235 }
236
237 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
238 {
239 static const uint32 _gen_station_name_bits[] = {
240 0, // STATIONNAMING_RAIL
241 0, // STATIONNAMING_ROAD
242 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
243 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
244 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
245 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
246 };
247
248 const Town *t = st->town;
249 uint32 free_names = UINT32_MAX;
250
251 bool indtypes[NUM_INDUSTRYTYPES];
252 memset(indtypes, 0, sizeof(indtypes));
253
254 const Station *s;
255 FOR_ALL_STATIONS(s) {
256 if (s != st && s->town == t) {
257 if (s->indtype != IT_INVALID) {
258 indtypes[s->indtype] = true;
259 StringID name = GetIndustrySpec(s->indtype)->station_name;
260 if (name != STR_UNDEFINED) {
261 /* Filter for other industrytypes with the same name */
262 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
263 const IndustrySpec *indsp = GetIndustrySpec(it);
264 if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
265 }
266 }
267 continue;
268 }
269 uint str = M(s->string_id);
270 if (str <= 0x20) {
271 if (str == M(STR_SV_STNAME_FOREST)) {
272 str = M(STR_SV_STNAME_WOODS);
273 }
274 ClrBit(free_names, str);
275 }
276 }
277 }
278
279 TileIndex indtile = tile;
280 StationNameInformation sni = { free_names, indtypes };
281 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
282 /* An industry has been found nearby */
283 IndustryType indtype = GetIndustryType(indtile);
284 const IndustrySpec *indsp = GetIndustrySpec(indtype);
285 /* STR_NULL means it only disables oil rig/mines */
286 if (indsp->station_name != STR_NULL) {
287 st->indtype = indtype;
288 return STR_SV_STNAME_FALLBACK;
289 }
290 }
291
292 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
293 free_names = sni.free_names;
294
295 /* check default names */
296 uint32 tmp = free_names & _gen_station_name_bits[name_class];
297 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
298
299 /* check mine? */
300 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
301 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
302 return STR_SV_STNAME_MINES;
303 }
304 }
305
306 /* check close enough to town to get central as name? */
307 if (DistanceMax(tile, t->xy) < 8) {
308 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
309
310 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
311 }
312
313 /* Check lakeside */
314 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
315 DistanceFromEdge(tile) < 20 &&
316 CountMapSquareAround(tile, CMSAWater) >= 5) {
317 return STR_SV_STNAME_LAKESIDE;
318 }
319
320 /* Check woods */
321 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
322 CountMapSquareAround(tile, CMSATree) >= 8 ||
323 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
324 ) {
325 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
326 }
327
328 /* check elevation compared to town */
329 int z = GetTileZ(tile);
330 int z2 = GetTileZ(t->xy);
331 if (z < z2) {
332 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
333 } else if (z > z2) {
334 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
335 }
336
337 /* check direction compared to town */
338 static const int8 _direction_and_table[] = {
339 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
340 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
341 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
342 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
343 };
344
345 free_names &= _direction_and_table[
346 (TileX(tile) < TileX(t->xy)) +
347 (TileY(tile) < TileY(t->xy)) * 2];
348
349 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));
350 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
351 }
352 #undef M
353
359 static Station *GetClosestDeletedStation(TileIndex tile)
360 {
361 uint threshold = 8;
362 Station *best_station = NULL;
363 Station *st;
364
365 FOR_ALL_STATIONS(st) {
366 if (!st->IsInUse() && st->owner == _current_company) {
367 uint cur_dist = DistanceManhattan(tile, st->xy);
368
369 if (cur_dist < threshold) {
370 threshold = cur_dist;
371 best_station = st;
372 }
373 }
374 }
375
376 return best_station;
377 }
378
379
380 void Station::GetTileArea(TileArea *ta, StationType type) const
381 {
382 switch (type) {
383 case STATION_RAIL:
384 *ta = this->train_station;
385 return;
386
387 case STATION_AIRPORT:
388 *ta = this->airport;
389 return;
390
391 case STATION_TRUCK:
392 *ta = this->truck_station;
393 return;
394
395 case STATION_BUS:
396 *ta = this->bus_station;
397 return;
398
399 case STATION_DOCK:
400 case STATION_OILRIG:
401 ta->tile = this->dock_tile;
402 break;
403
404 default: NOT_REACHED();
405 }
406
407 ta->w = 1;
408 ta->h = 1;
409 }
410
414 void Station::UpdateVirtCoord()
415 {
416 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
417
418 pt.y -= 32 * ZOOM_LVL_BASE;
419 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
420
421 SetDParam(0, this->index);
422 SetDParam(1, this->facilities);
423 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
424
425 SetWindowDirty(WC_STATION_VIEW, this->index);
426 }
427
429 void UpdateAllStationVirtCoords()
430 {
431 BaseStation *st;
432
433 FOR_ALL_BASE_STATIONS(st) {
434 st->UpdateVirtCoord();
435 }
436 }
437
443 static uint GetAcceptanceMask(const Station *st)
444 {
445 uint mask = 0;
446
447 for (CargoID i = 0; i < NUM_CARGO; i++) {
448 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) mask |= 1 << i;
449 }
450 return mask;
451 }
452
457 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
458 {
459 for (uint i = 0; i < num_items; i++) {
460 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
461 }
462
463 SetDParam(0, st->index);
464 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
465 }
466
474 CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
475 {
476 CargoArray produced;
477
478 int x = TileX(tile);
479 int y = TileY(tile);
480
481 /* expand the region by rad tiles on each side
482 * while making sure that we remain inside the board. */
483 int x2 = min(x + w + rad, MapSizeX());
484 int x1 = max(x - rad, 0);
485
486 int y2 = min(y + h + rad, MapSizeY());
487 int y1 = max(y - rad, 0);
488
489 assert(x1 < x2);
490 assert(y1 < y2);
491 assert(w > 0);
492 assert(h > 0);
493
494 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
495
496 /* Loop over all tiles to get the produced cargo of
497 * everything except industries */
498 TILE_AREA_LOOP(tile, ta) AddProducedCargo(tile, produced);
499
500 /* Loop over the industries. They produce cargo for
501 * anything that is within 'rad' from their bounding
502 * box. As such if you have e.g. a oil well the tile
503 * area loop might not hit an industry tile while
504 * the industry would produce cargo for the station.
505 */
506 const Industry *i;
507 FOR_ALL_INDUSTRIES(i) {
508 if (!ta.Intersects(i->location)) continue;
509
510 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
511 CargoID cargo = i->produced_cargo[j];
512 if (cargo != CT_INVALID) produced[cargo]++;
513 }
514 }
515
516 return produced;
517 }
518
527 CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint32 *always_accepted)
528 {
529 CargoArray acceptance;
530 if (always_accepted != NULL) *always_accepted = 0;
531
532 int x = TileX(tile);
533 int y = TileY(tile);
534
535 /* expand the region by rad tiles on each side
536 * while making sure that we remain inside the board. */
537 int x2 = min(x + w + rad, MapSizeX());
538 int y2 = min(y + h + rad, MapSizeY());
539 int x1 = max(x - rad, 0);
540 int y1 = max(y - rad, 0);
541
542 assert(x1 < x2);
543 assert(y1 < y2);
544 assert(w > 0);
545 assert(h > 0);
546
547 for (int yc = y1; yc != y2; yc++) {
548 for (int xc = x1; xc != x2; xc++) {
549 TileIndex tile = TileXY(xc, yc);
550 AddAcceptedCargo(tile, acceptance, always_accepted);
551 }
552 }
553
554 return acceptance;
555 }
556
562 void UpdateStationAcceptance(Station *st, bool show_msg)
563 {
564 /* old accepted goods types */
565 uint old_acc = GetAcceptanceMask(st);
566
567 /* And retrieve the acceptance. */
568 CargoArray acceptance;
569 if (!st->rect.IsEmpty()) {
570 acceptance = GetAcceptanceAroundTiles(
571 TileXY(st->rect.left, st->rect.top),
572 st->rect.right - st->rect.left + 1,
573 st->rect.bottom - st->rect.top + 1,
574 st->GetCatchmentRadius(),
575 &st->always_accepted
576 );
577 }
578
579 /* Adjust in case our station only accepts fewer kinds of goods */
580 for (CargoID i = 0; i < NUM_CARGO; i++) {
581 uint amt = acceptance[i];
582
583 /* Make sure the station can accept the goods type. */
584 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
585 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
586 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
587 amt = 0;
588 }
589
590 GoodsEntry &ge = st->goods[i];
591 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
592 if (LinkGraph::IsValidID(ge.link_graph)) {
593 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
594 }
595 }
596
597 /* Only show a message in case the acceptance was actually changed. */
598 uint new_acc = GetAcceptanceMask(st);
599 if (old_acc == new_acc) return;
600
601 /* show a message to report that the acceptance was changed? */
602 if (show_msg && st->owner == _local_company && st->IsInUse()) {
603 /* List of accept and reject strings for different number of
604 * cargo types */
605 static const StringID accept_msg[] = {
606 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
607 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
608 };
609 static const StringID reject_msg[] = {
610 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
611 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
612 };
613
614 /* Array of accepted and rejected cargo types */
615 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
616 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
617 uint num_acc = 0;
618 uint num_rej = 0;
619
620 /* Test each cargo type to see if its acceptance has changed */
621 for (CargoID i = 0; i < NUM_CARGO; i++) {
622 if (HasBit(new_acc, i)) {
623 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
624 /* New cargo is accepted */
625 accepts[num_acc++] = i;
626 }
627 } else {
628 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
629 /* Old cargo is no longer accepted */
630 rejects[num_rej++] = i;
631 }
632 }
633 }
634
635 /* Show news message if there are any changes */
636 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
637 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
638 }
639
640 /* redraw the station view since acceptance changed */
641 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
642 }
643
644 static void UpdateStationSignCoord(BaseStation *st)
645 {
646 const StationRect *r = &st->rect;
647
648 if (r->IsEmpty()) return; // no tiles belong to this station
649
650 /* clamp sign coord to be inside the station rect */
651 st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
652 st->UpdateVirtCoord();
653
654 if (!Station::IsExpected(st)) return;
655 Station *full_station = Station::From(st);
656 for (CargoID c = 0; c < NUM_CARGO; ++c) {
657 LinkGraphID lg = full_station->goods[c].link_graph;
658 if (!LinkGraph::IsValidID(lg)) continue;
659 (*LinkGraph::Get(lg))[full_station->goods[c].node].UpdateLocation(st->xy);
660 }
661 }
662
672 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
673 {
674 /* Find a deleted station close to us */
675 if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
676
677 if (*st != NULL) {
678 if ((*st)->owner != _current_company) {
679 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
680 }
681
682 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
683 if (ret.Failed()) return ret;
684 } else {
685 /* allocate and initialize new station */
686 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
687
688 if (flags & DC_EXEC) {
689 *st = new Station(area.tile);
690
691 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
692 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
693
694 if (Company::IsValidID(_current_company)) {
695 SetBit((*st)->town->have_ratings, _current_company);
696 }
697 }
698 }
699 return CommandCost();
700 }
701
708 static void DeleteStationIfEmpty(BaseStation *st)
709 {
710 if (!st->IsInUse()) {
711 st->delete_ctr = 0;
712 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
713 }
714 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
715 UpdateStationSignCoord(st);
716 }
717
718 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
719
729 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
730 {
731 if (check_bridge && IsBridgeAbove(tile)) {
732 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
733 }
734
735 CommandCost ret = EnsureNoVehicleOnGround(tile);
736 if (ret.Failed()) return ret;
737
738 int z;
739 Slope tileh = GetTileSlope(tile, &z);
740
741 /* Prohibit building if
742 * 1) The tile is "steep" (i.e. stretches two height levels).
743 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
744 */
745 if ((!allow_steep && IsSteepSlope(tileh)) ||
746 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
747 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
748 }
749
750 CommandCost cost(EXPENSES_CONSTRUCTION);
751 int flat_z = z + GetSlopeMaxZ(tileh);
752 if (tileh != SLOPE_FLAT) {
753 /* Forbid building if the tile faces a slope in a invalid direction. */
754 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
755 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
756 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
757 }
758 }
759 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
760 }
761
762 /* The level of this tile must be equal to allowed_z. */
763 if (allowed_z < 0) {
764 /* First tile. */
765 allowed_z = flat_z;
766 } else if (allowed_z != flat_z) {
767 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
768 }
769
770 return cost;
771 }
772
779 CommandCost CheckFlatLand(TileArea tile_area, DoCommandFlag flags)
780 {
781 CommandCost cost(EXPENSES_CONSTRUCTION);
782 int allowed_z = -1;
783
784 TILE_AREA_LOOP(tile_cur, tile_area) {
785 CommandCost ret = CheckBuildableTile(tile_cur, 0, allowed_z, true);
786 if (ret.Failed()) return ret;
787 cost.AddCost(ret);
788
789 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
790 if (ret.Failed()) return ret;
791 cost.AddCost(ret);
792 }
793
794 return cost;
795 }
796
811 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)
812 {
813 CommandCost cost(EXPENSES_CONSTRUCTION);
814 int allowed_z = -1;
815 uint invalid_dirs = 5 << axis;
816
817 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
818 bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
819
820 TILE_AREA_LOOP(tile_cur, tile_area) {
821 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
822 if (ret.Failed()) return ret;
823 cost.AddCost(ret);
824
825 if (slope_cb) {
826 /* Do slope check if requested. */
827 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
828 if (ret.Failed()) return ret;
829 }
830
831 /* if station is set, then we have special handling to allow building on top of already existing stations.
832 * so station points to INVALID_STATION if we can build on any station.
833 * Or it points to a station if we're only allowed to build on exactly that station. */
834 if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
835 if (!IsRailStation(tile_cur)) {
836 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
837 } else {
838 StationID st = GetStationIndex(tile_cur);
839 if (*station == INVALID_STATION) {
840 *station = st;
841 } else if (*station != st) {
842 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
843 }
844 }
845 } else {
846 /* Rail type is only valid when building a railway station; if station to
847 * build isn't a rail station it's INVALID_RAILTYPE. */
848 if (rt != INVALID_RAILTYPE &&
849 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
850 HasPowerOnRail(GetRailType(tile_cur), rt)) {
851 /* Allow overbuilding if the tile:
852 * - has rail, but no signals
853 * - it has exactly one track
854 * - the track is in line with the station
855 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
856 */
857 TrackBits tracks = GetTrackBits(tile_cur);
858 Track track = RemoveFirstTrack(&tracks);
859 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
860
861 if (tracks == TRACK_BIT_NONE && track == expected_track) {
862 /* Check for trains having a reservation for this tile. */
863 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
864 Train *v = GetTrainForReservation(tile_cur, track);
865 if (v != NULL) {
866 *affected_vehicles.Append() = v;
867 }
868 }
869 CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
870 if (ret.Failed()) return ret;
871 cost.AddCost(ret);
872 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
873 continue;
874 }
875 }
876 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
877 if (ret.Failed()) return ret;
878 cost.AddCost(ret);
879 }
880 }
881
882 return cost;
883 }
884
897 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)
898 {
899 CommandCost cost(EXPENSES_CONSTRUCTION);
900 int allowed_z = -1;
901
902 TILE_AREA_LOOP(cur_tile, tile_area) {
903 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
904 if (ret.Failed()) return ret;
905 cost.AddCost(ret);
906
907 /* If station is set, then we have special handling to allow building on top of already existing stations.
908 * Station points to INVALID_STATION if we can build on any station.
909 * Or it points to a station if we're only allowed to build on exactly that station. */
910 if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
911 if (!IsRoadStop(cur_tile)) {
912 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
913 } else {
914 if (is_truck_stop != IsTruckStop(cur_tile) ||
915 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
916 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
917 }
918 /* Drive-through station in the wrong direction. */
919 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
920 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
921 }
922 StationID st = GetStationIndex(cur_tile);
923 if (*station == INVALID_STATION) {
924 *station = st;
925 } else if (*station != st) {
926 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
927 }
928 }
929 } else {
930 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
931 /* Road bits in the wrong direction. */
932 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
933 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
934 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
935 switch (CountBits(rb)) {
936 case 1:
937 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
938
939 case 2:
940 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
941 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
942
943 default: // 3 or 4
944 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
945 }
946 }
947
948 RoadTypes cur_rts = IsNormalRoadTile(cur_tile) ? GetRoadTypes(cur_tile) : ROADTYPES_NONE;
949 uint num_roadbits = 0;
950 if (build_over_road) {
951 /* There is a road, check if we can build road+tram stop over it. */
952 if (HasBit(cur_rts, ROADTYPE_ROAD)) {
953 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
954 if (road_owner == OWNER_TOWN) {
955 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
956 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
957 CommandCost ret = CheckOwnership(road_owner);
958 if (ret.Failed()) return ret;
959 }
960 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_ROAD));
961 }
962
963 /* There is a tram, check if we can build road+tram stop over it. */
964 if (HasBit(cur_rts, ROADTYPE_TRAM)) {
965 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
966 if (!_settings_game.construction.road_stop_on_competitor_road && tram_owner != OWNER_NONE) {
967 CommandCost ret = CheckOwnership(tram_owner);
968 if (ret.Failed()) return ret;
969 }
970 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
971 }
972
973 /* Take into account existing roadbits. */
974 rts |= cur_rts;
975 } else {
976 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
977 if (ret.Failed()) return ret;
978 cost.AddCost(ret);
979 }
980
981 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
982 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
983 }
984 }
985
986 return cost;
987 }
988
996 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
997 {
998 TileArea cur_ta = st->train_station;
999
1000 /* determine new size of train station region.. */
1001 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
1002 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
1003 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1004 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1005 new_ta.tile = TileXY(x, y);
1006
1007 /* make sure the final size is not too big. */
1008 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1009 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1010 }
1011
1012 return CommandCost();
1013 }
1014
1015 static inline byte *CreateSingle(byte *layout, int n)
1016 {
1017 int i = n;
1018 do *layout++ = 0; while (--i);
1019 layout[((n - 1) >> 1) - n] = 2;
1020 return layout;
1021 }
1022
1023 static inline byte *CreateMulti(byte *layout, int n, byte b)
1024 {
1025 int i = n;
1026 do *layout++ = b; while (--i);
1027 if (n > 4) {
1028 layout[0 - n] = 0;
1029 layout[n - 1 - n] = 0;
1030 }
1031 return layout;
1032 }
1033
1041 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
1042 {
1043 if (statspec != NULL && statspec->lengths >= plat_len &&
1044 statspec->platforms[plat_len - 1] >= numtracks &&
1045 statspec->layouts[plat_len - 1][numtracks - 1]) {
1046 /* Custom layout defined, follow it. */
1047 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
1048 plat_len * numtracks);
1049 return;
1050 }
1051
1052 if (plat_len == 1) {
1053 CreateSingle(layout, numtracks);
1054 } else {
1055 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1056 numtracks >>= 1;
1057
1058 while (--numtracks >= 0) {
1059 layout = CreateMulti(layout, plat_len, 4);
1060 layout = CreateMulti(layout, plat_len, 6);
1061 }
1062 }
1063 }
1064
1076 template <class T, StringID error_message>
1077 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1078 {
1079 assert(*st == NULL);
1080 bool check_surrounding = true;
1081
1082 if (_settings_game.station.adjacent_stations) {
1083 if (existing_station != INVALID_STATION) {
1084 if (adjacent && existing_station != station_to_join) {
1085 /* You can't build an adjacent station over the top of one that
1086 * already exists. */
1087 return_cmd_error(error_message);
1088 } else {
1089 /* Extend the current station, and don't check whether it will
1090 * be near any other stations. */
1091 *st = T::GetIfValid(existing_station);
1092 check_surrounding = (*st == NULL);
1093 }
1094 } else {
1095 /* There's no station here. Don't check the tiles surrounding this
1096 * one if the company wanted to build an adjacent station. */
1097 if (adjacent) check_surrounding = false;
1098 }
1099 }
1100
1101 if (check_surrounding) {
1102 /* Make sure there are no similar stations around us. */
1103 CommandCost ret = GetStationAround(ta, existing_station, st);
1104 if (ret.Failed()) return ret;
1105 }
1106
1107 /* Distant join */
1108 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1109
1110 return CommandCost();
1111 }
1112
1122 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1123 {
1124 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1125 }
1126
1136 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1137 {
1138 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1139 }
1140
1158 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1159 {
1160 /* Unpack parameters */
1161 RailType rt = Extract<RailType, 0, 4>(p1);
1162 Axis axis = Extract<Axis, 4, 1>(p1);
1163 byte numtracks = GB(p1, 8, 8);
1164 byte plat_len = GB(p1, 16, 8);
1165 bool adjacent = HasBit(p1, 24);
1166
1167 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1168 byte spec_index = GB(p2, 8, 8);
1169 StationID station_to_join = GB(p2, 16, 16);
1170
1171 /* Does the authority allow this? */
1172 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1173 if (ret.Failed()) return ret;
1174
1175 if (!ValParamRailtype(rt)) return CMD_ERROR;
1176
1177 /* Check if the given station class is valid */
1178 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1179 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1180 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1181
1182 int w_org, h_org;
1183 if (axis == AXIS_X) {
1184 w_org = plat_len;
1185 h_org = numtracks;
1186 } else {
1187 h_org = plat_len;
1188 w_org = numtracks;
1189 }
1190
1191 bool reuse = (station_to_join != NEW_STATION);
1192 if (!reuse) station_to_join = INVALID_STATION;
1193 bool distant_join = (station_to_join != INVALID_STATION);
1194
1195 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1196
1197 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1198
1199 /* these values are those that will be stored in train_tile and station_platforms */
1200 TileArea new_location(tile_org, w_org, h_org);
1201
1202 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1203 StationID est = INVALID_STATION;
1204 SmallVector<Train *, 4> affected_vehicles;
1205 /* Clear the land below the station. */
1206 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1207 if (cost.Failed()) return cost;
1208 /* Add construction expenses. */
1209 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1210 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1211
1212 Station *st = NULL;
1213 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1214 if (ret.Failed()) return ret;
1215
1216 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1217 if (ret.Failed()) return ret;
1218
1219 if (st != NULL && st->train_station.tile != INVALID_TILE) {
1220 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1221 if (ret.Failed()) return ret;
1222 }
1223
1224 /* Check if we can allocate a custom stationspec to this station */
1225 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1226 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1227 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1228
1229 if (statspec != NULL) {
1230 /* Perform NewStation checks */
1231
1232 /* Check if the station size is permitted */
1233 if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
1234 return CMD_ERROR;
1235 }
1236
1237 /* Check if the station is buildable */
1238 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1239 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1240 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1241 }
1242 }
1243
1244 if (flags & DC_EXEC) {
1245 TileIndexDiff tile_delta;
1246 byte *layout_ptr;
1247 byte numtracks_orig;
1248 Track track;
1249
1250 st->train_station = new_location;
1251 st->AddFacility(FACIL_TRAIN, new_location.tile);
1252
1253 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1254
1255 if (statspec != NULL) {
1256 /* Include this station spec's animation trigger bitmask
1257 * in the station's cached copy. */
1258 st->cached_anim_triggers |= statspec->animation.triggers;
1259 }
1260
1261 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1262 track = AxisToTrack(axis);
1263
1264 layout_ptr = AllocaM(byte, numtracks * plat_len);
1265 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1266
1267 numtracks_orig = numtracks;
1268
1269 Company *c = Company::Get(st->owner);
1270 TileIndex tile_track = tile_org;
1271 do {
1272 TileIndex tile = tile_track;
1273 int w = plat_len;
1274 do {
1275 byte layout = *layout_ptr++;
1276 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1277 /* Check for trains having a reservation for this tile. */
1278 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1279 if (v != NULL) {
1280 FreeTrainTrackReservation(v);
1281 *affected_vehicles.Append() = v;
1282 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1283 for (; v->Next() != NULL; v = v->Next()) { }
1284 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1285 }
1286 }
1287
1288 /* Railtype can change when overbuilding. */
1289 if (IsRailStationTile(tile)) {
1290 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1291 c->infrastructure.station--;
1292 }
1293
1294 /* Remove animation if overbuilding */
1295 DeleteAnimatedTile(tile);
1296 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1297 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1298 /* Free the spec if we overbuild something */
1299 DeallocateSpecFromStation(st, old_specindex);
1300
1301 SetCustomStationSpecIndex(tile, specindex);
1302 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1303 SetAnimationFrame(tile, 0);
1304
1305 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1306 c->infrastructure.station++;
1307
1308 if (statspec != NULL) {
1309 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1310 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1311
1312 /* As the station is not yet completely finished, the station does not yet exist. */
1313 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1314 if (callback != CALLBACK_FAILED) {
1315 if (callback < 8) {
1316 SetStationGfx(tile, (callback & ~1) + axis);
1317 } else {
1318 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1319 }
1320 }
1321
1322 /* Trigger station animation -- after building? */
1323 TriggerStationAnimation(st, tile, SAT_BUILT);
1324 }
1325
1326 tile += tile_delta;
1327 } while (--w);
1328 AddTrackToSignalBuffer(tile_track, track, _current_company);
1329 YapfNotifyTrackLayoutChange(tile_track, track);
1330 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1331 } while (--numtracks);
1332
1333 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1334 /* Restore reservations of trains. */
1335 Train *v = affected_vehicles[i];
1336 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1337 TryPathReserve(v, true, true);
1338 for (; v->Next() != NULL; v = v->Next()) { }
1339 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1340 }
1341
1342 /* Check whether we need to expand the reservation of trains already on the station. */
1343 TileArea update_reservation_area;
1344 if (axis == AXIS_X) {
1345 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1346 } else {
1347 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1348 }
1349
1350 TILE_AREA_LOOP(tile, update_reservation_area) {
1351 /* Don't even try to make eye candy parts reserved. */
1352 if (IsStationTileBlocked(tile)) continue;
1353
1354 DiagDirection dir = AxisToDiagDir(axis);
1355 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1356 TileIndex platform_begin = tile;
1357 TileIndex platform_end = tile;
1358
1359 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1360 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1361 platform_begin = next_tile;
1362 }
1363 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1364 platform_end = next_tile;
1365 }
1366
1367 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1368 bool reservation = false;
1369 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1370 reservation = HasStationReservation(t);
1371 }
1372
1373 if (reservation) {
1374 SetRailStationPlatformReservation(platform_begin, dir, true);
1375 }
1376 }
1377
1378 st->MarkTilesDirty(false);
1379 st->UpdateVirtCoord();
1380 UpdateStationAcceptance(st, false);
1381 st->RecomputeIndustriesNear();
1382 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1383 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1384 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1385 DirtyCompanyInfrastructureWindows(st->owner);
1386 }
1387
1388 return cost;
1389 }
1390
1391 static void MakeRailStationAreaSmaller(BaseStation *st)
1392 {
1393 TileArea ta = st->train_station;
1394
1395 restart:
1396
1397 /* too small? */
1398 if (ta.w != 0 && ta.h != 0) {
1399 /* check the left side, x = constant, y changes */
1400 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
1401 /* the left side is unused? */
1402 if (++i == ta.h) {
1403 ta.tile += TileDiffXY(1, 0);
1404 ta.w--;
1405 goto restart;
1406 }
1407 }
1408
1409 /* check the right side, x = constant, y changes */
1410 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
1411 /* the right side is unused? */
1412 if (++i == ta.h) {
1413 ta.w--;
1414 goto restart;
1415 }
1416 }
1417
1418 /* check the upper side, y = constant, x changes */
1419 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
1420 /* the left side is unused? */
1421 if (++i == ta.w) {
1422 ta.tile += TileDiffXY(0, 1);
1423 ta.h--;
1424 goto restart;
1425 }
1426 }
1427
1428 /* check the lower side, y = constant, x changes */
1429 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
1430 /* the left side is unused? */
1431 if (++i == ta.w) {
1432 ta.h--;
1433 goto restart;
1434 }
1435 }
1436 } else {
1437 ta.Clear();
1438 }
1439
1440 st->train_station = ta;
1441 }
1442
1453 template <class T>
1454 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1455 {
1456 /* Count of the number of tiles removed */
1457 int quantity = 0;
1458 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1459 /* Accumulator for the errors seen during clearing. If no errors happen,
1460 * and the quantity is 0 there is no station. Otherwise it will be one
1461 * of the other error that got accumulated. */
1462 CommandCost error;
1463
1464 /* Do the action for every tile into the area */
1465 TILE_AREA_LOOP(tile, ta) {
1466 /* Make sure the specified tile is a rail station */
1467 if (!HasStationTileRail(tile)) continue;
1468
1469 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1470 CommandCost ret = EnsureNoVehicleOnGround(tile);
1471 error.AddCost(ret);
1472 if (ret.Failed()) continue;
1473
1474 /* Check ownership of station */
1475 T *st = T::GetByTile(tile);
1476 if (st == NULL) continue;
1477
1478 if (_current_company != OWNER_WATER) {
1479 CommandCost ret = CheckOwnership(st->owner);
1480 error.AddCost(ret);
1481 if (ret.Failed()) continue;
1482 }
1483
1484 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1485 quantity++;
1486
1487 if (keep_rail || IsStationTileBlocked(tile)) {
1488 /* Don't refund the 'steel' of the track when we keep the
1489 * rail, or when the tile didn't have any rail at all. */
1490 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1491 }
1492
1493 if (flags & DC_EXEC) {
1494 /* read variables before the station tile is removed */
1495 uint specindex = GetCustomStationSpecIndex(tile);
1496 Track track = GetRailStationTrack(tile);
1497 Owner owner = GetTileOwner(tile);
1498 RailType rt = GetRailType(tile);
1499 Train *v = NULL;
1500
1501 if (HasStationReservation(tile)) {
1502 v = GetTrainForReservation(tile, track);
1503 if (v != NULL) {
1504 /* Free train reservation. */
1505 FreeTrainTrackReservation(v);
1506 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1507 Vehicle *temp = v;
1508 for (; temp->Next() != NULL; temp = temp->Next()) { }
1509 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
1510 }
1511 }
1512
1513 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1514 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1515
1516 DoClearSquare(tile);
1517 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1518 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1519 Company::Get(owner)->infrastructure.station--;
1520 DirtyCompanyInfrastructureWindows(owner);
1521
1522 st->rect.AfterRemoveTile(st, tile);
1523 AddTrackToSignalBuffer(tile, track, owner);
1524 YapfNotifyTrackLayoutChange(tile, track);
1525
1526 DeallocateSpecFromStation(st, specindex);
1527
1528 affected_stations.Include(st);
1529
1530 if (v != NULL) {
1531 /* Restore station reservation. */
1532 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1533 TryPathReserve(v, true, true);
1534 for (; v->Next() != NULL; v = v->Next()) { }
1535 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1536 }
1537 }
1538 }
1539
1540 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1541
1542 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1543 T *st = *stp;
1544
1545 /* now we need to make the "spanned" area of the railway station smaller
1546 * if we deleted something at the edges.
1547 * we also need to adjust train_tile. */
1548 MakeRailStationAreaSmaller(st);
1549 UpdateStationSignCoord(st);
1550
1551 /* if we deleted the whole station, delete the train facility. */
1552 if (st->train_station.tile == INVALID_TILE) {
1553 st->facilities &= ~FACIL_TRAIN;
1554 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1555 st->UpdateVirtCoord();
1556 DeleteStationIfEmpty(st);
1557 }
1558 }
1559
1560 total_cost.AddCost(quantity * removal_cost);
1561 return total_cost;
1562 }
1563
1575 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1576 {
1577 TileIndex end = p1 == 0 ? start : p1;
1578 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1579
1580 TileArea ta(start, end);
1581 SmallVector<Station *, 4> affected_stations;
1582
1583 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1584 if (ret.Failed()) return ret;
1585
1586 /* Do all station specific functions here. */
1587 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1588 Station *st = *stp;
1589
1590 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1591 st->MarkTilesDirty(false);
1592 st->RecomputeIndustriesNear();
1593 }
1594
1595 /* Now apply the rail cost to the number that we deleted */
1596 return ret;
1597 }
1598
1610 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1611 {
1612 TileIndex end = p1 == 0 ? start : p1;
1613 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1614
1615 TileArea ta(start, end);
1616 SmallVector<Waypoint *, 4> affected_stations;
1617
1618 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
1619 }
1620
1621
1629 template <class T>
1630 CommandCost RemoveRailStation(T *st, DoCommandFlag flags)
1631 {
1632 /* Current company owns the station? */
1633 if (_current_company != OWNER_WATER) {
1634 CommandCost ret = CheckOwnership(st->owner);
1635 if (ret.Failed()) return ret;
1636 }
1637
1638 /* determine width and height of platforms */
1639 TileArea ta = st->train_station;
1640
1641 assert(ta.w != 0 && ta.h != 0);
1642
1643 CommandCost cost(EXPENSES_CONSTRUCTION);
1644 /* clear all areas of the station */
1645 TILE_AREA_LOOP(tile, ta) {
1646 /* only remove tiles that are actually train station tiles */
1647 if (!st->TileBelongsToRailStation(tile)) continue;
1648
1649 CommandCost ret = EnsureNoVehicleOnGround(tile);
1650 if (ret.Failed()) return ret;
1651
1652 cost.AddCost(_price[PR_CLEAR_STATION_RAIL]);
1653 if (flags & DC_EXEC) {
1654 /* read variables before the station tile is removed */
1655 Track track = GetRailStationTrack(tile);
1656 Owner owner = GetTileOwner(tile); // _current_company can be OWNER_WATER
1657 Train *v = NULL;
1658 if (HasStationReservation(tile)) {
1659 v = GetTrainForReservation(tile, track);
1660 if (v != NULL) FreeTrainTrackReservation(v);
1661 }
1662 if (!IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1663 Company::Get(owner)->infrastructure.station--;
1664 DoClearSquare(tile);
1665 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1666 AddTrackToSignalBuffer(tile, track, owner);
1667 YapfNotifyTrackLayoutChange(tile, track);
1668 if (v != NULL) TryPathReserve(v, true);
1669 }
1670 }
1671
1672 if (flags & DC_EXEC) {
1673 st->rect.AfterRemoveRect(st, st->train_station);
1674
1675 st->train_station.Clear();
1676
1677 st->facilities &= ~FACIL_TRAIN;
1678
1679 free(st->speclist);
1680 st->num_specs = 0;
1681 st->speclist = NULL;
1682 st->cached_anim_triggers = 0;
1683
1684 DirtyCompanyInfrastructureWindows(st->owner);
1685 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1686 st->UpdateVirtCoord();
1687 DeleteStationIfEmpty(st);
1688 }
1689
1690 return cost;
1691 }
1692
1699 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1700 {
1701 /* if there is flooding, remove platforms tile by tile */
1702 if (_current_company == OWNER_WATER) {
1703 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1704 }
1705
1706 Station *st = Station::GetByTile(tile);
1707 CommandCost cost = RemoveRailStation(st, flags);
1708
1709 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1710
1711 return cost;
1712 }
1713
1720 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1721 {
1722 /* if there is flooding, remove waypoints tile by tile */
1723 if (_current_company == OWNER_WATER) {
1724 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1725 }
1726
1727 return RemoveRailStation(Waypoint::GetByTile(tile), flags);
1728 }
1729
1730
1736 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1737 {
1738 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1739
1740 if (*primary_stop == NULL) {
1741 /* we have no roadstop of the type yet, so write a "primary stop" */
1742 return primary_stop;
1743 } else {
1744 /* there are stops already, so append to the end of the list */
1745 RoadStop *stop = *primary_stop;
1746 while (stop->next != NULL) stop = stop->next;
1747 return &stop->next;
1748 }
1749 }
1750
1751 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1752
1762 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1763 {
1764 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1765 }
1766
1783 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1784 {
1785 bool type = HasBit(p2, 0);
1786 bool is_drive_through = HasBit(p2, 1);
1787 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1788 StationID station_to_join = GB(p2, 16, 16);
1789 bool reuse = (station_to_join != NEW_STATION);
1790 if (!reuse) station_to_join = INVALID_STATION;
1791 bool distant_join = (station_to_join != INVALID_STATION);
1792
1793 uint8 width = (uint8)GB(p1, 0, 8);
1794 uint8 lenght = (uint8)GB(p1, 8, 8);
1795
1796 /* Check if the requested road stop is too big */
1797 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1798 /* Check for incorrect width / length. */
1799 if (width == 0 || lenght == 0) return CMD_ERROR;
1800 /* Check if the first tile and the last tile are valid */
1801 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1802
1803 TileArea roadstop_area(tile, width, lenght);
1804
1805 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1806
1807 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1808
1809 /* Trams only have drive through stops */
1810 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1811
1812 DiagDirection ddir;
1813 Axis axis;
1814 if (is_drive_through) {
1815 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1816 axis = Extract<Axis, 6, 1>(p2);
1817 ddir = AxisToDiagDir(axis);
1818 } else {
1819 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1820 ddir = Extract<DiagDirection, 6, 2>(p2);
1821 axis = DiagDirToAxis(ddir);
1822 }
1823
1824 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1825 if (ret.Failed()) return ret;
1826
1827 /* Total road stop cost. */
1828 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1829 StationID est = INVALID_STATION;
1830 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rts);
1831 if (ret.Failed()) return ret;
1832 cost.AddCost(ret);
1833
1834 Station *st = NULL;
1835 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
1836 if (ret.Failed()) return ret;
1837
1838 /* Check if this number of road stops can be allocated. */
1839 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);
1840
1841 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1842 if (ret.Failed()) return ret;
1843
1844 if (flags & DC_EXEC) {
1845 /* Check every tile in the area. */
1846 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1847 RoadTypes cur_rts = GetRoadTypes(cur_tile);
1848 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1849 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1850
1851 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
1852 RemoveRoadStop(cur_tile, flags);
1853 }
1854
1855 RoadStop *road_stop = new RoadStop(cur_tile);
1856 /* Insert into linked list of RoadStops. */
1857 RoadStop **currstop = FindRoadStopSpot(type, st);
1858 *currstop = road_stop;
1859
1860 if (type) {
1861 st->truck_station.Add(cur_tile);
1862 } else {
1863 st->bus_station.Add(cur_tile);
1864 }
1865
1866 /* Initialize an empty station. */
1867 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1868
1869 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1870
1871 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1872 if (is_drive_through) {
1873 /* Update company infrastructure counts. If the current tile is a normal
1874 * road tile, count only the new road bits needed to get a full diagonal road. */
1875 RoadType rt;
1876 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1877 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1878 if (c != NULL) {
1879 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1880 DirtyCompanyInfrastructureWindows(c->index);
1881 }
1882 }
1883
1884 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, axis);
1885 road_stop->MakeDriveThrough();
1886 } else {
1887 /* Non-drive-through stop never overbuild and always count as two road bits. */
1888 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1889 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1890 }
1891 Company::Get(st->owner)->infrastructure.station++;
1892 DirtyCompanyInfrastructureWindows(st->owner);
1893
1894 MarkTileDirtyByTile(cur_tile);
1895 }
1896 }
1897
1898 if (st != NULL) {
1899 st->UpdateVirtCoord();
1900 UpdateStationAcceptance(st, false);
1901 st->RecomputeIndustriesNear();
1902 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1903 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1904 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1905 }
1906 return cost;
1907 }
1908
1909
1910 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
1911 {
1912 if (v->type == VEH_ROAD) {
1913 /* Okay... we are a road vehicle on a drive through road stop.
1914 * But that road stop has just been removed, so we need to make
1915 * sure we are in a valid state... however, vehicles can also
1916 * turn on road stop tiles, so only clear the 'road stop' state
1917 * bits and only when the state was 'in road stop', otherwise
1918 * we'll end up clearing the turn around bits. */
1919 RoadVehicle *rv = RoadVehicle::From(v);
1920 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1921 }
1922
1923 return NULL;
1924 }
1925
1926
1933 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1934 {
1935 Station *st = Station::GetByTile(tile);
1936
1937 if (_current_company != OWNER_WATER) {
1938 CommandCost ret = CheckOwnership(st->owner);
1939 if (ret.Failed()) return ret;
1940 }
1941
1942 bool is_truck = IsTruckStop(tile);
1943
1944 RoadStop **primary_stop;
1945 RoadStop *cur_stop;
1946 if (is_truck) { // truck stop
1947 primary_stop = &st->truck_stops;
1948 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1949 } else {
1950 primary_stop = &st->bus_stops;
1951 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1952 }
1953
1954 assert(cur_stop != NULL);
1955
1956 /* don't do the check for drive-through road stops when company bankrupts */
1957 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1958 /* remove the 'going through road stop' status from all vehicles on that tile */
1959 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
1960 } else {
1961 CommandCost ret = EnsureNoVehicleOnGround(tile);
1962 if (ret.Failed()) return ret;
1963 }
1964
1965 if (flags & DC_EXEC) {
1966 if (*primary_stop == cur_stop) {
1967 /* removed the first stop in the list */
1968 *primary_stop = cur_stop->next;
1969 /* removed the only stop? */
1970 if (*primary_stop == NULL) {
1971 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1972 }
1973 } else {
1974 /* tell the predecessor in the list to skip this stop */
1975 RoadStop *pred = *primary_stop;
1976 while (pred->next != cur_stop) pred = pred->next;
1977 pred->next = cur_stop->next;
1978 }
1979
1980 /* Update company infrastructure counts. */
1981 RoadType rt;
1982 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1983 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1984 if (c != NULL) {
1985 c->infrastructure.road[rt] -= 2;
1986 DirtyCompanyInfrastructureWindows(c->index);
1987 }
1988 }
1989 Company::Get(st->owner)->infrastructure.station--;
1990
1991 if (IsDriveThroughStopTile(tile)) {
1992 /* Clears the tile for us */
1993 cur_stop->ClearDriveThrough();
1994 } else {
1995 DoClearSquare(tile);
1996 }
1997
1998 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1999 delete cur_stop;
2000
2001 /* Make sure no vehicle is going to the old roadstop */
2002 RoadVehicle *v;
2003 FOR_ALL_ROADVEHICLES(v) {
2004 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
2005 v->dest_tile == tile) {
2006 v->dest_tile = v->GetOrderStationLocation(st->index);
2007 }
2008 }
2009
2010 st->rect.AfterRemoveTile(st, tile);
2011
2012 st->UpdateVirtCoord();
2013 st->RecomputeIndustriesNear();
2014 DeleteStationIfEmpty(st);
2015
2016 /* Update the tile area of the truck/bus stop */
2017 if (is_truck) {
2018 st->truck_station.Clear();
2019 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
2020 } else {
2021 st->bus_station.Clear();
2022 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
2023 }
2024 }
2025
2026 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
2027 }
2028
2039 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2040 {
2041 uint8 width = (uint8)GB(p1, 0, 8);
2042 uint8 height = (uint8)GB(p1, 8, 8);
2043
2044 /* Check for incorrect width / height. */
2045 if (width == 0 || height == 0) return CMD_ERROR;
2046 /* Check if the first tile and the last tile are valid */
2047 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2048
2049 TileArea roadstop_area(tile, width, height);
2050
2051 int quantity = 0;
2052 CommandCost cost(EXPENSES_CONSTRUCTION);
2053 TILE_AREA_LOOP(cur_tile, roadstop_area) {
2054 /* Make sure the specified tile is a road stop of the correct type */
2055 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2056
2057 /* Save the stop info before it is removed */
2058 bool is_drive_through = IsDriveThroughStopTile(cur_tile);
2059 RoadTypes rts = GetRoadTypes(cur_tile);
2060 RoadBits road_bits = IsDriveThroughStopTile(cur_tile) ?
2061 ((GetRoadStopDir(cur_tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
2062 DiagDirToRoadBits(GetRoadStopDir(cur_tile));
2063
2064 Owner road_owner = GetRoadOwner(cur_tile, ROADTYPE_ROAD);
2065 Owner tram_owner = GetRoadOwner(cur_tile, ROADTYPE_TRAM);
2066 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2067 if (ret.Failed()) return ret;
2068 cost.AddCost(ret);
2069
2070 quantity++;
2071 /* If the stop was a drive-through stop replace the road */
2072 if ((flags & DC_EXEC) && is_drive_through) {
2073 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2074 road_owner, tram_owner);
2075
2076 /* Update company infrastructure counts. */
2077 RoadType rt;
2078 FOR_EACH_SET_ROADTYPE(rt, rts) {
2079 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
2080 if (c != NULL) {
2081 c->infrastructure.road[rt] += CountBits(road_bits);
2082 DirtyCompanyInfrastructureWindows(c->index);
2083 }
2084 }
2085 }
2086 }
2087
2088 if (quantity == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_STATION);
2089
2090 return cost;
2091 }
2092
2099 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
2100 {
2101 uint mindist = UINT_MAX;
2102
2103 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2104 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
2105 }
2106
2107 return mindist;
2108 }
2109
2119 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
2120 {
2121 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2122 * So no need to go any further*/
2123 if (as->noise_level < 2) return as->noise_level;
2124
2125 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
2126
2127 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2128 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2129 * Basically, it says that the less tolerant a town is, the bigger the distance before
2130 * an actual decrease can be granted */
2131 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2132
2133 /* now, we want to have the distance segmented using the distance judged bareable by town
2134 * This will give us the coefficient of reduction the distance provides. */
2135 uint noise_reduction = distance / town_tolerance_distance;
2136
2137 /* If the noise reduction equals the airport noise itself, don't give it for free.
2138 * Otherwise, simply reduce the airport's level. */
2139 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2140 }
2141
2149 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
2150 {
2151 Town *t, *nearest = NULL;
2152 uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2153 uint mindist = UINT_MAX - add; // prevent overflow
2154 FOR_ALL_TOWNS(t) {
2155 if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2156 TileIterator *copy = it.Clone();
2157 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
2158 delete copy;
2159 if (dist < mindist) {
2160 nearest = t;
2161 mindist = dist;
2162 }
2163 }
2164 }
2165
2166 return nearest;
2167 }
2168
2169
2171 void UpdateAirportsNoise()
2172 {
2173 Town *t;
2174 const Station *st;
2175
2176 FOR_ALL_TOWNS(t) t->noise_reached = 0;
2177
2178 FOR_ALL_STATIONS(st) {
2179 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2180 const AirportSpec *as = st->airport.GetSpec();
2181 AirportTileIterator it(st);
2182 Town *nearest = AirportGetNearestTown(as, it);
2183 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
2184 }
2185 }
2186 }
2187
2201 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2202 {
2203 StationID station_to_join = GB(p2, 16, 16);
2204 bool reuse = (station_to_join != NEW_STATION);
2205 if (!reuse) station_to_join = INVALID_STATION;
2206 bool distant_join = (station_to_join != INVALID_STATION);
2207 byte airport_type = GB(p1, 0, 8);
2208 byte layout = GB(p1, 8, 8);
2209
2210 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2211
2212 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2213
2214 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2215 if (ret.Failed()) return ret;
2216
2217 /* Check if a valid, buildable airport was chosen for construction */
2218 const AirportSpec *as = AirportSpec::Get(airport_type);
2219 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2220
2221 Direction rotation = as->rotation[layout];
2222 int w = as->size_x;
2223 int h = as->size_y;
2224 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2225 TileArea airport_area = TileArea(tile, w, h);
2226
2227 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2228 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2229 }
2230
2231 CommandCost cost = CheckFlatLand(airport_area, flags);
2232 if (cost.Failed()) return cost;
2233
2234 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2235 AirportTileTableIterator iter(as->table[layout], tile);
2236 Town *nearest = AirportGetNearestTown(as, iter);
2237 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
2238
2239 /* Check if local auth would allow a new airport */
2240 StringID authority_refuse_message = STR_NULL;
2241 Town *authority_refuse_town = NULL;
2242
2243 if (_settings_game.economy.station_noise_level) {
2244 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2245 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2246 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2247 authority_refuse_town = nearest;
2248 }
2249 } else {
2250 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2251 uint num = 0;
2252 const Station *st;
2253 FOR_ALL_STATIONS(st) {
2254 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2255 }
2256 if (num >= 2) {
2257 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2258 authority_refuse_town = t;
2259 }
2260 }
2261
2262 if (authority_refuse_message != STR_NULL) {
2263 SetDParam(0, authority_refuse_town->index);
2264 return_cmd_error(authority_refuse_message);
2265 }
2266
2267 Station *st = NULL;
2268 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
2269 if (ret.Failed()) return ret;
2270
2271 /* Distant join */
2272 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2273
2274 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2275 if (ret.Failed()) return ret;
2276
2277 if (st != NULL && st->airport.tile != INVALID_TILE) {
2278 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2279 }
2280
2281 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2282 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2283 }
2284
2285 if (flags & DC_EXEC) {
2286 /* Always add the noise, so there will be no need to recalculate when option toggles */
2287 nearest->noise_reached += newnoise_level;
2288
2289 st->AddFacility(FACIL_AIRPORT, tile);
2290 st->airport.type = airport_type;
2291 st->airport.layout = layout;
2292 st->airport.flags = 0;
2293 st->airport.rotation = rotation;
2294
2295 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2296
2297 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2298 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2299 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2300 st->airport.Add(iter);
2301
2302 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2303 }
2304
2305 /* Only call the animation trigger after all tiles have been built */
2306 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2307 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2308 }
2309
2310 UpdateAirplanesOnNewStation(st);
2311
2312 Company::Get(st->owner)->infrastructure.airport++;
2313 DirtyCompanyInfrastructureWindows(st->owner);
2314
2315 st->UpdateVirtCoord();
2316 UpdateStationAcceptance(st, false);
2317 st->RecomputeIndustriesNear();
2318 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2319 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2320 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2321
2322 if (_settings_game.economy.station_noise_level) {
2323 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2324 }
2325 }
2326
2327 return cost;
2328 }
2329
2336 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2337 {
2338 Station *st = Station::GetByTile(tile);
2339
2340 if (_current_company != OWNER_WATER) {
2341 CommandCost ret = CheckOwnership(st->owner);
2342 if (ret.Failed()) return ret;
2343 }
2344
2345 tile = st->airport.tile;
2346
2347 CommandCost cost(EXPENSES_CONSTRUCTION);
2348
2349 const Aircraft *a;
2350 FOR_ALL_AIRCRAFT(a) {
2351 if (!a->IsNormalAircraft()) continue;
2352 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
2353 }
2354
2355 if (flags & DC_EXEC) {
2356 const AirportSpec *as = st->airport.GetSpec();
2357 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2358 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2359 * need of recalculation */
2360 AirportTileIterator it(st);
2361 Town *nearest = AirportGetNearestTown(as, it);
2362 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
2363 }
2364
2365 TILE_AREA_LOOP(tile_cur, st->airport) {
2366 if (!st->TileBelongsToAirport(tile_cur)) continue;
2367
2368 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2369 if (ret.Failed()) return ret;
2370
2371 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2372
2373 if (flags & DC_EXEC) {
2374 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2375 DeleteAnimatedTile(tile_cur);
2376 DoClearSquare(tile_cur);
2377 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2378 }
2379 }
2380
2381 if (flags & DC_EXEC) {
2382 /* Clear the persistent storage. */
2383 delete st->airport.psa;
2384
2385 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2386 DeleteWindowById(
2387 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2388 );
2389 }
2390
2391 st->rect.AfterRemoveRect(st, st->airport);
2392
2393 st->airport.Clear();
2394 st->facilities &= ~FACIL_AIRPORT;
2395
2396 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2397
2398 if (_settings_game.economy.station_noise_level) {
2399 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2400 }
2401
2402 Company::Get(st->owner)->infrastructure.airport--;
2403 DirtyCompanyInfrastructureWindows(st->owner);
2404
2405 st->UpdateVirtCoord();
2406 st->RecomputeIndustriesNear();
2407 DeleteStationIfEmpty(st);
2408 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2409 }
2410
2411 return cost;
2412 }
2413
2423 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2424 {
2425 if (!Station::IsValidID(p1)) return CMD_ERROR;
2426 Station *st = Station::Get(p1);
2427
2428 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2429
2430 CommandCost ret = CheckOwnership(st->owner);
2431 if (ret.Failed()) return ret;
2432
2433 if (flags & DC_EXEC) {
2434 st->airport.flags ^= AIRPORT_CLOSED_block;
2435 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2436 }
2437 return CommandCost();
2438 }
2439
2446 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2447 {
2448 const Vehicle *v;
2449 FOR_ALL_VEHICLES(v) {
2450 if ((v->owner == company) == include_company) {
2451 const Order *order;
2452 FOR_VEHICLE_ORDERS(v, order) {
2453 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2454 return true;
2455 }
2456 }
2457 }
2458 }
2459 return false;
2460 }
2461
2462 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2463 {-1, 0},
2464 { 0, 0},
2465 { 0, 0},
2466 { 0, -1}
2467 };
2468 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2469 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2470
2480 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2481 {
2482 StationID station_to_join = GB(p2, 16, 16);
2483 bool reuse = (station_to_join != NEW_STATION);
2484 if (!reuse) station_to_join = INVALID_STATION;
2485 bool distant_join = (station_to_join != INVALID_STATION);
2486
2487 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2488
2489 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2490 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2491 direction = ReverseDiagDir(direction);
2492
2493 /* Docks cannot be placed on rapids */
2494 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2495
2496 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2497 if (ret.Failed()) return ret;
2498
2499 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2500
2501 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2502 if (ret.Failed()) return ret;
2503
2504 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2505
2506 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2507 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2508 }
2509
2510 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2511
2512 /* Get the water class of the water tile before it is cleared.*/
2513 WaterClass wc = GetWaterClass(tile_cur);
2514
2515 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2516 if (ret.Failed()) return ret;
2517
2518 tile_cur += TileOffsByDiagDir(direction);
2519 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2520 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2521 }
2522
2523 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2524 _dock_w_chk[direction], _dock_h_chk[direction]);
2525
2526 /* middle */
2527 Station *st = NULL;
2528 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
2529 if (ret.Failed()) return ret;
2530
2531 /* Distant join */
2532 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2533
2534 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2535 if (ret.Failed()) return ret;
2536
2537 if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
2538
2539 if (flags & DC_EXEC) {
2540 st->dock_tile = tile;
2541 st->AddFacility(FACIL_DOCK, tile);
2542
2543 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2544
2545 /* If the water part of the dock is on a canal, update infrastructure counts.
2546 * This is needed as we've unconditionally cleared that tile before. */
2547 if (wc == WATER_CLASS_CANAL) {
2548 Company::Get(st->owner)->infrastructure.water++;
2549 }
2550 Company::Get(st->owner)->infrastructure.station += 2;
2551 DirtyCompanyInfrastructureWindows(st->owner);
2552
2553 MakeDock(tile, st->owner, st->index, direction, wc);
2554
2555 st->UpdateVirtCoord();
2556 UpdateStationAcceptance(st, false);
2557 st->RecomputeIndustriesNear();
2558 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2559 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2560 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2561 }
2562
2563 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2564 }
2565
2572 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2573 {
2574 Station *st = Station::GetByTile(tile);
2575 CommandCost ret = CheckOwnership(st->owner);
2576 if (ret.Failed()) return ret;
2577
2578 TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
2579
2580 TileIndex tile1 = st->dock_tile;
2581 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2582
2583 ret = EnsureNoVehicleOnGround(tile1);
2584 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2585 if (ret.Failed()) return ret;
2586
2587 if (flags & DC_EXEC) {
2588 DoClearSquare(tile1);
2589 MarkTileDirtyByTile(tile1);
2590 MakeWaterKeepingClass(tile2, st->owner);
2591
2592 st->rect.AfterRemoveTile(st, tile1);
2593 st->rect.AfterRemoveTile(st, tile2);
2594
2595 st->dock_tile = INVALID_TILE;
2596 st->facilities &= ~FACIL_DOCK;
2597
2598 Company::Get(st->owner)->infrastructure.station -= 2;
2599 DirtyCompanyInfrastructureWindows(st->owner);
2600
2601 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2602 st->UpdateVirtCoord();
2603 st->RecomputeIndustriesNear();
2604 DeleteStationIfEmpty(st);
2605
2606 /* All ships that were going to our station, can't go to it anymore.
2607 * Just clear the order, then automatically the next appropriate order
2608 * will be selected and in case of no appropriate order it will just
2609 * wander around the world. */
2610 Ship *s;
2611 FOR_ALL_SHIPS(s) {
2612 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2613 s->LeaveStation();
2614 }
2615
2616 if (s->dest_tile == docking_location) {
2617 s->dest_tile = 0;
2618 s->current_order.Free();
2619 }
2620 }
2621 }
2622
2623 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2624 }
2625
2626 #include "table/station_land.h"
2627
2628 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2629 {
2630 return &_station_display_datas[st][gfx];
2631 }
2632
2642 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2643 {
2644 bool snow_desert;
2645 switch (*ground) {
2646 case SPR_RAIL_TRACK_X:
2647 snow_desert = false;
2648 *overlay_offset = RTO_X;
2649 break;
2650
2651 case SPR_RAIL_TRACK_Y:
2652 snow_desert = false;
2653 *overlay_offset = RTO_Y;
2654 break;
2655
2656 case SPR_RAIL_TRACK_X_SNOW:
2657 snow_desert = true;
2658 *overlay_offset = RTO_X;
2659 break;
2660
2661 case SPR_RAIL_TRACK_Y_SNOW:
2662 snow_desert = true;
2663 *overlay_offset = RTO_Y;
2664 break;
2665
2666 default:
2667 return false;
2668 }
2669
2670 if (ti != NULL) {
2671 /* Decide snow/desert from tile */
2672 switch (_settings_game.game_creation.landscape) {
2673 case LT_ARCTIC:
2674 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2675 break;
2676
2677 case LT_TROPIC:
2678 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2679 break;
2680
2681 default:
2682 break;
2683 }
2684 }
2685
2686 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2687 return true;
2688 }
2689
2690 static void DrawTile_Station(TileInfo *ti)
2691 {
2692 const NewGRFSpriteLayout *layout = NULL;
2693 DrawTileSprites tmp_rail_layout;
2694 const DrawTileSprites *t = NULL;
2695 RoadTypes roadtypes;
2696 int32 total_offset;
2697 const RailtypeInfo *rti = NULL;
2698 uint32 relocation = 0;
2699 uint32 ground_relocation = 0;
2700 BaseStation *st = NULL;
2701 const StationSpec *statspec = NULL;
2702 uint tile_layout = 0;
2703
2704 if (HasStationRail(ti->tile)) {
2705 rti = GetRailTypeInfo(GetRailType(ti->tile));
2706 roadtypes = ROADTYPES_NONE;
2707 total_offset = rti->GetRailtypeSpriteOffset();
2708
2709 if (IsCustomStationSpecIndex(ti->tile)) {
2710 /* look for customization */
2711 st = BaseStation::GetByTile(ti->tile);
2712 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2713
2714 if (statspec != NULL) {
2715 tile_layout = GetStationGfx(ti->tile);
2716
2717 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2718 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2719 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2720 }
2721
2722 /* Ensure the chosen tile layout is valid for this custom station */
2723 if (statspec->renderdata != NULL) {
2724 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2725 if (!layout->NeedsPreprocessing()) {
2726 t = layout;
2727 layout = NULL;
2728 }
2729 }
2730 }
2731 }
2732 } else {
2733 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
2734 total_offset = 0;
2735 }
2736
2737 StationGfx gfx = GetStationGfx(ti->tile);
2738 if (IsAirport(ti->tile)) {
2739 gfx = GetAirportGfx(ti->tile);
2740 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2741 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2742 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2743 return;
2744 }
2745 /* No sprite group (or no valid one) found, meaning no graphics associated.
2746 * Use the substitute one instead */
2747 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2748 gfx = ats->grf_prop.subst_id;
2749 }
2750 switch (gfx) {
2751 case APT_RADAR_GRASS_FENCE_SW:
2752 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2753 break;
2754 case APT_GRASS_FENCE_NE_FLAG:
2755 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2756 break;
2757 case APT_RADAR_FENCE_SW:
2758 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2759 break;
2760 case APT_RADAR_FENCE_NE:
2761 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2762 break;
2763 case APT_GRASS_FENCE_NE_FLAG_2:
2764 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2765 break;
2766 }
2767 }
2768
2769 Owner owner = GetTileOwner(ti->tile);
2770
2771 PaletteID palette;
2772 if (Company::IsValidID(owner)) {
2773 palette = COMPANY_SPRITE_COLOUR(owner);
2774 } else {
2775 /* Some stations are not owner by a company, namely oil rigs */
2776 palette = PALETTE_TO_GREY;
2777 }
2778
2779 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2780
2781 /* don't show foundation for docks */
2782 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2783 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2784 /* Station has custom foundations.
2785 * Check whether the foundation continues beyond the tile's upper sides. */
2786 uint edge_info = 0;
2787 int z;
2788 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2789 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2790 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2791 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2792 if (image == 0) goto draw_default_foundation;
2793
2794 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2795 /* Station provides extended foundations. */
2796
2797 static const uint8 foundation_parts[] = {
2798 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2799 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2800 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2801 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2802 };
2803
2804 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2805 } else {
2806 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2807
2808 /* Each set bit represents one of the eight composite sprites to be drawn.
2809 * 'Invalid' entries will not drawn but are included for completeness. */
2810 static const uint8 composite_foundation_parts[] = {
2811 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2812 0x00, 0xD1, 0xE4, 0xE0,
2813 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2814 0xCA, 0xC9, 0xC4, 0xC0,
2815 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2816 0xD2, 0x91, 0xE4, 0xA0,
2817 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2818 0x4A, 0x09, 0x44
2819 };
2820
2821 uint8 parts = composite_foundation_parts[ti->tileh];
2822
2823 /* If foundations continue beyond the tile's upper sides then
2824 * mask out the last two pieces. */
2825 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2826 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2827
2828 if (parts == 0) {
2829 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2830 * correct offset for the childsprites.
2831 * So, draw the (completely empty) sprite of the default foundations. */
2832 goto draw_default_foundation;
2833 }
2834
2835 StartSpriteCombine();
2836 for (int i = 0; i < 8; i++) {
2837 if (HasBit(parts, i)) {
2838 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2839 }
2840 }
2841 EndSpriteCombine();
2842 }
2843
2844 OffsetGroundSprite(31, 1);
2845 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2846 } else {
2847 draw_default_foundation:
2848 DrawFoundation(ti, FOUNDATION_LEVELED);
2849 }
2850 }
2851
2852 if (IsBuoy(ti->tile)) {
2853 DrawWaterClassGround(ti);
2854 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2855 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2856 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2857 if (ti->tileh == SLOPE_FLAT) {
2858 DrawWaterClassGround(ti);
2859 } else {
2860 assert(IsDock(ti->tile));
2861 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2862 WaterClass wc = GetWaterClass(water_tile);
2863 if (wc == WATER_CLASS_SEA) {
2864 DrawShoreTile(ti->tileh);
2865 } else {
2866 DrawClearLandTile(ti, 3);
2867 }
2868 }
2869 } else {
2870 if (layout != NULL) {
2871 /* Sprite layout which needs preprocessing */
2872 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2873 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2874 uint8 var10;
2875 FOR_EACH_SET_BIT(var10, var10_values) {
2876 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2877 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2878 }
2879 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2880 t = &tmp_rail_layout;
2881 total_offset = 0;
2882 } else if (statspec != NULL) {
2883 /* Simple sprite layout */
2884 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2885 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2886 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2887 }
2888 ground_relocation += rti->fallback_railtype;
2889 }
2890
2891 SpriteID image = t->ground.sprite;
2892 PaletteID pal = t->ground.pal;
2893 RailTrackOffset overlay_offset;
2894 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2895 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2896 DrawGroundSprite(image, PAL_NONE);
2897 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2898
2899 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2900 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2901 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2902 }
2903 } else {
2904 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2905 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2906 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2907
2908 /* PBS debugging, draw reserved tracks darker */
2909 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2910 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2911 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
2912 }
2913 }
2914 }
2915
2916 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2917
2918 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2919 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
2920 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2921 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
2922 }
2923
2924 if (IsRailWaypoint(ti->tile)) {
2925 /* Don't offset the waypoint graphics; they're always the same. */
2926 total_offset = 0;
2927 }
2928
2929 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
2930 }
2931
2932 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
2933 {
2934 int32 total_offset = 0;
2935 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
2936 const DrawTileSprites *t = GetStationTileLayout(st, image);
2937 const RailtypeInfo *rti = NULL;
2938
2939 if (railtype != INVALID_RAILTYPE) {
2940 rti = GetRailTypeInfo(railtype);
2941 total_offset = rti->GetRailtypeSpriteOffset();
2942 }
2943
2944 SpriteID img = t->ground.sprite;
2945 RailTrackOffset overlay_offset;
2946 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
2947 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2948 DrawSprite(img, PAL_NONE, x, y);
2949 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
2950 } else {
2951 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
2952 }
2953
2954 if (roadtype == ROADTYPE_TRAM) {
2955 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
2956 }
2957
2958 /* Default waypoint has no railtype specific sprites */
2959 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
2960 }
2961
2962 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
2963 {
2964 return GetTileMaxPixelZ(tile);
2965 }
2966
2967 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
2968 {
2969 return FlatteningFoundation(tileh);
2970 }
2971
2972 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
2973 {
2974 td->owner[0] = GetTileOwner(tile);
2975 if (IsDriveThroughStopTile(tile)) {
2976 Owner road_owner = INVALID_OWNER;
2977 Owner tram_owner = INVALID_OWNER;
2978 RoadTypes rts = GetRoadTypes(tile);
2979 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
2980 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
2981
2982 /* Is there a mix of owners? */
2983 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
2984 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
2985 uint i = 1;
2986 if (road_owner != INVALID_OWNER) {
2987 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
2988 td->owner[i] = road_owner;
2989 i++;
2990 }
2991 if (tram_owner != INVALID_OWNER) {
2992 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
2993 td->owner[i] = tram_owner;
2994 }
2995 }
2996 }
2997 td->build_date = BaseStation::GetByTile(tile)->build_date;
2998
2999 if (HasStationTileRail(tile)) {
3000 const StationSpec *spec = GetStationSpec(tile);
3001
3002 if (spec != NULL) {
3003 td->station_class = StationClass::Get(spec->cls_id)->name;
3004 td->station_name = spec->name;
3005
3006 if (spec->grf_prop.grffile != NULL) {
3007 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3008 td->grf = gc->GetName();
3009 }
3010 }
3011
3012 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3013 td->rail_speed = rti->max_speed;
3014 }
3015
3016 if (IsAirport(tile)) {
3017 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3018 td->airport_class = AirportClass::Get(as->cls_id)->name;
3019 td->airport_name = as->name;
3020
3021 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3022 td->airport_tile_name = ats->name;
3023
3024 if (as->grf_prop.grffile != NULL) {
3025 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3026 td->grf = gc->GetName();
3027 } else if (ats->grf_prop.grffile != NULL) {
3028 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3029 td->grf = gc->GetName();
3030 }
3031 }
3032
3033 StringID str;
3034 switch (GetStationType(tile)) {
3035 default: NOT_REACHED();
3036 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3037 case STATION_AIRPORT:
3038 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3039 break;
3040 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3041 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3042 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3043 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3044 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3045 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3046 }
3047 td->str = str;
3048 }
3049
3050
3051 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3052 {
3053 TrackBits trackbits = TRACK_BIT_NONE;
3054
3055 switch (mode) {
3056 case TRANSPORT_RAIL:
3057 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3058 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3059 }
3060 break;
3061
3062 case TRANSPORT_WATER:
3063 /* buoy is coded as a station, it is always on open water */
3064 if (IsBuoy(tile)) {
3065 trackbits = TRACK_BIT_ALL;
3066 /* remove tracks that connect NE map edge */
3067 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3068 /* remove tracks that connect NW map edge */
3069 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3070 }
3071 break;
3072
3073 case TRANSPORT_ROAD:
3074 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
3075 DiagDirection dir = GetRoadStopDir(tile);
3076 Axis axis = DiagDirToAxis(dir);
3077
3078 if (side != INVALID_DIAGDIR) {
3079 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
3080 }
3081
3082 trackbits = AxisToTrackBits(axis);
3083 }
3084 break;
3085
3086 default:
3087 break;
3088 }
3089
3090 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3091 }
3092
3093
3094 static void TileLoop_Station(TileIndex tile)
3095 {
3096 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3097 * hardcoded.....not good */
3098 switch (GetStationType(tile)) {
3099 case STATION_AIRPORT:
3100 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3101 break;
3102
3103 case STATION_DOCK:
3104 if (!IsTileFlat(tile)) break; // only handle water part
3105 /* FALL THROUGH */
3106 case STATION_OILRIG: //(station part)
3107 case STATION_BUOY:
3108 TileLoop_Water(tile);
3109 break;
3110
3111 default: break;
3112 }
3113 }
3114
3115
3116 static void AnimateTile_Station(TileIndex tile)
3117 {
3118 if (HasStationRail(tile)) {
3119 AnimateStationTile(tile);
3120 return;
3121 }
3122
3123 if (IsAirport(tile)) {
3124 AnimateAirportTile(tile);
3125 }
3126 }
3127
3128
3129 static bool ClickTile_Station(TileIndex tile)
3130 {
3131 const BaseStation *bst = BaseStation::GetByTile(tile);
3132
3133 if (bst->facilities & FACIL_WAYPOINT) {
3134 ShowWaypointWindow(Waypoint::From(bst));
3135 } else if (IsHangar(tile)) {
3136 const Station *st = Station::From(bst);
3137 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3138 } else {
3139 ShowStationViewWindow(bst->index);
3140 }
3141 return true;
3142 }
3143
3144 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3145 {
3146 if (v->type == VEH_TRAIN) {
3147 StationID station_id = GetStationIndex(tile);
3148 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3149 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3150
3151 int station_ahead;
3152 int station_length;
3153 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3154
3155 /* Stop whenever that amount of station ahead + the distance from the
3156 * begin of the platform to the stop location is longer than the length
3157 * of the platform. Station ahead 'includes' the current tile where the
3158 * vehicle is on, so we need to subtract that. */
3159 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3160
3161 DiagDirection dir = DirToDiagDir(v->direction);
3162
3163 x &= 0xF;
3164 y &= 0xF;
3165
3166 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3167 if (y == TILE_SIZE / 2) {
3168 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3169 stop &= TILE_SIZE - 1;
3170
3171 if (x == stop) {
3172 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3173 } else if (x < stop) {
3174 v->vehstatus |= VS_TRAIN_SLOWING;
3175 uint16 spd = max(0, (stop - x) * 20 - 15);
3176 if (spd < v->cur_speed) v->cur_speed = spd;
3177 }
3178 }
3179 } else if (v->type == VEH_ROAD) {
3180 RoadVehicle *rv = RoadVehicle::From(v);
3181 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3182 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3183 /* Attempt to allocate a parking bay in a road stop */
3184 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3185 }
3186 }
3187 }
3188
3189 return VETSB_CONTINUE;
3190 }
3191
3196 void TriggerWatchedCargoCallbacks(Station *st)
3197 {
3198 /* Collect cargoes accepted since the last big tick. */
3199 uint cargoes = 0;
3200 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3201 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3202 }
3203
3204 /* Anything to do? */
3205 if (cargoes == 0) return;
3206
3207 /* Loop over all houses in the catchment. */
3208 Rect r = st->GetCatchmentRect();
3209 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
3210 TILE_AREA_LOOP(tile, ta) {
3211 if (IsTileType(tile, MP_HOUSE)) {
3212 WatchedCargoCallback(tile, cargoes);
3213 }
3214 }
3215 }
3216
3223 static bool StationHandleBigTick(BaseStation *st)
3224 {
3225 if (!st->IsInUse()) {
3226 if (++st->delete_ctr >= 8) delete st;
3227 return false;
3228 }
3229
3230 if (Station::IsExpected(st)) {
3231 TriggerWatchedCargoCallbacks(Station::From(st));
3232
3233 for (CargoID i = 0; i < NUM_CARGO; i++) {
3234 ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3235 }
3236 }
3237
3238
3239 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3240
3241 return true;
3242 }
3243
3244 static inline void byte_inc_sat(byte *p)
3245 {
3246 byte b = *p + 1;
3247 if (b != 0) *p = b;
3248 }
3249
3256 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3257 {
3258 /* If truncating also punish the source stations' ratings to
3259 * decrease the flow of incoming cargo. */
3260
3261 StationCargoAmountMap waiting_per_source;
3262 ge->cargo.Truncate(amount, &waiting_per_source);
3263 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3264 Station *source_station = Station::GetIfValid(i->first);
3265 if (source_station == NULL) continue;
3266
3267 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3268 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3269 }
3270 }
3271
3272 static void UpdateStationRating(Station *st)
3273 {
3274 bool waiting_changed = false;
3275
3276 byte_inc_sat(&st->time_since_load);
3277 byte_inc_sat(&st->time_since_unload);
3278
3279 const CargoSpec *cs;
3280 FOR_ALL_CARGOSPECS(cs) {
3281 GoodsEntry *ge = &st->goods[cs->Index()];
3282 /* Slowly increase the rating back to his original level in the case we
3283 * didn't deliver cargo yet to this station. This happens when a bribe
3284 * failed while you didn't moved that cargo yet to a station. */
3285 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3286 ge->rating++;
3287 }
3288
3289 /* Only change the rating if we are moving this cargo */
3290 if (ge->HasRating()) {
3291 byte_inc_sat(&ge->time_since_pickup);
3292 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3293 ClrBit(ge->status, GoodsEntry::GES_RATING);
3294 ge->last_speed = 0;
3295 TruncateCargo(cs, ge);
3296 waiting_changed = true;
3297 continue;
3298 }
3299
3300 bool skip = false;
3301 int rating = 0;
3302 uint waiting = ge->cargo.TotalCount();
3303
3304 /* num_dests is at least 1 if there is any cargo as
3305 * INVALID_STATION is also a destination.
3306 */
3307 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3308
3309 /* Average amount of cargo per next hop, but prefer solitary stations
3310 * with only one or two next hops. They are allowed to have more
3311 * cargo waiting per next hop.
3312 * With manual cargo distribution waiting_avg = waiting / 2 as then
3313 * INVALID_STATION is the only destination.
3314 */
3315 uint waiting_avg = waiting / (num_dests + 1);
3316
3317 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3318 /* Perform custom station rating. If it succeeds the speed, days in transit and
3319 * waiting cargo ratings must not be executed. */
3320
3321 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3322 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3323
3324 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3325 /* Convert to the 'old' vehicle types */
3326 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3327 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3328 if (callback != CALLBACK_FAILED) {
3329 skip = true;
3330 rating = GB(callback, 0, 14);
3331
3332 /* Simulate a 15 bit signed value */
3333 if (HasBit(callback, 14)) rating -= 0x4000;
3334 }
3335 }
3336
3337 if (!skip) {
3338 int b = ge->last_speed - 85;
3339 if (b >= 0) rating += b >> 2;
3340
3341 byte waittime = ge->time_since_pickup;
3342 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3343 (waittime > 21) ||
3344 (rating += 25, waittime > 12) ||
3345 (rating += 25, waittime > 6) ||
3346 (rating += 45, waittime > 3) ||
3347 (rating += 35, true);
3348
3349 (rating -= 90, ge->max_waiting_cargo > 1500) ||
3350 (rating += 55, ge->max_waiting_cargo > 1000) ||
3351 (rating += 35, ge->max_waiting_cargo > 600) ||
3352 (rating += 10, ge->max_waiting_cargo > 300) ||
3353 (rating += 20, ge->max_waiting_cargo > 100) ||
3354 (rating += 10, true);
3355 }
3356
3357 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3358
3359 byte age = ge->last_age;
3360 (age >= 3) ||
3361 (rating += 10, age >= 2) ||
3362 (rating += 10, age >= 1) ||
3363 (rating += 13, true);
3364
3365 {
3366 int or_ = ge->rating; // old rating
3367
3368 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3369 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3370
3371 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3372 * remove some random amount of goods from the station */
3373 if (rating <= 64 && waiting_avg >= 100) {
3374 int dec = Random() & 0x1F;
3375 if (waiting_avg < 200) dec &= 7;
3376 waiting -= (dec + 1) * num_dests;
3377 waiting_changed = true;
3378 }
3379
3380 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3381 if (rating <= 127 && waiting != 0) {
3382 uint32 r = Random();
3383 if (rating <= (int)GB(r, 0, 7)) {
3384 /* Need to have int, otherwise it will just overflow etc. */
3385 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3386 waiting_changed = true;
3387 }
3388 }
3389
3390 /* At some point we really must cap the cargo. Previously this
3391 * was a strict 4095, but now we'll have a less strict, but
3392 * increasingly aggressive truncation of the amount of cargo. */
3393 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3394 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3395 static const uint MAX_WAITING_CARGO = 1 << 15;
3396
3397 if (waiting > WAITING_CARGO_THRESHOLD) {
3398 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3399 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3400
3401 waiting = min(waiting, MAX_WAITING_CARGO);
3402 waiting_changed = true;
3403 }
3404
3405 /* We can't truncate cargo that's already reserved for loading.
3406 * Thus StoredCount() here. */
3407 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3408 /* Feed back the exact own waiting cargo at this station for the
3409 * next rating calculation. */
3410 ge->max_waiting_cargo = 0;
3411
3412 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3413 } else {
3414 /* If the average number per next hop is low, be more forgiving. */
3415 ge->max_waiting_cargo = waiting_avg;
3416 }
3417 }
3418 }
3419 }
3420
3421 StationID index = st->index;
3422 if (waiting_changed) {
3423 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3424 } else {
3425 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3426 }
3427 }
3428
3437 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3438 {
3439 GoodsEntry &ge = st->goods[c];
3440
3441 /* Reroute cargo in station. */
3442 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3443
3444 /* Reroute cargo staged to be transfered. */
3445 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3446 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3447 if (v->cargo_type != c) continue;
3448 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3449 }
3450 }
3451 }
3452
3461 void DeleteStaleLinks(Station *from)
3462 {
3463 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3464 GoodsEntry &ge = from->goods[c];
3465 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3466 if (lg == NULL) continue;
3467 Node node = (*lg)[ge.node];
3468 for (EdgeIterator it(node.Begin()); it != node.End();) {
3469 Edge edge = it->second;
3470 Station *to = Station::Get((*lg)[it->first].Station());
3471 assert(to->goods[c].node == it->first);
3472 ++it; // Do that before removing the edge. Anything else may crash.
3473 assert(_date >= edge.LastUpdate());
3474 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3475 if ((uint)(_date - edge.LastUpdate()) > timeout) {
3476 /* Have all vehicles refresh their next hops before deciding to
3477 * remove the node. */
3478 bool updated = false;
3479 OrderList *l;
3480 FOR_ALL_ORDER_LISTS(l) {
3481 bool found_from = false;
3482 bool found_to = false;
3483 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3484 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3485 if (order->GetDestination() == from->index) {
3486 found_from = true;
3487 if (found_to) break;
3488 } else if (order->GetDestination() == to->index) {
3489 found_to = true;
3490 if (found_from) break;
3491 }
3492 }
3493 if (!found_to || !found_from) continue;
3494 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
3495 /* There is potential for optimization here:
3496 * - Usually consists of the same order list are the same. It's probably better to
3497 * first check the first of each list, then the second of each list and so on.
3498 * - We could try to figure out if we've seen a consist with the same cargo on the
3499 * same list already and if the consist can actually carry the cargo we're looking
3500 * for. With conditional and refit orders this is not quite trivial, though. */
3501 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3502 if (edge.LastUpdate() == _date) updated = true;
3503 }
3504 if (updated) break;
3505 }
3506 if (!updated) {
3507 /* If it's still considered dead remove it. */
3508 node.RemoveEdge(to->goods[c].node);
3509 ge.flows.DeleteFlows(to->index);
3510 RerouteCargo(from, c, to->index, from->index);
3511 }
3512 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3513 edge.Restrict();
3514 ge.flows.RestrictFlows(to->index);
3515 RerouteCargo(from, c, to->index, from->index);
3516 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3517 edge.Release();
3518 }
3519 }
3520 assert(_date >= lg->LastCompression());
3521 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3522 lg->Compress();
3523 }
3524 }
3525 }
3526
3536 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
3537 {
3538 GoodsEntry &ge1 = st->goods[cargo];
3539 Station *st2 = Station::Get(next_station_id);
3540 GoodsEntry &ge2 = st2->goods[cargo];
3541 LinkGraph *lg = NULL;
3542 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3543 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3544 if (LinkGraph::CanAllocateItem()) {
3545 lg = new LinkGraph(cargo);
3546 LinkGraphSchedule::instance.Queue(lg);
3547 ge2.link_graph = lg->index;
3548 ge2.node = lg->AddNode(st2);
3549 } else {
3550 DEBUG(misc, 0, "Can't allocate link graph");
3551 }
3552 } else {
3553 lg = LinkGraph::Get(ge2.link_graph);
3554 }
3555 if (lg) {
3556 ge1.link_graph = lg->index;
3557 ge1.node = lg->AddNode(st);
3558 }
3559 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3560 lg = LinkGraph::Get(ge1.link_graph);
3561 ge2.link_graph = lg->index;
3562 ge2.node = lg->AddNode(st2);
3563 } else {
3564 lg = LinkGraph::Get(ge1.link_graph);
3565 if (ge1.link_graph != ge2.link_graph) {
3566 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3567 if (lg->Size() < lg2->Size()) {
3568 LinkGraphSchedule::instance.Unqueue(lg);
3569 lg2->Merge(lg); // Updates GoodsEntries of lg
3570 lg = lg2;
3571 } else {
3572 LinkGraphSchedule::instance.Unqueue(lg2);
3573 lg->Merge(lg2); // Updates GoodsEntries of lg2
3574 }
3575 }
3576 }
3577 if (lg != NULL) {
3578 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, mode);
3579 }
3580 }
3581
3588 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3589 {
3590 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3591 if (v->refit_cap > 0) {
3592 /* The cargo count can indeed be higher than the refit_cap if
3593 * wagons have been auto-replaced and subsequently auto-
3594 * refitted to a higher capacity. The cargo gets redistributed
3595 * among the wagons in that case.
3596 * As usage is not such an important figure anyway we just
3597 * ignore the additional cargo then.*/
3598 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3599 min(v->refit_cap, v->cargo.StoredCount()), EUM_INCREASE);
3600 }
3601 }
3602 }
3603
3604 /* called for every station each tick */
3605 static void StationHandleSmallTick(BaseStation *st)
3606 {
3607 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3608
3609 byte b = st->delete_ctr + 1;
3610 if (b >= STATION_RATING_TICKS) b = 0;
3611 st->delete_ctr = b;
3612
3613 if (b == 0) UpdateStationRating(Station::From(st));
3614 }
3615
3616 void OnTick_Station()
3617 {
3618 if (_game_mode == GM_EDITOR) return;
3619
3620 BaseStation *st;
3621 FOR_ALL_BASE_STATIONS(st) {
3622 StationHandleSmallTick(st);
3623
3624 /* Clean up the link graph about once a week. */
3625 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3626 DeleteStaleLinks(Station::From(st));
3627 };
3628
3629 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3630 * Station index is included so that triggers are not all done
3631 * at the same time. */
3632 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3633 /* Stop processing this station if it was deleted */
3634 if (!StationHandleBigTick(st)) continue;
3635 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3636 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3637 }
3638 }
3639 }
3640
3642 void StationMonthlyLoop()
3643 {
3644 Station *st;
3645
3646 FOR_ALL_STATIONS(st) {
3647 for (CargoID i = 0; i < NUM_CARGO; i++) {
3648 GoodsEntry *ge = &st->goods[i];
3649 SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3650 ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3651 }
3652 }
3653 }
3654
3655
3656 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3657 {
3658 Station *st;
3659
3660 FOR_ALL_STATIONS(st) {
3661 if (st->owner == owner &&
3662 DistanceManhattan(tile, st->xy) <= radius) {
3663 for (CargoID i = 0; i < NUM_CARGO; i++) {
3664 GoodsEntry *ge = &st->goods[i];
3665
3666 if (ge->status != 0) {
3667 ge->rating = Clamp(ge->rating + amount, 0, 255);
3668 }
3669 }
3670 }
3671 }
3672 }
3673
3674 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3675 {
3676 /* We can't allocate a CargoPacket? Then don't do anything
3677 * at all; i.e. just discard the incoming cargo. */
3678 if (!CargoPacket::CanAllocateItem()) return 0;
3679
3680 GoodsEntry &ge = st->goods[type];
3681 amount += ge.amount_fract;
3682 ge.amount_fract = GB(amount, 0, 8);
3683
3684 amount >>= 8;
3685 /* No new "real" cargo item yet. */
3686 if (amount == 0) return 0;
3687
3688 StationID next = ge.GetVia(st->index);
3689 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3690 LinkGraph *lg = NULL;
3691 if (ge.link_graph == INVALID_LINK_GRAPH) {
3692 if (LinkGraph::CanAllocateItem()) {
3693 lg = new LinkGraph(type);
3694 LinkGraphSchedule::instance.Queue(lg);
3695 ge.link_graph = lg->index;
3696 ge.node = lg->AddNode(st);
3697 } else {
3698 DEBUG(misc, 0, "Can't allocate link graph");
3699 }
3700 } else {
3701 lg = LinkGraph::Get(ge.link_graph);
3702 }
3703 if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
3704
3705 if (!ge.HasRating()) {
3706 InvalidateWindowData(WC_STATION_LIST, st->index);
3707 SetBit(ge.status, GoodsEntry::GES_RATING);
3708 }
3709
3710 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3711 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3712 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3713
3714 SetWindowDirty(WC_STATION_VIEW, st->index);
3715 st->MarkTilesDirty(true);
3716 return amount;
3717 }
3718
3719 static bool IsUniqueStationName(const char *name)
3720 {
3721 const Station *st;
3722
3723 FOR_ALL_STATIONS(st) {
3724 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3725 }
3726
3727 return true;
3728 }
3729
3739 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3740 {
3741 Station *st = Station::GetIfValid(p1);
3742 if (st == NULL) return CMD_ERROR;
3743
3744 CommandCost ret = CheckOwnership(st->owner);
3745 if (ret.Failed()) return ret;
3746
3747 bool reset = StrEmpty(text);
3748
3749 if (!reset) {
3750 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3751 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3752 }
3753
3754 if (flags & DC_EXEC) {
3755 free(st->name);
3756 st->name = reset ? NULL : stredup(text);
3757
3758 st->UpdateVirtCoord();
3759 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3760 }
3761
3762 return CommandCost();
3763 }
3764
3771 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3772 {
3773 /* area to search = producer plus station catchment radius */
3774 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
3775
3776 uint x = TileX(location.tile);
3777 uint y = TileY(location.tile);
3778
3779 uint min_x = (x > max_rad) ? x - max_rad : 0;
3780 uint max_x = x + location.w + max_rad;
3781 uint min_y = (y > max_rad) ? y - max_rad : 0;
3782 uint max_y = y + location.h + max_rad;
3783
3784 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3785 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3786 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3787 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3788
3789 for (uint cy = min_y; cy < max_y; cy++) {
3790 for (uint cx = min_x; cx < max_x; cx++) {
3791 TileIndex cur_tile = TileXY(cx, cy);
3792 if (!IsTileType(cur_tile, MP_STATION)) continue;
3793
3794 Station *st = Station::GetByTile(cur_tile);
3795 /* st can be NULL in case of waypoints */
3796 if (st == NULL) continue;
3797
3798 if (_settings_game.station.modified_catchment) {
3799 int rad = st->GetCatchmentRadius();
3800 int rad_x = cx - x;
3801 int rad_y = cy - y;
3802
3803 if (rad_x < -rad || rad_x >= rad + location.w) continue;
3804 if (rad_y < -rad || rad_y >= rad + location.h) continue;
3805 }
3806
3807 /* Insert the station in the set. This will fail if it has
3808 * already been added.
3809 */
3810 stations->Include(st);
3811 }
3812 }
3813 }
3814
3819 const StationList *StationFinder::GetStations()
3820 {
3821 if (this->tile != INVALID_TILE) {
3822 FindStationsAroundTiles(*this, &this->stations);
3823 this->tile = INVALID_TILE;
3824 }
3825 return &this->stations;
3826 }
3827
3828 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3829 {
3830 /* Return if nothing to do. Also the rounding below fails for 0. */
3831 if (amount == 0) return 0;
3832
3833 Station *st1 = NULL; // Station with best rating
3834 Station *st2 = NULL; // Second best station
3835 uint best_rating1 = 0; // rating of st1
3836 uint best_rating2 = 0; // rating of st2
3837
3838 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3839 Station *st = *st_iter;
3840
3841 /* Is the station reserved exclusively for somebody else? */
3842 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3843
3844 if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3845
3846 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3847
3848 if (IsCargoInClass(type, CC_PASSENGERS)) {
3849 if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
3850 } else {
3851 if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
3852 }
3853
3854 /* This station can be used, add it to st1/st2 */
3855 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3856 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3857 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3858 st2 = st; best_rating2 = st->goods[type].rating;
3859 }
3860 }
3861
3862 /* no stations around at all? */
3863 if (st1 == NULL) return 0;
3864
3865 /* From now we'll calculate with fractal cargo amounts.
3866 * First determine how much cargo we really have. */
3867 amount *= best_rating1 + 1;
3868
3869 if (st2 == NULL) {
3870 /* only one station around */
3871 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3872 }
3873
3874 /* several stations around, the best two (highest rating) are in st1 and st2 */
3875 assert(st1 != NULL);
3876 assert(st2 != NULL);
3877 assert(best_rating1 != 0 || best_rating2 != 0);
3878
3879 /* Then determine the amount the worst station gets. We do it this way as the
3880 * best should get a bonus, which in this case is the rounding difference from
3881 * this calculation. In reality that will mean the bonus will be pretty low.
3882 * Nevertheless, the best station should always get the most cargo regardless
3883 * of rounding issues. */
3884 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3885 assert(worst_cargo <= (amount - worst_cargo));
3886
3887 /* And then send the cargo to the stations! */
3888 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3889 /* These two UpdateStationWaiting's can't be in the statement as then the order
3890 * of execution would be undefined and that could cause desyncs with callbacks. */
3891 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3892 }
3893
3894 void BuildOilRig(TileIndex tile)
3895 {
3896 if (!Station::CanAllocateItem()) {
3897 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3898 return;
3899 }
3900
3901 Station *st = new Station(tile);
3902 st->town = ClosestTownFromTile(tile, UINT_MAX);
3903
3904 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3905
3906 assert(IsTileType(tile, MP_INDUSTRY));
3907 DeleteAnimatedTile(tile);
3908 MakeOilrig(tile, st->index, GetWaterClass(tile));
3909
3910 st->owner = OWNER_NONE;
3911 st->airport.type = AT_OILRIG;
3912 st->airport.Add(tile);
3913 st->dock_tile = tile;
3914 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
3915 st->build_date = _date;
3916
3917 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
3918
3919 st->UpdateVirtCoord();
3920 UpdateStationAcceptance(st, false);
3921 st->RecomputeIndustriesNear();
3922 }
3923
3924 void DeleteOilRig(TileIndex tile)
3925 {
3926 Station *st = Station::GetByTile(tile);
3927
3928 MakeWaterKeepingClass(tile, OWNER_NONE);
3929
3930 st->dock_tile = INVALID_TILE;
3931 st->airport.Clear();
3932 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
3933 st->airport.flags = 0;
3934
3935 st->rect.AfterRemoveTile(st, tile);
3936
3937 st->UpdateVirtCoord();
3938 st->RecomputeIndustriesNear();
3939 if (!st->IsInUse()) delete st;
3940 }
3941
3942 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
3943 {
3944 if (IsRoadStopTile(tile)) {
3945 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
3946 /* Update all roadtypes, no matter if they are present */
3947 if (GetRoadOwner(tile, rt) == old_owner) {
3948 if (HasTileRoadType(tile, rt)) {
3949 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3950 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
3951 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
3952 }
3953 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
3954 }
3955 }
3956 }
3957
3958 if (!IsTileOwner(tile, old_owner)) return;
3959
3960 if (new_owner != INVALID_OWNER) {
3961 /* Update company infrastructure counts. Only do it here
3962 * if the new owner is valid as otherwise the clear
3963 * command will do it for us. No need to dirty windows
3964 * here, we'll redraw the whole screen anyway.*/
3965 Company *old_company = Company::Get(old_owner);
3966 Company *new_company = Company::Get(new_owner);
3967
3968 /* Update counts for underlying infrastructure. */
3969 switch (GetStationType(tile)) {
3970 case STATION_RAIL:
3971 case STATION_WAYPOINT:
3972 if (!IsStationTileBlocked(tile)) {
3973 old_company->infrastructure.rail[GetRailType(tile)]--;
3974 new_company->infrastructure.rail[GetRailType(tile)]++;
3975 }
3976 break;
3977
3978 case STATION_BUS:
3979 case STATION_TRUCK:
3980 /* Road stops were already handled above. */
3981 break;
3982
3983 case STATION_BUOY:
3984 case STATION_DOCK:
3985 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
3986 old_company->infrastructure.water--;
3987 new_company->infrastructure.water++;
3988 }
3989 break;
3990
3991 default:
3992 break;
3993 }
3994
3995 /* Update station tile count. */
3996 if (!IsBuoy(tile) && !IsAirport(tile)) {
3997 old_company->infrastructure.station--;
3998 new_company->infrastructure.station++;
3999 }
4000
4001 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4002 SetTileOwner(tile, new_owner);
4003 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4004 } else {
4005 if (IsDriveThroughStopTile(tile)) {
4006 /* Remove the drive-through road stop */
4007 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
4008 assert(IsTileType(tile, MP_ROAD));
4009 /* Change owner of tile and all roadtypes */
4010 ChangeTileOwner(tile, old_owner, new_owner);
4011 } else {
4012 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
4013 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4014 * Update owner of buoy if it was not removed (was in orders).
4015 * Do not update when owned by OWNER_WATER (sea and rivers). */
4016 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4017 }
4018 }
4019 }
4020
4029 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4030 {
4031 /* Yeah... water can always remove stops, right? */
4032 if (_current_company == OWNER_WATER) return true;
4033
4034 RoadTypes rts = GetRoadTypes(tile);
4035 if (HasBit(rts, ROADTYPE_TRAM)) {
4036 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
4037 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4038 }
4039 if (HasBit(rts, ROADTYPE_ROAD)) {
4040 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
4041 if (road_owner != OWNER_TOWN) {
4042 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4043 } else {
4044 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4045 }
4046 }
4047
4048 return true;
4049 }
4050
4057 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4058 {
4059 if (flags & DC_AUTO) {
4060 switch (GetStationType(tile)) {
4061 default: break;
4062 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4063 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4064 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4065 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);
4066 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);
4067 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4068 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4069 case STATION_OILRIG:
4070 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4071 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4072 }
4073 }
4074
4075 switch (GetStationType(tile)) {
4076 case STATION_RAIL: return RemoveRailStation(tile, flags);
4077 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4078 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4079 case STATION_TRUCK:
4080 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4081 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4082 }
4083 return RemoveRoadStop(tile, flags);
4084 case STATION_BUS:
4085 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4086 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4087 }
4088 return RemoveRoadStop(tile, flags);
4089 case STATION_BUOY: return RemoveBuoy(tile, flags);
4090 case STATION_DOCK: return RemoveDock(tile, flags);
4091 default: break;
4092 }
4093
4094 return CMD_ERROR;
4095 }
4096
4097 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4098 {
4099 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4100 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4101 * TTDP does not call it.
4102 */
4103 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4104 switch (GetStationType(tile)) {
4105 case STATION_WAYPOINT:
4106 case STATION_RAIL: {
4107 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4108 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4109 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4110 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4111 }
4112
4113 case STATION_AIRPORT:
4114 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4115
4116 case STATION_TRUCK:
4117 case STATION_BUS: {
4118 DiagDirection direction = GetRoadStopDir(tile);
4119 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4120 if (IsDriveThroughStopTile(tile)) {
4121 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4122 }
4123 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4124 }
4125
4126 default: break;
4127 }
4128 }
4129 }
4130 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4131 }
4132
4138 uint FlowStat::GetShare(StationID st) const
4139 {
4140 uint32 prev = 0;
4141 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4142 if (it->second == st) {
4143 return it->first - prev;
4144 } else {
4145 prev = it->first;
4146 }
4147 }
4148 return 0;
4149 }
4150
4157 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4158 {
4159 if (this->unrestricted == 0) return INVALID_STATION;
4160 assert(!this->shares.empty());
4161 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4162 assert(it != this->shares.end() && it->first <= this->unrestricted);
4163 if (it->second != excluded && it->second != excluded2) return it->second;
4164
4165 /* We've hit one of the excluded stations.
4166 * Draw another share, from outside its range. */
4167
4168 uint end = it->first;
4169 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4170 uint interval = end - begin;
4171 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4172 uint new_max = this->unrestricted - interval;
4173 uint rand = RandomRange(new_max);
4174 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4175 this->shares.upper_bound(rand + interval);
4176 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4177 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4178
4179 /* We've hit the second excluded station.
4180 * Same as before, only a bit more complicated. */
4181
4182 uint end2 = it2->first;
4183 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4184 uint interval2 = end2 - begin2;
4185 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4186 new_max -= interval2;
4187 if (begin > begin2) {
4188 Swap(begin, begin2);
4189 Swap(end, end2);
4190 Swap(interval, interval2);
4191 }
4192 rand = RandomRange(new_max);
4193 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4194 if (rand < begin) {
4195 it3 = this->shares.upper_bound(rand);
4196 } else if (rand < begin2 - interval) {
4197 it3 = this->shares.upper_bound(rand + interval);
4198 } else {
4199 it3 = this->shares.upper_bound(rand + interval + interval2);
4200 }
4201 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4202 return it3->second;
4203 }
4204
4210 void FlowStat::Invalidate()
4211 {
4212 assert(!this->shares.empty());
4213 SharesMap new_shares;
4214 uint i = 0;
4215 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4216 new_shares[++i] = it->second;
4217 if (it->first == this->unrestricted) this->unrestricted = i;
4218 }
4219 this->shares.swap(new_shares);
4220 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4221 }
4222
4229 void FlowStat::ChangeShare(StationID st, int flow)
4230 {
4231 /* We assert only before changing as afterwards the shares can actually
4232 * be empty. In that case the whole flow stat must be deleted then. */
4233 assert(!this->shares.empty());
4234
4235 uint removed_shares = 0;
4236 uint added_shares = 0;
4237 uint last_share = 0;
4238 SharesMap new_shares;
4239 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4240 if (it->second == st) {
4241 if (flow < 0) {
4242 uint share = it->first - last_share;
4243 if (flow == INT_MIN || (uint)(-flow) >= share) {
4244 removed_shares += share;
4245 if (it->first <= this->unrestricted) this->unrestricted -= share;
4246 if (flow != INT_MIN) flow += share;
4247 last_share = it->first;
4248 continue; // remove the whole share
4249 }
4250 removed_shares += (uint)(-flow);
4251 } else {
4252 added_shares += (uint)(flow);
4253 }
4254 if (it->first <= this->unrestricted) this->unrestricted += flow;
4255
4256 /* If we don't continue above the whole flow has been added or
4257 * removed. */
4258 flow = 0;
4259 }
4260 new_shares[it->first + added_shares - removed_shares] = it->second;
4261 last_share = it->first;
4262 }
4263 if (flow > 0) {
4264 new_shares[last_share + (uint)flow] = st;
4265 if (this->unrestricted < last_share) {
4266 this->ReleaseShare(st);
4267 } else {
4268 this->unrestricted += flow;
4269 }
4270 }
4271 this->shares.swap(new_shares);
4272 }
4273
4279 void FlowStat::RestrictShare(StationID st)
4280 {
4281 assert(!this->shares.empty());
4282 uint flow = 0;
4283 uint last_share = 0;
4284 SharesMap new_shares;
4285 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4286 if (flow == 0) {
4287 if (it->first > this->unrestricted) return; // Not present or already restricted.
4288 if (it->second == st) {
4289 flow = it->first - last_share;
4290 this->unrestricted -= flow;
4291 } else {
4292 new_shares[it->first] = it->second;
4293 }
4294 } else {
4295 new_shares[it->first - flow] = it->second;
4296 }
4297 last_share = it->first;
4298 }
4299 if (flow == 0) return;
4300 new_shares[last_share + flow] = st;
4301 this->shares.swap(new_shares);
4302 assert(!this->shares.empty());
4303 }
4304
4310 void FlowStat::ReleaseShare(StationID st)
4311 {
4312 assert(!this->shares.empty());
4313 uint flow = 0;
4314 uint next_share = 0;
4315 bool found = false;
4316 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4317 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4318 if (found) {
4319 flow = next_share - it->first;
4320 this->unrestricted += flow;
4321 break;
4322 } else {
4323 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4324 if (it->second == st) found = true;
4325 }
4326 next_share = it->first;
4327 }
4328 if (flow == 0) return;
4329 SharesMap new_shares;
4330 new_shares[flow] = st;
4331 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4332 if (it->second != st) {
4333 new_shares[flow + it->first] = it->second;
4334 } else {
4335 flow = 0;
4336 }
4337 }
4338 this->shares.swap(new_shares);
4339 assert(!this->shares.empty());
4340 }
4341
4347 void FlowStat::ScaleToMonthly(uint runtime)
4348 {
4349 assert(runtime > 0);
4350 SharesMap new_shares;
4351 uint share = 0;
4352 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4353 share = max(share + 1, i->first * 30 / runtime);
4354 new_shares[share] = i->second;
4355 if (this->unrestricted == i->first) this->unrestricted = share;
4356 }
4357 this->shares.swap(new_shares);
4358 }
4359
4366 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4367 {
4368 FlowStatMap::iterator origin_it = this->find(origin);
4369 if (origin_it == this->end()) {
4370 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4371 } else {
4372 origin_it->second.ChangeShare(via, flow);
4373 assert(!origin_it->second.GetShares()->empty());
4374 }
4375 }
4376
4385 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4386 {
4387 FlowStatMap::iterator prev_it = this->find(origin);
4388 if (prev_it == this->end()) {
4389 FlowStat fs(via, flow);
4390 fs.AppendShare(INVALID_STATION, flow);
4391 this->insert(std::make_pair(origin, fs));
4392 } else {
4393 prev_it->second.ChangeShare(via, flow);
4394 prev_it->second.ChangeShare(INVALID_STATION, flow);
4395 assert(!prev_it->second.GetShares()->empty());
4396 }
4397 }
4398
4403 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4404 {
4405 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4406 FlowStat &fs = i->second;
4407 uint local = fs.GetShare(INVALID_STATION);
4408 if (local > INT_MAX) { // make sure it fits in an int
4409 fs.ChangeShare(self, -INT_MAX);
4410 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4411 local -= INT_MAX;
4412 }
4413 fs.ChangeShare(self, -(int)local);
4414 fs.ChangeShare(INVALID_STATION, -(int)local);
4415
4416 /* If the local share is used up there must be a share for some
4417 * remote station. */
4418 assert(!fs.GetShares()->empty());
4419 }
4420 }
4421
4428 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4429 {
4430 StationIDStack ret;
4431 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4432 FlowStat &s_flows = f_it->second;
4433 s_flows.ChangeShare(via, INT_MIN);
4434 if (s_flows.GetShares()->empty()) {
4435 ret.Push(f_it->first);
4436 this->erase(f_it++);
4437 } else {
4438 ++f_it;
4439 }
4440 }
4441 return ret;
4442 }
4443
4448 void FlowStatMap::RestrictFlows(StationID via)
4449 {
4450 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4451 it->second.RestrictShare(via);
4452 }
4453 }
4454
4459 void FlowStatMap::ReleaseFlows(StationID via)
4460 {
4461 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4462 it->second.ReleaseShare(via);
4463 }
4464 }
4465
4470 uint FlowStatMap::GetFlow() const
4471 {
4472 uint ret = 0;
4473 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4474 ret += (--(i->second.GetShares()->end()))->first;
4475 }
4476 return ret;
4477 }
4478
4484 uint FlowStatMap::GetFlowVia(StationID via) const
4485 {
4486 uint ret = 0;
4487 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4488 ret += i->second.GetShare(via);
4489 }
4490 return ret;
4491 }
4492
4498 uint FlowStatMap::GetFlowFrom(StationID from) const
4499 {
4500 FlowStatMap::const_iterator i = this->find(from);
4501 if (i == this->end()) return 0;
4502 return (--(i->second.GetShares()->end()))->first;
4503 }
4504
4511 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4512 {
4513 FlowStatMap::const_iterator i = this->find(from);
4514 if (i == this->end()) return 0;
4515 return i->second.GetShare(via);
4516 }
4517
4518 extern const TileTypeProcs _tile_type_station_procs = {
4519 DrawTile_Station, // draw_tile_proc
4520 GetSlopePixelZ_Station, // get_slope_z_proc
4521 ClearTile_Station, // clear_tile_proc
4522 NULL, // add_accepted_cargo_proc
4523 GetTileDesc_Station, // get_tile_desc_proc
4524 GetTileTrackStatus_Station, // get_tile_track_status_proc
4525 ClickTile_Station, // click_tile_proc
4526 AnimateTile_Station, // animate_tile_proc
4527 TileLoop_Station, // tile_loop_proc
4528 ChangeTileOwner_Station, // change_tile_owner_proc
4529 NULL, // add_produced_cargo_proc
4530 VehicleEnter_Station, // vehicle_enter_tile_proc
4531 GetFoundation_Station, // get_foundation_proc
4532 TerraformTile_Station, // terraform_tile_proc
4533 };