OpenTTD Source  1.11.0-beta1
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 "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "station_kdtree.h"
22 #include "company_base.h"
23 #include "news_func.h"
24 #include "error.h"
25 #include "object.h"
26 #include "genworld.h"
27 #include "newgrf_debug.h"
28 #include "newgrf_house.h"
29 #include "newgrf_text.h"
30 #include "autoslope.h"
31 #include "tunnelbridge_map.h"
32 #include "strings_func.h"
33 #include "window_func.h"
34 #include "string_func.h"
35 #include "newgrf_cargo.h"
36 #include "cheat_type.h"
37 #include "animated_tile_func.h"
38 #include "date_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 
52 #include "table/strings.h"
53 #include "table/town_land.h"
54 
55 #include "safeguards.h"
56 
57 TownID _new_town_id;
58 
59 /* Initialize the town-pool */
60 TownPool _town_pool("Town");
62 
63 
64 TownKdtree _town_kdtree(&Kdtree_TownXYFunc);
65 
66 void RebuildTownKdtree()
67 {
68  std::vector<TownID> townids;
69  for (const Town *town : Town::Iterate()) {
70  townids.push_back(town->index);
71  }
72  _town_kdtree.Build(townids.begin(), townids.end());
73 }
74 
75 
85 static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
86 {
87  if (!IsTileOwner(tile, OWNER_TOWN)) return false;
88 
90  bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
91 
92  if (!town_owned) {
93  /* Or other adjacent road */
95  town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
96  }
97 
98  return town_owned;
99 }
100 
102 {
103  if (CleaningPool()) return;
104 
105  /* Delete town authority window
106  * and remove from list of sorted towns */
108 
109  /* Check no industry is related to us. */
110  for (const Industry *i : Industry::Iterate()) assert(i->town != this);
111 
112  /* ... and no object is related to us. */
113  for (const Object *o : Object::Iterate()) assert(o->town != this);
114 
115  /* Check no tile is related to us. */
116  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
117  switch (GetTileType(tile)) {
118  case MP_HOUSE:
119  assert(GetTownIndex(tile) != this->index);
120  break;
121 
122  case MP_ROAD:
123  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
124  break;
125 
126  case MP_TUNNELBRIDGE:
127  assert(!TestTownOwnsBridge(tile, this));
128  break;
129 
130  default:
131  break;
132  }
133  }
134 
135  /* Clear the persistent storage list. */
136  this->psa_list.clear();
137 
142 }
143 
144 
150 void Town::PostDestructor(size_t index)
151 {
152  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
154 
155  /* Give objects a new home! */
156  for (Object *o : Object::Iterate()) {
157  if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
158  }
159 }
160 
165 {
166  if (layout != TL_RANDOM) {
167  this->layout = layout;
168  return;
169  }
170 
171  this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
172 }
173 
178 /* static */ Town *Town::GetRandom()
179 {
180  if (Town::GetNumItems() == 0) return nullptr;
181  int num = RandomRange((uint16)Town::GetNumItems());
182  size_t index = MAX_UVALUE(size_t);
183 
184  while (num >= 0) {
185  num--;
186  index++;
187 
188  /* Make sure we have a valid town */
189  while (!Town::IsValidID(index)) {
190  index++;
191  assert(index < Town::GetPoolSize());
192  }
193  }
194 
195  return Town::Get(index);
196 }
197 
198 void Town::FillCachedName() const
199 {
201  char *end = GetTownName(buf, this, lastof(buf));
202  this->cached_name.assign(buf, end);
203 }
204 
210 {
211  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
212 }
213 
214 /* Local */
215 static int _grow_town_result;
216 
217 /* Describe the possible states */
218 enum TownGrowthResult {
219  GROWTH_SUCCEED = -1,
220  GROWTH_SEARCH_STOPPED = 0
221 // GROWTH_SEARCH_RUNNING >= 1
222 };
223 
224 static bool BuildTownHouse(Town *t, TileIndex tile);
225 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
226 
227 static void TownDrawHouseLift(const TileInfo *ti)
228 {
229  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
230 }
231 
232 typedef void TownDrawTileProc(const TileInfo *ti);
233 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
234  TownDrawHouseLift
235 };
236 
243 {
244  return (DiagDirection)(3 & Random());
245 }
246 
252 static void DrawTile_Town(TileInfo *ti)
253 {
254  HouseID house_id = GetHouseType(ti->tile);
255 
256  if (house_id >= NEW_HOUSE_OFFSET) {
257  /* Houses don't necessarily need new graphics. If they don't have a
258  * spritegroup associated with them, then the sprite for the substitute
259  * house id is drawn instead. */
260  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
261  DrawNewHouseTile(ti, house_id);
262  return;
263  } else {
264  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
265  }
266  }
267 
268  /* Retrieve pointer to the draw town tile struct */
269  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
270 
272 
273  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
274 
275  /* If houses are invisible, do not draw the upper part */
276  if (IsInvisibilitySet(TO_HOUSES)) return;
277 
278  /* Add a house on top of the ground? */
279  SpriteID image = dcts->building.sprite;
280  if (image != 0) {
281  AddSortableSpriteToDraw(image, dcts->building.pal,
282  ti->x + dcts->subtile_x,
283  ti->y + dcts->subtile_y,
284  dcts->width,
285  dcts->height,
286  dcts->dz,
287  ti->z,
289  );
290 
291  if (IsTransparencySet(TO_HOUSES)) return;
292  }
293 
294  {
295  int proc = dcts->draw_proc - 1;
296 
297  if (proc >= 0) _town_draw_tile_procs[proc](ti);
298  }
299 }
300 
301 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
302 {
303  return GetTileMaxPixelZ(tile);
304 }
305 
308 {
309  HouseID hid = GetHouseType(tile);
310 
311  /* For NewGRF house tiles we might not be drawing a foundation. We need to
312  * account for this, as other structures should
313  * draw the wall of the foundation in this case.
314  */
315  if (hid >= NEW_HOUSE_OFFSET) {
316  const HouseSpec *hs = HouseSpec::Get(hid);
317  if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
318  uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
319  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
320  }
321  }
322  return FlatteningFoundation(tileh);
323 }
324 
331 static void AnimateTile_Town(TileIndex tile)
332 {
333  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
334  AnimateNewHouseTile(tile);
335  return;
336  }
337 
338  if (_tick_counter & 3) return;
339 
340  /* If the house is not one with a lift anymore, then stop this animating.
341  * Not exactly sure when this happens, but probably when a house changes.
342  * Before this was just a return...so it'd leak animated tiles..
343  * That bug seems to have been here since day 1?? */
344  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
345  DeleteAnimatedTile(tile);
346  return;
347  }
348 
349  if (!LiftHasDestination(tile)) {
350  uint i;
351 
352  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
353  * This is due to the fact that the first floor is, in the graphics,
354  * the height of 2 'normal' floors.
355  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
356  do {
357  i = RandomRange(7);
358  } while (i == 1 || i * 6 == GetLiftPosition(tile));
359 
360  SetLiftDestination(tile, i);
361  }
362 
363  int pos = GetLiftPosition(tile);
364  int dest = GetLiftDestination(tile) * 6;
365  pos += (pos < dest) ? 1 : -1;
366  SetLiftPosition(tile, pos);
367 
368  if (pos == dest) {
369  HaltLift(tile);
370  DeleteAnimatedTile(tile);
371  }
372 
373  MarkTileDirtyByTile(tile);
374 }
375 
382 static bool IsCloseToTown(TileIndex tile, uint dist)
383 {
384  if (_town_kdtree.Count() == 0) return false;
385  Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
386  return DistanceManhattan(tile, t->xy) < dist;
387 }
388 
394 {
395  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
396 
397  if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
398 
399  SetDParam(0, this->index);
400  SetDParam(1, this->cache.population);
401  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
402  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
403  STR_VIEWPORT_TOWN);
404 
405  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
406 
408 }
409 
412 {
413  for (Town *t : Town::Iterate()) {
414  t->UpdateVirtCoord();
415  }
416 }
417 
418 void ClearAllTownCachedNames()
419 {
420  for (Town *t : Town::Iterate()) {
421  t->cached_name.clear();
422  }
423 }
424 
430 static void ChangePopulation(Town *t, int mod)
431 {
432  t->cache.population += mod;
433  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
435 
436  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_POPULATION_CHANGE);
437 }
438 
445 {
446  uint32 pop = 0;
447  for (const Town *t : Town::Iterate()) pop += t->cache.population;
448  return pop;
449 }
450 
458 static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
459 {
460  for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
461  const Station *st = *it;
462 
463  bool covers_area = st->TileIsInCatchment(tile);
464  if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
465  if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
466  if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
467 
468  if (covers_area && !st->CatchmentCoversTown(t->index)) {
469  it = t->stations_near.erase(it);
470  } else {
471  ++it;
472  }
473  }
474 }
475 
481 {
482  assert(IsTileType(tile, MP_HOUSE));
483 
484  /* progress in construction stages */
486  if (GetHouseConstructionTick(tile) != 0) return;
487 
488  AnimateNewHouseConstruction(tile);
489 
490  if (IsHouseCompleted(tile)) {
491  /* Now that construction is complete, we can add the population of the
492  * building to the town. */
493  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
494  ResetHouseAge(tile);
495  }
496  MarkTileDirtyByTile(tile);
497 }
498 
504 {
505  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
506  if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
507  if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
508  if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
509  if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
510 }
511 
518 static void TileLoop_Town(TileIndex tile)
519 {
520  HouseID house_id = GetHouseType(tile);
521 
522  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
523  * doesn't exist any more, so don't continue here. */
524  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
525 
526  if (!IsHouseCompleted(tile)) {
527  /* Construction is not completed. See if we can go further in construction*/
528  MakeTownHouseBigger(tile);
529  return;
530  }
531 
532  const HouseSpec *hs = HouseSpec::Get(house_id);
533 
534  /* If the lift has a destination, it is already an animated tile. */
535  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
536  house_id < NEW_HOUSE_OFFSET &&
537  !LiftHasDestination(tile) &&
538  Chance16(1, 2)) {
539  AddAnimatedTile(tile);
540  }
541 
542  Town *t = Town::GetByTile(tile);
543  uint32 r = Random();
544 
545  StationFinder stations(TileArea(tile, 1, 1));
546 
548  for (uint i = 0; i < 256; i++) {
549  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
550 
551  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
552 
553  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
554  if (cargo == CT_INVALID) continue;
555 
556  uint amt = GB(callback, 0, 8);
557  if (amt == 0) continue;
558 
559  uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
560 
561  const CargoSpec *cs = CargoSpec::Get(cargo);
562  t->supplied[cs->Index()].new_max += amt;
563  t->supplied[cs->Index()].new_act += moved;
564  }
565  } else {
567  case TCGM_ORIGINAL:
568  /* Original (quadratic) cargo generation algorithm */
569  if (GB(r, 0, 8) < hs->population) {
570  uint amt = GB(r, 0, 8) / 8 + 1;
571 
572  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
573  t->supplied[CT_PASSENGERS].new_max += amt;
574  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
575  }
576 
577  if (GB(r, 8, 8) < hs->mail_generation) {
578  uint amt = GB(r, 8, 8) / 8 + 1;
579 
580  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
581  t->supplied[CT_MAIL].new_max += amt;
582  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
583  }
584  break;
585 
586  case TCGM_BITCOUNT:
587  /* Binomial distribution per tick, by a series of coin flips */
588  /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
589  * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
590  if (GB(_tick_counter, 8, 2) == GB(tile, 0, 2)) {
591  /* Make a bitmask with up to 32 bits set, one for each potential pax */
592  int genmax = (hs->population + 7) / 8;
593  uint32 genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
594  /* Mask random value by potential pax and count number of actual pax */
595  uint amt = CountBits(r & genmask);
596  /* Adjust and apply */
597  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
598  t->supplied[CT_PASSENGERS].new_max += amt;
599  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
600 
601  /* Do the same for mail, with a fresh random */
602  r = Random();
603  genmax = (hs->mail_generation + 7) / 8;
604  genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
605  amt = CountBits(r & genmask);
606  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
607  t->supplied[CT_MAIL].new_max += amt;
608  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
609  }
610  break;
611 
612  default:
613  NOT_REACHED();
614  }
615  }
616 
617  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
618 
619  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
621  CanDeleteHouse(tile) &&
622  GetHouseAge(tile) >= hs->minimum_life &&
623  --t->time_until_rebuild == 0) {
624  t->time_until_rebuild = GB(r, 16, 8) + 192;
625 
626  ClearTownHouse(t, tile);
627 
628  /* Rebuild with another house? */
629  if (GB(r, 24, 8) >= 12) {
630  /* If we are multi-tile houses, make sure to replace the house
631  * closest to city center. If we do not do this, houses tend to
632  * wander away from roads and other houses. */
633  if (hs->building_flags & BUILDING_HAS_2_TILES) {
634  /* House tiles are always the most north tile. Move the new
635  * house to the south if we are north of the city center. */
636  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
637  int x = Clamp(grid_pos.x, 0, 1);
638  int y = Clamp(grid_pos.y, 0, 1);
639 
640  if (hs->building_flags & TILE_SIZE_2x2) {
641  tile = TILE_ADDXY(tile, x, y);
642  } else if (hs->building_flags & TILE_SIZE_1x2) {
643  tile = TILE_ADDXY(tile, 0, y);
644  } else if (hs->building_flags & TILE_SIZE_2x1) {
645  tile = TILE_ADDXY(tile, x, 0);
646  }
647  }
648 
649  BuildTownHouse(t, tile);
650  }
651  }
652 
653  cur_company.Restore();
654 }
655 
656 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
657 {
658  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
659  if (!CanDeleteHouse(tile)) return CMD_ERROR;
660 
661  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
662 
664  cost.AddCost(hs->GetRemovalCost());
665 
666  int rating = hs->remove_rating_decrease;
667  Town *t = Town::GetByTile(tile);
668 
670  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
671  SetDParam(0, t->index);
672  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
673  }
674  }
675 
676  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
677  if (flags & DC_EXEC) {
678  ClearTownHouse(t, tile);
679  }
680 
681  return cost;
682 }
683 
684 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
685 {
686  HouseID house_id = GetHouseType(tile);
687  const HouseSpec *hs = HouseSpec::Get(house_id);
688  Town *t = Town::GetByTile(tile);
689 
691  for (uint i = 0; i < 256; i++) {
692  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
693 
694  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
695 
696  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
697 
698  if (cargo == CT_INVALID) continue;
699  produced[cargo]++;
700  }
701  } else {
702  if (hs->population > 0) {
703  produced[CT_PASSENGERS]++;
704  }
705  if (hs->mail_generation > 0) {
706  produced[CT_MAIL]++;
707  }
708  }
709 }
710 
711 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
712 {
713  if (cargo == CT_INVALID || amount == 0) return;
714  acceptance[cargo] += amount;
715  SetBit(*always_accepted, cargo);
716 }
717 
718 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
719 {
720  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
721  CargoID accepts[lengthof(hs->accepts_cargo)];
722 
723  /* Set the initial accepted cargo types */
724  for (uint8 i = 0; i < lengthof(accepts); i++) {
725  accepts[i] = hs->accepts_cargo[i];
726  }
727 
728  /* Check for custom accepted cargo types */
730  uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
731  if (callback != CALLBACK_FAILED) {
732  /* Replace accepted cargo types with translated values from callback */
733  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
734  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
735  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
736  }
737  }
738 
739  /* Check for custom cargo acceptance */
741  uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
742  if (callback != CALLBACK_FAILED) {
743  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
744  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
745  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
746  /* The 'S' bit indicates food instead of goods */
747  AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
748  } else {
749  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
750  }
751  return;
752  }
753  }
754 
755  /* No custom acceptance, so fill in with the default values */
756  for (uint8 i = 0; i < lengthof(accepts); i++) {
757  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
758  }
759 }
760 
761 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
762 {
763  const HouseID house = GetHouseType(tile);
764  const HouseSpec *hs = HouseSpec::Get(house);
765  bool house_completed = IsHouseCompleted(tile);
766 
767  td->str = hs->building_name;
768 
769  uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
770  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
771  if (callback_res > 0x400) {
773  } else {
774  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
775  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
776  td->str = new_name;
777  }
778  }
779  }
780 
781  if (!house_completed) {
782  SetDParamX(td->dparam, 0, td->str);
783  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
784  }
785 
786  if (hs->grf_prop.grffile != nullptr) {
787  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
788  td->grf = gc->GetName();
789  }
790 
791  td->owner[0] = OWNER_TOWN;
792 }
793 
794 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
795 {
796  /* not used */
797  return 0;
798 }
799 
800 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
801 {
802  /* not used */
803 }
804 
805 static bool GrowTown(Town *t);
806 
807 static void TownTickHandler(Town *t)
808 {
809  if (HasBit(t->flags, TOWN_IS_GROWING)) {
810  int i = (int)t->grow_counter - 1;
811  if (i < 0) {
812  if (GrowTown(t)) {
813  i = t->growth_rate;
814  } else {
815  /* If growth failed wait a bit before retrying */
816  i = std::min<uint16>(t->growth_rate, TOWN_GROWTH_TICKS - 1);
817  }
818  }
819  t->grow_counter = i;
820  }
821 }
822 
823 void OnTick_Town()
824 {
825  if (_game_mode == GM_EDITOR) return;
826 
827  for (Town *t : Town::Iterate()) {
828  TownTickHandler(t);
829  }
830 }
831 
841 {
842  if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
843 
844  return GetAnyRoadBits(tile, RTT_ROAD, true);
845 }
846 
847 RoadType GetTownRoadType(const Town *t)
848 {
849  RoadType best_rt = ROADTYPE_ROAD;
850  const RoadTypeInfo *best = nullptr;
851  const uint16 assume_max_speed = 50;
852 
853  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
854  if (RoadTypeIsTram(rt)) continue;
855 
856  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
857 
858  /* Unused road type. */
859  if (rti->label == 0) continue;
860 
861  /* Can town build this road. */
862  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
863 
864  /* Not yet introduced at this date. */
865  if (IsInsideMM(rti->introduction_date, 0, MAX_DAY) && rti->introduction_date > _date) continue;
866 
867  if (best != nullptr) {
868  if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
869  }
870 
871  best_rt = rt;
872  best = rti;
873  }
874 
875  return best_rt;
876 }
877 
888 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
889 {
890  if (!IsValidTile(tile)) return false;
891 
892  /* Lookup table for the used diff values */
893  const TileIndexDiff tid_lt[3] = {
897  };
898 
899  dist_multi = (dist_multi + 1) * 4;
900  for (uint pos = 4; pos < dist_multi; pos++) {
901  /* Go (pos / 4) tiles to the left or the right */
902  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
903 
904  /* Use the current tile as origin, or go one tile backwards */
905  if (pos & 2) cur += tid_lt[2];
906 
907  /* Test for roadbit parallel to dir and facing towards the middle axis */
908  if (IsValidTile(tile + cur) &&
909  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
910  }
911  return false;
912 }
913 
922 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
923 {
924  if (DistanceFromEdge(tile) == 0) return false;
925 
926  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
927  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
928 
929  /* Check if there already is a road at this point? */
930  if (GetTownRoadBits(tile) == ROAD_NONE) {
931  /* No, try if we are able to build a road piece there.
932  * If that fails clear the land, and if that fails exit.
933  * This is to make sure that we can build a road here later. */
934  RoadType rt = GetTownRoadType(t);
935  if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X) | (rt << 4), 0, DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Failed() &&
936  DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Failed()) {
937  return false;
938  }
939  }
940 
942  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
943  if (cur_slope == SLOPE_FLAT) return ret;
944 
945  /* If the tile is not a slope in the right direction, then
946  * maybe terraform some. */
947  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
948  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
949  if (Chance16(1, 8)) {
950  CommandCost res = CMD_ERROR;
951  if (!_generating_world && Chance16(1, 10)) {
952  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
953  res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
955  }
956  if (res.Failed() && Chance16(1, 3)) {
957  /* We can consider building on the slope, though. */
958  return ret;
959  }
960  }
961  return false;
962  }
963  return ret;
964 }
965 
966 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
967 {
968  assert(tile < MapSize());
969 
970  CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
971  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
972  DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
973  return true;
974 }
975 
976 static void LevelTownLand(TileIndex tile)
977 {
978  assert(tile < MapSize());
979 
980  /* Don't terraform if land is plain or if there's a house there. */
981  if (IsTileType(tile, MP_HOUSE)) return;
982  Slope tileh = GetTileSlope(tile);
983  if (tileh == SLOPE_FLAT) return;
984 
985  /* First try up, then down */
986  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
987  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
988  }
989 }
990 
1001 {
1002  /* align the grid to the downtown */
1003  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1004  RoadBits rcmd = ROAD_NONE;
1005 
1006  switch (t->layout) {
1007  default: NOT_REACHED();
1008 
1009  case TL_2X2_GRID:
1010  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1011  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1012  break;
1013 
1014  case TL_3X3_GRID:
1015  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1016  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1017  break;
1018  }
1019 
1020  /* Optimise only X-junctions */
1021  if (rcmd != ROAD_ALL) return rcmd;
1022 
1023  RoadBits rb_template;
1024 
1025  switch (GetTileSlope(tile)) {
1026  default: rb_template = ROAD_ALL; break;
1027  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1028  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1029  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1030  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1031  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1032  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1033  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1034  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1035  case SLOPE_STEEP_W:
1036  case SLOPE_STEEP_S:
1037  case SLOPE_STEEP_E:
1038  case SLOPE_STEEP_N:
1039  rb_template = ROAD_NONE;
1040  break;
1041  }
1042 
1043  /* Stop if the template is compatible to the growth dir */
1044  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1045  /* If not generate a straight road in the direction of the growth */
1047 }
1048 
1060 {
1061  /* We can't look further than that. */
1062  if (DistanceFromEdge(tile) == 0) return false;
1063 
1064  uint counter = 0; // counts the house neighbor tiles
1065 
1066  /* Check the tiles E,N,W and S of the current tile for houses */
1067  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1068  /* Count both void and house tiles for checking whether there
1069  * are enough houses in the area. This to make it likely that
1070  * houses get build up to the edge of the map. */
1071  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1072  case MP_HOUSE:
1073  case MP_VOID:
1074  counter++;
1075  break;
1076 
1077  default:
1078  break;
1079  }
1080 
1081  /* If there are enough neighbors stop here */
1082  if (counter >= 3) {
1083  if (BuildTownHouse(t, tile)) {
1084  _grow_town_result = GROWTH_SUCCEED;
1085  return true;
1086  }
1087  return false;
1088  }
1089  }
1090  return false;
1091 }
1092 
1101 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1102 {
1103  RoadType rt = GetTownRoadType(t);
1104  if (DoCommand(tile, rcmd | (rt << 4), t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1105  _grow_town_result = GROWTH_SUCCEED;
1106  return true;
1107  }
1108  return false;
1109 }
1110 
1120 static bool CanRoadContinueIntoNextTile(const Town* t, const TileIndex tile, const DiagDirection road_dir)
1121 {
1122  const int delta = TileOffsByDiagDir(road_dir); // +1 tile in the direction of the road
1123  TileIndex next_tile = tile + delta; // The tile beyond which must be connectable to the target tile
1124  RoadBits rcmd = DiagDirToRoadBits(ReverseDiagDir(road_dir));
1125  RoadType rt = GetTownRoadType(t);
1126 
1127  /* Before we try anything, make sure the tile is on the map and not the void. */
1128  if (!IsValidTile(next_tile)) return false;
1129 
1130  /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1131  if (IsTileType(next_tile, MP_TUNNELBRIDGE)) {
1132  return GetTunnelBridgeTransportType(next_tile) == TRANSPORT_ROAD && GetTunnelBridgeDirection(next_tile) == road_dir;
1133  }
1134 
1135  /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1136  if (IsTileType(next_tile, MP_STATION)) {
1137  /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1138  return IsRoadStop(next_tile) && (GetRoadStopDir(next_tile) == ReverseDiagDir(road_dir) || (IsDriveThroughStopTile(next_tile) && GetRoadStopDir(next_tile) == road_dir));
1139  }
1140 
1141  /* If the next tile is a road depot, allow if it's facing the right way. */
1142  if (IsTileType(next_tile, MP_ROAD)) {
1143  return IsRoadDepot(next_tile) && GetRoadDepotDirection(next_tile) == ReverseDiagDir(road_dir);
1144  }
1145 
1146  /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1147  * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1148  if (IsTileType(next_tile, MP_RAILWAY) && !_settings_game.economy.allow_town_level_crossings) return false;
1149 
1150  /* If a road tile can be built, the construction is allowed. */
1151  return DoCommand(next_tile, rcmd | (rt << 4), t->index, DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded();
1152 }
1153 
1164 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1165 {
1166  assert(bridge_dir < DIAGDIR_END);
1167 
1168  const Slope slope = GetTileSlope(tile);
1169 
1170  /* Make sure the direction is compatible with the slope.
1171  * Well we check if the slope has an up bit set in the
1172  * reverse direction. */
1173  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1174 
1175  /* Assure that the bridge is connectable to the start side */
1176  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1177 
1178  /* We are in the right direction */
1179  uint8 bridge_length = 0; // This value stores the length of the possible bridge
1180  TileIndex bridge_tile = tile; // Used to store the other waterside
1181 
1182  const int delta = TileOffsByDiagDir(bridge_dir);
1183 
1184  /* To prevent really small towns from building disproportionately
1185  * long bridges, make the max a function of its population. */
1186  int base_bridge_length = 5;
1187  int max_bridge_length = t->cache.population / 1000 + base_bridge_length;
1188 
1189  if (slope == SLOPE_FLAT) {
1190  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1191  do {
1192  if (bridge_length++ >= base_bridge_length) {
1193  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1194  return false;
1195  }
1196  bridge_tile += delta;
1197  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1198  } else {
1199  do {
1200  if (bridge_length++ >= max_bridge_length) {
1201  /* Ensure the bridge is not longer than the max allowed length. */
1202  return false;
1203  }
1204  bridge_tile += delta;
1205  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1206  }
1207 
1208  /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1209  if (bridge_length == 1) return false;
1210 
1211  /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1212  if (!CanRoadContinueIntoNextTile(t, bridge_tile, bridge_dir)) return false;
1213 
1214  for (uint8 times = 0; times <= 22; times++) {
1215  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1216 
1217  /* Can we actually build the bridge? */
1218  RoadType rt = GetTownRoadType(t);
1219  if (DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1220  DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1221  _grow_town_result = GROWTH_SUCCEED;
1222  return true;
1223  }
1224  }
1225  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1226  return false;
1227 }
1228 
1239 static bool GrowTownWithTunnel(const Town* t, const TileIndex tile, const DiagDirection tunnel_dir)
1240 {
1241  assert(tunnel_dir < DIAGDIR_END);
1242 
1243  Slope slope = GetTileSlope(tile);
1244 
1245  /* Only consider building a tunnel if the starting tile is sloped properly. */
1246  if (slope != InclinedSlope(tunnel_dir)) return false;
1247 
1248  /* Assure that the tunnel is connectable to the start side */
1249  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(tunnel_dir))) & DiagDirToRoadBits(tunnel_dir))) return false;
1250 
1251  const int delta = TileOffsByDiagDir(tunnel_dir);
1252  int max_tunnel_length = 0;
1253 
1254  /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1255  if (CanRoadContinueIntoNextTile(t, tile, tunnel_dir)) {
1256  /* 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. */
1257  TileIndex slope_tile = tile;
1258  for (uint8 tiles = 0; tiles < 4; tiles++) {
1259  slope = GetTileSlope(slope_tile);
1260  if (slope != InclinedSlope(tunnel_dir) && !IsSteepSlope(slope) && !IsSlopeWithOneCornerRaised(slope)) return false;
1261  slope_tile += delta;
1262  }
1263 
1264  /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which neccesitates tunneling. */
1265  max_tunnel_length = (t->cache.population / 1000) + 7;
1266  } else {
1267  /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1268  max_tunnel_length = 5;
1269  }
1270 
1271  uint8 tunnel_length = 0;
1272  TileIndex tunnel_tile = tile; // Iteratator to store the other end tile of the tunnel.
1273 
1274  /* Find the end tile of the tunnel for length and continuation checks. */
1275  do {
1276  if (tunnel_length++ >= max_tunnel_length) return false;
1277  tunnel_tile += delta;
1278  /* The tunnel ends when start and end tiles are the same height. */
1279  } while (IsValidTile(tunnel_tile) && GetTileZ(tile) != GetTileZ(tunnel_tile));
1280 
1281  /* Don't allow a tunnel where the start and end tiles are adjacent. */
1282  if (tunnel_length == 1) return false;
1283 
1284  /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1285  if (!CanRoadContinueIntoNextTile(t, tunnel_tile, tunnel_dir)) return false;
1286 
1287  /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1288  RoadType rt = GetTownRoadType(t);
1291  _grow_town_result = GROWTH_SUCCEED;
1292  return true;
1293  }
1294 
1295  return false;
1296 }
1297 
1304 static inline bool RoadTypesAllowHouseHere(TileIndex t)
1305 {
1306  static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1307  bool allow = false;
1308 
1309  for (const TileIndexDiffC *ptr = tiles; ptr != endof(tiles); ++ptr) {
1310  TileIndex cur_tile = t + ToTileIndexDiff(*ptr);
1311  if (!IsValidTile(cur_tile)) continue;
1312 
1313  if (!(IsTileType(cur_tile, MP_ROAD) || IsTileType(cur_tile, MP_STATION))) continue;
1314  allow = true;
1315 
1316  RoadType road_rt = GetRoadTypeRoad(cur_tile);
1317  RoadType tram_rt = GetRoadTypeTram(cur_tile);
1318  if (road_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(road_rt)->flags, ROTF_NO_HOUSES)) return true;
1319  if (tram_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(tram_rt)->flags, ROTF_NO_HOUSES)) return true;
1320  }
1321 
1322  /* If no road was found surrounding the tile we can allow building the house since there is
1323  * nothing which forbids it, if a road was found but the execution reached this point, then
1324  * all the found roads don't allow houses to be built */
1325  return !allow;
1326 }
1327 
1345 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1346 {
1347  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1348  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1349 
1350  assert(tile < MapSize());
1351 
1352  if (cur_rb == ROAD_NONE) {
1353  /* Tile has no road. First reset the status counter
1354  * to say that this is the last iteration. */
1355  _grow_town_result = GROWTH_SEARCH_STOPPED;
1356 
1359 
1360  /* Remove hills etc */
1361  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1362 
1363  /* Is a road allowed here? */
1364  switch (t1->layout) {
1365  default: NOT_REACHED();
1366 
1367  case TL_3X3_GRID:
1368  case TL_2X2_GRID:
1369  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1370  if (rcmd == ROAD_NONE) return;
1371  break;
1372 
1373  case TL_BETTER_ROADS:
1374  case TL_ORIGINAL:
1375  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1376 
1377  DiagDirection source_dir = ReverseDiagDir(target_dir);
1378 
1379  if (Chance16(1, 4)) {
1380  /* Randomize a new target dir */
1381  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1382  }
1383 
1384  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1385  /* A road is not allowed to continue the randomized road,
1386  * return if the road we're trying to build is curved. */
1387  if (target_dir != ReverseDiagDir(source_dir)) return;
1388 
1389  /* Return if neither side of the new road is a house */
1392  return;
1393  }
1394 
1395  /* That means that the road is only allowed if there is a house
1396  * at any side of the new road. */
1397  }
1398 
1399  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1400  break;
1401  }
1402 
1403  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1404  /* Continue building on a partial road.
1405  * Should be always OK, so we only generate
1406  * the fitting RoadBits */
1407  _grow_town_result = GROWTH_SEARCH_STOPPED;
1408 
1410 
1411  switch (t1->layout) {
1412  default: NOT_REACHED();
1413 
1414  case TL_3X3_GRID:
1415  case TL_2X2_GRID:
1416  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1417  break;
1418 
1419  case TL_BETTER_ROADS:
1420  case TL_ORIGINAL:
1421  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1422  break;
1423  }
1424  } else {
1425  bool allow_house = true; // Value which decides if we want to construct a house
1426 
1427  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1428  * it is the starting tile. Half the time, we stay on this side then.*/
1429  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1430  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1431  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1432  }
1433  return;
1434  }
1435 
1436  /* Possibly extend the road in a direction.
1437  * Randomize a direction and if it has a road, bail out. */
1438  target_dir = RandomDiagDir();
1439  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1440  TileIndex house_tile; // position of a possible house
1441 
1442  if (cur_rb & target_rb) {
1443  /* If it's a road turn possibly build a house in a corner.
1444  * Use intersection with straight road as an indicator
1445  * that we randomed corner house position.
1446  * A turn (and we check for that later) always has only
1447  * one common bit with a straight road so it has the same
1448  * chance to be chosen as the house on the side of a road.
1449  */
1450  if ((cur_rb & ROAD_X) != target_rb) return;
1451 
1452  /* Check whether it is a turn and if so determine
1453  * position of the corner tile */
1454  switch (cur_rb) {
1455  case ROAD_N:
1456  house_tile = TileAddByDir(tile, DIR_S);
1457  break;
1458  case ROAD_S:
1459  house_tile = TileAddByDir(tile, DIR_N);
1460  break;
1461  case ROAD_E:
1462  house_tile = TileAddByDir(tile, DIR_W);
1463  break;
1464  case ROAD_W:
1465  house_tile = TileAddByDir(tile, DIR_E);
1466  break;
1467  default:
1468  return; // not a turn
1469  }
1470  target_dir = DIAGDIR_END;
1471  } else {
1472  house_tile = TileAddByDiagDir(tile, target_dir);
1473  }
1474 
1475  /* Don't walk into water. */
1476  if (HasTileWaterGround(house_tile)) return;
1477 
1478  if (!IsValidTile(house_tile)) return;
1479 
1481  switch (t1->layout) {
1482  default: NOT_REACHED();
1483 
1484  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1485  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1486  FALLTHROUGH;
1487 
1488  case TL_2X2_GRID:
1489  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1490  allow_house = (rcmd & target_rb) == ROAD_NONE;
1491  break;
1492 
1493  case TL_BETTER_ROADS: // Use original afterwards!
1494  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1495  FALLTHROUGH;
1496 
1497  case TL_ORIGINAL:
1498  /* Allow a house at the edge. 60% chance or
1499  * always ok if no road allowed. */
1500  rcmd = target_rb;
1501  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1502  break;
1503  }
1504  }
1505 
1506  allow_house &= RoadTypesAllowHouseHere(house_tile);
1507 
1508  if (allow_house) {
1509  /* Build a house, but not if there already is a house there. */
1510  if (!IsTileType(house_tile, MP_HOUSE)) {
1511  /* Level the land if possible */
1512  if (Chance16(1, 6)) LevelTownLand(house_tile);
1513 
1514  /* And build a house.
1515  * Set result to -1 if we managed to build it. */
1516  if (BuildTownHouse(t1, house_tile)) {
1517  _grow_town_result = GROWTH_SUCCEED;
1518  }
1519  }
1520  return;
1521  }
1522 
1523  _grow_town_result = GROWTH_SEARCH_STOPPED;
1524  }
1525 
1526  /* Return if a water tile */
1527  if (HasTileWaterGround(tile)) return;
1528 
1529  /* Make the roads look nicer */
1530  rcmd = CleanUpRoadBits(tile, rcmd);
1531  if (rcmd == ROAD_NONE) return;
1532 
1533  /* Only use the target direction for bridges and tunnels to ensure they're connected.
1534  * The target_dir is as computed previously according to town layout, so
1535  * it will match it perfectly. */
1536  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1537  if (GrowTownWithTunnel(t1, tile, target_dir)) return;
1538 
1539  GrowTownWithRoad(t1, tile, rcmd);
1540 }
1541 
1549 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1550 {
1551  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1552  if (!IsValidTile(target_tile)) return false;
1553  if (HasTileWaterGround(target_tile)) return false;
1554 
1555  RoadBits target_rb = GetTownRoadBits(target_tile);
1557  /* Check whether a road connection exists or can be build. */
1558  switch (GetTileType(target_tile)) {
1559  case MP_ROAD:
1560  return target_rb != ROAD_NONE;
1561 
1562  case MP_STATION:
1563  return IsDriveThroughStopTile(target_tile);
1564 
1565  case MP_TUNNELBRIDGE:
1566  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1567 
1568  case MP_HOUSE:
1569  case MP_INDUSTRY:
1570  case MP_OBJECT:
1571  return false;
1572 
1573  default:
1574  /* Checked for void and water earlier */
1575  return true;
1576  }
1577  } else {
1578  /* Check whether a road connection already exists,
1579  * and it leads somewhere else. */
1580  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1581  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1582  }
1583 }
1584 
1591 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1592 {
1593  /* Special case.
1594  * @see GrowTownInTile Check the else if
1595  */
1596  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1597 
1598  assert(tile < MapSize());
1599 
1600  /* Number of times to search.
1601  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1602  * them a little handicap. */
1603  switch (t->layout) {
1604  case TL_BETTER_ROADS:
1605  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1606  break;
1607 
1608  case TL_3X3_GRID:
1609  case TL_2X2_GRID:
1610  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1611  break;
1612 
1613  default:
1614  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1615  break;
1616  }
1617 
1618  do {
1619  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1620 
1621  /* Try to grow the town from this point */
1622  GrowTownInTile(&tile, cur_rb, target_dir, t);
1623  if (_grow_town_result == GROWTH_SUCCEED) return true;
1624 
1625  /* Exclude the source position from the bitmask
1626  * and return if no more road blocks available */
1627  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1628  if (cur_rb == ROAD_NONE) return false;
1629 
1630  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1631  /* Only build in the direction away from the tunnel or bridge. */
1632  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1633  } else {
1634  /* Select a random bit from the blockmask, walk a step
1635  * and continue the search from there. */
1636  do {
1637  if (cur_rb == ROAD_NONE) return false;
1638  RoadBits target_bits;
1639  do {
1640  target_dir = RandomDiagDir();
1641  target_bits = DiagDirToRoadBits(target_dir);
1642  } while (!(cur_rb & target_bits));
1643  cur_rb &= ~target_bits;
1644  } while (!CanFollowRoad(tile, target_dir));
1645  }
1646  tile = TileAddByDiagDir(tile, target_dir);
1647 
1648  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, RTT_ROAD)) {
1649  /* Don't allow building over roads of other cities */
1650  if (IsRoadOwner(tile, RTT_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1651  return false;
1652  } else if (IsRoadOwner(tile, RTT_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1653  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1654  * owner :) (happy happy happy road now) */
1655  SetRoadOwner(tile, RTT_ROAD, OWNER_TOWN);
1656  SetTownIndex(tile, t->index);
1657  }
1658  }
1659 
1660  /* Max number of times is checked. */
1661  } while (--_grow_town_result >= 0);
1662 
1663  return false;
1664 }
1665 
1674 {
1675  uint32 r = Random();
1676  uint a = GB(r, 0, 2);
1677  uint b = GB(r, 8, 2);
1678  if (a == b) b ^= 2;
1679  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1680 }
1681 
1687 static bool GrowTown(Town *t)
1688 {
1689  static const TileIndexDiffC _town_coord_mod[] = {
1690  {-1, 0},
1691  { 1, 1},
1692  { 1, -1},
1693  {-1, -1},
1694  {-1, 0},
1695  { 0, 2},
1696  { 2, 0},
1697  { 0, -2},
1698  {-1, -1},
1699  {-2, 2},
1700  { 2, 2},
1701  { 2, -2},
1702  { 0, 0}
1703  };
1704 
1705  /* Current "company" is a town */
1706  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1707 
1708  TileIndex tile = t->xy; // The tile we are working with ATM
1709 
1710  /* Find a road that we can base the construction on. */
1711  const TileIndexDiffC *ptr;
1712  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1713  if (GetTownRoadBits(tile) != ROAD_NONE) {
1714  bool success = GrowTownAtRoad(t, tile);
1715  cur_company.Restore();
1716  return success;
1717  }
1718  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1719  }
1720 
1721  /* No road available, try to build a random road block by
1722  * clearing some land and then building a road there. */
1724  tile = t->xy;
1725  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1726  /* Only work with plain land that not already has a house */
1727  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1728  if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1729  RoadType rt = GetTownRoadType(t);
1730  DoCommand(tile, GenRandomRoadBits() | (rt << 4), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1731  cur_company.Restore();
1732  return true;
1733  }
1734  }
1735  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1736  }
1737  }
1738 
1739  cur_company.Restore();
1740  return false;
1741 }
1742 
1743 void UpdateTownRadius(Town *t)
1744 {
1745  static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1746  { 4, 0, 0, 0, 0}, // 0
1747  { 16, 0, 0, 0, 0},
1748  { 25, 0, 0, 0, 0},
1749  { 36, 0, 0, 0, 0},
1750  { 49, 0, 4, 0, 0},
1751  { 64, 0, 4, 0, 0}, // 20
1752  { 64, 0, 9, 0, 1},
1753  { 64, 0, 9, 0, 4},
1754  { 64, 0, 16, 0, 4},
1755  { 81, 0, 16, 0, 4},
1756  { 81, 0, 16, 0, 4}, // 40
1757  { 81, 0, 25, 0, 9},
1758  { 81, 36, 25, 0, 9},
1759  { 81, 36, 25, 16, 9},
1760  { 81, 49, 0, 25, 9},
1761  { 81, 64, 0, 25, 9}, // 60
1762  { 81, 64, 0, 36, 9},
1763  { 81, 64, 0, 36, 16},
1764  {100, 81, 0, 49, 16},
1765  {100, 81, 0, 49, 25},
1766  {121, 81, 0, 49, 25}, // 80
1767  {121, 81, 0, 49, 25},
1768  {121, 81, 0, 49, 36}, // 88
1769  };
1770 
1771  if (t->cache.num_houses < 92) {
1772  memcpy(t->cache.squared_town_zone_radius, _town_squared_town_zone_radius_data[t->cache.num_houses / 4], sizeof(t->cache.squared_town_zone_radius));
1773  } else {
1774  int mass = t->cache.num_houses / 8;
1775  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1776  * The offsets are to make sure the radii do not decrease in size when going from the table
1777  * to the calculated value.*/
1778  t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1779  t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1780  t->cache.squared_town_zone_radius[2] = 0;
1781  t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1782  t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1783  }
1784 }
1785 
1786 void UpdateTownMaxPass(Town *t)
1787 {
1788  t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1789  t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1790 }
1791 
1792 static void UpdateTownGrowthRate(Town *t);
1793 static void UpdateTownGrowth(Town *t);
1794 
1806 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1807 {
1808  t->xy = tile;
1809  t->cache.num_houses = 0;
1810  t->time_until_rebuild = 10;
1811  UpdateTownRadius(t);
1812  t->flags = 0;
1813  t->cache.population = 0;
1814  /* Spread growth across ticks so even if there are many
1815  * similar towns they're unlikely to grow all in one tick */
1817  t->growth_rate = TownTicksToGameTicks(250);
1818  t->show_zone = false;
1819 
1820  _town_kdtree.Insert(t->index);
1821 
1822  /* Set the default cargo requirement for town growth */
1824  case LT_ARCTIC:
1826  break;
1827 
1828  case LT_TROPIC:
1831  break;
1832  }
1833 
1834  t->fund_buildings_months = 0;
1835 
1836  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1837 
1838  t->have_ratings = 0;
1840  t->exclusive_counter = 0;
1841  t->statues = 0;
1842 
1843  extern int _nb_orig_names;
1845  /* Original town name */
1846  t->townnamegrfid = 0;
1847  t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1848  } else {
1849  /* Newgrf town name */
1850  t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1851  t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1852  }
1853  t->townnameparts = townnameparts;
1854 
1855  t->UpdateVirtCoord();
1856  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
1857 
1858  t->InitializeLayout(layout);
1859 
1860  t->larger_town = city;
1861 
1862  int x = (int)size * 16 + 3;
1863  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1864  /* Don't create huge cities when founding town in-game */
1865  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1866 
1867  t->cache.num_houses += x;
1868  UpdateTownRadius(t);
1869 
1870  int i = x * 4;
1871  do {
1872  GrowTown(t);
1873  } while (--i);
1874 
1875  t->cache.num_houses -= x;
1876  UpdateTownRadius(t);
1878  UpdateTownMaxPass(t);
1880 }
1881 
1888 {
1889  /* Check if too close to the edge of map */
1890  if (DistanceFromEdge(tile) < 12) {
1891  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1892  }
1893 
1894  /* Check distance to all other towns. */
1895  if (IsCloseToTown(tile, 20)) {
1896  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1897  }
1898 
1899  /* Can only build on clear flat areas, possibly with trees. */
1900  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1901  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1902  }
1903 
1904  return CommandCost(EXPENSES_OTHER);
1905 }
1906 
1912 static bool IsUniqueTownName(const char *name)
1913 {
1914  for (const Town *t : Town::Iterate()) {
1915  if (!t->name.empty() && t->name == name) return false;
1916  }
1917 
1918  return true;
1919 }
1920 
1933 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1934 {
1935  TownSize size = Extract<TownSize, 0, 2>(p1);
1936  bool city = HasBit(p1, 2);
1937  TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1939  bool random = HasBit(p1, 6);
1940  uint32 townnameparts = p2;
1941 
1942  if (size >= TSZ_END) return CMD_ERROR;
1943  if (layout >= NUM_TLS) return CMD_ERROR;
1944 
1945  /* Some things are allowed only in the scenario editor and for game scripts. */
1946  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1948  if (size == TSZ_LARGE) return CMD_ERROR;
1949  if (random) return CMD_ERROR;
1951  return CMD_ERROR;
1952  }
1953  } else if (_current_company == OWNER_DEITY && random) {
1954  /* Random parameter is not allowed for Game Scripts. */
1955  return CMD_ERROR;
1956  }
1957 
1958  if (StrEmpty(text)) {
1959  /* If supplied name is empty, townnameparts has to generate unique automatic name */
1960  if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1961  } else {
1962  /* If name is not empty, it has to be unique custom name */
1964  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1965  }
1966 
1967  /* Allocate town struct */
1968  if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1969 
1970  if (!random) {
1971  CommandCost ret = TownCanBePlacedHere(tile);
1972  if (ret.Failed()) return ret;
1973  }
1974 
1975  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1976  /* multidimensional arrays have to have defined length of non-first dimension */
1977  static_assert(lengthof(price_mult[0]) == 4);
1978 
1979  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1980  byte mult = price_mult[city][size];
1981 
1982  cost.MultiplyCost(mult);
1983 
1984  /* Create the town */
1985  if (flags & DC_EXEC) {
1986  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1987  _additional_cash_required = cost.GetCost();
1988  return CommandCost(EXPENSES_OTHER);
1989  }
1990 
1991  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1993  Town *t;
1994  if (random) {
1995  t = CreateRandomTown(20, townnameparts, size, city, layout);
1996  if (t == nullptr) {
1997  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1998  } else {
1999  _new_town_id = t->index;
2000  }
2001  } else {
2002  t = new Town(tile);
2003  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
2004  }
2006  old_generating_world.Restore();
2007 
2008  if (t != nullptr && !StrEmpty(text)) {
2009  t->name = stredup(text);
2010  t->UpdateVirtCoord();
2011  }
2012 
2013  if (_game_mode != GM_EDITOR) {
2014  /* 't' can't be nullptr since 'random' is false outside scenedit */
2015  assert(!random);
2016 
2017  if (_current_company == OWNER_DEITY) {
2018  SetDParam(0, t->index);
2019  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
2020  } else {
2021  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2023  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2024 
2025  char *cn = stredup(company_name);
2026  SetDParamStr(0, cn);
2027  SetDParam(1, t->index);
2028 
2029  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
2030  }
2031  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
2032  Game::NewEvent(new ScriptEventTownFounded(t->index));
2033  }
2034  }
2035  return cost;
2036 }
2037 
2048 {
2049  switch (layout) {
2050  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
2051  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
2052  default: return tile;
2053  }
2054 }
2055 
2065 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
2066 {
2067  switch (layout) {
2068  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2069  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2070  default: return true;
2071  }
2072 }
2073 
2077 struct SpotData {
2079  uint max_dist;
2081 };
2082 
2099 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
2100 {
2101  SpotData *sp = (SpotData*)user_data;
2102  uint dist = GetClosestWaterDistance(tile, true);
2103 
2104  if (IsTileType(tile, MP_CLEAR) &&
2105  IsTileFlat(tile) &&
2106  IsTileAlignedToGrid(tile, sp->layout) &&
2107  dist > sp->max_dist) {
2108  sp->tile = tile;
2109  sp->max_dist = dist;
2110  }
2111 
2112  return false;
2113 }
2114 
2121 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
2122 {
2123  return IsTileType(tile, MP_CLEAR);
2124 }
2125 
2139 {
2140  SpotData sp = { INVALID_TILE, 0, layout };
2141 
2142  TileIndex coast = tile;
2143  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
2144  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
2145  return sp.tile;
2146  }
2147 
2148  /* if we get here just give up */
2149  return INVALID_TILE;
2150 }
2151 
2152 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
2153 {
2154  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
2155 
2156  if (!Town::CanAllocateItem()) return nullptr;
2157 
2158  do {
2159  /* Generate a tile index not too close from the edge */
2160  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2161 
2162  /* if we tried to place the town on water, slide it over onto
2163  * the nearest likely-looking spot */
2164  if (IsTileType(tile, MP_WATER)) {
2165  tile = FindNearestGoodCoastalTownSpot(tile, layout);
2166  if (tile == INVALID_TILE) continue;
2167  }
2168 
2169  /* Make sure town can be placed here */
2170  if (TownCanBePlacedHere(tile).Failed()) continue;
2171 
2172  /* Allocate a town struct */
2173  Town *t = new Town(tile);
2174 
2175  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2176 
2177  /* if the population is still 0 at the point, then the
2178  * placement is so bad it couldn't grow at all */
2179  if (t->cache.population > 0) return t;
2180 
2181  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2183  cur_company.Restore();
2184  assert(rc.Succeeded());
2185 
2186  /* We already know that we can allocate a single town when
2187  * entering this function. However, we create and delete
2188  * a town which "resets" the allocation checks. As such we
2189  * need to check again when assertions are enabled. */
2190  assert(Town::CanAllocateItem());
2191  } while (--attempts != 0);
2192 
2193  return nullptr;
2194 }
2195 
2196 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2197 
2206 {
2207  uint current_number = 0;
2208  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2209  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
2210  total = std::min<uint>(TownPool::MAX_SIZE, total);
2211  uint32 townnameparts;
2212  TownNames town_names;
2213 
2215 
2216  /* First attempt will be made at creating the suggested number of towns.
2217  * Note that this is really a suggested value, not a required one.
2218  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2219  do {
2222  /* Get a unique name for the town. */
2223  if (!GenerateTownName(&townnameparts, &town_names)) continue;
2224  /* try 20 times to create a random-sized town for the first loop. */
2225  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2226  } while (--total);
2227 
2228  town_names.clear();
2229 
2230  /* Build the town k-d tree again to make sure it's well balanced */
2231  RebuildTownKdtree();
2232 
2233  if (current_number != 0) return true;
2234 
2235  /* If current_number is still zero at this point, it means that not a single town has been created.
2236  * So give it a last try, but now more aggressive */
2237  if (GenerateTownName(&townnameparts) &&
2238  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2239  return true;
2240  }
2241 
2242  /* If there are no towns at all and we are generating new game, bail out */
2243  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2244  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2245  }
2246 
2247  return false; // we are still without a town? we failed, simply
2248 }
2249 
2250 
2257 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2258 {
2259  uint dist = DistanceSquare(tile, t->xy);
2260 
2261  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2262 
2263  HouseZonesBits smallest = HZB_TOWN_EDGE;
2264  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2265  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2266  }
2267 
2268  return smallest;
2269 }
2270 
2281 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2282 {
2284 
2285  assert(cc.Succeeded());
2286 
2287  IncreaseBuildingCount(t, type);
2288  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2289  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2290 
2291  MarkTileDirtyByTile(tile);
2292 }
2293 
2294 
2305 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2306 {
2307  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2308 
2309  ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2310  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2311  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2312  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2313 
2314  if (!_generating_world) {
2315  ForAllStationsAroundTiles(TileArea(t, (size & BUILDING_2_TILES_X) ? 2 : 1, (size & BUILDING_2_TILES_Y) ? 2 : 1), [town](Station *st, TileIndex tile) {
2316  town->stations_near.insert(st);
2317  return true;
2318  });
2319  }
2320 }
2321 
2322 
2330 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2331 {
2332  /* cannot build on these slopes... */
2333  Slope slope = GetTileSlope(tile);
2334  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2335 
2336  /* at least one RoadTypes allow building the house here? */
2337  if (!RoadTypesAllowHouseHere(tile)) return false;
2338 
2339  /* building under a bridge? */
2340  if (IsBridgeAbove(tile)) return false;
2341 
2342  /* can we clear the land? */
2343  return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2344 }
2345 
2346 
2355 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2356 {
2357  if (!CanBuildHouseHere(tile, noslope)) return false;
2358 
2359  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2360  if (GetTileMaxZ(tile) != z) return false;
2361 
2362  return true;
2363 }
2364 
2365 
2374 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2375 {
2376  /* we need to check this tile too because we can be at different tile now */
2377  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2378 
2379  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2380  tile += TileOffsByDiagDir(d);
2381  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2382  }
2383 
2384  return true;
2385 }
2386 
2387 
2395 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2396 {
2397  /* Allow towns everywhere when we don't build roads */
2399 
2400  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2401 
2402  switch (t->layout) {
2403  case TL_2X2_GRID:
2404  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2405  break;
2406 
2407  case TL_3X3_GRID:
2408  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2409  break;
2410 
2411  default:
2412  break;
2413  }
2414 
2415  return true;
2416 }
2417 
2418 
2426 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2427 {
2428  /* Allow towns everywhere when we don't build roads */
2430 
2431  /* Compute relative position of tile. (Positive offsets are towards north) */
2432  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2433 
2434  switch (t->layout) {
2435  case TL_2X2_GRID:
2436  grid_pos.x %= 3;
2437  grid_pos.y %= 3;
2438  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2439  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2440  break;
2441 
2442  case TL_3X3_GRID:
2443  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2444  break;
2445 
2446  default:
2447  break;
2448  }
2449 
2450  return true;
2451 }
2452 
2453 
2463 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2464 {
2465  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2466 
2467  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2468  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2469 
2470  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2471  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2472  *tile = tile2;
2473  return true;
2474  }
2475 
2476  return false;
2477 }
2478 
2479 
2488 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2489 {
2490  TileIndex tile2 = *tile;
2491 
2492  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2493  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2494  *tile = tile2;
2495  return true;
2496  }
2497  if (d == DIAGDIR_END) break;
2498  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2499  }
2500 
2501  return false;
2502 }
2503 
2504 
2511 static bool BuildTownHouse(Town *t, TileIndex tile)
2512 {
2513  /* forbidden building here by town layout */
2514  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2515 
2516  /* no house allowed at all, bail out */
2517  if (!CanBuildHouseHere(tile, false)) return false;
2518 
2519  Slope slope = GetTileSlope(tile);
2520  int maxz = GetTileMaxZ(tile);
2521 
2522  /* Get the town zone type of the current tile, as well as the climate.
2523  * This will allow to easily compare with the specs of the new house to build */
2524  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2525 
2526  /* Above snow? */
2528  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2529 
2530  uint bitmask = (1 << rad) + (1 << (land + 12));
2531 
2532  /* bits 0-4 are used
2533  * bits 11-15 are used
2534  * bits 5-10 are not used. */
2535  HouseID houses[NUM_HOUSES];
2536  uint num = 0;
2537  uint probs[NUM_HOUSES];
2538  uint probability_max = 0;
2539 
2540  /* Generate a list of all possible houses that can be built. */
2541  for (uint i = 0; i < NUM_HOUSES; i++) {
2542  const HouseSpec *hs = HouseSpec::Get(i);
2543 
2544  /* Verify that the candidate house spec matches the current tile status */
2545  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2546 
2547  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2548  if (hs->class_id != HOUSE_NO_CLASS) {
2549  /* id_count is always <= class_count, so it doesn't need to be checked */
2550  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2551  } else {
2552  /* If the house has no class, check id_count instead */
2553  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2554  }
2555 
2556  uint cur_prob = hs->probability;
2557  probability_max += cur_prob;
2558  probs[num] = cur_prob;
2559  houses[num++] = (HouseID)i;
2560  }
2561 
2562  TileIndex baseTile = tile;
2563 
2564  while (probability_max > 0) {
2565  /* Building a multitile building can change the location of tile.
2566  * The building would still be built partially on that tile, but
2567  * its northern tile would be elsewhere. However, if the callback
2568  * fails we would be basing further work from the changed tile.
2569  * So a next 1x1 tile building could be built on the wrong tile. */
2570  tile = baseTile;
2571 
2572  uint r = RandomRange(probability_max);
2573  uint i;
2574  for (i = 0; i < num; i++) {
2575  if (probs[i] > r) break;
2576  r -= probs[i];
2577  }
2578 
2579  HouseID house = houses[i];
2580  probability_max -= probs[i];
2581 
2582  /* remove tested house from the set */
2583  num--;
2584  houses[i] = houses[num];
2585  probs[i] = probs[num];
2586 
2587  const HouseSpec *hs = HouseSpec::Get(house);
2588 
2589  if (!_generating_world && _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2590  continue;
2591  }
2592 
2593  if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2594 
2595  /* Special houses that there can be only one of. */
2596  uint oneof = 0;
2597 
2598  if (hs->building_flags & BUILDING_IS_CHURCH) {
2599  SetBit(oneof, TOWN_HAS_CHURCH);
2600  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2601  SetBit(oneof, TOWN_HAS_STADIUM);
2602  }
2603 
2604  if (t->flags & oneof) continue;
2605 
2606  /* Make sure there is no slope? */
2607  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2608  if (noslope && slope != SLOPE_FLAT) continue;
2609 
2610  if (hs->building_flags & TILE_SIZE_2x2) {
2611  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2612  } else if (hs->building_flags & TILE_SIZE_2x1) {
2613  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2614  } else if (hs->building_flags & TILE_SIZE_1x2) {
2615  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2616  } else {
2617  /* 1x1 house checks are already done */
2618  }
2619 
2620  byte random_bits = Random();
2621 
2623  uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2624  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2625  }
2626 
2627  /* build the house */
2628  t->cache.num_houses++;
2629 
2630  /* Special houses that there can be only one of. */
2631  t->flags |= oneof;
2632 
2633  byte construction_counter = 0;
2634  byte construction_stage = 0;
2635 
2636  if (_generating_world || _game_mode == GM_EDITOR) {
2637  uint32 r = Random();
2638 
2639  construction_stage = TOWN_HOUSE_COMPLETED;
2640  if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2641 
2642  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2643  ChangePopulation(t, hs->population);
2644  } else {
2645  construction_counter = GB(r, 2, 2);
2646  }
2647  }
2648 
2649  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2650  UpdateTownRadius(t);
2652 
2653  return true;
2654  }
2655 
2656  return false;
2657 }
2658 
2665 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2666 {
2667  assert(IsTileType(tile, MP_HOUSE));
2668  DecreaseBuildingCount(t, house);
2669  DoClearSquare(tile);
2670  DeleteAnimatedTile(tile);
2671 
2672  DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2673 }
2674 
2683 {
2684  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2685  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2686  house--;
2687  return TileDiffXY(-1, 0);
2688  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2689  house--;
2690  return TileDiffXY(0, -1);
2691  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2692  house -= 2;
2693  return TileDiffXY(-1, 0);
2694  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2695  house -= 3;
2696  return TileDiffXY(-1, -1);
2697  }
2698  }
2699  return 0;
2700 }
2701 
2702 void ClearTownHouse(Town *t, TileIndex tile)
2703 {
2704  assert(IsTileType(tile, MP_HOUSE));
2705 
2706  HouseID house = GetHouseType(tile);
2707 
2708  /* need to align the tile to point to the upper left corner of the house */
2709  tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2710 
2711  const HouseSpec *hs = HouseSpec::Get(house);
2712 
2713  /* Remove population from the town if the house is finished. */
2714  if (IsHouseCompleted(tile)) {
2715  ChangePopulation(t, -hs->population);
2716  }
2717 
2718  t->cache.num_houses--;
2719 
2720  /* Clear flags for houses that only may exist once/town. */
2721  if (hs->building_flags & BUILDING_IS_CHURCH) {
2723  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2725  }
2726 
2727  /* Do the actual clearing of tiles */
2728  DoClearTownHouseHelper(tile, t, house);
2729  if (hs->building_flags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2730  if (hs->building_flags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2731  if (hs->building_flags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2732 
2733  RemoveNearbyStations(t, tile, hs->building_flags);
2734 
2735  UpdateTownRadius(t);
2736 }
2737 
2747 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2748 {
2749  Town *t = Town::GetIfValid(p1);
2750  if (t == nullptr) return CMD_ERROR;
2751 
2752  bool reset = StrEmpty(text);
2753 
2754  if (!reset) {
2756  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2757  }
2758 
2759  if (flags & DC_EXEC) {
2760  t->cached_name.clear();
2761  if (reset) {
2762  t->name.clear();
2763  } else {
2764  t->name = text;
2765  }
2766 
2767  t->UpdateVirtCoord();
2768  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_RESORT);
2769  ClearAllStationCachedNames();
2770  ClearAllIndustryCachedNames();
2772  }
2773  return CommandCost();
2774 }
2775 
2782 {
2783  const CargoSpec *cs;
2784  FOR_ALL_CARGOSPECS(cs) {
2785  if (cs->town_effect == effect) return cs;
2786  }
2787  return nullptr;
2788 }
2789 
2801 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2802 {
2803  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2804 
2805  TownEffect te = (TownEffect)GB(p1, 16, 8);
2806  if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2807 
2808  uint16 index = GB(p1, 0, 16);
2809  Town *t = Town::GetIfValid(index);
2810  if (t == nullptr) return CMD_ERROR;
2811 
2812  /* Validate if there is a cargo which is the requested TownEffect */
2813  const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2814  if (cargo == nullptr) return CMD_ERROR;
2815 
2816  if (flags & DC_EXEC) {
2817  t->goal[te] = p2;
2818  UpdateTownGrowth(t);
2820  }
2821 
2822  return CommandCost();
2823 }
2824 
2834 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2835 {
2836  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2837  Town *t = Town::GetIfValid(p1);
2838  if (t == nullptr) return CMD_ERROR;
2839 
2840  if (flags & DC_EXEC) {
2841  t->text.clear();
2842  if (!StrEmpty(text)) t->text = text;
2844  }
2845 
2846  return CommandCost();
2847 }
2848 
2858 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2859 {
2860  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2861  if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2862 
2863  Town *t = Town::GetIfValid(p1);
2864  if (t == nullptr) return CMD_ERROR;
2865 
2866  if (flags & DC_EXEC) {
2867  if (p2 == 0) {
2868  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
2870  } else {
2871  uint old_rate = t->growth_rate;
2872  if (t->grow_counter >= old_rate) {
2873  /* This also catches old_rate == 0 */
2874  t->grow_counter = p2;
2875  } else {
2876  /* Scale grow_counter, so half finished houses stay half finished */
2877  t->grow_counter = t->grow_counter * p2 / old_rate;
2878  }
2879  t->growth_rate = p2;
2881  }
2882  UpdateTownGrowth(t);
2884  }
2885 
2886  return CommandCost();
2887 }
2888 
2898 CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2899 {
2900  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2901 
2902  TownID town_id = (TownID)GB(p1, 0, 16);
2903  Town *t = Town::GetIfValid(town_id);
2904  if (t == nullptr) return CMD_ERROR;
2905 
2906  CompanyID company_id = (CompanyID)GB(p1, 16, 8);
2907  if (!Company::IsValidID(company_id)) return CMD_ERROR;
2908 
2909  int16 new_rating = Clamp((int16)GB(p2, 0, 16), RATING_MINIMUM, RATING_MAXIMUM);
2910  if (flags & DC_EXEC) {
2911  t->ratings[company_id] = new_rating;
2913  }
2914 
2915  return CommandCost();
2916 }
2917 
2927 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2928 {
2929  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2930  Town *t = Town::GetIfValid(p1);
2931  if (t == nullptr) return CMD_ERROR;
2932 
2933  if (flags & DC_EXEC) {
2934  /* The more houses, the faster we grow */
2935  if (p2 == 0) {
2936  uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2937  t->cache.num_houses += amount;
2938  UpdateTownRadius(t);
2939 
2940  uint n = amount * 10;
2941  do GrowTown(t); while (--n);
2942 
2943  t->cache.num_houses -= amount;
2944  } else {
2945  for (; p2 > 0; p2--) {
2946  /* Try several times to grow, as we are really suppose to grow */
2947  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2948  }
2949  }
2950  UpdateTownRadius(t);
2951 
2952  UpdateTownMaxPass(t);
2953  }
2954 
2955  return CommandCost();
2956 }
2957 
2967 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2968 {
2969  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2970  Town *t = Town::GetIfValid(p1);
2971  if (t == nullptr) return CMD_ERROR;
2972 
2973  /* Stations refer to towns. */
2974  for (const Station *st : Station::Iterate()) {
2975  if (st->town == t) {
2976  /* Non-oil rig stations are always a problem. */
2977  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2978  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2979  CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2980  if (ret.Failed()) return ret;
2981  }
2982  }
2983 
2984  /* Depots refer to towns. */
2985  for (const Depot *d : Depot::Iterate()) {
2986  if (d->town == t) return CMD_ERROR;
2987  }
2988 
2989  /* Check all tiles for town ownership. First check for bridge tiles, as
2990  * these do not directly have an owner so we need to check adjacent
2991  * tiles. This won't work correctly in the same loop if the adjacent
2992  * tile was already deleted earlier in the loop. */
2993  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2994  if (IsTileType(tile, MP_TUNNELBRIDGE) && TestTownOwnsBridge(tile, t)) {
2995  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2996  if (ret.Failed()) return ret;
2997  }
2998  }
2999 
3000  /* Check all remaining tiles for town ownership. */
3001  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
3002  bool try_clear = false;
3003  switch (GetTileType(tile)) {
3004  case MP_ROAD:
3005  try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
3006  break;
3007 
3008  case MP_HOUSE:
3009  try_clear = GetTownIndex(tile) == t->index;
3010  break;
3011 
3012  case MP_INDUSTRY:
3013  try_clear = Industry::GetByTile(tile)->town == t;
3014  break;
3015 
3016  case MP_OBJECT:
3017  if (Town::GetNumItems() == 1) {
3018  /* No towns will be left, remove it! */
3019  try_clear = true;
3020  } else {
3021  Object *o = Object::GetByTile(tile);
3022  if (o->town == t) {
3023  if (o->type == OBJECT_STATUE) {
3024  /* Statue... always remove. */
3025  try_clear = true;
3026  } else {
3027  /* Tell to find a new town. */
3028  if (flags & DC_EXEC) o->town = nullptr;
3029  }
3030  }
3031  }
3032  break;
3033 
3034  default:
3035  break;
3036  }
3037  if (try_clear) {
3038  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3039  if (ret.Failed()) return ret;
3040  }
3041  }
3042 
3043  /* The town destructor will delete the other things related to the town. */
3044  if (flags & DC_EXEC) {
3045  _town_kdtree.Remove(t->index);
3046  if (t->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
3047  delete t;
3048  }
3049 
3050  return CommandCost();
3051 }
3052 
3058  2, 4, 9, 35, 48, 53, 117, 175
3059 };
3060 
3061 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
3062 {
3063  if (flags & DC_EXEC) {
3064  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
3065  }
3066  return CommandCost();
3067 }
3068 
3069 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
3070 {
3071  if (flags & DC_EXEC) {
3072  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
3073  }
3074  return CommandCost();
3075 }
3076 
3077 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
3078 {
3079  if (flags & DC_EXEC) {
3080  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
3081  }
3082  return CommandCost();
3083 }
3084 
3085 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
3086 {
3087  /* Check if the company is allowed to fund new roads. */
3089 
3090  if (flags & DC_EXEC) {
3091  t->road_build_months = 6;
3092 
3093  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
3095  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
3096 
3097  char *cn = stredup(company_name);
3098  SetDParam(0, t->index);
3099  SetDParamStr(1, cn);
3100 
3101  AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
3102  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3103  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3104  }
3105  return CommandCost();
3106 }
3107 
3113 static bool TryClearTile(TileIndex tile)
3114 {
3115  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3117  cur_company.Restore();
3118  return r.Succeeded();
3119 }
3120 
3125 
3126  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
3127 };
3128 
3135 static bool SearchTileForStatue(TileIndex tile, void *user_data)
3136 {
3137  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3138 
3139  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
3140  statue_data->tile_count++;
3141 
3142  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3143  if (IsSteepSlope(GetTileSlope(tile))) return false;
3144  /* Don't build statues under bridges. */
3145  if (IsBridgeAbove(tile)) return false;
3146 
3147  /* A clear-able open space is always preferred. */
3148  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
3149  statue_data->best_position = tile;
3150  return true;
3151  }
3152 
3153  bool house = IsTileType(tile, MP_HOUSE);
3154 
3155  /* Searching inside the inner circle. */
3156  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
3157  /* Save first house in inner circle. */
3158  if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
3159  statue_data->best_position = tile;
3160  }
3161 
3162  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3163  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
3164  }
3165 
3166  /* Searching outside the circle, just pick the first possible spot. */
3167  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
3168  return house && TryClearTile(tile);
3169 }
3170 
3179 {
3180  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
3181 
3182  TileIndex tile = t->xy;
3183  StatueBuildSearchData statue_data(INVALID_TILE, 0);
3184  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3185 
3186  if (flags & DC_EXEC) {
3187  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3188  DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
3189  cur_company.Restore();
3191  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
3192  MarkTileDirtyByTile(statue_data.best_position);
3193  }
3194  return CommandCost();
3195 }
3196 
3197 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
3198 {
3199  /* Check if it's allowed to buy the rights */
3201 
3202  if (flags & DC_EXEC) {
3203  /* And grow for 3 months */
3204  t->fund_buildings_months = 3;
3205 
3206  /* Enable growth (also checking GameScript's opinion) */
3207  UpdateTownGrowth(t);
3208 
3209  /* Build a new house, but add a small delay to make sure
3210  * that spamming funding doesn't let town grow any faster
3211  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3212  * Also emulate original behaviour when town was only growing in
3213  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3214  * tick-perfect and gives player some time window where he can
3215  * spam funding with the exact same efficiency.
3216  */
3217  t->grow_counter = std::min<uint16>(t->grow_counter, 2 * TOWN_GROWTH_TICKS - (t->growth_rate - t->grow_counter) % TOWN_GROWTH_TICKS);
3218 
3220  }
3221  return CommandCost();
3222 }
3223 
3224 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
3225 {
3226  /* Check if it's allowed to buy the rights */
3228 
3229  if (flags & DC_EXEC) {
3230  t->exclusive_counter = 12;
3232 
3233  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3234 
3236 
3237  /* Spawn news message */
3238  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
3240  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3241  SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
3242  SetDParam(2, t->index);
3243  SetDParamStr(3, cni->company_name);
3244  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3245  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3246  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3247  }
3248  return CommandCost();
3249 }
3250 
3251 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
3252 {
3253  if (flags & DC_EXEC) {
3254  if (Chance16(1, 14)) {
3255  /* set as unwanted for 6 months */
3256  t->unwanted[_current_company] = 6;
3257 
3258  /* set all close by station ratings to 0 */
3259  for (Station *st : Station::Iterate()) {
3260  if (st->town == t && st->owner == _current_company) {
3261  for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
3262  }
3263  }
3264 
3265  /* only show error message to the executing player. All errors are handled command.c
3266  * but this is special, because it can only 'fail' on a DC_EXEC */
3267  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3268 
3269  /* decrease by a lot!
3270  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3271  * be independent of any cheat settings
3272  */
3273  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3274  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3276  }
3277  } else {
3278  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3279  }
3280  }
3281  return CommandCost();
3282 }
3283 
3284 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3285 static TownActionProc * const _town_action_proc[] = {
3286  TownActionAdvertiseSmall,
3287  TownActionAdvertiseMedium,
3288  TownActionAdvertiseLarge,
3289  TownActionRoadRebuild,
3291  TownActionFundBuildings,
3292  TownActionBuyRights,
3293  TownActionBribe
3294 };
3295 
3303 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3304 {
3305  int num = 0;
3306  TownActions buttons = TACT_NONE;
3307 
3308  /* Spectators and unwanted have no options */
3309  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3310 
3311  /* Things worth more than this are not shown */
3312  Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3313 
3314  /* Check the action bits for validity and
3315  * if they are valid add them */
3316  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3317  const TownActions cur = (TownActions)(1 << i);
3318 
3319  /* Is the company not able to bribe ? */
3320  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3321 
3322  /* Is the company not able to buy exclusive rights ? */
3323  if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3324 
3325  /* Is the company not able to fund buildings ? */
3326  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3327 
3328  /* Is the company not able to fund local road reconstruction? */
3329  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3330 
3331  /* Is the company not able to build a statue ? */
3332  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3333 
3334  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3335  buttons |= cur;
3336  num++;
3337  }
3338  }
3339  }
3340 
3341  if (nump != nullptr) *nump = num;
3342  return buttons;
3343 }
3344 
3356 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3357 {
3358  Town *t = Town::GetIfValid(p1);
3359  if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3360 
3361  if (!HasBit(GetMaskOfTownActions(nullptr, _current_company, t), p2)) return CMD_ERROR;
3362 
3363  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3364 
3365  CommandCost ret = _town_action_proc[p2](t, flags);
3366  if (ret.Failed()) return ret;
3367 
3368  if (flags & DC_EXEC) {
3370  }
3371 
3372  return cost;
3373 }
3374 
3375 template <typename Func>
3376 static void ForAllStationsNearTown(Town *t, Func func)
3377 {
3378  /* Ideally the search radius should be close to the actual town zone 0 radius.
3379  * The true radius is not stored or calculated anywhere, only the squared radius. */
3380  /* The efficiency of this search might be improved for large towns and many stations on the map,
3381  * by using an integer square root approximation giving a value not less than the true square root. */
3382  uint search_radius = t->cache.squared_town_zone_radius[0] / 2;
3383  ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3384  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3385  func(st);
3386  }
3387  });
3388 }
3389 
3390 static void UpdateTownRating(Town *t)
3391 {
3392  /* Increase company ratings if they're low */
3393  for (const Company *c : Company::Iterate()) {
3394  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3395  t->ratings[c->index] = std::min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3396  }
3397  }
3398 
3399  ForAllStationsNearTown(t, [&](const Station *st) {
3400  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3401  if (Company::IsValidID(st->owner)) {
3402  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3403  t->ratings[st->owner] = std::min<int>(new_rating, INT16_MAX); // do not let it overflow
3404  }
3405  } else {
3406  if (Company::IsValidID(st->owner)) {
3407  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3408  t->ratings[st->owner] = std::max(new_rating, INT16_MIN);
3409  }
3410  }
3411  });
3412 
3413  /* clamp all ratings to valid values */
3414  for (uint i = 0; i < MAX_COMPANIES; i++) {
3415  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3416  }
3417 
3419 }
3420 
3421 
3428 static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
3429 {
3430  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3431  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3432  t->grow_counter = std::min<uint16>(t->growth_rate, t->grow_counter);
3433  return;
3434  }
3435  t->grow_counter = RoundDivSU((uint32)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3436 }
3437 
3444 {
3445  int n = 0;
3446  ForAllStationsNearTown(t, [&](const Station * st) {
3447  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3448  n++;
3449  }
3450  });
3451  return n;
3452 }
3453 
3460 static uint GetNormalGrowthRate(Town *t)
3461 {
3467  static const uint16 _grow_count_values[2][6] = {
3468  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3469  { 320, 420, 300, 220, 160, 100 } // Normal values
3470  };
3471 
3472  int n = CountActiveStations(t);
3473  uint16 m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][std::min(n, 5)];
3474 
3475  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3476 
3477  m >>= growth_multiplier;
3478  if (t->larger_town) m /= 2;
3479 
3480  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3481 }
3482 
3488 {
3489  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3490  uint old_rate = t->growth_rate;
3492  UpdateTownGrowCounter(t, old_rate);
3494 }
3495 
3500 static void UpdateTownGrowth(Town *t)
3501 {
3503 
3506 
3507  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3508 
3509  if (t->fund_buildings_months == 0) {
3510  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3511  for (int i = TE_BEGIN; i < TE_END; i++) {
3512  switch (t->goal[i]) {
3513  case TOWN_GROWTH_WINTER:
3514  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3515  break;
3516  case TOWN_GROWTH_DESERT:
3517  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3518  break;
3519  default:
3520  if (t->goal[i] > t->received[i].old_act) return;
3521  break;
3522  }
3523  }
3524  }
3525 
3526  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3529  return;
3530  }
3531 
3532  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3533 
3536 }
3537 
3538 static void UpdateTownAmounts(Town *t)
3539 {
3540  for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3541  for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3542  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3543 
3545 }
3546 
3547 static void UpdateTownUnwanted(Town *t)
3548 {
3549  for (const Company *c : Company::Iterate()) {
3550  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3551  }
3552 }
3553 
3561 {
3563 
3565  if (t == nullptr) return CommandCost();
3566 
3567  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3568 
3569  SetDParam(0, t->index);
3570  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3571 }
3572 
3582 {
3583  if (Town::GetNumItems() == 0) return nullptr;
3584 
3585  TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
3586  Town *town = Town::Get(tid);
3587  if (DistanceManhattan(tile, town->xy) < threshold) return town;
3588  return nullptr;
3589 }
3590 
3599 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3600 {
3601  switch (GetTileType(tile)) {
3602  case MP_ROAD:
3603  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3604 
3605  if (!HasTownOwnedRoad(tile)) {
3606  TownID tid = GetTownIndex(tile);
3607 
3608  if (tid == INVALID_TOWN) {
3609  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3610  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3611  assert(Town::GetNumItems() == 0);
3612  return nullptr;
3613  }
3614 
3615  assert(Town::IsValidID(tid));
3616  Town *town = Town::Get(tid);
3617 
3618  if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3619 
3620  return town;
3621  }
3622  FALLTHROUGH;
3623 
3624  case MP_HOUSE:
3625  return Town::GetByTile(tile);
3626 
3627  default:
3628  return CalcClosestTownFromTile(tile, threshold);
3629  }
3630 }
3631 
3632 static bool _town_rating_test = false;
3634 
3640 void SetTownRatingTestMode(bool mode)
3641 {
3642  static int ref_count = 0; // Number of times test-mode is switched on.
3643  if (mode) {
3644  if (ref_count == 0) {
3645  _town_test_ratings.clear();
3646  }
3647  ref_count++;
3648  } else {
3649  assert(ref_count > 0);
3650  ref_count--;
3651  }
3652  _town_rating_test = !(ref_count == 0);
3653 }
3654 
3660 static int GetRating(const Town *t)
3661 {
3662  if (_town_rating_test) {
3663  SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3664  if (it != _town_test_ratings.End()) {
3665  return it->second;
3666  }
3667  }
3668  return t->ratings[_current_company];
3669 }
3670 
3678 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3679 {
3680  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3681  if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3683  (_cheats.magic_bulldozer.value && add < 0)) {
3684  return;
3685  }
3686 
3687  int rating = GetRating(t);
3688  if (add < 0) {
3689  if (rating > max) {
3690  rating += add;
3691  if (rating < max) rating = max;
3692  }
3693  } else {
3694  if (rating < max) {
3695  rating += add;
3696  if (rating > max) rating = max;
3697  }
3698  }
3699  if (_town_rating_test) {
3700  _town_test_ratings[t] = rating;
3701  } else {
3703  t->ratings[_current_company] = rating;
3705  }
3706 }
3707 
3716 {
3717  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3718  if (t == nullptr || !Company::IsValidID(_current_company) ||
3720  return CommandCost();
3721  }
3722 
3723  /* minimum rating needed to be allowed to remove stuff */
3724  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3725  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3729  };
3730 
3731  /* check if you're allowed to remove the road/bridge/tunnel
3732  * owned by a town no removal if rating is lower than ... depends now on
3733  * difficulty setting. Minimum town rating selected by difficulty level
3734  */
3735  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3736 
3737  if (GetRating(t) < needed) {
3738  SetDParam(0, t->index);
3739  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3740  }
3741 
3742  return CommandCost();
3743 }
3744 
3745 void TownsMonthlyLoop()
3746 {
3747  for (Town *t : Town::Iterate()) {
3748  if (t->road_build_months != 0) t->road_build_months--;
3749 
3750  if (t->exclusive_counter != 0) {
3751  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3752  }
3753 
3754  UpdateTownAmounts(t);
3755  UpdateTownGrowth(t);
3756  UpdateTownRating(t);
3757  UpdateTownUnwanted(t);
3758  }
3759 
3760 }
3761 
3762 void TownsYearlyLoop()
3763 {
3764  /* Increment house ages */
3765  for (TileIndex t = 0; t < MapSize(); t++) {
3766  if (!IsTileType(t, MP_HOUSE)) continue;
3767  IncrementHouseAge(t);
3768  }
3769 }
3770 
3771 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3772 {
3773  if (AutoslopeEnabled()) {
3774  HouseID house = GetHouseType(tile);
3775  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3776  const HouseSpec *hs = HouseSpec::Get(house);
3777 
3778  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3779  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3780  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3781  bool allow_terraform = true;
3782 
3783  /* Call the autosloping callback per tile, not for the whole building at once. */
3784  house = GetHouseType(tile);
3785  hs = HouseSpec::Get(house);
3787  /* If the callback fails, allow autoslope. */
3788  uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3789  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3790  }
3791 
3792  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3793  }
3794  }
3795 
3796  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3797 }
3798 
3800 extern const TileTypeProcs _tile_type_town_procs = {
3801  DrawTile_Town, // draw_tile_proc
3802  GetSlopePixelZ_Town, // get_slope_z_proc
3803  ClearTile_Town, // clear_tile_proc
3804  AddAcceptedCargo_Town, // add_accepted_cargo_proc
3805  GetTileDesc_Town, // get_tile_desc_proc
3806  GetTileTrackStatus_Town, // get_tile_track_status_proc
3807  nullptr, // click_tile_proc
3808  AnimateTile_Town, // animate_tile_proc
3809  TileLoop_Town, // tile_loop_proc
3810  ChangeTileOwner_Town, // change_tile_owner_proc
3811  AddProducedCargo_Town, // add_produced_cargo_proc
3812  nullptr, // vehicle_enter_tile_proc
3813  GetFoundation_Town, // get_foundation_proc
3814  TerraformTile_Town, // terraform_tile_proc
3815 };
3816 
3817 
3818 HouseSpec _house_specs[NUM_HOUSES];
3819 
3820 void ResetHouses()
3821 {
3822  memset(&_house_specs, 0, sizeof(_house_specs));
3823  memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3824 
3825  /* Reset any overrides that have been set. */
3826  _house_mngr.ResetOverride();
3827 }
GrowTownInTile
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1345
game.hpp
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:124
TE_WATER
@ TE_WATER
Cargo behaves water-like.
Definition: cargotype.h:30
TileInfo::z
int z
Height.
Definition: tile_cmd.h:47
MP_CLEAR
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:41
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:44
HouseSpec::removal_cost
byte removal_cost
cost multiplier for removing it
Definition: house.h:103
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:732
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:80
TACT_BRIBE
@ TACT_BRIBE
Try to bribe the council.
Definition: town.h:219
HasTownOwnedRoad
static bool HasTownOwnedRoad(TileIndex t)
Checks if given tile has town owned road.
Definition: road_map.h:279
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:61
Town::have_ratings
CompanyMask have_ratings
which companies have a rating
Definition: town.h:69
GetRoadDepotDirection
static DiagDirection GetRoadDepotDirection(TileIndex t)
Get the direction of the exit of a road depot.
Definition: road_map.h:565
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:71
RoadTypeInfo
Definition: road.h:75
TACT_BUILD_STATUE
@ TACT_BUILD_STATUE
Build a statue.
Definition: town.h:216
NT_INDUSTRY_OPEN
@ NT_INDUSTRY_OPEN
Opening of industries.
Definition: news_type.h:26
TILE_ADD
#define TILE_ADD(x, y)
Adds to tiles together.
Definition: map_func.h:244
InvalidateWindowData
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:3319
StatueBuildSearchData
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:3122
TileLoop_Town
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:518
TryClearTile
static bool TryClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:3113
GRFFileProps::override
uint16 override
id of the entity been replaced by
Definition: newgrf_commons.h:333
ROAD_N
@ ROAD_N
Road at the two northern edges.
Definition: road_type.h:59
IsSea
static bool IsSea(TileIndex t)
Is it a sea water tile?
Definition: water_map.h:152
Cheats::magic_bulldozer
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
newgrf_house.h
RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
@ RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:61
StationFinder
Structure contains cached list of stations nearby.
Definition: station_type.h:100
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3581
Chance16
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
Definition: random_func.hpp:131
DoCommand
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:450
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
station_kdtree.h
TO_HOUSES
@ TO_HOUSES
town buildings
Definition: transparency.h:25
TileOffsByDiagDir
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:341
IsRoadStop
static bool IsRoadStop(TileIndex t)
Is the station at t a road station?
Definition: station_map.h:202
GetHouseAge
static Year GetHouseAge(TileIndex t)
Get the age of the house.
Definition: town_map.h:249
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3218
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
GetRating
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3660
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
CBM_HOUSE_CARGO_ACCEPTANCE
@ CBM_HOUSE_CARGO_ACCEPTANCE
decides amount of cargo acceptance
Definition: newgrf_callbacks.h:319
DoClearTownHouseHelper
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2665
command_func.h
Town::InitializeLayout
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:164
Town::road_build_months
byte road_build_months
fund road reconstruction in action?
Definition: town.h:91
InclinedSlope
static Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:256
EconomySettings::town_layout
TownLayout town_layout
select town layout,
Definition: settings_type.h:487
TileInfo::x
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:43
Pool::PoolItem<&_town_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:340
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:23
TownActionBuildStatue
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:3178
Kdtree
K-dimensional tree, specialised for 2-dimensional space.
Definition: kdtree.hpp:37
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:42
Town::unwanted
uint8 unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
Definition: town.h:70
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:293
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:66
company_base.h
ROTF_TOWN_BUILD
@ ROTF_TOWN_BUILD
Bit number for allowing towns to build this roadtype.
Definition: road.h:43
IsTransparencySet
static 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
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:25
tunnelbridge_map.h
EXPENSES_OTHER
@ EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:170
RemoveNearbyStations
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:458
CommandCost::MultiplyCost
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:73
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:53
CargoSpec::town_effect
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:66
Station
Station data structure.
Definition: station_base.h:450
IsHouseCompleted
static bool IsHouseCompleted(TileIndex t)
Get the completion of this house.
Definition: town_map.h:145
GetClosestWaterDistance
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:340
VerifyTownName
bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:82
CargoPacket::InvalidateAllFrom
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Definition: cargopacket.cpp:127
TF_FORBIDDEN
@ TF_FORBIDDEN
Forbidden.
Definition: town_type.h:94
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:27
DiagDirToAxis
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
ROAD_SW
@ ROAD_SW
South-west part.
Definition: road_type.h:53
DifficultySettings::town_council_tolerance
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:70
TE_FOOD
@ TE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:31
_town_rating_test
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3632
CmdTownRating
CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the rating of a company in a town.
Definition: town_cmd.cpp:2898
IsRoadDepotTile
static bool IsRoadDepotTile(TileIndex t)
Return whether a tile is a road depot tile.
Definition: road_map.h:115
TileAddByDir
static TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition: map_func.h:370
TL_RANDOM
@ TL_RANDOM
Random town layout.
Definition: town_type.h:85
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition: direction_type.h:83
TownCache::squared_town_zone_radius
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:45
TOWN_GROWTH_TICKS
static const int TOWN_GROWTH_TICKS
cycle duration for towns trying to grow. (this originates from the size of the town array in TTD
Definition: date_type.h:37
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
TACT_FUND_BUILDINGS
@ TACT_FUND_BUILDINGS
Fund new buildings.
Definition: town.h:217
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Object::GetByTile
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:50
EconomySettings::larger_towns
uint8 larger_towns
the number of cities to build. These start off larger and grow twice as fast
Definition: settings_type.h:485
GrowTownAtRoad
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Returns "growth" if a house was built, or no if the build failed.
Definition: town_cmd.cpp:1591
IsRoadAllowedHere
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:922
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:81
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:111
TownSize
TownSize
Supported initial town sizes.
Definition: town_type.h:19
GetWorldPopulation
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:444
CheckTownBuild2x2House
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if 2x2 building is allowed here, also takes into account current town layout Also,...
Definition: town_cmd.cpp:2488
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:547
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:121
_nb_orig_names
int _nb_orig_names
Number of original town names.
Definition: settings_gui.cpp:74
Town::goal
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:77
ROAD_X
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:56
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
DIAGDIRDIFF_90LEFT
@ DIAGDIRDIFF_90LEFT
90 degrees left
Definition: direction_type.h:108
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:42
_tile_type_town_procs
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
Definition: landscape.cpp:46
IsStandardRoadStopTile
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:223
IsValidDiagDirection
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
SetRoadOwner
static void SetRoadOwner(TileIndex t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:250
SetDParamX
static void SetDParamX(uint64 *s, uint n, uint64 v)
Set a string parameter v at index n in a given array s.
Definition: strings_func.h:189
OBJECT_STATUE
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
IsDriveThroughStopTile
static bool IsDriveThroughStopTile(TileIndex t)
Is tile t a drive through road stop station?
Definition: station_map.h:233
ResetHouseAge
static void ResetHouseAge(TileIndex t)
Sets the age of the house to zero.
Definition: town_map.h:226
GameCreationSettings::town_name
byte town_name
the town name generator used for town names
Definition: settings_type.h:292
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:13
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:26
CBID_HOUSE_CUSTOM_NAME
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
Definition: newgrf_callbacks.h:224
CMD_BUILD_BRIDGE
@ CMD_BUILD_BRIDGE
build a bridge
Definition: command_type.h:181
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
TileInfo::y
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:44
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
TCGM_ORIGINAL
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
Definition: town_type.h:103
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:55
DC_NO_WATER
@ DC_NO_WATER
don't allow building on water
Definition: command_type.h:351
EconomySettings::initial_city_size
uint8 initial_city_size
multiplier for the initial size of the cities compared to towns
Definition: settings_type.h:486
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:49
town.h
newgrf_debug.h
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:82
TownLayout
TownLayout
Town Layouts.
Definition: town_type.h:78
RandomRange
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:338
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
HouseSpec::max_year
Year max_year
last year it can be built
Definition: house.h:101
SLOPE_STEEP_S
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
Definition: slope_type.h:67
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
MAX_DAY
#define MAX_DAY
The number of days till the last day.
Definition: date_type.h:97
Industry
Defines the internal data of a functional industry.
Definition: industry.h:66
ConvertBooleanCallback
bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:550
RoadTypeInfo::introduction_date
Date introduction_date
Introduction date.
Definition: road.h:163
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:24
Station::CatchmentCoversTown
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition: station.cpp:393
CBID_HOUSE_DRAW_FOUNDATIONS
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
Definition: newgrf_callbacks.h:227
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
Town::fund_buildings_months
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:90
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:348
Kdtree::Build
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
Definition: kdtree.hpp:364
GetTownRoadBits
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile.
Definition: town_cmd.cpp:840
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:62
DIR_N
@ DIR_N
North.
Definition: direction_type.h:26
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:43
IsLocalCompany
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
CompanyNewsInformation::company_name
char company_name[64]
The name of the company.
Definition: news_type.h:149
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:51
NT_GENERAL
@ NT_GENERAL
General news (from towns)
Definition: news_type.h:36
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:199
Town::show_zone
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:96
TOWN_HAS_STADIUM
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition: town.h:183
TileIndexToTileIndexDiffC
static TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:316
CBM_HOUSE_PRODUCE_CARGO
@ CBM_HOUSE_PRODUCE_CARGO
custom cargo production
Definition: newgrf_callbacks.h:323
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:346
GetTownIndex
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:22
genworld.h
Town::UpdateVirtCoord
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else)
Definition: town_cmd.cpp:393
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
GenerateTowns
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:2205
CMD_BUILD_TUNNEL
@ CMD_BUILD_TUNNEL
build a tunnel
Definition: command_type.h:188
Kdtree::Count
size_t Count() const
Get number of elements stored in tree.
Definition: kdtree.hpp:432
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition: genworld_gui.cpp:1352
SpotData
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:2077
FlatteningFoundation
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
IncHouseConstructionTick
static void IncHouseConstructionTick(TileIndex t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
Definition: town_map.h:208
Town::GetRandom
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:178
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
RATING_GROWTH_UP_STEP
@ RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:52
object_base.h
EconomySettings::bribe
bool bribe
enable bribing the local authority
Definition: settings_type.h:472
ST_TOWN
@ ST_TOWN
Source/destination is a town.
Definition: cargo_type.h:148
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
Kdtree::Remove
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:419
SmallMap
Implementation of simple mapping class.
Definition: smallmap_type.hpp:26
DiagDirToRoadBits
static RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:96
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:372
CountBits
static uint CountBits(T value)
Counts the number of set bits in a variable.
Definition: bitmath_func.hpp:251
TransportedCargoStat::NewMonth
void NewMonth()
Update stats for a new month.
Definition: town_type.h:121
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:548
MAX_CHAR_LENGTH
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:18
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:270
MAX_LENGTH_COMPANY_NAME_CHARS
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
Definition: company_type.h:40
ai.hpp
IsInsideMM
static bool IsInsideMM(const T x, const size_t min, const size_t max)
Checks if a value is in an interval.
Definition: math_func.hpp:204
SLOPE_NW
@ SLOPE_NW
north and west corner are raised
Definition: slope_type.h:55
RATING_INITIAL
@ RATING_INITIAL
initial rating
Definition: town_type.h:44
TF_CUSTOM_LAYOUT
@ TF_CUSTOM_LAYOUT
Allowed, with custom town layout.
Definition: town_type.h:96
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:45
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
TestTownOwnsBridge
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
Definition: town_cmd.cpp:85
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
TownCache::building_counts
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:46
GetHouseType
static HouseID GetHouseType(TileIndex t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:59
townname_func.h
TRANSPORT_ROAD
@ TRANSPORT_ROAD
Transport by road vehicle.
Definition: transport_type.h:28
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:50
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:118
ROAD_NONE
@ ROAD_NONE
No road-part is build.
Definition: road_type.h:51
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:117
GrowTown
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1687
GetLiftPosition
static byte GetLiftPosition(TileIndex t)
Get the position of the lift on this animated house.
Definition: town_map.h:125
Utf8StringLength
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:334
ToTileIndexDiff
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Definition: map_func.h:230
Pool::PoolItem<&_town_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:350
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:157
GetSlopeMaxZ
static int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition: slope_func.h:160
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:81
EconomySettings::fund_buildings
bool fund_buildings
allow funding new buildings
Definition: settings_type.h:479
TileIndexDiffC::y
int16 y
The y value of the coordinate.
Definition: map_type.h:59
TownCache::population
uint32 population
Current population of people.
Definition: town.h:42
CargoSpec::Index
CargoID Index() const
Determines index of this cargospec.
Definition: cargotype.h:88
depot_base.h
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
TOWN_RATING_CHECK_TYPE_COUNT
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition: town.h:163
RandomDiagDir
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:242
MapSize
static uint MapSize()
Get the size of the map.
Definition: map_func.h:92
TL_BETTER_ROADS
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:81
Town::time_until_rebuild
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:85
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:158
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2257
IsSteepSlope
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
CommandCost
Common return value for all commands.
Definition: command_type.h:23
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:644
HasTileWaterGround
static bool HasTileWaterGround(TileIndex t)
Checks whether the tile has water at the ground.
Definition: water_map.h:344
cmd_helper.h
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:27
GetTownName
char * GetTownName(char *buff, const TownNameParams *par, uint32 townnameparts, const char *last)
Fills buffer with specified town name.
Definition: townname.cpp:49
TileHeight
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:29
CircularTileSearch
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:258
CMD_TERRAFORM_LAND
@ CMD_TERRAFORM_LAND
terraform a tile
Definition: command_type.h:186
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:152
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
CMD_BUILD_ROAD
@ CMD_BUILD_ROAD
build a "half" road
Definition: command_type.h:201
SLOPE_ELEVATED
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
Definition: slope_type.h:61
WC_TOWN_AUTHORITY
@ WC_TOWN_AUTHORITY
Town authority; Window numbers:
Definition: window_type.h:187
SpotData::tile
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:2078
ChangeDiagDir
static DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Definition: direction_func.h:149
GetAnyRoadBits
RoadBits GetAnyRoadBits(TileIndex tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:33
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:34
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:144
GSF_FAKE_TOWNS
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:89
Pool::MAX_SIZE
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:85
IsUniqueTownName
static bool IsUniqueTownName(const char *name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:1912
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
DRD_NONE
@ DRD_NONE
None of the directions are disallowed.
Definition: road_map.h:286
_original_house_specs
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1819
TileIndexDiff
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:154
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
TownCanBePlacedHere
static CommandCost TownCanBePlacedHere(TileIndex tile)
Checks if it's possible to place a town at given tile.
Definition: town_cmd.cpp:1887
TOWN_GROWTH_DESERT
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:32
GameCreationSettings::custom_town_number
uint16 custom_town_number
manually entered number of towns
Definition: settings_type.h:295
autoslope.h
SpotData::max_dist
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:2079
TownRatingCheckType
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:160
Convert8bitBooleanCallback
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:569
CountActiveStations
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3443
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:217
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
Kdtree::Insert
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:400
MP_OBJECT
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:51
CBID_HOUSE_ALLOW_CONSTRUCTION
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
Definition: newgrf_callbacks.h:54
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
GUISettings::population_in_label
bool population_in_label
show the population of a town in his label?
Definition: settings_type.h:118
CBM_HOUSE_ACCEPT_CARGO
@ CBM_HOUSE_ACCEPT_CARGO
decides accepted types
Definition: newgrf_callbacks.h:322
TE_END
@ TE_END
End of town effects.
Definition: cargotype.h:32
MP_WATER
@ MP_WATER
Water tile.
Definition: tile_type.h:47
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition: station_cmd.cpp:2216
ROAD_E
@ ROAD_E
Road at the two eastern edges.
Definition: road_type.h:60
Town::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:83
IsRoadOwner
static bool IsRoadOwner(TileIndex t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
Definition: road_map.h:267
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:159
MakeSingleHouseBigger
static void MakeSingleHouseBigger(TileIndex tile)
Helper function for house completion stages progression.
Definition: town_cmd.cpp:480
AlignTileToGrid
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:2047
IsInvisibilitySet
static 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
Object
An object, such as transmitter, on the map.
Definition: object_base.h:23
GrowTownWithTunnel
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
Definition: town_cmd.cpp:1239
GetLiftDestination
static byte GetLiftDestination(TileIndex t)
Get the current destination for this lift.
Definition: town_map.h:104
CmdDoTownAction
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Do a town action.
Definition: town_cmd.cpp:3356
HaltLift
static void HaltLift(TileIndex t)
Stop the lift of this animated house from moving.
Definition: town_map.h:115
TACT_ROAD_REBUILD
@ TACT_ROAD_REBUILD
Rebuild the roads.
Definition: town.h:215
TownLayoutAllowsHouseHere
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if current town layout allows building here.
Definition: town_cmd.cpp:2395
HasTileRoadType
static bool HasTileRoadType(TileIndex t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:210
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
GetTropicZone
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:238
DeleteSubsidyWith
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:149
CALLBACK_HOUSEPRODCARGO_END
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
Definition: newgrf_callbacks.h:405
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:141
BuildObject
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8 view=0)
Actually build the object.
Definition: object_cmd.cpp:83
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:557
WL_INFO
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:22
DIAGDIRDIFF_90RIGHT
@ DIAGDIRDIFF_90RIGHT
90 degrees right
Definition: direction_type.h:106
Object::type
ObjectType type
Type of the object.
Definition: object_base.h:24
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
ROAD_NE
@ ROAD_NE
North-east part.
Definition: road_type.h:55
AI::BroadcastNewEvent
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:259
_tick_counter
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:29
industry.h
ROAD_SE
@ ROAD_SE
South-east part.
Definition: road_type.h:54
safeguards.h
HighestSnowLine
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:658
ChangePopulation
static void ChangePopulation(Town *t, int mod)
Change the towns population.
Definition: town_cmd.cpp:430
RATING_ROAD_NEEDED_HOSTILE
@ RATING_ROAD_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:68
ROTF_NO_HOUSES
@ ROTF_NO_HOUSES
Bit number for setting this roadtype as not house friendly.
Definition: road.h:41
HouseSpec::callback_mask
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
ROAD_S
@ ROAD_S
Road at the two southern edges.
Definition: road_type.h:61
SearchTileForStatue
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:3135
IsValidTile
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:161
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:82
TileAddByDiagDir
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:382
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
ReverseDiagDir
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
SetLiftPosition
static void SetLiftPosition(TileIndex t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:135
DIR_S
@ DIR_S
South.
Definition: direction_type.h:30
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:602
IsTileOwner
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:60
StatueBuildSearchData::tile_count
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:3124
IsCloseToTown
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:382
GetFoundation_Town
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback routine.
Definition: town_cmd.cpp:307
RandomTile
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:435
RoadTypesAllowHouseHere
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding roads allows to build a house here.
Definition: town_cmd.cpp:1304
TSZ_END
@ TSZ_END
Number of available town sizes.
Definition: town_type.h:25
FindNearestGoodCoastalTownSpot
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:2138
DC_NO_TEST_TOWN_RATING
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:353
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:122
TileHash
static uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:316
CleanUpRoadBits
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition: road.cpp:47
EconomySettings::exclusive_rights
bool exclusive_rights
allow buying exclusive rights
Definition: settings_type.h:478
Town::growth_rate
uint16 growth_rate
town growth rate
Definition: town.h:88
CompanyNewsInformation::FillData
void FillData(const struct Company *c, const struct Company *other=nullptr)
Fill the CompanyNewsInformation struct with the required data.
Definition: company_cmd.cpp:757
MP_TUNNELBRIDGE
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:50
ROAD_ALL
@ ROAD_ALL
Full 4-way crossing.
Definition: road_type.h:64
TownLayoutAllows2x2HouseHere
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if current town layout allows 2x2 building here.
Definition: town_cmd.cpp:2426
newgrf_text.h
AutoslopeEnabled
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
road_internal.h
road.h
GetAvailableMoneyForCommand
Money GetAvailableMoneyForCommand()
Definition: command.cpp:528
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
FOUNDATION_NONE
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
IsRoadDepot
static bool IsRoadDepot(TileIndex t)
Return whether a tile is a road depot.
Definition: road_map.h:105
EconomySettings::found_town
TownFounding found_town
town founding.
Definition: settings_type.h:490
error.h
SLOPE_SW
@ SLOPE_SW
south and west corner are raised
Definition: slope_type.h:56
GetRoadStopDir
static DiagDirection GetRoadStopDir(TileIndex t)
Gets the direction the road stop entrance points towards.
Definition: station_map.h:257
SLOPE_STEEP_E
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
Definition: slope_type.h:68
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:77
SetTownRatingTestMode
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Definition: town_cmd.cpp:3640
GetFoundationSlope
Slope GetFoundationSlope(TileIndex tile, int *z)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition: landscape.cpp:422
TL_3X3_GRID
@ TL_3X3_GRID
Geometric 3x3 grid algorithm.
Definition: town_type.h:83
CmdDeleteTown
CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Delete a town (scenario editor or worldgen only).
Definition: town_cmd.cpp:2967
ROADTYPE_BEGIN
@ ROADTYPE_BEGIN
Used for iterations.
Definition: road_type.h:23
GetTownRoadGridElement
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:1000
date_func.h
TileDesc::dparam
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:62
CBID_HOUSE_CARGO_ACCEPTANCE
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
Definition: newgrf_callbacks.h:78
stdafx.h
NR_NONE
@ NR_NONE
Empty reference.
Definition: news_type.h:50
UpdateTownGrowth
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3500
RoundDivSU
static int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:276
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:22
GetHouseConstructionTick
static byte GetHouseConstructionTick(TileIndex t)
Gets the construction stage of a house.
Definition: town_map.h:195
landscape.h
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:145
GetCommandFlags
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:393
StationFinder::GetStations
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition: station_cmd.cpp:3979
TSZ_RANDOM
@ TSZ_RANDOM
Random size, bigger than small, smaller than large.
Definition: town_type.h:23
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
UpdateNearestTownForRoadTiles
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1828
HouseSpec::mail_generation
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
viewport_func.h
NF_NORMAL
@ NF_NORMAL
Normal news item. (Newspaper with text only)
Definition: news_type.h:78
RATING_ROAD_NEEDED_NEUTRAL
@ RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:67
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
Town::ratings
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:73
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
ROAD_NW
@ ROAD_NW
North-west part.
Definition: road_type.h:52
TownEffect
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:24
EconomySettings::town_cargogen_mode
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
Definition: settings_type.h:488
WC_TOWN_DIRECTORY
@ WC_TOWN_DIRECTORY
Town directory; Window numbers:
Definition: window_type.h:247
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
animated_tile_func.h
UpdateAllTownVirtCoords
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:411
GetTunnelBridgeDirection
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
Definition: tunnelbridge_map.h:26
AddSortableSpriteToDraw
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:660
DoCreateTown
static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Does the actual town creation.
Definition: town_cmd.cpp:1806
GetBridgeAxis
static Axis GetBridgeAxis(TileIndex t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
RATING_ROAD_NEEDED_PERMISSIVE
@ RATING_ROAD_NEEDED_PERMISSIVE
rating needed, "Permissive" difficulty settings
Definition: town_type.h:66
object_map.h
MP_TREES
@ MP_TREES
Tile got trees.
Definition: tile_type.h:45
TransportedCargoStat::new_max
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:114
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:57
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:470
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:60
EconomySettings::dist_local_authority
byte dist_local_authority
distance for town local authority, default 20
Definition: settings_type.h:477
DistanceSquare
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition: map.cpp:174
TransportedCargoStat::old_max
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
ForAllStationsRadius
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Definition: station_kdtree.h:29
Industry::town
Town * town
Nearest town.
Definition: industry.h:68
TOWN_GROWTH_WINTER
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:31
string_func.h
Town::PostDestructor
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
Definition: town_cmd.cpp:150
NR_TOWN
@ NR_TOWN
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:55
EconomyIsInRecession
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:47
GetMaskOfTownActions
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3303
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:404
EconomySettings::allow_town_level_crossings
bool allow_town_level_crossings
towns are allowed to build level crossings
Definition: settings_type.h:493
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SetLiftDestination
static void SetLiftDestination(TileIndex t, byte dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
Definition: town_map.h:93
Town::text
std::string text
General text with additional information.
Definition: town.h:79
TCGM_BITCOUNT
@ TCGM_BITCOUNT
Bit-counted algorithm (normal distribution from individual house population)
Definition: town_type.h:104
GetDisallowedRoadDirections
static DisallowedRoadDirections GetDisallowedRoadDirections(TileIndex t)
Gets the disallowed directions.
Definition: road_map.h:301
HouseID
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:46
TransportedCargoStat::new_act
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
SLOPE_N
@ SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:53
station_base.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
Pool::PoolItem<&_town_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
CompanyNewsInformation
Data that needs to be stored for company news messages.
Definition: news_type.h:148
strings_func.h
IsNeighborRoadTile
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:888
LiftHasDestination
static bool LiftHasDestination(TileIndex t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:82
Pool
Base class for all pools.
Definition: pool_type.hpp:81
DeleteWindowById
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1165
RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
@ RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
rating needed, "Permissive" difficulty settings
Definition: town_type.h:59
ScaleByMapSize
static uint ScaleByMapSize(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:122
CmdTownCargoGoal
CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2801
TACT_COUNT
@ TACT_COUNT
Number of available town actions.
Definition: town.h:221
CanFollowRoad
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:1549
MP_VOID
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:48
subsidy_func.h
GetHouseBuildingStage
static byte GetHouseBuildingStage(TileIndex t)
House Construction Scheme.
Definition: town_map.h:183
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:359
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:26
TileXY
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:163
RoadTypeInfo::label
RoadTypeLabel label
Unique 32 bit road type identifier.
Definition: road.h:144
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
TrackedViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport_type.h:64
MakeTownHouse
static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
Write house information into the map.
Definition: town_cmd.cpp:2305
IsSlopeWithOneCornerRaised
static bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
Definition: slope_func.h:88
IsWaterTile
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:184
IncreaseBuildingCount
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
Definition: newgrf_house.cpp:107
NF_COMPANY
@ NF_COMPANY
Company news item. (Newspaper with face)
Definition: news_type.h:80
FindNearestEmptyLand
static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the nearest land tile.
Definition: town_cmd.cpp:2121
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition: genworld_gui.cpp:1338
RATING_GROWTH_MAXIMUM
@ RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
Definition: town_type.h:53
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:385
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:306
DrawBuildingsTileStruct
This structure is the same for both Industries and Houses.
Definition: sprite.h:67
cheat_type.h
SetTownIndex
static void SetTownIndex(TileIndex t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:34
Pool::PoolItem<&_town_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:308
BuildTownHouse
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2511
MarkTileDirtyByTile
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:1985
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
TileDiffXY
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:179
Kdtree::FindNearest
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Definition: kdtree.hpp:443
CmdRenameTown
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename a town (server-only).
Definition: town_cmd.cpp:2747
TransportedCargoStat::old_act
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:46
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:53
OverrideManagerBase::ResetOverride
void ResetOverride()
Resets the override, which is used while initializing game.
Definition: newgrf_commons.cpp:88
GetCargoTranslation
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:91
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:58
ROAD_Y
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:57
ForAllStationsAroundTiles
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:569
CmdTownGrowthRate
CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the growth rate of the town.
Definition: town_cmd.cpp:2858
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:119
Pool::PoolItem<&_town_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:299
EconomySettings::town_growth_rate
uint8 town_growth_rate
town growth rate
Definition: settings_type.h:484
TownNameParams
Struct holding parameters used to generate town name.
Definition: townname_type.h:27
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3599
CmdFoundTown
CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Create a new town.
Definition: town_cmd.cpp:1933
Town::~Town
~Town()
Destroy the town.
Definition: town_cmd.cpp:101
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:78
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:110
MAX_UVALUE
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:478
CheckforTownRating
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3715
GetRoadTypeInfo
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:224
TOWN_IS_GROWING
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:181
ChangeTownRating
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3678
TileHash2Bit
static uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:334
OWNER_DEITY
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:52
EconomySettings::fund_roads
bool fund_roads
allow funding local road reconstruction
Definition: settings_type.h:480
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:349
SLOPE_S
@ SLOPE_S
the south corner of the tile is raised
Definition: slope_type.h:51
GetTileMaxPixelZ
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
DC_NO_MODIFY_TOWN_RATING
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:358
_town_action_costs
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:3057
CanRoadContinueIntoNextTile
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:1120
StatueBuildSearchData::best_position
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:3123
UpdateTownGrowCounter
static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3428
TACT_NONE
@ TACT_NONE
Empty action set.
Definition: town.h:210
GetHouseNorthPart
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2682
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:224
TILE_ADDXY
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:258
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:137
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:96
_town_test_ratings
static SmallMap< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3633
SLOPE_W
@ SLOPE_W
the west corner of the tile is raised
Definition: slope_type.h:50
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:789
CBID_HOUSE_PRODUCE_CARGO
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
Definition: newgrf_callbacks.h:129
window_func.h
AnimateTile_Town
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town Only certain houses can be animated The newhouses animation supersedes regu...
Definition: town_cmd.cpp:331
CommandFlagsToDCFlags
static DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:58
Depot
Definition: depot_base.h:19
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
GrowTownWithExtraHouse
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1059
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:377
Town
Town data structure.
Definition: town.h:50
RoadTypeInfo::max_speed
uint16 max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:139
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1610
CheckBuildHouseSameZ
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Checks if a house can be built at this tile, must have the same max z as parameter.
Definition: town_cmd.cpp:2355
random_func.hpp
OverflowSafeInt< int64, INT64_MAX, INT64_MIN >
GenRandomRoadBits
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1673
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
IsPlainRailTile
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
GrowTownWithBridge
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1164
HouseSpec
Definition: house.h:98
TownCache::num_houses
uint32 num_houses
Amount of houses.
Definition: town.h:41
ClampToU16
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:153
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:83
IsNormalRoadTile
static bool IsNormalRoadTile(TileIndex t)
Return whether a tile is a normal road tile.
Definition: road_map.h:73
CBM_HOUSE_AUTOSLOPE
@ CBM_HOUSE_AUTOSLOPE
decides allowance of autosloping
Definition: newgrf_callbacks.h:326
INVALID_COMPANY
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
SLOPE_STEEP_W
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
Definition: slope_type.h:66
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:326
Town::layout
TownLayout layout
town specific road layout
Definition: town.h:94
GetOtherTunnelBridgeEnd
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
Definition: tunnelbridge_map.h:78
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
TL_ORIGINAL
@ TL_ORIGINAL
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:80
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:46
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:549
ClearMakeHouseTile
static void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
Clears tile and builds a house or house part.
Definition: town_cmd.cpp:2281
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:516
DC_NONE
@ DC_NONE
no flag is set
Definition: command_type.h:347
GetTileType
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
NUM_TLS
@ NUM_TLS
Number of town layouts.
Definition: town_type.h:87
_town_draw_tile_data
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:27
ROAD_W
@ ROAD_W
Road at the two western edges.
Definition: road_type.h:62
Pool::PoolItem<&_town_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:318
CBM_HOUSE_DRAW_FOUNDATIONS
@ CBM_HOUSE_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
Definition: newgrf_callbacks.h:325
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3560
FindFurthestFromWater
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:2099
MakeTownHouseBigger
static void MakeTownHouseBigger(TileIndex tile)
Make the house advance in its construction stages until completion.
Definition: town_cmd.cpp:503
TSZ_LARGE
@ TSZ_LARGE
Large town.
Definition: town_type.h:22
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:55
Town::larger_town
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:93
DrawTile_Town
static void DrawTile_Town(TileInfo *ti)
House Tile drawing handler.
Definition: town_cmd.cpp:252
MAX_LENGTH_TOWN_NAME_CHARS
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
Definition: town_type.h:108
DecreaseBuildingCount
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
Definition: newgrf_house.cpp:126
BUILDING_IS_HISTORICAL
@ BUILDING_IS_HISTORICAL
this house will only appear during town generation in random games, thus the historical
Definition: house.h:90
pool_func.hpp
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:68
CMD_DELETE_TOWN
@ CMD_DELETE_TOWN
delete a town
Definition: command_type.h:270
TL_2X2_GRID
@ TL_2X2_GRID
Geometric 2x2 grid algorithm.
Definition: town_type.h:82
GetTunnelBridgeTransportType
static TransportType GetTunnelBridgeTransportType(TileIndex t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
Definition: tunnelbridge_map.h:39
TOWN_HOUSE_COMPLETED
static const byte TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:23
RemapCoords2
static 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:98
CBM_HOUSE_ALLOW_CONSTRUCTION
@ CBM_HOUSE_ALLOW_CONSTRUCTION
decide whether the house can be built on a given tile
Definition: newgrf_callbacks.h:314
Company
Definition: company_base.h:110
Town::name
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition: town.h:59
CmdExpandTown
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:2927
DifficultySettings::number_towns
byte number_towns
the amount of towns
Definition: settings_type.h:56
Town::supplied
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:75
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:71
CmdTownSetText
CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Set a custom text in the Town window.
Definition: town_cmd.cpp:2834
HouseSpec::remove_rating_decrease
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:105
SLOPE_SE
@ SLOPE_SE
south and east corner are raised
Definition: slope_type.h:57
Town::grow_counter
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:87
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3246
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition: station_cmd.cpp:447
HouseSpec::GetRemovalCost
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:209
TOWN_CUSTOM_GROWTH
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition: town.h:184
Town::exclusive_counter
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:72
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:393
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:489
GrowTownWithRoad
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1101
GWP_TOWN
@ GWP_TOWN
Generate towns.
Definition: genworld.h:72
CBID_HOUSE_ACCEPT_CARGO
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
Definition: newgrf_callbacks.h:114
newgrf_cargo.h
CheckTownBuild2House
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout Also,...
Definition: town_cmd.cpp:2463
Object::town
Town * town
Town the object is built in.
Definition: object_base.h:25
IncrementHouseAge
static void IncrementHouseAge(TileIndex t)
Increments the age of the house.
Definition: town_map.h:237
town_kdtree.h
TOWN_HAS_CHURCH
@ TOWN_HAS_CHURCH
There can be only one church by town.
Definition: town.h:182
SLOPE_NE
@ SLOPE_NE
north and east corner are raised
Definition: slope_type.h:58
ComplementSlope
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:76
TOWN_GROWTH_RATE_NONE
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:33
town_land.h
HouseSpec::grf_prop
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:114
SLOPE_E
@ SLOPE_E
the east corner of the tile is raised
Definition: slope_type.h:52
Town::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:60
TownActions
TownActions
Town actions of a company.
Definition: town.h:209
CUSTOM_TOWN_NUMBER_DIFFICULTY
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:26
CMD_LANDSCAPE_CLEAR
@ CMD_LANDSCAPE_CLEAR
demolish a tile
Definition: command_type.h:180
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:827
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
CBID_HOUSE_AUTOSLOPE
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
Definition: newgrf_callbacks.h:230
UpdateTownGrowthRate
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
Definition: town_cmd.cpp:3487
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:286
GenerateTownName
bool GenerateTownName(uint32 *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:119
road_cmd.h
DrawGroundSprite
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:576
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
MakeHouseTile
static void MakeHouseTile(TileIndex t, TownID tid, byte counter, byte stage, HouseID type, byte random_bits)
Make the tile a house.
Definition: town_map.h:352
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:565
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
TownCache::sign
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:43
object.h
RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
@ RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:60
Town::received
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:76
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:104
CheckFree2x2Area
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:2374
SLOPE_STEEP_N
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition: slope_type.h:69
Town::flags
byte flags
See TownFlags.
Definition: town.h:62
FindFirstCargoWithTownEffect
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2781
TACT_BUY_RIGHTS
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition: town.h:218
news_func.h
IsBridgeAbove
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
AddAnimatedTile
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet).
Definition: animated_tile.cpp:41
SpotData::layout
TownLayout layout
tells us what kind of town we're building
Definition: town_cmd.cpp:2080
GetNormalGrowthRate
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3460
IsTileAlignedToGrid
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:2065
CanBuildHouseHere
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Checks if a house can be built here.
Definition: town_cmd.cpp:2330
AddChildSpriteScreen
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:814
backup_type.hpp
TileIndexDiffC::x
int16 x
The x value of the coordinate.
Definition: map_type.h:58