OpenTTD: src/station_cmd.cpp Source File

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 27311 2015-06-21 09:19:27Z 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 (Company::IsValidID(tram_owner) &&
967 (!_settings_game.construction.road_stop_on_competitor_road ||
968 /* Disallow breaking end-of-line of someone else
969 * so trams can still reverse on this tile. */
970 HasExactlyOneBit(GetRoadBits(cur_tile, ROADTYPE_TRAM)))) {
971 CommandCost ret = CheckOwnership(tram_owner);
972 if (ret.Failed()) return ret;
973 }
974 num_roadbits += CountBits(GetRoadBits(cur_tile, ROADTYPE_TRAM));
975 }
976
977 /* Take into account existing roadbits. */
978 rts |= cur_rts;
979 } else {
980 ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
981 if (ret.Failed()) return ret;
982 cost.AddCost(ret);
983 }
984
985 uint roadbits_to_build = CountBits(rts) * 2 - num_roadbits;
986 cost.AddCost(_price[PR_BUILD_ROAD] * roadbits_to_build);
987 }
988 }
989
990 return cost;
991 }
992
1000 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
1001 {
1002 TileArea cur_ta = st->train_station;
1003
1004 /* determine new size of train station region.. */
1005 int x = min(TileX(cur_ta.tile), TileX(new_ta.tile));
1006 int y = min(TileY(cur_ta.tile), TileY(new_ta.tile));
1007 new_ta.w = max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1008 new_ta.h = max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1009 new_ta.tile = TileXY(x, y);
1010
1011 /* make sure the final size is not too big. */
1012 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1013 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1014 }
1015
1016 return CommandCost();
1017 }
1018
1019 static inline byte *CreateSingle(byte *layout, int n)
1020 {
1021 int i = n;
1022 do *layout++ = 0; while (--i);
1023 layout[((n - 1) >> 1) - n] = 2;
1024 return layout;
1025 }
1026
1027 static inline byte *CreateMulti(byte *layout, int n, byte b)
1028 {
1029 int i = n;
1030 do *layout++ = b; while (--i);
1031 if (n > 4) {
1032 layout[0 - n] = 0;
1033 layout[n - 1 - n] = 0;
1034 }
1035 return layout;
1036 }
1037
1045 void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
1046 {
1047 if (statspec != NULL && statspec->lengths >= plat_len &&
1048 statspec->platforms[plat_len - 1] >= numtracks &&
1049 statspec->layouts[plat_len - 1][numtracks - 1]) {
1050 /* Custom layout defined, follow it. */
1051 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1],
1052 plat_len * numtracks);
1053 return;
1054 }
1055
1056 if (plat_len == 1) {
1057 CreateSingle(layout, numtracks);
1058 } else {
1059 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1060 numtracks >>= 1;
1061
1062 while (--numtracks >= 0) {
1063 layout = CreateMulti(layout, plat_len, 4);
1064 layout = CreateMulti(layout, plat_len, 6);
1065 }
1066 }
1067 }
1068
1080 template <class T, StringID error_message>
1081 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1082 {
1083 assert(*st == NULL);
1084 bool check_surrounding = true;
1085
1086 if (_settings_game.station.adjacent_stations) {
1087 if (existing_station != INVALID_STATION) {
1088 if (adjacent && existing_station != station_to_join) {
1089 /* You can't build an adjacent station over the top of one that
1090 * already exists. */
1091 return_cmd_error(error_message);
1092 } else {
1093 /* Extend the current station, and don't check whether it will
1094 * be near any other stations. */
1095 *st = T::GetIfValid(existing_station);
1096 check_surrounding = (*st == NULL);
1097 }
1098 } else {
1099 /* There's no station here. Don't check the tiles surrounding this
1100 * one if the company wanted to build an adjacent station. */
1101 if (adjacent) check_surrounding = false;
1102 }
1103 }
1104
1105 if (check_surrounding) {
1106 /* Make sure there are no similar stations around us. */
1107 CommandCost ret = GetStationAround(ta, existing_station, st);
1108 if (ret.Failed()) return ret;
1109 }
1110
1111 /* Distant join */
1112 if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1113
1114 return CommandCost();
1115 }
1116
1126 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1127 {
1128 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1129 }
1130
1140 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1141 {
1142 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1143 }
1144
1162 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1163 {
1164 /* Unpack parameters */
1165 RailType rt = Extract<RailType, 0, 4>(p1);
1166 Axis axis = Extract<Axis, 4, 1>(p1);
1167 byte numtracks = GB(p1, 8, 8);
1168 byte plat_len = GB(p1, 16, 8);
1169 bool adjacent = HasBit(p1, 24);
1170
1171 StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1172 byte spec_index = GB(p2, 8, 8);
1173 StationID station_to_join = GB(p2, 16, 16);
1174
1175 /* Does the authority allow this? */
1176 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1177 if (ret.Failed()) return ret;
1178
1179 if (!ValParamRailtype(rt)) return CMD_ERROR;
1180
1181 /* Check if the given station class is valid */
1182 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1183 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1184 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1185
1186 int w_org, h_org;
1187 if (axis == AXIS_X) {
1188 w_org = plat_len;
1189 h_org = numtracks;
1190 } else {
1191 h_org = plat_len;
1192 w_org = numtracks;
1193 }
1194
1195 bool reuse = (station_to_join != NEW_STATION);
1196 if (!reuse) station_to_join = INVALID_STATION;
1197 bool distant_join = (station_to_join != INVALID_STATION);
1198
1199 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1200
1201 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1202
1203 /* these values are those that will be stored in train_tile and station_platforms */
1204 TileArea new_location(tile_org, w_org, h_org);
1205
1206 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1207 StationID est = INVALID_STATION;
1208 SmallVector<Train *, 4> affected_vehicles;
1209 /* Clear the land below the station. */
1210 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1211 if (cost.Failed()) return cost;
1212 /* Add construction expenses. */
1213 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1214 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1215
1216 Station *st = NULL;
1217 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1218 if (ret.Failed()) return ret;
1219
1220 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1221 if (ret.Failed()) return ret;
1222
1223 if (st != NULL && st->train_station.tile != INVALID_TILE) {
1224 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1225 if (ret.Failed()) return ret;
1226 }
1227
1228 /* Check if we can allocate a custom stationspec to this station */
1229 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1230 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1231 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1232
1233 if (statspec != NULL) {
1234 /* Perform NewStation checks */
1235
1236 /* Check if the station size is permitted */
1237 if (HasBit(statspec->disallowed_platforms, min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, min(plat_len - 1, 7))) {
1238 return CMD_ERROR;
1239 }
1240
1241 /* Check if the station is buildable */
1242 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1243 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
1244 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1245 }
1246 }
1247
1248 if (flags & DC_EXEC) {
1249 TileIndexDiff tile_delta;
1250 byte *layout_ptr;
1251 byte numtracks_orig;
1252 Track track;
1253
1254 st->train_station = new_location;
1255 st->AddFacility(FACIL_TRAIN, new_location.tile);
1256
1257 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1258
1259 if (statspec != NULL) {
1260 /* Include this station spec's animation trigger bitmask
1261 * in the station's cached copy. */
1262 st->cached_anim_triggers |= statspec->animation.triggers;
1263 }
1264
1265 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1266 track = AxisToTrack(axis);
1267
1268 layout_ptr = AllocaM(byte, numtracks * plat_len);
1269 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1270
1271 numtracks_orig = numtracks;
1272
1273 Company *c = Company::Get(st->owner);
1274 TileIndex tile_track = tile_org;
1275 do {
1276 TileIndex tile = tile_track;
1277 int w = plat_len;
1278 do {
1279 byte layout = *layout_ptr++;
1280 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1281 /* Check for trains having a reservation for this tile. */
1282 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1283 if (v != NULL) {
1284 FreeTrainTrackReservation(v);
1285 *affected_vehicles.Append() = v;
1286 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1287 for (; v->Next() != NULL; v = v->Next()) { }
1288 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1289 }
1290 }
1291
1292 /* Railtype can change when overbuilding. */
1293 if (IsRailStationTile(tile)) {
1294 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1295 c->infrastructure.station--;
1296 }
1297
1298 /* Remove animation if overbuilding */
1299 DeleteAnimatedTile(tile);
1300 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1301 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1302 /* Free the spec if we overbuild something */
1303 DeallocateSpecFromStation(st, old_specindex);
1304
1305 SetCustomStationSpecIndex(tile, specindex);
1306 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1307 SetAnimationFrame(tile, 0);
1308
1309 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1310 c->infrastructure.station++;
1311
1312 if (statspec != NULL) {
1313 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1314 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1315
1316 /* As the station is not yet completely finished, the station does not yet exist. */
1317 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
1318 if (callback != CALLBACK_FAILED) {
1319 if (callback < 8) {
1320 SetStationGfx(tile, (callback & ~1) + axis);
1321 } else {
1322 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1323 }
1324 }
1325
1326 /* Trigger station animation -- after building? */
1327 TriggerStationAnimation(st, tile, SAT_BUILT);
1328 }
1329
1330 tile += tile_delta;
1331 } while (--w);
1332 AddTrackToSignalBuffer(tile_track, track, _current_company);
1333 YapfNotifyTrackLayoutChange(tile_track, track);
1334 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1335 } while (--numtracks);
1336
1337 for (uint i = 0; i < affected_vehicles.Length(); ++i) {
1338 /* Restore reservations of trains. */
1339 Train *v = affected_vehicles[i];
1340 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1341 TryPathReserve(v, true, true);
1342 for (; v->Next() != NULL; v = v->Next()) { }
1343 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1344 }
1345
1346 /* Check whether we need to expand the reservation of trains already on the station. */
1347 TileArea update_reservation_area;
1348 if (axis == AXIS_X) {
1349 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1350 } else {
1351 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1352 }
1353
1354 TILE_AREA_LOOP(tile, update_reservation_area) {
1355 /* Don't even try to make eye candy parts reserved. */
1356 if (IsStationTileBlocked(tile)) continue;
1357
1358 DiagDirection dir = AxisToDiagDir(axis);
1359 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1360 TileIndex platform_begin = tile;
1361 TileIndex platform_end = tile;
1362
1363 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1364 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1365 platform_begin = next_tile;
1366 }
1367 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1368 platform_end = next_tile;
1369 }
1370
1371 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1372 bool reservation = false;
1373 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1374 reservation = HasStationReservation(t);
1375 }
1376
1377 if (reservation) {
1378 SetRailStationPlatformReservation(platform_begin, dir, true);
1379 }
1380 }
1381
1382 st->MarkTilesDirty(false);
1383 st->UpdateVirtCoord();
1384 UpdateStationAcceptance(st, false);
1385 st->RecomputeIndustriesNear();
1386 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1387 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1388 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1389 DirtyCompanyInfrastructureWindows(st->owner);
1390 }
1391
1392 return cost;
1393 }
1394
1395 static void MakeRailStationAreaSmaller(BaseStation *st)
1396 {
1397 TileArea ta = st->train_station;
1398
1399 restart:
1400
1401 /* too small? */
1402 if (ta.w != 0 && ta.h != 0) {
1403 /* check the left side, x = constant, y changes */
1404 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(0, i));) {
1405 /* the left side is unused? */
1406 if (++i == ta.h) {
1407 ta.tile += TileDiffXY(1, 0);
1408 ta.w--;
1409 goto restart;
1410 }
1411 }
1412
1413 /* check the right side, x = constant, y changes */
1414 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(ta.w - 1, i));) {
1415 /* the right side is unused? */
1416 if (++i == ta.h) {
1417 ta.w--;
1418 goto restart;
1419 }
1420 }
1421
1422 /* check the upper side, y = constant, x changes */
1423 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, 0));) {
1424 /* the left side is unused? */
1425 if (++i == ta.w) {
1426 ta.tile += TileDiffXY(0, 1);
1427 ta.h--;
1428 goto restart;
1429 }
1430 }
1431
1432 /* check the lower side, y = constant, x changes */
1433 for (uint i = 0; !st->TileBelongsToRailStation(ta.tile + TileDiffXY(i, ta.h - 1));) {
1434 /* the left side is unused? */
1435 if (++i == ta.w) {
1436 ta.h--;
1437 goto restart;
1438 }
1439 }
1440 } else {
1441 ta.Clear();
1442 }
1443
1444 st->train_station = ta;
1445 }
1446
1457 template <class T>
1458 CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1459 {
1460 /* Count of the number of tiles removed */
1461 int quantity = 0;
1462 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1463 /* Accumulator for the errors seen during clearing. If no errors happen,
1464 * and the quantity is 0 there is no station. Otherwise it will be one
1465 * of the other error that got accumulated. */
1466 CommandCost error;
1467
1468 /* Do the action for every tile into the area */
1469 TILE_AREA_LOOP(tile, ta) {
1470 /* Make sure the specified tile is a rail station */
1471 if (!HasStationTileRail(tile)) continue;
1472
1473 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1474 CommandCost ret = EnsureNoVehicleOnGround(tile);
1475 error.AddCost(ret);
1476 if (ret.Failed()) continue;
1477
1478 /* Check ownership of station */
1479 T *st = T::GetByTile(tile);
1480 if (st == NULL) continue;
1481
1482 if (_current_company != OWNER_WATER) {
1483 CommandCost ret = CheckOwnership(st->owner);
1484 error.AddCost(ret);
1485 if (ret.Failed()) continue;
1486 }
1487
1488 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1489 quantity++;
1490
1491 if (keep_rail || IsStationTileBlocked(tile)) {
1492 /* Don't refund the 'steel' of the track when we keep the
1493 * rail, or when the tile didn't have any rail at all. */
1494 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1495 }
1496
1497 if (flags & DC_EXEC) {
1498 /* read variables before the station tile is removed */
1499 uint specindex = GetCustomStationSpecIndex(tile);
1500 Track track = GetRailStationTrack(tile);
1501 Owner owner = GetTileOwner(tile);
1502 RailType rt = GetRailType(tile);
1503 Train *v = NULL;
1504
1505 if (HasStationReservation(tile)) {
1506 v = GetTrainForReservation(tile, track);
1507 if (v != NULL) {
1508 /* Free train reservation. */
1509 FreeTrainTrackReservation(v);
1510 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1511 Vehicle *temp = v;
1512 for (; temp->Next() != NULL; temp = temp->Next()) { }
1513 if (IsRailStationTile(temp->tile)) SetRailStationPlatformReservation(temp->tile, TrackdirToExitdir(ReverseTrackdir(temp->GetVehicleTrackdir())), false);
1514 }
1515 }
1516
1517 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1518 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1519
1520 DoClearSquare(tile);
1521 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1522 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1523 Company::Get(owner)->infrastructure.station--;
1524 DirtyCompanyInfrastructureWindows(owner);
1525
1526 st->rect.AfterRemoveTile(st, tile);
1527 AddTrackToSignalBuffer(tile, track, owner);
1528 YapfNotifyTrackLayoutChange(tile, track);
1529
1530 DeallocateSpecFromStation(st, specindex);
1531
1532 affected_stations.Include(st);
1533
1534 if (v != NULL) {
1535 /* Restore station reservation. */
1536 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1537 TryPathReserve(v, true, true);
1538 for (; v->Next() != NULL; v = v->Next()) { }
1539 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1540 }
1541 }
1542 }
1543
1544 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1545
1546 for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1547 T *st = *stp;
1548
1549 /* now we need to make the "spanned" area of the railway station smaller
1550 * if we deleted something at the edges.
1551 * we also need to adjust train_tile. */
1552 MakeRailStationAreaSmaller(st);
1553 UpdateStationSignCoord(st);
1554
1555 /* if we deleted the whole station, delete the train facility. */
1556 if (st->train_station.tile == INVALID_TILE) {
1557 st->facilities &= ~FACIL_TRAIN;
1558 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1559 st->UpdateVirtCoord();
1560 DeleteStationIfEmpty(st);
1561 }
1562 }
1563
1564 total_cost.AddCost(quantity * removal_cost);
1565 return total_cost;
1566 }
1567
1579 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1580 {
1581 TileIndex end = p1 == 0 ? start : p1;
1582 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1583
1584 TileArea ta(start, end);
1585 SmallVector<Station *, 4> affected_stations;
1586
1587 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1588 if (ret.Failed()) return ret;
1589
1590 /* Do all station specific functions here. */
1591 for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) {
1592 Station *st = *stp;
1593
1594 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1595 st->MarkTilesDirty(false);
1596 st->RecomputeIndustriesNear();
1597 }
1598
1599 /* Now apply the rail cost to the number that we deleted */
1600 return ret;
1601 }
1602
1614 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1615 {
1616 TileIndex end = p1 == 0 ? start : p1;
1617 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1618
1619 TileArea ta(start, end);
1620 SmallVector<Waypoint *, 4> affected_stations;
1621
1622 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
1623 }
1624
1625
1634 template <class T>
1635 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1636 {
1637 /* Current company owns the station? */
1638 if (_current_company != OWNER_WATER) {
1639 CommandCost ret = CheckOwnership(st->owner);
1640 if (ret.Failed()) return ret;
1641 }
1642
1643 /* determine width and height of platforms */
1644 TileArea ta = st->train_station;
1645
1646 assert(ta.w != 0 && ta.h != 0);
1647
1648 CommandCost cost(EXPENSES_CONSTRUCTION);
1649 /* clear all areas of the station */
1650 TILE_AREA_LOOP(tile, ta) {
1651 /* only remove tiles that are actually train station tiles */
1652 if (st->TileBelongsToRailStation(tile)) {
1653 SmallVector<T*, 4> affected_stations; // dummy
1654 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1655 if (ret.Failed()) return ret;
1656 cost.AddCost(ret);
1657 }
1658 }
1659
1660 return cost;
1661 }
1662
1669 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1670 {
1671 /* if there is flooding, remove platforms tile by tile */
1672 if (_current_company == OWNER_WATER) {
1673 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1674 }
1675
1676 Station *st = Station::GetByTile(tile);
1677 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1678
1679 if (flags & DC_EXEC) st->RecomputeIndustriesNear();
1680
1681 return cost;
1682 }
1683
1690 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1691 {
1692 /* if there is flooding, remove waypoints tile by tile */
1693 if (_current_company == OWNER_WATER) {
1694 return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1695 }
1696
1697 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1698 }
1699
1700
1706 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1707 {
1708 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1709
1710 if (*primary_stop == NULL) {
1711 /* we have no roadstop of the type yet, so write a "primary stop" */
1712 return primary_stop;
1713 } else {
1714 /* there are stops already, so append to the end of the list */
1715 RoadStop *stop = *primary_stop;
1716 while (stop->next != NULL) stop = stop->next;
1717 return &stop->next;
1718 }
1719 }
1720
1721 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1722
1732 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1733 {
1734 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1735 }
1736
1753 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1754 {
1755 bool type = HasBit(p2, 0);
1756 bool is_drive_through = HasBit(p2, 1);
1757 RoadTypes rts = Extract<RoadTypes, 2, 2>(p2);
1758 StationID station_to_join = GB(p2, 16, 16);
1759 bool reuse = (station_to_join != NEW_STATION);
1760 if (!reuse) station_to_join = INVALID_STATION;
1761 bool distant_join = (station_to_join != INVALID_STATION);
1762
1763 uint8 width = (uint8)GB(p1, 0, 8);
1764 uint8 lenght = (uint8)GB(p1, 8, 8);
1765
1766 /* Check if the requested road stop is too big */
1767 if (width > _settings_game.station.station_spread || lenght > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1768 /* Check for incorrect width / length. */
1769 if (width == 0 || lenght == 0) return CMD_ERROR;
1770 /* Check if the first tile and the last tile are valid */
1771 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, lenght - 1) == INVALID_TILE) return CMD_ERROR;
1772
1773 TileArea roadstop_area(tile, width, lenght);
1774
1775 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1776
1777 if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
1778
1779 /* Trams only have drive through stops */
1780 if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;
1781
1782 DiagDirection ddir;
1783 Axis axis;
1784 if (is_drive_through) {
1785 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1786 axis = Extract<Axis, 6, 1>(p2);
1787 ddir = AxisToDiagDir(axis);
1788 } else {
1789 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1790 ddir = Extract<DiagDirection, 6, 2>(p2);
1791 axis = DiagDirToAxis(ddir);
1792 }
1793
1794 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1795 if (ret.Failed()) return ret;
1796
1797 /* Total road stop cost. */
1798 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1799 StationID est = INVALID_STATION;
1800 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rts);
1801 if (ret.Failed()) return ret;
1802 cost.AddCost(ret);
1803
1804 Station *st = NULL;
1805 ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
1806 if (ret.Failed()) return ret;
1807
1808 /* Check if this number of road stops can be allocated. */
1809 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);
1810
1811 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1812 if (ret.Failed()) return ret;
1813
1814 if (flags & DC_EXEC) {
1815 /* Check every tile in the area. */
1816 TILE_AREA_LOOP(cur_tile, roadstop_area) {
1817 RoadTypes cur_rts = GetRoadTypes(cur_tile);
1818 Owner road_owner = HasBit(cur_rts, ROADTYPE_ROAD) ? GetRoadOwner(cur_tile, ROADTYPE_ROAD) : _current_company;
1819 Owner tram_owner = HasBit(cur_rts, ROADTYPE_TRAM) ? GetRoadOwner(cur_tile, ROADTYPE_TRAM) : _current_company;
1820
1821 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
1822 RemoveRoadStop(cur_tile, flags);
1823 }
1824
1825 RoadStop *road_stop = new RoadStop(cur_tile);
1826 /* Insert into linked list of RoadStops. */
1827 RoadStop **currstop = FindRoadStopSpot(type, st);
1828 *currstop = road_stop;
1829
1830 if (type) {
1831 st->truck_station.Add(cur_tile);
1832 } else {
1833 st->bus_station.Add(cur_tile);
1834 }
1835
1836 /* Initialize an empty station. */
1837 st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1838
1839 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1840
1841 RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1842 if (is_drive_through) {
1843 /* Update company infrastructure counts. If the current tile is a normal
1844 * road tile, count only the new road bits needed to get a full diagonal road. */
1845 RoadType rt;
1846 FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
1847 Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
1848 if (c != NULL) {
1849 c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
1850 DirtyCompanyInfrastructureWindows(c->index);
1851 }
1852 }
1853
1854 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, rts | cur_rts, axis);
1855 road_stop->MakeDriveThrough();
1856 } else {
1857 /* Non-drive-through stop never overbuild and always count as two road bits. */
1858 Company::Get(st->owner)->infrastructure.road[FIND_FIRST_BIT(rts)] += 2;
1859 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, rts, ddir);
1860 }
1861 Company::Get(st->owner)->infrastructure.station++;
1862 DirtyCompanyInfrastructureWindows(st->owner);
1863
1864 MarkTileDirtyByTile(cur_tile);
1865 }
1866 }
1867
1868 if (st != NULL) {
1869 st->UpdateVirtCoord();
1870 UpdateStationAcceptance(st, false);
1871 st->RecomputeIndustriesNear();
1872 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
1873 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
1874 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1875 }
1876 return cost;
1877 }
1878
1879
1880 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
1881 {
1882 if (v->type == VEH_ROAD) {
1883 /* Okay... we are a road vehicle on a drive through road stop.
1884 * But that road stop has just been removed, so we need to make
1885 * sure we are in a valid state... however, vehicles can also
1886 * turn on road stop tiles, so only clear the 'road stop' state
1887 * bits and only when the state was 'in road stop', otherwise
1888 * we'll end up clearing the turn around bits. */
1889 RoadVehicle *rv = RoadVehicle::From(v);
1890 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1891 }
1892
1893 return NULL;
1894 }
1895
1896
1903 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1904 {
1905 Station *st = Station::GetByTile(tile);
1906
1907 if (_current_company != OWNER_WATER) {
1908 CommandCost ret = CheckOwnership(st->owner);
1909 if (ret.Failed()) return ret;
1910 }
1911
1912 bool is_truck = IsTruckStop(tile);
1913
1914 RoadStop **primary_stop;
1915 RoadStop *cur_stop;
1916 if (is_truck) { // truck stop
1917 primary_stop = &st->truck_stops;
1918 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1919 } else {
1920 primary_stop = &st->bus_stops;
1921 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1922 }
1923
1924 assert(cur_stop != NULL);
1925
1926 /* don't do the check for drive-through road stops when company bankrupts */
1927 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1928 /* remove the 'going through road stop' status from all vehicles on that tile */
1929 if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
1930 } else {
1931 CommandCost ret = EnsureNoVehicleOnGround(tile);
1932 if (ret.Failed()) return ret;
1933 }
1934
1935 if (flags & DC_EXEC) {
1936 if (*primary_stop == cur_stop) {
1937 /* removed the first stop in the list */
1938 *primary_stop = cur_stop->next;
1939 /* removed the only stop? */
1940 if (*primary_stop == NULL) {
1941 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
1942 }
1943 } else {
1944 /* tell the predecessor in the list to skip this stop */
1945 RoadStop *pred = *primary_stop;
1946 while (pred->next != cur_stop) pred = pred->next;
1947 pred->next = cur_stop->next;
1948 }
1949
1950 /* Update company infrastructure counts. */
1951 RoadType rt;
1952 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
1953 Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
1954 if (c != NULL) {
1955 c->infrastructure.road[rt] -= 2;
1956 DirtyCompanyInfrastructureWindows(c->index);
1957 }
1958 }
1959 Company::Get(st->owner)->infrastructure.station--;
1960 DirtyCompanyInfrastructureWindows(st->owner);
1961
1962 if (IsDriveThroughStopTile(tile)) {
1963 /* Clears the tile for us */
1964 cur_stop->ClearDriveThrough();
1965 } else {
1966 DoClearSquare(tile);
1967 }
1968
1969 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ROADVEHS);
1970 delete cur_stop;
1971
1972 /* Make sure no vehicle is going to the old roadstop */
1973 RoadVehicle *v;
1974 FOR_ALL_ROADVEHICLES(v) {
1975 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
1976 v->dest_tile == tile) {
1977 v->dest_tile = v->GetOrderStationLocation(st->index);
1978 }
1979 }
1980
1981 st->rect.AfterRemoveTile(st, tile);
1982
1983 st->UpdateVirtCoord();
1984 st->RecomputeIndustriesNear();
1985 DeleteStationIfEmpty(st);
1986
1987 /* Update the tile area of the truck/bus stop */
1988 if (is_truck) {
1989 st->truck_station.Clear();
1990 for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
1991 } else {
1992 st->bus_station.Clear();
1993 for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
1994 }
1995 }
1996
1997 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
1998 }
1999
2011 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2012 {
2013 uint8 width = (uint8)GB(p1, 0, 8);
2014 uint8 height = (uint8)GB(p1, 8, 8);
2015 bool keep_drive_through_roads = !HasBit(p2, 1);
2016
2017 /* Check for incorrect width / height. */
2018 if (width == 0 || height == 0) return CMD_ERROR;
2019 /* Check if the first tile and the last tile are valid */
2020 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2021 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2022 if (!keep_drive_through_roads && (flags & DC_BANKRUPT)) return CMD_ERROR;
2023
2024 TileArea roadstop_area(tile, width, height);
2025
2026 CommandCost cost(EXPENSES_CONSTRUCTION);
2027 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2028 bool had_success = false;
2029
2030 TILE_AREA_LOOP(cur_tile, roadstop_area) {
2031 /* Make sure the specified tile is a road stop of the correct type */
2032 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2033
2034 /* Save information on to-be-restored roads before the stop is removed. */
2035 RoadTypes rts = ROADTYPES_NONE;
2036 RoadBits road_bits = ROAD_NONE;
2037 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2038 assert_compile(lengthof(road_owner) == ROADTYPE_END);
2039 if (IsDriveThroughStopTile(cur_tile)) {
2040 RoadType rt;
2041 FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(cur_tile)) {
2042 road_owner[rt] = GetRoadOwner(cur_tile, rt);
2043 /* If we don't want to preserve our roads then restore only roads of others. */
2044 if (keep_drive_through_roads || road_owner[rt] != _current_company) SetBit(rts, rt);
2045 }
2046 road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2047 }
2048
2049 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2050 if (ret.Failed()) {
2051 last_error = ret;
2052 continue;
2053 }
2054 cost.AddCost(ret);
2055 had_success = true;
2056
2057 /* Restore roads. */
2058 if ((flags & DC_EXEC) && rts != ROADTYPES_NONE) {
2059 MakeRoadNormal(cur_tile, road_bits, rts, ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2060 road_owner[ROADTYPE_ROAD], road_owner[ROADTYPE_TRAM]);
2061
2062 /* Update company infrastructure counts. */
2063 RoadType rt;
2064 FOR_EACH_SET_ROADTYPE(rt, rts) {
2065 Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
2066 if (c != NULL) {
2067 c->infrastructure.road[rt] += CountBits(road_bits);
2068 DirtyCompanyInfrastructureWindows(c->index);
2069 }
2070 }
2071 }
2072 }
2073
2074 return had_success ? cost : last_error;
2075 }
2076
2083 static uint GetMinimalAirportDistanceToTile(TileIterator &it, TileIndex town_tile)
2084 {
2085 uint mindist = UINT_MAX;
2086
2087 for (TileIndex cur_tile = it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2088 mindist = min(mindist, DistanceManhattan(town_tile, cur_tile));
2089 }
2090
2091 return mindist;
2092 }
2093
2103 uint8 GetAirportNoiseLevelForTown(const AirportSpec *as, TileIterator &it, TileIndex town_tile)
2104 {
2105 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2106 * So no need to go any further*/
2107 if (as->noise_level < 2) return as->noise_level;
2108
2109 uint distance = GetMinimalAirportDistanceToTile(it, town_tile);
2110
2111 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2112 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2113 * Basically, it says that the less tolerant a town is, the bigger the distance before
2114 * an actual decrease can be granted */
2115 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2116
2117 /* now, we want to have the distance segmented using the distance judged bareable by town
2118 * This will give us the coefficient of reduction the distance provides. */
2119 uint noise_reduction = distance / town_tolerance_distance;
2120
2121 /* If the noise reduction equals the airport noise itself, don't give it for free.
2122 * Otherwise, simply reduce the airport's level. */
2123 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2124 }
2125
2133 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it)
2134 {
2135 Town *t, *nearest = NULL;
2136 uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2137 uint mindist = UINT_MAX - add; // prevent overflow
2138 FOR_ALL_TOWNS(t) {
2139 if (DistanceManhattan(t->xy, it) < mindist + add) { // avoid calling GetMinimalAirportDistanceToTile too often
2140 TileIterator *copy = it.Clone();
2141 uint dist = GetMinimalAirportDistanceToTile(*copy, t->xy);
2142 delete copy;
2143 if (dist < mindist) {
2144 nearest = t;
2145 mindist = dist;
2146 }
2147 }
2148 }
2149
2150 return nearest;
2151 }
2152
2153
2155 void UpdateAirportsNoise()
2156 {
2157 Town *t;
2158 const Station *st;
2159
2160 FOR_ALL_TOWNS(t) t->noise_reached = 0;
2161
2162 FOR_ALL_STATIONS(st) {
2163 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2164 const AirportSpec *as = st->airport.GetSpec();
2165 AirportTileIterator it(st);
2166 Town *nearest = AirportGetNearestTown(as, it);
2167 nearest->noise_reached += GetAirportNoiseLevelForTown(as, it, nearest->xy);
2168 }
2169 }
2170 }
2171
2185 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2186 {
2187 StationID station_to_join = GB(p2, 16, 16);
2188 bool reuse = (station_to_join != NEW_STATION);
2189 if (!reuse) station_to_join = INVALID_STATION;
2190 bool distant_join = (station_to_join != INVALID_STATION);
2191 byte airport_type = GB(p1, 0, 8);
2192 byte layout = GB(p1, 8, 8);
2193
2194 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2195
2196 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2197
2198 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2199 if (ret.Failed()) return ret;
2200
2201 /* Check if a valid, buildable airport was chosen for construction */
2202 const AirportSpec *as = AirportSpec::Get(airport_type);
2203 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2204
2205 Direction rotation = as->rotation[layout];
2206 int w = as->size_x;
2207 int h = as->size_y;
2208 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2209 TileArea airport_area = TileArea(tile, w, h);
2210
2211 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2212 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2213 }
2214
2215 CommandCost cost = CheckFlatLand(airport_area, flags);
2216 if (cost.Failed()) return cost;
2217
2218 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2219 AirportTileTableIterator iter(as->table[layout], tile);
2220 Town *nearest = AirportGetNearestTown(as, iter);
2221 uint newnoise_level = GetAirportNoiseLevelForTown(as, iter, nearest->xy);
2222
2223 /* Check if local auth would allow a new airport */
2224 StringID authority_refuse_message = STR_NULL;
2225 Town *authority_refuse_town = NULL;
2226
2227 if (_settings_game.economy.station_noise_level) {
2228 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2229 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2230 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2231 authority_refuse_town = nearest;
2232 }
2233 } else {
2234 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2235 uint num = 0;
2236 const Station *st;
2237 FOR_ALL_STATIONS(st) {
2238 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2239 }
2240 if (num >= 2) {
2241 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2242 authority_refuse_town = t;
2243 }
2244 }
2245
2246 if (authority_refuse_message != STR_NULL) {
2247 SetDParam(0, authority_refuse_town->index);
2248 return_cmd_error(authority_refuse_message);
2249 }
2250
2251 Station *st = NULL;
2252 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
2253 if (ret.Failed()) return ret;
2254
2255 /* Distant join */
2256 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2257
2258 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2259 if (ret.Failed()) return ret;
2260
2261 if (st != NULL && st->airport.tile != INVALID_TILE) {
2262 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2263 }
2264
2265 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2266 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2267 }
2268
2269 if (flags & DC_EXEC) {
2270 /* Always add the noise, so there will be no need to recalculate when option toggles */
2271 nearest->noise_reached += newnoise_level;
2272
2273 st->AddFacility(FACIL_AIRPORT, tile);
2274 st->airport.type = airport_type;
2275 st->airport.layout = layout;
2276 st->airport.flags = 0;
2277 st->airport.rotation = rotation;
2278
2279 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2280
2281 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2282 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2283 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2284 st->airport.Add(iter);
2285
2286 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2287 }
2288
2289 /* Only call the animation trigger after all tiles have been built */
2290 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2291 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2292 }
2293
2294 UpdateAirplanesOnNewStation(st);
2295
2296 Company::Get(st->owner)->infrastructure.airport++;
2297 DirtyCompanyInfrastructureWindows(st->owner);
2298
2299 st->UpdateVirtCoord();
2300 UpdateStationAcceptance(st, false);
2301 st->RecomputeIndustriesNear();
2302 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2303 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2304 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2305
2306 if (_settings_game.economy.station_noise_level) {
2307 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2308 }
2309 }
2310
2311 return cost;
2312 }
2313
2320 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2321 {
2322 Station *st = Station::GetByTile(tile);
2323
2324 if (_current_company != OWNER_WATER) {
2325 CommandCost ret = CheckOwnership(st->owner);
2326 if (ret.Failed()) return ret;
2327 }
2328
2329 tile = st->airport.tile;
2330
2331 CommandCost cost(EXPENSES_CONSTRUCTION);
2332
2333 const Aircraft *a;
2334 FOR_ALL_AIRCRAFT(a) {
2335 if (!a->IsNormalAircraft()) continue;
2336 if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
2337 }
2338
2339 if (flags & DC_EXEC) {
2340 const AirportSpec *as = st->airport.GetSpec();
2341 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2342 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2343 * need of recalculation */
2344 AirportTileIterator it(st);
2345 Town *nearest = AirportGetNearestTown(as, it);
2346 nearest->noise_reached -= GetAirportNoiseLevelForTown(as, it, nearest->xy);
2347 }
2348
2349 TILE_AREA_LOOP(tile_cur, st->airport) {
2350 if (!st->TileBelongsToAirport(tile_cur)) continue;
2351
2352 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2353 if (ret.Failed()) return ret;
2354
2355 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2356
2357 if (flags & DC_EXEC) {
2358 if (IsHangarTile(tile_cur)) OrderBackup::Reset(tile_cur, false);
2359 DeleteAnimatedTile(tile_cur);
2360 DoClearSquare(tile_cur);
2361 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2362 }
2363 }
2364
2365 if (flags & DC_EXEC) {
2366 /* Clear the persistent storage. */
2367 delete st->airport.psa;
2368
2369 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2370 DeleteWindowById(
2371 WC_VEHICLE_DEPOT, st->airport.GetHangarTile(i)
2372 );
2373 }
2374
2375 st->rect.AfterRemoveRect(st, st->airport);
2376
2377 st->airport.Clear();
2378 st->facilities &= ~FACIL_AIRPORT;
2379
2380 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2381
2382 if (_settings_game.economy.station_noise_level) {
2383 SetWindowDirty(WC_TOWN_VIEW, st->town->index);
2384 }
2385
2386 Company::Get(st->owner)->infrastructure.airport--;
2387 DirtyCompanyInfrastructureWindows(st->owner);
2388
2389 st->UpdateVirtCoord();
2390 st->RecomputeIndustriesNear();
2391 DeleteStationIfEmpty(st);
2392 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2393 }
2394
2395 return cost;
2396 }
2397
2407 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2408 {
2409 if (!Station::IsValidID(p1)) return CMD_ERROR;
2410 Station *st = Station::Get(p1);
2411
2412 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2413
2414 CommandCost ret = CheckOwnership(st->owner);
2415 if (ret.Failed()) return ret;
2416
2417 if (flags & DC_EXEC) {
2418 st->airport.flags ^= AIRPORT_CLOSED_block;
2419 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2420 }
2421 return CommandCost();
2422 }
2423
2430 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2431 {
2432 const Vehicle *v;
2433 FOR_ALL_VEHICLES(v) {
2434 if ((v->owner == company) == include_company) {
2435 const Order *order;
2436 FOR_VEHICLE_ORDERS(v, order) {
2437 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2438 return true;
2439 }
2440 }
2441 }
2442 }
2443 return false;
2444 }
2445
2446 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2447 {-1, 0},
2448 { 0, 0},
2449 { 0, 0},
2450 { 0, -1}
2451 };
2452 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2453 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2454
2464 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2465 {
2466 StationID station_to_join = GB(p2, 16, 16);
2467 bool reuse = (station_to_join != NEW_STATION);
2468 if (!reuse) station_to_join = INVALID_STATION;
2469 bool distant_join = (station_to_join != INVALID_STATION);
2470
2471 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2472
2473 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2474 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2475 direction = ReverseDiagDir(direction);
2476
2477 /* Docks cannot be placed on rapids */
2478 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2479
2480 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2481 if (ret.Failed()) return ret;
2482
2483 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2484
2485 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2486 if (ret.Failed()) return ret;
2487
2488 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2489
2490 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2491 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2492 }
2493
2494 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2495
2496 /* Get the water class of the water tile before it is cleared.*/
2497 WaterClass wc = GetWaterClass(tile_cur);
2498
2499 ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2500 if (ret.Failed()) return ret;
2501
2502 tile_cur += TileOffsByDiagDir(direction);
2503 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2504 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2505 }
2506
2507 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2508 _dock_w_chk[direction], _dock_h_chk[direction]);
2509
2510 /* middle */
2511 Station *st = NULL;
2512 ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
2513 if (ret.Failed()) return ret;
2514
2515 /* Distant join */
2516 if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
2517
2518 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2519 if (ret.Failed()) return ret;
2520
2521 if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
2522
2523 if (flags & DC_EXEC) {
2524 st->dock_tile = tile;
2525 st->AddFacility(FACIL_DOCK, tile);
2526
2527 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2528
2529 /* If the water part of the dock is on a canal, update infrastructure counts.
2530 * This is needed as we've unconditionally cleared that tile before. */
2531 if (wc == WATER_CLASS_CANAL) {
2532 Company::Get(st->owner)->infrastructure.water++;
2533 }
2534 Company::Get(st->owner)->infrastructure.station += 2;
2535 DirtyCompanyInfrastructureWindows(st->owner);
2536
2537 MakeDock(tile, st->owner, st->index, direction, wc);
2538
2539 st->UpdateVirtCoord();
2540 UpdateStationAcceptance(st, false);
2541 st->RecomputeIndustriesNear();
2542 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
2543 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
2544 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2545 }
2546
2547 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2548 }
2549
2556 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2557 {
2558 Station *st = Station::GetByTile(tile);
2559 CommandCost ret = CheckOwnership(st->owner);
2560 if (ret.Failed()) return ret;
2561
2562 TileIndex docking_location = TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
2563
2564 TileIndex tile1 = st->dock_tile;
2565 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2566
2567 ret = EnsureNoVehicleOnGround(tile1);
2568 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2569 if (ret.Failed()) return ret;
2570
2571 if (flags & DC_EXEC) {
2572 DoClearSquare(tile1);
2573 MarkTileDirtyByTile(tile1);
2574 MakeWaterKeepingClass(tile2, st->owner);
2575
2576 st->rect.AfterRemoveTile(st, tile1);
2577 st->rect.AfterRemoveTile(st, tile2);
2578
2579 st->dock_tile = INVALID_TILE;
2580 st->facilities &= ~FACIL_DOCK;
2581
2582 Company::Get(st->owner)->infrastructure.station -= 2;
2583 DirtyCompanyInfrastructureWindows(st->owner);
2584
2585 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_SHIPS);
2586 st->UpdateVirtCoord();
2587 st->RecomputeIndustriesNear();
2588 DeleteStationIfEmpty(st);
2589
2590 /* All ships that were going to our station, can't go to it anymore.
2591 * Just clear the order, then automatically the next appropriate order
2592 * will be selected and in case of no appropriate order it will just
2593 * wander around the world. */
2594 Ship *s;
2595 FOR_ALL_SHIPS(s) {
2596 if (s->current_order.IsType(OT_LOADING) && s->tile == docking_location) {
2597 s->LeaveStation();
2598 }
2599
2600 if (s->dest_tile == docking_location) {
2601 s->dest_tile = 0;
2602 s->current_order.Free();
2603 }
2604 }
2605 }
2606
2607 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2608 }
2609
2610 #include "table/station_land.h"
2611
2612 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2613 {
2614 return &_station_display_datas[st][gfx];
2615 }
2616
2626 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2627 {
2628 bool snow_desert;
2629 switch (*ground) {
2630 case SPR_RAIL_TRACK_X:
2631 snow_desert = false;
2632 *overlay_offset = RTO_X;
2633 break;
2634
2635 case SPR_RAIL_TRACK_Y:
2636 snow_desert = false;
2637 *overlay_offset = RTO_Y;
2638 break;
2639
2640 case SPR_RAIL_TRACK_X_SNOW:
2641 snow_desert = true;
2642 *overlay_offset = RTO_X;
2643 break;
2644
2645 case SPR_RAIL_TRACK_Y_SNOW:
2646 snow_desert = true;
2647 *overlay_offset = RTO_Y;
2648 break;
2649
2650 default:
2651 return false;
2652 }
2653
2654 if (ti != NULL) {
2655 /* Decide snow/desert from tile */
2656 switch (_settings_game.game_creation.landscape) {
2657 case LT_ARCTIC:
2658 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2659 break;
2660
2661 case LT_TROPIC:
2662 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2663 break;
2664
2665 default:
2666 break;
2667 }
2668 }
2669
2670 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2671 return true;
2672 }
2673
2674 static void DrawTile_Station(TileInfo *ti)
2675 {
2676 const NewGRFSpriteLayout *layout = NULL;
2677 DrawTileSprites tmp_rail_layout;
2678 const DrawTileSprites *t = NULL;
2679 RoadTypes roadtypes;
2680 int32 total_offset;
2681 const RailtypeInfo *rti = NULL;
2682 uint32 relocation = 0;
2683 uint32 ground_relocation = 0;
2684 BaseStation *st = NULL;
2685 const StationSpec *statspec = NULL;
2686 uint tile_layout = 0;
2687
2688 if (HasStationRail(ti->tile)) {
2689 rti = GetRailTypeInfo(GetRailType(ti->tile));
2690 roadtypes = ROADTYPES_NONE;
2691 total_offset = rti->GetRailtypeSpriteOffset();
2692
2693 if (IsCustomStationSpecIndex(ti->tile)) {
2694 /* look for customization */
2695 st = BaseStation::GetByTile(ti->tile);
2696 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2697
2698 if (statspec != NULL) {
2699 tile_layout = GetStationGfx(ti->tile);
2700
2701 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2702 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2703 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2704 }
2705
2706 /* Ensure the chosen tile layout is valid for this custom station */
2707 if (statspec->renderdata != NULL) {
2708 layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2709 if (!layout->NeedsPreprocessing()) {
2710 t = layout;
2711 layout = NULL;
2712 }
2713 }
2714 }
2715 }
2716 } else {
2717 roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
2718 total_offset = 0;
2719 }
2720
2721 StationGfx gfx = GetStationGfx(ti->tile);
2722 if (IsAirport(ti->tile)) {
2723 gfx = GetAirportGfx(ti->tile);
2724 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2725 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2726 if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2727 return;
2728 }
2729 /* No sprite group (or no valid one) found, meaning no graphics associated.
2730 * Use the substitute one instead */
2731 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2732 gfx = ats->grf_prop.subst_id;
2733 }
2734 switch (gfx) {
2735 case APT_RADAR_GRASS_FENCE_SW:
2736 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2737 break;
2738 case APT_GRASS_FENCE_NE_FLAG:
2739 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2740 break;
2741 case APT_RADAR_FENCE_SW:
2742 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2743 break;
2744 case APT_RADAR_FENCE_NE:
2745 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2746 break;
2747 case APT_GRASS_FENCE_NE_FLAG_2:
2748 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2749 break;
2750 }
2751 }
2752
2753 Owner owner = GetTileOwner(ti->tile);
2754
2755 PaletteID palette;
2756 if (Company::IsValidID(owner)) {
2757 palette = COMPANY_SPRITE_COLOUR(owner);
2758 } else {
2759 /* Some stations are not owner by a company, namely oil rigs */
2760 palette = PALETTE_TO_GREY;
2761 }
2762
2763 if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2764
2765 /* don't show foundation for docks */
2766 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2767 if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2768 /* Station has custom foundations.
2769 * Check whether the foundation continues beyond the tile's upper sides. */
2770 uint edge_info = 0;
2771 int z;
2772 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2773 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2774 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2775 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2776 if (image == 0) goto draw_default_foundation;
2777
2778 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2779 /* Station provides extended foundations. */
2780
2781 static const uint8 foundation_parts[] = {
2782 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2783 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2784 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2785 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2786 };
2787
2788 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2789 } else {
2790 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2791
2792 /* Each set bit represents one of the eight composite sprites to be drawn.
2793 * 'Invalid' entries will not drawn but are included for completeness. */
2794 static const uint8 composite_foundation_parts[] = {
2795 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2796 0x00, 0xD1, 0xE4, 0xE0,
2797 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2798 0xCA, 0xC9, 0xC4, 0xC0,
2799 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2800 0xD2, 0x91, 0xE4, 0xA0,
2801 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2802 0x4A, 0x09, 0x44
2803 };
2804
2805 uint8 parts = composite_foundation_parts[ti->tileh];
2806
2807 /* If foundations continue beyond the tile's upper sides then
2808 * mask out the last two pieces. */
2809 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2810 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2811
2812 if (parts == 0) {
2813 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2814 * correct offset for the childsprites.
2815 * So, draw the (completely empty) sprite of the default foundations. */
2816 goto draw_default_foundation;
2817 }
2818
2819 StartSpriteCombine();
2820 for (int i = 0; i < 8; i++) {
2821 if (HasBit(parts, i)) {
2822 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2823 }
2824 }
2825 EndSpriteCombine();
2826 }
2827
2828 OffsetGroundSprite(31, 1);
2829 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2830 } else {
2831 draw_default_foundation:
2832 DrawFoundation(ti, FOUNDATION_LEVELED);
2833 }
2834 }
2835
2836 if (IsBuoy(ti->tile)) {
2837 DrawWaterClassGround(ti);
2838 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2839 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2840 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2841 if (ti->tileh == SLOPE_FLAT) {
2842 DrawWaterClassGround(ti);
2843 } else {
2844 assert(IsDock(ti->tile));
2845 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2846 WaterClass wc = GetWaterClass(water_tile);
2847 if (wc == WATER_CLASS_SEA) {
2848 DrawShoreTile(ti->tileh);
2849 } else {
2850 DrawClearLandTile(ti, 3);
2851 }
2852 }
2853 } else {
2854 if (layout != NULL) {
2855 /* Sprite layout which needs preprocessing */
2856 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2857 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2858 uint8 var10;
2859 FOR_EACH_SET_BIT(var10, var10_values) {
2860 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2861 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2862 }
2863 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2864 t = &tmp_rail_layout;
2865 total_offset = 0;
2866 } else if (statspec != NULL) {
2867 /* Simple sprite layout */
2868 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2869 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2870 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2871 }
2872 ground_relocation += rti->fallback_railtype;
2873 }
2874
2875 SpriteID image = t->ground.sprite;
2876 PaletteID pal = t->ground.pal;
2877 RailTrackOffset overlay_offset;
2878 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2879 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2880 DrawGroundSprite(image, PAL_NONE);
2881 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2882
2883 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2884 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2885 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2886 }
2887 } else {
2888 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2889 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2890 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2891
2892 /* PBS debugging, draw reserved tracks darker */
2893 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2894 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2895 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
2896 }
2897 }
2898 }
2899
2900 if (HasStationRail(ti->tile) && HasCatenaryDrawn(GetRailType(ti->tile))) DrawCatenary(ti);
2901
2902 if (HasBit(roadtypes, ROADTYPE_TRAM)) {
2903 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
2904 DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
2905 DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
2906 }
2907
2908 if (IsRailWaypoint(ti->tile)) {
2909 /* Don't offset the waypoint graphics; they're always the same. */
2910 total_offset = 0;
2911 }
2912
2913 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
2914 }
2915
2916 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
2917 {
2918 int32 total_offset = 0;
2919 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
2920 const DrawTileSprites *t = GetStationTileLayout(st, image);
2921 const RailtypeInfo *rti = NULL;
2922
2923 if (railtype != INVALID_RAILTYPE) {
2924 rti = GetRailTypeInfo(railtype);
2925 total_offset = rti->GetRailtypeSpriteOffset();
2926 }
2927
2928 SpriteID img = t->ground.sprite;
2929 RailTrackOffset overlay_offset;
2930 if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
2931 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2932 DrawSprite(img, PAL_NONE, x, y);
2933 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
2934 } else {
2935 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
2936 }
2937
2938 if (roadtype == ROADTYPE_TRAM) {
2939 DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
2940 }
2941
2942 /* Default waypoint has no railtype specific sprites */
2943 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
2944 }
2945
2946 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
2947 {
2948 return GetTileMaxPixelZ(tile);
2949 }
2950
2951 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
2952 {
2953 return FlatteningFoundation(tileh);
2954 }
2955
2956 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
2957 {
2958 td->owner[0] = GetTileOwner(tile);
2959 if (IsDriveThroughStopTile(tile)) {
2960 Owner road_owner = INVALID_OWNER;
2961 Owner tram_owner = INVALID_OWNER;
2962 RoadTypes rts = GetRoadTypes(tile);
2963 if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
2964 if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
2965
2966 /* Is there a mix of owners? */
2967 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
2968 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
2969 uint i = 1;
2970 if (road_owner != INVALID_OWNER) {
2971 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
2972 td->owner[i] = road_owner;
2973 i++;
2974 }
2975 if (tram_owner != INVALID_OWNER) {
2976 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
2977 td->owner[i] = tram_owner;
2978 }
2979 }
2980 }
2981 td->build_date = BaseStation::GetByTile(tile)->build_date;
2982
2983 if (HasStationTileRail(tile)) {
2984 const StationSpec *spec = GetStationSpec(tile);
2985
2986 if (spec != NULL) {
2987 td->station_class = StationClass::Get(spec->cls_id)->name;
2988 td->station_name = spec->name;
2989
2990 if (spec->grf_prop.grffile != NULL) {
2991 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
2992 td->grf = gc->GetName();
2993 }
2994 }
2995
2996 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2997 td->rail_speed = rti->max_speed;
2998 }
2999
3000 if (IsAirport(tile)) {
3001 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3002 td->airport_class = AirportClass::Get(as->cls_id)->name;
3003 td->airport_name = as->name;
3004
3005 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3006 td->airport_tile_name = ats->name;
3007
3008 if (as->grf_prop.grffile != NULL) {
3009 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3010 td->grf = gc->GetName();
3011 } else if (ats->grf_prop.grffile != NULL) {
3012 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3013 td->grf = gc->GetName();
3014 }
3015 }
3016
3017 StringID str;
3018 switch (GetStationType(tile)) {
3019 default: NOT_REACHED();
3020 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3021 case STATION_AIRPORT:
3022 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3023 break;
3024 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3025 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3026 case STATION_OILRIG: str = STR_INDUSTRY_NAME_OIL_RIG; break;
3027 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3028 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3029 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3030 }
3031 td->str = str;
3032 }
3033
3034
3035 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3036 {
3037 TrackBits trackbits = TRACK_BIT_NONE;
3038
3039 switch (mode) {
3040 case TRANSPORT_RAIL:
3041 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3042 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3043 }
3044 break;
3045
3046 case TRANSPORT_WATER:
3047 /* buoy is coded as a station, it is always on open water */
3048 if (IsBuoy(tile)) {
3049 trackbits = TRACK_BIT_ALL;
3050 /* remove tracks that connect NE map edge */
3051 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3052 /* remove tracks that connect NW map edge */
3053 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3054 }
3055 break;
3056
3057 case TRANSPORT_ROAD:
3058 if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
3059 DiagDirection dir = GetRoadStopDir(tile);
3060 Axis axis = DiagDirToAxis(dir);
3061
3062 if (side != INVALID_DIAGDIR) {
3063 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
3064 }
3065
3066 trackbits = AxisToTrackBits(axis);
3067 }
3068 break;
3069
3070 default:
3071 break;
3072 }
3073
3074 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3075 }
3076
3077
3078 static void TileLoop_Station(TileIndex tile)
3079 {
3080 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3081 * hardcoded.....not good */
3082 switch (GetStationType(tile)) {
3083 case STATION_AIRPORT:
3084 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3085 break;
3086
3087 case STATION_DOCK:
3088 if (!IsTileFlat(tile)) break; // only handle water part
3089 /* FALL THROUGH */
3090 case STATION_OILRIG: //(station part)
3091 case STATION_BUOY:
3092 TileLoop_Water(tile);
3093 break;
3094
3095 default: break;
3096 }
3097 }
3098
3099
3100 static void AnimateTile_Station(TileIndex tile)
3101 {
3102 if (HasStationRail(tile)) {
3103 AnimateStationTile(tile);
3104 return;
3105 }
3106
3107 if (IsAirport(tile)) {
3108 AnimateAirportTile(tile);
3109 }
3110 }
3111
3112
3113 static bool ClickTile_Station(TileIndex tile)
3114 {
3115 const BaseStation *bst = BaseStation::GetByTile(tile);
3116
3117 if (bst->facilities & FACIL_WAYPOINT) {
3118 ShowWaypointWindow(Waypoint::From(bst));
3119 } else if (IsHangar(tile)) {
3120 const Station *st = Station::From(bst);
3121 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3122 } else {
3123 ShowStationViewWindow(bst->index);
3124 }
3125 return true;
3126 }
3127
3128 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3129 {
3130 if (v->type == VEH_TRAIN) {
3131 StationID station_id = GetStationIndex(tile);
3132 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3133 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3134
3135 int station_ahead;
3136 int station_length;
3137 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3138
3139 /* Stop whenever that amount of station ahead + the distance from the
3140 * begin of the platform to the stop location is longer than the length
3141 * of the platform. Station ahead 'includes' the current tile where the
3142 * vehicle is on, so we need to subtract that. */
3143 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3144
3145 DiagDirection dir = DirToDiagDir(v->direction);
3146
3147 x &= 0xF;
3148 y &= 0xF;
3149
3150 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3151 if (y == TILE_SIZE / 2) {
3152 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3153 stop &= TILE_SIZE - 1;
3154
3155 if (x == stop) {
3156 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3157 } else if (x < stop) {
3158 v->vehstatus |= VS_TRAIN_SLOWING;
3159 uint16 spd = max(0, (stop - x) * 20 - 15);
3160 if (spd < v->cur_speed) v->cur_speed = spd;
3161 }
3162 }
3163 } else if (v->type == VEH_ROAD) {
3164 RoadVehicle *rv = RoadVehicle::From(v);
3165 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3166 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3167 /* Attempt to allocate a parking bay in a road stop */
3168 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3169 }
3170 }
3171 }
3172
3173 return VETSB_CONTINUE;
3174 }
3175
3180 void TriggerWatchedCargoCallbacks(Station *st)
3181 {
3182 /* Collect cargoes accepted since the last big tick. */
3183 uint cargoes = 0;
3184 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3185 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3186 }
3187
3188 /* Anything to do? */
3189 if (cargoes == 0) return;
3190
3191 /* Loop over all houses in the catchment. */
3192 Rect r = st->GetCatchmentRect();
3193 TileArea ta(TileXY(r.left, r.top), TileXY(r.right, r.bottom));
3194 TILE_AREA_LOOP(tile, ta) {
3195 if (IsTileType(tile, MP_HOUSE)) {
3196 WatchedCargoCallback(tile, cargoes);
3197 }
3198 }
3199 }
3200
3207 static bool StationHandleBigTick(BaseStation *st)
3208 {
3209 if (!st->IsInUse()) {
3210 if (++st->delete_ctr >= 8) delete st;
3211 return false;
3212 }
3213
3214 if (Station::IsExpected(st)) {
3215 TriggerWatchedCargoCallbacks(Station::From(st));
3216
3217 for (CargoID i = 0; i < NUM_CARGO; i++) {
3218 ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3219 }
3220 }
3221
3222
3223 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3224
3225 return true;
3226 }
3227
3228 static inline void byte_inc_sat(byte *p)
3229 {
3230 byte b = *p + 1;
3231 if (b != 0) *p = b;
3232 }
3233
3240 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3241 {
3242 /* If truncating also punish the source stations' ratings to
3243 * decrease the flow of incoming cargo. */
3244
3245 StationCargoAmountMap waiting_per_source;
3246 ge->cargo.Truncate(amount, &waiting_per_source);
3247 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3248 Station *source_station = Station::GetIfValid(i->first);
3249 if (source_station == NULL) continue;
3250
3251 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3252 source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
3253 }
3254 }
3255
3256 static void UpdateStationRating(Station *st)
3257 {
3258 bool waiting_changed = false;
3259
3260 byte_inc_sat(&st->time_since_load);
3261 byte_inc_sat(&st->time_since_unload);
3262
3263 const CargoSpec *cs;
3264 FOR_ALL_CARGOSPECS(cs) {
3265 GoodsEntry *ge = &st->goods[cs->Index()];
3266 /* Slowly increase the rating back to his original level in the case we
3267 * didn't deliver cargo yet to this station. This happens when a bribe
3268 * failed while you didn't moved that cargo yet to a station. */
3269 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3270 ge->rating++;
3271 }
3272
3273 /* Only change the rating if we are moving this cargo */
3274 if (ge->HasRating()) {
3275 byte_inc_sat(&ge->time_since_pickup);
3276 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3277 ClrBit(ge->status, GoodsEntry::GES_RATING);
3278 ge->last_speed = 0;
3279 TruncateCargo(cs, ge);
3280 waiting_changed = true;
3281 continue;
3282 }
3283
3284 bool skip = false;
3285 int rating = 0;
3286 uint waiting = ge->cargo.AvailableCount();
3287
3288 /* num_dests is at least 1 if there is any cargo as
3289 * INVALID_STATION is also a destination.
3290 */
3291 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3292
3293 /* Average amount of cargo per next hop, but prefer solitary stations
3294 * with only one or two next hops. They are allowed to have more
3295 * cargo waiting per next hop.
3296 * With manual cargo distribution waiting_avg = waiting / 2 as then
3297 * INVALID_STATION is the only destination.
3298 */
3299 uint waiting_avg = waiting / (num_dests + 1);
3300
3301 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3302 /* Perform custom station rating. If it succeeds the speed, days in transit and
3303 * waiting cargo ratings must not be executed. */
3304
3305 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3306 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3307
3308 uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
3309 /* Convert to the 'old' vehicle types */
3310 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3311 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3312 if (callback != CALLBACK_FAILED) {
3313 skip = true;
3314 rating = GB(callback, 0, 14);
3315
3316 /* Simulate a 15 bit signed value */
3317 if (HasBit(callback, 14)) rating -= 0x4000;
3318 }
3319 }
3320
3321 if (!skip) {
3322 int b = ge->last_speed - 85;
3323 if (b >= 0) rating += b >> 2;
3324
3325 byte waittime = ge->time_since_pickup;
3326 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3327 (waittime > 21) ||
3328 (rating += 25, waittime > 12) ||
3329 (rating += 25, waittime > 6) ||
3330 (rating += 45, waittime > 3) ||
3331 (rating += 35, true);
3332
3333 (rating -= 90, ge->max_waiting_cargo > 1500) ||
3334 (rating += 55, ge->max_waiting_cargo > 1000) ||
3335 (rating += 35, ge->max_waiting_cargo > 600) ||
3336 (rating += 10, ge->max_waiting_cargo > 300) ||
3337 (rating += 20, ge->max_waiting_cargo > 100) ||
3338 (rating += 10, true);
3339 }
3340
3341 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3342
3343 byte age = ge->last_age;
3344 (age >= 3) ||
3345 (rating += 10, age >= 2) ||
3346 (rating += 10, age >= 1) ||
3347 (rating += 13, true);
3348
3349 {
3350 int or_ = ge->rating; // old rating
3351
3352 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3353 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3354
3355 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3356 * remove some random amount of goods from the station */
3357 if (rating <= 64 && waiting_avg >= 100) {
3358 int dec = Random() & 0x1F;
3359 if (waiting_avg < 200) dec &= 7;
3360 waiting -= (dec + 1) * num_dests;
3361 waiting_changed = true;
3362 }
3363
3364 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3365 if (rating <= 127 && waiting != 0) {
3366 uint32 r = Random();
3367 if (rating <= (int)GB(r, 0, 7)) {
3368 /* Need to have int, otherwise it will just overflow etc. */
3369 waiting = max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3370 waiting_changed = true;
3371 }
3372 }
3373
3374 /* At some point we really must cap the cargo. Previously this
3375 * was a strict 4095, but now we'll have a less strict, but
3376 * increasingly aggressive truncation of the amount of cargo. */
3377 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3378 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3379 static const uint MAX_WAITING_CARGO = 1 << 15;
3380
3381 if (waiting > WAITING_CARGO_THRESHOLD) {
3382 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3383 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3384
3385 waiting = min(waiting, MAX_WAITING_CARGO);
3386 waiting_changed = true;
3387 }
3388
3389 /* We can't truncate cargo that's already reserved for loading.
3390 * Thus StoredCount() here. */
3391 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3392 /* Feed back the exact own waiting cargo at this station for the
3393 * next rating calculation. */
3394 ge->max_waiting_cargo = 0;
3395
3396 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3397 } else {
3398 /* If the average number per next hop is low, be more forgiving. */
3399 ge->max_waiting_cargo = waiting_avg;
3400 }
3401 }
3402 }
3403 }
3404
3405 StationID index = st->index;
3406 if (waiting_changed) {
3407 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3408 } else {
3409 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3410 }
3411 }
3412
3421 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3422 {
3423 GoodsEntry &ge = st->goods[c];
3424
3425 /* Reroute cargo in station. */
3426 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3427
3428 /* Reroute cargo staged to be transfered. */
3429 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3430 for (Vehicle *v = *it; v != NULL; v = v->Next()) {
3431 if (v->cargo_type != c) continue;
3432 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3433 }
3434 }
3435 }
3436
3445 void DeleteStaleLinks(Station *from)
3446 {
3447 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3448 GoodsEntry &ge = from->goods[c];
3449 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3450 if (lg == NULL) continue;
3451 Node node = (*lg)[ge.node];
3452 for (EdgeIterator it(node.Begin()); it != node.End();) {
3453 Edge edge = it->second;
3454 Station *to = Station::Get((*lg)[it->first].Station());
3455 assert(to->goods[c].node == it->first);
3456 ++it; // Do that before removing the edge. Anything else may crash.
3457 assert(_date >= edge.LastUpdate());
3458 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3459 if ((uint)(_date - edge.LastUpdate()) > timeout) {
3460 /* Have all vehicles refresh their next hops before deciding to
3461 * remove the node. */
3462 bool updated = false;
3463 OrderList *l;
3464 FOR_ALL_ORDER_LISTS(l) {
3465 bool found_from = false;
3466 bool found_to = false;
3467 for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
3468 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3469 if (order->GetDestination() == from->index) {
3470 found_from = true;
3471 if (found_to) break;
3472 } else if (order->GetDestination() == to->index) {
3473 found_to = true;
3474 if (found_from) break;
3475 }
3476 }
3477 if (!found_to || !found_from) continue;
3478 for (Vehicle *v = l->GetFirstSharedVehicle(); !updated && v != NULL; v = v->NextShared()) {
3479 /* There is potential for optimization here:
3480 * - Usually consists of the same order list are the same. It's probably better to
3481 * first check the first of each list, then the second of each list and so on.
3482 * - We could try to figure out if we've seen a consist with the same cargo on the
3483 * same list already and if the consist can actually carry the cargo we're looking
3484 * for. With conditional and refit orders this is not quite trivial, though. */
3485 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3486 if (edge.LastUpdate() == _date) updated = true;
3487 }
3488 if (updated) break;
3489 }
3490 if (!updated) {
3491 /* If it's still considered dead remove it. */
3492 node.RemoveEdge(to->goods[c].node);
3493 ge.flows.DeleteFlows(to->index);
3494 RerouteCargo(from, c, to->index, from->index);
3495 }
3496 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3497 edge.Restrict();
3498 ge.flows.RestrictFlows(to->index);
3499 RerouteCargo(from, c, to->index, from->index);
3500 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3501 edge.Release();
3502 }
3503 }
3504 assert(_date >= lg->LastCompression());
3505 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3506 lg->Compress();
3507 }
3508 }
3509 }
3510
3520 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, EdgeUpdateMode mode)
3521 {
3522 GoodsEntry &ge1 = st->goods[cargo];
3523 Station *st2 = Station::Get(next_station_id);
3524 GoodsEntry &ge2 = st2->goods[cargo];
3525 LinkGraph *lg = NULL;
3526 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3527 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3528 if (LinkGraph::CanAllocateItem()) {
3529 lg = new LinkGraph(cargo);
3530 LinkGraphSchedule::instance.Queue(lg);
3531 ge2.link_graph = lg->index;
3532 ge2.node = lg->AddNode(st2);
3533 } else {
3534 DEBUG(misc, 0, "Can't allocate link graph");
3535 }
3536 } else {
3537 lg = LinkGraph::Get(ge2.link_graph);
3538 }
3539 if (lg) {
3540 ge1.link_graph = lg->index;
3541 ge1.node = lg->AddNode(st);
3542 }
3543 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3544 lg = LinkGraph::Get(ge1.link_graph);
3545 ge2.link_graph = lg->index;
3546 ge2.node = lg->AddNode(st2);
3547 } else {
3548 lg = LinkGraph::Get(ge1.link_graph);
3549 if (ge1.link_graph != ge2.link_graph) {
3550 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3551 if (lg->Size() < lg2->Size()) {
3552 LinkGraphSchedule::instance.Unqueue(lg);
3553 lg2->Merge(lg); // Updates GoodsEntries of lg
3554 lg = lg2;
3555 } else {
3556 LinkGraphSchedule::instance.Unqueue(lg2);
3557 lg->Merge(lg2); // Updates GoodsEntries of lg2
3558 }
3559 }
3560 }
3561 if (lg != NULL) {
3562 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, mode);
3563 }
3564 }
3565
3572 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
3573 {
3574 for (const Vehicle *v = front; v != NULL; v = v->Next()) {
3575 if (v->refit_cap > 0) {
3576 /* The cargo count can indeed be higher than the refit_cap if
3577 * wagons have been auto-replaced and subsequently auto-
3578 * refitted to a higher capacity. The cargo gets redistributed
3579 * among the wagons in that case.
3580 * As usage is not such an important figure anyway we just
3581 * ignore the additional cargo then.*/
3582 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3583 min(v->refit_cap, v->cargo.StoredCount()), EUM_INCREASE);
3584 }
3585 }
3586 }
3587
3588 /* called for every station each tick */
3589 static void StationHandleSmallTick(BaseStation *st)
3590 {
3591 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3592
3593 byte b = st->delete_ctr + 1;
3594 if (b >= STATION_RATING_TICKS) b = 0;
3595 st->delete_ctr = b;
3596
3597 if (b == 0) UpdateStationRating(Station::From(st));
3598 }
3599
3600 void OnTick_Station()
3601 {
3602 if (_game_mode == GM_EDITOR) return;
3603
3604 BaseStation *st;
3605 FOR_ALL_BASE_STATIONS(st) {
3606 StationHandleSmallTick(st);
3607
3608 /* Clean up the link graph about once a week. */
3609 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3610 DeleteStaleLinks(Station::From(st));
3611 };
3612
3613 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3614 * Station index is included so that triggers are not all done
3615 * at the same time. */
3616 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3617 /* Stop processing this station if it was deleted */
3618 if (!StationHandleBigTick(st)) continue;
3619 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3620 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3621 }
3622 }
3623 }
3624
3626 void StationMonthlyLoop()
3627 {
3628 Station *st;
3629
3630 FOR_ALL_STATIONS(st) {
3631 for (CargoID i = 0; i < NUM_CARGO; i++) {
3632 GoodsEntry *ge = &st->goods[i];
3633 SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3634 ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3635 }
3636 }
3637 }
3638
3639
3640 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3641 {
3642 Station *st;
3643
3644 FOR_ALL_STATIONS(st) {
3645 if (st->owner == owner &&
3646 DistanceManhattan(tile, st->xy) <= radius) {
3647 for (CargoID i = 0; i < NUM_CARGO; i++) {
3648 GoodsEntry *ge = &st->goods[i];
3649
3650 if (ge->status != 0) {
3651 ge->rating = Clamp(ge->rating + amount, 0, 255);
3652 }
3653 }
3654 }
3655 }
3656 }
3657
3658 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3659 {
3660 /* We can't allocate a CargoPacket? Then don't do anything
3661 * at all; i.e. just discard the incoming cargo. */
3662 if (!CargoPacket::CanAllocateItem()) return 0;
3663
3664 GoodsEntry &ge = st->goods[type];
3665 amount += ge.amount_fract;
3666 ge.amount_fract = GB(amount, 0, 8);
3667
3668 amount >>= 8;
3669 /* No new "real" cargo item yet. */
3670 if (amount == 0) return 0;
3671
3672 StationID next = ge.GetVia(st->index);
3673 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3674 LinkGraph *lg = NULL;
3675 if (ge.link_graph == INVALID_LINK_GRAPH) {
3676 if (LinkGraph::CanAllocateItem()) {
3677 lg = new LinkGraph(type);
3678 LinkGraphSchedule::instance.Queue(lg);
3679 ge.link_graph = lg->index;
3680 ge.node = lg->AddNode(st);
3681 } else {
3682 DEBUG(misc, 0, "Can't allocate link graph");
3683 }
3684 } else {
3685 lg = LinkGraph::Get(ge.link_graph);
3686 }
3687 if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
3688
3689 if (!ge.HasRating()) {
3690 InvalidateWindowData(WC_STATION_LIST, st->index);
3691 SetBit(ge.status, GoodsEntry::GES_RATING);
3692 }
3693
3694 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3695 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3696 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3697
3698 SetWindowDirty(WC_STATION_VIEW, st->index);
3699 st->MarkTilesDirty(true);
3700 return amount;
3701 }
3702
3703 static bool IsUniqueStationName(const char *name)
3704 {
3705 const Station *st;
3706
3707 FOR_ALL_STATIONS(st) {
3708 if (st->name != NULL && strcmp(st->name, name) == 0) return false;
3709 }
3710
3711 return true;
3712 }
3713
3723 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3724 {
3725 Station *st = Station::GetIfValid(p1);
3726 if (st == NULL) return CMD_ERROR;
3727
3728 CommandCost ret = CheckOwnership(st->owner);
3729 if (ret.Failed()) return ret;
3730
3731 bool reset = StrEmpty(text);
3732
3733 if (!reset) {
3734 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3735 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3736 }
3737
3738 if (flags & DC_EXEC) {
3739 free(st->name);
3740 st->name = reset ? NULL : stredup(text);
3741
3742 st->UpdateVirtCoord();
3743 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3744 }
3745
3746 return CommandCost();
3747 }
3748
3755 void FindStationsAroundTiles(const TileArea &location, StationList *stations)
3756 {
3757 /* area to search = producer plus station catchment radius */
3758 uint max_rad = (_settings_game.station.modified_catchment ? MAX_CATCHMENT : CA_UNMODIFIED);
3759
3760 uint x = TileX(location.tile);
3761 uint y = TileY(location.tile);
3762
3763 uint min_x = (x > max_rad) ? x - max_rad : 0;
3764 uint max_x = x + location.w + max_rad;
3765 uint min_y = (y > max_rad) ? y - max_rad : 0;
3766 uint max_y = y + location.h + max_rad;
3767
3768 if (min_x == 0 && _settings_game.construction.freeform_edges) min_x = 1;
3769 if (min_y == 0 && _settings_game.construction.freeform_edges) min_y = 1;
3770 if (max_x >= MapSizeX()) max_x = MapSizeX() - 1;
3771 if (max_y >= MapSizeY()) max_y = MapSizeY() - 1;
3772
3773 for (uint cy = min_y; cy < max_y; cy++) {
3774 for (uint cx = min_x; cx < max_x; cx++) {
3775 TileIndex cur_tile = TileXY(cx, cy);
3776 if (!IsTileType(cur_tile, MP_STATION)) continue;
3777
3778 Station *st = Station::GetByTile(cur_tile);
3779 /* st can be NULL in case of waypoints */
3780 if (st == NULL) continue;
3781
3782 if (_settings_game.station.modified_catchment) {
3783 int rad = st->GetCatchmentRadius();
3784 int rad_x = cx - x;
3785 int rad_y = cy - y;
3786
3787 if (rad_x < -rad || rad_x >= rad + location.w) continue;
3788 if (rad_y < -rad || rad_y >= rad + location.h) continue;
3789 }
3790
3791 /* Insert the station in the set. This will fail if it has
3792 * already been added.
3793 */
3794 stations->Include(st);
3795 }
3796 }
3797 }
3798
3803 const StationList *StationFinder::GetStations()
3804 {
3805 if (this->tile != INVALID_TILE) {
3806 FindStationsAroundTiles(*this, &this->stations);
3807 this->tile = INVALID_TILE;
3808 }
3809 return &this->stations;
3810 }
3811
3812 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations)
3813 {
3814 /* Return if nothing to do. Also the rounding below fails for 0. */
3815 if (amount == 0) return 0;
3816
3817 Station *st1 = NULL; // Station with best rating
3818 Station *st2 = NULL; // Second best station
3819 uint best_rating1 = 0; // rating of st1
3820 uint best_rating2 = 0; // rating of st2
3821
3822 for (Station * const *st_iter = all_stations->Begin(); st_iter != all_stations->End(); ++st_iter) {
3823 Station *st = *st_iter;
3824
3825 /* Is the station reserved exclusively for somebody else? */
3826 if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;
3827
3828 if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore
3829
3830 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
3831
3832 if (IsCargoInClass(type, CC_PASSENGERS)) {
3833 if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
3834 } else {
3835 if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
3836 }
3837
3838 /* This station can be used, add it to st1/st2 */
3839 if (st1 == NULL || st->goods[type].rating >= best_rating1) {
3840 st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
3841 } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
3842 st2 = st; best_rating2 = st->goods[type].rating;
3843 }
3844 }
3845
3846 /* no stations around at all? */
3847 if (st1 == NULL) return 0;
3848
3849 /* From now we'll calculate with fractal cargo amounts.
3850 * First determine how much cargo we really have. */
3851 amount *= best_rating1 + 1;
3852
3853 if (st2 == NULL) {
3854 /* only one station around */
3855 return UpdateStationWaiting(st1, type, amount, source_type, source_id);
3856 }
3857
3858 /* several stations around, the best two (highest rating) are in st1 and st2 */
3859 assert(st1 != NULL);
3860 assert(st2 != NULL);
3861 assert(best_rating1 != 0 || best_rating2 != 0);
3862
3863 /* Then determine the amount the worst station gets. We do it this way as the
3864 * best should get a bonus, which in this case is the rounding difference from
3865 * this calculation. In reality that will mean the bonus will be pretty low.
3866 * Nevertheless, the best station should always get the most cargo regardless
3867 * of rounding issues. */
3868 uint worst_cargo = amount * best_rating2 / (best_rating1 + best_rating2);
3869 assert(worst_cargo <= (amount - worst_cargo));
3870
3871 /* And then send the cargo to the stations! */
3872 uint moved = UpdateStationWaiting(st1, type, amount - worst_cargo, source_type, source_id);
3873 /* These two UpdateStationWaiting's can't be in the statement as then the order
3874 * of execution would be undefined and that could cause desyncs with callbacks. */
3875 return moved + UpdateStationWaiting(st2, type, worst_cargo, source_type, source_id);
3876 }
3877
3878 void BuildOilRig(TileIndex tile)
3879 {
3880 if (!Station::CanAllocateItem()) {
3881 DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
3882 return;
3883 }
3884
3885 Station *st = new Station(tile);
3886 st->town = ClosestTownFromTile(tile, UINT_MAX);
3887
3888 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
3889
3890 assert(IsTileType(tile, MP_INDUSTRY));
3891 DeleteAnimatedTile(tile);
3892 MakeOilrig(tile, st->index, GetWaterClass(tile));
3893
3894 st->owner = OWNER_NONE;
3895 st->airport.type = AT_OILRIG;
3896 st->airport.Add(tile);
3897 st->dock_tile = tile;
3898 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
3899 st->build_date = _date;
3900
3901 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
3902
3903 st->UpdateVirtCoord();
3904 UpdateStationAcceptance(st, false);
3905 st->RecomputeIndustriesNear();
3906 }
3907
3908 void DeleteOilRig(TileIndex tile)
3909 {
3910 Station *st = Station::GetByTile(tile);
3911
3912 MakeWaterKeepingClass(tile, OWNER_NONE);
3913
3914 st->dock_tile = INVALID_TILE;
3915 st->airport.Clear();
3916 st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
3917 st->airport.flags = 0;
3918
3919 st->rect.AfterRemoveTile(st, tile);
3920
3921 st->UpdateVirtCoord();
3922 st->RecomputeIndustriesNear();
3923 if (!st->IsInUse()) delete st;
3924 }
3925
3926 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
3927 {
3928 if (IsRoadStopTile(tile)) {
3929 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
3930 /* Update all roadtypes, no matter if they are present */
3931 if (GetRoadOwner(tile, rt) == old_owner) {
3932 if (HasTileRoadType(tile, rt)) {
3933 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
3934 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
3935 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
3936 }
3937 SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
3938 }
3939 }
3940 }
3941
3942 if (!IsTileOwner(tile, old_owner)) return;
3943
3944 if (new_owner != INVALID_OWNER) {
3945 /* Update company infrastructure counts. Only do it here
3946 * if the new owner is valid as otherwise the clear
3947 * command will do it for us. No need to dirty windows
3948 * here, we'll redraw the whole screen anyway.*/
3949 Company *old_company = Company::Get(old_owner);
3950 Company *new_company = Company::Get(new_owner);
3951
3952 /* Update counts for underlying infrastructure. */
3953 switch (GetStationType(tile)) {
3954 case STATION_RAIL:
3955 case STATION_WAYPOINT:
3956 if (!IsStationTileBlocked(tile)) {
3957 old_company->infrastructure.rail[GetRailType(tile)]--;
3958 new_company->infrastructure.rail[GetRailType(tile)]++;
3959 }
3960 break;
3961
3962 case STATION_BUS:
3963 case STATION_TRUCK:
3964 /* Road stops were already handled above. */
3965 break;
3966
3967 case STATION_BUOY:
3968 case STATION_DOCK:
3969 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
3970 old_company->infrastructure.water--;
3971 new_company->infrastructure.water++;
3972 }
3973 break;
3974
3975 default:
3976 break;
3977 }
3978
3979 /* Update station tile count. */
3980 if (!IsBuoy(tile) && !IsAirport(tile)) {
3981 old_company->infrastructure.station--;
3982 new_company->infrastructure.station++;
3983 }
3984
3985 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
3986 SetTileOwner(tile, new_owner);
3987 InvalidateWindowClassesData(WC_STATION_LIST, 0);
3988 } else {
3989 if (IsDriveThroughStopTile(tile)) {
3990 /* Remove the drive-through road stop */
3991 DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
3992 assert(IsTileType(tile, MP_ROAD));
3993 /* Change owner of tile and all roadtypes */
3994 ChangeTileOwner(tile, old_owner, new_owner);
3995 } else {
3996 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
3997 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
3998 * Update owner of buoy if it was not removed (was in orders).
3999 * Do not update when owned by OWNER_WATER (sea and rivers). */
4000 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4001 }
4002 }
4003 }
4004
4013 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4014 {
4015 /* Yeah... water can always remove stops, right? */
4016 if (_current_company == OWNER_WATER) return true;
4017
4018 RoadTypes rts = GetRoadTypes(tile);
4019 if (HasBit(rts, ROADTYPE_TRAM)) {
4020 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
4021 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4022 }
4023 if (HasBit(rts, ROADTYPE_ROAD)) {
4024 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
4025 if (road_owner != OWNER_TOWN) {
4026 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4027 } else {
4028 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, ROADTYPE_ROAD, flags).Failed()) return false;
4029 }
4030 }
4031
4032 return true;
4033 }
4034
4041 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4042 {
4043 if (flags & DC_AUTO) {
4044 switch (GetStationType(tile)) {
4045 default: break;
4046 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4047 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4048 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4049 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);
4050 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);
4051 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4052 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4053 case STATION_OILRIG:
4054 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4055 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4056 }
4057 }
4058
4059 switch (GetStationType(tile)) {
4060 case STATION_RAIL: return RemoveRailStation(tile, flags);
4061 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4062 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4063 case STATION_TRUCK:
4064 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4065 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4066 }
4067 return RemoveRoadStop(tile, flags);
4068 case STATION_BUS:
4069 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4070 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4071 }
4072 return RemoveRoadStop(tile, flags);
4073 case STATION_BUOY: return RemoveBuoy(tile, flags);
4074 case STATION_DOCK: return RemoveDock(tile, flags);
4075 default: break;
4076 }
4077
4078 return CMD_ERROR;
4079 }
4080
4081 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4082 {
4083 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4084 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4085 * TTDP does not call it.
4086 */
4087 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4088 switch (GetStationType(tile)) {
4089 case STATION_WAYPOINT:
4090 case STATION_RAIL: {
4091 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4092 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4093 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4094 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4095 }
4096
4097 case STATION_AIRPORT:
4098 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4099
4100 case STATION_TRUCK:
4101 case STATION_BUS: {
4102 DiagDirection direction = GetRoadStopDir(tile);
4103 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4104 if (IsDriveThroughStopTile(tile)) {
4105 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4106 }
4107 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4108 }
4109
4110 default: break;
4111 }
4112 }
4113 }
4114 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4115 }
4116
4122 uint FlowStat::GetShare(StationID st) const
4123 {
4124 uint32 prev = 0;
4125 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4126 if (it->second == st) {
4127 return it->first - prev;
4128 } else {
4129 prev = it->first;
4130 }
4131 }
4132 return 0;
4133 }
4134
4141 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4142 {
4143 if (this->unrestricted == 0) return INVALID_STATION;
4144 assert(!this->shares.empty());
4145 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4146 assert(it != this->shares.end() && it->first <= this->unrestricted);
4147 if (it->second != excluded && it->second != excluded2) return it->second;
4148
4149 /* We've hit one of the excluded stations.
4150 * Draw another share, from outside its range. */
4151
4152 uint end = it->first;
4153 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4154 uint interval = end - begin;
4155 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4156 uint new_max = this->unrestricted - interval;
4157 uint rand = RandomRange(new_max);
4158 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4159 this->shares.upper_bound(rand + interval);
4160 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4161 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4162
4163 /* We've hit the second excluded station.
4164 * Same as before, only a bit more complicated. */
4165
4166 uint end2 = it2->first;
4167 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4168 uint interval2 = end2 - begin2;
4169 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4170 new_max -= interval2;
4171 if (begin > begin2) {
4172 Swap(begin, begin2);
4173 Swap(end, end2);
4174 Swap(interval, interval2);
4175 }
4176 rand = RandomRange(new_max);
4177 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4178 if (rand < begin) {
4179 it3 = this->shares.upper_bound(rand);
4180 } else if (rand < begin2 - interval) {
4181 it3 = this->shares.upper_bound(rand + interval);
4182 } else {
4183 it3 = this->shares.upper_bound(rand + interval + interval2);
4184 }
4185 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4186 return it3->second;
4187 }
4188
4194 void FlowStat::Invalidate()
4195 {
4196 assert(!this->shares.empty());
4197 SharesMap new_shares;
4198 uint i = 0;
4199 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4200 new_shares[++i] = it->second;
4201 if (it->first == this->unrestricted) this->unrestricted = i;
4202 }
4203 this->shares.swap(new_shares);
4204 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4205 }
4206
4213 void FlowStat::ChangeShare(StationID st, int flow)
4214 {
4215 /* We assert only before changing as afterwards the shares can actually
4216 * be empty. In that case the whole flow stat must be deleted then. */
4217 assert(!this->shares.empty());
4218
4219 uint removed_shares = 0;
4220 uint added_shares = 0;
4221 uint last_share = 0;
4222 SharesMap new_shares;
4223 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4224 if (it->second == st) {
4225 if (flow < 0) {
4226 uint share = it->first - last_share;
4227 if (flow == INT_MIN || (uint)(-flow) >= share) {
4228 removed_shares += share;
4229 if (it->first <= this->unrestricted) this->unrestricted -= share;
4230 if (flow != INT_MIN) flow += share;
4231 last_share = it->first;
4232 continue; // remove the whole share
4233 }
4234 removed_shares += (uint)(-flow);
4235 } else {
4236 added_shares += (uint)(flow);
4237 }
4238 if (it->first <= this->unrestricted) this->unrestricted += flow;
4239
4240 /* If we don't continue above the whole flow has been added or
4241 * removed. */
4242 flow = 0;
4243 }
4244 new_shares[it->first + added_shares - removed_shares] = it->second;
4245 last_share = it->first;
4246 }
4247 if (flow > 0) {
4248 new_shares[last_share + (uint)flow] = st;
4249 if (this->unrestricted < last_share) {
4250 this->ReleaseShare(st);
4251 } else {
4252 this->unrestricted += flow;
4253 }
4254 }
4255 this->shares.swap(new_shares);
4256 }
4257
4263 void FlowStat::RestrictShare(StationID st)
4264 {
4265 assert(!this->shares.empty());
4266 uint flow = 0;
4267 uint last_share = 0;
4268 SharesMap new_shares;
4269 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4270 if (flow == 0) {
4271 if (it->first > this->unrestricted) return; // Not present or already restricted.
4272 if (it->second == st) {
4273 flow = it->first - last_share;
4274 this->unrestricted -= flow;
4275 } else {
4276 new_shares[it->first] = it->second;
4277 }
4278 } else {
4279 new_shares[it->first - flow] = it->second;
4280 }
4281 last_share = it->first;
4282 }
4283 if (flow == 0) return;
4284 new_shares[last_share + flow] = st;
4285 this->shares.swap(new_shares);
4286 assert(!this->shares.empty());
4287 }
4288
4294 void FlowStat::ReleaseShare(StationID st)
4295 {
4296 assert(!this->shares.empty());
4297 uint flow = 0;
4298 uint next_share = 0;
4299 bool found = false;
4300 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4301 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4302 if (found) {
4303 flow = next_share - it->first;
4304 this->unrestricted += flow;
4305 break;
4306 } else {
4307 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4308 if (it->second == st) found = true;
4309 }
4310 next_share = it->first;
4311 }
4312 if (flow == 0) return;
4313 SharesMap new_shares;
4314 new_shares[flow] = st;
4315 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4316 if (it->second != st) {
4317 new_shares[flow + it->first] = it->second;
4318 } else {
4319 flow = 0;
4320 }
4321 }
4322 this->shares.swap(new_shares);
4323 assert(!this->shares.empty());
4324 }
4325
4331 void FlowStat::ScaleToMonthly(uint runtime)
4332 {
4333 assert(runtime > 0);
4334 SharesMap new_shares;
4335 uint share = 0;
4336 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4337 share = max(share + 1, i->first * 30 / runtime);
4338 new_shares[share] = i->second;
4339 if (this->unrestricted == i->first) this->unrestricted = share;
4340 }
4341 this->shares.swap(new_shares);
4342 }
4343
4350 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4351 {
4352 FlowStatMap::iterator origin_it = this->find(origin);
4353 if (origin_it == this->end()) {
4354 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4355 } else {
4356 origin_it->second.ChangeShare(via, flow);
4357 assert(!origin_it->second.GetShares()->empty());
4358 }
4359 }
4360
4369 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4370 {
4371 FlowStatMap::iterator prev_it = this->find(origin);
4372 if (prev_it == this->end()) {
4373 FlowStat fs(via, flow);
4374 fs.AppendShare(INVALID_STATION, flow);
4375 this->insert(std::make_pair(origin, fs));
4376 } else {
4377 prev_it->second.ChangeShare(via, flow);
4378 prev_it->second.ChangeShare(INVALID_STATION, flow);
4379 assert(!prev_it->second.GetShares()->empty());
4380 }
4381 }
4382
4387 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4388 {
4389 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4390 FlowStat &fs = i->second;
4391 uint local = fs.GetShare(INVALID_STATION);
4392 if (local > INT_MAX) { // make sure it fits in an int
4393 fs.ChangeShare(self, -INT_MAX);
4394 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4395 local -= INT_MAX;
4396 }
4397 fs.ChangeShare(self, -(int)local);
4398 fs.ChangeShare(INVALID_STATION, -(int)local);
4399
4400 /* If the local share is used up there must be a share for some
4401 * remote station. */
4402 assert(!fs.GetShares()->empty());
4403 }
4404 }
4405
4412 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4413 {
4414 StationIDStack ret;
4415 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4416 FlowStat &s_flows = f_it->second;
4417 s_flows.ChangeShare(via, INT_MIN);
4418 if (s_flows.GetShares()->empty()) {
4419 ret.Push(f_it->first);
4420 this->erase(f_it++);
4421 } else {
4422 ++f_it;
4423 }
4424 }
4425 return ret;
4426 }
4427
4432 void FlowStatMap::RestrictFlows(StationID via)
4433 {
4434 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4435 it->second.RestrictShare(via);
4436 }
4437 }
4438
4443 void FlowStatMap::ReleaseFlows(StationID via)
4444 {
4445 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4446 it->second.ReleaseShare(via);
4447 }
4448 }
4449
4454 uint FlowStatMap::GetFlow() const
4455 {
4456 uint ret = 0;
4457 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4458 ret += (--(i->second.GetShares()->end()))->first;
4459 }
4460 return ret;
4461 }
4462
4468 uint FlowStatMap::GetFlowVia(StationID via) const
4469 {
4470 uint ret = 0;
4471 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4472 ret += i->second.GetShare(via);
4473 }
4474 return ret;
4475 }
4476
4482 uint FlowStatMap::GetFlowFrom(StationID from) const
4483 {
4484 FlowStatMap::const_iterator i = this->find(from);
4485 if (i == this->end()) return 0;
4486 return (--(i->second.GetShares()->end()))->first;
4487 }
4488
4495 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4496 {
4497 FlowStatMap::const_iterator i = this->find(from);
4498 if (i == this->end()) return 0;
4499 return i->second.GetShare(via);
4500 }
4501
4502 extern const TileTypeProcs _tile_type_station_procs = {
4503 DrawTile_Station, // draw_tile_proc
4504 GetSlopePixelZ_Station, // get_slope_z_proc
4505 ClearTile_Station, // clear_tile_proc
4506 NULL, // add_accepted_cargo_proc
4507 GetTileDesc_Station, // get_tile_desc_proc
4508 GetTileTrackStatus_Station, // get_tile_track_status_proc
4509 ClickTile_Station, // click_tile_proc
4510 AnimateTile_Station, // animate_tile_proc
4511 TileLoop_Station, // tile_loop_proc
4512 ChangeTileOwner_Station, // change_tile_owner_proc
4513 NULL, // add_produced_cargo_proc
4514 VehicleEnter_Station, // vehicle_enter_tile_proc
4515 GetFoundation_Station, // get_foundation_proc
4516 TerraformTile_Station, // terraform_tile_proc
4517 };