OpenTTD Source  12.0-beta2
town.h
Go to the documentation of this file.
1 /*
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/>.
6  */
7 
10 #ifndef TOWN_H
11 #define TOWN_H
12 
13 #include "viewport_type.h"
14 #include "town_map.h"
15 #include "subsidy_type.h"
16 #include "newgrf_storage.h"
17 #include "cargotype.h"
18 #include <list>
19 
20 template <typename T>
22  T id_count[NUM_HOUSES];
23  T class_count[HOUSE_CLASS_MAX];
24 };
25 
26 static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4;
27 static const uint CUSTOM_TOWN_MAX_NUMBER = 5000;
28 
29 static const TownID INVALID_TOWN = 0xFFFF;
30 
31 static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE;
32 static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF;
33 static const uint16 TOWN_GROWTH_RATE_NONE = 0xFFFF;
34 static const uint16 MAX_TOWN_GROWTH_TICKS = 930;
35 
37 extern TownPool _town_pool;
38 
40 struct TownCache {
41  uint32 num_houses;
42  uint32 population;
45  uint32 squared_town_zone_radius[HZB_END];
47 };
48 
50 struct Town : TownPool::PoolItem<&_town_pool> {
52 
54 
55  /* Town name */
56  uint32 townnamegrfid;
57  uint16 townnametype;
58  uint32 townnameparts;
59  std::string name;
60  mutable std::string cached_name;
61 
62  byte flags;
63 
64  uint16 noise_reached;
65 
66  CompanyMask statues;
67 
68  /* Company ratings. */
69  CompanyMask have_ratings;
74 
77  uint32 goal[NUM_TE];
78 
79  std::string text;
80 
81  inline byte GetPercentTransported(CargoID cid) const { return this->supplied[cid].old_act * 256 / (this->supplied[cid].old_max + 1); }
82 
84 
86 
87  uint16 grow_counter;
88  uint16 growth_rate;
89 
92 
93  bool larger_town;
95 
96  bool show_zone;
97 
98  std::list<PersistentStorage *> psa_list;
99 
104  Town(TileIndex tile = INVALID_TILE) : xy(tile) { }
105 
107  ~Town();
108 
110 
117  inline uint16 MaxTownNoise() const
118  {
119  if (this->cache.population == 0) return 0; // no population? no noise
120 
121  /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
123  }
124 
125  void UpdateVirtCoord();
126 
127  inline const char *GetCachedName() const
128  {
129  if (!this->name.empty()) return this->name.c_str();
130  if (this->cached_name.empty()) this->FillCachedName();
131  return this->cached_name.c_str();
132  }
133 
134  static inline Town *GetByTile(TileIndex tile)
135  {
136  return Town::Get(GetTownIndex(tile));
137  }
138 
139  static Town *GetRandom();
140  static void PostDestructor(size_t index);
141 
142 private:
143  void FillCachedName() const;
144 };
145 
146 uint32 GetWorldPopulation();
147 
149 void ClearAllTownCachedNames();
150 void ShowTownViewWindow(TownID town);
151 void ExpandTown(Town *t);
152 
153 void RebuildTownKdtree();
154 
155 
164 };
165 
168  TDIWD_FORCE_REBUILD,
169  TDIWD_POPULATION_CHANGE,
170  TDIWD_FORCE_RESORT,
171 };
172 
180 enum TownFlags {
185 };
186 
188 
189 
191 
192 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
193 
194 void ResetHouses();
195 
196 void ClearTownHouse(Town *t, TileIndex tile);
197 void UpdateTownMaxPass(Town *t);
198 void UpdateTownRadius(Town *t);
200 Town *ClosestTownFromTile(TileIndex tile, uint threshold);
201 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags);
202 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile);
203 void SetTownRatingTestMode(bool mode);
204 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t);
205 bool GenerateTowns(TownLayout layout);
207 
210  TACT_NONE = 0x00,
211 
219  TACT_BRIBE = 0x80,
220 
222 
227 };
229 
230 extern const byte _town_action_costs[TACT_COUNT];
231 extern TownID _new_town_id;
232 
238 template <class T>
239 void MakeDefaultName(T *obj)
240 {
241  /* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
242  assert(obj->name.empty() || obj->town_cn == UINT16_MAX);
243 
244  obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
245 
246  /* Find first unused number belonging to this town. This can never fail,
247  * as long as there can be at most 65535 waypoints/depots in total.
248  *
249  * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at
250  * most 'n * (1 + ceil(m / 32))' steps (n - number of waypoints in pool,
251  * m - number of waypoints near this town).
252  * Usually, it needs only 'n' steps.
253  *
254  * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
255  * but this way it is faster */
256 
257  uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
258  uint32 next = 0; // first number in the bitmap
259  uint32 idx = 0; // index where we will stop
260  uint32 cid = 0; // current index, goes to T::GetPoolSize()-1, then wraps to 0
261 
262  do {
263  T *lobj = T::GetIfValid(cid);
264 
265  /* check only valid waypoints... */
266  if (lobj != nullptr && obj != lobj) {
267  /* only objects within the same city and with the same type */
268  if (lobj->town == obj->town && lobj->IsOfType(obj)) {
269  /* if lobj->town_cn < next, uint will overflow to '+inf' */
270  uint i = (uint)lobj->town_cn - next;
271 
272  if (i < 32) {
273  SetBit(used, i); // update bitmap
274  if (i == 0) {
275  /* shift bitmap while the lowest bit is '1';
276  * increase the base of the bitmap too */
277  do {
278  used >>= 1;
279  next++;
280  } while (HasBit(used, 0));
281  /* when we are at 'idx' again at end of the loop and
282  * 'next' hasn't changed, then no object had town_cn == next,
283  * so we can safely use it */
284  idx = cid;
285  }
286  }
287  }
288  }
289 
290  cid++;
291  if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
292  } while (cid != idx);
293 
294  obj->town_cn = (uint16)next; // set index...
295 }
296 
297 /*
298  * Converts original town ticks counters to plain game ticks. Note that
299  * tick 0 is a valid tick so actual amount is one more than the counter value.
300  */
301 static inline uint16 TownTicksToGameTicks(uint16 ticks) {
302  return (std::min(ticks, MAX_TOWN_GROWTH_TICKS) + 1) * TOWN_GROWTH_TICKS - 1;
303 }
304 
305 
306 RoadType GetTownRoadType(const Town *t);
307 
308 #endif /* TOWN_H */
TACT_BRIBE
@ TACT_BRIBE
Try to bribe the council.
Definition: town.h:219
Town::have_ratings
CompanyMask have_ratings
which companies have a rating
Definition: town.h:69
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:83
TACT_BUILD_STATUE
@ TACT_BUILD_STATUE
Build a statue.
Definition: town.h:216
MAX_TOWN_GROWTH_TICKS
static const uint16 MAX_TOWN_GROWTH_TICKS
Max amount of original town ticks that still fit into uint16, about equal to UINT16_MAX / TOWN_GROWTH...
Definition: town.h:34
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
Town::InitializeLayout
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:170
Town::road_build_months
byte road_build_months
fund road reconstruction in action?
Definition: town.h:91
TownDirectoryInvalidateWindowData
TownDirectoryInvalidateWindowData
Special values for town list window for the data parameter of InvalidateWindowData.
Definition: town.h:167
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3594
Town::unwanted
uint8 unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
Definition: town.h:70
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:66
DifficultySettings::town_council_tolerance
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:90
Town::noise_reached
uint16 noise_reached
level of noise that all the airports are generating
Definition: town.h:64
TownCache::squared_town_zone_radius
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:45
TOWN_GROWTH_TICKS
static const int TOWN_GROWTH_TICKS
cycle duration for towns trying to grow. (this originates from the size of the town array in TTD
Definition: date_type.h:38
Pool::PoolItem<&_town_pool >::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
TACT_FUND_BUILDINGS
@ TACT_FUND_BUILDINGS
Fund new buildings.
Definition: town.h:217
GetHouseNorthPart
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2681
TACT_ADVERTISE
@ TACT_ADVERTISE
All possible advertising actions.
Definition: town.h:223
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:575
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
Town::goal
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:77
subsidy_type.h
TownCache::part_of_subsidy
PartOfSubsidy part_of_subsidy
Is this town a source/destination of a subsidy?
Definition: town.h:44
TownCache
Data structure with cached data of towns.
Definition: town.h:40
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:57
TownLayout
TownLayout
Town Layouts.
Definition: town_type.h:78
HOUSE_CLASS_MAX
static const uint HOUSE_CLASS_MAX
There can only be as many classes as there are new houses, plus one for NO_CLASS, as the original hou...
Definition: house.h:38
FindFirstCargoWithTownEffect
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2780
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
TACT_FUNDS
@ TACT_FUNDS
All possible funding actions.
Definition: town.h:225
Town::fund_buildings_months
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:90
CheckforTownRating
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3710
Town::show_zone
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:96
TOWN_HAS_STADIUM
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition: town.h:183
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3555
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:346
GetTownIndex
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:22
Town::UpdateVirtCoord
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else)
Definition: town_cmd.cpp:399
Town::GetRandom
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:184
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2257
TACT_ADVERTISE_MEDIUM
@ TACT_ADVERTISE_MEDIUM
Medium advertising campaign.
Definition: town.h:213
TownCache::building_counts
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:46
Town::Town
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:104
UpdateAllTownVirtCoords
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:417
TownCache::population
uint32 population
Current population of people.
Definition: town.h:42
CUSTOM_TOWN_MAX_NUMBER
static const uint CUSTOM_TOWN_MAX_NUMBER
this is the maximum number of towns a user can specify in customisation
Definition: town.h:27
TOWN_RATING_CHECK_TYPE_COUNT
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition: town.h:163
Town::time_until_rebuild
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:85
CommandCost
Common return value for all commands.
Definition: command_type.h:23
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3576
TrackedViewportSign
Specialised ViewportSign that tracks whether it is valid for entering into a Kdtree.
Definition: viewport_type.h:57
TileIndexDiff
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:154
NUM_TE
@ NUM_TE
Amount of town effects.
Definition: cargotype.h:35
TOWN_GROWTH_DESERT
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:32
TownRatingCheckType
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:160
BuildingCounts
Definition: town.h:21
Town::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:83
TACT_ROAD_REBUILD
@ TACT_ROAD_REBUILD
Rebuild the roads.
Definition: town.h:215
GetMaskOfTownActions
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3298
TownFlags
TownFlags
This enum is used in conjunction with town->flags.
Definition: town.h:180
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:53
Town::MaxTownNoise
uint16 MaxTownNoise() const
Calculate the max town noise.
Definition: town.h:117
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:585
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
GetWorldPopulation
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:450
Town::growth_rate
uint16 growth_rate
town growth rate
Definition: town.h:88
_town_action_costs
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:3055
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:22
StationList
std::set< Station *, StationCompare > StationList
List of stations.
Definition: station_type.h:94
Town::ratings
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:73
TACT_ADVERTISE_LARGE
@ TACT_ADVERTISE_LARGE
Large advertising campaign.
Definition: town.h:214
TownEffect
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:26
ChangeTownRating
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3673
TACT_CONSTRUCTION
@ TACT_CONSTRUCTION
All possible construction actions.
Definition: town.h:224
TransportedCargoStat::old_max
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
TOWN_GROWTH_WINTER
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:31
Town::PostDestructor
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
Definition: town_cmd.cpp:156
MakeDefaultName
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition: town.h:239
Town::text
std::string text
General text with additional information.
Definition: town.h:79
HouseID
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
EconomySettings::town_noise_population
uint16 town_noise_population[3]
population to base decision on noise evaluation (
Definition: settings_type.h:520
Pool
Base class for all pools.
Definition: pool_type.hpp:81
GenerateTowns
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:2205
TACT_COUNT
@ TACT_COUNT
Number of available town actions.
Definition: town.h:221
TACT_ADVERTISE_SMALL
@ TACT_ADVERTISE_SMALL
Small advertising campaign.
Definition: town.h:212
TransportedCargoStat::old_act
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:53
cargotype.h
Town::~Town
~Town()
Destroy the town.
Definition: town_cmd.cpp:101
TOWN_IS_GROWING
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:181
PartOfSubsidy
PartOfSubsidy
What part of a subsidy is something?
Definition: subsidy_type.h:16
TACT_NONE
@ TACT_NONE
Empty action set.
Definition: town.h:210
DECLARE_ENUM_AS_BIT_SET
DECLARE_ENUM_AS_BIT_SET(GenderEthnicity) enum CompanyManagerFaceVariable
Bitgroups of the CompanyManagerFace variable.
Definition: company_manager_face.h:29
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
Town
Town data structure.
Definition: town.h:50
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
TownCache::num_houses
uint32 num_houses
Amount of houses.
Definition: town.h:41
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:88
Town::layout
TownLayout layout
town specific road layout
Definition: town.h:94
viewport_type.h
Town::larger_town
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:93
TUNNELBRIDGE_REMOVE
@ TUNNELBRIDGE_REMOVE
Removal of a tunnel or bridge owned by the towb.
Definition: town.h:162
ROAD_REMOVE
@ ROAD_REMOVE
Removal of a road owned by the town.
Definition: town.h:161
Town::name
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition: town.h:59
Town::supplied
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:75
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:71
Town::grow_counter
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:87
newgrf_storage.h
TACT_ALL
@ TACT_ALL
All possible actions.
Definition: town.h:226
Pool::PoolItem
Base class for all PoolItems.
Definition: pool_type.hpp:234
TOWN_CUSTOM_GROWTH
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition: town.h:184
Town::exclusive_counter
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:72
SetTownRatingTestMode
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Definition: town_cmd.cpp:3635
TOWN_HAS_CHURCH
@ TOWN_HAS_CHURCH
There can be only one church by town.
Definition: town.h:182
TOWN_GROWTH_RATE_NONE
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:33
Town::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:60
TownActions
TownActions
Town actions of a company.
Definition: town.h:209
CUSTOM_TOWN_NUMBER_DIFFICULTY
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:26
TransportedCargoStat< uint32 >
TownCache::sign
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:43
Town::received
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:76
Town::flags
byte flags
See TownFlags.
Definition: town.h:62
TACT_BUY_RIGHTS
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition: town.h:218
town_map.h