OpenTTD Source  20241120-master-g6d3adc6169
town_cmd.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "road.h"
12 #include "road_internal.h" /* Cleaning up road bits */
13 #include "road_cmd.h"
14 #include "landscape.h"
15 #include "viewport_func.h"
16 #include "viewport_kdtree.h"
17 #include "command_func.h"
18 #include "company_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "waypoint_base.h"
22 #include "station_kdtree.h"
23 #include "company_base.h"
24 #include "news_func.h"
25 #include "error.h"
26 #include "object.h"
27 #include "genworld.h"
28 #include "newgrf_debug.h"
29 #include "newgrf_house.h"
30 #include "newgrf_text.h"
31 #include "autoslope.h"
32 #include "tunnelbridge_map.h"
33 #include "strings_func.h"
34 #include "window_func.h"
35 #include "string_func.h"
36 #include "newgrf_cargo.h"
37 #include "cheat_type.h"
38 #include "animated_tile_func.h"
39 #include "subsidy_func.h"
40 #include "core/pool_func.hpp"
41 #include "town.h"
42 #include "town_kdtree.h"
43 #include "townname_func.h"
44 #include "core/random_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "depot_base.h"
47 #include "object_map.h"
48 #include "object_base.h"
49 #include "ai/ai.hpp"
50 #include "game/game.hpp"
51 #include "town_cmd.h"
52 #include "landscape_cmd.h"
53 #include "road_cmd.h"
54 #include "terraform_cmd.h"
55 #include "tunnelbridge_cmd.h"
56 #include "timer/timer.h"
59 #include "timer/timer_game_tick.h"
60 
61 #include "table/strings.h"
62 #include "table/town_land.h"
63 
64 #include "safeguards.h"
65 
66 /* Initialize the town-pool */
67 TownPool _town_pool("Town");
69 
70 
71 TownKdtree _town_kdtree{};
72 
73 void RebuildTownKdtree()
74 {
75  std::vector<TownID> townids;
76  for (const Town *town : Town::Iterate()) {
77  townids.push_back(town->index);
78  }
79  _town_kdtree.Build(townids.begin(), townids.end());
80 }
81 
83 static bool _generating_town = false;
84 
94 static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
95 {
96  if (!IsTileOwner(tile, OWNER_TOWN)) return false;
97 
99  bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
100 
101  if (!town_owned) {
102  /* Or other adjacent road */
104  town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
105  }
106 
107  return town_owned;
108 }
109 
111 {
112  if (CleaningPool()) return;
113 
114  /* Delete town authority window
115  * and remove from list of sorted towns */
117 
118 #ifdef WITH_ASSERT
119  /* Check no industry is related to us. */
120  for (const Industry *i : Industry::Iterate()) {
121  assert(i->town != this);
122  }
123 
124  /* ... and no object is related to us. */
125  for (const Object *o : Object::Iterate()) {
126  assert(o->town != this);
127  }
128 #endif /* WITH_ASSERT */
129 
130  /* Check no tile is related to us. */
131  for (TileIndex tile = 0; tile < Map::Size(); ++tile) {
132  switch (GetTileType(tile)) {
133  case MP_HOUSE:
134  assert(GetTownIndex(tile) != this->index);
135  break;
136 
137  case MP_ROAD:
138  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
139  break;
140 
141  case MP_TUNNELBRIDGE:
142  assert(!TestTownOwnsBridge(tile, this));
143  break;
144 
145  default:
146  break;
147  }
148  }
149 
150  /* Clear the persistent storage list. */
151  for (auto &psa : this->psa_list) {
152  delete psa;
153  }
154  this->psa_list.clear();
155 
160 }
161 
162 
168 {
169  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
171 
172  /* Give objects a new home! */
173  for (Object *o : Object::Iterate()) {
174  if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
175  }
176 }
177 
183 {
184  if (layout != TL_RANDOM) {
185  this->layout = layout;
186  return;
187  }
188 
189  this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
190 }
191 
196 /* static */ Town *Town::GetRandom()
197 {
198  if (Town::GetNumItems() == 0) return nullptr;
199  int num = RandomRange((uint16_t)Town::GetNumItems());
200  size_t index = MAX_UVALUE(size_t);
201 
202  while (num >= 0) {
203  num--;
204  index++;
205 
206  /* Make sure we have a valid town */
207  while (!Town::IsValidID(index)) {
208  index++;
209  assert(index < Town::GetPoolSize());
210  }
211  }
212 
213  return Town::Get(index);
214 }
215 
216 void Town::FillCachedName() const
217 {
218  this->cached_name = GetTownName(this);
219 }
220 
226 {
227  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
228 }
229 
230 /* Local */
231 static int _grow_town_result;
232 
233 /* The possible states of town growth. */
234 enum TownGrowthResult {
235  GROWTH_SUCCEED = -1,
236  GROWTH_SEARCH_STOPPED = 0
237 // GROWTH_SEARCH_RUNNING >= 1
238 };
239 
240 static bool TryBuildTownHouse(Town *t, TileIndex tile);
241 static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout);
242 
243 static void TownDrawHouseLift(const TileInfo *ti)
244 {
245  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
246 }
247 
248 typedef void TownDrawTileProc(const TileInfo *ti);
249 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
250  TownDrawHouseLift
251 };
252 
259 {
261 }
262 
267 static void DrawTile_Town(TileInfo *ti)
268 {
269  HouseID house_id = GetHouseType(ti->tile);
270 
271  if (house_id >= NEW_HOUSE_OFFSET) {
272  /* Houses don't necessarily need new graphics. If they don't have a
273  * spritegroup associated with them, then the sprite for the substitute
274  * house id is drawn instead. */
275  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
276  DrawNewHouseTile(ti, house_id);
277  return;
278  } else {
279  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
280  }
281  }
282 
283  /* Retrieve pointer to the draw town tile struct */
284  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
285 
287 
288  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
289 
290  /* If houses are invisible, do not draw the upper part */
291  if (IsInvisibilitySet(TO_HOUSES)) return;
292 
293  /* Add a house on top of the ground? */
294  SpriteID image = dcts->building.sprite;
295  if (image != 0) {
296  AddSortableSpriteToDraw(image, dcts->building.pal,
297  ti->x + dcts->subtile_x,
298  ti->y + dcts->subtile_y,
299  dcts->width,
300  dcts->height,
301  dcts->dz,
302  ti->z,
304  );
305 
306  if (IsTransparencySet(TO_HOUSES)) return;
307  }
308 
309  {
310  int proc = dcts->draw_proc - 1;
311 
312  if (proc >= 0) _town_draw_tile_procs[proc](ti);
313  }
314 }
315 
316 static int GetSlopePixelZ_Town(TileIndex tile, uint, uint, bool)
317 {
318  return GetTileMaxPixelZ(tile);
319 }
320 
327 {
328  HouseID hid = GetHouseType(tile);
329 
330  /* For NewGRF house tiles we might not be drawing a foundation. We need to
331  * account for this, as other structures should
332  * draw the wall of the foundation in this case.
333  */
334  if (hid >= NEW_HOUSE_OFFSET) {
335  const HouseSpec *hs = HouseSpec::Get(hid);
336  if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
337  uint32_t callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
338  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
339  }
340  }
341  return FlatteningFoundation(tileh);
342 }
343 
350 static void AnimateTile_Town(TileIndex tile)
351 {
352  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
353  AnimateNewHouseTile(tile);
354  return;
355  }
356 
357  if (TimerGameTick::counter & 3) return;
358 
359  /* If the house is not one with a lift anymore, then stop this animating.
360  * Not exactly sure when this happens, but probably when a house changes.
361  * Before this was just a return...so it'd leak animated tiles..
362  * That bug seems to have been here since day 1?? */
363  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
364  DeleteAnimatedTile(tile);
365  return;
366  }
367 
368  if (!LiftHasDestination(tile)) {
369  uint i;
370 
371  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
372  * This is due to the fact that the first floor is, in the graphics,
373  * the height of 2 'normal' floors.
374  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
375  do {
376  i = RandomRange(7);
377  } while (i == 1 || i * 6 == GetLiftPosition(tile));
378 
379  SetLiftDestination(tile, i);
380  }
381 
382  int pos = GetLiftPosition(tile);
383  int dest = GetLiftDestination(tile) * 6;
384  pos += (pos < dest) ? 1 : -1;
385  SetLiftPosition(tile, pos);
386 
387  if (pos == dest) {
388  HaltLift(tile);
389  DeleteAnimatedTile(tile);
390  }
391 
392  MarkTileDirtyByTile(tile);
393 }
394 
401 static bool IsCloseToTown(TileIndex tile, uint dist)
402 {
403  if (_town_kdtree.Count() == 0) return false;
404  Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
405  return DistanceManhattan(tile, t->xy) < dist;
406 }
407 
410 {
411  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
412 
413  if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
414 
415  SetDParam(0, this->index);
416  SetDParam(1, this->cache.population);
417  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_BASE,
418  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
419  STR_VIEWPORT_TOWN_TINY_WHITE);
420 
421  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
422 
424 }
425 
428 {
429  for (Town *t : Town::Iterate()) {
430  t->UpdateVirtCoord();
431  }
432 }
433 
436 {
437  for (Town *t : Town::Iterate()) {
438  t->cached_name.clear();
439  }
440 }
441 
447 static void ChangePopulation(Town *t, int mod)
448 {
449  t->cache.population += mod;
450  if (_generating_town) [[unlikely]] return;
451 
452  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
454 
455  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_POPULATION_CHANGE);
456 }
457 
463 {
464  uint32_t pop = 0;
465  for (const Town *t : Town::Iterate()) pop += t->cache.population;
466  return pop;
467 }
468 
476 static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
477 {
478  for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
479  const Station *st = *it;
480 
481  bool covers_area = st->TileIsInCatchment(tile);
482  if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
483  if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
484  if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
485 
486  if (covers_area && !st->CatchmentCoversTown(t->index)) {
487  it = t->stations_near.erase(it);
488  } else {
489  ++it;
490  }
491  }
492 }
493 
499 {
500  assert(IsTileType(tile, MP_HOUSE));
501 
502  /* Progress in construction stages */
504  if (GetHouseConstructionTick(tile) != 0) return;
505 
506  AnimateNewHouseConstruction(tile);
507 
508  if (IsHouseCompleted(tile)) {
509  /* Now that construction is complete, we can add the population of the
510  * building to the town. */
511  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
512  ResetHouseAge(tile);
513  }
514  MarkTileDirtyByTile(tile);
515 }
516 
522 {
523  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
524  if (flags & BUILDING_HAS_1_TILE) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 0));
525  if (flags & BUILDING_2_TILES_Y) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 1));
526  if (flags & BUILDING_2_TILES_X) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 0));
527  if (flags & BUILDING_HAS_4_TILES) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 1));
528 }
529 
538 static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
539 {
540  if (amount == 0) return;
541 
542  /* All production is halved during a recession (except for NewGRF-supplied town cargo). */
543  if (affected_by_recession && EconomyIsInRecession()) {
544  amount = (amount + 1) >> 1;
545  }
546 
547  /* Scale by cargo scale setting. */
548  amount = ScaleByCargoScale(amount, true);
549 
550  /* Actually generate cargo and update town statistics. */
551  t->supplied[ct].new_max += amount;
552  t->supplied[ct].new_act += MoveGoodsToStation(ct, amount, SourceType::Town, t->index, stations.GetStations());;
553 }
554 
562 static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
563 {
564  for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
565  uint32_t r = Random();
566  if (GB(r, 0, 8) < rate) {
567  CargoID cid = cs->Index();
568  uint amt = (GB(r, 0, 8) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR) / 8 + 1;
569 
570  TownGenerateCargo(t, cid, amt, stations, true);
571  }
572  }
573 }
574 
582 static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
583 {
584  for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
585  CargoID cid = cs->Index();
586  uint32_t r = Random();
587 
588  /* Make a bitmask with up to 32 bits set, one for each potential pax. */
589  int genmax = (rate + 7) / 8;
590  uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
591 
592  /* Mask random value by potential pax and count number of actual pax. */
593  uint amt = CountBits(r & genmask) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR;
594 
595  TownGenerateCargo(t, cid, amt, stations, true);
596  }
597 }
598 
605 static void TileLoop_Town(TileIndex tile)
606 {
607  HouseID house_id = GetHouseType(tile);
608 
609  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
610  * doesn't exist any more, so don't continue here. */
611  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
612 
613  if (!IsHouseCompleted(tile)) {
614  /* Construction is not completed, so we advance a construction stage. */
616  return;
617  }
618 
619  const HouseSpec *hs = HouseSpec::Get(house_id);
620 
621  /* If the lift has a destination, it is already an animated tile. */
622  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
623  house_id < NEW_HOUSE_OFFSET &&
624  !LiftHasDestination(tile) &&
625  Chance16(1, 2)) {
626  AddAnimatedTile(tile);
627  }
628 
629  Town *t = Town::GetByTile(tile);
630  uint32_t r = Random();
631 
632  StationFinder stations(TileArea(tile, 1, 1));
633 
635  for (uint i = 0; i < 256; i++) {
636  uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
637 
638  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
639 
640  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
641  if (!IsValidCargoID(cargo)) continue;
642 
643  uint amt = GB(callback, 0, 8);
644  if (amt == 0) continue;
645 
646  /* NewGRF-supplied town cargos are not affected by recessions. */
647  TownGenerateCargo(t, cargo, amt, stations, false);
648  }
649  } else {
651  case TCGM_ORIGINAL:
652  /* Original (quadratic) cargo generation algorithm */
655  break;
656 
657  case TCGM_BITCOUNT:
658  /* Binomial distribution per tick, by a series of coin flips */
659  /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
660  * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
661  if (GB(TimerGameTick::counter, 8, 2) == GB(tile.base(), 0, 2)) {
664  }
665  break;
666 
667  default:
668  NOT_REACHED();
669  }
670  }
671 
673 
674  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
676  CanDeleteHouse(tile) &&
677  GetHouseAge(tile) >= hs->minimum_life &&
678  --t->time_until_rebuild == 0) {
679  t->time_until_rebuild = GB(r, 16, 8) + 192;
680 
681  ClearTownHouse(t, tile);
682 
683  /* Rebuild with another house? */
684  if (GB(r, 24, 8) >= 12) {
685  /* If we are multi-tile houses, make sure to replace the house
686  * closest to city center. If we do not do this, houses tend to
687  * wander away from roads and other houses. */
688  if (hs->building_flags & BUILDING_HAS_2_TILES) {
689  /* House tiles are always the most north tile. Move the new
690  * house to the south if we are north of the city center. */
691  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
692  int x = Clamp(grid_pos.x, 0, 1);
693  int y = Clamp(grid_pos.y, 0, 1);
694 
695  if (hs->building_flags & TILE_SIZE_2x2) {
696  tile = TileAddXY(tile, x, y);
697  } else if (hs->building_flags & TILE_SIZE_1x2) {
698  tile = TileAddXY(tile, 0, y);
699  } else if (hs->building_flags & TILE_SIZE_2x1) {
700  tile = TileAddXY(tile, x, 0);
701  }
702  }
703 
704  TryBuildTownHouse(t, tile);
705  }
706  }
707 
708  cur_company.Restore();
709 }
710 
718 {
719  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
720  if (!CanDeleteHouse(tile)) return CMD_ERROR;
721 
722  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
723 
725  cost.AddCost(hs->GetRemovalCost());
726 
727  int rating = hs->remove_rating_decrease;
728  Town *t = Town::GetByTile(tile);
729 
731  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) &&
733  SetDParam(0, t->index);
734  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
735  }
736  }
737 
738  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
739  if (flags & DC_EXEC) {
740  ClearTownHouse(t, tile);
741  }
742 
743  return cost;
744 }
745 
746 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
747 {
748  HouseID house_id = GetHouseType(tile);
749  const HouseSpec *hs = HouseSpec::Get(house_id);
750  Town *t = Town::GetByTile(tile);
751 
753  for (uint i = 0; i < 256; i++) {
754  uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
755 
756  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
757 
758  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
759 
760  if (!IsValidCargoID(cargo)) continue;
761  produced[cargo]++;
762  }
763  } else {
764  if (hs->population > 0) {
766  produced[cs->Index()]++;
767  }
768  }
769  if (hs->mail_generation > 0) {
771  produced[cs->Index()]++;
772  }
773  }
774  }
775 }
776 
784 static void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
785 {
786  if (!IsValidCargoID(cargo) || amount == 0) return;
787  acceptance[cargo] += amount;
788  SetBit(always_accepted, cargo);
789 }
790 
791 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
792 {
793  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
794  CargoID accepts[lengthof(hs->accepts_cargo)];
795 
796  /* Set the initial accepted cargo types */
797  for (uint8_t i = 0; i < lengthof(accepts); i++) {
798  accepts[i] = hs->accepts_cargo[i];
799  }
800 
801  /* Check for custom accepted cargo types */
803  uint16_t callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
804  if (callback != CALLBACK_FAILED) {
805  /* Replace accepted cargo types with translated values from callback */
806  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
807  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
808  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
809  }
810  }
811 
812  /* Check for custom cargo acceptance */
814  uint16_t callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
815  if (callback != CALLBACK_FAILED) {
816  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
817  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
818  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
819  /* The 'S' bit indicates food instead of goods */
820  AddAcceptedCargoSetMask(GetCargoIDByLabel(CT_FOOD), GB(callback, 8, 4), acceptance, always_accepted);
821  } else {
822  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
823  }
824  return;
825  }
826  }
827 
828  /* No custom acceptance, so fill in with the default values */
829  for (uint8_t i = 0; i < lengthof(accepts); i++) {
830  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
831  }
832 }
833 
834 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
835 {
836  const HouseID house = GetHouseType(tile);
837  const HouseSpec *hs = HouseSpec::Get(house);
838  bool house_completed = IsHouseCompleted(tile);
839 
840  td->str = hs->building_name;
841 
842  uint16_t callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
843  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
844  if (callback_res > 0x400) {
846  } else {
847  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
848  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
849  td->str = new_name;
850  }
851  }
852  }
853 
854  if (!house_completed) {
855  td->dparam = td->str;
856  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
857  }
858 
859  if (hs->grf_prop.grffile != nullptr) {
860  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
861  td->grf = gc->GetName();
862  }
863 
864  td->owner[0] = OWNER_TOWN;
865 }
866 
867 static TrackStatus GetTileTrackStatus_Town(TileIndex, TransportType, uint, DiagDirection)
868 {
869  /* not used */
870  return 0;
871 }
872 
873 static void ChangeTileOwner_Town(TileIndex, Owner, Owner)
874 {
875  /* not used */
876 }
877 
878 static bool GrowTown(Town *t);
879 
884 static void TownTickHandler(Town *t)
885 {
886  if (HasBit(t->flags, TOWN_IS_GROWING)) {
887  int i = (int)t->grow_counter - 1;
888  if (i < 0) {
889  if (GrowTown(t)) {
890  i = t->growth_rate;
891  } else {
892  /* If growth failed wait a bit before retrying */
893  i = std::min<uint16_t>(t->growth_rate, Ticks::TOWN_GROWTH_TICKS - 1);
894  }
895  }
896  t->grow_counter = i;
897  }
898 }
899 
902 {
903  if (_game_mode == GM_EDITOR) return;
904 
905  for (Town *t : Town::Iterate()) {
906  TownTickHandler(t);
907  }
908 }
909 
916 {
917  if (IsRoadDepotTile(tile) || IsBayRoadStopTile(tile)) return ROAD_NONE;
918 
919  return GetAnyRoadBits(tile, RTT_ROAD, true);
920 }
921 
927 {
928  RoadType best_rt = ROADTYPE_ROAD;
929  const RoadTypeInfo *best = nullptr;
930  const uint16_t assume_max_speed = 50;
931 
932  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
933  if (RoadTypeIsTram(rt)) continue;
934 
935  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
936 
937  /* Unused road type. */
938  if (rti->label == 0) continue;
939 
940  /* Can town build this road. */
941  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
942 
943  /* Not yet introduced at this date. */
945 
946  if (best != nullptr) {
947  if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
948  }
949 
950  best_rt = rt;
951  best = rti;
952  }
953 
954  return best_rt;
955 }
956 
961 static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
962 {
963  const RoadTypeInfo *best = nullptr;
964  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
965  if (RoadTypeIsTram(rt)) continue;
966  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
967  if (rti->label == 0) continue; // Unused road type.
968  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue; // Town can't build this road type.
969 
970  if (best != nullptr && rti->introduction_date >= best->introduction_date) continue;
971  best = rti;
972  }
973 
974  if (best == nullptr) return INT32_MAX;
975  return best->introduction_date;
976 }
977 
983 {
984  auto min_date = GetTownRoadTypeFirstIntroductionDate();
985  if (min_date <= TimerGameCalendar::date) return true;
986 
987  if (min_date < INT32_MAX) {
988  SetDParam(0, min_date);
989  ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET_EXPLANATION, WL_CRITICAL);
990  } else {
991  ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL_EXPLANATION, WL_CRITICAL);
992  }
993  return false;
994 }
995 
1006 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
1007 {
1008  if (!IsValidTile(tile)) return false;
1009 
1010  /* Lookup table for the used diff values */
1011  const TileIndexDiff tid_lt[3] = {
1015  };
1016 
1017  dist_multi = (dist_multi + 1) * 4;
1018  for (uint pos = 4; pos < dist_multi; pos++) {
1019  /* Go (pos / 4) tiles to the left or the right */
1020  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
1021 
1022  /* Use the current tile as origin, or go one tile backwards */
1023  if (pos & 2) cur += tid_lt[2];
1024 
1025  /* Test for roadbit parallel to dir and facing towards the middle axis */
1026  if (IsValidTile(tile + cur) &&
1027  GetTownRoadBits(TileAdd(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
1028  }
1029  return false;
1030 }
1031 
1040 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
1041 {
1042  if (DistanceFromEdge(tile) == 0) return false;
1043 
1044  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
1045  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
1046 
1047  /* Check if there already is a road at this point? */
1048  if (GetTownRoadBits(tile) == ROAD_NONE) {
1049  /* No, try if we are able to build a road piece there.
1050  * If that fails clear the land, and if that fails exit.
1051  * This is to make sure that we can build a road here later. */
1052  RoadType rt = GetTownRoadType();
1053  if (Command<CMD_BUILD_ROAD>::Do(DC_AUTO | DC_NO_WATER, tile, (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X, rt, DRD_NONE, 0).Failed() &&
1055  return false;
1056  }
1057  }
1058 
1059  Slope cur_slope = _settings_game.construction.build_on_slopes ? std::get<0>(GetFoundationSlope(tile)) : GetTileSlope(tile);
1060  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
1061  if (cur_slope == SLOPE_FLAT) return ret;
1062 
1063  /* If the tile is not a slope in the right direction, then
1064  * maybe terraform some. */
1065  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
1066  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
1067  if (Chance16(1, 8)) {
1068  CommandCost res = CMD_ERROR;
1069  if (!_generating_world && Chance16(1, 10)) {
1070  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
1072  tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, false));
1073  }
1074  if (res.Failed() && Chance16(1, 3)) {
1075  /* We can consider building on the slope, though. */
1076  return ret;
1077  }
1078  }
1079  return false;
1080  }
1081  return ret;
1082 }
1083 
1084 static bool TerraformTownTile(TileIndex tile, Slope edges, bool dir)
1085 {
1086  assert(tile < Map::Size());
1087 
1088  CommandCost r = std::get<0>(Command<CMD_TERRAFORM_LAND>::Do(DC_AUTO | DC_NO_WATER, tile, edges, dir));
1089  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
1091  return true;
1092 }
1093 
1094 static void LevelTownLand(TileIndex tile)
1095 {
1096  assert(tile < Map::Size());
1097 
1098  /* Don't terraform if land is plain or if there's a house there. */
1099  if (IsTileType(tile, MP_HOUSE)) return;
1100  Slope tileh = GetTileSlope(tile);
1101  if (tileh == SLOPE_FLAT) return;
1102 
1103  /* First try up, then down */
1104  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, true)) {
1105  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, false);
1106  }
1107 }
1108 
1118 {
1119  /* align the grid to the downtown */
1120  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1121  RoadBits rcmd = ROAD_NONE;
1122 
1123  switch (t->layout) {
1124  default: NOT_REACHED();
1125 
1126  case TL_2X2_GRID:
1127  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1128  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1129  break;
1130 
1131  case TL_3X3_GRID:
1132  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1133  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1134  break;
1135  }
1136 
1137  /* Optimise only X-junctions */
1138  if (rcmd != ROAD_ALL) return rcmd;
1139 
1140  RoadBits rb_template;
1141 
1142  switch (GetTileSlope(tile)) {
1143  default: rb_template = ROAD_ALL; break;
1144  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1145  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1146  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1147  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1148  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1149  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1150  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1151  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1152  case SLOPE_STEEP_W:
1153  case SLOPE_STEEP_S:
1154  case SLOPE_STEEP_E:
1155  case SLOPE_STEEP_N:
1156  rb_template = ROAD_NONE;
1157  break;
1158  }
1159 
1160  /* Stop if the template is compatible to the growth dir */
1161  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1162  /* If not generate a straight road in the direction of the growth */
1164 }
1165 
1177 {
1178  /* We can't look further than that. */
1179  if (DistanceFromEdge(tile) == 0) return false;
1180 
1181  uint counter = 0; // counts the house neighbor tiles
1182 
1183  /* Check the tiles E,N,W and S of the current tile for houses */
1184  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1185  /* Count both void and house tiles for checking whether there
1186  * are enough houses in the area. This to make it likely that
1187  * houses get build up to the edge of the map. */
1188  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1189  case MP_HOUSE:
1190  case MP_VOID:
1191  counter++;
1192  break;
1193 
1194  default:
1195  break;
1196  }
1197 
1198  /* If there are enough neighbors stop here */
1199  if (counter >= 3) {
1200  if (TryBuildTownHouse(t, tile)) {
1201  _grow_town_result = GROWTH_SUCCEED;
1202  return true;
1203  }
1204  return false;
1205  }
1206  }
1207  return false;
1208 }
1209 
1218 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1219 {
1220  RoadType rt = GetTownRoadType();
1221  if (Command<CMD_BUILD_ROAD>::Do(DC_EXEC | DC_AUTO | DC_NO_WATER, tile, rcmd, rt, DRD_NONE, t->index).Succeeded()) {
1222  _grow_town_result = GROWTH_SUCCEED;
1223  return true;
1224  }
1225  return false;
1226 }
1227 
1237 static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
1238 {
1239  const TileIndexDiff delta = TileOffsByDiagDir(road_dir); // +1 tile in the direction of the road
1240  TileIndex next_tile = tile + delta; // The tile beyond which must be connectable to the target tile
1241  RoadBits rcmd = DiagDirToRoadBits(ReverseDiagDir(road_dir));
1242  RoadType rt = GetTownRoadType();
1243 
1244  /* Before we try anything, make sure the tile is on the map and not the void. */
1245  if (!IsValidTile(next_tile)) return false;
1246 
1247  /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1248  if (IsTileType(next_tile, MP_TUNNELBRIDGE)) {
1249  return GetTunnelBridgeTransportType(next_tile) == TRANSPORT_ROAD && GetTunnelBridgeDirection(next_tile) == road_dir;
1250  }
1251 
1252  /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1253  if (IsTileType(next_tile, MP_STATION)) {
1254  /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1255  if (IsDriveThroughStopTile(next_tile)) return GetDriveThroughStopAxis(next_tile) == DiagDirToAxis(road_dir);
1256  if (IsBayRoadStopTile(next_tile)) return GetBayRoadStopDir(next_tile) == ReverseDiagDir(road_dir);
1257  return false;
1258  }
1259 
1260  /* If the next tile is a road depot, allow if it's facing the right way. */
1261  if (IsTileType(next_tile, MP_ROAD)) {
1262  return IsRoadDepot(next_tile) && GetRoadDepotDirection(next_tile) == ReverseDiagDir(road_dir);
1263  }
1264 
1265  /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1266  * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1267  if (IsTileType(next_tile, MP_RAILWAY) && !_settings_game.economy.allow_town_level_crossings) return false;
1268 
1269  /* If a road tile can be built, the construction is allowed. */
1270  return Command<CMD_BUILD_ROAD>::Do(DC_AUTO | DC_NO_WATER, next_tile, rcmd, rt, DRD_NONE, t->index).Succeeded();
1271 }
1272 
1279 static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data)
1280 {
1281  /* Don't look into the void. */
1282  if (!IsValidTile(tile)) return false;
1283 
1284  /* Only consider bridge head tiles. */
1285  if (!IsBridgeTile(tile)) return false;
1286 
1287  /* Only consider road bridges. */
1288  if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return false;
1289 
1290  /* If the bridge is facing the same direction as the proposed bridge, we've found a redundant bridge. */
1291  return (GetTileSlope(tile) & InclinedSlope(ReverseDiagDir(*(DiagDirection *)user_data)));
1292 }
1293 
1304 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1305 {
1306  assert(bridge_dir < DIAGDIR_END);
1307 
1308  const Slope slope = GetTileSlope(tile);
1309 
1310  /* Make sure the direction is compatible with the slope.
1311  * Well we check if the slope has an up bit set in the
1312  * reverse direction. */
1313  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1314 
1315  /* Assure that the bridge is connectable to the start side */
1316  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1317 
1318  /* We are in the right direction */
1319  uint bridge_length = 0; // This value stores the length of the possible bridge
1320  TileIndex bridge_tile = tile; // Used to store the other waterside
1321 
1322  const TileIndexDiff delta = TileOffsByDiagDir(bridge_dir);
1323 
1324  /* To prevent really small towns from building disproportionately
1325  * long bridges, make the max a function of its population. */
1326  const uint TOWN_BRIDGE_LENGTH_CAP = 11;
1327  uint base_bridge_length = 5;
1328  uint max_bridge_length = std::min(t->cache.population / 1000 + base_bridge_length, TOWN_BRIDGE_LENGTH_CAP);
1329 
1330  if (slope == SLOPE_FLAT) {
1331  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1332  do {
1333  if (bridge_length++ >= base_bridge_length) {
1334  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1335  return false;
1336  }
1337  bridge_tile += delta;
1338  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1339  } else {
1340  do {
1341  if (bridge_length++ >= max_bridge_length) {
1342  /* Ensure the bridge is not longer than the max allowed length. */
1343  return false;
1344  }
1345  bridge_tile += delta;
1346  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1347  }
1348 
1349  /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1350  if (bridge_length == 1) return false;
1351 
1352  /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1353  if (!CanRoadContinueIntoNextTile(t, bridge_tile, bridge_dir)) return false;
1354 
1355  /* If another parallel bridge exists nearby, this one would be redundant and shouldn't be built. We don't care about flat bridges. */
1356  TileIndex search = tile;
1357  DiagDirection direction_to_match = bridge_dir;
1358  if (slope != SLOPE_FLAT && CircularTileSearch(&search, bridge_length, 0, 0, RedundantBridgeExistsNearby, &direction_to_match)) return false;
1359 
1360  for (uint8_t times = 0; times <= 22; times++) {
1361  uint8_t bridge_type = RandomRange(MAX_BRIDGES - 1);
1362 
1363  /* Can we actually build the bridge? */
1364  RoadType rt = GetTownRoadType();
1365  if (Command<CMD_BUILD_BRIDGE>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_BRIDGE>()), tile, bridge_tile, TRANSPORT_ROAD, bridge_type, rt).Succeeded()) {
1366  Command<CMD_BUILD_BRIDGE>::Do(DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_BRIDGE>()), tile, bridge_tile, TRANSPORT_ROAD, bridge_type, rt);
1367  _grow_town_result = GROWTH_SUCCEED;
1368  return true;
1369  }
1370  }
1371  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1372  return false;
1373 }
1374 
1385 static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
1386 {
1387  assert(tunnel_dir < DIAGDIR_END);
1388 
1389  Slope slope = GetTileSlope(tile);
1390 
1391  /* Only consider building a tunnel if the starting tile is sloped properly. */
1392  if (slope != InclinedSlope(tunnel_dir)) return false;
1393 
1394  /* Assure that the tunnel is connectable to the start side */
1395  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(tunnel_dir))) & DiagDirToRoadBits(tunnel_dir))) return false;
1396 
1397  const TileIndexDiff delta = TileOffsByDiagDir(tunnel_dir);
1398  int max_tunnel_length = 0;
1399 
1400  /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1401  if (CanRoadContinueIntoNextTile(t, tile, tunnel_dir)) {
1402  /* Only tunnel under a mountain if the slope is continuous for at least 4 tiles. We want tunneling to be a last resort for large hills. */
1403  TileIndex slope_tile = tile;
1404  for (uint8_t tiles = 0; tiles < 4; tiles++) {
1405  if (!IsValidTile(slope_tile)) return false;
1406  slope = GetTileSlope(slope_tile);
1407  if (slope != InclinedSlope(tunnel_dir) && !IsSteepSlope(slope) && !IsSlopeWithOneCornerRaised(slope)) return false;
1408  slope_tile += delta;
1409  }
1410 
1411  /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which neccesitates tunneling. */
1412  max_tunnel_length = (t->cache.population / 1000) + 7;
1413  } else {
1414  /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1415  max_tunnel_length = 5;
1416  }
1417 
1418  uint8_t tunnel_length = 0;
1419  TileIndex tunnel_tile = tile; // Iteratator to store the other end tile of the tunnel.
1420 
1421  /* Find the end tile of the tunnel for length and continuation checks. */
1422  do {
1423  if (tunnel_length++ >= max_tunnel_length) return false;
1424  tunnel_tile += delta;
1425  /* The tunnel ends when start and end tiles are the same height. */
1426  } while (IsValidTile(tunnel_tile) && GetTileZ(tile) != GetTileZ(tunnel_tile));
1427 
1428  /* Don't allow a tunnel where the start and end tiles are adjacent. */
1429  if (tunnel_length == 1) return false;
1430 
1431  /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1432  if (!CanRoadContinueIntoNextTile(t, tunnel_tile, tunnel_dir)) return false;
1433 
1434  /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1435  RoadType rt = GetTownRoadType();
1436  if (Command<CMD_BUILD_TUNNEL>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_TUNNEL>()), tile, TRANSPORT_ROAD, rt).Succeeded()) {
1437  Command<CMD_BUILD_TUNNEL>::Do(DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_TUNNEL>()), tile, TRANSPORT_ROAD, rt);
1438  _grow_town_result = GROWTH_SUCCEED;
1439  return true;
1440  }
1441 
1442  return false;
1443 }
1444 
1451 static inline bool RoadTypesAllowHouseHere(TileIndex t)
1452 {
1453  static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1454  bool allow = false;
1455 
1456  for (const auto &ptr : tiles) {
1457  TileIndex cur_tile = t + ToTileIndexDiff(ptr);
1458  if (!IsValidTile(cur_tile)) continue;
1459 
1460  if (!(IsTileType(cur_tile, MP_ROAD) || IsAnyRoadStopTile(cur_tile))) continue;
1461  allow = true;
1462 
1463  RoadType road_rt = GetRoadTypeRoad(cur_tile);
1464  RoadType tram_rt = GetRoadTypeTram(cur_tile);
1465  if (road_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(road_rt)->flags, ROTF_NO_HOUSES)) return true;
1466  if (tram_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(tram_rt)->flags, ROTF_NO_HOUSES)) return true;
1467  }
1468 
1469  /* If no road was found surrounding the tile we can allow building the house since there is
1470  * nothing which forbids it, if a road was found but the execution reached this point, then
1471  * all the found roads don't allow houses to be built */
1472  return !allow;
1473 }
1474 
1479 static bool TownCanGrowRoad(TileIndex tile)
1480 {
1481  if (!IsTileType(tile, MP_ROAD)) return true;
1482 
1483  /* Allow extending on roadtypes which can be built by town, or if the road type matches the type the town will build. */
1484  RoadType rt = GetRoadTypeRoad(tile);
1485  return HasBit(GetRoadTypeInfo(rt)->flags, ROTF_TOWN_BUILD) || GetTownRoadType() == rt;
1486 }
1487 
1492 static inline bool TownAllowedToBuildRoads()
1493 {
1494  return _settings_game.economy.allow_town_roads || _generating_world || _game_mode == GM_EDITOR;
1495 }
1496 
1514 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1515 {
1516  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1517  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1518 
1519  assert(tile < Map::Size());
1520 
1521  if (cur_rb == ROAD_NONE) {
1522  /* Tile has no road. First reset the status counter
1523  * to say that this is the last iteration. */
1524  _grow_town_result = GROWTH_SEARCH_STOPPED;
1525 
1526  if (!TownAllowedToBuildRoads()) return;
1528 
1529  /* Remove hills etc */
1530  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1531 
1532  /* Is a road allowed here? */
1533  switch (t1->layout) {
1534  default: NOT_REACHED();
1535 
1536  case TL_3X3_GRID:
1537  case TL_2X2_GRID:
1538  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1539  if (rcmd == ROAD_NONE) return;
1540  break;
1541 
1542  case TL_BETTER_ROADS:
1543  case TL_ORIGINAL:
1544  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1545 
1546  DiagDirection source_dir = ReverseDiagDir(target_dir);
1547 
1548  if (Chance16(1, 4)) {
1549  /* Randomize a new target dir */
1550  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1551  }
1552 
1553  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1554  /* A road is not allowed to continue the randomized road,
1555  * return if the road we're trying to build is curved. */
1556  if (target_dir != ReverseDiagDir(source_dir)) return;
1557 
1558  /* Return if neither side of the new road is a house */
1561  return;
1562  }
1563 
1564  /* That means that the road is only allowed if there is a house
1565  * at any side of the new road. */
1566  }
1567 
1568  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1569  break;
1570  }
1571 
1572  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1573  if (!TownCanGrowRoad(tile)) return;
1574 
1575  /* Continue building on a partial road.
1576  * Should be always OK, so we only generate
1577  * the fitting RoadBits */
1578  _grow_town_result = GROWTH_SEARCH_STOPPED;
1579 
1580  if (!TownAllowedToBuildRoads()) return;
1581 
1582  switch (t1->layout) {
1583  default: NOT_REACHED();
1584 
1585  case TL_3X3_GRID:
1586  case TL_2X2_GRID:
1587  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1588  break;
1589 
1590  case TL_BETTER_ROADS:
1591  case TL_ORIGINAL:
1592  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1593  break;
1594  }
1595  } else {
1596  bool allow_house = true; // Value which decides if we want to construct a house
1597 
1598  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1599  * it is the starting tile. Half the time, we stay on this side then.*/
1600  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1601  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1602  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1603  }
1604  return;
1605  }
1606 
1607  /* Possibly extend the road in a direction.
1608  * Randomize a direction and if it has a road, bail out. */
1609  target_dir = RandomDiagDir();
1610  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1611  TileIndex house_tile; // position of a possible house
1612 
1613  if (cur_rb & target_rb) {
1614  /* If it's a road turn possibly build a house in a corner.
1615  * Use intersection with straight road as an indicator
1616  * that we randomed corner house position.
1617  * A turn (and we check for that later) always has only
1618  * one common bit with a straight road so it has the same
1619  * chance to be chosen as the house on the side of a road.
1620  */
1621  if ((cur_rb & ROAD_X) != target_rb) return;
1622 
1623  /* Check whether it is a turn and if so determine
1624  * position of the corner tile */
1625  switch (cur_rb) {
1626  case ROAD_N:
1627  house_tile = TileAddByDir(tile, DIR_S);
1628  break;
1629  case ROAD_S:
1630  house_tile = TileAddByDir(tile, DIR_N);
1631  break;
1632  case ROAD_E:
1633  house_tile = TileAddByDir(tile, DIR_W);
1634  break;
1635  case ROAD_W:
1636  house_tile = TileAddByDir(tile, DIR_E);
1637  break;
1638  default:
1639  return; // not a turn
1640  }
1641  target_dir = DIAGDIR_END;
1642  } else {
1643  house_tile = TileAddByDiagDir(tile, target_dir);
1644  }
1645 
1646  /* Don't walk into water. */
1647  if (HasTileWaterGround(house_tile)) return;
1648 
1649  if (!IsValidTile(house_tile)) return;
1650 
1651  if (target_dir != DIAGDIR_END && TownAllowedToBuildRoads()) {
1652  switch (t1->layout) {
1653  default: NOT_REACHED();
1654 
1655  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1656  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1657  [[fallthrough]];
1658 
1659  case TL_2X2_GRID:
1660  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1661  allow_house = (rcmd & target_rb) == ROAD_NONE;
1662  break;
1663 
1664  case TL_BETTER_ROADS: // Use original afterwards!
1665  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1666  [[fallthrough]];
1667 
1668  case TL_ORIGINAL:
1669  /* Allow a house at the edge. 60% chance or
1670  * always ok if no road allowed. */
1671  rcmd = target_rb;
1672  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1673  break;
1674  }
1675  }
1676 
1677  allow_house &= RoadTypesAllowHouseHere(house_tile);
1678 
1679  if (allow_house) {
1680  /* Build a house, but not if there already is a house there. */
1681  if (!IsTileType(house_tile, MP_HOUSE)) {
1682  /* Level the land if possible */
1683  if (Chance16(1, 6)) LevelTownLand(house_tile);
1684 
1685  /* And build a house.
1686  * Set result to -1 if we managed to build it. */
1687  if (TryBuildTownHouse(t1, house_tile)) {
1688  _grow_town_result = GROWTH_SUCCEED;
1689  }
1690  }
1691  return;
1692  }
1693 
1694  if (!TownCanGrowRoad(tile)) return;
1695 
1696  _grow_town_result = GROWTH_SEARCH_STOPPED;
1697  }
1698 
1699  /* Return if a water tile */
1700  if (HasTileWaterGround(tile)) return;
1701 
1702  /* Make the roads look nicer */
1703  rcmd = CleanUpRoadBits(tile, rcmd);
1704  if (rcmd == ROAD_NONE) return;
1705 
1706  /* Only use the target direction for bridges and tunnels to ensure they're connected.
1707  * The target_dir is as computed previously according to town layout, so
1708  * it will match it perfectly. */
1709  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1710  if (GrowTownWithTunnel(t1, tile, target_dir)) return;
1711 
1712  GrowTownWithRoad(t1, tile, rcmd);
1713 }
1714 
1722 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1723 {
1724  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1725  if (!IsValidTile(target_tile)) return false;
1726  if (HasTileWaterGround(target_tile)) return false;
1727 
1728  RoadBits target_rb = GetTownRoadBits(target_tile);
1729  if (TownAllowedToBuildRoads()) {
1730  /* Check whether a road connection exists or can be build. */
1731  switch (GetTileType(target_tile)) {
1732  case MP_ROAD:
1733  return target_rb != ROAD_NONE;
1734 
1735  case MP_STATION:
1736  return IsDriveThroughStopTile(target_tile);
1737 
1738  case MP_TUNNELBRIDGE:
1739  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1740 
1741  case MP_HOUSE:
1742  case MP_INDUSTRY:
1743  case MP_OBJECT:
1744  return false;
1745 
1746  default:
1747  /* Checked for void and water earlier */
1748  return true;
1749  }
1750  } else {
1751  /* Check whether a road connection already exists,
1752  * and it leads somewhere else. */
1753  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1754  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1755  }
1756 }
1757 
1764 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1765 {
1766  /* Special case.
1767  * @see GrowTownInTile Check the else if
1768  */
1769  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1770 
1771  assert(tile < Map::Size());
1772 
1773  /* Number of times to search.
1774  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1775  * them a little handicap. */
1776  switch (t->layout) {
1777  case TL_BETTER_ROADS:
1778  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1779  break;
1780 
1781  case TL_3X3_GRID:
1782  case TL_2X2_GRID:
1783  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1784  break;
1785 
1786  default:
1787  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1788  break;
1789  }
1790 
1791  do {
1792  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1793 
1794  /* Try to grow the town from this point */
1795  GrowTownInTile(&tile, cur_rb, target_dir, t);
1796  if (_grow_town_result == GROWTH_SUCCEED) return true;
1797 
1798  /* Exclude the source position from the bitmask
1799  * and return if no more road blocks available */
1800  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1801  if (cur_rb == ROAD_NONE) return false;
1802 
1803  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1804  /* Only build in the direction away from the tunnel or bridge. */
1805  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1806  } else {
1807  /* Select a random bit from the blockmask, walk a step
1808  * and continue the search from there. */
1809  do {
1810  if (cur_rb == ROAD_NONE) return false;
1811  RoadBits target_bits;
1812  do {
1813  target_dir = RandomDiagDir();
1814  target_bits = DiagDirToRoadBits(target_dir);
1815  } while (!(cur_rb & target_bits));
1816  cur_rb &= ~target_bits;
1817  } while (!CanFollowRoad(tile, target_dir));
1818  }
1819  tile = TileAddByDiagDir(tile, target_dir);
1820 
1821  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, RTT_ROAD)) {
1822  /* Don't allow building over roads of other cities */
1823  if (IsRoadOwner(tile, RTT_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1824  return false;
1825  } else if (IsRoadOwner(tile, RTT_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1826  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1827  * owner :) (happy happy happy road now) */
1828  SetRoadOwner(tile, RTT_ROAD, OWNER_TOWN);
1829  SetTownIndex(tile, t->index);
1830  }
1831  }
1832 
1833  /* Max number of times is checked. */
1834  } while (--_grow_town_result >= 0);
1835 
1836  return false;
1837 }
1838 
1847 {
1848  uint32_t r = Random();
1849  uint a = GB(r, 0, 2);
1850  uint b = GB(r, 8, 2);
1851  if (a == b) b ^= 2;
1852  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1853 }
1854 
1860 static bool GrowTown(Town *t)
1861 {
1862  static const TileIndexDiffC _town_coord_mod[] = {
1863  {-1, 0},
1864  { 1, 1},
1865  { 1, -1},
1866  {-1, -1},
1867  {-1, 0},
1868  { 0, 2},
1869  { 2, 0},
1870  { 0, -2},
1871  {-1, -1},
1872  {-2, 2},
1873  { 2, 2},
1874  { 2, -2},
1875  { 0, 0}
1876  };
1877 
1878  /* Current "company" is a town */
1880 
1881  TileIndex tile = t->xy; // The tile we are working with ATM
1882 
1883  /* Find a road that we can base the construction on. */
1884  for (const auto &ptr : _town_coord_mod) {
1885  if (GetTownRoadBits(tile) != ROAD_NONE) {
1886  bool success = GrowTownAtRoad(t, tile);
1887  cur_company.Restore();
1888  return success;
1889  }
1890  tile = TileAdd(tile, ToTileIndexDiff(ptr));
1891  }
1892 
1893  /* No road available, try to build a random road block by
1894  * clearing some land and then building a road there. */
1895  if (TownAllowedToBuildRoads()) {
1896  tile = t->xy;
1897  for (const auto &ptr : _town_coord_mod) {
1898  /* Only work with plain land that not already has a house */
1899  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1900  if (Command<CMD_LANDSCAPE_CLEAR>::Do(DC_AUTO | DC_NO_WATER, tile).Succeeded()) {
1901  RoadType rt = GetTownRoadType();
1903  cur_company.Restore();
1904  return true;
1905  }
1906  }
1907  tile = TileAdd(tile, ToTileIndexDiff(ptr));
1908  }
1909  }
1910 
1911  cur_company.Restore();
1912  return false;
1913 }
1914 
1920 {
1921  static const std::array<std::array<uint32_t, HZB_END>, 23> _town_squared_town_zone_radius_data = {{
1922  { 4, 0, 0, 0, 0}, // 0
1923  { 16, 0, 0, 0, 0},
1924  { 25, 0, 0, 0, 0},
1925  { 36, 0, 0, 0, 0},
1926  { 49, 0, 4, 0, 0},
1927  { 64, 0, 4, 0, 0}, // 20
1928  { 64, 0, 9, 0, 1},
1929  { 64, 0, 9, 0, 4},
1930  { 64, 0, 16, 0, 4},
1931  { 81, 0, 16, 0, 4},
1932  { 81, 0, 16, 0, 4}, // 40
1933  { 81, 0, 25, 0, 9},
1934  { 81, 36, 25, 0, 9},
1935  { 81, 36, 25, 16, 9},
1936  { 81, 49, 0, 25, 9},
1937  { 81, 64, 0, 25, 9}, // 60
1938  { 81, 64, 0, 36, 9},
1939  { 81, 64, 0, 36, 16},
1940  {100, 81, 0, 49, 16},
1941  {100, 81, 0, 49, 25},
1942  {121, 81, 0, 49, 25}, // 80
1943  {121, 81, 0, 49, 25},
1944  {121, 81, 0, 49, 36}, // 88
1945  }};
1946 
1947  if (t->cache.num_houses < std::size(_town_squared_town_zone_radius_data) * 4) {
1948  t->cache.squared_town_zone_radius = _town_squared_town_zone_radius_data[t->cache.num_houses / 4];
1949  } else {
1950  int mass = t->cache.num_houses / 8;
1951  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1952  * The offsets are to make sure the radii do not decrease in size when going from the table
1953  * to the calculated value.*/
1954  t->cache.squared_town_zone_radius[HZB_TOWN_EDGE] = mass * 15 - 40;
1955  t->cache.squared_town_zone_radius[HZB_TOWN_OUTSKIRT] = mass * 9 - 15;
1956  t->cache.squared_town_zone_radius[HZB_TOWN_OUTER_SUBURB] = 0;
1957  t->cache.squared_town_zone_radius[HZB_TOWN_INNER_SUBURB] = mass * 5 - 5;
1958  t->cache.squared_town_zone_radius[HZB_TOWN_CENTRE] = mass * 3 + 5;
1959  }
1960 }
1961 
1967 {
1969  t->supplied[cs->Index()].old_max = ScaleByCargoScale(t->cache.population >> 3, true);
1970  }
1972  t->supplied[cs->Index()].old_max = ScaleByCargoScale(t->cache.population >> 4, true);
1973  }
1974 }
1975 
1976 static void UpdateTownGrowthRate(Town *t);
1977 static void UpdateTownGrowth(Town *t);
1978 
1990 static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1991 {
1992  AutoRestoreBackup backup(_generating_town, true);
1993 
1994  t->xy = tile;
1995  t->cache.num_houses = 0;
1996  t->time_until_rebuild = 10;
1997  UpdateTownRadius(t);
1998  t->flags = 0;
1999  t->cache.population = 0;
2001  /* Spread growth across ticks so even if there are many
2002  * similar towns they're unlikely to grow all in one tick */
2004  t->growth_rate = TownTicksToGameTicks(250);
2005  t->show_zone = false;
2006 
2007  _town_kdtree.Insert(t->index);
2008 
2009  /* Set the default cargo requirement for town growth */
2011  case LT_ARCTIC:
2013  break;
2014 
2015  case LT_TROPIC:
2018  break;
2019  }
2020 
2021  t->fund_buildings_months = 0;
2022 
2023  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2024 
2025  t->have_ratings = 0;
2027  t->exclusive_counter = 0;
2028  t->statues = 0;
2029 
2030  {
2032  t->townnamegrfid = tnp.grfid;
2033  t->townnametype = tnp.type;
2034  }
2035  t->townnameparts = townnameparts;
2036 
2037  t->InitializeLayout(layout);
2038 
2039  t->larger_town = city;
2040 
2041  int x = (int)size * 16 + 3;
2042  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
2043  /* Don't create huge cities when founding town in-game */
2044  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
2045 
2046  t->cache.num_houses += x;
2047  UpdateTownRadius(t);
2048 
2049  int i = x * 4;
2050  do {
2051  GrowTown(t);
2052  } while (--i);
2053 
2054  t->UpdateVirtCoord();
2055  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
2056 
2057  t->cache.num_houses -= x;
2058  UpdateTownRadius(t);
2060  UpdateTownMaxPass(t);
2062 }
2063 
2070 {
2071  /* Check if too close to the edge of map */
2072  if (DistanceFromEdge(tile) < 12) {
2073  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
2074  }
2075 
2076  /* Check distance to all other towns. */
2077  if (IsCloseToTown(tile, 20)) {
2078  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
2079  }
2080 
2081  /* Can only build on clear flat areas, possibly with trees. */
2082  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
2083  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2084  }
2085 
2086  return CommandCost(EXPENSES_OTHER);
2087 }
2088 
2094 static bool IsUniqueTownName(const std::string &name)
2095 {
2096  for (const Town *t : Town::Iterate()) {
2097  if (!t->name.empty() && t->name == name) return false;
2098  }
2099 
2100  return true;
2101 }
2102 
2115 std::tuple<CommandCost, Money, TownID> CmdFoundTown(DoCommandFlag flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
2116 {
2118 
2119  if (size >= TSZ_END) return { CMD_ERROR, 0, INVALID_TOWN };
2120  if (layout >= NUM_TLS) return { CMD_ERROR, 0, INVALID_TOWN };
2121 
2122  /* Some things are allowed only in the scenario editor and for game scripts. */
2123  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
2124  if (_settings_game.economy.found_town == TF_FORBIDDEN) return { CMD_ERROR, 0, INVALID_TOWN };
2125  if (size == TSZ_LARGE) return { CMD_ERROR, 0, INVALID_TOWN };
2126  if (random_location) return { CMD_ERROR, 0, INVALID_TOWN };
2128  return { CMD_ERROR, 0, INVALID_TOWN };
2129  }
2130  } else if (_current_company == OWNER_DEITY && random_location) {
2131  /* Random parameter is not allowed for Game Scripts. */
2132  return { CMD_ERROR, 0, INVALID_TOWN };
2133  }
2134 
2135  if (text.empty()) {
2136  /* If supplied name is empty, townnameparts has to generate unique automatic name */
2137  if (!VerifyTownName(townnameparts, &par)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, INVALID_TOWN };
2138  } else {
2139  /* If name is not empty, it has to be unique custom name */
2140  if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return { CMD_ERROR, 0, INVALID_TOWN };
2141  if (!IsUniqueTownName(text)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, INVALID_TOWN };
2142  }
2143 
2144  /* Allocate town struct */
2145  if (!Town::CanAllocateItem()) return { CommandCost(STR_ERROR_TOO_MANY_TOWNS), 0, INVALID_TOWN };
2146 
2147  if (!random_location) {
2148  CommandCost ret = TownCanBePlacedHere(tile);
2149  if (ret.Failed()) return { ret, 0, INVALID_TOWN };
2150  }
2151 
2152  static const uint8_t price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
2153  /* multidimensional arrays have to have defined length of non-first dimension */
2154  static_assert(lengthof(price_mult[0]) == 4);
2155 
2156  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
2157  uint8_t mult = price_mult[city][size];
2158 
2159  cost.MultiplyCost(mult);
2160 
2161  /* Create the town */
2162  TownID new_town = INVALID_TOWN;
2163  if (flags & DC_EXEC) {
2164  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
2165  return { CommandCost(EXPENSES_OTHER), cost.GetCost(), INVALID_TOWN };
2166  }
2167 
2168  Backup<bool> old_generating_world(_generating_world, true);
2170  Town *t;
2171  if (random_location) {
2172  t = CreateRandomTown(20, townnameparts, size, city, layout);
2173  } else {
2174  t = new Town(tile);
2175  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
2176  }
2177 
2179  old_generating_world.Restore();
2180 
2181  if (t == nullptr) return { CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN), 0, INVALID_TOWN };
2182 
2183  new_town = t->index;
2184 
2185  if (!text.empty()) {
2186  t->name = text;
2187  t->UpdateVirtCoord();
2188  }
2189 
2190  if (_game_mode != GM_EDITOR) {
2191  /* 't' can't be nullptr since 'random' is false outside scenedit */
2192  assert(!random_location);
2193 
2194  if (_current_company == OWNER_DEITY) {
2195  SetDParam(0, t->index);
2196  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
2197  } else {
2199  std::string company_name = GetString(STR_COMPANY_NAME);
2200 
2201  SetDParamStr(0, company_name);
2202  SetDParam(1, t->index);
2203 
2204  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile);
2205  }
2206  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
2207  Game::NewEvent(new ScriptEventTownFounded(t->index));
2208  }
2209  }
2210  return { cost, 0, new_town };
2211 }
2212 
2223 {
2224  switch (layout) {
2225  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
2226  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
2227  default: return tile;
2228  }
2229 }
2230 
2240 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
2241 {
2242  switch (layout) {
2243  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2244  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2245  default: return true;
2246  }
2247 }
2248 
2252 struct SpotData {
2254  uint max_dist;
2256 };
2257 
2274 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
2275 {
2276  SpotData *sp = (SpotData*)user_data;
2277  uint dist = GetClosestWaterDistance(tile, true);
2278 
2279  if (IsTileType(tile, MP_CLEAR) &&
2280  IsTileFlat(tile) &&
2281  IsTileAlignedToGrid(tile, sp->layout) &&
2282  dist > sp->max_dist) {
2283  sp->tile = tile;
2284  sp->max_dist = dist;
2285  }
2286 
2287  return false;
2288 }
2289 
2294 static bool FindNearestEmptyLand(TileIndex tile, void *)
2295 {
2296  return IsTileType(tile, MP_CLEAR);
2297 }
2298 
2312 {
2313  SpotData sp = { INVALID_TILE, 0, layout };
2314 
2315  TileIndex coast = tile;
2316  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
2317  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
2318  return sp.tile;
2319  }
2320 
2321  /* if we get here just give up */
2322  return INVALID_TILE;
2323 }
2324 
2334 static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
2335 {
2336  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
2337 
2338  if (!Town::CanAllocateItem()) return nullptr;
2339 
2340  do {
2341  /* Generate a tile index not too close from the edge */
2342  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2343 
2344  /* if we tried to place the town on water, slide it over onto
2345  * the nearest likely-looking spot */
2346  if (IsTileType(tile, MP_WATER)) {
2347  tile = FindNearestGoodCoastalTownSpot(tile, layout);
2348  if (tile == INVALID_TILE) continue;
2349  }
2350 
2351  /* Make sure town can be placed here */
2352  if (TownCanBePlacedHere(tile).Failed()) continue;
2353 
2354  /* Allocate a town struct */
2355  Town *t = new Town(tile);
2356 
2357  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2358 
2359  /* if the population is still 0 at the point, then the
2360  * placement is so bad it couldn't grow at all */
2361  if (t->cache.population > 0) return t;
2362 
2364  [[maybe_unused]] CommandCost rc = Command<CMD_DELETE_TOWN>::Do(DC_EXEC, t->index);
2365  cur_company.Restore();
2366  assert(rc.Succeeded());
2367 
2368  /* We already know that we can allocate a single town when
2369  * entering this function. However, we create and delete
2370  * a town which "resets" the allocation checks. As such we
2371  * need to check again when assertions are enabled. */
2372  assert(Town::CanAllocateItem());
2373  } while (--attempts != 0);
2374 
2375  return nullptr;
2376 }
2377 
2378 static const uint8_t _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2379 
2387 {
2388  uint current_number = 0;
2389  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2390  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : Map::ScaleBySize(_num_initial_towns[difficulty] + (Random() & 7));
2391  total = std::min<uint>(TownPool::MAX_SIZE, total);
2392  uint32_t townnameparts;
2393  TownNames town_names;
2394 
2396 
2397  /* Pre-populate the town names list with the names of any towns already on the map */
2398  for (const Town *town : Town::Iterate()) {
2399  town_names.insert(town->GetCachedName());
2400  }
2401 
2402  /* Randomised offset for city status. This means with e.g. 1-in-4 towns being cities, a map with 10 towns
2403  * may have 2 or 3 cities, instead of always 3. */
2404  uint city_random_offset = _settings_game.economy.larger_towns == 0 ? 0 : (Random() % _settings_game.economy.larger_towns);
2405 
2406  /* First attempt will be made at creating the suggested number of towns.
2407  * Note that this is really a suggested value, not a required one.
2408  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2409  do {
2410  bool city = (_settings_game.economy.larger_towns != 0 && ((city_random_offset + current_number) % _settings_game.economy.larger_towns) == 0);
2412  /* Get a unique name for the town. */
2413  if (!GenerateTownName(_random, &townnameparts, &town_names)) continue;
2414  /* try 20 times to create a random-sized town for the first loop. */
2415  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2416  } while (--total);
2417 
2418  town_names.clear();
2419 
2420  /* Build the town k-d tree again to make sure it's well balanced */
2421  RebuildTownKdtree();
2422 
2423  if (current_number != 0) return true;
2424 
2425  /* If current_number is still zero at this point, it means that not a single town has been created.
2426  * So give it a last try, but now more aggressive */
2427  if (GenerateTownName(_random, &townnameparts) &&
2428  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2429  return true;
2430  }
2431 
2432  /* If there are no towns at all and we are generating new game, bail out */
2433  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2434  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2435  }
2436 
2437  return false; // we are still without a town? we failed, simply
2438 }
2439 
2440 
2447 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2448 {
2449  uint dist = DistanceSquare(tile, t->xy);
2450 
2451  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2452 
2453  HouseZonesBits smallest = HZB_TOWN_EDGE;
2454  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2455  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2456  }
2457 
2458  return smallest;
2459 }
2460 
2471 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
2472 {
2473  [[maybe_unused]] CommandCost cc = Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_AUTO | DC_NO_WATER, tile);
2474  assert(cc.Succeeded());
2475 
2476  IncreaseBuildingCount(t, type);
2477  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2478  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile, false);
2479 
2480  MarkTileDirtyByTile(tile);
2481 }
2482 
2483 
2494 static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
2495 {
2496  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2497 
2498  ClearMakeHouseTile(tile, t, counter, stage, type, random_bits);
2499  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(tile + TileDiffXY(0, 1), t, counter, stage, ++type, random_bits);
2500  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(tile + TileDiffXY(1, 0), t, counter, stage, ++type, random_bits);
2501  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(tile + TileDiffXY(1, 1), t, counter, stage, ++type, random_bits);
2502 
2503  ForAllStationsAroundTiles(TileArea(tile, (size & BUILDING_2_TILES_X) ? 2 : 1, (size & BUILDING_2_TILES_Y) ? 2 : 1), [t](Station *st, TileIndex) {
2504  t->stations_near.insert(st);
2505  return true;
2506  });
2507 }
2508 
2509 
2516 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2517 {
2518  /* cannot build on these slopes... */
2519  Slope slope = GetTileSlope(tile);
2520  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2521 
2522  /* at least one RoadTypes allow building the house here? */
2523  if (!RoadTypesAllowHouseHere(tile)) return false;
2524 
2525  /* building under a bridge? */
2526  if (IsBridgeAbove(tile)) return false;
2527 
2528  /* can we clear the land? */
2529  return Command<CMD_LANDSCAPE_CLEAR>::Do(DC_AUTO | DC_NO_WATER, tile).Succeeded();
2530 }
2531 
2532 
2541 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2542 {
2543  if (!CanBuildHouseHere(tile, noslope)) return false;
2544 
2545  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2546  if (GetTileMaxZ(tile) != z) return false;
2547 
2548  return true;
2549 }
2550 
2551 
2560 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2561 {
2562  /* we need to check this tile too because we can be at different tile now */
2563  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2564 
2565  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2566  tile += TileOffsByDiagDir(d);
2567  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2568  }
2569 
2570  return true;
2571 }
2572 
2573 
2581 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2582 {
2583  /* Allow towns everywhere when we don't build roads */
2584  if (!TownAllowedToBuildRoads()) return true;
2585 
2586  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2587 
2588  switch (t->layout) {
2589  case TL_2X2_GRID:
2590  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2591  break;
2592 
2593  case TL_3X3_GRID:
2594  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2595  break;
2596 
2597  default:
2598  break;
2599  }
2600 
2601  return true;
2602 }
2603 
2604 
2612 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2613 {
2614  /* Allow towns everywhere when we don't build roads */
2615  if (!TownAllowedToBuildRoads()) return true;
2616 
2617  /* Compute relative position of tile. (Positive offsets are towards north) */
2618  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2619 
2620  switch (t->layout) {
2621  case TL_2X2_GRID:
2622  grid_pos.x %= 3;
2623  grid_pos.y %= 3;
2624  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2625  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2626  break;
2627 
2628  case TL_3X3_GRID:
2629  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2630  break;
2631 
2632  default:
2633  break;
2634  }
2635 
2636  return true;
2637 }
2638 
2639 
2649 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2650 {
2651  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2652 
2653  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2654  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2655 
2656  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2657  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2658  *tile = tile2;
2659  return true;
2660  }
2661 
2662  return false;
2663 }
2664 
2665 
2674 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2675 {
2676  TileIndex tile2 = *tile;
2677 
2678  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2679  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2680  *tile = tile2;
2681  return true;
2682  }
2683  if (d == DIAGDIR_END) break;
2684  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2685  }
2686 
2687  return false;
2688 }
2689 
2698 static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits)
2699 {
2700  /* build the house */
2701  t->cache.num_houses++;
2702 
2703  uint8_t construction_counter = 0;
2704  uint8_t construction_stage = 0;
2705 
2706  if (_generating_world || _game_mode == GM_EDITOR) {
2707  uint32_t construction_random = Random();
2708 
2709  construction_stage = TOWN_HOUSE_COMPLETED;
2710  if (_generating_world && Chance16(1, 7)) construction_stage = GB(construction_random, 0, 2);
2711 
2712  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2713  ChangePopulation(t, hs->population);
2714  } else {
2715  construction_counter = GB(construction_random, 2, 2);
2716  }
2717  }
2718 
2719  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2720  UpdateTownRadius(t);
2722 }
2723 
2730 static bool TryBuildTownHouse(Town *t, TileIndex tile)
2731 {
2732  /* forbidden building here by town layout */
2733  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2734 
2735  /* no house allowed at all, bail out */
2736  if (!CanBuildHouseHere(tile, false)) return false;
2737 
2738  Slope slope = GetTileSlope(tile);
2739  int maxz = GetTileMaxZ(tile);
2740 
2741  /* Get the town zone type of the current tile, as well as the climate.
2742  * This will allow to easily compare with the specs of the new house to build */
2743  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2744 
2745  /* Above snow? */
2747  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2748 
2749  uint bitmask = (1 << rad) + (1 << (land + 12));
2750 
2751  /* bits 0-4 are used
2752  * bits 11-15 are used
2753  * bits 5-10 are not used. */
2754  static std::vector<std::pair<HouseID, uint>> probs;
2755  probs.clear();
2756 
2757  uint probability_max = 0;
2758 
2759  /* Generate a list of all possible houses that can be built. */
2760  for (const auto &hs : HouseSpec::Specs()) {
2761  /* Verify that the candidate house spec matches the current tile status */
2762  if ((~hs.building_availability & bitmask) != 0 || !hs.enabled || hs.grf_prop.override != INVALID_HOUSE_ID) continue;
2763 
2764  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2765  if (hs.class_id != HOUSE_NO_CLASS) {
2766  /* id_count is always <= class_count, so it doesn't need to be checked */
2767  if (t->cache.building_counts.class_count[hs.class_id] == UINT16_MAX) continue;
2768  } else {
2769  /* If the house has no class, check id_count instead */
2770  if (t->cache.building_counts.id_count[hs.Index()] == UINT16_MAX) continue;
2771  }
2772 
2773  uint cur_prob = hs.probability;
2774  probability_max += cur_prob;
2775  probs.emplace_back(hs.Index(), cur_prob);
2776  }
2777 
2778  TileIndex baseTile = tile;
2779 
2780  while (probability_max > 0) {
2781  /* Building a multitile building can change the location of tile.
2782  * The building would still be built partially on that tile, but
2783  * its northern tile would be elsewhere. However, if the callback
2784  * fails we would be basing further work from the changed tile.
2785  * So a next 1x1 tile building could be built on the wrong tile. */
2786  tile = baseTile;
2787 
2788  uint r = RandomRange(probability_max);
2789  uint i;
2790  for (i = 0; i < probs.size(); i++) {
2791  if (probs[i].second > r) break;
2792  r -= probs[i].second;
2793  }
2794 
2795  HouseID house = probs[i].first;
2796  probability_max -= probs[i].second;
2797 
2798  /* remove tested house from the set */
2799  probs[i] = probs.back();
2800  probs.pop_back();
2801 
2802  const HouseSpec *hs = HouseSpec::Get(house);
2803 
2804  if (!_generating_world && _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2805  continue;
2806  }
2807 
2808  if (TimerGameCalendar::year < hs->min_year || TimerGameCalendar::year > hs->max_year) continue;
2809 
2810  /* Special houses that there can be only one of. */
2811  uint oneof = 0;
2812 
2813  if (hs->building_flags & BUILDING_IS_CHURCH) {
2814  SetBit(oneof, TOWN_HAS_CHURCH);
2815  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2816  SetBit(oneof, TOWN_HAS_STADIUM);
2817  }
2818 
2819  if (t->flags & oneof) continue;
2820 
2821  /* Make sure there is no slope? */
2822  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2823  if (noslope && slope != SLOPE_FLAT) continue;
2824 
2825  if (hs->building_flags & TILE_SIZE_2x2) {
2826  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2827  } else if (hs->building_flags & TILE_SIZE_2x1) {
2828  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2829  } else if (hs->building_flags & TILE_SIZE_1x2) {
2830  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2831  } else {
2832  /* 1x1 house checks are already done */
2833  }
2834 
2835  uint8_t random_bits = Random();
2836 
2838  uint16_t callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2839  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2840  }
2841 
2842  /* Special houses that there can be only one of. */
2843  t->flags |= oneof;
2844 
2845  BuildTownHouse(t, tile, hs, house, random_bits);
2846 
2847  return true;
2848  }
2849 
2850  return false;
2851 }
2852 
2853 CommandCost CmdPlaceHouse(DoCommandFlag flags, TileIndex tile, HouseID house)
2854 {
2855  if (_game_mode != GM_EDITOR) return CMD_ERROR;
2856  if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
2857 
2858  if (static_cast<size_t>(house) >= HouseSpec::Specs().size()) return CMD_ERROR;
2859  const HouseSpec *hs = HouseSpec::Get(house);
2860  if (!hs->enabled) return CMD_ERROR;
2861 
2862  Town *t = ClosestTownFromTile(tile, UINT_MAX);
2863 
2864  /* cannot build on these slopes... */
2865  Slope slope = GetTileSlope(tile);
2866  if (IsSteepSlope(slope)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
2867 
2868  /* building under a bridge? */
2869  if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2870 
2871  /* can we clear the land? */
2873  if (!cost.Succeeded()) return cost;
2874 
2875  int maxz = GetTileMaxZ(tile);
2876 
2877  /* Make sure there is no slope? */
2878  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2879  if (noslope && slope != SLOPE_FLAT) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
2880 
2881  TileArea ta = tile;
2882  if (hs->building_flags & TILE_SIZE_2x2) ta.Add(TileAddXY(tile, 1, 1));
2883  if (hs->building_flags & TILE_SIZE_2x1) ta.Add(TileAddByDiagDir(tile, DIAGDIR_SW));
2884  if (hs->building_flags & TILE_SIZE_1x2) ta.Add(TileAddByDiagDir(tile, DIAGDIR_SE));
2885 
2886  /* Check additonal tiles covered by this house. */
2887  for (const TileIndex &subtile : ta) {
2889  if (!cost.Succeeded()) return cost;
2890 
2891  if (!CheckBuildHouseSameZ(subtile, maxz, noslope)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
2892  }
2893 
2894  if (flags & DC_EXEC) {
2895  BuildTownHouse(t, tile, hs, house, Random());
2896  }
2897 
2898  return CommandCost();
2899 }
2900 
2907 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2908 {
2909  assert(IsTileType(tile, MP_HOUSE));
2910  DecreaseBuildingCount(t, house);
2911  DoClearSquare(tile);
2912  DeleteAnimatedTile(tile);
2913 
2914  DeleteNewGRFInspectWindow(GSF_HOUSES, tile.base());
2915 }
2916 
2925 {
2926  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2927  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2928  house--;
2929  return TileDiffXY(-1, 0);
2930  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2931  house--;
2932  return TileDiffXY(0, -1);
2933  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2934  house -= 2;
2935  return TileDiffXY(-1, 0);
2936  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2937  house -= 3;
2938  return TileDiffXY(-1, -1);
2939  }
2940  }
2941  return TileDiffXY(0, 0);
2942 }
2943 
2950 {
2951  assert(IsTileType(tile, MP_HOUSE));
2952 
2953  HouseID house = GetHouseType(tile);
2954 
2955  /* The northernmost tile of the house is the main house. */
2956  tile += GetHouseNorthPart(house);
2957 
2958  const HouseSpec *hs = HouseSpec::Get(house);
2959 
2960  /* Remove population from the town if the house is finished. */
2961  if (IsHouseCompleted(tile)) {
2962  ChangePopulation(t, -hs->population);
2963  }
2964 
2965  t->cache.num_houses--;
2966 
2967  /* Clear flags for houses that only may exist once/town. */
2968  if (hs->building_flags & BUILDING_IS_CHURCH) {
2970  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2972  }
2973 
2974  /* Do the actual clearing of tiles */
2975  DoClearTownHouseHelper(tile, t, house);
2976  if (hs->building_flags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2977  if (hs->building_flags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2978  if (hs->building_flags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2979 
2980  RemoveNearbyStations(t, tile, hs->building_flags);
2981 
2982  UpdateTownRadius(t);
2983 }
2984 
2992 CommandCost CmdRenameTown(DoCommandFlag flags, TownID town_id, const std::string &text)
2993 {
2994  Town *t = Town::GetIfValid(town_id);
2995  if (t == nullptr) return CMD_ERROR;
2996 
2997  bool reset = text.empty();
2998 
2999  if (!reset) {
3001  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3002  }
3003 
3004  if (flags & DC_EXEC) {
3005  t->cached_name.clear();
3006  if (reset) {
3007  t->name.clear();
3008  } else {
3009  t->name = text;
3010  }
3011 
3012  t->UpdateVirtCoord();
3013  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_RESORT);
3014  ClearAllStationCachedNames();
3015  ClearAllIndustryCachedNames();
3017  }
3018  return CommandCost();
3019 }
3020 
3027 {
3028  for (const CargoSpec *cs : CargoSpec::Iterate()) {
3029  if (cs->town_acceptance_effect == effect) return cs;
3030  }
3031  return nullptr;
3032 }
3033 
3042 CommandCost CmdTownCargoGoal(DoCommandFlag flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
3043 {
3044  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3045 
3046  if (tae < TAE_BEGIN || tae >= TAE_END) return CMD_ERROR;
3047 
3048  Town *t = Town::GetIfValid(town_id);
3049  if (t == nullptr) return CMD_ERROR;
3050 
3051  /* Validate if there is a cargo which is the requested TownEffect */
3053  if (cargo == nullptr) return CMD_ERROR;
3054 
3055  if (flags & DC_EXEC) {
3056  t->goal[tae] = goal;
3057  UpdateTownGrowth(t);
3059  }
3060 
3061  return CommandCost();
3062 }
3063 
3071 CommandCost CmdTownSetText(DoCommandFlag flags, TownID town_id, const std::string &text)
3072 {
3073  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3074  Town *t = Town::GetIfValid(town_id);
3075  if (t == nullptr) return CMD_ERROR;
3076 
3077  if (flags & DC_EXEC) {
3078  t->text.clear();
3079  if (!text.empty()) t->text = text;
3081  }
3082 
3083  return CommandCost();
3084 }
3085 
3093 CommandCost CmdTownGrowthRate(DoCommandFlag flags, TownID town_id, uint16_t growth_rate)
3094 {
3095  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3096 
3097  Town *t = Town::GetIfValid(town_id);
3098  if (t == nullptr) return CMD_ERROR;
3099 
3100  if (flags & DC_EXEC) {
3101  if (growth_rate == 0) {
3102  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
3104  } else {
3105  uint old_rate = t->growth_rate;
3106  if (t->grow_counter >= old_rate) {
3107  /* This also catches old_rate == 0 */
3108  t->grow_counter = growth_rate;
3109  } else {
3110  /* Scale grow_counter, so half finished houses stay half finished */
3111  t->grow_counter = t->grow_counter * growth_rate / old_rate;
3112  }
3113  t->growth_rate = growth_rate;
3115  }
3116  UpdateTownGrowth(t);
3118  }
3119 
3120  return CommandCost();
3121 }
3122 
3131 CommandCost CmdTownRating(DoCommandFlag flags, TownID town_id, CompanyID company_id, int16_t rating)
3132 {
3133  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3134 
3135  Town *t = Town::GetIfValid(town_id);
3136  if (t == nullptr) return CMD_ERROR;
3137 
3138  if (!Company::IsValidID(company_id)) return CMD_ERROR;
3139 
3140  int16_t new_rating = Clamp(rating, RATING_MINIMUM, RATING_MAXIMUM);
3141  if (flags & DC_EXEC) {
3142  t->ratings[company_id] = new_rating;
3144  }
3145 
3146  return CommandCost();
3147 }
3148 
3156 CommandCost CmdExpandTown(DoCommandFlag flags, TownID town_id, uint32_t grow_amount)
3157 {
3158  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
3159  Town *t = Town::GetIfValid(town_id);
3160  if (t == nullptr) return CMD_ERROR;
3161 
3162  if (flags & DC_EXEC) {
3163  /* The more houses, the faster we grow */
3164  if (grow_amount == 0) {
3165  uint amount = RandomRange(ClampTo<uint16_t>(t->cache.num_houses / 10)) + 3;
3166  t->cache.num_houses += amount;
3167  UpdateTownRadius(t);
3168 
3169  uint n = amount * 10;
3170  do GrowTown(t); while (--n);
3171 
3172  t->cache.num_houses -= amount;
3173  } else {
3174  for (; grow_amount > 0; grow_amount--) {
3175  /* Try several times to grow, as we are really suppose to grow */
3176  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
3177  }
3178  }
3179  UpdateTownRadius(t);
3180 
3181  UpdateTownMaxPass(t);
3182  }
3183 
3184  return CommandCost();
3185 }
3186 
3194 {
3195  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
3196  Town *t = Town::GetIfValid(town_id);
3197  if (t == nullptr) return CMD_ERROR;
3198 
3199  /* Stations refer to towns. */
3200  for (const Station *st : Station::Iterate()) {
3201  if (st->town == t) {
3202  /* Non-oil rig stations are always a problem. */
3203  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
3204  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
3205  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, st->airport.tile);
3206  if (ret.Failed()) return ret;
3207  }
3208  }
3209 
3210  /* Waypoints refer to towns. */
3211  for (const Waypoint *wp : Waypoint::Iterate()) {
3212  if (wp->town == t) return CMD_ERROR;
3213  }
3214 
3215  /* Depots refer to towns. */
3216  for (const Depot *d : Depot::Iterate()) {
3217  if (d->town == t) return CMD_ERROR;
3218  }
3219 
3220  /* Check all tiles for town ownership. First check for bridge tiles, as
3221  * these do not directly have an owner so we need to check adjacent
3222  * tiles. This won't work correctly in the same loop if the adjacent
3223  * tile was already deleted earlier in the loop. */
3224  for (TileIndex current_tile = 0; current_tile < Map::Size(); ++current_tile) {
3225  if (IsTileType(current_tile, MP_TUNNELBRIDGE) && TestTownOwnsBridge(current_tile, t)) {
3226  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, current_tile);
3227  if (ret.Failed()) return ret;
3228  }
3229  }
3230 
3231  /* Check all remaining tiles for town ownership. */
3232  for (TileIndex current_tile = 0; current_tile < Map::Size(); ++current_tile) {
3233  bool try_clear = false;
3234  switch (GetTileType(current_tile)) {
3235  case MP_ROAD:
3236  try_clear = HasTownOwnedRoad(current_tile) && GetTownIndex(current_tile) == t->index;
3237  break;
3238 
3239  case MP_HOUSE:
3240  try_clear = GetTownIndex(current_tile) == t->index;
3241  break;
3242 
3243  case MP_INDUSTRY:
3244  try_clear = Industry::GetByTile(current_tile)->town == t;
3245  break;
3246 
3247  case MP_OBJECT:
3248  if (Town::GetNumItems() == 1) {
3249  /* No towns will be left, remove it! */
3250  try_clear = true;
3251  } else {
3252  Object *o = Object::GetByTile(current_tile);
3253  if (o->town == t) {
3254  if (o->type == OBJECT_STATUE) {
3255  /* Statue... always remove. */
3256  try_clear = true;
3257  } else {
3258  /* Tell to find a new town. */
3259  if (flags & DC_EXEC) o->town = nullptr;
3260  }
3261  }
3262  }
3263  break;
3264 
3265  default:
3266  break;
3267  }
3268  if (try_clear) {
3269  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, current_tile);
3270  if (ret.Failed()) return ret;
3271  }
3272  }
3273 
3274  /* The town destructor will delete the other things related to the town. */
3275  if (flags & DC_EXEC) {
3276  _town_kdtree.Remove(t->index);
3277  if (t->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
3278  delete t;
3279  }
3280 
3281  return CommandCost();
3282 }
3283 
3288 const uint8_t _town_action_costs[TACT_COUNT] = {
3289  2, 4, 9, 35, 48, 53, 117, 175
3290 };
3291 
3299 {
3300  if (flags & DC_EXEC) {
3301  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
3302  }
3303  return CommandCost();
3304 }
3305 
3313 {
3314  if (flags & DC_EXEC) {
3315  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
3316  }
3317  return CommandCost();
3318 }
3319 
3327 {
3328  if (flags & DC_EXEC) {
3329  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
3330  }
3331  return CommandCost();
3332 }
3333 
3341 {
3342  /* Check if the company is allowed to fund new roads. */
3344 
3345  if (flags & DC_EXEC) {
3346  t->road_build_months = 6;
3347 
3349  std::string company_name = GetString(STR_COMPANY_NAME);
3350 
3351  SetDParam(0, t->index);
3352  SetDParamStr(1, company_name);
3353 
3354  AddNewsItem(
3355  TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_ROAD_REBUILDING_MINUTES : STR_NEWS_ROAD_REBUILDING_MONTHS,
3356  NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX);
3357  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3358  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3359  }
3360  return CommandCost();
3361 }
3362 
3368 static bool CheckClearTile(TileIndex tile)
3369 {
3372  cur_company.Restore();
3373  return r.Succeeded();
3374 }
3375 
3380 
3381  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
3382 };
3383 
3390 static bool SearchTileForStatue(TileIndex tile, void *user_data)
3391 {
3392  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3393 
3394  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
3395  statue_data->tile_count++;
3396 
3397  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3398  if (IsSteepSlope(GetTileSlope(tile))) return false;
3399  /* Don't build statues under bridges. */
3400  if (IsBridgeAbove(tile)) return false;
3401 
3402  /* A clear-able open space is always preferred. */
3403  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && CheckClearTile(tile)) {
3404  statue_data->best_position = tile;
3405  return true;
3406  }
3407 
3408  bool house = IsTileType(tile, MP_HOUSE);
3409 
3410  /* Searching inside the inner circle. */
3411  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
3412  /* Save first house in inner circle. */
3413  if (house && statue_data->best_position == INVALID_TILE && CheckClearTile(tile)) {
3414  statue_data->best_position = tile;
3415  }
3416 
3417  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3418  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
3419  }
3420 
3421  /* Searching outside the circle, just pick the first possible spot. */
3422  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
3423  return house && CheckClearTile(tile);
3424 }
3425 
3434 {
3435  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
3436 
3437  TileIndex tile = t->xy;
3438  StatueBuildSearchData statue_data(INVALID_TILE, 0);
3439  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3440 
3441  if (flags & DC_EXEC) {
3444  cur_company.Restore();
3446  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
3447  MarkTileDirtyByTile(statue_data.best_position);
3448  }
3449  return CommandCost();
3450 }
3451 
3459 {
3460  /* Check if it's allowed to buy the rights */
3462 
3463  if (flags & DC_EXEC) {
3464  /* And grow for 3 months */
3465  t->fund_buildings_months = 3;
3466 
3467  /* Enable growth (also checking GameScript's opinion) */
3468  UpdateTownGrowth(t);
3469 
3470  /* Build a new house, but add a small delay to make sure
3471  * that spamming funding doesn't let town grow any faster
3472  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3473  * Also emulate original behaviour when town was only growing in
3474  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3475  * tick-perfect and gives player some time window where they can
3476  * spam funding with the exact same efficiency.
3477  */
3479 
3481  }
3482  return CommandCost();
3483 }
3484 
3492 {
3493  /* Check if it's allowed to buy the rights */
3495  if (t->exclusivity != INVALID_COMPANY) return CMD_ERROR;
3496 
3497  if (flags & DC_EXEC) {
3498  t->exclusive_counter = 12;
3500 
3501  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3502 
3504 
3505  /* Spawn news message */
3507  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3508  SetDParam(1, TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MINUTES : STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MONTHS);
3509  SetDParam(2, t->index);
3510  SetDParamStr(3, cni->company_name);
3511  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3512  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3513  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3514  }
3515  return CommandCost();
3516 }
3517 
3525 {
3526  if (flags & DC_EXEC) {
3527  if (Chance16(1, 14)) {
3528  /* set as unwanted for 6 months */
3529  t->unwanted[_current_company] = 6;
3530 
3531  /* set all close by station ratings to 0 */
3532  for (Station *st : Station::Iterate()) {
3533  if (st->town == t && st->owner == _current_company) {
3534  for (GoodsEntry &ge : st->goods) ge.rating = 0;
3535  }
3536  }
3537 
3538  /* only show error message to the executing player. All errors are handled command.c
3539  * but this is special, because it can only 'fail' on a DC_EXEC */
3540  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3541 
3542  /* decrease by a lot!
3543  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3544  * be independent of any cheat settings
3545  */
3546  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3547  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3549  }
3550  } else {
3551  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3554  t->exclusive_counter = 0;
3555  }
3556  }
3557  }
3558  return CommandCost();
3559 }
3560 
3561 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3562 static TownActionProc * const _town_action_proc[] = {
3571 };
3572 
3580 {
3581  TownActions buttons = TACT_NONE;
3582 
3583  /* Spectators and unwanted have no options */
3584  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3585 
3586  /* Actions worth more than this are not able to be performed */
3587  Money avail = GetAvailableMoney(cid);
3588 
3589  /* Check the action bits for validity and
3590  * if they are valid add them */
3591  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3592  const TownActions cur = (TownActions)(1 << i);
3593 
3594  /* Is the company prohibited from bribing ? */
3595  if (cur == TACT_BRIBE) {
3596  /* Company can't bribe if setting is disabled */
3597  if (!_settings_game.economy.bribe) continue;
3598  /* Company can bribe if another company has exclusive transport rights,
3599  * or its standing with the town is less than outstanding. */
3600  if (t->ratings[cid] >= RATING_BRIBE_MAXIMUM) {
3601  if (t->exclusivity == _current_company) continue;
3602  if (t->exclusive_counter == 0) continue;
3603  }
3604  }
3605 
3606  /* Is the company not able to buy exclusive rights ? */
3607  if (cur == TACT_BUY_RIGHTS && (!_settings_game.economy.exclusive_rights || t->exclusive_counter != 0)) continue;
3608 
3609  /* Is the company not able to fund buildings ? */
3610  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3611 
3612  /* Is the company not able to fund local road reconstruction? */
3613  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3614 
3615  /* Is the company not able to build a statue ? */
3616  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3617 
3618  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3619  buttons |= cur;
3620  }
3621  }
3622  }
3623 
3624  return buttons;
3625 }
3626 
3636 CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
3637 {
3638  Town *t = Town::GetIfValid(town_id);
3639  if (t == nullptr || action >= lengthof(_town_action_proc)) return CMD_ERROR;
3640 
3641  if (!HasBit(GetMaskOfTownActions(_current_company, t), action)) return CMD_ERROR;
3642 
3643  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[action] >> 8);
3644 
3645  CommandCost ret = _town_action_proc[action](t, flags);
3646  if (ret.Failed()) return ret;
3647 
3648  if (flags & DC_EXEC) {
3650  }
3651 
3652  return cost;
3653 }
3654 
3655 template <typename Func>
3656 static void ForAllStationsNearTown(Town *t, Func func)
3657 {
3658  /* Ideally the search radius should be close to the actual town zone 0 radius.
3659  * The true radius is not stored or calculated anywhere, only the squared radius. */
3660  /* The efficiency of this search might be improved for large towns and many stations on the map,
3661  * by using an integer square root approximation giving a value not less than the true square root. */
3662  uint search_radius = t->cache.squared_town_zone_radius[HZB_TOWN_EDGE] / 2;
3663  ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3664  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
3665  func(st);
3666  }
3667  });
3668 }
3669 
3674 static void UpdateTownRating(Town *t)
3675 {
3676  /* Increase company ratings if they're low */
3677  for (const Company *c : Company::Iterate()) {
3678  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3679  t->ratings[c->index] = std::min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3680  }
3681  }
3682 
3683  ForAllStationsNearTown(t, [&](const Station *st) {
3684  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3685  if (Company::IsValidID(st->owner)) {
3686  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3687  t->ratings[st->owner] = std::min<int>(new_rating, INT16_MAX); // do not let it overflow
3688  }
3689  } else {
3690  if (Company::IsValidID(st->owner)) {
3691  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3692  t->ratings[st->owner] = std::max(new_rating, INT16_MIN);
3693  }
3694  }
3695  });
3696 
3697  /* clamp all ratings to valid values */
3698  for (uint i = 0; i < MAX_COMPANIES; i++) {
3699  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3700  }
3701 
3703 }
3704 
3705 
3712 static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
3713 {
3714  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3715  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3716  t->grow_counter = std::min<uint16_t>(t->growth_rate, t->grow_counter);
3717  return;
3718  }
3719  t->grow_counter = RoundDivSU((uint32_t)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3720 }
3721 
3728 {
3729  int n = 0;
3730  ForAllStationsNearTown(t, [&](const Station * st) {
3731  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3732  n++;
3733  }
3734  });
3735  return n;
3736 }
3737 
3744 static uint GetNormalGrowthRate(Town *t)
3745 {
3751  static const uint16_t _grow_count_values[2][6] = {
3752  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3753  { 320, 420, 300, 220, 160, 100 } // Normal values
3754  };
3755 
3756  int n = CountActiveStations(t);
3757  uint16_t m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][std::min(n, 5)];
3758 
3759  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3760 
3761  m >>= growth_multiplier;
3762  if (t->larger_town) m /= 2;
3763 
3764  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3765 }
3766 
3772 {
3773  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3774  uint old_rate = t->growth_rate;
3776  UpdateTownGrowCounter(t, old_rate);
3778 }
3779 
3784 static void UpdateTownGrowth(Town *t)
3785 {
3787 
3790 
3791  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3792 
3793  if (t->fund_buildings_months == 0) {
3794  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3795  for (int i = TAE_BEGIN; i < TAE_END; i++) {
3796  switch (t->goal[i]) {
3797  case TOWN_GROWTH_WINTER:
3798  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3799  break;
3800  case TOWN_GROWTH_DESERT:
3801  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3802  break;
3803  default:
3804  if (t->goal[i] > t->received[i].old_act) return;
3805  break;
3806  }
3807  }
3808  }
3809 
3810  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3813  return;
3814  }
3815 
3816  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3817 
3820 }
3821 
3829 {
3830  /* The required rating is hardcoded to RATING_VERYPOOR (see below), not the authority attitude setting, so we can bail out like this. */
3831  if (_settings_game.difficulty.town_council_tolerance == TOWN_COUNCIL_PERMISSIVE) return CommandCost();
3832 
3834 
3836  if (t == nullptr) return CommandCost();
3837 
3838  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3839 
3840  SetDParam(0, t->index);
3841  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3842 }
3843 
3853 {
3854  if (Town::GetNumItems() == 0) return nullptr;
3855 
3856  TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
3857  Town *town = Town::Get(tid);
3858  if (DistanceManhattan(tile, town->xy) < threshold) return town;
3859  return nullptr;
3860 }
3861 
3870 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3871 {
3872  switch (GetTileType(tile)) {
3873  case MP_ROAD:
3874  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3875 
3876  if (!HasTownOwnedRoad(tile)) {
3877  TownID tid = GetTownIndex(tile);
3878 
3879  if (tid == INVALID_TOWN) {
3880  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3881  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3882  assert(Town::GetNumItems() == 0);
3883  return nullptr;
3884  }
3885 
3886  assert(Town::IsValidID(tid));
3887  Town *town = Town::Get(tid);
3888 
3889  if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3890 
3891  return town;
3892  }
3893  [[fallthrough]];
3894 
3895  case MP_HOUSE:
3896  return Town::GetByTile(tile);
3897 
3898  default:
3899  return CalcClosestTownFromTile(tile, threshold);
3900  }
3901 }
3902 
3903 static bool _town_rating_test = false;
3904 static std::map<const Town *, int> _town_test_ratings;
3905 
3911 void SetTownRatingTestMode(bool mode)
3912 {
3913  static int ref_count = 0; // Number of times test-mode is switched on.
3914  if (mode) {
3915  if (ref_count == 0) {
3916  _town_test_ratings.clear();
3917  }
3918  ref_count++;
3919  } else {
3920  assert(ref_count > 0);
3921  ref_count--;
3922  }
3923  _town_rating_test = !(ref_count == 0);
3924 }
3925 
3931 static int GetRating(const Town *t)
3932 {
3933  if (_town_rating_test) {
3934  auto it = _town_test_ratings.find(t);
3935  if (it != _town_test_ratings.end()) {
3936  return it->second;
3937  }
3938  }
3939  return t->ratings[_current_company];
3940 }
3941 
3949 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3950 {
3951  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3952  if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3954  (_cheats.magic_bulldozer.value && add < 0)) {
3955  return;
3956  }
3957 
3958  int rating = GetRating(t);
3959  if (add < 0) {
3960  if (rating > max) {
3961  rating += add;
3962  if (rating < max) rating = max;
3963  }
3964  } else {
3965  if (rating < max) {
3966  rating += add;
3967  if (rating > max) rating = max;
3968  }
3969  }
3970  if (_town_rating_test) {
3971  _town_test_ratings[t] = rating;
3972  } else {
3974  t->ratings[_current_company] = rating;
3976  }
3977 }
3978 
3987 {
3988  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3989  if (t == nullptr || !Company::IsValidID(_current_company) ||
3991  return CommandCost();
3992  }
3993 
3994  /* minimum rating needed to be allowed to remove stuff */
3995  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3996  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
4001  };
4002 
4003  /* check if you're allowed to remove the road/bridge/tunnel
4004  * owned by a town no removal if rating is lower than ... depends now on
4005  * difficulty setting. Minimum town rating selected by difficulty level
4006  */
4007  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
4008 
4009  if (GetRating(t) < needed) {
4010  SetDParam(0, t->index);
4011  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
4012  }
4013 
4014  return CommandCost();
4015 }
4016 
4017 static IntervalTimer<TimerGameEconomy> _economy_towns_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::TOWN}, [](auto)
4018 {
4019  for (Town *t : Town::Iterate()) {
4020  /* Check for active town actions and decrement their counters. */
4021  if (t->road_build_months != 0) t->road_build_months--;
4022  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
4023 
4024  if (t->exclusive_counter != 0) {
4025  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
4026  }
4027 
4028  /* Check for active failed bribe cooloff periods and decrement them. */
4029  for (const Company *c : Company::Iterate()) {
4030  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
4031  }
4032 
4033  /* Update cargo statistics. */
4034  for (auto &supplied : t->supplied) supplied.NewMonth();
4035  for (auto &received : t->received) received.NewMonth();
4036 
4037  UpdateTownGrowth(t);
4038  UpdateTownRating(t);
4039 
4041  }
4042 });
4043 
4044 static IntervalTimer<TimerGameEconomy> _economy_towns_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::TOWN}, [](auto)
4045 {
4046  /* Increment house ages */
4047  for (TileIndex t = 0; t < Map::Size(); t++) {
4048  if (!IsTileType(t, MP_HOUSE)) continue;
4049  IncrementHouseAge(t);
4050  }
4051 });
4052 
4053 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4054 {
4055  if (AutoslopeEnabled()) {
4056  HouseID house = GetHouseType(tile);
4057  GetHouseNorthPart(house); // modifies house to the ID of the north tile
4058  const HouseSpec *hs = HouseSpec::Get(house);
4059 
4060  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
4061  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
4062  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
4063  bool allow_terraform = true;
4064 
4065  /* Call the autosloping callback per tile, not for the whole building at once. */
4066  house = GetHouseType(tile);
4067  hs = HouseSpec::Get(house);
4069  /* If the callback fails, allow autoslope. */
4070  uint16_t res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
4071  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
4072  }
4073 
4074  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4075  }
4076  }
4077 
4078  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4079 }
4080 
4082 extern const TileTypeProcs _tile_type_town_procs = {
4083  DrawTile_Town, // draw_tile_proc
4084  GetSlopePixelZ_Town, // get_slope_z_proc
4085  ClearTile_Town, // clear_tile_proc
4086  AddAcceptedCargo_Town, // add_accepted_cargo_proc
4087  GetTileDesc_Town, // get_tile_desc_proc
4088  GetTileTrackStatus_Town, // get_tile_track_status_proc
4089  nullptr, // click_tile_proc
4090  AnimateTile_Town, // animate_tile_proc
4091  TileLoop_Town, // tile_loop_proc
4092  ChangeTileOwner_Town, // change_tile_owner_proc
4093  AddProducedCargo_Town, // add_produced_cargo_proc
4094  nullptr, // vehicle_enter_tile_proc
4095  GetFoundation_Town, // get_foundation_proc
4096  TerraformTile_Town, // terraform_tile_proc
4097 };
4098 
4099 std::span<const DrawBuildingsTileStruct> GetTownDrawTileData()
4100 {
4101  return _town_draw_tile_data;
4102 }
Base functions for all AIs.
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
Tile animation!
Functions related to autoslope.
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:65
Class for backupping variables and making sure they are restored later.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:35
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition: bridge_map.h:35
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
Axis GetBridgeAxis(Tile t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
@ Town
Source/destination is a town.
TownProductionEffect
Town effect when producing cargo.
Definition: cargotype.h:34
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
Definition: cargotype.h:36
@ TPE_MAIL
Cargo behaves mail-like for production.
Definition: cargotype.h:37
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:21
@ TAE_END
End of town effects.
Definition: cargotype.h:29
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:28
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:27
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
Types related to cheating.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:263
Common return value for all commands.
Definition: command_type.h:23
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
bool Failed() const
Did this command fail?
Definition: command_type.h:171
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:74
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:146
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition: timer.h:76
K-dimensional tree, specialised for 2-dimensional space.
Definition: kdtree.hpp:35
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
Definition: kdtree.hpp:362
size_t Count() const
Get number of elements stored in tree.
Definition: kdtree.hpp:430
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:398
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:417
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Definition: kdtree.hpp:441
RoadTypeLabel label
Unique 32 bit road type identifier.
Definition: road.h:147
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: road.h:166
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:127
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
Structure contains cached list of stations nearby.
Definition: station_type.h:100
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Date MAX_DATE
The date of the last day of the max year.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Functions related to commands.
static constexpr DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:58
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
DoCommandFlag
List of flags for a command.
Definition: command_type.h:374
@ DC_NONE
no flag is set
Definition: command_type.h:375
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:381
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:377
@ DC_NO_WATER
don't allow building on water
Definition: command_type.h:379
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:386
@ DC_EXEC
execute the given command
Definition: command_type.h:376
Definition of stuff that is very close to a company, like the company struct itself.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:53
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:47
Owner
Enum for all companies/owners.
Definition: company_type.h:18
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
Base for all depots (except hangars)
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
@ DIR_N
North.
@ DIR_S
South.
@ DIR_W
West.
@ DIR_E
East.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ DIAGDIR_SW
Southwest.
@ DIAGDIRDIFF_90RIGHT
90 degrees right
@ DIAGDIRDIFF_90LEFT
90 degrees left
bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
Definition: economy_func.h:77
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:173
@ EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:185
Functions related to errors.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:24
Base functions for all Games.
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:67
Functions related to world/map generation.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
@ GWP_TOWN
Generate towns.
Definition: genworld.h:74
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:18
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:609
uint8_t HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:622
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1529
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:2057
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:23
@ BUILDING_IS_HISTORICAL
this house will only appear during town generation in random games, thus the historical
Definition: house.h:85
uint16_t HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
Base of all industries.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:425
std::tuple< Slope, int > GetFoundationSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition: landscape.cpp:382
Functions related to OTTD's landscape.
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition: landscape.h:95
Command definitions related to landscape (slopes etc.).
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:247
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition: map.cpp:163
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:206
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:146
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:329
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition: map_func.h:467
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition: map_func.h:596
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:373
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:440
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:608
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:389
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
Definition: map_func.h:454
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:661
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:425
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:415
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:567
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:528
int32_t TileIndexDiff
An offset value between two tiles.
Definition: map_type.h:23
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:342
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:91
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
@ CBM_HOUSE_PRODUCE_CARGO
custom cargo production
@ CBM_HOUSE_ALLOW_CONSTRUCTION
decide whether the house can be built on a given tile
@ CBM_HOUSE_CARGO_ACCEPTANCE
decides amount of cargo acceptance
@ CBM_HOUSE_AUTOSLOPE
decides allowance of autosloping
@ CBM_HOUSE_ACCEPT_CARGO
decides accepted types
@ CBM_HOUSE_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Cargo support for NewGRFs.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
void InitializeBuildingCounts(Town *t)
Initialise building counts for a town.
Functions related to NewGRF houses.
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
Functions related to news.
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:829
@ NT_INDUSTRY_OPEN
Opening of industries.
Definition: news_type.h:29
@ NT_GENERAL
General news (from towns)
Definition: news_type.h:39
@ NR_TOWN
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:58
@ NR_NONE
Empty reference.
Definition: news_type.h:53
@ NF_COMPANY
Company news item. (Newspaper with face)
Definition: news_type.h:83
@ NF_NORMAL
Normal news item. (Newspaper with text only)
Definition: news_type.h:81
Functions related to objects.
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
Definition: object_cmd.cpp:88
Base for all objects.
Map accessors for object tiles.
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:237
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:37
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:88
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition: road.cpp:47
Road specific functions.
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:227
@ ROTF_NO_HOUSES
Bit number for setting this roadtype as not house friendly.
Definition: road.h:40
@ ROTF_TOWN_BUILD
Bit number for allowing towns to build this roadtype.
Definition: road.h:42
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1918
Road related functions.
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:96
Functions used internally by the roads.
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:33
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:251
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition: road_map.h:280
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition: road_map.h:74
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition: road_map.h:106
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition: road_map.h:301
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:211
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
Definition: road_map.h:565
static debug_inline bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
Definition: road_map.h:116
bool IsRoadOwner(Tile t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
Definition: road_map.h:268
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:52
@ ROAD_SW
South-west part.
Definition: road_type.h:55
@ ROAD_ALL
Full 4-way crossing.
Definition: road_type.h:66
@ ROAD_NONE
No road-part is build.
Definition: road_type.h:53
@ ROAD_E
Road at the two eastern edges.
Definition: road_type.h:62
@ ROAD_NE
North-east part.
Definition: road_type.h:57
@ ROAD_N
Road at the two northern edges.
Definition: road_type.h:61
@ ROAD_SE
South-east part.
Definition: road_type.h:56
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:59
@ ROAD_S
Road at the two southern edges.
Definition: road_type.h:63
@ ROAD_W
Road at the two western edges.
Definition: road_type.h:64
@ ROAD_NW
North-west part.
Definition: road_type.h:54
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:58
RoadType
The different roadtypes we support.
Definition: road_type.h:25
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
@ ROADTYPE_BEGIN
Used for iterations.
Definition: road_type.h:26
@ DRD_NONE
None of the directions are disallowed.
Definition: road_type.h:74
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:57
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:56
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition: slope_func.h:160
bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
Definition: slope_func.h:88
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:256
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:76
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
@ SLOPE_W
the west corner of the tile is raised
Definition: slope_type.h:50
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
Definition: slope_type.h:61
@ SLOPE_E
the east corner of the tile is raised
Definition: slope_type.h:52
@ SLOPE_S
the south corner of the tile is raised
Definition: slope_type.h:51
@ SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:53
@ SLOPE_SW
south and west corner are raised
Definition: slope_type.h:56
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
Definition: slope_type.h:66
@ SLOPE_NE
north and east corner are raised
Definition: slope_type.h:58
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
Definition: slope_type.h:68
@ SLOPE_SE
south and east corner are raised
Definition: slope_type.h:57
@ SLOPE_NW
north and west corner are raised
Definition: slope_type.h:55
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition: slope_type.h:69
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
Definition: slope_type.h:67
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
Base classes/functions for stations.
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
Definition: station_base.h:564
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Declarations for accessing the k-d tree of stations.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:266
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Definition: station_map.h:276
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
Definition: station_map.h:356
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
Definition: station_map.h:344
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
Definition: station_map.h:256
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:57
Definition of base types and functions in a cross-platform compatible way.
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:343
#define lengthof(array)
Return the length of an fixed size array.
Definition: stdafx.h:280
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:359
Functions related to low-level strings.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:319
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:357
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
void Restore()
Restore the variable.
Owner owner
The owner of this station.
Class for storing amounts of cargo.
Definition: cargo_type.h:114
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Specification of a cargo type.
Definition: cargotype.h:71
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:190
static std::array< std::vector< const CargoSpec * >, NUM_TPE > town_production_cargoes
List of cargo specs for each Town Product Effect.
Definition: cargotype.h:193
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
GUISettings gui
settings related to the GUI
Data that needs to be stored for company news messages.
Definition: news_type.h:153
std::string company_name
The name of the company.
Definition: news_type.h:154
bool build_on_slopes
allow building on slopes
uint8_t number_towns
the amount of towns
uint8_t town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
This structure is the same for both Industries and Houses.
Definition: sprite.h:67
bool bribe
enable bribing the local authority
TownFounding found_town
town founding.
bool exclusive_rights
allow buying exclusive rights
uint8_t initial_city_size
multiplier for the initial size of the cities compared to towns
TownLayout town_layout
select town layout,
bool allow_town_level_crossings
towns are allowed to build level crossings
uint8_t town_growth_rate
town growth rate
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
bool fund_buildings
allow funding new buildings
bool fund_roads
allow funding local road reconstruction
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
uint8_t dist_local_authority
distance for town local authority, default 20
uint8_t larger_towns
the number of cities to build. These start off larger and grow twice as fast
Information about GRF, used in the game and (part of it) in savegames.
const char * GetName() const
Get the name of this grf.
const struct GRFFile * grffile
grf file that introduced this entity
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
uint16_t override
id of the entity been replaced by
bool population_in_label
show the population of a town in its label?
uint16_t custom_town_number
manually entered number of towns
uint8_t landscape
the landscape we're currently in
uint8_t town_name
the town name generator used for town names
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
Stores station stats for a single cargo.
Definition: station_base.h:166
uint8_t rating
Station rating for this cargo.
Definition: station_base.h:226
uint8_t probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:112
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:103
uint8_t removal_cost
cost multiplier for removing it
Definition: house.h:98
uint8_t mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:101
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:106
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:225
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:104
TimerGameCalendar::Year max_year
last year it can be built
Definition: house.h:96
uint16_t remove_rating_decrease
rating decrease if removed
Definition: house.h:100
uint8_t population
population (Zero on other tiles in multi tile house.)
Definition: house.h:97
HouseExtraFlags extra_flags
some more flags
Definition: house.h:113
uint8_t cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:102
HouseID Index() const
Gets the index of this spec.
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:114
StringID building_name
building name
Definition: house.h:99
uint8_t minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:117
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:109
uint16_t callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:110
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:105
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Defines the internal data of a functional industry.
Definition: industry.h:66
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:238
Town * town
Nearest town.
Definition: industry.h:95
static uint ScaleBySize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
Definition: map_func.h:328
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
An object, such as transmitter, on the map.
Definition: object_base.h:23
ObjectType type
Type of the object.
Definition: object_base.h:24
Town * town
Town the object is built in.
Definition: object_base.h:25
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:55
Represents the covered area of e.g.
Definition: tilearea_type.h:18
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:24
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:25
Coordinates of a point in 2D.
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:360
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:369
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:318
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:328
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
Base class for all pools.
Definition: pool_type.hpp:80
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:84
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:2252
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:2254
TownLayout layout
tells us what kind of town we're building
Definition: town_cmd.cpp:2255
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:2253
Station data structure.
Definition: station_base.h:439
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition: station.cpp:448
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:3377
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:3379
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:3378
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:52
StringID str
Description of the tile.
Definition: tile_cmd.h:53
uint64_t dparam
Parameter of the str string.
Definition: tile_cmd.h:54
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
A pair-construct of a TileIndexDiff.
Definition: map_type.h:31
int16_t x
The x value of the coordinate.
Definition: map_type.h:32
int16_t y
The y value of the coordinate.
Definition: map_type.h:33
Tile information, used while rendering the tile.
Definition: tile_cmd.h:43
int z
Height.
Definition: tile_cmd.h:48
int x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:44
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:46
TileIndex tile
Tile index.
Definition: tile_cmd.h:47
int y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:45
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:158
uint32_t population
Current population of people.
Definition: town.h:44
uint32_t num_houses
Amount of houses.
Definition: town.h:43
std::array< uint32_t, HZB_END > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
Definition: town.h:47
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:45
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition: town.h:48
Struct holding parameters used to generate town name.
Definition: townname_type.h:28
Town data structure.
Definition: town.h:54
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:101
TransportedCargoStat< uint32_t > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:79
CompanyMask statues
which companies have a statue?
Definition: town.h:70
uint16_t time_until_rebuild
time until we rebuild a house
Definition: town.h:93
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:64
TileIndex xy
town center tile
Definition: town.h:55
uint8_t fund_buildings_months
fund buildings program in action?
Definition: town.h:98
int16_t ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:77
TownLayout layout
town specific road layout
Definition: town.h:102
TransportedCargoStat< uint16_t > received[NUM_TAE]
Cargo statistics about received cargotypes.
Definition: town.h:80
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:196
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition: town.h:63
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:95
uint8_t flags
See TownFlags.
Definition: town.h:66
TownCache cache
Container for all cacheable data.
Definition: town.h:57
CompanyID exclusivity
which company has exclusivity
Definition: town.h:75
void InitializeLayout(TownLayout layout)
Assign the town layout.
Definition: town_cmd.cpp:182
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:104
uint32_t goal[NUM_TAE]
Amount of cargo required for the town to grow.
Definition: town.h:81
uint8_t exclusive_counter
months till the exclusivity expires
Definition: town.h:76
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Definition: town_cmd.cpp:409
std::string text
General text with additional information.
Definition: town.h:83
CompanyMask have_ratings
which companies have a rating
Definition: town.h:73
~Town()
Destroy the town.
Definition: town_cmd.cpp:110
uint8_t unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
Definition: town.h:74
uint16_t growth_rate
town growth rate
Definition: town.h:96
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:91
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
Definition: town_cmd.cpp:167
uint8_t road_build_months
fund road reconstruction in action?
Definition: town.h:99
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport_type.h:60
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:52
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:115
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:114
Tstorage old_act
Actually transported last month.
Definition: town_type.h:116
Tstorage new_act
Actually transported this month.
Definition: town_type.h:117
Representation of a waypoint.
Definition: waypoint_base.h:23
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:151
Functions related to subsidies.
Command definitions related to terraforming.
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:95
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:136
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:116
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:324
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:312
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition: tile_map.h:161
uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:342
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition: tile_map.h:238
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition: tile_map.h:279
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
Definition: tile_map.h:29
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:78
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:50
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:57
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:48
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
@ MP_WATER
Water tile.
Definition: tile_type.h:54
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:55
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:58
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:33
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:34
@ TOWN_HAS_CHURCH
There can be only one church by town.
Definition: town.h:197
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition: town.h:198
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:196
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition: town.h:199
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:175
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition: town.h:178
TownActions
Town actions of a company.
Definition: town.h:212
@ TACT_BUILD_STATUE
Build a statue.
Definition: town.h:219
@ TACT_ROAD_REBUILD
Rebuild the roads.
Definition: town.h:218
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition: town.h:221
@ TACT_BRIBE
Try to bribe the council.
Definition: town.h:222
@ TACT_COUNT
Number of available town actions.
Definition: town.h:224
@ TACT_FUND_BUILDINGS
Fund new buildings.
Definition: town.h:220
@ TACT_NONE
Empty action set.
Definition: town.h:213
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:28
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:35
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding road allows to build a house here.
Definition: town_cmd.cpp:1451
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
Definition: town_cmd.cpp:2560
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows a 2x2 building here.
Definition: town_cmd.cpp:2612
static void ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Clears tile and builds a house or house part.
Definition: town_cmd.cpp:2471
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:3026
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2447
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1176
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:3390
static bool FindNearestEmptyLand(TileIndex tile, void *)
CircularTileSearch callback to find the nearest land tile.
Definition: town_cmd.cpp:2294
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:2240
static void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
Fill cargo acceptance array and always_accepted mask, if cargo ID is valid.
Definition: town_cmd.cpp:784
static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
Perform the "bribe" town action.
Definition: town_cmd.cpp:3524
CommandCost CmdRenameTown(DoCommandFlag flags, TownID town_id, const std::string &text)
Rename a town (server-only).
Definition: town_cmd.cpp:2992
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2924
static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
Perform the "large advertising campaign" town action.
Definition: town_cmd.cpp:3326
static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
Perform the "small advertising campaign" town action.
Definition: town_cmd.cpp:3298
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3931
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
Definition: town_cmd.cpp:2949
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3744
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
Definition: town_cmd.cpp:3579
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
Callback function to clear a house tile.
Definition: town_cmd.cpp:717
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1304
static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
Given a spot on the map (presumed to be a water tile), find a good coastal spot to build a city.
Definition: town_cmd.cpp:2311
CommandCost CmdTownGrowthRate(DoCommandFlag flags, TownID town_id, uint16_t growth_rate)
Change the growth rate of the town.
Definition: town_cmd.cpp:3093
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:1040
static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
Checks if a town road can be continued into the next tile.
Definition: town_cmd.cpp:1237
CommandCost CmdTownRating(DoCommandFlag flags, TownID town_id, CompanyID company_id, int16_t rating)
Change the rating of a company in a town.
Definition: town_cmd.cpp:3131
static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3712
CommandCost CmdTownCargoGoal(DoCommandFlag flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
Change the cargo goal of a town.
Definition: town_cmd.cpp:3042
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3727
static CommandCost TownCanBePlacedHere(TileIndex tile)
Check if it's possible to place a town on a given tile.
Definition: town_cmd.cpp:2069
static bool _generating_town
Set if a town is being generated.
Definition: town_cmd.cpp:83
static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
Definition: town_cmd.cpp:1722
static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data)
CircularTileSearch proc which checks for a nearby parallel bridge to avoid building redundant bridges...
Definition: town_cmd.cpp:1279
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows building here.
Definition: town_cmd.cpp:2581
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:605
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Check if a house can be built here, based on slope, whether there's a bridge above,...
Definition: town_cmd.cpp:2516
static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
Perform the "medium advertising campaign" town action.
Definition: town_cmd.cpp:3312
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1218
CommandCost CmdDeleteTown(DoCommandFlag flags, TownID town_id)
Delete a town (scenario editor or worldgen only).
Definition: town_cmd.cpp:3193
static void UpdateTownRating(Town *t)
Monthly callback to update town and station ratings.
Definition: town_cmd.cpp:3674
static void AdvanceHouseConstruction(TileIndex tile)
Increase the construction stage of a house.
Definition: town_cmd.cpp:521
static bool TownCanGrowRoad(TileIndex tile)
Test if town can grow road onto a specific tile.
Definition: town_cmd.cpp:1479
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition: town_cmd.cpp:462
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
Definition: town_cmd.cpp:1385
static std::map< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3904
static bool CheckClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:3368
const uint8_t _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:3288
static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
Perform the "local road reconstruction" town action.
Definition: town_cmd.cpp:3340
static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
Perform the "fund new buildings" town action.
Definition: town_cmd.cpp:3458
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the original algorithm.
Definition: town_cmd.cpp:562
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
Definition: town_cmd.cpp:1966
static void ChangePopulation(Town *t, int mod)
Change the town's population as recorded in the town cache, town label, and town directory.
Definition: town_cmd.cpp:447
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
Definition: town_cmd.cpp:2674
static bool TownAllowedToBuildRoads()
Check if the town is allowed to build roads.
Definition: town_cmd.cpp:1492
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:1006
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1860
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:258
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:2222
static Town * CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
Create a random town somewhere in the world.
Definition: town_cmd.cpp:2334
static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
Remove stations from nearby station list if a town is no longer in the catchment area of each.
Definition: town_cmd.cpp:476
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Try to grow a town at a given road tile.
Definition: town_cmd.cpp:1764
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition: town_cmd.cpp:435
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3949
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:2274
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Get the foundation for a house.
Definition: town_cmd.cpp:326
static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
Generate cargo for a house, scaled by the current economy scale.
Definition: town_cmd.cpp:538
static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
Get the calendar date of the earliest town-buildable road type.
Definition: town_cmd.cpp:961
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town.
Definition: town_cmd.cpp:350
CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
Do a town action.
Definition: town_cmd.cpp:3636
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
Definition: landscape.cpp:51
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Definition: town_cmd.cpp:926
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile, ignoring depot and bay road stops.
Definition: town_cmd.cpp:915
CommandCost CmdExpandTown(DoCommandFlag flags, TownID town_id, uint32_t grow_amount)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:3156
static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
Perform the "buy exclusive transport rights" town action.
Definition: town_cmd.cpp:3491
static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Actually create a town.
Definition: town_cmd.cpp:1990
static bool TryBuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2730
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
Definition: town_cmd.cpp:94
void OnTick_Town()
Iterate through all towns and call their tick handler.
Definition: town_cmd.cpp:901
bool CheckTownRoadTypes()
Check if towns are able to build road.
Definition: town_cmd.cpp:982
bool GenerateTowns(TownLayout layout)
Generate a number of towns with a given layout.
Definition: town_cmd.cpp:2386
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3828
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3986
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
Definition: town_cmd.cpp:2649
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
Definition: town_cmd.cpp:3771
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:1117
static void AdvanceSingleHouseConstruction(TileIndex tile)
Helper function for house construction stage progression.
Definition: town_cmd.cpp:498
static void TownTickHandler(Town *t)
Handle the town tick for a single town, by growing the town if desired.
Definition: town_cmd.cpp:884
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3852
static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Write house information into the map.
Definition: town_cmd.cpp:2494
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Definition: town_cmd.cpp:3911
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
Definition: town_cmd.cpp:3433
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3903
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
Definition: town_cmd.cpp:1919
static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits)
Build a house at this tile.
Definition: town_cmd.cpp:2698
CommandCost CmdTownSetText(DoCommandFlag flags, TownID town_id, const std::string &text)
Set a custom text in the Town window.
Definition: town_cmd.cpp:3071
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:401
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3784
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2907
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3870
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1846
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Check if a tile where we want to build a multi-tile house has an appropriate max Z.
Definition: town_cmd.cpp:2541
static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the binominal algorithm.
Definition: town_cmd.cpp:582
std::tuple< CommandCost, Money, TownID > CmdFoundTown(DoCommandFlag flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
Create a new town.
Definition: town_cmd.cpp:2115
static bool IsUniqueTownName(const std::string &name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:2094
static void DrawTile_Town(TileInfo *ti)
Draw a house and its tile.
Definition: town_cmd.cpp:267
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:427
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1514
Command definitions related to towns.
Declarations for accessing the k-d tree of towns.
Sprites to use and how to display them for town tiles.
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:27
void IncrementHouseAge(Tile t)
Increments the age of the house.
Definition: town_map.h:238
void HaltLift(Tile t)
Stop the lift of this animated house from moving.
Definition: town_map.h:116
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:60
void ResetHouseAge(Tile t)
Sets the age of the house to zero.
Definition: town_map.h:227
void IncHouseConstructionTick(Tile t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
Definition: town_map.h:209
uint8_t GetLiftPosition(Tile t)
Get the position of the lift on this animated house.
Definition: town_map.h:126
void SetLiftDestination(Tile t, uint8_t dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
Definition: town_map.h:94
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
Definition: town_map.h:250
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
Definition: town_map.h:136
uint8_t GetLiftDestination(Tile t)
Get the current destination for this lift.
Definition: town_map.h:105
uint8_t GetHouseBuildingStage(Tile t)
House Construction Scheme.
Definition: town_map.h:184
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:23
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:35
bool LiftHasDestination(Tile t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:83
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition: town_map.h:146
void MakeHouseTile(Tile t, TownID tid, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Make the tile a house.
Definition: town_map.h:353
uint8_t GetHouseConstructionTick(Tile t)
Gets the construction stage of a house.
Definition: town_map.h:196
static constexpr int RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:51
static constexpr int RATING_INITIAL
initial rating
Definition: town_type.h:43
static constexpr int RATING_ROAD_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:69
@ TCGM_BITCOUNT
Bit-counted algorithm (normal distribution from individual house population)
Definition: town_type.h:105
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
Definition: town_type.h:104
static constexpr int RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:68
TownLayout
Town Layouts.
Definition: town_type.h:79
@ TL_3X3_GRID
Geometric 3x3 grid algorithm.
Definition: town_type.h:84
@ TL_ORIGINAL
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:81
@ TL_2X2_GRID
Geometric 2x2 grid algorithm.
Definition: town_type.h:83
@ TL_RANDOM
Random town layout.
Definition: town_type.h:86
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:82
@ NUM_TLS
Number of town layouts.
Definition: town_type.h:88
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition: town_type.h:59
@ TF_CUSTOM_LAYOUT
Allowed, with custom town layout.
Definition: town_type.h:97
@ TF_FORBIDDEN
Forbidden.
Definition: town_type.h:95
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:61
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition: town_type.h:62
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:60
static constexpr int RATING_ROAD_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition: town_type.h:67
TownSize
Supported initial town sizes.
Definition: town_type.h:19
@ TSZ_RANDOM
Random size, bigger than small, smaller than large.
Definition: town_type.h:23
@ TSZ_END
Number of available town sizes.
Definition: town_type.h:25
@ TSZ_LARGE
Large town.
Definition: town_type.h:22
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
Definition: town_type.h:109
static constexpr int RATING_ROAD_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition: town_type.h:70
static constexpr int RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
Definition: town_type.h:52
bool VerifyTownName(uint32_t r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:103
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:136
static void GetTownName(StringBuilder &builder, const TownNameParams *par, uint32_t townnameparts)
Fills builder with specified town name.
Definition: townname.cpp:48
Town name generator stuff.
@ TO_HOUSES
town buildings
Definition: transparency.h:25
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:48
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:59
TransportType
Available types of transport.
@ TRANSPORT_ROAD
Transport by road vehicle.
Command definitions related to tunnels and bridges.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:671
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:827
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:587
Functions related to (drawing on) viewports.
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition: water_map.h:350
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition: water_map.h:190
bool IsSea(Tile t)
Is it a sea water tile?
Definition: water_map.h:158
Base of waypoints.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1140
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3119
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3211
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3093
Window functions not directly related to making/drawing windows.
@ WC_TOWN_AUTHORITY
Town authority; Window numbers:
Definition: window_type.h:194
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:345
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:333
@ WC_TOWN_DIRECTORY
Town directory; Window numbers:
Definition: window_type.h:254