Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / town.h
blob59c4761a28f5f439ff392483962907191da18bc7
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file town.h Base of the town class. */
12 #ifndef TOWN_H
13 #define TOWN_H
15 #include "viewport_type.h"
16 #include "town_map.h"
17 #include "subsidy_type.h"
18 #include "newgrf_storage.h"
19 #include "cargotype.h"
20 #include "tilematrix_type.hpp"
21 #include "openttd.h"
22 #include "table/strings.h"
23 #include "company_func.h"
24 #include <list>
26 template <typename T>
27 struct BuildingCounts {
28 T id_count[NUM_HOUSES];
29 T class_count[HOUSE_CLASS_MAX];
32 typedef TileMatrix<uint32, 4> AcceptanceMatrix;
34 static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4; //!< value for custom town number in difficulty settings
35 static const uint CUSTOM_TOWN_MAX_NUMBER = 5000; //!< this is the maximum number of towns a user can specify in customisation
37 static const uint INVALID_TOWN = 0xFFFF;
39 static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE; //!< The town only needs this cargo in the winter (any amount)
40 static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF; //!< The town needs the cargo for growth when on desert (any amount)
41 static const Ticks TOWN_GROWTH_RATE_NONE = INVALID_TICKS; //!< Special value for Town::growth_rate to disable town growth.
43 typedef Pool<Town, TownID, 64, 64000> TownPool;
44 extern TownPool _town_pool;
46 /**
47 * Action types that a company must ask permission for to a town authority.
48 * @see CheckforTownRating
50 enum TownRatingCheckType
52 ROAD_REMOVE = 0, ///< Removal of a road owned by the town.
53 TUNNELBRIDGE_REMOVE = 1, ///< Removal of a tunnel or bridge owned by the towb.
54 TOWN_RATING_CHECK_TYPE_COUNT, ///< Number of town checking action types.
57 /**
58 * This enum is used in conjunction with town->flags.
59 * IT simply states what bit is used for.
60 * It is pretty unrealistic (IMHO) to only have one church/stadium
61 * per town, NO MATTER the population of it.
62 * And there are 5 more bits available on flags...
64 enum TownFlags
66 TOWN_IS_GROWING = 0, ///< Conditions for town growth are met. Grow according to Town::growth_rate.
67 TOWN_HAS_CHURCH = 1, ///< There can be only one church by town.
68 TOWN_HAS_STADIUM = 2, ///< There can be only one stadium by town.
69 TOWN_CUSTOM_GROWTH = 3, ///< Growth rate is controlled by GS.
72 /** Data structure with cached data of towns. */
73 struct TownCache {
74 uint32 num_houses; ///< Amount of houses
75 uint32 population; ///< Current population of people
76 ViewportSign sign; ///< Location of name sign, UpdateVirtCoord updates this
77 PartOfSubsidyByte part_of_subsidy; ///< Is this town a source/destination of a subsidy?
78 uint32 squared_town_zone_radius[HZB_END]; ///< UpdateTownRadius updates this given the house count
79 BuildingCounts<uint16> building_counts; ///< The number of each type of building in the town
82 /** Town data structure. */
83 struct Town : TownPool::PoolItem<&_town_pool> {
84 TileIndex xy; ///< town center tile
86 TownCache cache; ///< Container for all cacheable data.
88 /* Town name */
89 uint32 townnamegrfid;
90 uint16 townnametype;
91 uint32 townnameparts;
92 char *name; ///< Custom town name. If nullptr, the town was not renamed and uses the generated name.
94 byte flags; ///< See #TownFlags.
96 uint16 noise_reached; ///< level of noise that all the airports are generating
98 CompanyMask statues; ///< which companies have a statue?
100 /* Company ratings. */
101 CompanyMask have_ratings; ///< which companies have a rating
102 uint8 unwanted[MAX_COMPANIES]; ///< how many months companies aren't wanted by towns (bribe)
103 CompanyByte exclusivity; ///< which company has exclusivity
104 uint8 exclusive_counter; ///< months till the exclusivity expires
105 int16 ratings[MAX_COMPANIES]; ///< ratings of each company for this town
106 StringID town_label; ///< Label dependent on _local_company rating.
108 TransportedCargoStat<uint32> supplied[NUM_CARGO]; ///< Cargo statistics about supplied cargo.
109 TransportedCargoStat<uint16> received[NUM_TE]; ///< Cargo statistics about received cargotypes.
110 uint32 goal[NUM_TE]; ///< Amount of cargo required for the town to grow.
112 char *text; ///< General text with additional information.
114 inline byte GetPercentTransported(CargoID cid) const { return this->supplied[cid].old_act * 256 / (this->supplied[cid].old_max + 1); }
116 /* Cargo production and acceptance stats. */
117 uint32 cargo_produced; ///< Bitmap of all cargoes produced by houses in this town.
118 AcceptanceMatrix cargo_accepted; ///< Bitmap of cargoes accepted by houses for each 4*4 map square of the town.
119 uint32 cargo_accepted_total; ///< NOSAVE: Bitmap of all cargoes accepted by houses in this town.
121 int32 time_until_rebuild; ///< date at which we we rebuild a house
123 Ticks grow_counter; ///< counter to count when to grow, value is smaller than or equal to growth_rate
124 Ticks growth_rate; ///< town growth rate
126 byte fund_buildings_months; ///< fund buildings program in action?
127 byte road_build_months; ///< fund road reconstruction in action?
129 bool larger_town; ///< if this is a larger town and should grow more quickly
130 TownLayoutByte layout; ///< town specific road layout
132 std::list<PersistentStorage *> psa_list;
135 * Creates a new town.
136 * @param tile center tile of the town
138 Town(TileIndex tile = INVALID_TILE) : xy(tile) { }
140 /** Destroy the town. */
141 ~Town();
143 void InitializeLayout(TownLayout layout);
145 void UpdateLabel();
148 * Returns the correct town label, based on rating.
150 inline StringID Label() const{
151 if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
152 return STR_VIEWPORT_TOWN_POP_VERY_POOR_RATING + this->town_label;
153 } else {
154 return _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN;
159 * Returns the correct town small label, based on rating.
161 inline StringID SmallLabel() const{
162 if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
163 return STR_VIEWPORT_TOWN_TINY_VERY_POOR_RATING + this->town_label;
164 } else {
165 return STR_VIEWPORT_TOWN_TINY_WHITE;
170 * Calculate the max town noise.
171 * The value is counted using the population divided by the content of the
172 * entry in town_noise_population corresponding to the town's tolerance.
173 * @return the maximum noise level the town will tolerate.
175 inline uint16 MaxTownNoise() const
177 if (this->cache.population == 0) return 0; // no population? no noise
179 /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
180 return (this->cache.population / _settings_game.economy.town_noise_population[_settings_game.difficulty.town_council_tolerance]) + 3;
183 void UpdateVirtCoord();
185 static inline Town *GetByTile(TileIndex tile)
187 return Town::Get(GetTownIndex(tile));
190 static Town *GetRandom();
192 bool IsGrowing() const
194 return HasBit(this->flags, TOWN_IS_GROWING);
197 int32 GetGrowthRateInDays() const
199 return IsGrowing() ? RoundDivSU(this->growth_rate + 1, DAY_TICKS) : 0;
202 static void PostDestructor(size_t index);
205 uint32 GetWorldPopulation();
207 void UpdateAllTownVirtCoords();
208 void ShowTownViewWindow(TownID town);
209 void ExpandTown(Town *t);
211 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type);
214 TileIndexDiff GetHouseNorthPart(HouseID &house);
216 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
218 #define FOR_ALL_TOWNS_FROM(var, start) FOR_ALL_ITEMS_FROM(Town, town_index, var, start)
219 #define FOR_ALL_TOWNS(var) FOR_ALL_TOWNS_FROM(var, 0)
221 void ResetHouses();
223 void ClearTownHouse(Town *t, TileIndex tile);
224 void UpdateTownMaxPass(Town *t);
225 void UpdateTownRadius(Town *t);
226 void UpdateTownCargoes(Town *t);
227 void UpdateTownCargoTotal(Town *t);
228 void UpdateTownCargoBitmap();
229 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags);
230 Town *ClosestTownFromTile(TileIndex tile, uint threshold);
231 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags);
232 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile);
233 void SetTownRatingTestMode(bool mode);
234 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t);
235 bool GenerateTowns(TownLayout layout);
236 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect);
238 /** Town actions of a company. */
239 enum TownActions {
240 TACT_NONE = 0x00, ///< Empty action set.
242 TACT_ADVERTISE_SMALL = 0x01, ///< Small advertising campaign.
243 TACT_ADVERTISE_MEDIUM = 0x02, ///< Medium advertising campaign.
244 TACT_ADVERTISE_LARGE = 0x04, ///< Large advertising campaign.
245 TACT_ROAD_REBUILD = 0x08, ///< Rebuild the roads.
246 TACT_BUILD_STATUE = 0x10, ///< Build a statue.
247 TACT_FUND_BUILDINGS = 0x20, ///< Fund new buildings.
248 TACT_BUY_RIGHTS = 0x40, ///< Buy exclusive transport rights.
249 TACT_BRIBE = 0x80, ///< Try to bribe the council.
251 TACT_COUNT = 8, ///< Number of available town actions.
253 TACT_ADVERTISE = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE, ///< All possible advertising actions.
254 TACT_CONSTRUCTION = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FUND_BUILDINGS, ///< All possible construction actions.
255 TACT_FUNDS = TACT_BUY_RIGHTS | TACT_BRIBE, ///< All possible funding actions.
256 TACT_ALL = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS, ///< All possible actions.
258 DECLARE_ENUM_AS_BIT_SET(TownActions)
260 extern const byte _town_action_costs[TACT_COUNT];
261 extern TownID _new_town_id;
264 * Set the default name for a depot/waypoint
265 * @tparam T The type/class to make a default name for
266 * @param obj The object/instance we want to find the name for
268 template <class T>
269 void MakeDefaultName(T *obj)
271 /* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
272 assert(obj->name == nullptr || obj->town_cn == UINT16_MAX);
274 obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
276 /* Find first unused number belonging to this town. This can never fail,
277 * as long as there can be at most 65535 waypoints/depots in total.
279 * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at
280 * most 'n * (1 + ceil(m / 32))' steps (n - number of waypoints in pool,
281 * m - number of waypoints near this town).
282 * Usually, it needs only 'n' steps.
284 * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
285 * but this way it is faster */
287 uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
288 uint32 next = 0; // first number in the bitmap
289 uint32 idx = 0; // index where we will stop
290 uint32 cid = 0; // current index, goes to T::GetPoolSize()-1, then wraps to 0
292 do {
293 T *lobj = T::GetIfValid(cid);
295 /* check only valid waypoints... */
296 if (lobj != nullptr && obj != lobj) {
297 /* only objects within the same city and with the same type */
298 if (lobj->town == obj->town && lobj->IsOfType(obj)) {
299 /* if lobj->town_cn < next, uint will overflow to '+inf' */
300 uint i = (uint)lobj->town_cn - next;
302 if (i < 32) {
303 SetBit(used, i); // update bitmap
304 if (i == 0) {
305 /* shift bitmap while the lowest bit is '1';
306 * increase the base of the bitmap too */
307 do {
308 used >>= 1;
309 next++;
310 } while (HasBit(used, 0));
311 /* when we are at 'idx' again at end of the loop and
312 * 'next' hasn't changed, then no object had town_cn == next,
313 * so we can safely use it */
314 idx = cid;
320 cid++;
321 if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
322 } while (cid != idx);
324 obj->town_cn = (uint16)next; // set index...
328 * Converts original town ticks counters to plain game ticks. Note that
329 * tick 0 is a valid tick so actual amount is one more than the counter value.
331 static inline Ticks TownTicksToGameTicks(Ticks ticks) {
332 return (ticks + 1) * TOWN_GROWTH_TICKS - 1;
336 extern uint32 _town_cargoes_accepted;
338 #endif /* TOWN_H */