Fix: Data races on cursor state in OpenGL backends
[openttd-github.git] / src / town.h
blobe186951e63fce23ab9dd5f26bdb9a6db7846168a
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 */
8 /** @file town.h Base of the town class. */
10 #ifndef TOWN_H
11 #define TOWN_H
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>
20 template <typename T>
21 struct BuildingCounts {
22 T id_count[NUM_HOUSES];
23 T class_count[HOUSE_CLASS_MAX];
26 static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4; ///< value for custom town number in difficulty settings
27 static const uint CUSTOM_TOWN_MAX_NUMBER = 5000; ///< this is the maximum number of towns a user can specify in customisation
29 static const TownID INVALID_TOWN = 0xFFFF;
31 static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE; ///< The town only needs this cargo in the winter (any amount)
32 static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF; ///< The town needs the cargo for growth when on desert (any amount)
33 static const uint16 TOWN_GROWTH_RATE_NONE = 0xFFFF; ///< Special value for Town::growth_rate to disable town growth.
34 static const uint16 MAX_TOWN_GROWTH_TICKS = 930; ///< Max amount of original town ticks that still fit into uint16, about equal to UINT16_MAX / TOWN_GROWTH_TICKS but slightly less to simplify calculations
36 typedef Pool<Town, TownID, 64, 64000> TownPool;
37 extern TownPool _town_pool;
39 /** Data structure with cached data of towns. */
40 struct TownCache {
41 uint32 num_houses; ///< Amount of houses
42 uint32 population; ///< Current population of people
43 TrackedViewportSign sign; ///< Location of name sign, UpdateVirtCoord updates this
44 PartOfSubsidy part_of_subsidy; ///< Is this town a source/destination of a subsidy?
45 uint32 squared_town_zone_radius[HZB_END]; ///< UpdateTownRadius updates this given the house count
46 BuildingCounts<uint16> building_counts; ///< The number of each type of building in the town
49 /** Town data structure. */
50 struct Town : TownPool::PoolItem<&_town_pool> {
51 TileIndex xy; ///< town center tile
53 TownCache cache; ///< Container for all cacheable data.
55 /* Town name */
56 uint32 townnamegrfid;
57 uint16 townnametype;
58 uint32 townnameparts;
59 std::string name; ///< Custom town name. If empty, the town was not renamed and uses the generated name.
60 mutable std::string cached_name; ///< NOSAVE: Cache of the resolved name of the town, if not using a custom town name
62 byte flags; ///< See #TownFlags.
64 uint16 noise_reached; ///< level of noise that all the airports are generating
66 CompanyMask statues; ///< which companies have a statue?
68 /* Company ratings. */
69 CompanyMask have_ratings; ///< which companies have a rating
70 uint8 unwanted[MAX_COMPANIES]; ///< how many months companies aren't wanted by towns (bribe)
71 CompanyID exclusivity; ///< which company has exclusivity
72 uint8 exclusive_counter; ///< months till the exclusivity expires
73 int16 ratings[MAX_COMPANIES]; ///< ratings of each company for this town
75 TransportedCargoStat<uint32> supplied[NUM_CARGO]; ///< Cargo statistics about supplied cargo.
76 TransportedCargoStat<uint16> received[NUM_TE]; ///< Cargo statistics about received cargotypes.
77 uint32 goal[NUM_TE]; ///< Amount of cargo required for the town to grow.
79 std::string text; ///< General text with additional information.
81 inline byte GetPercentTransported(CargoID cid) const { return this->supplied[cid].old_act * 256 / (this->supplied[cid].old_max + 1); }
83 StationList stations_near; ///< NOSAVE: List of nearby stations.
85 uint16 time_until_rebuild; ///< time until we rebuild a house
87 uint16 grow_counter; ///< counter to count when to grow, value is smaller than or equal to growth_rate
88 uint16 growth_rate; ///< town growth rate
90 byte fund_buildings_months; ///< fund buildings program in action?
91 byte road_build_months; ///< fund road reconstruction in action?
93 bool larger_town; ///< if this is a larger town and should grow more quickly
94 TownLayout layout; ///< town specific road layout
96 bool show_zone; ///< NOSAVE: mark town to show the local authority zone in the viewports
98 std::list<PersistentStorage *> psa_list;
101 * Creates a new town.
102 * @param tile center tile of the town
104 Town(TileIndex tile = INVALID_TILE) : xy(tile) { }
106 /** Destroy the town. */
107 ~Town();
109 void InitializeLayout(TownLayout layout);
112 * Calculate the max town noise.
113 * The value is counted using the population divided by the content of the
114 * entry in town_noise_population corresponding to the town's tolerance.
115 * @return the maximum noise level the town will tolerate.
117 inline uint16 MaxTownNoise() const
119 if (this->cache.population == 0) return 0; // no population? no noise
121 /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
122 return (this->cache.population / _settings_game.economy.town_noise_population[_settings_game.difficulty.town_council_tolerance]) + 3;
125 void UpdateVirtCoord();
127 inline const char *GetCachedName() const
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();
134 static inline Town *GetByTile(TileIndex tile)
136 return Town::Get(GetTownIndex(tile));
139 static Town *GetRandom();
140 static void PostDestructor(size_t index);
142 private:
143 void FillCachedName() const;
146 uint32 GetWorldPopulation();
148 void UpdateAllTownVirtCoords();
149 void ClearAllTownCachedNames();
150 void ShowTownViewWindow(TownID town);
151 void ExpandTown(Town *t);
153 void RebuildTownKdtree();
157 * Action types that a company must ask permission for to a town authority.
158 * @see CheckforTownRating
160 enum TownRatingCheckType {
161 ROAD_REMOVE = 0, ///< Removal of a road owned by the town.
162 TUNNELBRIDGE_REMOVE = 1, ///< Removal of a tunnel or bridge owned by the towb.
163 TOWN_RATING_CHECK_TYPE_COUNT, ///< Number of town checking action types.
166 /** Special values for town list window for the data parameter of #InvalidateWindowData. */
167 enum TownDirectoryInvalidateWindowData {
168 TDIWD_FORCE_REBUILD,
169 TDIWD_POPULATION_CHANGE,
170 TDIWD_FORCE_RESORT,
174 * This enum is used in conjunction with town->flags.
175 * IT simply states what bit is used for.
176 * It is pretty unrealistic (IMHO) to only have one church/stadium
177 * per town, NO MATTER the population of it.
178 * And there are 5 more bits available on flags...
180 enum TownFlags {
181 TOWN_IS_GROWING = 0, ///< Conditions for town growth are met. Grow according to Town::growth_rate.
182 TOWN_HAS_CHURCH = 1, ///< There can be only one church by town.
183 TOWN_HAS_STADIUM = 2, ///< There can be only one stadium by town.
184 TOWN_CUSTOM_GROWTH = 3, ///< Growth rate is controlled by GS.
187 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type);
190 TileIndexDiff GetHouseNorthPart(HouseID &house);
192 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
194 void ResetHouses();
196 void ClearTownHouse(Town *t, TileIndex tile);
197 void UpdateTownMaxPass(Town *t);
198 void UpdateTownRadius(Town *t);
199 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags);
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);
206 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect);
208 /** Town actions of a company. */
209 enum TownActions {
210 TACT_NONE = 0x00, ///< Empty action set.
212 TACT_ADVERTISE_SMALL = 0x01, ///< Small advertising campaign.
213 TACT_ADVERTISE_MEDIUM = 0x02, ///< Medium advertising campaign.
214 TACT_ADVERTISE_LARGE = 0x04, ///< Large advertising campaign.
215 TACT_ROAD_REBUILD = 0x08, ///< Rebuild the roads.
216 TACT_BUILD_STATUE = 0x10, ///< Build a statue.
217 TACT_FUND_BUILDINGS = 0x20, ///< Fund new buildings.
218 TACT_BUY_RIGHTS = 0x40, ///< Buy exclusive transport rights.
219 TACT_BRIBE = 0x80, ///< Try to bribe the council.
221 TACT_COUNT = 8, ///< Number of available town actions.
223 TACT_ADVERTISE = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE, ///< All possible advertising actions.
224 TACT_CONSTRUCTION = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FUND_BUILDINGS, ///< All possible construction actions.
225 TACT_FUNDS = TACT_BUY_RIGHTS | TACT_BRIBE, ///< All possible funding actions.
226 TACT_ALL = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS, ///< All possible actions.
228 DECLARE_ENUM_AS_BIT_SET(TownActions)
230 extern const byte _town_action_costs[TACT_COUNT];
231 extern TownID _new_town_id;
234 * Set the default name for a depot/waypoint
235 * @tparam T The type/class to make a default name for
236 * @param obj The object/instance we want to find the name for
238 template <class T>
239 void MakeDefaultName(T *obj)
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);
244 obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
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.
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.
254 * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
255 * but this way it is faster */
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
262 do {
263 T *lobj = T::GetIfValid(cid);
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;
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;
290 cid++;
291 if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
292 } while (cid != idx);
294 obj->town_cn = (uint16)next; // set index...
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.
301 static inline uint16 TownTicksToGameTicks(uint16 ticks) {
302 return (std::min(ticks, MAX_TOWN_GROWTH_TICKS) + 1) * TOWN_GROWTH_TICKS - 1;
306 RoadType GetTownRoadType(const Town *t);
308 #endif /* TOWN_H */