Rework the way the ReinitSeparation command is called. The old way was way too danger...
[openttd-joker.git] / src / town_cmd.cpp
blobcfdc063c8a2086b5fca7774397e19a8a15eb9c93
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_cmd.cpp Handling of town tiles. */
12 #include "stdafx.h"
13 #include "road_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
50 #include "table/strings.h"
51 #include "table/town_land.h"
53 #include "safeguards.h"
55 TownID _new_town_id;
56 uint32 _town_cargoes_accepted; ///< Bitmap of all cargoes accepted by houses.
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
60 INSTANTIATE_POOL_METHODS(Town)
62 Town::~Town()
64 free(this->name);
65 free(this->text);
67 if (CleaningPool()) return;
69 /* Delete town authority window
70 * and remove from list of sorted towns */
71 DeleteWindowById(WC_TOWN_VIEW, this->index);
73 /* Check no industry is related to us. */
74 const Industry *i;
75 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
77 /* ... and no object is related to us. */
78 const Object *o;
79 FOR_ALL_OBJECTS(o) assert(o->town != this);
81 /* Check no tile is related to us. */
82 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83 switch (GetTileType(tile)) {
84 case MP_HOUSE:
85 assert(GetTownIndex(tile) != this->index);
86 break;
88 case MP_ROAD:
89 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90 break;
92 case MP_TUNNELBRIDGE:
93 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94 break;
96 default:
97 break;
101 /* Clear the persistent storage list. */
102 this->psa_list.clear();
104 DeleteSubsidyWith(ST_TOWN, this->index);
105 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
106 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
107 MarkWholeScreenDirty();
112 * Invalidating of the "nearest town cache" has to be done
113 * after removing item from the pool.
114 * @param index index of deleted item
116 void Town::PostDestructor(size_t index)
118 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
119 UpdateNearestTownForRoadTiles(false);
121 /* Give objects a new home! */
122 Object *o;
123 FOR_ALL_OBJECTS(o) {
124 if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
129 * Assigns town layout. If Random, generates one based on TileHash.
131 void Town::InitializeLayout(TownLayout layout)
133 if (layout != TL_RANDOM) {
134 this->layout = layout;
135 return;
138 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
142 * Return a random valid town.
143 * @return random town, nullptr if there are no towns
145 /* static */ Town *Town::GetRandom()
147 if (Town::GetNumItems() == 0) return nullptr;
148 int num = RandomRange((uint16)Town::GetNumItems());
149 size_t index = MAX_UVALUE(size_t);
151 while (num >= 0) {
152 num--;
153 index++;
155 /* Make sure we have a valid town */
156 while (!Town::IsValidID(index)) {
157 index++;
158 assert(index < Town::GetPoolSize());
162 return Town::Get(index);
166 * Updates the town label of the town after changes in rating. The colour scheme is:
167 * Red: Appalling and Very poor ratings.
168 * Orange: Poor and mediocre ratings.
169 * Yellow: Good rating.
170 * White: Very good rating (standard).
171 * Green: Excellent and outstanding ratings.
173 void Town::UpdateLabel()
175 if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
176 int r = this->ratings[_local_company];
177 (this->town_label = 0, r <= RATING_VERYPOOR) || // Appalling and Very Poor
178 (this->town_label++, r <= RATING_MEDIOCRE) || // Poor and Mediocre
179 (this->town_label++, r <= RATING_GOOD) || // Good
180 (this->town_label++, r <= RATING_VERYGOOD) || // Very Good
181 (this->town_label++, true); // Excellent and Outstanding
186 * Get the cost for removing this house
187 * @return the cost (inflation corrected etc)
189 Money HouseSpec::GetRemovalCost() const
191 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
194 /* Local */
195 static int _grow_town_result;
197 /* Describe the possible states */
198 enum TownGrowthResult {
199 GROWTH_SUCCEED = -1,
200 GROWTH_SEARCH_STOPPED = 0
201 // GROWTH_SEARCH_RUNNING >= 1
204 static bool BuildTownHouse(Town *t, TileIndex tile);
205 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
207 static void TownDrawHouseLift(const TileInfo *ti)
209 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
212 typedef void TownDrawTileProc(const TileInfo *ti);
213 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
214 TownDrawHouseLift
218 * Return a random direction
220 * @return a random direction
222 static inline DiagDirection RandomDiagDir()
224 return (DiagDirection)(3 & Random());
228 * House Tile drawing handler.
229 * Part of the tile loop process
230 * @param ti TileInfo of the tile to draw
232 static void DrawTile_Town(TileInfo *ti)
234 HouseID house_id = GetHouseType(ti->tile);
236 if (house_id >= NEW_HOUSE_OFFSET) {
237 /* Houses don't necessarily need new graphics. If they don't have a
238 * spritegroup associated with them, then the sprite for the substitute
239 * house id is drawn instead. */
240 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
241 DrawNewHouseTile(ti, house_id);
242 return;
243 } else {
244 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
248 /* Retrieve pointer to the draw town tile struct */
249 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
251 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
253 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
255 DrawOverlay(ti, MP_HOUSE);
257 /* If houses are invisible, do not draw the upper part */
258 if (IsInvisibilitySet(TO_HOUSES)) return;
260 /* Add a house on top of the ground? */
261 SpriteID image = dcts->building.sprite;
262 if (image != 0) {
263 AddSortableSpriteToDraw(image, dcts->building.pal,
264 ti->x + dcts->subtile_x,
265 ti->y + dcts->subtile_y,
266 dcts->width,
267 dcts->height,
268 dcts->dz,
269 ti->z,
270 IsTransparencySet(TO_HOUSES)
273 if (IsTransparencySet(TO_HOUSES)) return;
277 int proc = dcts->draw_proc - 1;
279 if (proc >= 0) _town_draw_tile_procs[proc](ti);
283 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
285 return GetTileMaxPixelZ(tile);
288 /** Tile callback routine */
289 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
291 HouseID hid = GetHouseType(tile);
293 /* For NewGRF house tiles we might not be drawing a foundation. We need to
294 * account for this, as other structures should
295 * draw the wall of the foundation in this case.
297 if (hid >= NEW_HOUSE_OFFSET) {
298 const HouseSpec *hs = HouseSpec::Get(hid);
299 if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
300 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
301 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
304 return FlatteningFoundation(tileh);
308 * Animate a tile for a town
309 * Only certain houses can be animated
310 * The newhouses animation supersedes regular ones
311 * @param tile TileIndex of the house to animate
313 static void AnimateTile_Town(TileIndex tile)
315 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
316 AnimateNewHouseTile(tile);
317 return;
320 if (_tick_counter & 3) return;
322 /* If the house is not one with a lift anymore, then stop this animating.
323 * Not exactly sure when this happens, but probably when a house changes.
324 * Before this was just a return...so it'd leak animated tiles..
325 * That bug seems to have been here since day 1?? */
326 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
327 DeleteAnimatedTile(tile);
328 return;
331 if (!LiftHasDestination(tile)) {
332 uint i;
334 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
335 * This is due to the fact that the first floor is, in the graphics,
336 * the height of 2 'normal' floors.
337 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
338 do {
339 i = RandomRange(7);
340 } while (i == 1 || i * 6 == GetLiftPosition(tile));
342 SetLiftDestination(tile, i);
345 int pos = GetLiftPosition(tile);
346 int dest = GetLiftDestination(tile) * 6;
347 pos += (pos < dest) ? 1 : -1;
348 SetLiftPosition(tile, pos);
350 if (pos == dest) {
351 HaltLift(tile);
352 DeleteAnimatedTile(tile);
355 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
359 * Determines if a town is close to a tile
360 * @param tile TileIndex of the tile to query
361 * @param dist maximum distance to be accepted
362 * @returns true if the tile correspond to the distance criteria
364 static bool IsCloseToTown(TileIndex tile, uint dist)
366 /* On a large map with many towns, it may be faster to check the surroundings of the tile.
367 * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
368 if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
369 const int tx = TileX(tile);
370 const int ty = TileY(tile);
371 TileArea tile_area = TileArea(
372 TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
373 TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
375 TILE_AREA_LOOP(atile, tile_area) {
376 if (GetTileType(atile) == MP_HOUSE) {
377 Town *t = Town::GetByTile(atile);
378 if (DistanceManhattan(tile, t->xy) < dist) return true;
381 return false;
384 const Town *t;
386 FOR_ALL_TOWNS(t) {
387 if (DistanceManhattan(tile, t->xy) < dist) return true;
389 return false;
393 * Resize the sign(label) of the town after changes in
394 * population (creation or growth or else)
396 void Town::UpdateVirtCoord()
398 this->UpdateLabel();
399 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
400 SetDParam(0, this->index);
401 SetDParam(1, this->cache.population);
402 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE, this->Label());
404 SetWindowDirty(WC_TOWN_VIEW, this->index);
407 /** Update the virtual coords needed to draw the town sign for all towns. */
408 void UpdateAllTownVirtCoords()
410 Town *t;
412 FOR_ALL_TOWNS(t) {
413 t->UpdateVirtCoord();
418 * Change the towns population
419 * @param t Town which population has changed
420 * @param mod population change (can be positive or negative)
422 static void ChangePopulation(Town *t, int mod)
424 t->cache.population += mod;
425 InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
426 t->UpdateVirtCoord();
428 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
432 * Determines the world population
433 * Basically, count population of all towns, one by one
434 * @return uint32 the calculated population of the world
436 uint32 GetWorldPopulation()
438 uint32 pop = 0;
439 const Town *t;
441 FOR_ALL_TOWNS(t) pop += t->cache.population;
442 return pop;
446 * Helper function for house completion stages progression
447 * @param tile TileIndex of the house (or parts of it) to "grow"
449 static void MakeSingleHouseBigger(TileIndex tile)
451 assert(IsTileType(tile, MP_HOUSE));
453 /* progress in construction stages */
454 IncHouseConstructionTick(tile);
455 if (GetHouseConstructionTick(tile) != 0) return;
457 AnimateNewHouseConstruction(tile);
459 if (IsHouseCompleted(tile)) {
460 /* Now that construction is complete, we can add the population of the
461 * building to the town. */
462 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
463 ResetHouseAge(tile);
465 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
469 * Make the house advance in its construction stages until completion
470 * @param tile TileIndex of house
472 static void MakeTownHouseBigger(TileIndex tile)
474 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
475 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
476 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
477 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
478 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
482 * Generate cargo for a town (house).
484 * The amount of cargo should be and will be greater than zero.
486 * @param t current town
487 * @param ct type of cargo to generate, usually CT_PASSENGERS or CT_MAIL
488 * @param amount how many units of cargo
489 * @param stations available stations for this house
490 * @param economy_adjust true if amount should be reduced during recession
492 static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool economy_adjust)
494 // custom cargo generation factor
495 int cf = _settings_game.economy.town_cargo_factor;
497 // when the economy flunctuates, everyone wants to stay at home
498 if (economy_adjust && EconomyIsInRecession()) {
499 amount = (amount + 1) >> 1;
502 // apply custom factor?
503 if (cf < 0) {
504 // approx (amount / 2^cf)
505 // adjust with a constant offset of {(2 ^ cf) - 1} (i.e. add cf * 1-bits) before dividing to ensure that it doesn't become zero
506 // this skews the curve a little so that isn't entirely exponential, but will still decrease
507 amount = (amount + ((1 << -cf) - 1)) >> -cf;
510 else if (cf > 0) {
511 // approx (amount * 2^cf)
512 // XXX: overflow?
513 amount = amount << cf;
516 // with the adjustments above, this should never happen
517 assert(amount > 0);
519 // calculate for town stats
520 switch (ct) {
521 case CT_PASSENGERS:
522 case CT_MAIL:
523 t->supplied[ct].new_max += amount;
524 t->supplied[ct].new_act += MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
525 break;
527 default: {
528 const CargoSpec *cs = CargoSpec::Get(ct);
529 t->supplied[cs->Index()].new_max += amount;
530 t->supplied[cs->Index()].new_act += MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
531 break;
537 * Tile callback function.
539 * Periodic tic handler for houses and town
540 * @param tile been asked to do its stuff
542 static void TileLoop_Town(TileIndex tile)
544 HouseID house_id = GetHouseType(tile);
546 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
547 * doesn't exist any more, so don't continue here. */
548 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
550 if (!IsHouseCompleted(tile)) {
551 /* Construction is not completed. See if we can go further in construction*/
552 MakeTownHouseBigger(tile);
553 return;
556 const HouseSpec *hs = HouseSpec::Get(house_id);
558 /* If the lift has a destination, it is already an animated tile. */
559 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
560 house_id < NEW_HOUSE_OFFSET &&
561 !LiftHasDestination(tile) &&
562 Chance16(1, 2)) {
563 AddAnimatedTile(tile);
566 Town *t = Town::GetByTile(tile);
567 uint32 r = Random();
569 StationFinder stations(TileArea(tile, 1, 1));
571 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
572 for (uint i = 0; i < 256; i++) {
573 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
575 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
577 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
578 if (cargo == CT_INVALID) continue;
580 uint amt = GB(callback, 0, 8);
581 if (amt == 0) continue;
583 // XXX: no economy flunctuation for GRF cargos?
584 TownGenerateCargo(t, cargo, amt, stations, false);
586 } else {
587 if (GB(r, 0, 8) < hs->population) {
588 uint amt = GB(r, 16, 3) + 1;
590 TownGenerateCargo(t, CT_PASSENGERS, amt, stations, true);
593 if (GB(r, 8, 8) < hs->mail_generation) {
594 uint amt = GB(r, 24, 3) + 1;
596 TownGenerateCargo(t, CT_MAIL, amt, stations, true);
600 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
602 const int32 ticks_per_tile_loop = 256;
604 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
605 t->IsGrowing() &&
606 CanDeleteHouse(tile) &&
607 GetHouseAge(tile) >= hs->minimum_life &&
608 t->time_until_rebuild <= (_date - (hs->minimum_life * DAYS_IN_YEAR))) {
610 int32 tile_loops_until_rebuild = GB(r, 16, 8) + 192;
611 t->time_until_rebuild = _date + ((tile_loops_until_rebuild * ticks_per_tile_loop) / DEFAULT_DAY_TICKS);
613 ClearTownHouse(t, tile);
615 /* Rebuild with another house? */
616 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
619 cur_company.Restore();
622 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
624 if (flags & DC_AUTO) return CommandError(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
625 if (!CanDeleteHouse(tile)) return CommandError();
627 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
629 CommandCost cost(EXPENSES_CONSTRUCTION);
630 cost.AddCost(hs->GetRemovalCost());
632 int rating = hs->remove_rating_decrease;
633 Town *t = Town::GetByTile(tile);
635 if (Company::IsValidID(_current_company)) {
636 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
637 SetDParam(0, t->index);
638 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
642 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
643 if (flags & DC_EXEC) {
644 ClearTownHouse(t, tile);
647 return cost;
650 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
652 HouseID house_id = GetHouseType(tile);
653 const HouseSpec *hs = HouseSpec::Get(house_id);
654 Town *t = Town::GetByTile(tile);
656 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
657 for (uint i = 0; i < 256; i++) {
658 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
660 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
662 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
664 if (cargo == CT_INVALID) continue;
665 produced[cargo]++;
667 } else {
668 if (hs->population > 0) {
669 produced[CT_PASSENGERS]++;
671 if (hs->mail_generation > 0) {
672 produced[CT_MAIL]++;
677 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
679 if (cargo == CT_INVALID || amount == 0) return;
680 acceptance[cargo] += amount;
681 SetBit(*always_accepted, cargo);
684 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
686 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
687 CargoID accepts[3];
689 /* Set the initial accepted cargo types */
690 for (uint8 i = 0; i < lengthof(accepts); i++) {
691 accepts[i] = hs->accepts_cargo[i];
694 /* Check for custom accepted cargo types */
695 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
696 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
697 if (callback != CALLBACK_FAILED) {
698 /* Replace accepted cargo types with translated values from callback */
699 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
700 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
701 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
705 /* Check for custom cargo acceptance */
706 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
707 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
708 if (callback != CALLBACK_FAILED) {
709 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
710 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
711 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
712 /* The 'S' bit indicates food instead of goods */
713 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
714 } else {
715 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
717 return;
721 /* No custom acceptance, so fill in with the default values */
722 for (uint8 i = 0; i < lengthof(accepts); i++) {
723 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
727 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
729 const HouseID house = GetHouseType(tile);
730 const HouseSpec *hs = HouseSpec::Get(house);
731 bool house_completed = IsHouseCompleted(tile);
733 td->str = hs->building_name;
735 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
736 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
737 if (callback_res > 0x400) {
738 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
739 } else {
740 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
741 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
742 td->str = new_name;
747 if (!house_completed) {
748 SetDParamX(td->dparam, 0, td->str);
749 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
752 if (hs->grf_prop.grffile != nullptr) {
753 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
754 td->grf = gc->GetName();
757 td->owner[0] = OWNER_TOWN;
760 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
762 /* not used */
763 return 0;
766 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
768 /* not used */
771 /** Update the total cargo acceptance of the whole town.
772 * @param t The town to update.
774 void UpdateTownCargoTotal(Town *t)
776 t->cargo_accepted_total = 0;
778 const TileArea &area = t->cargo_accepted.GetArea();
779 TILE_AREA_LOOP(tile, area) {
780 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
781 t->cargo_accepted_total |= t->cargo_accepted[tile];
787 * Update accepted town cargoes around a specific tile.
788 * @param t The town to update.
789 * @param start Update the values around this tile.
790 * @param update_total Set to true if the total cargo acceptance should be updated.
792 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
794 CargoArray accepted, produced;
795 uint32 dummy;
797 /* Gather acceptance for all houses in an area around the start tile.
798 * The area is composed of the square the tile is in, extended one square in all
799 * directions as the coverage area of a single station is bigger than just one square. */
800 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
801 TILE_AREA_LOOP(tile, area) {
802 if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
804 AddAcceptedCargo_Town(tile, accepted, &dummy);
805 AddProducedCargo_Town(tile, produced);
808 /* Create bitmap of produced and accepted cargoes. */
809 uint32 acc = 0;
810 for (uint cid = 0; cid < NUM_CARGO; cid++) {
811 if (accepted[cid] >= 8) SetBit(acc, cid);
812 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
814 t->cargo_accepted[start] = acc;
816 if (update_total) UpdateTownCargoTotal(t);
819 /** Update cargo acceptance for the complete town.
820 * @param t The town to update.
822 void UpdateTownCargoes(Town *t)
824 t->cargo_produced = 0;
826 const TileArea &area = t->cargo_accepted.GetArea();
827 if (area.tile == INVALID_TILE) return;
829 /* Update acceptance for each grid square. */
830 TILE_AREA_LOOP(tile, area) {
831 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
832 UpdateTownCargoes(t, tile, false);
836 /* Update the total acceptance. */
837 UpdateTownCargoTotal(t);
840 /** Updates the bitmap of all cargoes accepted by houses. */
841 void UpdateTownCargoBitmap()
843 Town *town;
844 _town_cargoes_accepted = 0;
846 FOR_ALL_TOWNS(town) {
847 _town_cargoes_accepted |= town->cargo_accepted_total;
851 static bool GrowTown(Town *t);
853 static void TownTickHandler(Town *t)
855 if (t->IsGrowing()) {
856 auto i = t->grow_counter - 1;
858 if (i < 0) {
859 if (GrowTown(t)) {
860 i = t->growth_rate;
861 } else {
862 /* If growth failed wait a bit before retrying */
863 i = min(t->growth_rate, TOWN_GROWTH_TICKS - 1);
867 t->grow_counter = i;
871 void OnTick_Town()
873 if (_game_mode == GM_EDITOR) return;
875 Town *t;
876 FOR_ALL_TOWNS(t) {
877 TownTickHandler(t);
882 * Return the RoadBits of a tile
884 * @note There are many other functions doing things like that.
885 * @note Needs to be checked for needlessness.
886 * @param tile The tile we want to analyse
887 * @return The roadbits of the given tile
889 static RoadBits GetTownRoadBits(TileIndex tile)
891 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
893 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
897 * Check for parallel road inside a given distance.
898 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
899 * is there a parallel road left or right of it within distance dist_multi?
901 * @param tile current tile
902 * @param dir target direction
903 * @param dist_multi distance multiplayer
904 * @return true if there is a parallel road
906 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
908 if (!IsValidTile(tile)) return false;
910 /* Lookup table for the used diff values */
911 const TileIndexDiff tid_lt[3] = {
912 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
913 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
914 TileOffsByDiagDir(ReverseDiagDir(dir)),
917 dist_multi = (dist_multi + 1) * 4;
918 for (uint pos = 4; pos < dist_multi; pos++) {
919 /* Go (pos / 4) tiles to the left or the right */
920 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
922 /* Use the current tile as origin, or go one tile backwards */
923 if (pos & 2) cur += tid_lt[2];
925 /* Test for roadbit parallel to dir and facing towards the middle axis */
926 if (IsValidTile(tile + cur) &&
927 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
929 return false;
933 * Check if a Road is allowed on a given tile
935 * @param t The current town
936 * @param tile The target tile
937 * @param dir The direction in which we want to extend the town
938 * @return true if it is allowed else false
940 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
942 if (DistanceFromEdge(tile) == 0) return false;
944 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
945 if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
947 /* Check if there already is a road at this point? */
948 if (GetTownRoadBits(tile) == ROAD_NONE) {
949 /* No, try if we are able to build a road piece there.
950 * If that fails clear the land, and if that fails exit.
951 * This is to make sure that we can build a road here later. */
952 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
953 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
954 return false;
958 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
959 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
960 if (cur_slope == SLOPE_FLAT) return ret;
962 /* If the tile is not a slope in the right direction, then
963 * maybe terraform some. */
964 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
965 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
966 if (Chance16(1, 8)) {
967 CommandCost res = CommandError();
968 if (!_generating_world && Chance16(1, 10)) {
969 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
970 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
971 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
973 if (res.Failed() && Chance16(1, 3)) {
974 /* We can consider building on the slope, though. */
975 return ret;
978 return false;
980 return ret;
983 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
985 assert(tile < MapSize());
987 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
988 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
989 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
990 return true;
993 static void LevelTownLand(TileIndex tile)
995 assert(tile < MapSize());
997 /* Don't terraform if land is plain or if there's a house there. */
998 if (IsTileType(tile, MP_HOUSE)) return;
999 Slope tileh = GetTileSlope(tile);
1000 if (tileh == SLOPE_FLAT) return;
1002 /* First try up, then down */
1003 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
1004 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
1009 * Generate the RoadBits of a grid tile
1011 * @param t current town
1012 * @param tile tile in reference to the town
1013 * @param dir The direction to which we are growing ATM
1014 * @return the RoadBit of the current tile regarding
1015 * the selected town layout
1017 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
1019 /* align the grid to the downtown */
1020 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1021 RoadBits rcmd = ROAD_NONE;
1023 switch (t->layout) {
1024 default: NOT_REACHED();
1026 case TL_2X2_GRID:
1027 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1028 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1029 break;
1031 case TL_3X3_GRID:
1032 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1033 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1034 break;
1037 /* Optimise only X-junctions */
1038 if (rcmd != ROAD_ALL) return rcmd;
1040 RoadBits rb_template;
1042 switch (GetTileSlope(tile)) {
1043 default: rb_template = ROAD_ALL; break;
1044 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1045 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1046 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1047 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1048 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1049 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1050 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1051 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1052 case SLOPE_STEEP_W:
1053 case SLOPE_STEEP_S:
1054 case SLOPE_STEEP_E:
1055 case SLOPE_STEEP_N:
1056 rb_template = ROAD_NONE;
1057 break;
1060 /* Stop if the template is compatible to the growth dir */
1061 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1062 /* If not generate a straight road in the direction of the growth */
1063 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
1067 * Grows the town with an extra house.
1068 * Check if there are enough neighbor house tiles
1069 * next to the current tile. If there are enough
1070 * add another house.
1072 * @param t The current town
1073 * @param tile The target tile for the extra house
1074 * @return true if an extra house has been added
1076 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
1078 /* We can't look further than that. */
1079 if (DistanceFromEdge(tile) == 0) return false;
1081 uint counter = 0; // counts the house neighbor tiles
1083 /* Check the tiles E,N,W and S of the current tile for houses */
1084 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1085 /* Count both void and house tiles for checking whether there
1086 * are enough houses in the area. This to make it likely that
1087 * houses get build up to the edge of the map. */
1088 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1089 case MP_HOUSE:
1090 case MP_VOID:
1091 counter++;
1092 break;
1094 default:
1095 break;
1098 /* If there are enough neighbors stop here */
1099 if (counter >= 3) {
1100 if (BuildTownHouse(t, tile)) {
1101 _grow_town_result = GROWTH_SUCCEED;
1102 return true;
1104 return false;
1107 return false;
1111 * Grows the town with a road piece.
1113 * @param t The current town
1114 * @param tile The current tile
1115 * @param rcmd The RoadBits we want to build on the tile
1116 * @return true if the RoadBits have been added else false
1118 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1120 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1121 _grow_town_result = GROWTH_SUCCEED;
1122 return true;
1124 return false;
1128 * Grows the town with a bridge.
1129 * At first we check if a bridge is reasonable.
1130 * If so we check if we are able to build it.
1132 * @param t The current town
1133 * @param tile The current tile
1134 * @param bridge_dir The valid direction in which to grow a bridge
1135 * @return true if a bridge has been build else false
1137 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1139 assert(bridge_dir < DIAGDIR_END);
1141 const Slope slope = GetTileSlope(tile);
1143 /* Make sure the direction is compatible with the slope.
1144 * Well we check if the slope has an up bit set in the
1145 * reverse direction. */
1146 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1148 /* Assure that the bridge is connectable to the start side */
1149 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1151 /* We are in the right direction */
1152 uint8 bridge_length = 0; // This value stores the length of the possible bridge
1153 TileIndex bridge_tile = tile; // Used to store the other waterside
1155 const int delta = TileOffsByDiagDir(bridge_dir);
1157 if (slope == SLOPE_FLAT) {
1158 /* Bridges starting on flat tiles are only allowed when crossing rivers or rails. */
1159 do {
1160 if (bridge_length++ >= 5) {
1161 /* Allow to cross rivers, not big lakes, nor large amounts of rails. */
1162 return false;
1164 bridge_tile += delta;
1165 } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile)));
1166 } else {
1167 do {
1168 if (bridge_length++ >= 11) {
1169 /* Max 11 tile long bridges */
1170 return false;
1172 bridge_tile += delta;
1173 } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile)));
1176 /* no water tiles in between? */
1177 if (bridge_length == 1) return false;
1179 for (uint8 times = 0; times <= 22; times++) {
1180 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1182 /* Can we actually build the bridge? */
1183 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1184 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1185 _grow_town_result = GROWTH_SUCCEED;
1186 return true;
1189 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1190 return false;
1194 * Grows the given town.
1195 * There are at the moment 3 possible way's for
1196 * the town expansion:
1197 * @li Generate a random tile and check if there is a road allowed
1198 * @li TL_ORIGINAL
1199 * @li TL_BETTER_ROADS
1200 * @li Check if the town geometry allows a road and which one
1201 * @li TL_2X2_GRID
1202 * @li TL_3X3_GRID
1203 * @li Forbid roads, only build houses
1205 * @param tile_ptr The current tile
1206 * @param cur_rb The current tiles RoadBits
1207 * @param target_dir The target road dir
1208 * @param t1 The current town
1210 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1212 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1213 TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1215 assert(tile < MapSize());
1217 if (cur_rb == ROAD_NONE) {
1218 /* Tile has no road. First reset the status counter
1219 * to say that this is the last iteration. */
1220 _grow_town_result = GROWTH_SEARCH_STOPPED;
1222 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1223 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
1225 /* Remove hills etc */
1226 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1228 /* Is a road allowed here? */
1229 switch (t1->layout) {
1230 default: NOT_REACHED();
1232 case TL_3X3_GRID:
1233 case TL_2X2_GRID:
1234 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1235 if (rcmd == ROAD_NONE) return;
1236 break;
1238 case TL_BETTER_ROADS:
1239 case TL_ORIGINAL:
1240 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1242 DiagDirection source_dir = ReverseDiagDir(target_dir);
1244 if (Chance16(1, 4)) {
1245 /* Randomize a new target dir */
1246 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1249 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1250 /* A road is not allowed to continue the randomized road,
1251 * return if the road we're trying to build is curved. */
1252 if (target_dir != ReverseDiagDir(source_dir)) return;
1254 /* Return if neither side of the new road is a house */
1255 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
1256 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
1257 return;
1260 /* That means that the road is only allowed if there is a house
1261 * at any side of the new road. */
1264 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1265 break;
1268 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1269 /* Continue building on a partial road.
1270 * Should be always OK, so we only generate
1271 * the fitting RoadBits */
1272 _grow_town_result = GROWTH_SEARCH_STOPPED;
1274 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1276 switch (t1->layout) {
1277 default: NOT_REACHED();
1279 case TL_3X3_GRID:
1280 case TL_2X2_GRID:
1281 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1282 break;
1284 case TL_BETTER_ROADS:
1285 case TL_ORIGINAL:
1286 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1287 break;
1289 } else {
1290 bool allow_house = true; // Value which decides if we want to construct a house
1292 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1293 * it is the starting tile. Half the time, we stay on this side then.*/
1294 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1295 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1296 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1298 return;
1301 /* Possibly extend the road in a direction.
1302 * Randomize a direction and if it has a road, bail out. */
1303 target_dir = RandomDiagDir();
1304 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
1306 /* This is the tile we will reach if we extend to this direction. */
1307 TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1309 /* Don't walk into water. */
1310 if (HasTileWaterGround(house_tile)) return;
1312 if (!IsValidTile(house_tile)) return;
1314 if (_settings_game.economy.allow_town_roads || _generating_world) {
1315 switch (t1->layout) {
1316 default: NOT_REACHED();
1318 case TL_3X3_GRID: // Use 2x2 grid afterwards!
1319 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1320 FALLTHROUGH;
1322 case TL_2X2_GRID:
1323 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1324 allow_house = (rcmd & DiagDirToRoadBits(target_dir)) == ROAD_NONE;
1325 break;
1327 case TL_BETTER_ROADS: // Use original afterwards!
1328 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1329 FALLTHROUGH;
1331 case TL_ORIGINAL:
1332 /* Allow a house at the edge. 60% chance or
1333 * always ok if no road allowed. */
1334 rcmd = DiagDirToRoadBits(target_dir);
1335 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1336 break;
1340 if (allow_house) {
1341 /* Build a house, but not if there already is a house there. */
1342 if (!IsTileType(house_tile, MP_HOUSE)) {
1343 /* Level the land if possible */
1344 if (Chance16(1, 6)) LevelTownLand(house_tile);
1346 /* And build a house.
1347 * Set result to -1 if we managed to build it. */
1348 if (BuildTownHouse(t1, house_tile)) {
1349 _grow_town_result = GROWTH_SUCCEED;
1352 return;
1355 _grow_town_result = GROWTH_SEARCH_STOPPED;
1358 /* Return if a water tile */
1359 if (HasTileWaterGround(tile)) return;
1361 /* Make the roads look nicer */
1362 rcmd = CleanUpRoadBits(tile, rcmd);
1363 if (rcmd == ROAD_NONE) return;
1365 /* Only use the target direction for bridges to ensure they're connected.
1366 * The target_dir is as computed previously according to town layout, so
1367 * it will match it perfectly. */
1368 if (GrowTownWithBridge(t1, tile, target_dir)) return;
1370 GrowTownWithRoad(t1, tile, rcmd);
1374 * Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
1375 * This only checks trivial but often cases.
1376 * @param tile Start tile for road.
1377 * @param dir Direction for road to follow or build.
1378 * @return true If road is or can be connected in the specified direction.
1380 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1382 TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1383 if (!IsValidTile(target_tile)) return false;
1384 if (HasTileWaterGround(target_tile)) return false;
1386 RoadBits target_rb = GetTownRoadBits(target_tile);
1387 if (_settings_game.economy.allow_town_roads || _generating_world) {
1388 /* Check whether a road connection exists or can be build. */
1389 switch (GetTileType(target_tile)) {
1390 case MP_ROAD:
1391 return target_rb != ROAD_NONE;
1393 case MP_STATION:
1394 return IsDriveThroughStopTile(target_tile);
1396 case MP_TUNNELBRIDGE:
1397 return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1399 case MP_HOUSE:
1400 case MP_INDUSTRY:
1401 case MP_OBJECT:
1402 return false;
1404 default:
1405 /* Checked for void and water earlier */
1406 return true;
1408 } else {
1409 /* Check whether a road connection already exists,
1410 * and it leads somewhere else. */
1411 RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1412 return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1417 * Returns "growth" if a house was built, or no if the build failed.
1418 * @param t town to inquiry
1419 * @param tile to inquiry
1420 * @return true if town expansion was possible
1422 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1424 /* Special case.
1425 * @see GrowTownInTile Check the else if
1427 DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1429 assert(tile < MapSize());
1431 /* Number of times to search.
1432 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1433 * them a little handicap. */
1434 switch (t->layout) {
1435 case TL_BETTER_ROADS:
1436 _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1437 break;
1439 case TL_3X3_GRID:
1440 case TL_2X2_GRID:
1441 _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1442 break;
1444 default:
1445 _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1446 break;
1449 do {
1450 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1452 /* Try to grow the town from this point */
1453 GrowTownInTile(&tile, cur_rb, target_dir, t);
1454 if (_grow_town_result == GROWTH_SUCCEED) return true;
1456 /* Exclude the source position from the bitmask
1457 * and return if no more road blocks available */
1458 if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1459 if (cur_rb == ROAD_NONE) return false;
1461 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1462 /* Only build in the direction away from the tunnel or bridge. */
1463 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1464 } else {
1465 /* Select a random bit from the blockmask, walk a step
1466 * and continue the search from there. */
1467 do {
1468 if (cur_rb == ROAD_NONE) return false;
1469 RoadBits target_bits;
1470 do {
1471 target_dir = RandomDiagDir();
1472 target_bits = DiagDirToRoadBits(target_dir);
1473 } while (!(cur_rb & target_bits));
1474 cur_rb &= ~target_bits;
1475 } while (!CanFollowRoad(tile, target_dir));
1477 tile = TileAddByDiagDir(tile, target_dir);
1479 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1480 /* Don't allow building over roads of other cities */
1481 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1482 return false;
1483 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1484 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1485 * owner :) (happy happy happy road now) */
1486 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
1487 SetTownIndex(tile, t->index);
1491 /* Max number of times is checked. */
1492 } while (--_grow_town_result >= 0);
1494 return false;
1498 * Generate a random road block.
1499 * The probability of a straight road
1500 * is somewhat higher than a curved.
1502 * @return A RoadBits value with 2 bits set
1504 static RoadBits GenRandomRoadBits()
1506 uint32 r = Random();
1507 uint a = GB(r, 0, 2);
1508 uint b = GB(r, 8, 2);
1509 if (a == b) b ^= 2;
1510 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1514 * Grow the town
1515 * @param t town to grow
1516 * @return true iff something (house, road, bridge, ...) was built
1518 static bool GrowTown(Town *t)
1520 static const TileIndexDiffC _town_coord_mod[] = {
1521 {-1, 0},
1522 { 1, 1},
1523 { 1, -1},
1524 {-1, -1},
1525 {-1, 0},
1526 { 0, 2},
1527 { 2, 0},
1528 { 0, -2},
1529 {-1, -1},
1530 {-2, 2},
1531 { 2, 2},
1532 { 2, -2},
1533 { 0, 0}
1536 /* Current "company" is a town */
1537 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1539 TileIndex tile = t->xy; // The tile we are working with ATM
1541 /* Find a road that we can base the construction on. */
1542 const TileIndexDiffC *ptr;
1543 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1544 if (GetTownRoadBits(tile) != ROAD_NONE) {
1545 bool success = GrowTownAtRoad(t, tile);
1546 cur_company.Restore();
1547 return success;
1549 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1552 /* No road available, try to build a random road block by
1553 * clearing some land and then building a road there. */
1554 if (_settings_game.economy.allow_town_roads || _generating_world) {
1555 tile = t->xy;
1556 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1557 /* Only work with plain land that not already has a house */
1558 if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1559 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1560 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1561 cur_company.Restore();
1562 return true;
1565 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1569 cur_company.Restore();
1570 return false;
1573 void UpdateTownRadius(Town *t)
1575 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1576 { 4, 0, 0, 0, 0}, // 0
1577 { 16, 0, 0, 0, 0},
1578 { 25, 0, 0, 0, 0},
1579 { 36, 0, 0, 0, 0},
1580 { 49, 0, 4, 0, 0},
1581 { 64, 0, 4, 0, 0}, // 20
1582 { 64, 0, 9, 0, 1},
1583 { 64, 0, 9, 0, 4},
1584 { 64, 0, 16, 0, 4},
1585 { 81, 0, 16, 0, 4},
1586 { 81, 0, 16, 0, 4}, // 40
1587 { 81, 0, 25, 0, 9},
1588 { 81, 36, 25, 0, 9},
1589 { 81, 36, 25, 16, 9},
1590 { 81, 49, 0, 25, 9},
1591 { 81, 64, 0, 25, 9}, // 60
1592 { 81, 64, 0, 36, 9},
1593 { 81, 64, 0, 36, 16},
1594 {100, 81, 0, 49, 16},
1595 {100, 81, 0, 49, 25},
1596 {121, 81, 0, 49, 25}, // 80
1597 {121, 81, 0, 49, 25},
1598 {121, 81, 0, 49, 36}, // 88
1601 if (t->cache.num_houses < 92) {
1602 memcpy(t->cache.squared_town_zone_radius, _town_squared_town_zone_radius_data[t->cache.num_houses / 4], sizeof(t->cache.squared_town_zone_radius));
1603 } else {
1604 int mass = t->cache.num_houses / 8;
1605 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1606 * The offsets are to make sure the radii do not decrease in size when going from the table
1607 * to the calculated value.*/
1608 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1609 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1610 t->cache.squared_town_zone_radius[2] = 0;
1611 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1612 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1616 void UpdateTownMaxPass(Town *t)
1618 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1619 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1623 * Does the actual town creation.
1625 * @param t The town
1626 * @param tile Where to put it
1627 * @param townnameparts The town name
1628 * @param size Parameter for size determination
1629 * @param city whether to build a city or town
1630 * @param layout the (road) layout of the town
1631 * @param manual was the town placed manually?
1633 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1635 const int32 tile_loops_until_rebuild = 10;
1636 const int32 ticks_per_tile_loop = 256;
1638 t->xy = tile;
1639 t->cache.num_houses = 0;
1640 t->time_until_rebuild = _date + ((tile_loops_until_rebuild * ticks_per_tile_loop) / DEFAULT_DAY_TICKS);
1641 UpdateTownRadius(t);
1642 t->flags = 0;
1643 t->cache.population = 0;
1644 /* Spread growth across ticks so even if there are many
1645 * similar towns they're unlikely to grow all in one tick */
1646 t->grow_counter = t->index % TOWN_GROWTH_TICKS;
1647 t->growth_rate = TownTicksToGameTicks(250);
1649 /* Set the default cargo requirement for town growth */
1650 switch (_settings_game.game_creation.landscape) {
1651 case LT_ARCTIC:
1652 if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
1653 break;
1655 case LT_TROPIC:
1656 if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
1657 if (FindFirstCargoWithTownEffect(TE_WATER) != nullptr) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
1658 break;
1661 t->fund_buildings_months = 0;
1663 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1665 t->have_ratings = 0;
1666 t->exclusivity = INVALID_COMPANY;
1667 t->exclusive_counter = 0;
1668 t->statues = 0;
1670 extern int _nb_orig_names;
1671 if (_settings_game.game_creation.town_name < _nb_orig_names) {
1672 /* Original town name */
1673 t->townnamegrfid = 0;
1674 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1675 } else {
1676 /* Newgrf town name */
1677 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1678 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1680 t->townnameparts = townnameparts;
1682 t->UpdateVirtCoord();
1683 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
1685 t->InitializeLayout(layout);
1687 t->larger_town = city;
1689 int x = (int)size * 16 + 3;
1690 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1691 /* Don't create huge cities when founding town in-game */
1692 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1694 t->cache.num_houses += x;
1695 UpdateTownRadius(t);
1697 int i = x * 4;
1698 do {
1699 GrowTown(t);
1700 } while (--i);
1702 t->cache.num_houses -= x;
1703 UpdateTownRadius(t);
1704 UpdateTownMaxPass(t);
1705 UpdateAirportsNoise();
1709 * Checks if it's possible to place a town at given tile
1710 * @param tile tile to check
1711 * @return error value or zero cost
1713 static CommandCost TownCanBePlacedHere(TileIndex tile)
1715 /* Check if too close to the edge of map */
1716 if (DistanceFromEdge(tile) < 12) {
1717 return CommandError(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1720 /* Check distance to all other towns. */
1721 if (IsCloseToTown(tile, _settings_game.economy.town_min_distance)) {
1722 return CommandError(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1725 /* Check max height level. */
1726 if (GetTileZ(tile) > _settings_game.economy.max_town_heightlevel) {
1727 return CommandError(STR_ERROR_SITE_UNSUITABLE);
1730 /* Cannot build above the tree line. */
1731 if (_settings_game.construction.trees_around_snow_line_enabled && (GetTileZ(tile) >= HighestSnowLine() + (_settings_game.construction.trees_around_snow_line_range / 2))) {
1732 return CommandError(STR_ERROR_SITE_UNSUITABLE);
1735 /* Can only build on clear flat areas, possibly with trees. */
1736 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1737 return CommandError(STR_ERROR_SITE_UNSUITABLE);
1740 return CommandCost(EXPENSES_OTHER);
1744 * Verifies this custom name is unique. Only custom names are checked.
1745 * @param name name to check
1746 * @return is this name unique?
1748 static bool IsUniqueTownName(const char *name)
1750 const Town *t;
1752 FOR_ALL_TOWNS(t) {
1753 if (t->name != nullptr && strcmp(t->name, name) == 0) return false;
1756 return true;
1760 * Create a new town.
1761 * @param tile coordinates where town is built
1762 * @param flags type of operation
1763 * @param p1 0..1 size of the town (@see TownSize)
1764 * 2 true iff it should be a city
1765 * 3..5 town road layout (@see TownLayout)
1766 * 6 use random location (randomize \c tile )
1767 * @param p2 town name parts
1768 * @param text Custom name for the town. If empty, the town name parts will be used.
1769 * @return the cost of this operation or an error
1771 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1773 TownSize size = Extract<TownSize, 0, 2>(p1);
1774 bool city = HasBit(p1, 2);
1775 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1776 TownNameParams par(_settings_game.game_creation.town_name);
1777 bool random = HasBit(p1, 6);
1778 uint32 townnameparts = p2;
1780 if (size >= TSZ_END) return CommandError();
1781 if (layout >= NUM_TLS) return CommandError();
1783 /* Some things are allowed only in the scenario editor and for game scripts. */
1784 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1785 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CommandError();
1786 if (size == TSZ_LARGE) return CommandError();
1787 if (random) return CommandError();
1788 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
1789 return CommandError();
1791 } else if (_current_company == OWNER_DEITY && random) {
1792 /* Random parameter is not allowed for Game Scripts. */
1793 return CommandError();
1796 if (StrEmpty(text)) {
1797 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1798 if (!VerifyTownName(townnameparts, &par)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1799 } else {
1800 /* If name is not empty, it has to be unique custom name */
1801 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CommandError();
1802 if (!IsUniqueTownName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1805 /* Allocate town struct */
1806 if (!Town::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_TOWNS);
1808 if (!random) {
1809 CommandCost ret = TownCanBePlacedHere(tile);
1810 if (ret.Failed()) return ret;
1813 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1814 /* multidimensional arrays have to have defined length of non-first dimension */
1815 assert_compile(lengthof(price_mult[0]) == 4);
1817 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1818 byte mult = price_mult[city][size];
1820 cost.MultiplyCost(mult);
1822 /* Create the town */
1823 if (flags & DC_EXEC) {
1824 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1825 _additional_cash_required = cost.GetCost();
1826 return CommandCost(EXPENSES_OTHER);
1829 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1830 UpdateNearestTownForRoadTiles(true);
1831 Town *t;
1832 if (random) {
1833 t = CreateRandomTown(20, townnameparts, size, city, layout);
1834 if (t == nullptr) {
1835 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1836 } else {
1837 _new_town_id = t->index;
1839 } else {
1840 t = new Town(tile);
1841 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1843 UpdateNearestTownForRoadTiles(false);
1844 old_generating_world.Restore();
1846 if (t != nullptr && !StrEmpty(text)) {
1847 t->name = stredup(text);
1848 t->UpdateVirtCoord();
1851 if (_game_mode != GM_EDITOR) {
1852 /* 't' can't be nullptr since 'random' is false outside scenedit */
1853 assert(!random);
1854 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1855 SetDParam(0, _current_company);
1856 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1858 char *cn = stredup(company_name);
1859 SetDParamStr(0, cn);
1860 SetDParam(1, t->index);
1862 AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1863 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1864 Game::NewEvent(new ScriptEventTownFounded(t->index));
1867 return cost;
1871 * Towns must all be placed on the same grid or when they eventually
1872 * interpenetrate their road networks will not mesh nicely; this
1873 * function adjusts a tile so that it aligns properly.
1875 * @param tile the tile to start at
1876 * @param layout which town layout algo is in effect
1877 * @return the adjusted tile
1879 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
1881 switch (layout) {
1882 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1883 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1884 default: return tile;
1889 * Towns must all be placed on the same grid or when they eventually
1890 * interpenetrate their road networks will not mesh nicely; this
1891 * function tells you if a tile is properly aligned.
1893 * @param tile the tile to start at
1894 * @param layout which town layout algo is in effect
1895 * @return true if the tile is in the correct location
1897 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1899 switch (layout) {
1900 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1901 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1902 default: return true;
1907 * Used as the user_data for FindFurthestFromWater
1909 struct SpotData {
1910 TileIndex tile; ///< holds the tile that was found
1911 uint max_dist; ///< holds the distance that tile is from the water
1912 TownLayout layout; ///< tells us what kind of town we're building
1916 * CircularTileSearch callback; finds the tile furthest from any
1917 * water. slightly bit tricky, since it has to do a search of its own
1918 * in order to find the distance to the water from each square in the
1919 * radius.
1921 * Also, this never returns true, because it needs to take into
1922 * account all locations being searched before it knows which is the
1923 * furthest.
1925 * @param tile Start looking from this tile
1926 * @param user_data Storage area for data that must last across calls;
1927 * must be a pointer to struct SpotData
1929 * @return always false
1931 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1933 SpotData *sp = (SpotData*)user_data;
1934 uint dist = GetClosestWaterDistance(tile, true);
1936 if (IsTileType(tile, MP_CLEAR) &&
1937 IsTileFlat(tile) &&
1938 IsTileAlignedToGrid(tile, sp->layout) &&
1939 dist > sp->max_dist) {
1940 sp->tile = tile;
1941 sp->max_dist = dist;
1944 return false;
1948 * CircularTileSearch callback; finds the nearest land tile
1950 * @param tile Start looking from this tile
1951 * @param user_data not used
1953 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1955 return IsTileType(tile, MP_CLEAR);
1959 * Given a spot on the map (presumed to be a water tile), find a good
1960 * coastal spot to build a city. We don't want to build too close to
1961 * the edge if we can help it (since that retards city growth) hence
1962 * the search within a search within a search. O(n*m^2), where n is
1963 * how far to search for land, and m is how far inland to look for a
1964 * flat spot.
1966 * @param tile Start looking from this spot.
1967 * @param layout the road layout to search for
1968 * @return tile that was found
1970 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
1972 SpotData sp = { INVALID_TILE, 0, layout };
1974 TileIndex coast = tile;
1975 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
1976 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1977 return sp.tile;
1980 /* if we get here just give up */
1981 return INVALID_TILE;
1984 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1986 assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1988 if (!Town::CanAllocateItem()) return nullptr;
1990 do {
1991 /* Generate a tile index not too close from the edge */
1992 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1994 /* if we tried to place the town on water, slide it over onto
1995 * the nearest likely-looking spot */
1996 if (IsTileType(tile, MP_WATER)) {
1997 tile = FindNearestGoodCoastalTownSpot(tile, layout);
1998 if (tile == INVALID_TILE) continue;
2001 /* Make sure town can be placed here */
2002 if (TownCanBePlacedHere(tile).Failed()) continue;
2004 /* Allocate a town struct */
2005 Town *t = new Town(tile);
2007 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2009 /* if the population is still 0 at the point, then the
2010 * placement is so bad it couldn't grow at all */
2011 if (t->cache.population > 0) return t;
2013 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2014 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
2015 cur_company.Restore();
2016 assert(rc.Succeeded());
2018 /* We already know that we can allocate a single town when
2019 * entering this function. However, we create and delete
2020 * a town which "resets" the allocation checks. As such we
2021 * need to check again when assertions are enabled. */
2022 assert(Town::CanAllocateItem());
2023 } while (--attempts != 0);
2025 return nullptr;
2028 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2031 * This function will generate a certain amount of towns, with a certain layout
2032 * It can be called from the scenario editor (i.e.: generate Random Towns)
2033 * as well as from world creation.
2034 * @param layout which towns will be set to, when created
2035 * @return true if towns have been successfully created
2037 bool GenerateTowns(TownLayout layout)
2039 uint current_number = 0;
2040 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2041 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
2042 total = min(TownPool::MAX_SIZE, total);
2043 uint32 townnameparts;
2044 TownNames town_names;
2046 SetGeneratingWorldProgress(GWP_TOWN, total);
2048 /* First attempt will be made at creating the suggested number of towns.
2049 * Note that this is really a suggested value, not a required one.
2050 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2051 do {
2052 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
2053 IncreaseGeneratingWorldProgress(GWP_TOWN);
2054 /* Get a unique name for the town. */
2055 if (!GenerateTownName(&townnameparts, &town_names)) continue;
2056 /* try 20 times to create a random-sized town for the first loop. */
2057 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2058 } while (--total);
2060 town_names.clear();
2062 if (current_number != 0) return true;
2064 /* If current_number is still zero at this point, it means that not a single town has been created.
2065 * So give it a last try, but now more aggressive */
2066 if (GenerateTownName(&townnameparts) &&
2067 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2068 return true;
2071 /* If there are no towns at all and we are generating new game, bail out */
2072 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2073 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2076 return false; // we are still without a town? we failed, simply
2081 * Returns the bit corresponding to the town zone of the specified tile
2082 * @param t Town on which town zone is to be found
2083 * @param tile TileIndex where town zone needs to be found
2084 * @return the bit position of the given zone, as defined in HouseZones
2086 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2088 uint dist = DistanceSquare(tile, t->xy);
2090 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2092 HouseZonesBits smallest = HZB_TOWN_EDGE;
2093 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2094 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2097 return smallest;
2101 * Clears tile and builds a house or house part.
2102 * @param tile tile index
2103 * @param t The town to clear the house for
2104 * @param counter of construction step
2105 * @param stage of construction (used for drawing)
2106 * @param type of house. Index into house specs array
2107 * @param random_bits required for newgrf houses
2108 * @pre house can be built here
2110 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2112 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
2114 assert(cc.Succeeded());
2116 IncreaseBuildingCount(t, type);
2117 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2118 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2120 MarkTileDirtyByTile(tile);
2125 * Write house information into the map. For houses > 1 tile, all tiles are marked.
2126 * @param t tile index
2127 * @param town The town related to this house
2128 * @param counter of construction step
2129 * @param stage of construction (used for drawing)
2130 * @param type of house. Index into house specs array
2131 * @param random_bits required for newgrf houses
2132 * @pre house can be built here
2134 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2136 BuildingFlags size = HouseSpec::Get(type)->building_flags;
2138 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2139 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2140 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2141 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2146 * Checks if a house can be built here. Important is slope, bridge above
2147 * and ability to clear the land.
2148 * @param tile tile to check
2149 * @param noslope are slopes (foundations) allowed?
2150 * @return true iff house can be built here
2152 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2154 /* cannot build on these slopes... */
2155 Slope slope = GetTileSlope(tile);
2156 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2158 /* building under a bridge? */
2159 if (IsBridgeAbove(tile)) return false;
2161 /* can we clear the land? */
2162 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2167 * Checks if a house can be built at this tile, must have the same max z as parameter.
2168 * @param tile tile to check
2169 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2170 * @param noslope are slopes (foundations) allowed?
2171 * @return true iff house can be built here
2172 * @see CanBuildHouseHere()
2174 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2176 if (!CanBuildHouseHere(tile, noslope)) return false;
2178 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2179 if (GetTileMaxZ(tile) != z) return false;
2181 return true;
2186 * Checks if a house of size 2x2 can be built at this tile
2187 * @param tile tile, N corner
2188 * @param z maximum tile z so all tile have the same max z
2189 * @param noslope are slopes (foundations) allowed?
2190 * @return true iff house can be built
2191 * @see CheckBuildHouseSameZ()
2193 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2195 /* we need to check this tile too because we can be at different tile now */
2196 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2198 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2199 tile += TileOffsByDiagDir(d);
2200 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2203 return true;
2208 * Checks if current town layout allows building here
2209 * @param t town
2210 * @param tile tile to check
2211 * @return true iff town layout allows building here
2212 * @note see layouts
2214 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2216 /* Allow towns everywhere when we don't build roads */
2217 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2219 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2221 switch (t->layout) {
2222 case TL_2X2_GRID:
2223 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2224 break;
2226 case TL_3X3_GRID:
2227 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2228 break;
2230 default:
2231 break;
2234 return true;
2239 * Checks if current town layout allows 2x2 building here
2240 * @param t town
2241 * @param tile tile to check
2242 * @return true iff town layout allows 2x2 building here
2243 * @note see layouts
2245 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2247 /* Allow towns everywhere when we don't build roads */
2248 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2250 /* Compute relative position of tile. (Positive offsets are towards north) */
2251 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2253 switch (t->layout) {
2254 case TL_2X2_GRID:
2255 grid_pos.x %= 3;
2256 grid_pos.y %= 3;
2257 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2258 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2259 break;
2261 case TL_3X3_GRID:
2262 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2263 break;
2265 default:
2266 break;
2269 return true;
2274 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2275 * Also, tests both building positions that occupy this tile
2276 * @param tile tile where the building should be built
2277 * @param t town
2278 * @param maxz all tiles should have the same height
2279 * @param noslope are slopes forbidden?
2280 * @param second diagdir from first tile to second tile
2282 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2284 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2286 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2287 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2289 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2290 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2291 *tile = tile2;
2292 return true;
2295 return false;
2300 * Checks if 2x2 building is allowed here, also takes into account current town layout
2301 * Also, tests all four building positions that occupy this tile
2302 * @param tile tile where the building should be built
2303 * @param t town
2304 * @param maxz all tiles should have the same height
2305 * @param noslope are slopes forbidden?
2307 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2309 TileIndex tile2 = *tile;
2311 for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2312 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2313 *tile = tile2;
2314 return true;
2316 if (d == DIAGDIR_END) break;
2317 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2320 return false;
2325 * Tries to build a house at this tile
2326 * @param t town the house will belong to
2327 * @param tile where the house will be built
2328 * @return false iff no house can be built at this tile
2330 static bool BuildTownHouse(Town *t, TileIndex tile)
2332 /* forbidden building here by town layout */
2333 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2335 /* no house allowed at all, bail out */
2336 if (!CanBuildHouseHere(tile, false)) return false;
2338 Slope slope = GetTileSlope(tile);
2339 int maxz = GetTileMaxZ(tile);
2341 /* Get the town zone type of the current tile, as well as the climate.
2342 * This will allow to easily compare with the specs of the new house to build */
2343 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2345 /* Above snow? */
2346 int land = _settings_game.game_creation.landscape;
2347 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2349 uint bitmask = (1 << rad) + (1 << (land + 12));
2351 /* bits 0-4 are used
2352 * bits 11-15 are used
2353 * bits 5-10 are not used. */
2354 HouseID houses[NUM_HOUSES];
2355 uint num = 0;
2356 uint probs[NUM_HOUSES];
2357 uint probability_max = 0;
2359 /* Generate a list of all possible houses that can be built. */
2360 for (uint i = 0; i < NUM_HOUSES; i++) {
2361 const HouseSpec *hs = HouseSpec::Get(i);
2363 /* Verify that the candidate house spec matches the current tile status */
2364 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2366 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2367 if (hs->class_id != HOUSE_NO_CLASS) {
2368 /* id_count is always <= class_count, so it doesn't need to be checked */
2369 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2370 } else {
2371 /* If the house has no class, check id_count instead */
2372 if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2375 /* Without NewHouses, all houses have probability '1' */
2376 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2377 probability_max += cur_prob;
2378 probs[num] = cur_prob;
2379 houses[num++] = (HouseID)i;
2382 TileIndex baseTile = tile;
2384 while (probability_max > 0) {
2385 /* Building a multitile building can change the location of tile.
2386 * The building would still be built partially on that tile, but
2387 * its northern tile would be elsewhere. However, if the callback
2388 * fails we would be basing further work from the changed tile.
2389 * So a next 1x1 tile building could be built on the wrong tile. */
2390 tile = baseTile;
2392 uint r = RandomRange(probability_max);
2393 uint i;
2394 for (i = 0; i < num; i++) {
2395 if (probs[i] > r) break;
2396 r -= probs[i];
2399 HouseID house = houses[i];
2400 probability_max -= probs[i];
2402 /* remove tested house from the set */
2403 num--;
2404 houses[i] = houses[num];
2405 probs[i] = probs[num];
2407 const HouseSpec *hs = HouseSpec::Get(house);
2409 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
2410 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2411 continue;
2414 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2416 /* Special houses that there can be only one of. */
2417 uint oneof = 0;
2419 if (hs->building_flags & BUILDING_IS_CHURCH) {
2420 SetBit(oneof, TOWN_HAS_CHURCH);
2421 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2422 SetBit(oneof, TOWN_HAS_STADIUM);
2425 if (t->flags & oneof) continue;
2427 /* Make sure there is no slope? */
2428 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2429 if (noslope && slope != SLOPE_FLAT) continue;
2431 if (hs->building_flags & TILE_SIZE_2x2) {
2432 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2433 } else if (hs->building_flags & TILE_SIZE_2x1) {
2434 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2435 } else if (hs->building_flags & TILE_SIZE_1x2) {
2436 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2437 } else {
2438 /* 1x1 house checks are already done */
2441 byte random_bits = Random();
2443 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
2444 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2445 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2448 /* build the house */
2449 t->cache.num_houses++;
2451 /* Special houses that there can be only one of. */
2452 t->flags |= oneof;
2454 byte construction_counter = 0;
2455 byte construction_stage = 0;
2457 if (_generating_world || _game_mode == GM_EDITOR) {
2458 uint32 r = Random();
2460 construction_stage = TOWN_HOUSE_COMPLETED;
2461 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2463 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2464 ChangePopulation(t, hs->population);
2465 } else {
2466 construction_counter = GB(r, 2, 2);
2470 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2471 UpdateTownRadius(t);
2472 UpdateTownCargoes(t, tile);
2474 return true;
2477 return false;
2481 * Update data structures when a house is removed
2482 * @param tile Tile of the house
2483 * @param t Town owning the house
2484 * @param house House type
2486 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2488 assert(IsTileType(tile, MP_HOUSE));
2489 DecreaseBuildingCount(t, house);
2490 DoClearSquare(tile);
2491 DeleteAnimatedTile(tile);
2493 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2497 * Determines if a given HouseID is part of a multitile house.
2498 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2500 * @param house Is changed to the HouseID of the north tile of the same house
2501 * @return TileDiff from the tile of the given HouseID to the north tile
2503 TileIndexDiff GetHouseNorthPart(HouseID &house)
2505 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2506 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2507 house--;
2508 return TileDiffXY(-1, 0);
2509 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2510 house--;
2511 return TileDiffXY(0, -1);
2512 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2513 house -= 2;
2514 return TileDiffXY(-1, 0);
2515 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2516 house -= 3;
2517 return TileDiffXY(-1, -1);
2520 return 0;
2523 void ClearTownHouse(Town *t, TileIndex tile)
2525 assert(IsTileType(tile, MP_HOUSE));
2527 HouseID house = GetHouseType(tile);
2529 /* need to align the tile to point to the upper left corner of the house */
2530 tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2532 const HouseSpec *hs = HouseSpec::Get(house);
2534 /* Remove population from the town if the house is finished. */
2535 if (IsHouseCompleted(tile)) {
2536 ChangePopulation(t, -hs->population);
2539 t->cache.num_houses--;
2541 /* Clear flags for houses that only may exist once/town. */
2542 if (hs->building_flags & BUILDING_IS_CHURCH) {
2543 ClrBit(t->flags, TOWN_HAS_CHURCH);
2544 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2545 ClrBit(t->flags, TOWN_HAS_STADIUM);
2548 /* Do the actual clearing of tiles */
2549 uint eflags = hs->building_flags;
2550 DoClearTownHouseHelper(tile, t, house);
2551 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2552 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2553 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2555 UpdateTownRadius(t);
2557 /* Update cargo acceptance. */
2558 UpdateTownCargoes(t, tile);
2562 * Rename a town (server-only).
2563 * @param tile unused
2564 * @param flags type of operation
2565 * @param p1 town ID to rename
2566 * @param p2 unused
2567 * @param text the new name or an empty string when resetting to the default
2568 * @return the cost of this operation or an error
2570 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2572 Town *t = Town::GetIfValid(p1);
2573 if (t == nullptr) return CommandError();
2575 bool reset = StrEmpty(text);
2577 if (!reset) {
2578 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CommandError();
2579 if (!IsUniqueTownName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
2582 if (flags & DC_EXEC) {
2583 free(t->name);
2584 t->name = reset ? nullptr : stredup(text);
2586 t->UpdateVirtCoord();
2587 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
2588 UpdateAllStationVirtCoords();
2590 return CommandCost();
2594 * Determines the first cargo with a certain town effect
2595 * @param effect Town effect of interest
2596 * @return first active cargo slot with that effect
2598 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
2600 const CargoSpec *cs;
2601 FOR_ALL_CARGOSPECS(cs) {
2602 if (cs->town_effect == effect) return cs;
2604 return nullptr;
2607 static void UpdateTownGrowRate(Town *t);
2610 * Change the cargo goal of a town.
2611 * @param tile Unused.
2612 * @param flags Type of operation.
2613 * @param p1 various bitstuffed elements
2614 * - p1 = (bit 0 - 15) - Town ID to cargo game of.
2615 * - p1 = (bit 16 - 23) - TownEffect to change the game of.
2616 * @param p2 The new goal value.
2617 * @param text Unused.
2618 * @return Empty cost or an error.
2620 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2622 if (_current_company != OWNER_DEITY) return CommandError();
2624 TownEffect te = (TownEffect)GB(p1, 16, 8);
2625 if (te < TE_BEGIN || te >= TE_END) return CommandError();
2627 uint16 index = GB(p1, 0, 16);
2628 Town *t = Town::GetIfValid(index);
2629 if (t == nullptr) return CommandError();
2631 /* Validate if there is a cargo which is the requested TownEffect */
2632 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2633 if (cargo == nullptr) return CommandError();
2635 if (flags & DC_EXEC) {
2636 t->goal[te] = p2;
2637 UpdateTownGrowRate(t);
2638 InvalidateWindowData(WC_TOWN_VIEW, index);
2641 return CommandCost();
2645 * Set a custom text in the Town window.
2646 * @param tile Unused.
2647 * @param flags Type of operation.
2648 * @param p1 Town ID to change the text of.
2649 * @param p2 Unused.
2650 * @param text The new text (empty to remove the text).
2651 * @return Empty cost or an error.
2653 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2655 if (_current_company != OWNER_DEITY) return CommandError();
2656 Town *t = Town::GetIfValid(p1);
2657 if (t == nullptr) return CommandError();
2659 if (flags & DC_EXEC) {
2660 free(t->text);
2661 t->text = StrEmpty(text) ? nullptr : stredup(text);
2662 InvalidateWindowData(WC_TOWN_VIEW, p1);
2665 return CommandCost();
2669 * Change the growth rate of the town.
2670 * @param tile Unused.
2671 * @param flags Type of operation.
2672 * @param p1 Town ID to cargo game of.
2673 * @param p2 Amount of days between growth, or TOWN_GROWTH_RATE_NONE, or 0 to reset custom growth rate.
2674 * @param text Unused.
2675 * @return Empty cost or an error.
2677 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2679 if (_current_company != OWNER_DEITY) return CommandError();
2681 Town *t = Town::GetIfValid(p1);
2682 if (t == nullptr) return CommandError();
2684 if (flags & DC_EXEC) {
2685 if (p2 == 0) {
2686 /* Just clear the flag, UpdateTownGrowRate will determine a proper growth rate */
2687 ClrBit(t->flags, TOWN_CUSTOM_GROWTH);
2688 } else {
2689 const Ticks old_rate = t->growth_rate;
2691 if (t->grow_counter >= old_rate) {
2692 /* This also catches old_rate == 0 */
2693 t->grow_counter = p2;
2694 } else {
2695 /* Scale grow_counter, so half finished houses stay half finished */
2696 t->grow_counter = t->grow_counter * p2 / old_rate;
2698 t->growth_rate = p2;
2699 SetBit(t->flags, TOWN_CUSTOM_GROWTH);
2701 UpdateTownGrowRate(t);
2702 InvalidateWindowData(WC_TOWN_VIEW, p1);
2705 return CommandCost();
2709 * Expand a town (scenario editor only).
2710 * @param tile Unused.
2711 * @param flags Type of operation.
2712 * @param p1 Town ID to expand.
2713 * @param p2 Amount to grow, or 0 to grow a random size up to the current amount of houses.
2714 * @param text Unused.
2715 * @return Empty cost or an error.
2717 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2719 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CommandError();
2720 Town *t = Town::GetIfValid(p1);
2721 if (t == nullptr) return CommandError();
2723 if (flags & DC_EXEC) {
2724 /* The more houses, the faster we grow */
2725 if (p2 == 0) {
2726 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2727 t->cache.num_houses += amount;
2728 UpdateTownRadius(t);
2730 uint n = amount * 10;
2731 do GrowTown(t); while (--n);
2733 t->cache.num_houses -= amount;
2734 } else {
2735 for (; p2 > 0; p2--) {
2736 /* Try several times to grow, as we are really suppose to grow */
2737 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2740 UpdateTownRadius(t);
2742 UpdateTownMaxPass(t);
2745 return CommandCost();
2749 * Delete a town (scenario editor or worldgen only).
2750 * @param tile Unused.
2751 * @param flags Type of operation.
2752 * @param p1 Town ID to delete.
2753 * @param p2 Unused.
2754 * @param text Unused.
2755 * @return Empty cost or an error.
2757 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2759 if (_game_mode != GM_EDITOR && !_generating_world) return CommandError();
2760 Town *t = Town::GetIfValid(p1);
2761 if (t == nullptr) return CommandError();
2763 /* Stations refer to towns. */
2764 const Station *st;
2765 FOR_ALL_STATIONS(st) {
2766 if (st->town == t) {
2767 /* Non-oil rig stations are always a problem. */
2768 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CommandError();
2769 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2770 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2771 if (ret.Failed()) return ret;
2775 /* Depots refer to towns. */
2776 const Depot *d;
2777 FOR_ALL_DEPOTS(d) {
2778 if (d->town == t) return CommandError();
2781 /* Check all tiles for town ownership. */
2782 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2783 bool try_clear = false;
2784 switch (GetTileType(tile)) {
2785 case MP_ROAD:
2786 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2787 break;
2789 case MP_TUNNELBRIDGE:
2790 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2791 break;
2793 case MP_HOUSE:
2794 try_clear = GetTownIndex(tile) == t->index;
2795 break;
2797 case MP_INDUSTRY:
2798 try_clear = Industry::GetByTile(tile)->town == t;
2799 break;
2801 case MP_OBJECT:
2802 if (Town::GetNumItems() == 1) {
2803 /* No towns will be left, remove it! */
2804 try_clear = true;
2805 } else {
2806 Object *o = Object::GetByTile(tile);
2807 if (o->town == t) {
2808 if (o->type == OBJECT_STATUE) {
2809 /* Statue... always remove. */
2810 try_clear = true;
2811 } else {
2812 /* Tell to find a new town. */
2813 if (flags & DC_EXEC) o->town = nullptr;
2817 break;
2819 default:
2820 break;
2822 if (try_clear) {
2823 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2824 if (ret.Failed()) return ret;
2828 /* The town destructor will delete the other things related to the town. */
2829 if (flags & DC_EXEC) delete t;
2831 return CommandCost();
2835 * Factor in the cost of each town action.
2836 * @see TownActions
2838 const byte _town_action_costs[TACT_COUNT] = {
2839 2, 4, 9, 35, 48, 53, 117, 175
2842 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2844 if (flags & DC_EXEC) {
2845 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2847 return CommandCost();
2850 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2852 if (flags & DC_EXEC) {
2853 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2855 return CommandCost();
2858 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2860 if (flags & DC_EXEC) {
2861 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2863 return CommandCost();
2866 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2868 /* Check if the company is allowed to fund new roads. */
2869 if (!_settings_game.economy.fund_roads) return CommandError();
2871 if (flags & DC_EXEC) {
2872 t->road_build_months = 6;
2874 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2875 SetDParam(0, _current_company);
2876 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2878 char *cn = stredup(company_name);
2879 SetDParam(0, t->index);
2880 SetDParamStr(1, cn);
2882 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2883 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2884 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2886 return CommandCost();
2890 * Check whether the land can be cleared.
2891 * @param tile Tile to check.
2892 * @return The tile can be cleared.
2894 static bool TryClearTile(TileIndex tile)
2896 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2897 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
2898 cur_company.Restore();
2899 return r.Succeeded();
2902 /** Structure for storing data while searching the best place to build a statue. */
2903 struct StatueBuildSearchData {
2904 TileIndex best_position; ///< Best position found so far.
2905 int tile_count; ///< Number of tiles tried.
2907 StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2911 * Search callback function for #TownActionBuildStatue.
2912 * @param tile Tile on which to perform the search.
2913 * @param user_data Reference to the statue search data.
2914 * @return Result of the test.
2916 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2918 static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2920 StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2921 statue_data->tile_count++;
2923 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2924 if (IsSteepSlope(GetTileSlope(tile))) return false;
2925 /* Don't build statues under bridges. */
2926 if (IsBridgeAbove(tile)) return false;
2928 /* A clear-able open space is always preferred. */
2929 if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2930 statue_data->best_position = tile;
2931 return true;
2934 bool house = IsTileType(tile, MP_HOUSE);
2936 /* Searching inside the inner circle. */
2937 if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2938 /* Save first house in inner circle. */
2939 if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2940 statue_data->best_position = tile;
2943 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2944 return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2947 /* Searching outside the circle, just pick the first possible spot. */
2948 statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2949 return house && TryClearTile(tile);
2953 * Perform a 9x9 tiles circular search from the center of the town
2954 * in order to find a free tile to place a statue
2955 * @param t town to search in
2956 * @param flags Used to check if the statue must be built or not.
2957 * @return Empty cost or an error.
2959 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
2961 if (!Object::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_OBJECTS);
2963 TileIndex tile = t->xy;
2964 StatueBuildSearchData statue_data(INVALID_TILE, 0);
2965 if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return CommandError(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2967 if (flags & DC_EXEC) {
2968 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2969 DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2970 cur_company.Restore();
2971 BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
2972 SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2973 MarkTileDirtyByTile(statue_data.best_position);
2975 return CommandCost();
2978 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2980 /* Check if it's allowed to buy the rights */
2981 if (!_settings_game.economy.fund_buildings) return CommandError();
2983 if (flags & DC_EXEC) {
2984 /* And grow for 3 months */
2985 t->fund_buildings_months = 3;
2987 /* Enable growth (also checking GameScript's opinion) */
2988 UpdateTownGrowRate(t);
2990 /* Build a new house, but add a small delay to make sure
2991 * that spamming funding doesn't let town grow any faster
2992 * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
2993 * Also emulate original behaviour when town was only growing in
2994 * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
2995 * tick-perfect and gives player some time window where he can
2996 * spam funding with the exact same effeciency.
2998 t->grow_counter = min(t->grow_counter, 2 * TOWN_GROWTH_TICKS - (t->growth_rate - t->grow_counter) % TOWN_GROWTH_TICKS);
3000 SetWindowDirty(WC_TOWN_VIEW, t->index);
3002 return CommandCost();
3005 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
3007 /* Check if it's allowed to buy the rights */
3008 if (!_settings_game.economy.exclusive_rights) return CommandError();
3010 if (flags & DC_EXEC) {
3011 t->exclusive_counter = 12;
3012 t->exclusivity = _current_company;
3014 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3016 SetWindowClassesDirty(WC_STATION_VIEW);
3018 /* Spawn news message */
3019 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
3020 cni->FillData(Company::Get(_current_company));
3021 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3022 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
3023 SetDParam(2, t->index);
3024 SetDParamStr(3, cni->company_name);
3025 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3026 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3027 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3029 return CommandCost();
3032 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
3034 if (flags & DC_EXEC) {
3035 if (Chance16(1, 14)) {
3036 /* set as unwanted for 6 months */
3037 t->unwanted[_current_company] = 6;
3039 /* set all close by station ratings to 0 */
3040 Station *st;
3041 FOR_ALL_STATIONS(st) {
3042 if (st->town == t && st->owner == _current_company) {
3043 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
3047 /* only show error message to the executing player. All errors are handled command.c
3048 * but this is special, because it can only 'fail' on a DC_EXEC */
3049 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3051 /* decrease by a lot!
3052 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3053 * be independent of any cheat settings
3055 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3056 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3057 t->UpdateVirtCoord();
3058 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3060 } else {
3061 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3064 return CommandCost();
3067 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3068 static TownActionProc * const _town_action_proc[] = {
3069 TownActionAdvertiseSmall,
3070 TownActionAdvertiseMedium,
3071 TownActionAdvertiseLarge,
3072 TownActionRoadRebuild,
3073 TownActionBuildStatue,
3074 TownActionFundBuildings,
3075 TownActionBuyRights,
3076 TownActionBribe
3080 * Get a list of available actions to do at a town.
3081 * @param nump if not nullptr add put the number of available actions in it
3082 * @param cid the company that is querying the town
3083 * @param t the town that is queried
3084 * @return bitmasked value of enabled actions
3086 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3088 int num = 0;
3089 TownActions buttons = TACT_NONE;
3091 /* Spectators and unwanted have no options */
3092 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3094 /* Things worth more than this are not shown */
3095 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3097 /* Check the action bits for validity and
3098 * if they are valid add them */
3099 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3100 const TownActions cur = (TownActions)(1 << i);
3102 /* Is the company not able to bribe ? */
3103 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3105 /* Is the company not able to buy exclusive rights ? */
3106 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3108 /* Is the company not able to fund buildings ? */
3109 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3111 /* Is the company not able to fund local road reconstruction? */
3112 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3114 /* Is the company not able to build a statue ? */
3115 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3117 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3118 buttons |= cur;
3119 num++;
3124 if (nump != nullptr) *nump = num;
3125 return buttons;
3129 * Do a town action.
3130 * This performs an action such as advertising, building a statue, funding buildings,
3131 * but also bribing the town-council
3132 * @param tile unused
3133 * @param flags type of operation
3134 * @param p1 town to do the action at
3135 * @param p2 action to perform, @see _town_action_proc for the list of available actions
3136 * @param text unused
3137 * @return the cost of this operation or an error
3139 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3141 Town *t = Town::GetIfValid(p1);
3142 if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CommandError();
3144 if (!HasBit(GetMaskOfTownActions(nullptr, _current_company, t), p2)) return CommandError();
3146 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3148 CommandCost ret = _town_action_proc[p2](t, flags);
3149 if (ret.Failed()) return ret;
3151 if (flags & DC_EXEC) {
3152 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
3155 return cost;
3158 static void UpdateTownRating(Town *t)
3160 /* Increase company ratings if they're low */
3161 const Company *c;
3162 FOR_ALL_COMPANIES(c) {
3163 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3164 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3168 const Station *st;
3169 FOR_ALL_STATIONS(st) {
3170 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3171 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3172 if (Company::IsValidID(st->owner)) {
3173 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3174 t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3176 } else {
3177 if (Company::IsValidID(st->owner)) {
3178 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3179 t->ratings[st->owner] = max(new_rating, INT16_MIN);
3185 /* clamp all ratings to valid values */
3186 for (uint i = 0; i < MAX_COMPANIES; i++) {
3187 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3190 t->UpdateVirtCoord();
3191 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3194 static void UpdateTownGrowRate(Town *t)
3196 ClrBit(t->flags, TOWN_IS_GROWING);
3197 SetWindowDirty(WC_TOWN_VIEW, t->index);
3199 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3201 if (t->fund_buildings_months == 0) {
3202 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3203 for (int i = TE_BEGIN; i < TE_END; i++) {
3204 switch (t->goal[i]) {
3205 case TOWN_GROWTH_WINTER:
3206 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3207 break;
3208 case TOWN_GROWTH_DESERT:
3209 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3210 break;
3211 default:
3212 if (t->goal[i] > t->received[i].old_act) return;
3213 break;
3218 if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3219 if (t->growth_rate != TOWN_GROWTH_RATE_NONE) SetBit(t->flags, TOWN_IS_GROWING);
3220 SetWindowDirty(WC_TOWN_VIEW, t->index);
3221 return;
3225 * Towns are processed every TOWN_GROWTH_TICKS ticks, and this is the
3226 * number of times towns are processed before a new building is built.
3228 static const uint16 _grow_count_values[2][6] = {
3229 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3230 { 320, 420, 300, 220, 160, 100 } // Normal values
3233 int n = 0;
3235 const Station *st;
3236 FOR_ALL_STATIONS(st) {
3237 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3238 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3239 n++;
3244 uint16 m;
3246 if (t->fund_buildings_months != 0) {
3247 m = _grow_count_values[0][min(n, 5)];
3248 } else {
3249 m = _grow_count_values[1][min(n, 5)];
3250 if (n == 0 && !Chance16(1, 12)) return;
3253 /* Use the normal growth rate values if new buildings have been funded in
3254 * this town and the growth rate is set to none. */
3255 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3257 m >>= growth_multiplier;
3258 if (t->larger_town) m /= 2;
3260 t->growth_rate = TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3261 t->grow_counter = min(t->growth_rate, t->grow_counter);
3263 SetBit(t->flags, TOWN_IS_GROWING);
3264 SetWindowDirty(WC_TOWN_VIEW, t->index);
3267 static void UpdateTownAmounts(Town *t)
3269 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3270 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3271 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3273 SetWindowDirty(WC_TOWN_VIEW, t->index);
3276 static void UpdateTownUnwanted(Town *t)
3278 const Company *c;
3280 FOR_ALL_COMPANIES(c) {
3281 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3286 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3287 * @param tile The tile where the station shall be constructed.
3288 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3289 * @return Succeeded or failed command.
3291 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
3293 return CommandCost();
3297 * Return the town closest to the given tile within \a threshold.
3298 * @param tile Starting point of the search.
3299 * @param threshold Biggest allowed distance to the town.
3300 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3302 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3304 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
3306 Town *t;
3307 uint best = threshold;
3308 Town *best_town = nullptr;
3310 FOR_ALL_TOWNS(t) {
3311 uint dist = DistanceManhattan(tile, t->xy);
3312 if (dist < best) {
3313 best = dist;
3314 best_town = t;
3318 return best_town;
3322 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3323 * @param tile Starting point of the search.
3324 * @param threshold Biggest allowed distance to the town.
3325 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3327 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3329 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3331 switch (GetTileType(tile)) {
3332 case MP_ROAD:
3333 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3335 if (!HasTownOwnedRoad(tile)) {
3336 TownID tid = GetTownIndex(tile);
3338 if (tid == (TownID)INVALID_TOWN) {
3339 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3340 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3341 assert(Town::GetNumItems() == 0);
3342 return nullptr;
3345 assert(Town::IsValidID(tid));
3346 Town *town = Town::Get(tid);
3348 if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3350 return town;
3352 FALLTHROUGH;
3354 case MP_HOUSE:
3355 return Town::GetByTile(tile);
3357 default:
3358 return CalcClosestTownFromTile(tile, threshold);
3362 static bool _town_rating_test = false; ///< If \c true, town rating is in test-mode.
3363 static SmallMap<const Town *, int, 4> _town_test_ratings; ///< Map of towns to modified ratings, while in town rating test-mode.
3366 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3367 * The function is safe to use in nested calls.
3368 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3370 void SetTownRatingTestMode(bool mode)
3372 static int ref_count = 0; // Number of times test-mode is switched on.
3373 if (mode) {
3374 if (ref_count == 0) {
3375 _town_test_ratings.Clear();
3377 ref_count++;
3378 } else {
3379 assert(ref_count > 0);
3380 ref_count--;
3382 _town_rating_test = !(ref_count == 0);
3386 * Get the rating of a town for the #_current_company.
3387 * @param t Town to get the rating from.
3388 * @return Rating of the current company in the given town.
3390 static int GetRating(const Town *t)
3392 if (_town_rating_test) {
3393 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3394 if (it != _town_test_ratings.End()) {
3395 return it->second;
3398 return t->ratings[_current_company];
3402 * Changes town rating of the current company
3403 * @param t Town to affect
3404 * @param add Value to add
3405 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3406 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3408 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3410 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3411 if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3412 !Company::IsValidID(_current_company) ||
3413 (_cheats.magic_bulldozer.value && add < 0)) {
3414 return;
3417 int rating = GetRating(t);
3418 if (add < 0) {
3419 if (rating > max) {
3420 rating += add;
3421 if (rating < max) rating = max;
3423 } else {
3424 if (rating < max) {
3425 rating += add;
3426 if (rating > max) rating = max;
3429 if (_town_rating_test) {
3430 _town_test_ratings[t] = rating;
3431 } else {
3432 SetBit(t->have_ratings, _current_company);
3433 t->ratings[_current_company] = rating;
3434 t->UpdateVirtCoord();
3435 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3440 * Does the town authority allow the (destructive) action of the current company?
3441 * @param flags Checking flags of the command.
3442 * @param t Town that must allow the company action.
3443 * @param type Type of action that is wanted.
3444 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3446 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
3448 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3449 if (t == nullptr || !Company::IsValidID(_current_company) ||
3450 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
3451 return CommandCost();
3454 /* minimum rating needed to be allowed to remove stuff */
3455 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3456 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3457 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
3458 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
3459 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
3462 /* check if you're allowed to remove the road/bridge/tunnel
3463 * owned by a town no removal if rating is lower than ... depends now on
3464 * difficulty setting. Minimum town rating selected by difficulty level
3466 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3468 if (GetRating(t) < needed) {
3469 SetDParam(0, t->index);
3470 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3473 return CommandCost();
3476 void TownsMonthlyLoop()
3478 Town *t;
3480 FOR_ALL_TOWNS(t) {
3481 if (t->road_build_months != 0) t->road_build_months--;
3483 if (t->exclusive_counter != 0) {
3484 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3487 UpdateTownAmounts(t);
3488 UpdateTownRating(t);
3489 UpdateTownGrowRate(t);
3490 UpdateTownUnwanted(t);
3491 UpdateTownCargoes(t);
3494 UpdateTownCargoBitmap();
3497 void TownsYearlyLoop()
3499 /* Increment house ages */
3500 for (TileIndex t = 0; t < MapSize(); t++) {
3501 if (!IsTileType(t, MP_HOUSE)) continue;
3502 IncrementHouseAge(t);
3506 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3508 if (AutoslopeEnabled()) {
3509 HouseID house = GetHouseType(tile);
3510 GetHouseNorthPart(house); // modifies house to the ID of the north tile
3511 const HouseSpec *hs = HouseSpec::Get(house);
3513 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3514 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3515 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3516 bool allow_terraform = true;
3518 /* Call the autosloping callback per tile, not for the whole building at once. */
3519 house = GetHouseType(tile);
3520 hs = HouseSpec::Get(house);
3521 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
3522 /* If the callback fails, allow autoslope. */
3523 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3524 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3527 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3531 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3534 /** Tile callback functions for a town */
3535 extern const TileTypeProcs _tile_type_town_procs = {
3536 DrawTile_Town, // draw_tile_proc
3537 GetSlopePixelZ_Town, // get_slope_z_proc
3538 ClearTile_Town, // clear_tile_proc
3539 AddAcceptedCargo_Town, // add_accepted_cargo_proc
3540 GetTileDesc_Town, // get_tile_desc_proc
3541 GetTileTrackStatus_Town, // get_tile_track_status_proc
3542 nullptr, // click_tile_proc
3543 AnimateTile_Town, // animate_tile_proc
3544 TileLoop_Town, // tile_loop_proc
3545 ChangeTileOwner_Town, // change_tile_owner_proc
3546 AddProducedCargo_Town, // add_produced_cargo_proc
3547 nullptr, // vehicle_enter_tile_proc
3548 GetFoundation_Town, // get_foundation_proc
3549 TerraformTile_Town, // terraform_tile_proc
3553 HouseSpec _house_specs[NUM_HOUSES];
3555 void ResetHouses()
3557 memset(&_house_specs, 0, sizeof(_house_specs));
3558 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3560 /* Reset any overrides that have been set. */
3561 _house_mngr.ResetOverride();