/
road_cmd.cpp
1875 lines (1577 loc) · 63.4 KB
/
road_cmd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file road_cmd.cpp Commands related to road tiles. */
#include "stdafx.h"
#include "cmd_helper.h"
#include "road_internal.h"
#include "viewport_func.h"
#include "command_func.h"
#include "pathfinder/yapf/yapf_cache.h"
#include "depot_base.h"
#include "newgrf.h"
#include "autoslope.h"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "tunnelbridge.h"
#include "cheat_type.h"
#include "effectvehicle_func.h"
#include "effectvehicle_base.h"
#include "elrail_func.h"
#include "roadveh.h"
#include "town.h"
#include "company_base.h"
#include "core/random_func.hpp"
#include "newgrf_railtype.h"
#include "date_func.h"
#include "genworld.h"
#include "company_gui.h"
#include "table/strings.h"
#include "safeguards.h"
/**
* Verify whether a road vehicle is available.
* @return \c true if at least one road vehicle is available, \c false if not
*/
bool RoadVehiclesAreBuilt()
{
const RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) return true;
return false;
}
/** Invalid RoadBits on slopes. */
static const RoadBits _invalid_tileh_slopes_road[2][15] = {
/* The inverse of the mixable RoadBits on a leveled slope */
{
ROAD_NONE, // SLOPE_FLAT
ROAD_NE | ROAD_SE, // SLOPE_W
ROAD_NE | ROAD_NW, // SLOPE_S
ROAD_NE, // SLOPE_SW
ROAD_NW | ROAD_SW, // SLOPE_E
ROAD_NONE, // SLOPE_EW
ROAD_NW, // SLOPE_SE
ROAD_NONE, // SLOPE_WSE
ROAD_SE | ROAD_SW, // SLOPE_N
ROAD_SE, // SLOPE_NW
ROAD_NONE, // SLOPE_NS
ROAD_NONE, // SLOPE_ENW
ROAD_SW, // SLOPE_NE
ROAD_NONE, // SLOPE_SEN
ROAD_NONE // SLOPE_NWS
},
/* The inverse of the allowed straight roads on a slope
* (with and without a foundation). */
{
ROAD_NONE, // SLOPE_FLAT
ROAD_NONE, // SLOPE_W Foundation
ROAD_NONE, // SLOPE_S Foundation
ROAD_Y, // SLOPE_SW
ROAD_NONE, // SLOPE_E Foundation
ROAD_ALL, // SLOPE_EW
ROAD_X, // SLOPE_SE
ROAD_ALL, // SLOPE_WSE
ROAD_NONE, // SLOPE_N Foundation
ROAD_X, // SLOPE_NW
ROAD_ALL, // SLOPE_NS
ROAD_ALL, // SLOPE_ENW
ROAD_Y, // SLOPE_NE
ROAD_ALL, // SLOPE_SEN
ROAD_ALL // SLOPE_NW
}
};
static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
/**
* Is it allowed to remove the given road bits from the given tile?
* @param tile the tile to remove the road from
* @param remove the roadbits that are going to be removed
* @param owner the actual owner of the roadbits of the tile
* @param rt the road type to remove the bits from
* @param flags command flags
* @param town_check Shall the town rating checked/affected
* @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
*/
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadType rt, DoCommandFlag flags, bool town_check)
{
if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
/* Water can always flood and towns can always remove "normal" road pieces.
* Towns are not be allowed to remove non "normal" road pieces, like tram
* tracks as that would result in trams that cannot turn. */
if (_current_company == OWNER_WATER ||
(rt == ROADTYPE_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
/* Only do the special processing if the road is owned
* by a town */
if (owner != OWNER_TOWN) {
if (owner == OWNER_NONE) return CommandCost();
CommandCost ret = CheckOwnership(owner);
return ret;
}
if (!town_check) return CommandCost();
if (_cheats.magic_bulldozer.value) return CommandCost();
Town *t = ClosestTownFromTile(tile, UINT_MAX);
if (t == NULL) return CommandCost();
/* check if you're allowed to remove the street owned by a town
* removal allowance depends on difficulty setting */
CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
if (ret.Failed()) return ret;
/* Get a bitmask of which neighbouring roads has a tile */
RoadBits n = ROAD_NONE;
RoadBits present = GetAnyRoadBits(tile, rt);
if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rt) & ROAD_SW)) n |= ROAD_NE;
if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rt) & ROAD_NW)) n |= ROAD_SE;
if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rt) & ROAD_NE)) n |= ROAD_SW;
if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rt) & ROAD_SE)) n |= ROAD_NW;
int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
/* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
* then allow it */
if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
/* you can remove all kind of roads with extra dynamite */
if (!_settings_game.construction.extra_dynamite) {
SetDParam(0, t->index);
return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
}
rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
}
ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
return CommandCost();
}
/**
* Delete a piece of road.
* @param tile tile where to remove road from
* @param flags operation to perform
* @param pieces roadbits to remove
* @param rt roadtype to remove
* @param crossing_check should we check if there is a tram track when we are removing road from crossing?
* @param town_check should we check if the town allows removal?
*/
static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadType rt, bool crossing_check, bool town_check = true)
{
RoadTypes rts = GetRoadTypes(tile);
/* The tile doesn't have the given road type */
if (!HasBit(rts, rt)) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
switch (GetTileType(tile)) {
case MP_ROAD: {
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
break;
}
case MP_STATION: {
if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
break;
}
case MP_TUNNELBRIDGE: {
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
if (ret.Failed()) return ret;
break;
}
default:
return CMD_ERROR;
}
CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rt), rt, flags, town_check);
if (ret.Failed()) return ret;
if (!IsTileType(tile, MP_ROAD)) {
/* If it's the last roadtype, just clear the whole tile */
if (rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
CommandCost cost(EXPENSES_CONSTRUCTION);
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
/* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
if ((AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile))) & pieces) == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
/* Pay for *every* tile of the bridge or tunnel */
uint len = GetTunnelBridgeLength(other_end, tile) + 2;
cost.AddCost(len * 2 * _price[PR_CLEAR_ROAD]);
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
if (c != NULL) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(c->index);
}
SetRoadTypes(other_end, GetRoadTypes(other_end) & ~RoadTypeToRoadTypes(rt));
SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
/* If the owner of the bridge sells all its road, also move the ownership
* to the owner of the other roadtype, unless the bridge owner is a town. */
RoadType other_rt = (rt == ROADTYPE_ROAD) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
Owner other_owner = GetRoadOwner(tile, other_rt);
if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
SetTileOwner(tile, other_owner);
SetTileOwner(other_end, other_owner);
}
/* Mark tiles dirty that have been repaved */
if (IsBridge(tile)) {
MarkBridgeDirty(tile);
} else {
MarkTileDirtyByTile(tile);
MarkTileDirtyByTile(other_end);
}
}
} else {
assert(IsDriveThroughStopTile(tile));
cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
if (c != NULL) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
}
SetRoadTypes(tile, GetRoadTypes(tile) & ~RoadTypeToRoadTypes(rt));
MarkTileDirtyByTile(tile);
}
}
return cost;
}
switch (GetRoadTileType(tile)) {
case ROAD_TILE_NORMAL: {
Slope tileh = GetTileSlope(tile);
/* Steep slopes behave the same as slopes with one corner raised. */
if (IsSteepSlope(tileh)) {
tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
}
RoadBits present = GetRoadBits(tile, rt);
const RoadBits other = GetOtherRoadBits(tile, rt);
const Foundation f = GetRoadFoundation(tileh, present);
if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
/* Autocomplete to a straight road
* @li if the bits of the other roadtypes result in another foundation
* @li if build on slopes is disabled */
if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
(tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
pieces |= MirrorRoadBits(pieces);
}
/* limit the bits to delete to the existing bits. */
pieces &= present;
if (pieces == ROAD_NONE) return_cmd_error(rt == ROADTYPE_TRAM ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
/* Now set present what it will be after the remove */
present ^= pieces;
/* Check for invalid RoadBit combinations on slopes */
if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
(present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
return CMD_ERROR;
}
if (flags & DC_EXEC) {
if (HasRoadWorks(tile)) {
/* flooding tile with road works, don't forget to remove the effect vehicle too */
assert(_current_company == OWNER_WATER);
EffectVehicle *v;
FOR_ALL_EFFECTVEHICLES(v) {
if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
delete v;
}
}
}
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
if (c != NULL) {
c->infrastructure.road[rt] -= CountBits(pieces);
DirtyCompanyInfrastructureWindows(c->index);
}
if (present == ROAD_NONE) {
RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
if (rts == ROADTYPES_NONE) {
/* Includes MarkTileDirtyByTile() */
DoClearSquare(tile);
} else {
if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
/* Update nearest-town index */
const Town *town = CalcClosestTownFromTile(tile);
SetTownIndex(tile, town == NULL ? (TownID)INVALID_TOWN : town->index);
}
SetRoadBits(tile, ROAD_NONE, rt);
SetRoadTypes(tile, rts);
MarkTileDirtyByTile(tile);
}
} else {
/* When bits are removed, you *always* end up with something that
* is not a complete straight road tile. However, trams do not have
* onewayness, so they cannot remove it either. */
if (rt != ROADTYPE_TRAM) SetDisallowedRoadDirections(tile, DRD_NONE);
SetRoadBits(tile, present, rt);
MarkTileDirtyByTile(tile);
}
}
CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * _price[PR_CLEAR_ROAD]);
/* If we build a foundation we have to pay for it. */
if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
return cost;
}
case ROAD_TILE_CROSSING: {
if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
return CMD_ERROR;
}
/* Don't allow road to be removed from the crossing when there is tram;
* we can't draw the crossing without roadbits ;) */
if (rt == ROADTYPE_ROAD && HasTileRoadType(tile, ROADTYPE_TRAM) && (flags & DC_EXEC || crossing_check)) return CMD_ERROR;
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
if (c != NULL) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
}
Track railtrack = GetCrossingRailTrack(tile);
RoadTypes rts = GetRoadTypes(tile) & ComplementRoadTypes(RoadTypeToRoadTypes(rt));
if (rts == ROADTYPES_NONE) {
TrackBits tracks = GetCrossingRailBits(tile);
bool reserved = HasCrossingReservation(tile);
MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
if (reserved) SetTrackReservation(tile, tracks);
/* Update rail count for level crossings. The plain track should still be accounted
* for, so only subtract the difference to the level crossing cost. */
c = Company::GetIfValid(GetTileOwner(tile));
if (c != NULL) {
c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
DirtyCompanyInfrastructureWindows(c->index);
}
} else {
SetRoadTypes(tile, rts);
}
MarkTileDirtyByTile(tile);
YapfNotifyTrackLayoutChange(tile, railtrack);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_ROAD] * 2);
}
default:
case ROAD_TILE_DEPOT:
return CMD_ERROR;
}
}
/**
* Calculate the costs for roads on slopes
* Aside modify the RoadBits to fit on the slopes
*
* @note The RoadBits are modified too!
* @param tileh The current slope
* @param pieces The RoadBits we want to add
* @param existing The existent RoadBits of the current type
* @param other The other existent RoadBits
* @return The costs for these RoadBits on this slope
*/
static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
{
/* Remove already build pieces */
CLRBITS(*pieces, existing);
/* If we can't build anything stop here */
if (*pieces == ROAD_NONE) return CMD_ERROR;
/* All RoadBit combos are valid on flat land */
if (tileh == SLOPE_FLAT) return CommandCost();
/* Steep slopes behave the same as slopes with one corner raised. */
if (IsSteepSlope(tileh)) {
tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
}
/* Save the merge of all bits of the current type */
RoadBits type_bits = existing | *pieces;
/* Roads on slopes */
if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
/* If we add leveling we've got to pay for it */
if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
return CommandCost();
}
/* Autocomplete uphill roads */
*pieces |= MirrorRoadBits(*pieces);
type_bits = existing | *pieces;
/* Uphill roads */
if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
(_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
/* Slopes with foundation ? */
if (IsSlopeWithOneCornerRaised(tileh)) {
/* Prevent build on slopes if it isn't allowed */
if (_settings_game.construction.build_on_slopes) {
/* If we add foundation we've got to pay for it */
if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
return CommandCost();
}
} else {
if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
return CommandCost();
}
}
return CMD_ERROR;
}
/**
* Build a piece of road.
* @param tile tile where to build road
* @param flags operation to perform
* @param p1 bit 0..3 road pieces to build (RoadBits)
* bit 4..5 road type
* bit 6..7 disallowed directions to toggle
* @param p2 the town that is building the road (0 if not applicable)
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CompanyID company = _current_company;
CommandCost cost(EXPENSES_CONSTRUCTION);
RoadBits existing = ROAD_NONE;
RoadBits other_bits = ROAD_NONE;
/* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
* if a non-company is building the road */
if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CMD_ERROR;
if (company != OWNER_TOWN) {
const Town *town = CalcClosestTownFromTile(tile);
p2 = (town != NULL) ? town->index : (TownID)INVALID_TOWN;
if (company == OWNER_DEITY) {
company = OWNER_TOWN;
/* If we are not within a town, we are not owned by the town */
if (town == NULL || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
company = OWNER_NONE;
}
}
}
RoadBits pieces = Extract<RoadBits, 0, 4>(p1);
/* do not allow building 'zero' road bits, code wouldn't handle it */
if (pieces == ROAD_NONE) return CMD_ERROR;
RoadType rt = Extract<RoadType, 4, 2>(p1);
if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
DisallowedRoadDirections toggle_drd = Extract<DisallowedRoadDirections, 6, 2>(p1);
Slope tileh = GetTileSlope(tile);
bool need_to_clear = false;
switch (GetTileType(tile)) {
case MP_ROAD:
switch (GetRoadTileType(tile)) {
case ROAD_TILE_NORMAL: {
if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
other_bits = GetOtherRoadBits(tile, rt);
if (!HasTileRoadType(tile, rt)) break;
existing = GetRoadBits(tile, rt);
bool crossing = !IsStraightRoad(existing | pieces);
if (rt != ROADTYPE_TRAM && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
/* Junctions cannot be one-way */
return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
}
if ((existing & pieces) == pieces) {
/* We only want to set the (dis)allowed road directions */
if (toggle_drd != DRD_NONE && rt != ROADTYPE_TRAM) {
if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
Owner owner = GetRoadOwner(tile, ROADTYPE_ROAD);
if (owner != OWNER_NONE) {
CommandCost ret = CheckOwnership(owner, tile);
if (ret.Failed()) return ret;
}
DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
DisallowedRoadDirections dis_new = dis_existing ^ toggle_drd;
/* We allow removing disallowed directions to break up
* deadlocks, but adding them can break articulated
* vehicles. As such, only when less is disallowed,
* i.e. bits are removed, we skip the vehicle check. */
if (CountBits(dis_existing) <= CountBits(dis_new)) {
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
}
/* Ignore half built tiles */
if ((flags & DC_EXEC) && rt != ROADTYPE_TRAM && IsStraightRoad(existing)) {
SetDisallowedRoadDirections(tile, dis_new);
MarkTileDirtyByTile(tile);
}
return CommandCost();
}
return_cmd_error(STR_ERROR_ALREADY_BUILT);
}
/* Disallow breaking end-of-line of someone else
* so trams can still reverse on this tile. */
if (rt == ROADTYPE_TRAM && HasExactlyOneBit(existing)) {
Owner owner = GetRoadOwner(tile, rt);
if (Company::IsValidID(owner)) {
CommandCost ret = CheckOwnership(owner);
if (ret.Failed()) return ret;
}
}
break;
}
case ROAD_TILE_CROSSING:
other_bits = GetCrossingRoadBits(tile);
if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
pieces = other_bits; // we need to pay for both roadbits
if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
break;
case ROAD_TILE_DEPOT:
if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
goto do_clear;
default: NOT_REACHED();
}
break;
case MP_RAILWAY: {
if (IsSteepSlope(tileh)) {
return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
}
/* Level crossings may only be built on these slopes */
if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
}
if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
if (RailNoLevelCrossings(GetRailType(tile))) {
return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
}
Axis roaddir;
switch (GetTrackBits(tile)) {
case TRACK_BIT_X:
if (pieces & ROAD_X) goto do_clear;
roaddir = AXIS_Y;
break;
case TRACK_BIT_Y:
if (pieces & ROAD_Y) goto do_clear;
roaddir = AXIS_X;
break;
default: goto do_clear;
}
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
if (flags & DC_EXEC) {
Track railtrack = AxisToTrack(OtherAxis(roaddir));
YapfNotifyTrackLayoutChange(tile, railtrack);
/* Update company infrastructure counts. A level crossing has two road bits. */
Company *c = Company::GetIfValid(company);
if (c != NULL) {
c->infrastructure.road[rt] += 2;
if (rt != ROADTYPE_ROAD) c->infrastructure.road[ROADTYPE_ROAD] += 2;
DirtyCompanyInfrastructureWindows(company);
}
/* Update rail count for level crossings. The plain track is already
* counted, so only add the difference to the level crossing cost. */
c = Company::GetIfValid(GetTileOwner(tile));
if (c != NULL) {
c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
DirtyCompanyInfrastructureWindows(c->index);
}
/* Always add road to the roadtypes (can't draw without it) */
bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), RoadTypeToRoadTypes(rt) | ROADTYPES_ROAD, p2);
SetCrossingReservation(tile, reserved);
UpdateLevelCrossing(tile, false);
MarkTileDirtyByTile(tile);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_ROAD] * (rt == ROADTYPE_ROAD ? 2 : 4));
}
case MP_STATION: {
if ((GetAnyRoadBits(tile, rt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
if (!IsDriveThroughStopTile(tile)) goto do_clear;
RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
if (pieces & ~curbits) goto do_clear;
pieces = curbits; // we need to pay for both roadbits
if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
break;
}
case MP_TUNNELBRIDGE: {
if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
/* Only allow building the outern roadbit, so building long roads stops at existing bridges */
if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
if (HasTileRoadType(tile, rt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
/* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
if (ret.Failed()) return ret;
break;
}
default: {
do_clear:;
need_to_clear = true;
break;
}
}
if (need_to_clear) {
CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (ret.Failed()) return ret;
cost.AddCost(ret);
}
if (other_bits != pieces) {
/* Check the foundation/slopes when adding road/tram bits */
CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
/* Return an error if we need to build a foundation (ret != 0) but the
* current setting is turned off */
if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
}
cost.AddCost(ret);
}
if (!need_to_clear) {
if (IsTileType(tile, MP_ROAD)) {
/* Don't put the pieces that already exist */
pieces &= ComplementRoadBits(existing);
/* Check if new road bits will have the same foundation as other existing road types */
if (IsNormalRoad(tile)) {
Slope slope = GetTileSlope(tile);
Foundation found_new = GetRoadFoundation(slope, pieces | existing);
/* Test if all other roadtypes can be built at that foundation */
for (RoadType rtest = ROADTYPE_ROAD; rtest < ROADTYPE_END; rtest++) {
if (rtest != rt) { // check only other road types
RoadBits bits = GetRoadBits(tile, rtest);
/* do not check if there are not road bits of given type */
if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
}
}
}
}
}
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
}
uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
/* There are 2 pieces on *every* tile of the bridge or tunnel */
2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
/* Count pieces */
CountBits(pieces);
cost.AddCost(num_pieces * _price[PR_BUILD_ROAD]);
if (flags & DC_EXEC) {
switch (GetTileType(tile)) {
case MP_ROAD: {
RoadTileType rtt = GetRoadTileType(tile);
if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
SetRoadOwner(tile, rt, company);
if (rt == ROADTYPE_ROAD) SetTownIndex(tile, p2);
}
if (rtt != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rt);
break;
}
case MP_TUNNELBRIDGE: {
TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
SetRoadTypes(other_end, GetRoadTypes(other_end) | RoadTypeToRoadTypes(rt));
SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
SetRoadOwner(other_end, rt, company);
SetRoadOwner(tile, rt, company);
/* Mark tiles dirty that have been repaved */
if (IsBridge(tile)) {
MarkBridgeDirty(tile);
} else {
MarkTileDirtyByTile(other_end);
MarkTileDirtyByTile(tile);
}
break;
}
case MP_STATION:
assert(IsDriveThroughStopTile(tile));
SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
SetRoadOwner(tile, rt, company);
break;
default:
MakeRoadNormal(tile, pieces, RoadTypeToRoadTypes(rt), p2, company, company);
break;
}
/* Update company infrastructure count. */
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
if (c != NULL) {
if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
c->infrastructure.road[rt] += num_pieces;
DirtyCompanyInfrastructureWindows(c->index);
}
if (rt != ROADTYPE_TRAM && IsNormalRoadTile(tile)) {
existing |= pieces;
SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
}
MarkTileDirtyByTile(tile);
}
return cost;
}
/**
* Checks whether a road or tram connection can be found when building a new road or tram.
* @param tile Tile at which the road being built will end.
* @param rt Roadtype of the road being built.
* @param dir Direction that the road is following.
* @return True if the next tile at dir direction is suitable for being connected directly by a second roadbit at the end of the road being built.
*/
static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
{
RoadBits bits = GetAnyRoadBits(tile + TileOffsByDiagDir(dir), rt, false);
return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
}
/**
* Build a long piece of road.
* @param start_tile start tile of drag (the building cost will appear over this tile)
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1). Only used if bit 6 is set or if we are building a single tile
* - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2). Only used if bit 6 is set or if we are building a single tile
* - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
* - p2 = (bit 3 + 4) - road type
* - p2 = (bit 5) - set road direction
* - p2 = (bit 6) - defines two different behaviors for this command:
* - 0 = Build up to an obstacle. Do not build the first and last roadbits unless they can be connected to something, or if we are building a single tile
* - 1 = Fail if an obstacle is found. Always take into account bit 0 and 1. This behavior is used for scripts
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
DisallowedRoadDirections drd = DRD_NORTHBOUND;
if (p1 >= MapSize()) return CMD_ERROR;
TileIndex end_tile = p1;
RoadType rt = Extract<RoadType, 3, 2>(p2);
if (!IsValidRoadType(rt) || !ValParamRoadType(rt)) return CMD_ERROR;
Axis axis = Extract<Axis, 2, 1>(p2);
/* Only drag in X or Y direction dictated by the direction variable */
if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
DiagDirection dir = AxisToDiagDir(axis);
/* Swap direction, also the half-tile drag var (bit 0 and 1) */
if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
dir = ReverseDiagDir(dir);
p2 ^= 3;
drd = DRD_SOUTHBOUND;
}
/* On the X-axis, we have to swap the initial bits, so they
* will be interpreted correctly in the GTTS. Furthermore
* when you just 'click' on one tile to build them. */
if ((axis == AXIS_Y) == (start_tile == end_tile && HasBit(p2, 0) == HasBit(p2, 1))) drd ^= DRD_BOTH;
/* No disallowed direction bits have to be toggled */
if (!HasBit(p2, 5)) drd = DRD_NONE;
CommandCost cost(EXPENSES_CONSTRUCTION);
CommandCost last_error = CMD_ERROR;
TileIndex tile = start_tile;
bool had_bridge = false;
bool had_tunnel = false;
bool had_success = false;
bool is_ai = HasBit(p2, 6);
/* Start tile is the first tile clicked by the user. */
for (;;) {
RoadBits bits = AxisToRoadBits(axis);
/* Determine which road parts should be built. */
if (!is_ai && start_tile != end_tile) {
/* Only build the first and last roadbit if they can connect to something. */
if (tile == end_tile && !CanConnectToRoad(tile, rt, dir)) {
bits = DiagDirToRoadBits(ReverseDiagDir(dir));
} else if (tile == start_tile && !CanConnectToRoad(tile, rt, ReverseDiagDir(dir))) {
bits = DiagDirToRoadBits(dir);
}
} else {
/* Road parts only have to be built at the start tile or at the end tile. */
if (tile == end_tile && !HasBit(p2, 1)) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
if (tile == start_tile && HasBit(p2, 0)) bits &= DiagDirToRoadBits(dir);
}
CommandCost ret = DoCommand(tile, drd << 6 | rt << 4 | bits, 0, flags, CMD_BUILD_ROAD);
if (ret.Failed()) {
last_error = ret;
if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
if (is_ai) return last_error;
break;
}
} else {
had_success = true;
/* Only pay for the upgrade on one side of the bridges and tunnels */
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
if (IsBridge(tile)) {
if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
cost.AddCost(ret);
}
had_bridge = true;
} else { // IsTunnel(tile)
if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
cost.AddCost(ret);
}
had_tunnel = true;
}
} else {
cost.AddCost(ret);
}
}
if (tile == end_tile) break;
tile += TileOffsByDiagDir(dir);
}
return had_success ? cost : last_error;
}
/**
* Remove a long piece of road.
* @param start_tile start tile of drag
* @param flags operation to perform
* @param p1 end tile of drag
* @param p2 various bitstuffed elements
* - p2 = (bit 0) - start tile starts in the 2nd half of tile (p2 & 1)
* - p2 = (bit 1) - end tile starts in the 2nd half of tile (p2 & 2)
* - p2 = (bit 2) - direction: 0 = along x-axis, 1 = along y-axis (p2 & 4)
* - p2 = (bit 3 + 4) - road type
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
if (p1 >= MapSize()) return CMD_ERROR;
TileIndex end_tile = p1;
RoadType rt = Extract<RoadType, 3, 2>(p2);
if (!IsValidRoadType(rt)) return CMD_ERROR;
Axis axis = Extract<Axis, 2, 1>(p2);
/* Only drag in X or Y direction dictated by the direction variable */
if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
/* Swap start and ending tile, also the half-tile drag var (bit 0 and 1) */
if (start_tile > end_tile || (start_tile == end_tile && HasBit(p2, 0))) {
TileIndex t = start_tile;
start_tile = end_tile;
end_tile = t;
p2 ^= IsInsideMM(p2 & 3, 1, 3) ? 3 : 0;
}
Money money = GetAvailableMoneyForCommand();
TileIndex tile = start_tile;
CommandCost last_error = CMD_ERROR;
bool had_success = false;
/* Start tile is the small number. */
for (;;) {
RoadBits bits = AxisToRoadBits(axis);
if (tile == end_tile && !HasBit(p2, 1)) bits &= ROAD_NW | ROAD_NE;
if (tile == start_tile && HasBit(p2, 0)) bits &= ROAD_SE | ROAD_SW;
/* try to remove the halves. */
if (bits != 0) {
CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rt, true);
if (ret.Succeeded()) {
if (flags & DC_EXEC) {
money -= ret.GetCost();
if (money < 0) {
_additional_cash_required = DoCommand(start_tile, end_tile, p2, flags & ~DC_EXEC, CMD_REMOVE_LONG_ROAD).GetCost();
return cost;
}
RemoveRoad(tile, flags, bits, rt, true, false);
}
cost.AddCost(ret);
had_success = true;
} else {
/* Ownership errors are more important. */
if (last_error.GetErrorMessage() != STR_ERROR_OWNED_BY) last_error = ret;
}
}
if (tile == end_tile) break;
tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
}
return had_success ? cost : last_error;
}
/**