2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file town_cmd.cpp Handling of town tiles. */
12 #include "road_internal.h" /* Cleaning up road bits */
14 #include "landscape.h"
15 #include "viewport_func.h"
16 #include "viewport_kdtree.h"
17 #include "command_func.h"
18 #include "company_func.h"
20 #include "station_base.h"
21 #include "waypoint_base.h"
22 #include "station_kdtree.h"
23 #include "company_base.h"
24 #include "news_func.h"
28 #include "newgrf_debug.h"
29 #include "newgrf_house.h"
30 #include "newgrf_text.h"
31 #include "autoslope.h"
32 #include "tunnelbridge_map.h"
33 #include "strings_func.h"
34 #include "window_func.h"
35 #include "string_func.h"
36 #include "newgrf_cargo.h"
37 #include "cheat_type.h"
38 #include "animated_tile_func.h"
39 #include "subsidy_func.h"
40 #include "core/pool_func.hpp"
42 #include "town_kdtree.h"
43 #include "townname_func.h"
44 #include "core/random_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "depot_base.h"
47 #include "object_map.h"
48 #include "object_base.h"
50 #include "game/game.hpp"
52 #include "landscape_cmd.h"
54 #include "terraform_cmd.h"
55 #include "tunnelbridge_cmd.h"
56 #include "timer/timer.h"
57 #include "timer/timer_game_calendar.h"
58 #include "timer/timer_game_economy.h"
59 #include "timer/timer_game_tick.h"
61 #include "table/strings.h"
62 #include "table/town_land.h"
64 #include "safeguards.h"
66 /* Initialize the town-pool */
67 TownPool
_town_pool("Town");
68 INSTANTIATE_POOL_METHODS(Town
)
71 TownKdtree
_town_kdtree(&Kdtree_TownXYFunc
);
73 void RebuildTownKdtree()
75 std::vector
<TownID
> townids
;
76 for (const Town
*town
: Town::Iterate()) {
77 townids
.push_back(town
->index
);
79 _town_kdtree
.Build(townids
.begin(), townids
.end());
82 /** Set if a town is being generated. */
83 static bool _generating_town
= false;
86 * Check if a town 'owns' a bridge.
87 * Bridges do not directly have an owner, so we check the tiles adjacent to the bridge ends.
88 * If either adjacent tile belongs to the town then it will be assumed that the town built
90 * @param tile The bridge tile to test
91 * @param t The town we are interested in
92 * @return true If town 'owns' a bridge.
94 static bool TestTownOwnsBridge(TileIndex tile
, const Town
*t
)
96 if (!IsTileOwner(tile
, OWNER_TOWN
)) return false;
98 TileIndex adjacent
= tile
+ TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(tile
)));
99 bool town_owned
= IsTileType(adjacent
, MP_ROAD
) && IsTileOwner(adjacent
, OWNER_TOWN
) && GetTownIndex(adjacent
) == t
->index
;
102 /* Or other adjacent road */
103 adjacent
= tile
+ TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(GetOtherTunnelBridgeEnd(tile
))));
104 town_owned
= IsTileType(adjacent
, MP_ROAD
) && IsTileOwner(adjacent
, OWNER_TOWN
) && GetTownIndex(adjacent
) == t
->index
;
112 if (CleaningPool()) return;
114 /* Delete town authority window
115 * and remove from list of sorted towns */
116 CloseWindowById(WC_TOWN_VIEW
, this->index
);
119 /* Check no industry is related to us. */
120 for (const Industry
*i
: Industry::Iterate()) {
121 assert(i
->town
!= this);
124 /* ... and no object is related to us. */
125 for (const Object
*o
: Object::Iterate()) {
126 assert(o
->town
!= this);
128 #endif /* WITH_ASSERT */
130 /* Check no tile is related to us. */
131 for (TileIndex tile
= 0; tile
< Map::Size(); ++tile
) {
132 switch (GetTileType(tile
)) {
134 assert(GetTownIndex(tile
) != this->index
);
138 assert(!HasTownOwnedRoad(tile
) || GetTownIndex(tile
) != this->index
);
141 case MP_TUNNELBRIDGE
:
142 assert(!TestTownOwnsBridge(tile
, this));
150 /* Clear the persistent storage list. */
151 for (auto &psa
: this->psa_list
) {
154 this->psa_list
.clear();
156 DeleteSubsidyWith(SourceType::Town
, this->index
);
157 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS
, this->index
);
158 CargoPacket::InvalidateAllFrom(SourceType::Town
, this->index
);
159 MarkWholeScreenDirty();
164 * Invalidating of the "nearest town cache" has to be done
165 * after removing item from the pool.
167 void Town::PostDestructor(size_t)
169 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_REBUILD
);
170 UpdateNearestTownForRoadTiles(false);
172 /* Give objects a new home! */
173 for (Object
*o
: Object::Iterate()) {
174 if (o
->town
== nullptr) o
->town
= CalcClosestTownFromTile(o
->location
.tile
, UINT_MAX
);
179 * Assign the town layout.
180 * @param layout The desired layout. If TL_RANDOM, we pick one based on TileHash.
182 void Town::InitializeLayout(TownLayout layout
)
184 if (layout
!= TL_RANDOM
) {
185 this->layout
= layout
;
189 this->layout
= static_cast<TownLayout
>(TileHash(TileX(this->xy
), TileY(this->xy
)) % (NUM_TLS
- 1));
193 * Return a random valid town.
194 * @return A random town, or nullptr if there are no towns.
196 /* static */ Town
*Town::GetRandom()
198 if (Town::GetNumItems() == 0) return nullptr;
199 int num
= RandomRange((uint16_t)Town::GetNumItems());
200 size_t index
= MAX_UVALUE(size_t);
206 /* Make sure we have a valid town */
207 while (!Town::IsValidID(index
)) {
209 assert(index
< Town::GetPoolSize());
213 return Town::Get(index
);
216 void Town::FillCachedName() const
218 this->cached_name
= GetTownName(this);
222 * Get the cost for removing this house.
223 * @return The cost adjusted for inflation, etc.
225 Money
HouseSpec::GetRemovalCost() const
227 return (_price
[PR_CLEAR_HOUSE
] * this->removal_cost
) >> 8;
231 static int _grow_town_result
;
233 /* The possible states of town growth. */
234 enum TownGrowthResult
{
236 GROWTH_SEARCH_STOPPED
= 0
237 // GROWTH_SEARCH_RUNNING >= 1
240 static bool TryBuildTownHouse(Town
*t
, TileIndex tile
);
241 static Town
*CreateRandomTown(uint attempts
, uint32_t townnameparts
, TownSize size
, bool city
, TownLayout layout
);
243 static void TownDrawHouseLift(const TileInfo
*ti
)
245 AddChildSpriteScreen(SPR_LIFT
, PAL_NONE
, 14, 60 - GetLiftPosition(ti
->tile
));
248 typedef void TownDrawTileProc(const TileInfo
*ti
);
249 static TownDrawTileProc
* const _town_draw_tile_procs
[1] = {
254 * Return a random direction
256 * @return a random direction
258 static inline DiagDirection
RandomDiagDir()
260 return (DiagDirection
)(RandomRange(DIAGDIR_END
));
264 * Draw a house and its tile. This is a tile callback routine.
265 * @param ti TileInfo of the tile to draw
267 static void DrawTile_Town(TileInfo
*ti
)
269 HouseID house_id
= GetHouseType(ti
->tile
);
271 if (house_id
>= NEW_HOUSE_OFFSET
) {
272 /* Houses don't necessarily need new graphics. If they don't have a
273 * spritegroup associated with them, then the sprite for the substitute
274 * house id is drawn instead. */
275 if (HouseSpec::Get(house_id
)->grf_prop
.spritegroup
[0] != nullptr) {
276 DrawNewHouseTile(ti
, house_id
);
279 house_id
= HouseSpec::Get(house_id
)->grf_prop
.subst_id
;
283 /* Retrieve pointer to the draw town tile struct */
284 const DrawBuildingsTileStruct
*dcts
= &_town_draw_tile_data
[house_id
<< 4 | TileHash2Bit(ti
->x
, ti
->y
) << 2 | GetHouseBuildingStage(ti
->tile
)];
286 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
288 DrawGroundSprite(dcts
->ground
.sprite
, dcts
->ground
.pal
);
290 /* If houses are invisible, do not draw the upper part */
291 if (IsInvisibilitySet(TO_HOUSES
)) return;
293 /* Add a house on top of the ground? */
294 SpriteID image
= dcts
->building
.sprite
;
296 AddSortableSpriteToDraw(image
, dcts
->building
.pal
,
297 ti
->x
+ dcts
->subtile_x
,
298 ti
->y
+ dcts
->subtile_y
,
303 IsTransparencySet(TO_HOUSES
)
306 if (IsTransparencySet(TO_HOUSES
)) return;
310 int proc
= dcts
->draw_proc
- 1;
312 if (proc
>= 0) _town_draw_tile_procs
[proc
](ti
);
316 static int GetSlopePixelZ_Town(TileIndex tile
, uint
, uint
, bool)
318 return GetTileMaxPixelZ(tile
);
322 * Get the foundation for a house. This is a tile callback routine.
323 * @param tile The tile to find a foundation for.
324 * @param tileh The slope of the tile.
326 static Foundation
GetFoundation_Town(TileIndex tile
, Slope tileh
)
328 HouseID hid
= GetHouseType(tile
);
330 /* For NewGRF house tiles we might not be drawing a foundation. We need to
331 * account for this, as other structures should
332 * draw the wall of the foundation in this case.
334 if (hid
>= NEW_HOUSE_OFFSET
) {
335 const HouseSpec
*hs
= HouseSpec::Get(hid
);
336 if (hs
->grf_prop
.spritegroup
[0] != nullptr && HasBit(hs
->callback_mask
, CBM_HOUSE_DRAW_FOUNDATIONS
)) {
337 uint32_t callback_res
= GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS
, 0, 0, hid
, Town::GetByTile(tile
), tile
);
338 if (callback_res
!= CALLBACK_FAILED
&& !ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_DRAW_FOUNDATIONS
, callback_res
)) return FOUNDATION_NONE
;
341 return FlatteningFoundation(tileh
);
345 * Animate a tile for a town.
346 * Only certain houses can be animated.
347 * The newhouses animation supersedes regular ones.
348 * @param tile TileIndex of the house to animate.
350 static void AnimateTile_Town(TileIndex tile
)
352 if (GetHouseType(tile
) >= NEW_HOUSE_OFFSET
) {
353 AnimateNewHouseTile(tile
);
357 if (TimerGameTick::counter
& 3) return;
359 /* If the house is not one with a lift anymore, then stop this animating.
360 * Not exactly sure when this happens, but probably when a house changes.
361 * Before this was just a return...so it'd leak animated tiles..
362 * That bug seems to have been here since day 1?? */
363 if (!(HouseSpec::Get(GetHouseType(tile
))->building_flags
& BUILDING_IS_ANIMATED
)) {
364 DeleteAnimatedTile(tile
);
368 if (!LiftHasDestination(tile
)) {
371 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
372 * This is due to the fact that the first floor is, in the graphics,
373 * the height of 2 'normal' floors.
374 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
377 } while (i
== 1 || i
* 6 == GetLiftPosition(tile
));
379 SetLiftDestination(tile
, i
);
382 int pos
= GetLiftPosition(tile
);
383 int dest
= GetLiftDestination(tile
) * 6;
384 pos
+= (pos
< dest
) ? 1 : -1;
385 SetLiftPosition(tile
, pos
);
389 DeleteAnimatedTile(tile
);
392 MarkTileDirtyByTile(tile
);
396 * Determines if a town is close to a tile.
397 * @param tile TileIndex of the tile to query.
398 * @param dist The maximum distance to be accepted.
399 * @returns true if the tile is within the specified distance.
401 static bool IsCloseToTown(TileIndex tile
, uint dist
)
403 if (_town_kdtree
.Count() == 0) return false;
404 Town
*t
= Town::Get(_town_kdtree
.FindNearest(TileX(tile
), TileY(tile
)));
405 return DistanceManhattan(tile
, t
->xy
) < dist
;
408 /** Resize the sign (label) of the town after it changes population. */
409 void Town::UpdateVirtCoord()
411 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
413 if (this->cache
.sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeTown(this->index
));
415 SetDParam(0, this->index
);
416 SetDParam(1, this->cache
.population
);
417 this->cache
.sign
.UpdatePosition(pt
.x
, pt
.y
- 24 * ZOOM_BASE
,
418 _settings_client
.gui
.population_in_label
? STR_VIEWPORT_TOWN_POP
: STR_VIEWPORT_TOWN
,
419 STR_VIEWPORT_TOWN_TINY_WHITE
);
421 _viewport_sign_kdtree
.Insert(ViewportSignKdtreeItem::MakeTown(this->index
));
423 SetWindowDirty(WC_TOWN_VIEW
, this->index
);
426 /** Update the virtual coords needed to draw the town sign for all towns. */
427 void UpdateAllTownVirtCoords()
429 for (Town
*t
: Town::Iterate()) {
430 t
->UpdateVirtCoord();
434 /** Clear the cached_name of all towns. */
435 void ClearAllTownCachedNames()
437 for (Town
*t
: Town::Iterate()) {
438 t
->cached_name
.clear();
443 * Change the town's population as recorded in the town cache, town label, and town directory.
444 * @param t The town which has changed.
445 * @param mod The population change (can be positive or negative).
447 static void ChangePopulation(Town
*t
, int mod
)
449 t
->cache
.population
+= mod
;
450 if (_generating_town
) [[unlikely
]] return;
452 InvalidateWindowData(WC_TOWN_VIEW
, t
->index
); // Cargo requirements may appear/vanish for small populations
453 if (_settings_client
.gui
.population_in_label
) t
->UpdateVirtCoord();
455 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_POPULATION_CHANGE
);
459 * Get the total population, the sum of all towns in the world.
460 * @return The calculated population of the world
462 uint32_t GetWorldPopulation()
465 for (const Town
*t
: Town::Iterate()) pop
+= t
->cache
.population
;
470 * Remove stations from nearby station list if a town is no longer in the catchment area of each.
471 * To improve performance only checks stations that cover the provided house area (doesn't need to contain an actual house).
472 * @param t Town to work on.
473 * @param tile Location of house area (north tile).
474 * @param flags BuildingFlags containing the size of house area.
476 static void RemoveNearbyStations(Town
*t
, TileIndex tile
, BuildingFlags flags
)
478 for (StationList::iterator it
= t
->stations_near
.begin(); it
!= t
->stations_near
.end(); /* incremented inside loop */) {
479 const Station
*st
= *it
;
481 bool covers_area
= st
->TileIsInCatchment(tile
);
482 if (flags
& BUILDING_2_TILES_Y
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(0, 1));
483 if (flags
& BUILDING_2_TILES_X
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(1, 0));
484 if (flags
& BUILDING_HAS_4_TILES
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(1, 1));
486 if (covers_area
&& !st
->CatchmentCoversTown(t
->index
)) {
487 it
= t
->stations_near
.erase(it
);
495 * Helper function for house construction stage progression.
496 * @param tile TileIndex of the house (or parts of it) to construct.
498 static void AdvanceSingleHouseConstruction(TileIndex tile
)
500 assert(IsTileType(tile
, MP_HOUSE
));
502 /* Progress in construction stages */
503 IncHouseConstructionTick(tile
);
504 if (GetHouseConstructionTick(tile
) != 0) return;
506 AnimateNewHouseConstruction(tile
);
508 if (IsHouseCompleted(tile
)) {
509 /* Now that construction is complete, we can add the population of the
510 * building to the town. */
511 ChangePopulation(Town::GetByTile(tile
), HouseSpec::Get(GetHouseType(tile
))->population
);
514 MarkTileDirtyByTile(tile
);
518 * Increase the construction stage of a house.
519 * @param tile The tile of the house under construction.
521 static void AdvanceHouseConstruction(TileIndex tile
)
523 uint flags
= HouseSpec::Get(GetHouseType(tile
))->building_flags
;
524 if (flags
& BUILDING_HAS_1_TILE
) AdvanceSingleHouseConstruction(TileAddXY(tile
, 0, 0));
525 if (flags
& BUILDING_2_TILES_Y
) AdvanceSingleHouseConstruction(TileAddXY(tile
, 0, 1));
526 if (flags
& BUILDING_2_TILES_X
) AdvanceSingleHouseConstruction(TileAddXY(tile
, 1, 0));
527 if (flags
& BUILDING_HAS_4_TILES
) AdvanceSingleHouseConstruction(TileAddXY(tile
, 1, 1));
531 * Generate cargo for a house, scaled by the current economy scale.
532 * @param t The current town.
533 * @param ct Type of cargo to generate, usually CT_PASSENGERS or CT_MAIL.
534 * @param amount The number of cargo units.
535 * @param stations Available stations for this house.
536 * @param affected_by_recession Is this cargo halved during recessions?
538 static void TownGenerateCargo(Town
*t
, CargoID ct
, uint amount
, StationFinder
&stations
, bool affected_by_recession
)
540 if (amount
== 0) return;
542 /* All production is halved during a recession (except for NewGRF-supplied town cargo). */
543 if (affected_by_recession
&& EconomyIsInRecession()) {
544 amount
= (amount
+ 1) >> 1;
547 /* Scale by cargo scale setting. */
548 amount
= ScaleByCargoScale(amount
, true);
550 /* Actually generate cargo and update town statistics. */
551 t
->supplied
[ct
].new_max
+= amount
;
552 t
->supplied
[ct
].new_act
+= MoveGoodsToStation(ct
, amount
, SourceType::Town
, t
->index
, stations
.GetStations());;
556 * Generate cargo for a house using the original algorithm.
557 * @param t The current town.
558 * @param tpe The town production effect.
559 * @param rate The town's product rate for this production.
560 * @param stations Available stations for this house.
562 static void TownGenerateCargoOriginal(Town
*t
, TownProductionEffect tpe
, uint8_t rate
, StationFinder
&stations
)
564 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[tpe
]) {
565 uint32_t r
= Random();
566 if (GB(r
, 0, 8) < rate
) {
567 CargoID cid
= cs
->Index();
568 uint amt
= (GB(r
, 0, 8) * cs
->town_production_multiplier
/ TOWN_PRODUCTION_DIVISOR
) / 8 + 1;
570 TownGenerateCargo(t
, cid
, amt
, stations
, true);
576 * Generate cargo for a house using the binominal algorithm.
577 * @param t The current town.
578 * @param tpe The town production effect.
579 * @param rate The town's product rate for this production.
580 * @param stations Available stations for this house.
582 static void TownGenerateCargoBinominal(Town
*t
, TownProductionEffect tpe
, uint8_t rate
, StationFinder
&stations
)
584 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[tpe
]) {
585 CargoID cid
= cs
->Index();
586 uint32_t r
= Random();
588 /* Make a bitmask with up to 32 bits set, one for each potential pax. */
589 int genmax
= (rate
+ 7) / 8;
590 uint32_t genmask
= (genmax
>= 32) ? 0xFFFFFFFF : ((1 << genmax
) - 1);
592 /* Mask random value by potential pax and count number of actual pax. */
593 uint amt
= CountBits(r
& genmask
) * cs
->town_production_multiplier
/ TOWN_PRODUCTION_DIVISOR
;
595 TownGenerateCargo(t
, cid
, amt
, stations
, true);
600 * Tile callback function.
602 * Tile callback function. Periodic tick handler for the tiles of a town.
603 * @param tile been asked to do its stuff
605 static void TileLoop_Town(TileIndex tile
)
607 HouseID house_id
= GetHouseType(tile
);
609 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
610 * doesn't exist any more, so don't continue here. */
611 if (house_id
>= NEW_HOUSE_OFFSET
&& !NewHouseTileLoop(tile
)) return;
613 if (!IsHouseCompleted(tile
)) {
614 /* Construction is not completed, so we advance a construction stage. */
615 AdvanceHouseConstruction(tile
);
619 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
621 /* If the lift has a destination, it is already an animated tile. */
622 if ((hs
->building_flags
& BUILDING_IS_ANIMATED
) &&
623 house_id
< NEW_HOUSE_OFFSET
&&
624 !LiftHasDestination(tile
) &&
626 AddAnimatedTile(tile
);
629 Town
*t
= Town::GetByTile(tile
);
630 uint32_t r
= Random();
632 StationFinder
stations(TileArea(tile
, 1, 1));
634 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
635 for (uint i
= 0; i
< 256; i
++) {
636 uint16_t callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, r
, house_id
, t
, tile
);
638 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
640 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
641 if (!IsValidCargoID(cargo
)) continue;
643 uint amt
= GB(callback
, 0, 8);
644 if (amt
== 0) continue;
646 /* NewGRF-supplied town cargos are not affected by recessions. */
647 TownGenerateCargo(t
, cargo
, amt
, stations
, false);
650 switch (_settings_game
.economy
.town_cargogen_mode
) {
652 /* Original (quadratic) cargo generation algorithm */
653 TownGenerateCargoOriginal(t
, TPE_PASSENGERS
, hs
->population
, stations
);
654 TownGenerateCargoOriginal(t
, TPE_MAIL
, hs
->mail_generation
, stations
);
658 /* Binomial distribution per tick, by a series of coin flips */
659 /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
660 * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
661 if (GB(TimerGameTick::counter
, 8, 2) == GB(tile
.base(), 0, 2)) {
662 TownGenerateCargoBinominal(t
, TPE_PASSENGERS
, hs
->population
, stations
);
663 TownGenerateCargoBinominal(t
, TPE_MAIL
, hs
->mail_generation
, stations
);
672 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
);
674 if ((hs
->building_flags
& BUILDING_HAS_1_TILE
) &&
675 HasBit(t
->flags
, TOWN_IS_GROWING
) &&
676 CanDeleteHouse(tile
) &&
677 GetHouseAge(tile
) >= hs
->minimum_life
&&
678 --t
->time_until_rebuild
== 0) {
679 t
->time_until_rebuild
= GB(r
, 16, 8) + 192;
681 ClearTownHouse(t
, tile
);
683 /* Rebuild with another house? */
684 if (GB(r
, 24, 8) >= 12) {
685 /* If we are multi-tile houses, make sure to replace the house
686 * closest to city center. If we do not do this, houses tend to
687 * wander away from roads and other houses. */
688 if (hs
->building_flags
& BUILDING_HAS_2_TILES
) {
689 /* House tiles are always the most north tile. Move the new
690 * house to the south if we are north of the city center. */
691 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
692 int x
= Clamp(grid_pos
.x
, 0, 1);
693 int y
= Clamp(grid_pos
.y
, 0, 1);
695 if (hs
->building_flags
& TILE_SIZE_2x2
) {
696 tile
= TileAddXY(tile
, x
, y
);
697 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
698 tile
= TileAddXY(tile
, 0, y
);
699 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
700 tile
= TileAddXY(tile
, x
, 0);
704 TryBuildTownHouse(t
, tile
);
708 cur_company
.Restore();
712 * Callback function to clear a house tile.
713 * @param tile The tile to clear.
714 * @param flags Type of operation.
715 * @return The cost of this operation or an error.
717 static CommandCost
ClearTile_Town(TileIndex tile
, DoCommandFlag flags
)
719 if (flags
& DC_AUTO
) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
720 if (!CanDeleteHouse(tile
)) return CMD_ERROR
;
722 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
724 CommandCost
cost(EXPENSES_CONSTRUCTION
);
725 cost
.AddCost(hs
->GetRemovalCost());
727 int rating
= hs
->remove_rating_decrease
;
728 Town
*t
= Town::GetByTile(tile
);
730 if (Company::IsValidID(_current_company
)) {
731 if (rating
> t
->ratings
[_current_company
] && !(flags
& DC_NO_TEST_TOWN_RATING
) &&
732 !_cheats
.magic_bulldozer
.value
&& _settings_game
.difficulty
.town_council_tolerance
!= TOWN_COUNCIL_PERMISSIVE
) {
733 SetDParam(0, t
->index
);
734 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
738 ChangeTownRating(t
, -rating
, RATING_HOUSE_MINIMUM
, flags
);
739 if (flags
& DC_EXEC
) {
740 ClearTownHouse(t
, tile
);
746 static void AddProducedCargo_Town(TileIndex tile
, CargoArray
&produced
)
748 HouseID house_id
= GetHouseType(tile
);
749 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
750 Town
*t
= Town::GetByTile(tile
);
752 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
753 for (uint i
= 0; i
< 256; i
++) {
754 uint16_t callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, 0, house_id
, t
, tile
);
756 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
758 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
760 if (!IsValidCargoID(cargo
)) continue;
764 if (hs
->population
> 0) {
765 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[TPE_PASSENGERS
]) {
766 produced
[cs
->Index()]++;
769 if (hs
->mail_generation
> 0) {
770 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[TPE_MAIL
]) {
771 produced
[cs
->Index()]++;
778 * Fill cargo acceptance array and always_accepted mask, if cargo ID is valid.
779 * @param cargo Cargo type to add.
780 * @param amount Amount of cargo to add.
781 * @param[out] acceptance Output array containing amount of cargo accepted.
782 * @param[out] always_accepted Output mask of accepted cargo types.
784 static void AddAcceptedCargoSetMask(CargoID cargo
, uint amount
, CargoArray
&acceptance
, CargoTypes
&always_accepted
)
786 if (!IsValidCargoID(cargo
) || amount
== 0) return;
787 acceptance
[cargo
] += amount
;
788 SetBit(always_accepted
, cargo
);
791 static void AddAcceptedCargo_Town(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
&always_accepted
)
793 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
794 CargoID accepts
[lengthof(hs
->accepts_cargo
)];
796 /* Set the initial accepted cargo types */
797 for (uint8_t i
= 0; i
< lengthof(accepts
); i
++) {
798 accepts
[i
] = hs
->accepts_cargo
[i
];
801 /* Check for custom accepted cargo types */
802 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ACCEPT_CARGO
)) {
803 uint16_t callback
= GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
804 if (callback
!= CALLBACK_FAILED
) {
805 /* Replace accepted cargo types with translated values from callback */
806 accepts
[0] = GetCargoTranslation(GB(callback
, 0, 5), hs
->grf_prop
.grffile
);
807 accepts
[1] = GetCargoTranslation(GB(callback
, 5, 5), hs
->grf_prop
.grffile
);
808 accepts
[2] = GetCargoTranslation(GB(callback
, 10, 5), hs
->grf_prop
.grffile
);
812 /* Check for custom cargo acceptance */
813 if (HasBit(hs
->callback_mask
, CBM_HOUSE_CARGO_ACCEPTANCE
)) {
814 uint16_t callback
= GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
815 if (callback
!= CALLBACK_FAILED
) {
816 AddAcceptedCargoSetMask(accepts
[0], GB(callback
, 0, 4), acceptance
, always_accepted
);
817 AddAcceptedCargoSetMask(accepts
[1], GB(callback
, 4, 4), acceptance
, always_accepted
);
818 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
&& HasBit(callback
, 12)) {
819 /* The 'S' bit indicates food instead of goods */
820 AddAcceptedCargoSetMask(GetCargoIDByLabel(CT_FOOD
), GB(callback
, 8, 4), acceptance
, always_accepted
);
822 AddAcceptedCargoSetMask(accepts
[2], GB(callback
, 8, 4), acceptance
, always_accepted
);
828 /* No custom acceptance, so fill in with the default values */
829 for (uint8_t i
= 0; i
< lengthof(accepts
); i
++) {
830 AddAcceptedCargoSetMask(accepts
[i
], hs
->cargo_acceptance
[i
], acceptance
, always_accepted
);
834 static void GetTileDesc_Town(TileIndex tile
, TileDesc
*td
)
836 const HouseID house
= GetHouseType(tile
);
837 const HouseSpec
*hs
= HouseSpec::Get(house
);
838 bool house_completed
= IsHouseCompleted(tile
);
840 td
->str
= hs
->building_name
;
842 uint16_t callback_res
= GetHouseCallback(CBID_HOUSE_CUSTOM_NAME
, house_completed
? 1 : 0, 0, house
, Town::GetByTile(tile
), tile
);
843 if (callback_res
!= CALLBACK_FAILED
&& callback_res
!= 0x400) {
844 if (callback_res
> 0x400) {
845 ErrorUnknownCallbackResult(hs
->grf_prop
.grffile
->grfid
, CBID_HOUSE_CUSTOM_NAME
, callback_res
);
847 StringID new_name
= GetGRFStringID(hs
->grf_prop
.grffile
->grfid
, 0xD000 + callback_res
);
848 if (new_name
!= STR_NULL
&& new_name
!= STR_UNDEFINED
) {
854 if (!house_completed
) {
855 td
->dparam
= td
->str
;
856 td
->str
= STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION
;
859 if (hs
->grf_prop
.grffile
!= nullptr) {
860 const GRFConfig
*gc
= GetGRFConfig(hs
->grf_prop
.grffile
->grfid
);
861 td
->grf
= gc
->GetName();
864 td
->owner
[0] = OWNER_TOWN
;
867 static TrackStatus
GetTileTrackStatus_Town(TileIndex
, TransportType
, uint
, DiagDirection
)
873 static void ChangeTileOwner_Town(TileIndex
, Owner
, Owner
)
878 static bool GrowTown(Town
*t
);
881 * Handle the town tick for a single town, by growing the town if desired.
882 * @param t The town to try growing.
884 static void TownTickHandler(Town
*t
)
886 if (HasBit(t
->flags
, TOWN_IS_GROWING
)) {
887 int i
= (int)t
->grow_counter
- 1;
892 /* If growth failed wait a bit before retrying */
893 i
= std::min
<uint16_t>(t
->growth_rate
, Ticks::TOWN_GROWTH_TICKS
- 1);
900 /** Iterate through all towns and call their tick handler. */
903 if (_game_mode
== GM_EDITOR
) return;
905 for (Town
*t
: Town::Iterate()) {
911 * Return the RoadBits of a tile, ignoring depot and bay road stops.
912 * @param tile The tile to check.
913 * @return The roadbits of the given tile.
915 static RoadBits
GetTownRoadBits(TileIndex tile
)
917 if (IsRoadDepotTile(tile
) || IsBayRoadStopTile(tile
)) return ROAD_NONE
;
919 return GetAnyRoadBits(tile
, RTT_ROAD
, true);
923 * Get the road type that towns should build at this current moment.
924 * They may have built a different type in the past.
926 RoadType
GetTownRoadType()
928 RoadType best_rt
= ROADTYPE_ROAD
;
929 const RoadTypeInfo
*best
= nullptr;
930 const uint16_t assume_max_speed
= 50;
932 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
933 if (RoadTypeIsTram(rt
)) continue;
935 const RoadTypeInfo
*rti
= GetRoadTypeInfo(rt
);
937 /* Unused road type. */
938 if (rti
->label
== 0) continue;
940 /* Can town build this road. */
941 if (!HasBit(rti
->flags
, ROTF_TOWN_BUILD
)) continue;
943 /* Not yet introduced at this date. */
944 if (IsInsideMM(rti
->introduction_date
, 0, CalendarTime::MAX_DATE
.base()) && rti
->introduction_date
> TimerGameCalendar::date
) continue;
946 if (best
!= nullptr) {
947 if ((rti
->max_speed
== 0 ? assume_max_speed
: rti
->max_speed
) < (best
->max_speed
== 0 ? assume_max_speed
: best
->max_speed
)) continue;
958 * Get the calendar date of the earliest town-buildable road type.
959 * @return introduction date of earliest road type, or INT32_MAX if none available.
961 static TimerGameCalendar::Date
GetTownRoadTypeFirstIntroductionDate()
963 const RoadTypeInfo
*best
= nullptr;
964 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
965 if (RoadTypeIsTram(rt
)) continue;
966 const RoadTypeInfo
*rti
= GetRoadTypeInfo(rt
);
967 if (rti
->label
== 0) continue; // Unused road type.
968 if (!HasBit(rti
->flags
, ROTF_TOWN_BUILD
)) continue; // Town can't build this road type.
970 if (best
!= nullptr && rti
->introduction_date
>= best
->introduction_date
) continue;
974 if (best
== nullptr) return INT32_MAX
;
975 return best
->introduction_date
;
979 * Check if towns are able to build road.
980 * @return true iff the towns are currently able to build road.
982 bool CheckTownRoadTypes()
984 auto min_date
= GetTownRoadTypeFirstIntroductionDate();
985 if (min_date
<= TimerGameCalendar::date
) return true;
987 if (min_date
< INT32_MAX
) {
988 SetDParam(0, min_date
);
989 ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET
, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET_EXPLANATION
, WL_CRITICAL
);
991 ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL
, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL_EXPLANATION
, WL_CRITICAL
);
997 * Check for parallel road inside a given distance.
998 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
999 * is there a parallel road left or right of it within distance dist_multi?
1001 * @param tile The current tile.
1002 * @param dir The target direction.
1003 * @param dist_multi The distance multiplier.
1004 * @return true if there is a parallel road.
1006 static bool IsNeighborRoadTile(TileIndex tile
, const DiagDirection dir
, uint dist_multi
)
1008 if (!IsValidTile(tile
)) return false;
1010 /* Lookup table for the used diff values */
1011 const TileIndexDiff tid_lt
[3] = {
1012 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90RIGHT
)),
1013 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90LEFT
)),
1014 TileOffsByDiagDir(ReverseDiagDir(dir
)),
1017 dist_multi
= (dist_multi
+ 1) * 4;
1018 for (uint pos
= 4; pos
< dist_multi
; pos
++) {
1019 /* Go (pos / 4) tiles to the left or the right */
1020 TileIndexDiff cur
= tid_lt
[(pos
& 1) ? 0 : 1] * (pos
/ 4);
1022 /* Use the current tile as origin, or go one tile backwards */
1023 if (pos
& 2) cur
+= tid_lt
[2];
1025 /* Test for roadbit parallel to dir and facing towards the middle axis */
1026 if (IsValidTile(tile
+ cur
) &&
1027 GetTownRoadBits(TileAdd(tile
, cur
)) & DiagDirToRoadBits((pos
& 2) ? dir
: ReverseDiagDir(dir
))) return true;
1033 * Check if a Road is allowed on a given tile.
1035 * @param t The current town.
1036 * @param tile The target tile.
1037 * @param dir The direction in which we want to extend the town.
1038 * @return true if it is allowed.
1040 static bool IsRoadAllowedHere(Town
*t
, TileIndex tile
, DiagDirection dir
)
1042 if (DistanceFromEdge(tile
) == 0) return false;
1044 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
1045 if (IsBridgeAbove(tile
) && GetBridgeAxis(tile
) == DiagDirToAxis(dir
)) return false;
1047 /* Check if there already is a road at this point? */
1048 if (GetTownRoadBits(tile
) == ROAD_NONE
) {
1049 /* No, try if we are able to build a road piece there.
1050 * If that fails clear the land, and if that fails exit.
1051 * This is to make sure that we can build a road here later. */
1052 RoadType rt
= GetTownRoadType();
1053 if (Command
<CMD_BUILD_ROAD
>::Do(DC_AUTO
| DC_NO_WATER
, tile
, (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? ROAD_Y
: ROAD_X
, rt
, DRD_NONE
, 0).Failed() &&
1054 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Failed()) {
1059 Slope cur_slope
= _settings_game
.construction
.build_on_slopes
? std::get
<0>(GetFoundationSlope(tile
)) : GetTileSlope(tile
);
1060 bool ret
= !IsNeighborRoadTile(tile
, dir
, t
->layout
== TL_ORIGINAL
? 1 : 2);
1061 if (cur_slope
== SLOPE_FLAT
) return ret
;
1063 /* If the tile is not a slope in the right direction, then
1064 * maybe terraform some. */
1065 Slope desired_slope
= (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? SLOPE_NW
: SLOPE_NE
;
1066 if (desired_slope
!= cur_slope
&& ComplementSlope(desired_slope
) != cur_slope
) {
1067 if (Chance16(1, 8)) {
1068 CommandCost res
= CMD_ERROR
;
1069 if (!_generating_world
&& Chance16(1, 10)) {
1070 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
1071 res
= std::get
<0>(Command
<CMD_TERRAFORM_LAND
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
,
1072 tile
, Chance16(1, 16) ? cur_slope
: cur_slope
^ SLOPE_ELEVATED
, false));
1074 if (res
.Failed() && Chance16(1, 3)) {
1075 /* We can consider building on the slope, though. */
1084 static bool TerraformTownTile(TileIndex tile
, Slope edges
, bool dir
)
1086 assert(tile
< Map::Size());
1088 CommandCost r
= std::get
<0>(Command
<CMD_TERRAFORM_LAND
>::Do(DC_AUTO
| DC_NO_WATER
, tile
, edges
, dir
));
1089 if (r
.Failed() || r
.GetCost() >= (_price
[PR_TERRAFORM
] + 2) * 8) return false;
1090 Command
<CMD_TERRAFORM_LAND
>::Do(DC_AUTO
| DC_NO_WATER
| DC_EXEC
, tile
, edges
, dir
);
1094 static void LevelTownLand(TileIndex tile
)
1096 assert(tile
< Map::Size());
1098 /* Don't terraform if land is plain or if there's a house there. */
1099 if (IsTileType(tile
, MP_HOUSE
)) return;
1100 Slope tileh
= GetTileSlope(tile
);
1101 if (tileh
== SLOPE_FLAT
) return;
1103 /* First try up, then down */
1104 if (!TerraformTownTile(tile
, ~tileh
& SLOPE_ELEVATED
, true)) {
1105 TerraformTownTile(tile
, tileh
& SLOPE_ELEVATED
, false);
1110 * Generate the RoadBits of a grid tile.
1112 * @param t The current town.
1113 * @param tile The tile in reference to the town.
1114 * @param dir The direction to which we are growing.
1115 * @return The RoadBit of the current tile regarding the selected town layout.
1117 static RoadBits
GetTownRoadGridElement(Town
*t
, TileIndex tile
, DiagDirection dir
)
1119 /* align the grid to the downtown */
1120 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
); // Vector from downtown to the tile
1121 RoadBits rcmd
= ROAD_NONE
;
1123 switch (t
->layout
) {
1124 default: NOT_REACHED();
1127 if ((grid_pos
.x
% 3) == 0) rcmd
|= ROAD_Y
;
1128 if ((grid_pos
.y
% 3) == 0) rcmd
|= ROAD_X
;
1132 if ((grid_pos
.x
% 4) == 0) rcmd
|= ROAD_Y
;
1133 if ((grid_pos
.y
% 4) == 0) rcmd
|= ROAD_X
;
1137 /* Optimise only X-junctions */
1138 if (rcmd
!= ROAD_ALL
) return rcmd
;
1140 RoadBits rb_template
;
1142 switch (GetTileSlope(tile
)) {
1143 default: rb_template
= ROAD_ALL
; break;
1144 case SLOPE_W
: rb_template
= ROAD_NW
| ROAD_SW
; break;
1145 case SLOPE_SW
: rb_template
= ROAD_Y
| ROAD_SW
; break;
1146 case SLOPE_S
: rb_template
= ROAD_SW
| ROAD_SE
; break;
1147 case SLOPE_SE
: rb_template
= ROAD_X
| ROAD_SE
; break;
1148 case SLOPE_E
: rb_template
= ROAD_SE
| ROAD_NE
; break;
1149 case SLOPE_NE
: rb_template
= ROAD_Y
| ROAD_NE
; break;
1150 case SLOPE_N
: rb_template
= ROAD_NE
| ROAD_NW
; break;
1151 case SLOPE_NW
: rb_template
= ROAD_X
| ROAD_NW
; break;
1156 rb_template
= ROAD_NONE
;
1160 /* Stop if the template is compatible to the growth dir */
1161 if (DiagDirToRoadBits(ReverseDiagDir(dir
)) & rb_template
) return rb_template
;
1162 /* If not generate a straight road in the direction of the growth */
1163 return DiagDirToRoadBits(dir
) | DiagDirToRoadBits(ReverseDiagDir(dir
));
1167 * Grows the town with an extra house.
1168 * Check if there are enough neighbor house tiles
1169 * next to the current tile. If there are enough
1170 * add another house.
1172 * @param t The current town.
1173 * @param tile The target tile for the extra house.
1174 * @return true if an extra house has been added.
1176 static bool GrowTownWithExtraHouse(Town
*t
, TileIndex tile
)
1178 /* We can't look further than that. */
1179 if (DistanceFromEdge(tile
) == 0) return false;
1181 uint counter
= 0; // counts the house neighbor tiles
1183 /* Check the tiles E,N,W and S of the current tile for houses */
1184 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
< DIAGDIR_END
; dir
++) {
1185 /* Count both void and house tiles for checking whether there
1186 * are enough houses in the area. This to make it likely that
1187 * houses get build up to the edge of the map. */
1188 switch (GetTileType(TileAddByDiagDir(tile
, dir
))) {
1198 /* If there are enough neighbors stop here */
1200 if (TryBuildTownHouse(t
, tile
)) {
1201 _grow_town_result
= GROWTH_SUCCEED
;
1211 * Grows the town with a road piece.
1213 * @param t The current town.
1214 * @param tile The current tile.
1215 * @param rcmd The RoadBits we want to build on the tile.
1216 * @return true if the RoadBits have been added.
1218 static bool GrowTownWithRoad(const Town
*t
, TileIndex tile
, RoadBits rcmd
)
1220 RoadType rt
= GetTownRoadType();
1221 if (Command
<CMD_BUILD_ROAD
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
, tile
, rcmd
, rt
, DRD_NONE
, t
->index
).Succeeded()) {
1222 _grow_town_result
= GROWTH_SUCCEED
;
1229 * Checks if a town road can be continued into the next tile.
1230 * Road vehicle stations, bridges, and tunnels are fine, as long as they are facing the right direction.
1232 * @param t The current town
1233 * @param tile The tile where the road would be built
1234 * @param road_dir The direction of the road
1235 * @return true if the road can be continued, else false
1237 static bool CanRoadContinueIntoNextTile(const Town
*t
, const TileIndex tile
, const DiagDirection road_dir
)
1239 const TileIndexDiff delta
= TileOffsByDiagDir(road_dir
); // +1 tile in the direction of the road
1240 TileIndex next_tile
= tile
+ delta
; // The tile beyond which must be connectable to the target tile
1241 RoadBits rcmd
= DiagDirToRoadBits(ReverseDiagDir(road_dir
));
1242 RoadType rt
= GetTownRoadType();
1244 /* Before we try anything, make sure the tile is on the map and not the void. */
1245 if (!IsValidTile(next_tile
)) return false;
1247 /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1248 if (IsTileType(next_tile
, MP_TUNNELBRIDGE
)) {
1249 return GetTunnelBridgeTransportType(next_tile
) == TRANSPORT_ROAD
&& GetTunnelBridgeDirection(next_tile
) == road_dir
;
1252 /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1253 if (IsTileType(next_tile
, MP_STATION
)) {
1254 /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1255 return IsAnyRoadStop(next_tile
) && (GetRoadStopDir(next_tile
) == ReverseDiagDir(road_dir
) || (IsDriveThroughStopTile(next_tile
) && GetRoadStopDir(next_tile
) == road_dir
));
1258 /* If the next tile is a road depot, allow if it's facing the right way. */
1259 if (IsTileType(next_tile
, MP_ROAD
)) {
1260 return IsRoadDepot(next_tile
) && GetRoadDepotDirection(next_tile
) == ReverseDiagDir(road_dir
);
1263 /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1264 * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1265 if (IsTileType(next_tile
, MP_RAILWAY
) && !_settings_game
.economy
.allow_town_level_crossings
) return false;
1267 /* If a road tile can be built, the construction is allowed. */
1268 return Command
<CMD_BUILD_ROAD
>::Do(DC_AUTO
| DC_NO_WATER
, next_tile
, rcmd
, rt
, DRD_NONE
, t
->index
).Succeeded();
1272 * CircularTileSearch proc which checks for a nearby parallel bridge to avoid building redundant bridges.
1273 * @param tile The tile to search.
1274 * @param user_data Reference to the valid direction of the proposed bridge.
1275 * @return true if another bridge exists, else false.
1277 static bool RedundantBridgeExistsNearby(TileIndex tile
, void *user_data
)
1279 /* Don't look into the void. */
1280 if (!IsValidTile(tile
)) return false;
1282 /* Only consider bridge head tiles. */
1283 if (!IsBridgeTile(tile
)) return false;
1285 /* Only consider road bridges. */
1286 if (GetTunnelBridgeTransportType(tile
) != TRANSPORT_ROAD
) return false;
1288 /* If the bridge is facing the same direction as the proposed bridge, we've found a redundant bridge. */
1289 return (GetTileSlope(tile
) & InclinedSlope(ReverseDiagDir(*(DiagDirection
*)user_data
)));
1293 * Grows the town with a bridge.
1294 * At first we check if a bridge is reasonable.
1295 * If so we check if we are able to build it.
1297 * @param t The current town
1298 * @param tile The current tile
1299 * @param bridge_dir The valid direction in which to grow a bridge
1300 * @return true if a bridge has been build else false
1302 static bool GrowTownWithBridge(const Town
*t
, const TileIndex tile
, const DiagDirection bridge_dir
)
1304 assert(bridge_dir
< DIAGDIR_END
);
1306 const Slope slope
= GetTileSlope(tile
);
1308 /* Make sure the direction is compatible with the slope.
1309 * Well we check if the slope has an up bit set in the
1310 * reverse direction. */
1311 if (slope
!= SLOPE_FLAT
&& slope
& InclinedSlope(bridge_dir
)) return false;
1313 /* Assure that the bridge is connectable to the start side */
1314 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(bridge_dir
))) & DiagDirToRoadBits(bridge_dir
))) return false;
1316 /* We are in the right direction */
1317 uint bridge_length
= 0; // This value stores the length of the possible bridge
1318 TileIndex bridge_tile
= tile
; // Used to store the other waterside
1320 const TileIndexDiff delta
= TileOffsByDiagDir(bridge_dir
);
1322 /* To prevent really small towns from building disproportionately
1323 * long bridges, make the max a function of its population. */
1324 const uint TOWN_BRIDGE_LENGTH_CAP
= 11;
1325 uint base_bridge_length
= 5;
1326 uint max_bridge_length
= std::min(t
->cache
.population
/ 1000 + base_bridge_length
, TOWN_BRIDGE_LENGTH_CAP
);
1328 if (slope
== SLOPE_FLAT
) {
1329 /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1331 if (bridge_length
++ >= base_bridge_length
) {
1332 /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1335 bridge_tile
+= delta
;
1336 } while (IsValidTile(bridge_tile
) && ((IsWaterTile(bridge_tile
) && !IsSea(bridge_tile
)) || IsPlainRailTile(bridge_tile
) || (IsNormalRoadTile(bridge_tile
) && GetDisallowedRoadDirections(bridge_tile
) != DRD_NONE
)));
1339 if (bridge_length
++ >= max_bridge_length
) {
1340 /* Ensure the bridge is not longer than the max allowed length. */
1343 bridge_tile
+= delta
;
1344 } while (IsValidTile(bridge_tile
) && (IsWaterTile(bridge_tile
) || IsPlainRailTile(bridge_tile
) || (IsNormalRoadTile(bridge_tile
) && GetDisallowedRoadDirections(bridge_tile
) != DRD_NONE
)));
1347 /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1348 if (bridge_length
== 1) return false;
1350 /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1351 if (!CanRoadContinueIntoNextTile(t
, bridge_tile
, bridge_dir
)) return false;
1353 /* If another parallel bridge exists nearby, this one would be redundant and shouldn't be built. We don't care about flat bridges. */
1354 TileIndex search
= tile
;
1355 DiagDirection direction_to_match
= bridge_dir
;
1356 if (slope
!= SLOPE_FLAT
&& CircularTileSearch(&search
, bridge_length
, 0, 0, RedundantBridgeExistsNearby
, &direction_to_match
)) return false;
1358 for (uint8_t times
= 0; times
<= 22; times
++) {
1359 uint8_t bridge_type
= RandomRange(MAX_BRIDGES
- 1);
1361 /* Can we actually build the bridge? */
1362 RoadType rt
= GetTownRoadType();
1363 if (Command
<CMD_BUILD_BRIDGE
>::Do(CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_BRIDGE
>()), tile
, bridge_tile
, TRANSPORT_ROAD
, bridge_type
, rt
).Succeeded()) {
1364 Command
<CMD_BUILD_BRIDGE
>::Do(DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_BRIDGE
>()), tile
, bridge_tile
, TRANSPORT_ROAD
, bridge_type
, rt
);
1365 _grow_town_result
= GROWTH_SUCCEED
;
1369 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1374 * Grows the town with a tunnel.
1375 * First we check if a tunnel is reasonable.
1376 * If so we check if we are able to build it.
1378 * @param t The current town
1379 * @param tile The current tile
1380 * @param tunnel_dir The valid direction in which to grow a tunnel
1381 * @return true if a tunnel has been built, else false
1383 static bool GrowTownWithTunnel(const Town
*t
, const TileIndex tile
, const DiagDirection tunnel_dir
)
1385 assert(tunnel_dir
< DIAGDIR_END
);
1387 Slope slope
= GetTileSlope(tile
);
1389 /* Only consider building a tunnel if the starting tile is sloped properly. */
1390 if (slope
!= InclinedSlope(tunnel_dir
)) return false;
1392 /* Assure that the tunnel is connectable to the start side */
1393 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(tunnel_dir
))) & DiagDirToRoadBits(tunnel_dir
))) return false;
1395 const TileIndexDiff delta
= TileOffsByDiagDir(tunnel_dir
);
1396 int max_tunnel_length
= 0;
1398 /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1399 if (CanRoadContinueIntoNextTile(t
, tile
, tunnel_dir
)) {
1400 /* Only tunnel under a mountain if the slope is continuous for at least 4 tiles. We want tunneling to be a last resort for large hills. */
1401 TileIndex slope_tile
= tile
;
1402 for (uint8_t tiles
= 0; tiles
< 4; tiles
++) {
1403 if (!IsValidTile(slope_tile
)) return false;
1404 slope
= GetTileSlope(slope_tile
);
1405 if (slope
!= InclinedSlope(tunnel_dir
) && !IsSteepSlope(slope
) && !IsSlopeWithOneCornerRaised(slope
)) return false;
1406 slope_tile
+= delta
;
1409 /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which neccesitates tunneling. */
1410 max_tunnel_length
= (t
->cache
.population
/ 1000) + 7;
1412 /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1413 max_tunnel_length
= 5;
1416 uint8_t tunnel_length
= 0;
1417 TileIndex tunnel_tile
= tile
; // Iteratator to store the other end tile of the tunnel.
1419 /* Find the end tile of the tunnel for length and continuation checks. */
1421 if (tunnel_length
++ >= max_tunnel_length
) return false;
1422 tunnel_tile
+= delta
;
1423 /* The tunnel ends when start and end tiles are the same height. */
1424 } while (IsValidTile(tunnel_tile
) && GetTileZ(tile
) != GetTileZ(tunnel_tile
));
1426 /* Don't allow a tunnel where the start and end tiles are adjacent. */
1427 if (tunnel_length
== 1) return false;
1429 /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1430 if (!CanRoadContinueIntoNextTile(t
, tunnel_tile
, tunnel_dir
)) return false;
1432 /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1433 RoadType rt
= GetTownRoadType();
1434 if (Command
<CMD_BUILD_TUNNEL
>::Do(CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_TUNNEL
>()), tile
, TRANSPORT_ROAD
, rt
).Succeeded()) {
1435 Command
<CMD_BUILD_TUNNEL
>::Do(DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_TUNNEL
>()), tile
, TRANSPORT_ROAD
, rt
);
1436 _grow_town_result
= GROWTH_SUCCEED
;
1444 * Checks whether at least one surrounding road allows to build a house here.
1446 * @param t The tile where the house will be built.
1447 * @return true if at least one surrounding roadtype allows building houses here.
1449 static inline bool RoadTypesAllowHouseHere(TileIndex t
)
1451 static const TileIndexDiffC tiles
[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1454 for (const auto &ptr
: tiles
) {
1455 TileIndex cur_tile
= t
+ ToTileIndexDiff(ptr
);
1456 if (!IsValidTile(cur_tile
)) continue;
1458 if (!(IsTileType(cur_tile
, MP_ROAD
) || IsAnyRoadStopTile(cur_tile
))) continue;
1461 RoadType road_rt
= GetRoadTypeRoad(cur_tile
);
1462 RoadType tram_rt
= GetRoadTypeTram(cur_tile
);
1463 if (road_rt
!= INVALID_ROADTYPE
&& !HasBit(GetRoadTypeInfo(road_rt
)->flags
, ROTF_NO_HOUSES
)) return true;
1464 if (tram_rt
!= INVALID_ROADTYPE
&& !HasBit(GetRoadTypeInfo(tram_rt
)->flags
, ROTF_NO_HOUSES
)) return true;
1467 /* If no road was found surrounding the tile we can allow building the house since there is
1468 * nothing which forbids it, if a road was found but the execution reached this point, then
1469 * all the found roads don't allow houses to be built */
1473 /** Test if town can grow road onto a specific tile.
1474 * @param tile Tile to build upon.
1475 * @return true iff the tile's road type don't prevent extending the road.
1477 static bool TownCanGrowRoad(TileIndex tile
)
1479 if (!IsTileType(tile
, MP_ROAD
)) return true;
1481 /* Allow extending on roadtypes which can be built by town, or if the road type matches the type the town will build. */
1482 RoadType rt
= GetRoadTypeRoad(tile
);
1483 return HasBit(GetRoadTypeInfo(rt
)->flags
, ROTF_TOWN_BUILD
) || GetTownRoadType() == rt
;
1487 * Check if the town is allowed to build roads.
1488 * @return true If the town is allowed to build roads.
1490 static inline bool TownAllowedToBuildRoads()
1492 return _settings_game
.economy
.allow_town_roads
|| _generating_world
|| _game_mode
== GM_EDITOR
;
1496 * Grows the given town.
1497 * There are at the moment 3 possible way's for
1498 * the town expansion:
1499 * @li Generate a random tile and check if there is a road allowed
1501 * @li TL_BETTER_ROADS
1502 * @li Check if the town geometry allows a road and which one
1505 * @li Forbid roads, only build houses
1507 * @param tile_ptr The current tile
1508 * @param cur_rb The current tiles RoadBits
1509 * @param target_dir The target road dir
1510 * @param t1 The current town
1512 static void GrowTownInTile(TileIndex
*tile_ptr
, RoadBits cur_rb
, DiagDirection target_dir
, Town
*t1
)
1514 RoadBits rcmd
= ROAD_NONE
; // RoadBits for the road construction command
1515 TileIndex tile
= *tile_ptr
; // The main tile on which we base our growth
1517 assert(tile
< Map::Size());
1519 if (cur_rb
== ROAD_NONE
) {
1520 /* Tile has no road. First reset the status counter
1521 * to say that this is the last iteration. */
1522 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1524 if (!TownAllowedToBuildRoads()) return;
1525 if (!_settings_game
.economy
.allow_town_level_crossings
&& IsTileType(tile
, MP_RAILWAY
)) return;
1527 /* Remove hills etc */
1528 if (!_settings_game
.construction
.build_on_slopes
|| Chance16(1, 6)) LevelTownLand(tile
);
1530 /* Is a road allowed here? */
1531 switch (t1
->layout
) {
1532 default: NOT_REACHED();
1536 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1537 if (rcmd
== ROAD_NONE
) return;
1540 case TL_BETTER_ROADS
:
1542 if (!IsRoadAllowedHere(t1
, tile
, target_dir
)) return;
1544 DiagDirection source_dir
= ReverseDiagDir(target_dir
);
1546 if (Chance16(1, 4)) {
1547 /* Randomize a new target dir */
1548 do target_dir
= RandomDiagDir(); while (target_dir
== source_dir
);
1551 if (!IsRoadAllowedHere(t1
, TileAddByDiagDir(tile
, target_dir
), target_dir
)) {
1552 /* A road is not allowed to continue the randomized road,
1553 * return if the road we're trying to build is curved. */
1554 if (target_dir
!= ReverseDiagDir(source_dir
)) return;
1556 /* Return if neither side of the new road is a house */
1557 if (!IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90RIGHT
)), MP_HOUSE
) &&
1558 !IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90LEFT
)), MP_HOUSE
)) {
1562 /* That means that the road is only allowed if there is a house
1563 * at any side of the new road. */
1566 rcmd
= DiagDirToRoadBits(target_dir
) | DiagDirToRoadBits(source_dir
);
1570 } else if (target_dir
< DIAGDIR_END
&& !(cur_rb
& DiagDirToRoadBits(ReverseDiagDir(target_dir
)))) {
1571 if (!TownCanGrowRoad(tile
)) return;
1573 /* Continue building on a partial road.
1574 * Should be always OK, so we only generate
1575 * the fitting RoadBits */
1576 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1578 if (!TownAllowedToBuildRoads()) return;
1580 switch (t1
->layout
) {
1581 default: NOT_REACHED();
1585 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1588 case TL_BETTER_ROADS
:
1590 rcmd
= DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1594 bool allow_house
= true; // Value which decides if we want to construct a house
1596 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1597 * it is the starting tile. Half the time, we stay on this side then.*/
1598 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1599 if (GetTunnelBridgeTransportType(tile
) == TRANSPORT_ROAD
&& (target_dir
!= DIAGDIR_END
|| Chance16(1, 2))) {
1600 *tile_ptr
= GetOtherTunnelBridgeEnd(tile
);
1605 /* Possibly extend the road in a direction.
1606 * Randomize a direction and if it has a road, bail out. */
1607 target_dir
= RandomDiagDir();
1608 RoadBits target_rb
= DiagDirToRoadBits(target_dir
);
1609 TileIndex house_tile
; // position of a possible house
1611 if (cur_rb
& target_rb
) {
1612 /* If it's a road turn possibly build a house in a corner.
1613 * Use intersection with straight road as an indicator
1614 * that we randomed corner house position.
1615 * A turn (and we check for that later) always has only
1616 * one common bit with a straight road so it has the same
1617 * chance to be chosen as the house on the side of a road.
1619 if ((cur_rb
& ROAD_X
) != target_rb
) return;
1621 /* Check whether it is a turn and if so determine
1622 * position of the corner tile */
1625 house_tile
= TileAddByDir(tile
, DIR_S
);
1628 house_tile
= TileAddByDir(tile
, DIR_N
);
1631 house_tile
= TileAddByDir(tile
, DIR_W
);
1634 house_tile
= TileAddByDir(tile
, DIR_E
);
1637 return; // not a turn
1639 target_dir
= DIAGDIR_END
;
1641 house_tile
= TileAddByDiagDir(tile
, target_dir
);
1644 /* Don't walk into water. */
1645 if (HasTileWaterGround(house_tile
)) return;
1647 if (!IsValidTile(house_tile
)) return;
1649 if (target_dir
!= DIAGDIR_END
&& TownAllowedToBuildRoads()) {
1650 switch (t1
->layout
) {
1651 default: NOT_REACHED();
1653 case TL_3X3_GRID
: // Use 2x2 grid afterwards!
1654 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1658 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1659 allow_house
= (rcmd
& target_rb
) == ROAD_NONE
;
1662 case TL_BETTER_ROADS
: // Use original afterwards!
1663 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1667 /* Allow a house at the edge. 60% chance or
1668 * always ok if no road allowed. */
1670 allow_house
= (!IsRoadAllowedHere(t1
, house_tile
, target_dir
) || Chance16(6, 10));
1675 allow_house
&= RoadTypesAllowHouseHere(house_tile
);
1678 /* Build a house, but not if there already is a house there. */
1679 if (!IsTileType(house_tile
, MP_HOUSE
)) {
1680 /* Level the land if possible */
1681 if (Chance16(1, 6)) LevelTownLand(house_tile
);
1683 /* And build a house.
1684 * Set result to -1 if we managed to build it. */
1685 if (TryBuildTownHouse(t1
, house_tile
)) {
1686 _grow_town_result
= GROWTH_SUCCEED
;
1692 if (!TownCanGrowRoad(tile
)) return;
1694 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1697 /* Return if a water tile */
1698 if (HasTileWaterGround(tile
)) return;
1700 /* Make the roads look nicer */
1701 rcmd
= CleanUpRoadBits(tile
, rcmd
);
1702 if (rcmd
== ROAD_NONE
) return;
1704 /* Only use the target direction for bridges and tunnels to ensure they're connected.
1705 * The target_dir is as computed previously according to town layout, so
1706 * it will match it perfectly. */
1707 if (GrowTownWithBridge(t1
, tile
, target_dir
)) return;
1708 if (GrowTownWithTunnel(t1
, tile
, target_dir
)) return;
1710 GrowTownWithRoad(t1
, tile
, rcmd
);
1714 * Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
1715 * This only checks trivial but often cases.
1716 * @param tile Start tile for road.
1717 * @param dir Direction for road to follow or build.
1718 * @return true If road is or can be connected in the specified direction.
1720 static bool CanFollowRoad(TileIndex tile
, DiagDirection dir
)
1722 TileIndex target_tile
= tile
+ TileOffsByDiagDir(dir
);
1723 if (!IsValidTile(target_tile
)) return false;
1724 if (HasTileWaterGround(target_tile
)) return false;
1726 RoadBits target_rb
= GetTownRoadBits(target_tile
);
1727 if (TownAllowedToBuildRoads()) {
1728 /* Check whether a road connection exists or can be build. */
1729 switch (GetTileType(target_tile
)) {
1731 return target_rb
!= ROAD_NONE
;
1734 return IsDriveThroughStopTile(target_tile
);
1736 case MP_TUNNELBRIDGE
:
1737 return GetTunnelBridgeTransportType(target_tile
) == TRANSPORT_ROAD
;
1745 /* Checked for void and water earlier */
1749 /* Check whether a road connection already exists,
1750 * and it leads somewhere else. */
1751 RoadBits back_rb
= DiagDirToRoadBits(ReverseDiagDir(dir
));
1752 return (target_rb
& back_rb
) != 0 && (target_rb
& ~back_rb
) != 0;
1757 * Try to grow a town at a given road tile.
1758 * @param t The town to grow.
1759 * @param tile The road tile to try growing from.
1760 * @return true if we successfully expanded the town.
1762 static bool GrowTownAtRoad(Town
*t
, TileIndex tile
)
1765 * @see GrowTownInTile Check the else if
1767 DiagDirection target_dir
= DIAGDIR_END
; // The direction in which we want to extend the town
1769 assert(tile
< Map::Size());
1771 /* Number of times to search.
1772 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1773 * them a little handicap. */
1774 switch (t
->layout
) {
1775 case TL_BETTER_ROADS
:
1776 _grow_town_result
= 10 + t
->cache
.num_houses
* 2 / 9;
1781 _grow_town_result
= 10 + t
->cache
.num_houses
* 1 / 9;
1785 _grow_town_result
= 10 + t
->cache
.num_houses
* 4 / 9;
1790 RoadBits cur_rb
= GetTownRoadBits(tile
); // The RoadBits of the current tile
1792 /* Try to grow the town from this point */
1793 GrowTownInTile(&tile
, cur_rb
, target_dir
, t
);
1794 if (_grow_town_result
== GROWTH_SUCCEED
) return true;
1796 /* Exclude the source position from the bitmask
1797 * and return if no more road blocks available */
1798 if (IsValidDiagDirection(target_dir
)) cur_rb
&= ~DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1799 if (cur_rb
== ROAD_NONE
) return false;
1801 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1802 /* Only build in the direction away from the tunnel or bridge. */
1803 target_dir
= ReverseDiagDir(GetTunnelBridgeDirection(tile
));
1805 /* Select a random bit from the blockmask, walk a step
1806 * and continue the search from there. */
1808 if (cur_rb
== ROAD_NONE
) return false;
1809 RoadBits target_bits
;
1811 target_dir
= RandomDiagDir();
1812 target_bits
= DiagDirToRoadBits(target_dir
);
1813 } while (!(cur_rb
& target_bits
));
1814 cur_rb
&= ~target_bits
;
1815 } while (!CanFollowRoad(tile
, target_dir
));
1817 tile
= TileAddByDiagDir(tile
, target_dir
);
1819 if (IsTileType(tile
, MP_ROAD
) && !IsRoadDepot(tile
) && HasTileRoadType(tile
, RTT_ROAD
)) {
1820 /* Don't allow building over roads of other cities */
1821 if (IsRoadOwner(tile
, RTT_ROAD
, OWNER_TOWN
) && Town::GetByTile(tile
) != t
) {
1823 } else if (IsRoadOwner(tile
, RTT_ROAD
, OWNER_NONE
) && _game_mode
== GM_EDITOR
) {
1824 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1825 * owner :) (happy happy happy road now) */
1826 SetRoadOwner(tile
, RTT_ROAD
, OWNER_TOWN
);
1827 SetTownIndex(tile
, t
->index
);
1831 /* Max number of times is checked. */
1832 } while (--_grow_town_result
>= 0);
1838 * Generate a random road block.
1839 * The probability of a straight road
1840 * is somewhat higher than a curved.
1842 * @return A RoadBits value with 2 bits set
1844 static RoadBits
GenRandomRoadBits()
1846 uint32_t r
= Random();
1847 uint a
= GB(r
, 0, 2);
1848 uint b
= GB(r
, 8, 2);
1850 return (RoadBits
)((ROAD_NW
<< a
) + (ROAD_NW
<< b
));
1855 * @param t The town to grow
1856 * @return true if we successfully grew the town with a road or house.
1858 static bool GrowTown(Town
*t
)
1860 static const TileIndexDiffC _town_coord_mod
[] = {
1876 /* Current "company" is a town */
1877 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
);
1879 TileIndex tile
= t
->xy
; // The tile we are working with ATM
1881 /* Find a road that we can base the construction on. */
1882 for (const auto &ptr
: _town_coord_mod
) {
1883 if (GetTownRoadBits(tile
) != ROAD_NONE
) {
1884 bool success
= GrowTownAtRoad(t
, tile
);
1885 cur_company
.Restore();
1888 tile
= TileAdd(tile
, ToTileIndexDiff(ptr
));
1891 /* No road available, try to build a random road block by
1892 * clearing some land and then building a road there. */
1893 if (TownAllowedToBuildRoads()) {
1895 for (const auto &ptr
: _town_coord_mod
) {
1896 /* Only work with plain land that not already has a house */
1897 if (!IsTileType(tile
, MP_HOUSE
) && IsTileFlat(tile
)) {
1898 if (Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Succeeded()) {
1899 RoadType rt
= GetTownRoadType();
1900 Command
<CMD_BUILD_ROAD
>::Do(DC_EXEC
| DC_AUTO
, tile
, GenRandomRoadBits(), rt
, DRD_NONE
, t
->index
);
1901 cur_company
.Restore();
1905 tile
= TileAdd(tile
, ToTileIndexDiff(ptr
));
1909 cur_company
.Restore();
1914 * Update the cached town zone radii of a town, based on the number of houses.
1915 * @param t The town to update.
1917 void UpdateTownRadius(Town
*t
)
1919 static const std::array
<std::array
<uint32_t, HZB_END
>, 23> _town_squared_town_zone_radius_data
= {{
1920 { 4, 0, 0, 0, 0}, // 0
1925 { 64, 0, 4, 0, 0}, // 20
1930 { 81, 0, 16, 0, 4}, // 40
1932 { 81, 36, 25, 0, 9},
1933 { 81, 36, 25, 16, 9},
1934 { 81, 49, 0, 25, 9},
1935 { 81, 64, 0, 25, 9}, // 60
1936 { 81, 64, 0, 36, 9},
1937 { 81, 64, 0, 36, 16},
1938 {100, 81, 0, 49, 16},
1939 {100, 81, 0, 49, 25},
1940 {121, 81, 0, 49, 25}, // 80
1941 {121, 81, 0, 49, 25},
1942 {121, 81, 0, 49, 36}, // 88
1945 if (t
->cache
.num_houses
< std::size(_town_squared_town_zone_radius_data
) * 4) {
1946 t
->cache
.squared_town_zone_radius
= _town_squared_town_zone_radius_data
[t
->cache
.num_houses
/ 4];
1948 int mass
= t
->cache
.num_houses
/ 8;
1949 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1950 * The offsets are to make sure the radii do not decrease in size when going from the table
1951 * to the calculated value.*/
1952 t
->cache
.squared_town_zone_radius
[HZB_TOWN_EDGE
] = mass
* 15 - 40;
1953 t
->cache
.squared_town_zone_radius
[HZB_TOWN_OUTSKIRT
] = mass
* 9 - 15;
1954 t
->cache
.squared_town_zone_radius
[HZB_TOWN_OUTER_SUBURB
] = 0;
1955 t
->cache
.squared_town_zone_radius
[HZB_TOWN_INNER_SUBURB
] = mass
* 5 - 5;
1956 t
->cache
.squared_town_zone_radius
[HZB_TOWN_CENTRE
] = mass
* 3 + 5;
1961 * Update the maximum amount of montly passengers and mail for a town, based on its population.
1962 * @param t The town to update.
1964 void UpdateTownMaxPass(Town
*t
)
1966 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[TPE_PASSENGERS
]) {
1967 t
->supplied
[cs
->Index()].old_max
= ScaleByCargoScale(t
->cache
.population
>> 3, true);
1969 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[TPE_MAIL
]) {
1970 t
->supplied
[cs
->Index()].old_max
= ScaleByCargoScale(t
->cache
.population
>> 4, true);
1974 static void UpdateTownGrowthRate(Town
*t
);
1975 static void UpdateTownGrowth(Town
*t
);
1978 * Actually create a town.
1980 * @param t The town.
1981 * @param tile Where to put it.
1982 * @param townnameparts The town name.
1983 * @param size The preset size of the town.
1984 * @param city Should we create a city?
1985 * @param layout The road layout of the town.
1986 * @param manual Was the town placed manually?
1988 static void DoCreateTown(Town
*t
, TileIndex tile
, uint32_t townnameparts
, TownSize size
, bool city
, TownLayout layout
, bool manual
)
1990 AutoRestoreBackup
backup(_generating_town
, true);
1993 t
->cache
.num_houses
= 0;
1994 t
->time_until_rebuild
= 10;
1995 UpdateTownRadius(t
);
1997 t
->cache
.population
= 0;
1998 InitializeBuildingCounts(t
);
1999 /* Spread growth across ticks so even if there are many
2000 * similar towns they're unlikely to grow all in one tick */
2001 t
->grow_counter
= t
->index
% Ticks::TOWN_GROWTH_TICKS
;
2002 t
->growth_rate
= TownTicksToGameTicks(250);
2003 t
->show_zone
= false;
2005 _town_kdtree
.Insert(t
->index
);
2007 /* Set the default cargo requirement for town growth */
2008 switch (_settings_game
.game_creation
.landscape
) {
2010 if (FindFirstCargoWithTownAcceptanceEffect(TAE_FOOD
) != nullptr) t
->goal
[TAE_FOOD
] = TOWN_GROWTH_WINTER
;
2014 if (FindFirstCargoWithTownAcceptanceEffect(TAE_FOOD
) != nullptr) t
->goal
[TAE_FOOD
] = TOWN_GROWTH_DESERT
;
2015 if (FindFirstCargoWithTownAcceptanceEffect(TAE_WATER
) != nullptr) t
->goal
[TAE_WATER
] = TOWN_GROWTH_DESERT
;
2019 t
->fund_buildings_months
= 0;
2021 for (uint i
= 0; i
!= MAX_COMPANIES
; i
++) t
->ratings
[i
] = RATING_INITIAL
;
2023 t
->have_ratings
= 0;
2024 t
->exclusivity
= INVALID_COMPANY
;
2025 t
->exclusive_counter
= 0;
2029 TownNameParams
tnp(_settings_game
.game_creation
.town_name
);
2030 t
->townnamegrfid
= tnp
.grfid
;
2031 t
->townnametype
= tnp
.type
;
2033 t
->townnameparts
= townnameparts
;
2035 t
->InitializeLayout(layout
);
2037 t
->larger_town
= city
;
2039 int x
= (int)size
* 16 + 3;
2040 if (size
== TSZ_RANDOM
) x
= (Random() & 0xF) + 8;
2041 /* Don't create huge cities when founding town in-game */
2042 if (city
&& (!manual
|| _game_mode
== GM_EDITOR
)) x
*= _settings_game
.economy
.initial_city_size
;
2044 t
->cache
.num_houses
+= x
;
2045 UpdateTownRadius(t
);
2052 t
->UpdateVirtCoord();
2053 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_REBUILD
);
2055 t
->cache
.num_houses
-= x
;
2056 UpdateTownRadius(t
);
2057 UpdateTownGrowthRate(t
);
2058 UpdateTownMaxPass(t
);
2059 UpdateAirportsNoise();
2063 * Check if it's possible to place a town on a given tile.
2064 * @param tile The tile to check.
2065 * @return A zero cost if allowed, otherwise an error.
2067 static CommandCost
TownCanBePlacedHere(TileIndex tile
)
2069 /* Check if too close to the edge of map */
2070 if (DistanceFromEdge(tile
) < 12) {
2071 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
);
2074 /* Check distance to all other towns. */
2075 if (IsCloseToTown(tile
, 20)) {
2076 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN
);
2079 /* Can only build on clear flat areas, possibly with trees. */
2080 if ((!IsTileType(tile
, MP_CLEAR
) && !IsTileType(tile
, MP_TREES
)) || !IsTileFlat(tile
)) {
2081 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2084 return CommandCost(EXPENSES_OTHER
);
2088 * Verifies this custom name is unique. Only custom names are checked.
2089 * @param name The name to check.
2090 * @return true if the name is unique
2092 static bool IsUniqueTownName(const std::string
&name
)
2094 for (const Town
*t
: Town::Iterate()) {
2095 if (!t
->name
.empty() && t
->name
== name
) return false;
2102 * Create a new town.
2103 * @param flags The type of operation.
2104 * @param tile The coordinates where town is built.
2105 * @param size The size of the town (@see TownSize).
2106 * @param city Should we build a city?
2107 * @param layout The town road layout (@see TownLayout).
2108 * @param random_location Should we use a random location? (randomize \c tile )
2109 * @param townnameparts Town name parts.
2110 * @param text Custom name for the town. If empty, the town name parts will be used.
2111 * @return The cost of this operation or an error.
2113 std::tuple
<CommandCost
, Money
, TownID
> CmdFoundTown(DoCommandFlag flags
, TileIndex tile
, TownSize size
, bool city
, TownLayout layout
, bool random_location
, uint32_t townnameparts
, const std::string
&text
)
2115 TownNameParams
par(_settings_game
.game_creation
.town_name
);
2117 if (size
>= TSZ_END
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2118 if (layout
>= NUM_TLS
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2120 /* Some things are allowed only in the scenario editor and for game scripts. */
2121 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) {
2122 if (_settings_game
.economy
.found_town
== TF_FORBIDDEN
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2123 if (size
== TSZ_LARGE
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2124 if (random_location
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2125 if (_settings_game
.economy
.found_town
!= TF_CUSTOM_LAYOUT
&& layout
!= _settings_game
.economy
.town_layout
) {
2126 return { CMD_ERROR
, 0, INVALID_TOWN
};
2128 } else if (_current_company
== OWNER_DEITY
&& random_location
) {
2129 /* Random parameter is not allowed for Game Scripts. */
2130 return { CMD_ERROR
, 0, INVALID_TOWN
};
2134 /* If supplied name is empty, townnameparts has to generate unique automatic name */
2135 if (!VerifyTownName(townnameparts
, &par
)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE
), 0, INVALID_TOWN
};
2137 /* If name is not empty, it has to be unique custom name */
2138 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return { CMD_ERROR
, 0, INVALID_TOWN
};
2139 if (!IsUniqueTownName(text
)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE
), 0, INVALID_TOWN
};
2142 /* Allocate town struct */
2143 if (!Town::CanAllocateItem()) return { CommandCost(STR_ERROR_TOO_MANY_TOWNS
), 0, INVALID_TOWN
};
2145 if (!random_location
) {
2146 CommandCost ret
= TownCanBePlacedHere(tile
);
2147 if (ret
.Failed()) return { ret
, 0, INVALID_TOWN
};
2150 static const uint8_t price_mult
[][TSZ_RANDOM
+ 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
2151 /* multidimensional arrays have to have defined length of non-first dimension */
2152 static_assert(lengthof(price_mult
[0]) == 4);
2154 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_BUILD_TOWN
]);
2155 uint8_t mult
= price_mult
[city
][size
];
2157 cost
.MultiplyCost(mult
);
2159 /* Create the town */
2160 TownID new_town
= INVALID_TOWN
;
2161 if (flags
& DC_EXEC
) {
2162 if (cost
.GetCost() > GetAvailableMoneyForCommand()) {
2163 return { CommandCost(EXPENSES_OTHER
), cost
.GetCost(), INVALID_TOWN
};
2166 Backup
<bool> old_generating_world(_generating_world
, true);
2167 UpdateNearestTownForRoadTiles(true);
2169 if (random_location
) {
2170 t
= CreateRandomTown(20, townnameparts
, size
, city
, layout
);
2171 if (t
== nullptr) return { CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN
), 0, INVALID_TOWN
};
2174 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, true);
2177 new_town
= t
->index
;
2178 UpdateNearestTownForRoadTiles(false);
2179 old_generating_world
.Restore();
2181 if (t
!= nullptr && !text
.empty()) {
2183 t
->UpdateVirtCoord();
2186 if (_game_mode
!= GM_EDITOR
) {
2187 /* 't' can't be nullptr since 'random' is false outside scenedit */
2188 assert(!random_location
);
2190 if (_current_company
== OWNER_DEITY
) {
2191 SetDParam(0, t
->index
);
2192 AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED
, NT_INDUSTRY_OPEN
, tile
);
2194 SetDParam(0, _current_company
);
2195 std::string company_name
= GetString(STR_COMPANY_NAME
);
2197 SetDParamStr(0, company_name
);
2198 SetDParam(1, t
->index
);
2200 AddTileNewsItem(STR_NEWS_NEW_TOWN
, NT_INDUSTRY_OPEN
, tile
);
2202 AI::BroadcastNewEvent(new ScriptEventTownFounded(t
->index
));
2203 Game::NewEvent(new ScriptEventTownFounded(t
->index
));
2206 return { cost
, 0, new_town
};
2210 * Towns must all be placed on the same grid or when they eventually
2211 * interpenetrate their road networks will not mesh nicely; this
2212 * function adjusts a tile so that it aligns properly.
2214 * @param tile The tile to start at.
2215 * @param layout The town layout in effect.
2216 * @return The adjusted tile.
2218 static TileIndex
AlignTileToGrid(TileIndex tile
, TownLayout layout
)
2221 case TL_2X2_GRID
: return TileXY(TileX(tile
) - TileX(tile
) % 3, TileY(tile
) - TileY(tile
) % 3);
2222 case TL_3X3_GRID
: return TileXY(TileX(tile
) & ~3, TileY(tile
) & ~3);
2223 default: return tile
;
2228 * Towns must all be placed on the same grid or when they eventually
2229 * interpenetrate their road networks will not mesh nicely; this
2230 * function tells you if a tile is properly aligned.
2232 * @param tile The tile to start at.
2233 * @param layout The town layout in effect.
2234 * @return true if the tile is in the correct location.
2236 static bool IsTileAlignedToGrid(TileIndex tile
, TownLayout layout
)
2239 case TL_2X2_GRID
: return TileX(tile
) % 3 == 0 && TileY(tile
) % 3 == 0;
2240 case TL_3X3_GRID
: return TileX(tile
) % 4 == 0 && TileY(tile
) % 4 == 0;
2241 default: return true;
2246 * Used as the user_data for FindFurthestFromWater
2249 TileIndex tile
; ///< holds the tile that was found
2250 uint max_dist
; ///< holds the distance that tile is from the water
2251 TownLayout layout
; ///< tells us what kind of town we're building
2255 * CircularTileSearch callback; finds the tile furthest from any
2256 * water. slightly bit tricky, since it has to do a search of its own
2257 * in order to find the distance to the water from each square in the
2260 * Also, this never returns true, because it needs to take into
2261 * account all locations being searched before it knows which is the
2264 * @param tile Start looking from this tile
2265 * @param user_data Storage area for data that must last across calls;
2266 * must be a pointer to struct SpotData
2268 * @return always false
2270 static bool FindFurthestFromWater(TileIndex tile
, void *user_data
)
2272 SpotData
*sp
= (SpotData
*)user_data
;
2273 uint dist
= GetClosestWaterDistance(tile
, true);
2275 if (IsTileType(tile
, MP_CLEAR
) &&
2277 IsTileAlignedToGrid(tile
, sp
->layout
) &&
2278 dist
> sp
->max_dist
) {
2280 sp
->max_dist
= dist
;
2287 * CircularTileSearch callback to find the nearest land tile.
2288 * @param tile Start looking from this tile
2290 static bool FindNearestEmptyLand(TileIndex tile
, void *)
2292 return IsTileType(tile
, MP_CLEAR
);
2296 * Given a spot on the map (presumed to be a water tile), find a good
2297 * coastal spot to build a city. We don't want to build too close to
2298 * the edge if we can help it (since that inhibits city growth) hence
2299 * the search within a search within a search. O(n*m^2), where n is
2300 * how far to search for land, and m is how far inland to look for a
2303 * @param tile Start looking from this spot.
2304 * @param layout the road layout to search for
2305 * @return tile that was found
2307 static TileIndex
FindNearestGoodCoastalTownSpot(TileIndex tile
, TownLayout layout
)
2309 SpotData sp
= { INVALID_TILE
, 0, layout
};
2311 TileIndex coast
= tile
;
2312 if (CircularTileSearch(&coast
, 40, FindNearestEmptyLand
, nullptr)) {
2313 CircularTileSearch(&coast
, 10, FindFurthestFromWater
, &sp
);
2317 /* if we get here just give up */
2318 return INVALID_TILE
;
2322 * Create a random town somewhere in the world.
2323 * @param attempts How many times should we try?
2324 * @param townnameparts The name of the town.
2325 * @param size The size preset of the town.
2326 * @param city Should we build a city?
2327 * @param layout The road layout to build.
2328 * @return The town object, or nullptr if we failed to create a town anywhere.
2330 static Town
*CreateRandomTown(uint attempts
, uint32_t townnameparts
, TownSize size
, bool city
, TownLayout layout
)
2332 assert(_game_mode
== GM_EDITOR
|| _generating_world
); // These are the preconditions for CMD_DELETE_TOWN
2334 if (!Town::CanAllocateItem()) return nullptr;
2337 /* Generate a tile index not too close from the edge */
2338 TileIndex tile
= AlignTileToGrid(RandomTile(), layout
);
2340 /* if we tried to place the town on water, slide it over onto
2341 * the nearest likely-looking spot */
2342 if (IsTileType(tile
, MP_WATER
)) {
2343 tile
= FindNearestGoodCoastalTownSpot(tile
, layout
);
2344 if (tile
== INVALID_TILE
) continue;
2347 /* Make sure town can be placed here */
2348 if (TownCanBePlacedHere(tile
).Failed()) continue;
2350 /* Allocate a town struct */
2351 Town
*t
= new Town(tile
);
2353 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, false);
2355 /* if the population is still 0 at the point, then the
2356 * placement is so bad it couldn't grow at all */
2357 if (t
->cache
.population
> 0) return t
;
2359 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
);
2360 [[maybe_unused
]] CommandCost rc
= Command
<CMD_DELETE_TOWN
>::Do(DC_EXEC
, t
->index
);
2361 cur_company
.Restore();
2362 assert(rc
.Succeeded());
2364 /* We already know that we can allocate a single town when
2365 * entering this function. However, we create and delete
2366 * a town which "resets" the allocation checks. As such we
2367 * need to check again when assertions are enabled. */
2368 assert(Town::CanAllocateItem());
2369 } while (--attempts
!= 0);
2374 static const uint8_t _num_initial_towns
[4] = {5, 11, 23, 46}; // very low, low, normal, high
2377 * Generate a number of towns with a given layout.
2378 * This function is used by the Random Towns button in Scenario Editor as well as in world generation.
2379 * @param layout The road layout to build.
2380 * @return true if towns have been successfully created.
2382 bool GenerateTowns(TownLayout layout
)
2384 uint current_number
= 0;
2385 uint difficulty
= (_game_mode
!= GM_EDITOR
) ? _settings_game
.difficulty
.number_towns
: 0;
2386 uint total
= (difficulty
== (uint
)CUSTOM_TOWN_NUMBER_DIFFICULTY
) ? _settings_game
.game_creation
.custom_town_number
: Map::ScaleBySize(_num_initial_towns
[difficulty
] + (Random() & 7));
2387 total
= std::min
<uint
>(TownPool::MAX_SIZE
, total
);
2388 uint32_t townnameparts
;
2389 TownNames town_names
;
2391 SetGeneratingWorldProgress(GWP_TOWN
, total
);
2393 /* Pre-populate the town names list with the names of any towns already on the map */
2394 for (const Town
*town
: Town::Iterate()) {
2395 town_names
.insert(town
->GetCachedName());
2398 /* Randomised offset for city status. This means with e.g. 1-in-4 towns being cities, a map with 10 towns
2399 * may have 2 or 3 cities, instead of always 3. */
2400 uint city_random_offset
= Random() % _settings_game
.economy
.larger_towns
;
2402 /* First attempt will be made at creating the suggested number of towns.
2403 * Note that this is really a suggested value, not a required one.
2404 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2406 bool city
= (_settings_game
.economy
.larger_towns
!= 0 && ((city_random_offset
+ current_number
) % _settings_game
.economy
.larger_towns
) == 0);
2407 IncreaseGeneratingWorldProgress(GWP_TOWN
);
2408 /* Get a unique name for the town. */
2409 if (!GenerateTownName(_random
, &townnameparts
, &town_names
)) continue;
2410 /* try 20 times to create a random-sized town for the first loop. */
2411 if (CreateRandomTown(20, townnameparts
, TSZ_RANDOM
, city
, layout
) != nullptr) current_number
++; // If creation was successful, raise a flag.
2416 /* Build the town k-d tree again to make sure it's well balanced */
2417 RebuildTownKdtree();
2419 if (current_number
!= 0) return true;
2421 /* If current_number is still zero at this point, it means that not a single town has been created.
2422 * So give it a last try, but now more aggressive */
2423 if (GenerateTownName(_random
, &townnameparts
) &&
2424 CreateRandomTown(10000, townnameparts
, TSZ_RANDOM
, _settings_game
.economy
.larger_towns
!= 0, layout
) != nullptr) {
2428 /* If there are no towns at all and we are generating new game, bail out */
2429 if (Town::GetNumItems() == 0 && _game_mode
!= GM_EDITOR
) {
2430 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN
, INVALID_STRING_ID
, WL_CRITICAL
);
2433 return false; // we are still without a town? we failed, simply
2438 * Returns the bit corresponding to the town zone of the specified tile.
2439 * @param t Town on which town zone is to be found.
2440 * @param tile TileIndex where town zone needs to be found.
2441 * @return the bit position of the given zone, as defined in HouseZones.
2443 HouseZonesBits
GetTownRadiusGroup(const Town
*t
, TileIndex tile
)
2445 uint dist
= DistanceSquare(tile
, t
->xy
);
2447 if (t
->fund_buildings_months
&& dist
<= 25) return HZB_TOWN_CENTRE
;
2449 HouseZonesBits smallest
= HZB_TOWN_EDGE
;
2450 for (HouseZonesBits i
= HZB_BEGIN
; i
< HZB_END
; i
++) {
2451 if (dist
< t
->cache
.squared_town_zone_radius
[i
]) smallest
= i
;
2458 * Clears tile and builds a house or house part.
2459 * @param tile The tile to build upon.
2460 * @param t The town which will own the house.
2461 * @param counter The construction stage counter for the house.
2462 * @param stage The current construction stage of the house.
2463 * @param type The type of house.
2464 * @param random_bits Random bits for newgrf houses to use.
2465 * @pre The house can be built here.
2467 static inline void ClearMakeHouseTile(TileIndex tile
, Town
*t
, uint8_t counter
, uint8_t stage
, HouseID type
, uint8_t random_bits
)
2469 [[maybe_unused
]] CommandCost cc
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
, tile
);
2470 assert(cc
.Succeeded());
2472 IncreaseBuildingCount(t
, type
);
2473 MakeHouseTile(tile
, t
->index
, counter
, stage
, type
, random_bits
);
2474 if (HouseSpec::Get(type
)->building_flags
& BUILDING_IS_ANIMATED
) AddAnimatedTile(tile
, false);
2476 MarkTileDirtyByTile(tile
);
2481 * Write house information into the map. For multi-tile houses, all tiles are marked.
2482 * @param town The town related to this house
2483 * @param t The tile to build on. If a multi-tile house, this is the northern-most tile.
2484 * @param counter The counter of the construction stage.
2485 * @param stage The current construction stage.
2486 * @param The type of house.
2487 * @param random_bits Random bits for newgrf houses to use.
2488 * @pre The house can be built here.
2490 static void MakeTownHouse(TileIndex tile
, Town
*t
, uint8_t counter
, uint8_t stage
, HouseID type
, uint8_t random_bits
)
2492 BuildingFlags size
= HouseSpec::Get(type
)->building_flags
;
2494 ClearMakeHouseTile(tile
, t
, counter
, stage
, type
, random_bits
);
2495 if (size
& BUILDING_2_TILES_Y
) ClearMakeHouseTile(tile
+ TileDiffXY(0, 1), t
, counter
, stage
, ++type
, random_bits
);
2496 if (size
& BUILDING_2_TILES_X
) ClearMakeHouseTile(tile
+ TileDiffXY(1, 0), t
, counter
, stage
, ++type
, random_bits
);
2497 if (size
& BUILDING_HAS_4_TILES
) ClearMakeHouseTile(tile
+ TileDiffXY(1, 1), t
, counter
, stage
, ++type
, random_bits
);
2499 ForAllStationsAroundTiles(TileArea(tile
, (size
& BUILDING_2_TILES_X
) ? 2 : 1, (size
& BUILDING_2_TILES_Y
) ? 2 : 1), [t
](Station
*st
, TileIndex
) {
2500 t
->stations_near
.insert(st
);
2507 * Check if a house can be built here, based on slope, whether there's a bridge above, and if we can clear the land.
2508 * @param tile The tile to check.
2509 * @param noslope Are foundations prohibited for this house?
2510 * @return true iff house can be built here.
2512 static inline bool CanBuildHouseHere(TileIndex tile
, bool noslope
)
2514 /* cannot build on these slopes... */
2515 Slope slope
= GetTileSlope(tile
);
2516 if ((noslope
&& slope
!= SLOPE_FLAT
) || IsSteepSlope(slope
)) return false;
2518 /* at least one RoadTypes allow building the house here? */
2519 if (!RoadTypesAllowHouseHere(tile
)) return false;
2521 /* building under a bridge? */
2522 if (IsBridgeAbove(tile
)) return false;
2524 /* can we clear the land? */
2525 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Succeeded();
2530 * Check if a tile where we want to build a multi-tile house has an appropriate max Z.
2531 * @param tile The tile to check.
2532 * @param z The max Z level to allow.
2533 * @param noslope Are foundations disallowed for this house?
2534 * @return true iff house can be built here.
2535 * @see CanBuildHouseHere()
2537 static inline bool CheckBuildHouseSameZ(TileIndex tile
, int z
, bool noslope
)
2539 if (!CanBuildHouseHere(tile
, noslope
)) return false;
2541 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2542 if (GetTileMaxZ(tile
) != z
) return false;
2549 * Checks if a house of size 2x2 can be built at this tile.
2550 * @param tile The tile of the house's northernmost tile.
2551 * @param z The maximum tile z, so all tiles are the same height.
2552 * @param noslope Are foundations disallowed for this house?
2553 * @return true iff house can be built here.
2554 * @see CheckBuildHouseSameZ()
2556 static bool CheckFree2x2Area(TileIndex tile
, int z
, bool noslope
)
2558 /* we need to check this tile too because we can be at different tile now */
2559 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2561 for (DiagDirection d
= DIAGDIR_SE
; d
< DIAGDIR_END
; d
++) {
2562 tile
+= TileOffsByDiagDir(d
);
2563 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2571 * Checks if the current town layout allows building here.
2572 * @param t The town.
2573 * @param tile The tile to check.
2574 * @return true iff town layout allows building here.
2577 static inline bool TownLayoutAllowsHouseHere(Town
*t
, TileIndex tile
)
2579 /* Allow towns everywhere when we don't build roads */
2580 if (!TownAllowedToBuildRoads()) return true;
2582 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2584 switch (t
->layout
) {
2586 if ((grid_pos
.x
% 3) == 0 || (grid_pos
.y
% 3) == 0) return false;
2590 if ((grid_pos
.x
% 4) == 0 || (grid_pos
.y
% 4) == 0) return false;
2602 * Checks if the current town layout allows a 2x2 building here.
2603 * @param t The town.
2604 * @param tile The tile to check.
2605 * @return true iff town layout allows a 2x2 building here.
2608 static inline bool TownLayoutAllows2x2HouseHere(Town
*t
, TileIndex tile
)
2610 /* Allow towns everywhere when we don't build roads */
2611 if (!TownAllowedToBuildRoads()) return true;
2613 /* Compute relative position of tile. (Positive offsets are towards north) */
2614 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2616 switch (t
->layout
) {
2620 if ((grid_pos
.x
!= 2 && grid_pos
.x
!= -1) ||
2621 (grid_pos
.y
!= 2 && grid_pos
.y
!= -1)) return false;
2625 if ((grid_pos
.x
& 3) < 2 || (grid_pos
.y
& 3) < 2) return false;
2637 * Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
2638 * Also, tests both building positions that occupy this tile.
2639 * @param tile The tile where the building should be built.
2640 * @param t The town.
2641 * @param maxz The maximum Z level, since all tiles must have the same height.
2642 * @param noslope Are foundations disallowed for this house?
2643 * @param second The diagdir from the first tile to the second tile.
2645 static bool CheckTownBuild2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
, DiagDirection second
)
2647 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2649 TileIndex tile2
= *tile
+ TileOffsByDiagDir(second
);
2650 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) return true;
2652 tile2
= *tile
+ TileOffsByDiagDir(ReverseDiagDir(second
));
2653 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) {
2663 * Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
2664 * Also, tests all four building positions that occupy this tile.
2665 * @param tile The tile where the building should be built.
2666 * @param t The town.
2667 * @param maxz The maximum Z level, since all tiles must have the same height.
2668 * @param noslope Are foundations disallowed for this house?
2670 static bool CheckTownBuild2x2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
)
2672 TileIndex tile2
= *tile
;
2674 for (DiagDirection d
= DIAGDIR_SE
;; d
++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2675 if (TownLayoutAllows2x2HouseHere(t
, tile2
) && CheckFree2x2Area(tile2
, maxz
, noslope
)) {
2679 if (d
== DIAGDIR_END
) break;
2680 tile2
+= TileOffsByDiagDir(ReverseDiagDir(d
)); // go clockwise
2687 * Build a house at this tile.
2688 * @param t The town the house will belong to.
2689 * @param tile The tile to try building on.
2690 * @param hs The @a HouseSpec of the house.
2691 * @param house The @a HouseID of the house.
2692 * @param random_bits The random data to be associated with the house.
2694 static void BuildTownHouse(Town
*t
, TileIndex tile
, const HouseSpec
*hs
, HouseID house
, uint8_t random_bits
)
2696 /* build the house */
2697 t
->cache
.num_houses
++;
2699 uint8_t construction_counter
= 0;
2700 uint8_t construction_stage
= 0;
2702 if (_generating_world
|| _game_mode
== GM_EDITOR
) {
2703 uint32_t construction_random
= Random();
2705 construction_stage
= TOWN_HOUSE_COMPLETED
;
2706 if (_generating_world
&& Chance16(1, 7)) construction_stage
= GB(construction_random
, 0, 2);
2708 if (construction_stage
== TOWN_HOUSE_COMPLETED
) {
2709 ChangePopulation(t
, hs
->population
);
2711 construction_counter
= GB(construction_random
, 2, 2);
2715 MakeTownHouse(tile
, t
, construction_counter
, construction_stage
, house
, random_bits
);
2716 UpdateTownRadius(t
);
2717 UpdateTownGrowthRate(t
);
2721 * Tries to build a house at this tile.
2722 * @param t The town the house will belong to.
2723 * @param tile The tile to try building on.
2724 * @return false iff no house can be built on this tile.
2726 static bool TryBuildTownHouse(Town
*t
, TileIndex tile
)
2728 /* forbidden building here by town layout */
2729 if (!TownLayoutAllowsHouseHere(t
, tile
)) return false;
2731 /* no house allowed at all, bail out */
2732 if (!CanBuildHouseHere(tile
, false)) return false;
2734 Slope slope
= GetTileSlope(tile
);
2735 int maxz
= GetTileMaxZ(tile
);
2737 /* Get the town zone type of the current tile, as well as the climate.
2738 * This will allow to easily compare with the specs of the new house to build */
2739 HouseZonesBits rad
= GetTownRadiusGroup(t
, tile
);
2742 int land
= _settings_game
.game_creation
.landscape
;
2743 if (land
== LT_ARCTIC
&& maxz
> HighestSnowLine()) land
= -1;
2745 uint bitmask
= (1 << rad
) + (1 << (land
+ 12));
2747 /* bits 0-4 are used
2748 * bits 11-15 are used
2749 * bits 5-10 are not used. */
2750 static std::vector
<std::pair
<HouseID
, uint
>> probs
;
2753 uint probability_max
= 0;
2755 /* Generate a list of all possible houses that can be built. */
2756 for (const auto &hs
: HouseSpec::Specs()) {
2757 /* Verify that the candidate house spec matches the current tile status */
2758 if ((~hs
.building_availability
& bitmask
) != 0 || !hs
.enabled
|| hs
.grf_prop
.override
!= INVALID_HOUSE_ID
) continue;
2760 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2761 if (hs
.class_id
!= HOUSE_NO_CLASS
) {
2762 /* id_count is always <= class_count, so it doesn't need to be checked */
2763 if (t
->cache
.building_counts
.class_count
[hs
.class_id
] == UINT16_MAX
) continue;
2765 /* If the house has no class, check id_count instead */
2766 if (t
->cache
.building_counts
.id_count
[hs
.Index()] == UINT16_MAX
) continue;
2769 uint cur_prob
= hs
.probability
;
2770 probability_max
+= cur_prob
;
2771 probs
.emplace_back(hs
.Index(), cur_prob
);
2774 TileIndex baseTile
= tile
;
2776 while (probability_max
> 0) {
2777 /* Building a multitile building can change the location of tile.
2778 * The building would still be built partially on that tile, but
2779 * its northern tile would be elsewhere. However, if the callback
2780 * fails we would be basing further work from the changed tile.
2781 * So a next 1x1 tile building could be built on the wrong tile. */
2784 uint r
= RandomRange(probability_max
);
2786 for (i
= 0; i
< probs
.size(); i
++) {
2787 if (probs
[i
].second
> r
) break;
2788 r
-= probs
[i
].second
;
2791 HouseID house
= probs
[i
].first
;
2792 probability_max
-= probs
[i
].second
;
2794 /* remove tested house from the set */
2795 probs
[i
] = probs
.back();
2798 const HouseSpec
*hs
= HouseSpec::Get(house
);
2800 if (!_generating_world
&& _game_mode
!= GM_EDITOR
&& (hs
->extra_flags
& BUILDING_IS_HISTORICAL
) != 0) {
2804 if (TimerGameCalendar::year
< hs
->min_year
|| TimerGameCalendar::year
> hs
->max_year
) continue;
2806 /* Special houses that there can be only one of. */
2809 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2810 SetBit(oneof
, TOWN_HAS_CHURCH
);
2811 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2812 SetBit(oneof
, TOWN_HAS_STADIUM
);
2815 if (t
->flags
& oneof
) continue;
2817 /* Make sure there is no slope? */
2818 bool noslope
= (hs
->building_flags
& TILE_NOT_SLOPED
) != 0;
2819 if (noslope
&& slope
!= SLOPE_FLAT
) continue;
2821 if (hs
->building_flags
& TILE_SIZE_2x2
) {
2822 if (!CheckTownBuild2x2House(&tile
, t
, maxz
, noslope
)) continue;
2823 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
2824 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SW
)) continue;
2825 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
2826 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SE
)) continue;
2828 /* 1x1 house checks are already done */
2831 uint8_t random_bits
= Random();
2833 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ALLOW_CONSTRUCTION
)) {
2834 uint16_t callback_res
= GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION
, 0, 0, house
, t
, tile
, true, random_bits
);
2835 if (callback_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_ALLOW_CONSTRUCTION
, callback_res
)) continue;
2838 /* Special houses that there can be only one of. */
2841 BuildTownHouse(t
, tile
, hs
, house
, random_bits
);
2849 CommandCost
CmdPlaceHouse(DoCommandFlag flags
, TileIndex tile
, HouseID house
)
2851 if (_game_mode
!= GM_EDITOR
) return CMD_ERROR
;
2852 if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST
);
2854 if (static_cast<size_t>(house
) >= HouseSpec::Specs().size()) return CMD_ERROR
;
2855 const HouseSpec
*hs
= HouseSpec::Get(house
);
2856 if (!hs
->enabled
) return CMD_ERROR
;
2858 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2860 /* cannot build on these slopes... */
2861 Slope slope
= GetTileSlope(tile
);
2862 if (IsSteepSlope(slope
)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
2864 /* building under a bridge? */
2865 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2867 /* can we clear the land? */
2868 CommandCost cost
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
);
2869 if (!cost
.Succeeded()) return cost
;
2871 int maxz
= GetTileMaxZ(tile
);
2873 /* Make sure there is no slope? */
2874 bool noslope
= (hs
->building_flags
& TILE_NOT_SLOPED
) != 0;
2875 if (noslope
&& slope
!= SLOPE_FLAT
) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
2878 if (hs
->building_flags
& TILE_SIZE_2x2
) ta
.Add(TileAddXY(tile
, 1, 1));
2879 if (hs
->building_flags
& TILE_SIZE_2x1
) ta
.Add(TileAddByDiagDir(tile
, DIAGDIR_SW
));
2880 if (hs
->building_flags
& TILE_SIZE_1x2
) ta
.Add(TileAddByDiagDir(tile
, DIAGDIR_SE
));
2882 /* Check additonal tiles covered by this house. */
2883 for (const TileIndex
&subtile
: ta
) {
2884 cost
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, subtile
);
2885 if (!cost
.Succeeded()) return cost
;
2887 if (!CheckBuildHouseSameZ(subtile
, maxz
, noslope
)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
2890 if (flags
& DC_EXEC
) {
2891 BuildTownHouse(t
, tile
, hs
, house
, Random());
2894 return CommandCost();
2898 * Update data structures when a house is removed
2899 * @param tile Tile of the house
2900 * @param t Town owning the house
2901 * @param house House type
2903 static void DoClearTownHouseHelper(TileIndex tile
, Town
*t
, HouseID house
)
2905 assert(IsTileType(tile
, MP_HOUSE
));
2906 DecreaseBuildingCount(t
, house
);
2907 DoClearSquare(tile
);
2908 DeleteAnimatedTile(tile
);
2910 DeleteNewGRFInspectWindow(GSF_HOUSES
, tile
.base());
2914 * Determines if a given HouseID is part of a multitile house.
2915 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2917 * @param house Is changed to the HouseID of the north tile of the same house
2918 * @return TileDiff from the tile of the given HouseID to the north tile
2920 TileIndexDiff
GetHouseNorthPart(HouseID
&house
)
2922 if (house
>= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2923 if (HouseSpec::Get(house
- 1)->building_flags
& TILE_SIZE_2x1
) {
2925 return TileDiffXY(-1, 0);
2926 } else if (HouseSpec::Get(house
- 1)->building_flags
& BUILDING_2_TILES_Y
) {
2928 return TileDiffXY(0, -1);
2929 } else if (HouseSpec::Get(house
- 2)->building_flags
& BUILDING_HAS_4_TILES
) {
2931 return TileDiffXY(-1, 0);
2932 } else if (HouseSpec::Get(house
- 3)->building_flags
& BUILDING_HAS_4_TILES
) {
2934 return TileDiffXY(-1, -1);
2937 return TileDiffXY(0, 0);
2941 * Clear a town house.
2942 * @param t The town which owns the house.
2943 * @param tile The tile to clear.
2945 void ClearTownHouse(Town
*t
, TileIndex tile
)
2947 assert(IsTileType(tile
, MP_HOUSE
));
2949 HouseID house
= GetHouseType(tile
);
2951 /* The northernmost tile of the house is the main house. */
2952 tile
+= GetHouseNorthPart(house
);
2954 const HouseSpec
*hs
= HouseSpec::Get(house
);
2956 /* Remove population from the town if the house is finished. */
2957 if (IsHouseCompleted(tile
)) {
2958 ChangePopulation(t
, -hs
->population
);
2961 t
->cache
.num_houses
--;
2963 /* Clear flags for houses that only may exist once/town. */
2964 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2965 ClrBit(t
->flags
, TOWN_HAS_CHURCH
);
2966 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2967 ClrBit(t
->flags
, TOWN_HAS_STADIUM
);
2970 /* Do the actual clearing of tiles */
2971 DoClearTownHouseHelper(tile
, t
, house
);
2972 if (hs
->building_flags
& BUILDING_2_TILES_Y
) DoClearTownHouseHelper(tile
+ TileDiffXY(0, 1), t
, ++house
);
2973 if (hs
->building_flags
& BUILDING_2_TILES_X
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 0), t
, ++house
);
2974 if (hs
->building_flags
& BUILDING_HAS_4_TILES
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 1), t
, ++house
);
2976 RemoveNearbyStations(t
, tile
, hs
->building_flags
);
2978 UpdateTownRadius(t
);
2982 * Rename a town (server-only).
2983 * @param flags type of operation
2984 * @param town_id town ID to rename
2985 * @param text the new name or an empty string when resetting to the default
2986 * @return the cost of this operation or an error
2988 CommandCost
CmdRenameTown(DoCommandFlag flags
, TownID town_id
, const std::string
&text
)
2990 Town
*t
= Town::GetIfValid(town_id
);
2991 if (t
== nullptr) return CMD_ERROR
;
2993 bool reset
= text
.empty();
2996 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CMD_ERROR
;
2997 if (!IsUniqueTownName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
3000 if (flags
& DC_EXEC
) {
3001 t
->cached_name
.clear();
3008 t
->UpdateVirtCoord();
3009 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_RESORT
);
3010 ClearAllStationCachedNames();
3011 ClearAllIndustryCachedNames();
3012 UpdateAllStationVirtCoords();
3014 return CommandCost();
3018 * Determines the first cargo with a certain town effect
3019 * @param effect Town effect of interest
3020 * @return first active cargo slot with that effect
3022 const CargoSpec
*FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect
)
3024 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
3025 if (cs
->town_acceptance_effect
== effect
) return cs
;
3031 * Change the cargo goal of a town.
3032 * @param flags Type of operation.
3033 * @param town_id Town ID to cargo game of.
3034 * @param tae TownEffect to change the game of.
3035 * @param goal The new goal value.
3036 * @return Empty cost or an error.
3038 CommandCost
CmdTownCargoGoal(DoCommandFlag flags
, TownID town_id
, TownAcceptanceEffect tae
, uint32_t goal
)
3040 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3042 if (tae
< TAE_BEGIN
|| tae
>= TAE_END
) return CMD_ERROR
;
3044 Town
*t
= Town::GetIfValid(town_id
);
3045 if (t
== nullptr) return CMD_ERROR
;
3047 /* Validate if there is a cargo which is the requested TownEffect */
3048 const CargoSpec
*cargo
= FindFirstCargoWithTownAcceptanceEffect(tae
);
3049 if (cargo
== nullptr) return CMD_ERROR
;
3051 if (flags
& DC_EXEC
) {
3052 t
->goal
[tae
] = goal
;
3053 UpdateTownGrowth(t
);
3054 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
3057 return CommandCost();
3061 * Set a custom text in the Town window.
3062 * @param flags Type of operation.
3063 * @param town_id Town ID to change the text of.
3064 * @param text The new text (empty to remove the text).
3065 * @return Empty cost or an error.
3067 CommandCost
CmdTownSetText(DoCommandFlag flags
, TownID town_id
, const std::string
&text
)
3069 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3070 Town
*t
= Town::GetIfValid(town_id
);
3071 if (t
== nullptr) return CMD_ERROR
;
3073 if (flags
& DC_EXEC
) {
3075 if (!text
.empty()) t
->text
= text
;
3076 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
3079 return CommandCost();
3083 * Change the growth rate of the town.
3084 * @param flags Type of operation.
3085 * @param town_id Town ID to cargo game of.
3086 * @param growth_rate Amount of days between growth, or TOWN_GROWTH_RATE_NONE, or 0 to reset custom growth rate.
3087 * @return Empty cost or an error.
3089 CommandCost
CmdTownGrowthRate(DoCommandFlag flags
, TownID town_id
, uint16_t growth_rate
)
3091 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3093 Town
*t
= Town::GetIfValid(town_id
);
3094 if (t
== nullptr) return CMD_ERROR
;
3096 if (flags
& DC_EXEC
) {
3097 if (growth_rate
== 0) {
3098 /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
3099 ClrBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
3101 uint old_rate
= t
->growth_rate
;
3102 if (t
->grow_counter
>= old_rate
) {
3103 /* This also catches old_rate == 0 */
3104 t
->grow_counter
= growth_rate
;
3106 /* Scale grow_counter, so half finished houses stay half finished */
3107 t
->grow_counter
= t
->grow_counter
* growth_rate
/ old_rate
;
3109 t
->growth_rate
= growth_rate
;
3110 SetBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
3112 UpdateTownGrowth(t
);
3113 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
3116 return CommandCost();
3120 * Change the rating of a company in a town
3121 * @param flags Type of operation.
3122 * @param town_id Town ID to change, bit 16..23 =
3123 * @param company_id Company ID to change.
3124 * @param rating New rating of company (signed int16_t).
3125 * @return Empty cost or an error.
3127 CommandCost
CmdTownRating(DoCommandFlag flags
, TownID town_id
, CompanyID company_id
, int16_t rating
)
3129 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3131 Town
*t
= Town::GetIfValid(town_id
);
3132 if (t
== nullptr) return CMD_ERROR
;
3134 if (!Company::IsValidID(company_id
)) return CMD_ERROR
;
3136 int16_t new_rating
= Clamp(rating
, RATING_MINIMUM
, RATING_MAXIMUM
);
3137 if (flags
& DC_EXEC
) {
3138 t
->ratings
[company_id
] = new_rating
;
3139 InvalidateWindowData(WC_TOWN_AUTHORITY
, town_id
);
3142 return CommandCost();
3146 * Expand a town (scenario editor only).
3147 * @param flags Type of operation.
3148 * @param TownID Town ID to expand.
3149 * @param grow_amount Amount to grow, or 0 to grow a random size up to the current amount of houses.
3150 * @return Empty cost or an error.
3152 CommandCost
CmdExpandTown(DoCommandFlag flags
, TownID town_id
, uint32_t grow_amount
)
3154 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3155 Town
*t
= Town::GetIfValid(town_id
);
3156 if (t
== nullptr) return CMD_ERROR
;
3158 if (flags
& DC_EXEC
) {
3159 /* The more houses, the faster we grow */
3160 if (grow_amount
== 0) {
3161 uint amount
= RandomRange(ClampTo
<uint16_t>(t
->cache
.num_houses
/ 10)) + 3;
3162 t
->cache
.num_houses
+= amount
;
3163 UpdateTownRadius(t
);
3165 uint n
= amount
* 10;
3166 do GrowTown(t
); while (--n
);
3168 t
->cache
.num_houses
-= amount
;
3170 for (; grow_amount
> 0; grow_amount
--) {
3171 /* Try several times to grow, as we are really suppose to grow */
3172 for (uint i
= 0; i
< 25; i
++) if (GrowTown(t
)) break;
3175 UpdateTownRadius(t
);
3177 UpdateTownMaxPass(t
);
3180 return CommandCost();
3184 * Delete a town (scenario editor or worldgen only).
3185 * @param flags Type of operation.
3186 * @param town_id Town ID to delete.
3187 * @return Empty cost or an error.
3189 CommandCost
CmdDeleteTown(DoCommandFlag flags
, TownID town_id
)
3191 if (_game_mode
!= GM_EDITOR
&& !_generating_world
) return CMD_ERROR
;
3192 Town
*t
= Town::GetIfValid(town_id
);
3193 if (t
== nullptr) return CMD_ERROR
;
3195 /* Stations refer to towns. */
3196 for (const Station
*st
: Station::Iterate()) {
3197 if (st
->town
== t
) {
3198 /* Non-oil rig stations are always a problem. */
3199 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->airport
.type
!= AT_OILRIG
) return CMD_ERROR
;
3200 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
3201 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, st
->airport
.tile
);
3202 if (ret
.Failed()) return ret
;
3206 /* Waypoints refer to towns. */
3207 for (const Waypoint
*wp
: Waypoint::Iterate()) {
3208 if (wp
->town
== t
) return CMD_ERROR
;
3211 /* Depots refer to towns. */
3212 for (const Depot
*d
: Depot::Iterate()) {
3213 if (d
->town
== t
) return CMD_ERROR
;
3216 /* Check all tiles for town ownership. First check for bridge tiles, as
3217 * these do not directly have an owner so we need to check adjacent
3218 * tiles. This won't work correctly in the same loop if the adjacent
3219 * tile was already deleted earlier in the loop. */
3220 for (TileIndex current_tile
= 0; current_tile
< Map::Size(); ++current_tile
) {
3221 if (IsTileType(current_tile
, MP_TUNNELBRIDGE
) && TestTownOwnsBridge(current_tile
, t
)) {
3222 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, current_tile
);
3223 if (ret
.Failed()) return ret
;
3227 /* Check all remaining tiles for town ownership. */
3228 for (TileIndex current_tile
= 0; current_tile
< Map::Size(); ++current_tile
) {
3229 bool try_clear
= false;
3230 switch (GetTileType(current_tile
)) {
3232 try_clear
= HasTownOwnedRoad(current_tile
) && GetTownIndex(current_tile
) == t
->index
;
3236 try_clear
= GetTownIndex(current_tile
) == t
->index
;
3240 try_clear
= Industry::GetByTile(current_tile
)->town
== t
;
3244 if (Town::GetNumItems() == 1) {
3245 /* No towns will be left, remove it! */
3248 Object
*o
= Object::GetByTile(current_tile
);
3250 if (o
->type
== OBJECT_STATUE
) {
3251 /* Statue... always remove. */
3254 /* Tell to find a new town. */
3255 if (flags
& DC_EXEC
) o
->town
= nullptr;
3265 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, current_tile
);
3266 if (ret
.Failed()) return ret
;
3270 /* The town destructor will delete the other things related to the town. */
3271 if (flags
& DC_EXEC
) {
3272 _town_kdtree
.Remove(t
->index
);
3273 if (t
->cache
.sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeTown(t
->index
));
3277 return CommandCost();
3281 * Factor in the cost of each town action.
3284 const uint8_t _town_action_costs
[TACT_COUNT
] = {
3285 2, 4, 9, 35, 48, 53, 117, 175
3289 * Perform the "small advertising campaign" town action.
3290 * @param t The town to advertise in.
3291 * @param flags Type of operation.
3292 * @return An empty cost.
3294 static CommandCost
TownActionAdvertiseSmall(Town
*t
, DoCommandFlag flags
)
3296 if (flags
& DC_EXEC
) {
3297 ModifyStationRatingAround(t
->xy
, _current_company
, 0x40, 10);
3299 return CommandCost();
3303 * Perform the "medium advertising campaign" town action.
3304 * @param t The town to advertise in.
3305 * @param flags Type of operation.
3306 * @return An empty cost.
3308 static CommandCost
TownActionAdvertiseMedium(Town
*t
, DoCommandFlag flags
)
3310 if (flags
& DC_EXEC
) {
3311 ModifyStationRatingAround(t
->xy
, _current_company
, 0x70, 15);
3313 return CommandCost();
3317 * Perform the "large advertising campaign" town action.
3318 * @param t The town to advertise in.
3319 * @param flags Type of operation.
3320 * @return An empty cost.
3322 static CommandCost
TownActionAdvertiseLarge(Town
*t
, DoCommandFlag flags
)
3324 if (flags
& DC_EXEC
) {
3325 ModifyStationRatingAround(t
->xy
, _current_company
, 0xA0, 20);
3327 return CommandCost();
3331 * Perform the "local road reconstruction" town action.
3332 * @param t The town to grief in.
3333 * @param flags Type of operation.
3334 * @return An empty cost.
3336 static CommandCost
TownActionRoadRebuild(Town
*t
, DoCommandFlag flags
)
3338 /* Check if the company is allowed to fund new roads. */
3339 if (!_settings_game
.economy
.fund_roads
) return CMD_ERROR
;
3341 if (flags
& DC_EXEC
) {
3342 t
->road_build_months
= 6;
3344 SetDParam(0, _current_company
);
3345 std::string company_name
= GetString(STR_COMPANY_NAME
);
3347 SetDParam(0, t
->index
);
3348 SetDParamStr(1, company_name
);
3351 TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_ROAD_REBUILDING_MINUTES
: STR_NEWS_ROAD_REBUILDING_MONTHS
,
3352 NT_GENERAL
, NF_NORMAL
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
);
3353 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3354 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3356 return CommandCost();
3360 * Check whether the land can be cleared.
3361 * @param tile Tile to check.
3362 * @return true if the tile can be cleared.
3364 static bool CheckClearTile(TileIndex tile
)
3366 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
);
3367 CommandCost r
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_NONE
, tile
);
3368 cur_company
.Restore();
3369 return r
.Succeeded();
3372 /** Structure for storing data while searching the best place to build a statue. */
3373 struct StatueBuildSearchData
{
3374 TileIndex best_position
; ///< Best position found so far.
3375 int tile_count
; ///< Number of tiles tried.
3377 StatueBuildSearchData(TileIndex best_pos
, int count
) : best_position(best_pos
), tile_count(count
) { }
3381 * Search callback function for #TownActionBuildStatue.
3382 * @param tile Tile on which to perform the search.
3383 * @param user_data Reference to the statue search data.
3384 * @return Result of the test.
3386 static bool SearchTileForStatue(TileIndex tile
, void *user_data
)
3388 static const int STATUE_NUMBER_INNER_TILES
= 25; // Number of tiles int the center of the city, where we try to protect houses.
3390 StatueBuildSearchData
*statue_data
= (StatueBuildSearchData
*)user_data
;
3391 statue_data
->tile_count
++;
3393 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3394 if (IsSteepSlope(GetTileSlope(tile
))) return false;
3395 /* Don't build statues under bridges. */
3396 if (IsBridgeAbove(tile
)) return false;
3398 /* A clear-able open space is always preferred. */
3399 if ((IsTileType(tile
, MP_CLEAR
) || IsTileType(tile
, MP_TREES
)) && CheckClearTile(tile
)) {
3400 statue_data
->best_position
= tile
;
3404 bool house
= IsTileType(tile
, MP_HOUSE
);
3406 /* Searching inside the inner circle. */
3407 if (statue_data
->tile_count
<= STATUE_NUMBER_INNER_TILES
) {
3408 /* Save first house in inner circle. */
3409 if (house
&& statue_data
->best_position
== INVALID_TILE
&& CheckClearTile(tile
)) {
3410 statue_data
->best_position
= tile
;
3413 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3414 return statue_data
->tile_count
== STATUE_NUMBER_INNER_TILES
&& statue_data
->best_position
!= INVALID_TILE
;
3417 /* Searching outside the circle, just pick the first possible spot. */
3418 statue_data
->best_position
= tile
; // Is optimistic, the condition below must also hold.
3419 return house
&& CheckClearTile(tile
);
3423 * Perform a 9x9 tiles circular search from the center of the town
3424 * in order to find a free tile to place a statue
3425 * @param t town to search in
3426 * @param flags Used to check if the statue must be built or not.
3427 * @return Empty cost or an error.
3429 static CommandCost
TownActionBuildStatue(Town
*t
, DoCommandFlag flags
)
3431 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
3433 TileIndex tile
= t
->xy
;
3434 StatueBuildSearchData
statue_data(INVALID_TILE
, 0);
3435 if (!CircularTileSearch(&tile
, 9, SearchTileForStatue
, &statue_data
)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE
);
3437 if (flags
& DC_EXEC
) {
3438 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
);
3439 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
, statue_data
.best_position
);
3440 cur_company
.Restore();
3441 BuildObject(OBJECT_STATUE
, statue_data
.best_position
, _current_company
, t
);
3442 SetBit(t
->statues
, _current_company
); // Once found and built, "inform" the Town.
3443 MarkTileDirtyByTile(statue_data
.best_position
);
3445 return CommandCost();
3449 * Perform the "fund new buildings" town action.
3450 * @param t The town to fund buildings in.
3451 * @param flags Type of operation.
3452 * @return An empty cost.
3454 static CommandCost
TownActionFundBuildings(Town
*t
, DoCommandFlag flags
)
3456 /* Check if it's allowed to buy the rights */
3457 if (!_settings_game
.economy
.fund_buildings
) return CMD_ERROR
;
3459 if (flags
& DC_EXEC
) {
3460 /* And grow for 3 months */
3461 t
->fund_buildings_months
= 3;
3463 /* Enable growth (also checking GameScript's opinion) */
3464 UpdateTownGrowth(t
);
3466 /* Build a new house, but add a small delay to make sure
3467 * that spamming funding doesn't let town grow any faster
3468 * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3469 * Also emulate original behaviour when town was only growing in
3470 * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3471 * tick-perfect and gives player some time window where they can
3472 * spam funding with the exact same efficiency.
3474 t
->grow_counter
= std::min
<uint16_t>(t
->grow_counter
, 2 * Ticks::TOWN_GROWTH_TICKS
- (t
->growth_rate
- t
->grow_counter
) % Ticks::TOWN_GROWTH_TICKS
);
3476 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3478 return CommandCost();
3482 * Perform the "buy exclusive transport rights" town action.
3483 * @param t The town to buy exclusivity in.
3484 * @param flags Type of operation.
3485 * @return An empty cost.
3487 static CommandCost
TownActionBuyRights(Town
*t
, DoCommandFlag flags
)
3489 /* Check if it's allowed to buy the rights */
3490 if (!_settings_game
.economy
.exclusive_rights
) return CMD_ERROR
;
3491 if (t
->exclusivity
!= INVALID_COMPANY
) return CMD_ERROR
;
3493 if (flags
& DC_EXEC
) {
3494 t
->exclusive_counter
= 12;
3495 t
->exclusivity
= _current_company
;
3497 ModifyStationRatingAround(t
->xy
, _current_company
, 130, 17);
3499 SetWindowClassesDirty(WC_STATION_VIEW
);
3501 /* Spawn news message */
3502 CompanyNewsInformation
*cni
= new CompanyNewsInformation(Company::Get(_current_company
));
3503 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE
);
3504 SetDParam(1, TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MINUTES
: STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MONTHS
);
3505 SetDParam(2, t
->index
);
3506 SetDParamStr(3, cni
->company_name
);
3507 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_GENERAL
, NF_COMPANY
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cni
);
3508 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3509 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3511 return CommandCost();
3515 * Perform the "bribe" town action.
3516 * @param t The town to bribe.
3517 * @param flags Type of operation.
3518 * @return An empty cost.
3520 static CommandCost
TownActionBribe(Town
*t
, DoCommandFlag flags
)
3522 if (flags
& DC_EXEC
) {
3523 if (Chance16(1, 14)) {
3524 /* set as unwanted for 6 months */
3525 t
->unwanted
[_current_company
] = 6;
3527 /* set all close by station ratings to 0 */
3528 for (Station
*st
: Station::Iterate()) {
3529 if (st
->town
== t
&& st
->owner
== _current_company
) {
3530 for (GoodsEntry
&ge
: st
->goods
) ge
.rating
= 0;
3534 /* only show error message to the executing player. All errors are handled command.c
3535 * but this is special, because it can only 'fail' on a DC_EXEC */
3536 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED
, INVALID_STRING_ID
, WL_INFO
);
3538 /* decrease by a lot!
3539 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3540 * be independent of any cheat settings
3542 if (t
->ratings
[_current_company
] > RATING_BRIBE_DOWN_TO
) {
3543 t
->ratings
[_current_company
] = RATING_BRIBE_DOWN_TO
;
3544 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3547 ChangeTownRating(t
, RATING_BRIBE_UP_STEP
, RATING_BRIBE_MAXIMUM
, DC_EXEC
);
3548 if (t
->exclusivity
!= _current_company
&& t
->exclusivity
!= INVALID_COMPANY
) {
3549 t
->exclusivity
= INVALID_COMPANY
;
3550 t
->exclusive_counter
= 0;
3554 return CommandCost();
3557 typedef CommandCost
TownActionProc(Town
*t
, DoCommandFlag flags
);
3558 static TownActionProc
* const _town_action_proc
[] = {
3559 TownActionAdvertiseSmall
,
3560 TownActionAdvertiseMedium
,
3561 TownActionAdvertiseLarge
,
3562 TownActionRoadRebuild
,
3563 TownActionBuildStatue
,
3564 TownActionFundBuildings
,
3565 TownActionBuyRights
,
3570 * Get a list of available town authority actions.
3571 * @param cid The company that is querying the town.
3572 * @param t The town that is queried.
3573 * @return The bitmasked value of enabled actions.
3575 TownActions
GetMaskOfTownActions(CompanyID cid
, const Town
*t
)
3577 TownActions buttons
= TACT_NONE
;
3579 /* Spectators and unwanted have no options */
3580 if (cid
!= COMPANY_SPECTATOR
&& !(_settings_game
.economy
.bribe
&& t
->unwanted
[cid
])) {
3582 /* Actions worth more than this are not able to be performed */
3583 Money avail
= GetAvailableMoney(cid
);
3585 /* Check the action bits for validity and
3586 * if they are valid add them */
3587 for (uint i
= 0; i
!= lengthof(_town_action_costs
); i
++) {
3588 const TownActions cur
= (TownActions
)(1 << i
);
3590 /* Is the company prohibited from bribing ? */
3591 if (cur
== TACT_BRIBE
) {
3592 /* Company can't bribe if setting is disabled */
3593 if (!_settings_game
.economy
.bribe
) continue;
3594 /* Company can bribe if another company has exclusive transport rights,
3595 * or its standing with the town is less than outstanding. */
3596 if (t
->ratings
[cid
] >= RATING_BRIBE_MAXIMUM
) {
3597 if (t
->exclusivity
== _current_company
) continue;
3598 if (t
->exclusive_counter
== 0) continue;
3602 /* Is the company not able to buy exclusive rights ? */
3603 if (cur
== TACT_BUY_RIGHTS
&& (!_settings_game
.economy
.exclusive_rights
|| t
->exclusive_counter
!= 0)) continue;
3605 /* Is the company not able to fund buildings ? */
3606 if (cur
== TACT_FUND_BUILDINGS
&& !_settings_game
.economy
.fund_buildings
) continue;
3608 /* Is the company not able to fund local road reconstruction? */
3609 if (cur
== TACT_ROAD_REBUILD
&& !_settings_game
.economy
.fund_roads
) continue;
3611 /* Is the company not able to build a statue ? */
3612 if (cur
== TACT_BUILD_STATUE
&& HasBit(t
->statues
, cid
)) continue;
3614 if (avail
>= _town_action_costs
[i
] * _price
[PR_TOWN_ACTION
] >> 8) {
3625 * This performs an action such as advertising, building a statue, funding buildings,
3626 * but also bribing the town-council
3627 * @param flags type of operation
3628 * @param town_id town to do the action at
3629 * @param action action to perform, @see _town_action_proc for the list of available actions
3630 * @return the cost of this operation or an error
3632 CommandCost
CmdDoTownAction(DoCommandFlag flags
, TownID town_id
, uint8_t action
)
3634 Town
*t
= Town::GetIfValid(town_id
);
3635 if (t
== nullptr || action
>= lengthof(_town_action_proc
)) return CMD_ERROR
;
3637 if (!HasBit(GetMaskOfTownActions(_current_company
, t
), action
)) return CMD_ERROR
;
3639 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_TOWN_ACTION
] * _town_action_costs
[action
] >> 8);
3641 CommandCost ret
= _town_action_proc
[action
](t
, flags
);
3642 if (ret
.Failed()) return ret
;
3644 if (flags
& DC_EXEC
) {
3645 SetWindowDirty(WC_TOWN_AUTHORITY
, town_id
);
3651 template <typename Func
>
3652 static void ForAllStationsNearTown(Town
*t
, Func func
)
3654 /* Ideally the search radius should be close to the actual town zone 0 radius.
3655 * The true radius is not stored or calculated anywhere, only the squared radius. */
3656 /* The efficiency of this search might be improved for large towns and many stations on the map,
3657 * by using an integer square root approximation giving a value not less than the true square root. */
3658 uint search_radius
= t
->cache
.squared_town_zone_radius
[HZB_TOWN_EDGE
] / 2;
3659 ForAllStationsRadius(t
->xy
, search_radius
, [&](const Station
* st
) {
3660 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[HZB_TOWN_EDGE
]) {
3667 * Monthly callback to update town and station ratings.
3668 * @param t The town to update.
3670 static void UpdateTownRating(Town
*t
)
3672 /* Increase company ratings if they're low */
3673 for (const Company
*c
: Company::Iterate()) {
3674 if (t
->ratings
[c
->index
] < RATING_GROWTH_MAXIMUM
) {
3675 t
->ratings
[c
->index
] = std::min((int)RATING_GROWTH_MAXIMUM
, t
->ratings
[c
->index
] + RATING_GROWTH_UP_STEP
);
3679 ForAllStationsNearTown(t
, [&](const Station
*st
) {
3680 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3681 if (Company::IsValidID(st
->owner
)) {
3682 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_UP_STEP
;
3683 t
->ratings
[st
->owner
] = std::min
<int>(new_rating
, INT16_MAX
); // do not let it overflow
3686 if (Company::IsValidID(st
->owner
)) {
3687 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_DOWN_STEP
;
3688 t
->ratings
[st
->owner
] = std::max(new_rating
, INT16_MIN
);
3693 /* clamp all ratings to valid values */
3694 for (uint i
= 0; i
< MAX_COMPANIES
; i
++) {
3695 t
->ratings
[i
] = Clamp(t
->ratings
[i
], RATING_MINIMUM
, RATING_MAXIMUM
);
3698 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3703 * Updates town grow counter after growth rate change.
3704 * Preserves relative house builting progress whenever it can.
3705 * @param t The town to calculate grow counter for
3706 * @param prev_growth_rate Town growth rate before it changed (one that was used with grow counter to be updated)
3708 static void UpdateTownGrowCounter(Town
*t
, uint16_t prev_growth_rate
)
3710 if (t
->growth_rate
== TOWN_GROWTH_RATE_NONE
) return;
3711 if (prev_growth_rate
== TOWN_GROWTH_RATE_NONE
) {
3712 t
->grow_counter
= std::min
<uint16_t>(t
->growth_rate
, t
->grow_counter
);
3715 t
->grow_counter
= RoundDivSU((uint32_t)t
->grow_counter
* (t
->growth_rate
+ 1), prev_growth_rate
+ 1);
3719 * Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
3720 * @param t The town to calculate stations for
3721 * @returns Amount of active stations
3723 static int CountActiveStations(Town
*t
)
3726 ForAllStationsNearTown(t
, [&](const Station
* st
) {
3727 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3735 * Calculates town growth rate in normal conditions (custom growth rate not set).
3736 * If town growth speed is set to None(0) returns the same rate as if it was Normal(2).
3737 * @param t The town to calculate growth rate for
3738 * @returns Calculated growth rate
3740 static uint
GetNormalGrowthRate(Town
*t
)
3744 * Unserviced+unfunded towns get an additional malus in UpdateTownGrowth(),
3745 * so the "320" is actually not better than the "420".
3747 static const uint16_t _grow_count_values
[2][6] = {
3748 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3749 { 320, 420, 300, 220, 160, 100 } // Normal values
3752 int n
= CountActiveStations(t
);
3753 uint16_t m
= _grow_count_values
[t
->fund_buildings_months
!= 0 ? 0 : 1][std::min(n
, 5)];
3755 uint growth_multiplier
= _settings_game
.economy
.town_growth_rate
!= 0 ? _settings_game
.economy
.town_growth_rate
- 1 : 1;
3757 m
>>= growth_multiplier
;
3758 if (t
->larger_town
) m
/= 2;
3760 return TownTicksToGameTicks(m
/ (t
->cache
.num_houses
/ 50 + 1));
3764 * Updates town growth rate.
3765 * @param t The town to update growth rate for
3767 static void UpdateTownGrowthRate(Town
*t
)
3769 if (HasBit(t
->flags
, TOWN_CUSTOM_GROWTH
)) return;
3770 uint old_rate
= t
->growth_rate
;
3771 t
->growth_rate
= GetNormalGrowthRate(t
);
3772 UpdateTownGrowCounter(t
, old_rate
);
3773 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3777 * Updates town growth state (whether it is growing or not).
3778 * @param t The town to update growth for
3780 static void UpdateTownGrowth(Town
*t
)
3782 UpdateTownGrowthRate(t
);
3784 ClrBit(t
->flags
, TOWN_IS_GROWING
);
3785 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3787 if (_settings_game
.economy
.town_growth_rate
== 0 && t
->fund_buildings_months
== 0) return;
3789 if (t
->fund_buildings_months
== 0) {
3790 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3791 for (int i
= TAE_BEGIN
; i
< TAE_END
; i
++) {
3792 switch (t
->goal
[i
]) {
3793 case TOWN_GROWTH_WINTER
:
3794 if (TileHeight(t
->xy
) >= GetSnowLine() && t
->received
[i
].old_act
== 0 && t
->cache
.population
> 90) return;
3796 case TOWN_GROWTH_DESERT
:
3797 if (GetTropicZone(t
->xy
) == TROPICZONE_DESERT
&& t
->received
[i
].old_act
== 0 && t
->cache
.population
> 60) return;
3800 if (t
->goal
[i
] > t
->received
[i
].old_act
) return;
3806 if (HasBit(t
->flags
, TOWN_CUSTOM_GROWTH
)) {
3807 if (t
->growth_rate
!= TOWN_GROWTH_RATE_NONE
) SetBit(t
->flags
, TOWN_IS_GROWING
);
3808 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3812 if (t
->fund_buildings_months
== 0 && CountActiveStations(t
) == 0 && !Chance16(1, 12)) return;
3814 SetBit(t
->flags
, TOWN_IS_GROWING
);
3815 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3819 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3820 * @param tile The tile where the station shall be constructed.
3821 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3822 * @return Succeeded or failed command.
3824 CommandCost
CheckIfAuthorityAllowsNewStation(TileIndex tile
, DoCommandFlag flags
)
3826 /* The required rating is hardcoded to RATING_VERYPOOR (see below), not the authority attitude setting, so we can bail out like this. */
3827 if (_settings_game
.difficulty
.town_council_tolerance
== TOWN_COUNCIL_PERMISSIVE
) return CommandCost();
3829 if (!Company::IsValidID(_current_company
) || (flags
& DC_NO_TEST_TOWN_RATING
)) return CommandCost();
3831 Town
*t
= ClosestTownFromTile(tile
, _settings_game
.economy
.dist_local_authority
);
3832 if (t
== nullptr) return CommandCost();
3834 if (t
->ratings
[_current_company
] > RATING_VERYPOOR
) return CommandCost();
3836 SetDParam(0, t
->index
);
3837 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3841 * Return the town closest to the given tile within \a threshold.
3842 * @param tile Starting point of the search.
3843 * @param threshold Biggest allowed distance to the town.
3844 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3846 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3848 Town
*CalcClosestTownFromTile(TileIndex tile
, uint threshold
)
3850 if (Town::GetNumItems() == 0) return nullptr;
3852 TownID tid
= _town_kdtree
.FindNearest(TileX(tile
), TileY(tile
));
3853 Town
*town
= Town::Get(tid
);
3854 if (DistanceManhattan(tile
, town
->xy
) < threshold
) return town
;
3859 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3860 * @param tile Starting point of the search.
3861 * @param threshold Biggest allowed distance to the town.
3862 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3864 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3866 Town
*ClosestTownFromTile(TileIndex tile
, uint threshold
)
3868 switch (GetTileType(tile
)) {
3870 if (IsRoadDepot(tile
)) return CalcClosestTownFromTile(tile
, threshold
);
3872 if (!HasTownOwnedRoad(tile
)) {
3873 TownID tid
= GetTownIndex(tile
);
3875 if (tid
== INVALID_TOWN
) {
3876 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3877 if (_generating_world
) return CalcClosestTownFromTile(tile
, threshold
);
3878 assert(Town::GetNumItems() == 0);
3882 assert(Town::IsValidID(tid
));
3883 Town
*town
= Town::Get(tid
);
3885 if (DistanceManhattan(tile
, town
->xy
) >= threshold
) town
= nullptr;
3892 return Town::GetByTile(tile
);
3895 return CalcClosestTownFromTile(tile
, threshold
);
3899 static bool _town_rating_test
= false; ///< If \c true, town rating is in test-mode.
3900 static std::map
<const Town
*, int> _town_test_ratings
; ///< Map of towns to modified ratings, while in town rating test-mode.
3903 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3904 * The function is safe to use in nested calls.
3905 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3907 void SetTownRatingTestMode(bool mode
)
3909 static int ref_count
= 0; // Number of times test-mode is switched on.
3911 if (ref_count
== 0) {
3912 _town_test_ratings
.clear();
3916 assert(ref_count
> 0);
3919 _town_rating_test
= !(ref_count
== 0);
3923 * Get the rating of a town for the #_current_company.
3924 * @param t Town to get the rating from.
3925 * @return Rating of the current company in the given town.
3927 static int GetRating(const Town
*t
)
3929 if (_town_rating_test
) {
3930 auto it
= _town_test_ratings
.find(t
);
3931 if (it
!= _town_test_ratings
.end()) {
3935 return t
->ratings
[_current_company
];
3939 * Changes town rating of the current company
3940 * @param t Town to affect
3941 * @param add Value to add
3942 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3943 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3945 void ChangeTownRating(Town
*t
, int add
, int max
, DoCommandFlag flags
)
3947 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3948 if (t
== nullptr || (flags
& DC_NO_MODIFY_TOWN_RATING
) ||
3949 !Company::IsValidID(_current_company
) ||
3950 (_cheats
.magic_bulldozer
.value
&& add
< 0)) {
3954 int rating
= GetRating(t
);
3958 if (rating
< max
) rating
= max
;
3963 if (rating
> max
) rating
= max
;
3966 if (_town_rating_test
) {
3967 _town_test_ratings
[t
] = rating
;
3969 SetBit(t
->have_ratings
, _current_company
);
3970 t
->ratings
[_current_company
] = rating
;
3971 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3976 * Does the town authority allow the (destructive) action of the current company?
3977 * @param flags Checking flags of the command.
3978 * @param t Town that must allow the company action.
3979 * @param type Type of action that is wanted.
3980 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3982 CommandCost
CheckforTownRating(DoCommandFlag flags
, Town
*t
, TownRatingCheckType type
)
3984 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3985 if (t
== nullptr || !Company::IsValidID(_current_company
) ||
3986 _cheats
.magic_bulldozer
.value
|| (flags
& DC_NO_TEST_TOWN_RATING
)) {
3987 return CommandCost();
3990 /* minimum rating needed to be allowed to remove stuff */
3991 static const int needed_rating
[][TOWN_RATING_CHECK_TYPE_COUNT
] = {
3992 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3993 { RATING_ROAD_NEEDED_LENIENT
, RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
}, // Lenient
3994 { RATING_ROAD_NEEDED_NEUTRAL
, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
}, // Neutral
3995 { RATING_ROAD_NEEDED_HOSTILE
, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
}, // Hostile
3996 { RATING_ROAD_NEEDED_PERMISSIVE
, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
}, // Permissive
3999 /* check if you're allowed to remove the road/bridge/tunnel
4000 * owned by a town no removal if rating is lower than ... depends now on
4001 * difficulty setting. Minimum town rating selected by difficulty level
4003 int needed
= needed_rating
[_settings_game
.difficulty
.town_council_tolerance
][type
];
4005 if (GetRating(t
) < needed
) {
4006 SetDParam(0, t
->index
);
4007 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
4010 return CommandCost();
4013 static IntervalTimer
<TimerGameEconomy
> _economy_towns_monthly({TimerGameEconomy::MONTH
, TimerGameEconomy::Priority::TOWN
}, [](auto)
4015 for (Town
*t
: Town::Iterate()) {
4016 /* Check for active town actions and decrement their counters. */
4017 if (t
->road_build_months
!= 0) t
->road_build_months
--;
4018 if (t
->fund_buildings_months
!= 0) t
->fund_buildings_months
--;
4020 if (t
->exclusive_counter
!= 0) {
4021 if (--t
->exclusive_counter
== 0) t
->exclusivity
= INVALID_COMPANY
;
4024 /* Check for active failed bribe cooloff periods and decrement them. */
4025 for (const Company
*c
: Company::Iterate()) {
4026 if (t
->unwanted
[c
->index
] > 0) t
->unwanted
[c
->index
]--;
4029 /* Update cargo statistics. */
4030 for (auto &supplied
: t
->supplied
) supplied
.NewMonth();
4031 for (auto &received
: t
->received
) received
.NewMonth();
4033 UpdateTownGrowth(t
);
4034 UpdateTownRating(t
);
4036 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
4040 static IntervalTimer
<TimerGameEconomy
> _economy_towns_yearly({TimerGameEconomy::YEAR
, TimerGameEconomy::Priority::TOWN
}, [](auto)
4042 /* Increment house ages */
4043 for (TileIndex t
= 0; t
< Map::Size(); t
++) {
4044 if (!IsTileType(t
, MP_HOUSE
)) continue;
4045 IncrementHouseAge(t
);
4049 static CommandCost
TerraformTile_Town(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4051 if (AutoslopeEnabled()) {
4052 HouseID house
= GetHouseType(tile
);
4053 GetHouseNorthPart(house
); // modifies house to the ID of the north tile
4054 const HouseSpec
*hs
= HouseSpec::Get(house
);
4056 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
4057 if (((hs
->building_flags
& TILE_NOT_SLOPED
) == 0) && !IsSteepSlope(tileh_new
) &&
4058 (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
4059 bool allow_terraform
= true;
4061 /* Call the autosloping callback per tile, not for the whole building at once. */
4062 house
= GetHouseType(tile
);
4063 hs
= HouseSpec::Get(house
);
4064 if (HasBit(hs
->callback_mask
, CBM_HOUSE_AUTOSLOPE
)) {
4065 /* If the callback fails, allow autoslope. */
4066 uint16_t res
= GetHouseCallback(CBID_HOUSE_AUTOSLOPE
, 0, 0, house
, Town::GetByTile(tile
), tile
);
4067 if (res
!= CALLBACK_FAILED
&& ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_AUTOSLOPE
, res
)) allow_terraform
= false;
4070 if (allow_terraform
) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4074 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
4077 /** Tile callback functions for a town */
4078 extern const TileTypeProcs _tile_type_town_procs
= {
4079 DrawTile_Town
, // draw_tile_proc
4080 GetSlopePixelZ_Town
, // get_slope_z_proc
4081 ClearTile_Town
, // clear_tile_proc
4082 AddAcceptedCargo_Town
, // add_accepted_cargo_proc
4083 GetTileDesc_Town
, // get_tile_desc_proc
4084 GetTileTrackStatus_Town
, // get_tile_track_status_proc
4085 nullptr, // click_tile_proc
4086 AnimateTile_Town
, // animate_tile_proc
4087 TileLoop_Town
, // tile_loop_proc
4088 ChangeTileOwner_Town
, // change_tile_owner_proc
4089 AddProducedCargo_Town
, // add_produced_cargo_proc
4090 nullptr, // vehicle_enter_tile_proc
4091 GetFoundation_Town
, // get_foundation_proc
4092 TerraformTile_Town
, // terraform_tile_proc
4095 std::span
<const DrawBuildingsTileStruct
> GetTownDrawTileData()
4097 return _town_draw_tile_data
;