OpenTTD Source  1.10.2
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;
59 
60 /* Initialize the town-pool */
61 TownPool _town_pool("Town");
63 
64 
65 TownKdtree _town_kdtree(&Kdtree_TownXYFunc);
66 
67 void RebuildTownKdtree()
68 {
69  std::vector<TownID> townids;
70  for (const Town *town : Town::Iterate()) {
71  townids.push_back(town->index);
72  }
73  _town_kdtree.Build(townids.begin(), townids.end());
74 }
75 
76 
86 static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
87 {
88  if (!IsTileOwner(tile, OWNER_TOWN)) return false;
89 
91  bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
92 
93  if (!town_owned) {
94  /* Or other adjacent road */
96  town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
97  }
98 
99  return town_owned;
100 }
101 
103 {
104  free(this->name);
105  free(this->text);
106 
107  if (CleaningPool()) return;
108 
109  /* Delete town authority window
110  * and remove from list of sorted towns */
112 
113  /* Check no industry is related to us. */
114  for (const Industry *i : Industry::Iterate()) assert(i->town != this);
115 
116  /* ... and no object is related to us. */
117  for (const Object *o : Object::Iterate()) assert(o->town != this);
118 
119  /* Check no tile is related to us. */
120  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
121  switch (GetTileType(tile)) {
122  case MP_HOUSE:
123  assert(GetTownIndex(tile) != this->index);
124  break;
125 
126  case MP_ROAD:
127  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
128  break;
129 
130  case MP_TUNNELBRIDGE:
131  assert(!TestTownOwnsBridge(tile, this));
132  break;
133 
134  default:
135  break;
136  }
137  }
138 
139  /* Clear the persistent storage list. */
140  this->psa_list.clear();
141 
146 }
147 
148 
155 {
156  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
158 
159  /* Give objects a new home! */
160  for (Object *o : Object::Iterate()) {
161  if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
162  }
163 }
164 
169 {
170  if (layout != TL_RANDOM) {
171  this->layout = layout;
172  return;
173  }
174 
175  this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
176 }
177 
182 /* static */ Town *Town::GetRandom()
183 {
184  if (Town::GetNumItems() == 0) return nullptr;
185  int num = RandomRange((uint16)Town::GetNumItems());
186  size_t index = MAX_UVALUE(size_t);
187 
188  while (num >= 0) {
189  num--;
190  index++;
191 
192  /* Make sure we have a valid town */
193  while (!Town::IsValidID(index)) {
194  index++;
195  assert(index < Town::GetPoolSize());
196  }
197  }
198 
199  return Town::Get(index);
200 }
201 
202 void Town::FillCachedName() const
203 {
205  char *end = GetTownName(buf, this, lastof(buf));
206  this->cached_name.assign(buf, end);
207 }
208 
214 {
215  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
216 }
217 
218 /* Local */
219 static int _grow_town_result;
220 
221 /* Describe the possible states */
222 enum TownGrowthResult {
223  GROWTH_SUCCEED = -1,
224  GROWTH_SEARCH_STOPPED = 0
225 // GROWTH_SEARCH_RUNNING >= 1
226 };
227 
228 static bool BuildTownHouse(Town *t, TileIndex tile);
229 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
230 
231 static void TownDrawHouseLift(const TileInfo *ti)
232 {
233  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
234 }
235 
236 typedef void TownDrawTileProc(const TileInfo *ti);
237 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
238  TownDrawHouseLift
239 };
240 
247 {
248  return (DiagDirection)(3 & Random());
249 }
250 
256 static void DrawTile_Town(TileInfo *ti)
257 {
258  HouseID house_id = GetHouseType(ti->tile);
259 
260  if (house_id >= NEW_HOUSE_OFFSET) {
261  /* Houses don't necessarily need new graphics. If they don't have a
262  * spritegroup associated with them, then the sprite for the substitute
263  * house id is drawn instead. */
264  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
265  DrawNewHouseTile(ti, house_id);
266  return;
267  } else {
268  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
269  }
270  }
271 
272  /* Retrieve pointer to the draw town tile struct */
273  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
274 
276 
277  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
278 
279  /* If houses are invisible, do not draw the upper part */
280  if (IsInvisibilitySet(TO_HOUSES)) return;
281 
282  /* Add a house on top of the ground? */
283  SpriteID image = dcts->building.sprite;
284  if (image != 0) {
285  AddSortableSpriteToDraw(image, dcts->building.pal,
286  ti->x + dcts->subtile_x,
287  ti->y + dcts->subtile_y,
288  dcts->width,
289  dcts->height,
290  dcts->dz,
291  ti->z,
293  );
294 
295  if (IsTransparencySet(TO_HOUSES)) return;
296  }
297 
298  {
299  int proc = dcts->draw_proc - 1;
300 
301  if (proc >= 0) _town_draw_tile_procs[proc](ti);
302  }
303 }
304 
305 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
306 {
307  return GetTileMaxPixelZ(tile);
308 }
309 
312 {
313  HouseID hid = GetHouseType(tile);
314 
315  /* For NewGRF house tiles we might not be drawing a foundation. We need to
316  * account for this, as other structures should
317  * draw the wall of the foundation in this case.
318  */
319  if (hid >= NEW_HOUSE_OFFSET) {
320  const HouseSpec *hs = HouseSpec::Get(hid);
321  if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
322  uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
323  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
324  }
325  }
326  return FlatteningFoundation(tileh);
327 }
328 
335 static void AnimateTile_Town(TileIndex tile)
336 {
337  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
338  AnimateNewHouseTile(tile);
339  return;
340  }
341 
342  if (_tick_counter & 3) return;
343 
344  /* If the house is not one with a lift anymore, then stop this animating.
345  * Not exactly sure when this happens, but probably when a house changes.
346  * Before this was just a return...so it'd leak animated tiles..
347  * That bug seems to have been here since day 1?? */
348  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
349  DeleteAnimatedTile(tile);
350  return;
351  }
352 
353  if (!LiftHasDestination(tile)) {
354  uint i;
355 
356  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
357  * This is due to the fact that the first floor is, in the graphics,
358  * the height of 2 'normal' floors.
359  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
360  do {
361  i = RandomRange(7);
362  } while (i == 1 || i * 6 == GetLiftPosition(tile));
363 
364  SetLiftDestination(tile, i);
365  }
366 
367  int pos = GetLiftPosition(tile);
368  int dest = GetLiftDestination(tile) * 6;
369  pos += (pos < dest) ? 1 : -1;
370  SetLiftPosition(tile, pos);
371 
372  if (pos == dest) {
373  HaltLift(tile);
374  DeleteAnimatedTile(tile);
375  }
376 
377  MarkTileDirtyByTile(tile);
378 }
379 
386 static bool IsCloseToTown(TileIndex tile, uint dist)
387 {
388  if (_town_kdtree.Count() == 0) return false;
389  Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
390  return DistanceManhattan(tile, t->xy) < dist;
391 }
392 
398 {
399  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
400 
401  if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
402 
403  SetDParam(0, this->index);
404  SetDParam(1, this->cache.population);
405  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
406  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
407  STR_VIEWPORT_TOWN);
408 
409  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
410 
412 }
413 
416 {
417  for (Town *t : Town::Iterate()) {
418  t->UpdateVirtCoord();
419  }
420 }
421 
422 void ClearAllTownCachedNames()
423 {
424  for (Town *t : Town::Iterate()) {
425  t->cached_name.clear();
426  }
427 }
428 
434 static void ChangePopulation(Town *t, int mod)
435 {
436  t->cache.population += mod;
437  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
439 
440  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_POPULATION_CHANGE);
441 }
442 
449 {
450  uint32 pop = 0;
451  for (const Town *t : Town::Iterate()) pop += t->cache.population;
452  return pop;
453 }
454 
462 static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
463 {
464  for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
465  const Station *st = *it;
466 
467  bool covers_area = st->TileIsInCatchment(tile);
468  if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
469  if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
470  if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
471 
472  if (covers_area && !st->CatchmentCoversTown(t->index)) {
473  it = t->stations_near.erase(it);
474  } else {
475  ++it;
476  }
477  }
478 }
479 
485 {
486  assert(IsTileType(tile, MP_HOUSE));
487 
488  /* progress in construction stages */
490  if (GetHouseConstructionTick(tile) != 0) return;
491 
492  AnimateNewHouseConstruction(tile);
493 
494  if (IsHouseCompleted(tile)) {
495  /* Now that construction is complete, we can add the population of the
496  * building to the town. */
497  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
498  ResetHouseAge(tile);
499  }
500  MarkTileDirtyByTile(tile);
501 }
502 
508 {
509  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
510  if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
511  if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
512  if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
513  if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
514 }
515 
522 static void TileLoop_Town(TileIndex tile)
523 {
524  HouseID house_id = GetHouseType(tile);
525 
526  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
527  * doesn't exist any more, so don't continue here. */
528  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
529 
530  if (!IsHouseCompleted(tile)) {
531  /* Construction is not completed. See if we can go further in construction*/
532  MakeTownHouseBigger(tile);
533  return;
534  }
535 
536  const HouseSpec *hs = HouseSpec::Get(house_id);
537 
538  /* If the lift has a destination, it is already an animated tile. */
539  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
540  house_id < NEW_HOUSE_OFFSET &&
541  !LiftHasDestination(tile) &&
542  Chance16(1, 2)) {
543  AddAnimatedTile(tile);
544  }
545 
546  Town *t = Town::GetByTile(tile);
547  uint32 r = Random();
548 
549  StationFinder stations(TileArea(tile, 1, 1));
550 
552  for (uint i = 0; i < 256; i++) {
553  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
554 
555  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
556 
557  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
558  if (cargo == CT_INVALID) continue;
559 
560  uint amt = GB(callback, 0, 8);
561  if (amt == 0) continue;
562 
563  uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
564 
565  const CargoSpec *cs = CargoSpec::Get(cargo);
566  t->supplied[cs->Index()].new_max += amt;
567  t->supplied[cs->Index()].new_act += moved;
568  }
569  } else {
571  case TCGM_ORIGINAL:
572  /* Original (quadratic) cargo generation algorithm */
573  if (GB(r, 0, 8) < hs->population) {
574  uint amt = GB(r, 0, 8) / 8 + 1;
575 
576  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
577  t->supplied[CT_PASSENGERS].new_max += amt;
578  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
579  }
580 
581  if (GB(r, 8, 8) < hs->mail_generation) {
582  uint amt = GB(r, 8, 8) / 8 + 1;
583 
584  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
585  t->supplied[CT_MAIL].new_max += amt;
586  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
587  }
588  break;
589 
590  case TCGM_BITCOUNT:
591  /* Binomial distribution per tick, by a series of coin flips */
592  /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
593  * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
594  if (GB(_tick_counter, 8, 2) == GB(tile, 0, 2)) {
595  /* Make a bitmask with up to 32 bits set, one for each potential pax */
596  int genmax = (hs->population + 7) / 8;
597  uint32 genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
598  /* Mask random value by potential pax and count number of actual pax */
599  uint amt = CountBits(r & genmask);
600  /* Adjust and apply */
601  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
602  t->supplied[CT_PASSENGERS].new_max += amt;
603  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
604 
605  /* Do the same for mail, with a fresh random */
606  r = Random();
607  genmax = (hs->mail_generation + 7) / 8;
608  genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
609  amt = CountBits(r & genmask);
610  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
611  t->supplied[CT_MAIL].new_max += amt;
612  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
613  }
614  break;
615 
616  default:
617  NOT_REACHED();
618  }
619  }
620 
621  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
622 
623  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
625  CanDeleteHouse(tile) &&
626  GetHouseAge(tile) >= hs->minimum_life &&
627  --t->time_until_rebuild == 0) {
628  t->time_until_rebuild = GB(r, 16, 8) + 192;
629 
630  ClearTownHouse(t, tile);
631 
632  /* Rebuild with another house? */
633  if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
634  }
635 
636  cur_company.Restore();
637 }
638 
639 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
640 {
641  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
642  if (!CanDeleteHouse(tile)) return CMD_ERROR;
643 
644  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
645 
647  cost.AddCost(hs->GetRemovalCost());
648 
649  int rating = hs->remove_rating_decrease;
650  Town *t = Town::GetByTile(tile);
651 
653  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
654  SetDParam(0, t->index);
655  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
656  }
657  }
658 
659  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
660  if (flags & DC_EXEC) {
661  ClearTownHouse(t, tile);
662  }
663 
664  return cost;
665 }
666 
667 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
668 {
669  HouseID house_id = GetHouseType(tile);
670  const HouseSpec *hs = HouseSpec::Get(house_id);
671  Town *t = Town::GetByTile(tile);
672 
674  for (uint i = 0; i < 256; i++) {
675  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
676 
677  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
678 
679  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
680 
681  if (cargo == CT_INVALID) continue;
682  produced[cargo]++;
683  }
684  } else {
685  if (hs->population > 0) {
686  produced[CT_PASSENGERS]++;
687  }
688  if (hs->mail_generation > 0) {
689  produced[CT_MAIL]++;
690  }
691  }
692 }
693 
694 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
695 {
696  if (cargo == CT_INVALID || amount == 0) return;
697  acceptance[cargo] += amount;
698  SetBit(*always_accepted, cargo);
699 }
700 
701 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
702 {
703  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
704  CargoID accepts[lengthof(hs->accepts_cargo)];
705 
706  /* Set the initial accepted cargo types */
707  for (uint8 i = 0; i < lengthof(accepts); i++) {
708  accepts[i] = hs->accepts_cargo[i];
709  }
710 
711  /* Check for custom accepted cargo types */
713  uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
714  if (callback != CALLBACK_FAILED) {
715  /* Replace accepted cargo types with translated values from callback */
716  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
717  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
718  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
719  }
720  }
721 
722  /* Check for custom cargo acceptance */
724  uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
725  if (callback != CALLBACK_FAILED) {
726  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
727  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
728  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
729  /* The 'S' bit indicates food instead of goods */
730  AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
731  } else {
732  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
733  }
734  return;
735  }
736  }
737 
738  /* No custom acceptance, so fill in with the default values */
739  for (uint8 i = 0; i < lengthof(accepts); i++) {
740  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
741  }
742 }
743 
744 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
745 {
746  const HouseID house = GetHouseType(tile);
747  const HouseSpec *hs = HouseSpec::Get(house);
748  bool house_completed = IsHouseCompleted(tile);
749 
750  td->str = hs->building_name;
751 
752  uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
753  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
754  if (callback_res > 0x400) {
756  } else {
757  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
758  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
759  td->str = new_name;
760  }
761  }
762  }
763 
764  if (!house_completed) {
765  SetDParamX(td->dparam, 0, td->str);
766  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
767  }
768 
769  if (hs->grf_prop.grffile != nullptr) {
770  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
771  td->grf = gc->GetName();
772  }
773 
774  td->owner[0] = OWNER_TOWN;
775 }
776 
777 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
778 {
779  /* not used */
780  return 0;
781 }
782 
783 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
784 {
785  /* not used */
786 }
787 
792 {
793  t->cargo_accepted_total = 0;
794 
795  const TileArea &area = t->cargo_accepted.GetArea();
796  TILE_AREA_LOOP(tile, area) {
797  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
798  t->cargo_accepted_total |= t->cargo_accepted[tile];
799  }
800  }
801 }
802 
809 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
810 {
811  CargoArray accepted, produced;
812  CargoTypes dummy = 0;
813 
814  /* Gather acceptance for all houses in an area around the start tile.
815  * The area is composed of the square the tile is in, extended one square in all
816  * directions as the coverage area of a single station is bigger than just one square. */
818  TILE_AREA_LOOP(tile, area) {
819  if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
820 
821  AddAcceptedCargo_Town(tile, accepted, &dummy);
822  AddProducedCargo_Town(tile, produced);
823  }
824 
825  /* Create bitmap of produced and accepted cargoes. */
826  CargoTypes acc = 0;
827  for (uint cid = 0; cid < NUM_CARGO; cid++) {
828  if (accepted[cid] >= 8) SetBit(acc, cid);
829  if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
830  }
831  t->cargo_accepted[start] = acc;
832 
833  if (update_total) UpdateTownCargoTotal(t);
834 }
835 
840 {
841  t->cargo_produced = 0;
842 
843  const TileArea &area = t->cargo_accepted.GetArea();
844  if (area.tile == INVALID_TILE) return;
845 
846  /* Update acceptance for each grid square. */
847  TILE_AREA_LOOP(tile, area) {
848  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
849  UpdateTownCargoes(t, tile, false);
850  }
851  }
852 
853  /* Update the total acceptance. */
855 }
856 
859 {
861 
862  for (const Town *town : Town::Iterate()) {
863  _town_cargoes_accepted |= town->cargo_accepted_total;
864  }
865 }
866 
867 static bool GrowTown(Town *t);
868 
869 static void TownTickHandler(Town *t)
870 {
871  if (HasBit(t->flags, TOWN_IS_GROWING)) {
872  int i = (int)t->grow_counter - 1;
873  if (i < 0) {
874  if (GrowTown(t)) {
875  i = t->growth_rate;
876  } else {
877  /* If growth failed wait a bit before retrying */
878  i = min(t->growth_rate, TOWN_GROWTH_TICKS - 1);
879  }
880  }
881  t->grow_counter = i;
882  }
883 }
884 
885 void OnTick_Town()
886 {
887  if (_game_mode == GM_EDITOR) return;
888 
889  for (Town *t : Town::Iterate()) {
890  TownTickHandler(t);
891  }
892 }
893 
903 {
904  if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
905 
906  return GetAnyRoadBits(tile, RTT_ROAD, true);
907 }
908 
909 RoadType GetTownRoadType(const Town *t)
910 {
911  RoadType best_rt = ROADTYPE_ROAD;
912  const RoadTypeInfo *best = nullptr;
913  const uint16 assume_max_speed = 50;
914 
915  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
916  if (RoadTypeIsTram(rt)) continue;
917 
918  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
919 
920  /* Unused road type. */
921  if (rti->label == 0) continue;
922 
923  /* Can town build this road. */
924  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
925 
926  /* Not yet introduced at this date. */
927  if (IsInsideMM(rti->introduction_date, 0, MAX_DAY) && rti->introduction_date > _date) continue;
928 
929  if (best != nullptr) {
930  if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
931  }
932 
933  best_rt = rt;
934  best = rti;
935  }
936 
937  return best_rt;
938 }
939 
950 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
951 {
952  if (!IsValidTile(tile)) return false;
953 
954  /* Lookup table for the used diff values */
955  const TileIndexDiff tid_lt[3] = {
959  };
960 
961  dist_multi = (dist_multi + 1) * 4;
962  for (uint pos = 4; pos < dist_multi; pos++) {
963  /* Go (pos / 4) tiles to the left or the right */
964  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
965 
966  /* Use the current tile as origin, or go one tile backwards */
967  if (pos & 2) cur += tid_lt[2];
968 
969  /* Test for roadbit parallel to dir and facing towards the middle axis */
970  if (IsValidTile(tile + cur) &&
971  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
972  }
973  return false;
974 }
975 
984 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
985 {
986  if (DistanceFromEdge(tile) == 0) return false;
987 
988  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
989  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
990 
991  /* Check if there already is a road at this point? */
992  if (GetTownRoadBits(tile) == ROAD_NONE) {
993  /* No, try if we are able to build a road piece there.
994  * If that fails clear the land, and if that fails exit.
995  * This is to make sure that we can build a road here later. */
996  RoadType rt = GetTownRoadType(t);
997  if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X) | (rt << 4), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
998  DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
999  return false;
1000  }
1001  }
1002 
1004  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
1005  if (cur_slope == SLOPE_FLAT) return ret;
1006 
1007  /* If the tile is not a slope in the right direction, then
1008  * maybe terraform some. */
1009  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
1010  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
1011  if (Chance16(1, 8)) {
1012  CommandCost res = CMD_ERROR;
1013  if (!_generating_world && Chance16(1, 10)) {
1014  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
1015  res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
1017  }
1018  if (res.Failed() && Chance16(1, 3)) {
1019  /* We can consider building on the slope, though. */
1020  return ret;
1021  }
1022  }
1023  return false;
1024  }
1025  return ret;
1026 }
1027 
1028 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
1029 {
1030  assert(tile < MapSize());
1031 
1032  CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
1033  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
1034  DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
1035  return true;
1036 }
1037 
1038 static void LevelTownLand(TileIndex tile)
1039 {
1040  assert(tile < MapSize());
1041 
1042  /* Don't terraform if land is plain or if there's a house there. */
1043  if (IsTileType(tile, MP_HOUSE)) return;
1044  Slope tileh = GetTileSlope(tile);
1045  if (tileh == SLOPE_FLAT) return;
1046 
1047  /* First try up, then down */
1048  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
1049  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
1050  }
1051 }
1052 
1063 {
1064  /* align the grid to the downtown */
1065  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1066  RoadBits rcmd = ROAD_NONE;
1067 
1068  switch (t->layout) {
1069  default: NOT_REACHED();
1070 
1071  case TL_2X2_GRID:
1072  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1073  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1074  break;
1075 
1076  case TL_3X3_GRID:
1077  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1078  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1079  break;
1080  }
1081 
1082  /* Optimise only X-junctions */
1083  if (rcmd != ROAD_ALL) return rcmd;
1084 
1085  RoadBits rb_template;
1086 
1087  switch (GetTileSlope(tile)) {
1088  default: rb_template = ROAD_ALL; break;
1089  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1090  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1091  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1092  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1093  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1094  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1095  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1096  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1097  case SLOPE_STEEP_W:
1098  case SLOPE_STEEP_S:
1099  case SLOPE_STEEP_E:
1100  case SLOPE_STEEP_N:
1101  rb_template = ROAD_NONE;
1102  break;
1103  }
1104 
1105  /* Stop if the template is compatible to the growth dir */
1106  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1107  /* If not generate a straight road in the direction of the growth */
1109 }
1110 
1122 {
1123  /* We can't look further than that. */
1124  if (DistanceFromEdge(tile) == 0) return false;
1125 
1126  uint counter = 0; // counts the house neighbor tiles
1127 
1128  /* Check the tiles E,N,W and S of the current tile for houses */
1129  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1130  /* Count both void and house tiles for checking whether there
1131  * are enough houses in the area. This to make it likely that
1132  * houses get build up to the edge of the map. */
1133  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1134  case MP_HOUSE:
1135  case MP_VOID:
1136  counter++;
1137  break;
1138 
1139  default:
1140  break;
1141  }
1142 
1143  /* If there are enough neighbors stop here */
1144  if (counter >= 3) {
1145  if (BuildTownHouse(t, tile)) {
1146  _grow_town_result = GROWTH_SUCCEED;
1147  return true;
1148  }
1149  return false;
1150  }
1151  }
1152  return false;
1153 }
1154 
1163 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1164 {
1165  RoadType rt = GetTownRoadType(t);
1166  if (DoCommand(tile, rcmd | (rt << 4), t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1167  _grow_town_result = GROWTH_SUCCEED;
1168  return true;
1169  }
1170  return false;
1171 }
1172 
1183 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1184 {
1185  assert(bridge_dir < DIAGDIR_END);
1186 
1187  const Slope slope = GetTileSlope(tile);
1188 
1189  /* Make sure the direction is compatible with the slope.
1190  * Well we check if the slope has an up bit set in the
1191  * reverse direction. */
1192  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1193 
1194  /* Assure that the bridge is connectable to the start side */
1195  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1196 
1197  /* We are in the right direction */
1198  uint8 bridge_length = 0; // This value stores the length of the possible bridge
1199  TileIndex bridge_tile = tile; // Used to store the other waterside
1200 
1201  const int delta = TileOffsByDiagDir(bridge_dir);
1202 
1203  if (slope == SLOPE_FLAT) {
1204  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1205  do {
1206  if (bridge_length++ >= 4) {
1207  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1208  return false;
1209  }
1210  bridge_tile += delta;
1211  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1212  } else {
1213  do {
1214  if (bridge_length++ >= 11) {
1215  /* Max 11 tile long bridges */
1216  return false;
1217  }
1218  bridge_tile += delta;
1219  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1220  }
1221 
1222  /* no water tiles in between? */
1223  if (bridge_length == 1) return false;
1224 
1225  for (uint8 times = 0; times <= 22; times++) {
1226  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1227 
1228  /* Can we actually build the bridge? */
1229  RoadType rt = GetTownRoadType(t);
1230  if (DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1231  DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1232  _grow_town_result = GROWTH_SUCCEED;
1233  return true;
1234  }
1235  }
1236  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1237  return false;
1238 }
1239 
1240 
1247 static inline bool RoadTypesAllowHouseHere(TileIndex t)
1248 {
1249  static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1250  bool allow = false;
1251 
1252  for (const TileIndexDiffC *ptr = tiles; ptr != endof(tiles); ++ptr) {
1253  TileIndex cur_tile = t + ToTileIndexDiff(*ptr);
1254  if (!IsValidTile(cur_tile)) continue;
1255 
1256  if (!(IsTileType(cur_tile, MP_ROAD) || IsTileType(cur_tile, MP_STATION))) continue;
1257  allow = true;
1258 
1259  RoadType road_rt = GetRoadTypeRoad(cur_tile);
1260  RoadType tram_rt = GetRoadTypeTram(cur_tile);
1261  if (road_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(road_rt)->flags, ROTF_NO_HOUSES)) return true;
1262  if (tram_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(tram_rt)->flags, ROTF_NO_HOUSES)) return true;
1263  }
1264 
1265  /* If no road was found surrounding the tile we can allow building the house since there is
1266  * nothing which forbids it, if a road was found but the execution reached this point, then
1267  * all the found roads don't allow houses to be built */
1268  return !allow;
1269 }
1270 
1288 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1289 {
1290  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1291  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1292 
1293  assert(tile < MapSize());
1294 
1295  if (cur_rb == ROAD_NONE) {
1296  /* Tile has no road. First reset the status counter
1297  * to say that this is the last iteration. */
1298  _grow_town_result = GROWTH_SEARCH_STOPPED;
1299 
1302 
1303  /* Remove hills etc */
1304  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1305 
1306  /* Is a road allowed here? */
1307  switch (t1->layout) {
1308  default: NOT_REACHED();
1309 
1310  case TL_3X3_GRID:
1311  case TL_2X2_GRID:
1312  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1313  if (rcmd == ROAD_NONE) return;
1314  break;
1315 
1316  case TL_BETTER_ROADS:
1317  case TL_ORIGINAL:
1318  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1319 
1320  DiagDirection source_dir = ReverseDiagDir(target_dir);
1321 
1322  if (Chance16(1, 4)) {
1323  /* Randomize a new target dir */
1324  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1325  }
1326 
1327  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1328  /* A road is not allowed to continue the randomized road,
1329  * return if the road we're trying to build is curved. */
1330  if (target_dir != ReverseDiagDir(source_dir)) return;
1331 
1332  /* Return if neither side of the new road is a house */
1335  return;
1336  }
1337 
1338  /* That means that the road is only allowed if there is a house
1339  * at any side of the new road. */
1340  }
1341 
1342  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1343  break;
1344  }
1345 
1346  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1347  /* Continue building on a partial road.
1348  * Should be always OK, so we only generate
1349  * the fitting RoadBits */
1350  _grow_town_result = GROWTH_SEARCH_STOPPED;
1351 
1353 
1354  switch (t1->layout) {
1355  default: NOT_REACHED();
1356 
1357  case TL_3X3_GRID:
1358  case TL_2X2_GRID:
1359  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1360  break;
1361 
1362  case TL_BETTER_ROADS:
1363  case TL_ORIGINAL:
1364  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1365  break;
1366  }
1367  } else {
1368  bool allow_house = true; // Value which decides if we want to construct a house
1369 
1370  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1371  * it is the starting tile. Half the time, we stay on this side then.*/
1372  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1373  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1374  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1375  }
1376  return;
1377  }
1378 
1379  /* Possibly extend the road in a direction.
1380  * Randomize a direction and if it has a road, bail out. */
1381  target_dir = RandomDiagDir();
1382  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1383  TileIndex house_tile; // position of a possible house
1384 
1385  if (cur_rb & target_rb) {
1386  /* If it's a road turn possibly build a house in a corner.
1387  * Use intersection with straight road as an indicator
1388  * that we randomed corner house position.
1389  * A turn (and we check for that later) always has only
1390  * one common bit with a straight road so it has the same
1391  * chance to be chosen as the house on the side of a road.
1392  */
1393  if ((cur_rb & ROAD_X) != target_rb) return;
1394 
1395  /* Check whether it is a turn and if so determine
1396  * position of the corner tile */
1397  switch (cur_rb) {
1398  case ROAD_N:
1399  house_tile = TileAddByDir(tile, DIR_S);
1400  break;
1401  case ROAD_S:
1402  house_tile = TileAddByDir(tile, DIR_N);
1403  break;
1404  case ROAD_E:
1405  house_tile = TileAddByDir(tile, DIR_W);
1406  break;
1407  case ROAD_W:
1408  house_tile = TileAddByDir(tile, DIR_E);
1409  break;
1410  default:
1411  return; // not a turn
1412  }
1413  target_dir = DIAGDIR_END;
1414  } else {
1415  house_tile = TileAddByDiagDir(tile, target_dir);
1416  }
1417 
1418  /* Don't walk into water. */
1419  if (HasTileWaterGround(house_tile)) return;
1420 
1421  if (!IsValidTile(house_tile)) return;
1422 
1424  switch (t1->layout) {
1425  default: NOT_REACHED();
1426 
1427  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1428  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1429  FALLTHROUGH;
1430 
1431  case TL_2X2_GRID:
1432  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1433  allow_house = (rcmd & target_rb) == ROAD_NONE;
1434  break;
1435 
1436  case TL_BETTER_ROADS: // Use original afterwards!
1437  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1438  FALLTHROUGH;
1439 
1440  case TL_ORIGINAL:
1441  /* Allow a house at the edge. 60% chance or
1442  * always ok if no road allowed. */
1443  rcmd = target_rb;
1444  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1445  break;
1446  }
1447  }
1448 
1449  allow_house &= RoadTypesAllowHouseHere(house_tile);
1450 
1451  if (allow_house) {
1452  /* Build a house, but not if there already is a house there. */
1453  if (!IsTileType(house_tile, MP_HOUSE)) {
1454  /* Level the land if possible */
1455  if (Chance16(1, 6)) LevelTownLand(house_tile);
1456 
1457  /* And build a house.
1458  * Set result to -1 if we managed to build it. */
1459  if (BuildTownHouse(t1, house_tile)) {
1460  _grow_town_result = GROWTH_SUCCEED;
1461  }
1462  }
1463  return;
1464  }
1465 
1466  _grow_town_result = GROWTH_SEARCH_STOPPED;
1467  }
1468 
1469  /* Return if a water tile */
1470  if (HasTileWaterGround(tile)) return;
1471 
1472  /* Make the roads look nicer */
1473  rcmd = CleanUpRoadBits(tile, rcmd);
1474  if (rcmd == ROAD_NONE) return;
1475 
1476  /* Only use the target direction for bridges to ensure they're connected.
1477  * The target_dir is as computed previously according to town layout, so
1478  * it will match it perfectly. */
1479  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1480 
1481  GrowTownWithRoad(t1, tile, rcmd);
1482 }
1483 
1491 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1492 {
1493  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1494  if (!IsValidTile(target_tile)) return false;
1495  if (HasTileWaterGround(target_tile)) return false;
1496 
1497  RoadBits target_rb = GetTownRoadBits(target_tile);
1499  /* Check whether a road connection exists or can be build. */
1500  switch (GetTileType(target_tile)) {
1501  case MP_ROAD:
1502  return target_rb != ROAD_NONE;
1503 
1504  case MP_STATION:
1505  return IsDriveThroughStopTile(target_tile);
1506 
1507  case MP_TUNNELBRIDGE:
1508  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1509 
1510  case MP_HOUSE:
1511  case MP_INDUSTRY:
1512  case MP_OBJECT:
1513  return false;
1514 
1515  default:
1516  /* Checked for void and water earlier */
1517  return true;
1518  }
1519  } else {
1520  /* Check whether a road connection already exists,
1521  * and it leads somewhere else. */
1522  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1523  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1524  }
1525 }
1526 
1533 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1534 {
1535  /* Special case.
1536  * @see GrowTownInTile Check the else if
1537  */
1538  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1539 
1540  assert(tile < MapSize());
1541 
1542  /* Number of times to search.
1543  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1544  * them a little handicap. */
1545  switch (t->layout) {
1546  case TL_BETTER_ROADS:
1547  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1548  break;
1549 
1550  case TL_3X3_GRID:
1551  case TL_2X2_GRID:
1552  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1553  break;
1554 
1555  default:
1556  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1557  break;
1558  }
1559 
1560  do {
1561  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1562 
1563  /* Try to grow the town from this point */
1564  GrowTownInTile(&tile, cur_rb, target_dir, t);
1565  if (_grow_town_result == GROWTH_SUCCEED) return true;
1566 
1567  /* Exclude the source position from the bitmask
1568  * and return if no more road blocks available */
1569  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1570  if (cur_rb == ROAD_NONE) return false;
1571 
1572  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1573  /* Only build in the direction away from the tunnel or bridge. */
1574  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1575  } else {
1576  /* Select a random bit from the blockmask, walk a step
1577  * and continue the search from there. */
1578  do {
1579  if (cur_rb == ROAD_NONE) return false;
1580  RoadBits target_bits;
1581  do {
1582  target_dir = RandomDiagDir();
1583  target_bits = DiagDirToRoadBits(target_dir);
1584  } while (!(cur_rb & target_bits));
1585  cur_rb &= ~target_bits;
1586  } while (!CanFollowRoad(tile, target_dir));
1587  }
1588  tile = TileAddByDiagDir(tile, target_dir);
1589 
1590  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, RTT_ROAD)) {
1591  /* Don't allow building over roads of other cities */
1592  if (IsRoadOwner(tile, RTT_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1593  return false;
1594  } else if (IsRoadOwner(tile, RTT_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1595  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1596  * owner :) (happy happy happy road now) */
1597  SetRoadOwner(tile, RTT_ROAD, OWNER_TOWN);
1598  SetTownIndex(tile, t->index);
1599  }
1600  }
1601 
1602  /* Max number of times is checked. */
1603  } while (--_grow_town_result >= 0);
1604 
1605  return false;
1606 }
1607 
1616 {
1617  uint32 r = Random();
1618  uint a = GB(r, 0, 2);
1619  uint b = GB(r, 8, 2);
1620  if (a == b) b ^= 2;
1621  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1622 }
1623 
1629 static bool GrowTown(Town *t)
1630 {
1631  static const TileIndexDiffC _town_coord_mod[] = {
1632  {-1, 0},
1633  { 1, 1},
1634  { 1, -1},
1635  {-1, -1},
1636  {-1, 0},
1637  { 0, 2},
1638  { 2, 0},
1639  { 0, -2},
1640  {-1, -1},
1641  {-2, 2},
1642  { 2, 2},
1643  { 2, -2},
1644  { 0, 0}
1645  };
1646 
1647  /* Current "company" is a town */
1648  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1649 
1650  TileIndex tile = t->xy; // The tile we are working with ATM
1651 
1652  /* Find a road that we can base the construction on. */
1653  const TileIndexDiffC *ptr;
1654  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1655  if (GetTownRoadBits(tile) != ROAD_NONE) {
1656  bool success = GrowTownAtRoad(t, tile);
1657  cur_company.Restore();
1658  return success;
1659  }
1660  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1661  }
1662 
1663  /* No road available, try to build a random road block by
1664  * clearing some land and then building a road there. */
1666  tile = t->xy;
1667  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1668  /* Only work with plain land that not already has a house */
1669  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1670  if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1671  RoadType rt = GetTownRoadType(t);
1672  DoCommand(tile, GenRandomRoadBits() | (rt << 4), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1673  cur_company.Restore();
1674  return true;
1675  }
1676  }
1677  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1678  }
1679  }
1680 
1681  cur_company.Restore();
1682  return false;
1683 }
1684 
1685 void UpdateTownRadius(Town *t)
1686 {
1687  static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1688  { 4, 0, 0, 0, 0}, // 0
1689  { 16, 0, 0, 0, 0},
1690  { 25, 0, 0, 0, 0},
1691  { 36, 0, 0, 0, 0},
1692  { 49, 0, 4, 0, 0},
1693  { 64, 0, 4, 0, 0}, // 20
1694  { 64, 0, 9, 0, 1},
1695  { 64, 0, 9, 0, 4},
1696  { 64, 0, 16, 0, 4},
1697  { 81, 0, 16, 0, 4},
1698  { 81, 0, 16, 0, 4}, // 40
1699  { 81, 0, 25, 0, 9},
1700  { 81, 36, 25, 0, 9},
1701  { 81, 36, 25, 16, 9},
1702  { 81, 49, 0, 25, 9},
1703  { 81, 64, 0, 25, 9}, // 60
1704  { 81, 64, 0, 36, 9},
1705  { 81, 64, 0, 36, 16},
1706  {100, 81, 0, 49, 16},
1707  {100, 81, 0, 49, 25},
1708  {121, 81, 0, 49, 25}, // 80
1709  {121, 81, 0, 49, 25},
1710  {121, 81, 0, 49, 36}, // 88
1711  };
1712 
1713  if (t->cache.num_houses < 92) {
1714  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));
1715  } else {
1716  int mass = t->cache.num_houses / 8;
1717  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1718  * The offsets are to make sure the radii do not decrease in size when going from the table
1719  * to the calculated value.*/
1720  t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1721  t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1722  t->cache.squared_town_zone_radius[2] = 0;
1723  t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1724  t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1725  }
1726 }
1727 
1728 void UpdateTownMaxPass(Town *t)
1729 {
1730  t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1731  t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1732 }
1733 
1734 static void UpdateTownGrowthRate(Town *t);
1735 static void UpdateTownGrowth(Town *t);
1736 
1748 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1749 {
1750  t->xy = tile;
1751  t->cache.num_houses = 0;
1752  t->time_until_rebuild = 10;
1753  UpdateTownRadius(t);
1754  t->flags = 0;
1755  t->cache.population = 0;
1756  /* Spread growth across ticks so even if there are many
1757  * similar towns they're unlikely to grow all in one tick */
1759  t->growth_rate = TownTicksToGameTicks(250);
1760  t->show_zone = false;
1761 
1762  _town_kdtree.Insert(t->index);
1763 
1764  /* Set the default cargo requirement for town growth */
1766  case LT_ARCTIC:
1768  break;
1769 
1770  case LT_TROPIC:
1773  break;
1774  }
1775 
1776  t->fund_buildings_months = 0;
1777 
1778  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1779 
1780  t->have_ratings = 0;
1782  t->exclusive_counter = 0;
1783  t->statues = 0;
1784 
1785  extern int _nb_orig_names;
1787  /* Original town name */
1788  t->townnamegrfid = 0;
1789  t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1790  } else {
1791  /* Newgrf town name */
1792  t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1793  t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1794  }
1795  t->townnameparts = townnameparts;
1796 
1797  t->UpdateVirtCoord();
1798  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
1799 
1800  t->InitializeLayout(layout);
1801 
1802  t->larger_town = city;
1803 
1804  int x = (int)size * 16 + 3;
1805  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1806  /* Don't create huge cities when founding town in-game */
1807  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1808 
1809  t->cache.num_houses += x;
1810  UpdateTownRadius(t);
1811 
1812  int i = x * 4;
1813  do {
1814  GrowTown(t);
1815  } while (--i);
1816 
1817  t->cache.num_houses -= x;
1818  UpdateTownRadius(t);
1820  UpdateTownMaxPass(t);
1822 }
1823 
1830 {
1831  /* Check if too close to the edge of map */
1832  if (DistanceFromEdge(tile) < 12) {
1833  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1834  }
1835 
1836  /* Check distance to all other towns. */
1837  if (IsCloseToTown(tile, 20)) {
1838  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1839  }
1840 
1841  /* Can only build on clear flat areas, possibly with trees. */
1842  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1843  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1844  }
1845 
1846  return CommandCost(EXPENSES_OTHER);
1847 }
1848 
1854 static bool IsUniqueTownName(const char *name)
1855 {
1856  for (const Town *t : Town::Iterate()) {
1857  if (t->name != nullptr && strcmp(t->name, name) == 0) return false;
1858  }
1859 
1860  return true;
1861 }
1862 
1875 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1876 {
1877  TownSize size = Extract<TownSize, 0, 2>(p1);
1878  bool city = HasBit(p1, 2);
1879  TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1881  bool random = HasBit(p1, 6);
1882  uint32 townnameparts = p2;
1883 
1884  if (size >= TSZ_END) return CMD_ERROR;
1885  if (layout >= NUM_TLS) return CMD_ERROR;
1886 
1887  /* Some things are allowed only in the scenario editor and for game scripts. */
1888  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1890  if (size == TSZ_LARGE) return CMD_ERROR;
1891  if (random) return CMD_ERROR;
1893  return CMD_ERROR;
1894  }
1895  } else if (_current_company == OWNER_DEITY && random) {
1896  /* Random parameter is not allowed for Game Scripts. */
1897  return CMD_ERROR;
1898  }
1899 
1900  if (StrEmpty(text)) {
1901  /* If supplied name is empty, townnameparts has to generate unique automatic name */
1902  if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1903  } else {
1904  /* If name is not empty, it has to be unique custom name */
1906  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1907  }
1908 
1909  /* Allocate town struct */
1910  if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1911 
1912  if (!random) {
1913  CommandCost ret = TownCanBePlacedHere(tile);
1914  if (ret.Failed()) return ret;
1915  }
1916 
1917  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1918  /* multidimensional arrays have to have defined length of non-first dimension */
1919  assert_compile(lengthof(price_mult[0]) == 4);
1920 
1921  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1922  byte mult = price_mult[city][size];
1923 
1924  cost.MultiplyCost(mult);
1925 
1926  /* Create the town */
1927  if (flags & DC_EXEC) {
1928  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1929  _additional_cash_required = cost.GetCost();
1930  return CommandCost(EXPENSES_OTHER);
1931  }
1932 
1933  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1935  Town *t;
1936  if (random) {
1937  t = CreateRandomTown(20, townnameparts, size, city, layout);
1938  if (t == nullptr) {
1939  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1940  } else {
1941  _new_town_id = t->index;
1942  }
1943  } else {
1944  t = new Town(tile);
1945  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1946  }
1948  old_generating_world.Restore();
1949 
1950  if (t != nullptr && !StrEmpty(text)) {
1951  t->name = stredup(text);
1952  t->UpdateVirtCoord();
1953  }
1954 
1955  if (_game_mode != GM_EDITOR) {
1956  /* 't' can't be nullptr since 'random' is false outside scenedit */
1957  assert(!random);
1958 
1959  if (_current_company == OWNER_DEITY) {
1960  SetDParam(0, t->index);
1961  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
1962  } else {
1963  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1965  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1966 
1967  char *cn = stredup(company_name);
1968  SetDParamStr(0, cn);
1969  SetDParam(1, t->index);
1970 
1971  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1972  }
1973  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1974  Game::NewEvent(new ScriptEventTownFounded(t->index));
1975  }
1976  }
1977  return cost;
1978 }
1979 
1990 {
1991  switch (layout) {
1992  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1993  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1994  default: return tile;
1995  }
1996 }
1997 
2007 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
2008 {
2009  switch (layout) {
2010  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2011  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2012  default: return true;
2013  }
2014 }
2015 
2019 struct SpotData {
2021  uint max_dist;
2023 };
2024 
2041 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
2042 {
2043  SpotData *sp = (SpotData*)user_data;
2044  uint dist = GetClosestWaterDistance(tile, true);
2045 
2046  if (IsTileType(tile, MP_CLEAR) &&
2047  IsTileFlat(tile) &&
2048  IsTileAlignedToGrid(tile, sp->layout) &&
2049  dist > sp->max_dist) {
2050  sp->tile = tile;
2051  sp->max_dist = dist;
2052  }
2053 
2054  return false;
2055 }
2056 
2063 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
2064 {
2065  return IsTileType(tile, MP_CLEAR);
2066 }
2067 
2081 {
2082  SpotData sp = { INVALID_TILE, 0, layout };
2083 
2084  TileIndex coast = tile;
2085  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
2086  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
2087  return sp.tile;
2088  }
2089 
2090  /* if we get here just give up */
2091  return INVALID_TILE;
2092 }
2093 
2094 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
2095 {
2096  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
2097 
2098  if (!Town::CanAllocateItem()) return nullptr;
2099 
2100  do {
2101  /* Generate a tile index not too close from the edge */
2102  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2103 
2104  /* if we tried to place the town on water, slide it over onto
2105  * the nearest likely-looking spot */
2106  if (IsTileType(tile, MP_WATER)) {
2107  tile = FindNearestGoodCoastalTownSpot(tile, layout);
2108  if (tile == INVALID_TILE) continue;
2109  }
2110 
2111  /* Make sure town can be placed here */
2112  if (TownCanBePlacedHere(tile).Failed()) continue;
2113 
2114  /* Allocate a town struct */
2115  Town *t = new Town(tile);
2116 
2117  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2118 
2119  /* if the population is still 0 at the point, then the
2120  * placement is so bad it couldn't grow at all */
2121  if (t->cache.population > 0) return t;
2122 
2123  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2125  cur_company.Restore();
2126  assert(rc.Succeeded());
2127 
2128  /* We already know that we can allocate a single town when
2129  * entering this function. However, we create and delete
2130  * a town which "resets" the allocation checks. As such we
2131  * need to check again when assertions are enabled. */
2132  assert(Town::CanAllocateItem());
2133  } while (--attempts != 0);
2134 
2135  return nullptr;
2136 }
2137 
2138 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2139 
2148 {
2149  uint current_number = 0;
2150  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2151  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
2152  total = min(TownPool::MAX_SIZE, total);
2153  uint32 townnameparts;
2154  TownNames town_names;
2155 
2157 
2158  /* First attempt will be made at creating the suggested number of towns.
2159  * Note that this is really a suggested value, not a required one.
2160  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2161  do {
2164  /* Get a unique name for the town. */
2165  if (!GenerateTownName(&townnameparts, &town_names)) continue;
2166  /* try 20 times to create a random-sized town for the first loop. */
2167  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2168  } while (--total);
2169 
2170  town_names.clear();
2171 
2172  /* Build the town k-d tree again to make sure it's well balanced */
2173  RebuildTownKdtree();
2174 
2175  if (current_number != 0) return true;
2176 
2177  /* If current_number is still zero at this point, it means that not a single town has been created.
2178  * So give it a last try, but now more aggressive */
2179  if (GenerateTownName(&townnameparts) &&
2180  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2181  return true;
2182  }
2183 
2184  /* If there are no towns at all and we are generating new game, bail out */
2185  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2186  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2187  }
2188 
2189  return false; // we are still without a town? we failed, simply
2190 }
2191 
2192 
2199 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2200 {
2201  uint dist = DistanceSquare(tile, t->xy);
2202 
2203  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2204 
2205  HouseZonesBits smallest = HZB_TOWN_EDGE;
2206  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2207  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2208  }
2209 
2210  return smallest;
2211 }
2212 
2223 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2224 {
2226 
2227  assert(cc.Succeeded());
2228 
2229  IncreaseBuildingCount(t, type);
2230  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2231  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2232 
2233  MarkTileDirtyByTile(tile);
2234 }
2235 
2236 
2247 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2248 {
2249  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2250 
2251  ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2252  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2253  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2254  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2255 
2256  if (!_generating_world) {
2257  ForAllStationsAroundTiles(TileArea(t, (size & BUILDING_2_TILES_X) ? 2 : 1, (size & BUILDING_2_TILES_Y) ? 2 : 1), [town](Station *st, TileIndex tile) {
2258  town->stations_near.insert(st);
2259  return true;
2260  });
2261  }
2262 }
2263 
2264 
2272 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2273 {
2274  /* cannot build on these slopes... */
2275  Slope slope = GetTileSlope(tile);
2276  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2277 
2278  /* at least one RoadTypes allow building the house here? */
2279  if (!RoadTypesAllowHouseHere(tile)) return false;
2280 
2281  /* building under a bridge? */
2282  if (IsBridgeAbove(tile)) return false;
2283 
2284  /* can we clear the land? */
2285  return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2286 }
2287 
2288 
2297 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2298 {
2299  if (!CanBuildHouseHere(tile, noslope)) return false;
2300 
2301  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2302  if (GetTileMaxZ(tile) != z) return false;
2303 
2304  return true;
2305 }
2306 
2307 
2316 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2317 {
2318  /* we need to check this tile too because we can be at different tile now */
2319  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2320 
2321  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2322  tile += TileOffsByDiagDir(d);
2323  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2324  }
2325 
2326  return true;
2327 }
2328 
2329 
2337 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2338 {
2339  /* Allow towns everywhere when we don't build roads */
2341 
2342  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2343 
2344  switch (t->layout) {
2345  case TL_2X2_GRID:
2346  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2347  break;
2348 
2349  case TL_3X3_GRID:
2350  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2351  break;
2352 
2353  default:
2354  break;
2355  }
2356 
2357  return true;
2358 }
2359 
2360 
2368 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2369 {
2370  /* Allow towns everywhere when we don't build roads */
2372 
2373  /* Compute relative position of tile. (Positive offsets are towards north) */
2374  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2375 
2376  switch (t->layout) {
2377  case TL_2X2_GRID:
2378  grid_pos.x %= 3;
2379  grid_pos.y %= 3;
2380  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2381  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2382  break;
2383 
2384  case TL_3X3_GRID:
2385  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2386  break;
2387 
2388  default:
2389  break;
2390  }
2391 
2392  return true;
2393 }
2394 
2395 
2405 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2406 {
2407  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2408 
2409  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2410  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2411 
2412  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2413  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2414  *tile = tile2;
2415  return true;
2416  }
2417 
2418  return false;
2419 }
2420 
2421 
2430 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2431 {
2432  TileIndex tile2 = *tile;
2433 
2434  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2435  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2436  *tile = tile2;
2437  return true;
2438  }
2439  if (d == DIAGDIR_END) break;
2440  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2441  }
2442 
2443  return false;
2444 }
2445 
2446 
2453 static bool BuildTownHouse(Town *t, TileIndex tile)
2454 {
2455  /* forbidden building here by town layout */
2456  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2457 
2458  /* no house allowed at all, bail out */
2459  if (!CanBuildHouseHere(tile, false)) return false;
2460 
2461  Slope slope = GetTileSlope(tile);
2462  int maxz = GetTileMaxZ(tile);
2463 
2464  /* Get the town zone type of the current tile, as well as the climate.
2465  * This will allow to easily compare with the specs of the new house to build */
2466  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2467 
2468  /* Above snow? */
2470  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2471 
2472  uint bitmask = (1 << rad) + (1 << (land + 12));
2473 
2474  /* bits 0-4 are used
2475  * bits 11-15 are used
2476  * bits 5-10 are not used. */
2477  HouseID houses[NUM_HOUSES];
2478  uint num = 0;
2479  uint probs[NUM_HOUSES];
2480  uint probability_max = 0;
2481 
2482  /* Generate a list of all possible houses that can be built. */
2483  for (uint i = 0; i < NUM_HOUSES; i++) {
2484  const HouseSpec *hs = HouseSpec::Get(i);
2485 
2486  /* Verify that the candidate house spec matches the current tile status */
2487  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2488 
2489  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2490  if (hs->class_id != HOUSE_NO_CLASS) {
2491  /* id_count is always <= class_count, so it doesn't need to be checked */
2492  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2493  } else {
2494  /* If the house has no class, check id_count instead */
2495  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2496  }
2497 
2498  /* Without NewHouses, all houses have probability '1' */
2499  uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2500  probability_max += cur_prob;
2501  probs[num] = cur_prob;
2502  houses[num++] = (HouseID)i;
2503  }
2504 
2505  TileIndex baseTile = tile;
2506 
2507  while (probability_max > 0) {
2508  /* Building a multitile building can change the location of tile.
2509  * The building would still be built partially on that tile, but
2510  * its northern tile would be elsewhere. However, if the callback
2511  * fails we would be basing further work from the changed tile.
2512  * So a next 1x1 tile building could be built on the wrong tile. */
2513  tile = baseTile;
2514 
2515  uint r = RandomRange(probability_max);
2516  uint i;
2517  for (i = 0; i < num; i++) {
2518  if (probs[i] > r) break;
2519  r -= probs[i];
2520  }
2521 
2522  HouseID house = houses[i];
2523  probability_max -= probs[i];
2524 
2525  /* remove tested house from the set */
2526  num--;
2527  houses[i] = houses[num];
2528  probs[i] = probs[num];
2529 
2530  const HouseSpec *hs = HouseSpec::Get(house);
2531 
2533  _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2534  continue;
2535  }
2536 
2537  if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2538 
2539  /* Special houses that there can be only one of. */
2540  uint oneof = 0;
2541 
2542  if (hs->building_flags & BUILDING_IS_CHURCH) {
2543  SetBit(oneof, TOWN_HAS_CHURCH);
2544  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2545  SetBit(oneof, TOWN_HAS_STADIUM);
2546  }
2547 
2548  if (t->flags & oneof) continue;
2549 
2550  /* Make sure there is no slope? */
2551  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2552  if (noslope && slope != SLOPE_FLAT) continue;
2553 
2554  if (hs->building_flags & TILE_SIZE_2x2) {
2555  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2556  } else if (hs->building_flags & TILE_SIZE_2x1) {
2557  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2558  } else if (hs->building_flags & TILE_SIZE_1x2) {
2559  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2560  } else {
2561  /* 1x1 house checks are already done */
2562  }
2563 
2564  byte random_bits = Random();
2565 
2567  uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2568  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2569  }
2570 
2571  /* build the house */
2572  t->cache.num_houses++;
2573 
2574  /* Special houses that there can be only one of. */
2575  t->flags |= oneof;
2576 
2577  byte construction_counter = 0;
2578  byte construction_stage = 0;
2579 
2580  if (_generating_world || _game_mode == GM_EDITOR) {
2581  uint32 r = Random();
2582 
2583  construction_stage = TOWN_HOUSE_COMPLETED;
2584  if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2585 
2586  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2587  ChangePopulation(t, hs->population);
2588  } else {
2589  construction_counter = GB(r, 2, 2);
2590  }
2591  }
2592 
2593  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2594  UpdateTownRadius(t);
2596  UpdateTownCargoes(t, tile);
2597 
2598  return true;
2599  }
2600 
2601  return false;
2602 }
2603 
2610 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2611 {
2612  assert(IsTileType(tile, MP_HOUSE));
2613  DecreaseBuildingCount(t, house);
2614  DoClearSquare(tile);
2615  DeleteAnimatedTile(tile);
2616 
2617  DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2618 }
2619 
2628 {
2629  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2630  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2631  house--;
2632  return TileDiffXY(-1, 0);
2633  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2634  house--;
2635  return TileDiffXY(0, -1);
2636  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2637  house -= 2;
2638  return TileDiffXY(-1, 0);
2639  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2640  house -= 3;
2641  return TileDiffXY(-1, -1);
2642  }
2643  }
2644  return 0;
2645 }
2646 
2647 void ClearTownHouse(Town *t, TileIndex tile)
2648 {
2649  assert(IsTileType(tile, MP_HOUSE));
2650 
2651  HouseID house = GetHouseType(tile);
2652 
2653  /* need to align the tile to point to the upper left corner of the house */
2654  tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2655 
2656  const HouseSpec *hs = HouseSpec::Get(house);
2657 
2658  /* Remove population from the town if the house is finished. */
2659  if (IsHouseCompleted(tile)) {
2660  ChangePopulation(t, -hs->population);
2661  }
2662 
2663  t->cache.num_houses--;
2664 
2665  /* Clear flags for houses that only may exist once/town. */
2666  if (hs->building_flags & BUILDING_IS_CHURCH) {
2668  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2670  }
2671 
2672  /* Do the actual clearing of tiles */
2673  DoClearTownHouseHelper(tile, t, house);
2674  if (hs->building_flags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2675  if (hs->building_flags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2676  if (hs->building_flags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2677 
2678  RemoveNearbyStations(t, tile, hs->building_flags);
2679 
2680  UpdateTownRadius(t);
2681 
2682  /* Update cargo acceptance. */
2683  UpdateTownCargoes(t, tile);
2684 }
2685 
2695 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2696 {
2697  Town *t = Town::GetIfValid(p1);
2698  if (t == nullptr) return CMD_ERROR;
2699 
2700  bool reset = StrEmpty(text);
2701 
2702  if (!reset) {
2704  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2705  }
2706 
2707  if (flags & DC_EXEC) {
2708  t->cached_name.clear();
2709  free(t->name);
2710  t->name = reset ? nullptr : stredup(text);
2711 
2712  t->UpdateVirtCoord();
2713  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_RESORT);
2714  ClearAllStationCachedNames();
2715  ClearAllIndustryCachedNames();
2717  }
2718  return CommandCost();
2719 }
2720 
2727 {
2728  const CargoSpec *cs;
2729  FOR_ALL_CARGOSPECS(cs) {
2730  if (cs->town_effect == effect) return cs;
2731  }
2732  return nullptr;
2733 }
2734 
2746 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2747 {
2748  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2749 
2750  TownEffect te = (TownEffect)GB(p1, 16, 8);
2751  if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2752 
2753  uint16 index = GB(p1, 0, 16);
2754  Town *t = Town::GetIfValid(index);
2755  if (t == nullptr) return CMD_ERROR;
2756 
2757  /* Validate if there is a cargo which is the requested TownEffect */
2758  const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2759  if (cargo == nullptr) return CMD_ERROR;
2760 
2761  if (flags & DC_EXEC) {
2762  t->goal[te] = p2;
2763  UpdateTownGrowth(t);
2765  }
2766 
2767  return CommandCost();
2768 }
2769 
2779 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2780 {
2781  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2782  Town *t = Town::GetIfValid(p1);
2783  if (t == nullptr) return CMD_ERROR;
2784 
2785  if (flags & DC_EXEC) {
2786  free(t->text);
2787  t->text = StrEmpty(text) ? nullptr : stredup(text);
2789  }
2790 
2791  return CommandCost();
2792 }
2793 
2803 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2804 {
2805  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2806  if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2807 
2808  Town *t = Town::GetIfValid(p1);
2809  if (t == nullptr) return CMD_ERROR;
2810 
2811  if (flags & DC_EXEC) {
2812  if (p2 == 0) {
2813  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
2815  } else {
2816  uint old_rate = t->growth_rate;
2817  if (t->grow_counter >= old_rate) {
2818  /* This also catches old_rate == 0 */
2819  t->grow_counter = p2;
2820  } else {
2821  /* Scale grow_counter, so half finished houses stay half finished */
2822  t->grow_counter = t->grow_counter * p2 / old_rate;
2823  }
2824  t->growth_rate = p2;
2826  }
2827  UpdateTownGrowth(t);
2829  }
2830 
2831  return CommandCost();
2832 }
2833 
2843 CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2844 {
2845  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2846 
2847  TownID town_id = (TownID)GB(p1, 0, 16);
2848  Town *t = Town::GetIfValid(town_id);
2849  if (t == nullptr) return CMD_ERROR;
2850 
2851  CompanyID company_id = (CompanyID)GB(p1, 16, 8);
2852  if (!Company::IsValidID(company_id)) return CMD_ERROR;
2853 
2854  int16 new_rating = Clamp((int16)GB(p2, 0, 16), RATING_MINIMUM, RATING_MAXIMUM);
2855  if (flags & DC_EXEC) {
2856  t->ratings[company_id] = new_rating;
2858  }
2859 
2860  return CommandCost();
2861 }
2862 
2872 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2873 {
2874  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2875  Town *t = Town::GetIfValid(p1);
2876  if (t == nullptr) return CMD_ERROR;
2877 
2878  if (flags & DC_EXEC) {
2879  /* The more houses, the faster we grow */
2880  if (p2 == 0) {
2881  uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2882  t->cache.num_houses += amount;
2883  UpdateTownRadius(t);
2884 
2885  uint n = amount * 10;
2886  do GrowTown(t); while (--n);
2887 
2888  t->cache.num_houses -= amount;
2889  } else {
2890  for (; p2 > 0; p2--) {
2891  /* Try several times to grow, as we are really suppose to grow */
2892  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2893  }
2894  }
2895  UpdateTownRadius(t);
2896 
2897  UpdateTownMaxPass(t);
2898  }
2899 
2900  return CommandCost();
2901 }
2902 
2912 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2913 {
2914  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2915  Town *t = Town::GetIfValid(p1);
2916  if (t == nullptr) return CMD_ERROR;
2917 
2918  /* Stations refer to towns. */
2919  for (const Station *st : Station::Iterate()) {
2920  if (st->town == t) {
2921  /* Non-oil rig stations are always a problem. */
2922  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2923  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2924  CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2925  if (ret.Failed()) return ret;
2926  }
2927  }
2928 
2929  /* Depots refer to towns. */
2930  for (const Depot *d : Depot::Iterate()) {
2931  if (d->town == t) return CMD_ERROR;
2932  }
2933 
2934  /* Check all tiles for town ownership. First check for bridge tiles, as
2935  * these do not directly have an owner so we need to check adjacent
2936  * tiles. This won't work correctly in the same loop if the adjacent
2937  * tile was already deleted earlier in the loop. */
2938  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2939  if (IsTileType(tile, MP_TUNNELBRIDGE) && TestTownOwnsBridge(tile, t)) {
2940  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2941  if (ret.Failed()) return ret;
2942  }
2943  }
2944 
2945  /* Check all remaining tiles for town ownership. */
2946  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2947  bool try_clear = false;
2948  switch (GetTileType(tile)) {
2949  case MP_ROAD:
2950  try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2951  break;
2952 
2953  case MP_HOUSE:
2954  try_clear = GetTownIndex(tile) == t->index;
2955  break;
2956 
2957  case MP_INDUSTRY:
2958  try_clear = Industry::GetByTile(tile)->town == t;
2959  break;
2960 
2961  case MP_OBJECT:
2962  if (Town::GetNumItems() == 1) {
2963  /* No towns will be left, remove it! */
2964  try_clear = true;
2965  } else {
2966  Object *o = Object::GetByTile(tile);
2967  if (o->town == t) {
2968  if (o->type == OBJECT_STATUE) {
2969  /* Statue... always remove. */
2970  try_clear = true;
2971  } else {
2972  /* Tell to find a new town. */
2973  if (flags & DC_EXEC) o->town = nullptr;
2974  }
2975  }
2976  }
2977  break;
2978 
2979  default:
2980  break;
2981  }
2982  if (try_clear) {
2983  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2984  if (ret.Failed()) return ret;
2985  }
2986  }
2987 
2988  /* The town destructor will delete the other things related to the town. */
2989  if (flags & DC_EXEC) {
2990  _town_kdtree.Remove(t->index);
2991  if (t->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
2992  delete t;
2993  }
2994 
2995  return CommandCost();
2996 }
2997 
3003  2, 4, 9, 35, 48, 53, 117, 175
3004 };
3005 
3006 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
3007 {
3008  if (flags & DC_EXEC) {
3009  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
3010  }
3011  return CommandCost();
3012 }
3013 
3014 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
3015 {
3016  if (flags & DC_EXEC) {
3017  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
3018  }
3019  return CommandCost();
3020 }
3021 
3022 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
3023 {
3024  if (flags & DC_EXEC) {
3025  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
3026  }
3027  return CommandCost();
3028 }
3029 
3030 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
3031 {
3032  /* Check if the company is allowed to fund new roads. */
3034 
3035  if (flags & DC_EXEC) {
3036  t->road_build_months = 6;
3037 
3038  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
3040  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
3041 
3042  char *cn = stredup(company_name);
3043  SetDParam(0, t->index);
3044  SetDParamStr(1, cn);
3045 
3046  AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
3047  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3048  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3049  }
3050  return CommandCost();
3051 }
3052 
3058 static bool TryClearTile(TileIndex tile)
3059 {
3060  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3062  cur_company.Restore();
3063  return r.Succeeded();
3064 }
3065 
3070 
3071  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
3072 };
3073 
3080 static bool SearchTileForStatue(TileIndex tile, void *user_data)
3081 {
3082  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3083 
3084  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
3085  statue_data->tile_count++;
3086 
3087  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3088  if (IsSteepSlope(GetTileSlope(tile))) return false;
3089  /* Don't build statues under bridges. */
3090  if (IsBridgeAbove(tile)) return false;
3091 
3092  /* A clear-able open space is always preferred. */
3093  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
3094  statue_data->best_position = tile;
3095  return true;
3096  }
3097 
3098  bool house = IsTileType(tile, MP_HOUSE);
3099 
3100  /* Searching inside the inner circle. */
3101  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
3102  /* Save first house in inner circle. */
3103  if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
3104  statue_data->best_position = tile;
3105  }
3106 
3107  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3108  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
3109  }
3110 
3111  /* Searching outside the circle, just pick the first possible spot. */
3112  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
3113  return house && TryClearTile(tile);
3114 }
3115 
3124 {
3125  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
3126 
3127  TileIndex tile = t->xy;
3128  StatueBuildSearchData statue_data(INVALID_TILE, 0);
3129  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3130 
3131  if (flags & DC_EXEC) {
3132  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3133  DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
3134  cur_company.Restore();
3136  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
3137  MarkTileDirtyByTile(statue_data.best_position);
3138  }
3139  return CommandCost();
3140 }
3141 
3142 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
3143 {
3144  /* Check if it's allowed to buy the rights */
3146 
3147  if (flags & DC_EXEC) {
3148  /* And grow for 3 months */
3149  t->fund_buildings_months = 3;
3150 
3151  /* Enable growth (also checking GameScript's opinion) */
3152  UpdateTownGrowth(t);
3153 
3154  /* Build a new house, but add a small delay to make sure
3155  * that spamming funding doesn't let town grow any faster
3156  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3157  * Also emulate original behaviour when town was only growing in
3158  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3159  * tick-perfect and gives player some time window where he can
3160  * spam funding with the exact same efficiency.
3161  */
3163 
3165  }
3166  return CommandCost();
3167 }
3168 
3169 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
3170 {
3171  /* Check if it's allowed to buy the rights */
3173 
3174  if (flags & DC_EXEC) {
3175  t->exclusive_counter = 12;
3177 
3178  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3179 
3181 
3182  /* Spawn news message */
3183  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
3185  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3186  SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
3187  SetDParam(2, t->index);
3188  SetDParamStr(3, cni->company_name);
3189  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3190  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3191  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3192  }
3193  return CommandCost();
3194 }
3195 
3196 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
3197 {
3198  if (flags & DC_EXEC) {
3199  if (Chance16(1, 14)) {
3200  /* set as unwanted for 6 months */
3201  t->unwanted[_current_company] = 6;
3202 
3203  /* set all close by station ratings to 0 */
3204  for (Station *st : Station::Iterate()) {
3205  if (st->town == t && st->owner == _current_company) {
3206  for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
3207  }
3208  }
3209 
3210  /* only show error message to the executing player. All errors are handled command.c
3211  * but this is special, because it can only 'fail' on a DC_EXEC */
3212  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3213 
3214  /* decrease by a lot!
3215  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3216  * be independent of any cheat settings
3217  */
3218  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3219  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3221  }
3222  } else {
3223  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3224  }
3225  }
3226  return CommandCost();
3227 }
3228 
3229 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3230 static TownActionProc * const _town_action_proc[] = {
3231  TownActionAdvertiseSmall,
3232  TownActionAdvertiseMedium,
3233  TownActionAdvertiseLarge,
3234  TownActionRoadRebuild,
3236  TownActionFundBuildings,
3237  TownActionBuyRights,
3238  TownActionBribe
3239 };
3240 
3248 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3249 {
3250  int num = 0;
3251  TownActions buttons = TACT_NONE;
3252 
3253  /* Spectators and unwanted have no options */
3254  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3255 
3256  /* Things worth more than this are not shown */
3257  Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3258 
3259  /* Check the action bits for validity and
3260  * if they are valid add them */
3261  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3262  const TownActions cur = (TownActions)(1 << i);
3263 
3264  /* Is the company not able to bribe ? */
3265  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3266 
3267  /* Is the company not able to buy exclusive rights ? */
3268  if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3269 
3270  /* Is the company not able to fund buildings ? */
3271  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3272 
3273  /* Is the company not able to fund local road reconstruction? */
3274  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3275 
3276  /* Is the company not able to build a statue ? */
3277  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3278 
3279  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3280  buttons |= cur;
3281  num++;
3282  }
3283  }
3284  }
3285 
3286  if (nump != nullptr) *nump = num;
3287  return buttons;
3288 }
3289 
3301 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3302 {
3303  Town *t = Town::GetIfValid(p1);
3304  if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3305 
3306  if (!HasBit(GetMaskOfTownActions(nullptr, _current_company, t), p2)) return CMD_ERROR;
3307 
3308  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3309 
3310  CommandCost ret = _town_action_proc[p2](t, flags);
3311  if (ret.Failed()) return ret;
3312 
3313  if (flags & DC_EXEC) {
3315  }
3316 
3317  return cost;
3318 }
3319 
3320 template <typename Func>
3321 static void ForAllStationsNearTown(Town *t, Func func)
3322 {
3323  /* Ideally the search radius should be close to the actual town zone 0 radius.
3324  * The true radius is not stored or calculated anywhere, only the squared radius. */
3325  /* The efficiency of this search might be improved for large towns and many stations on the map,
3326  * by using an integer square root approximation giving a value not less than the true square root. */
3327  uint search_radius = t->cache.squared_town_zone_radius[0] / 2;
3328  ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3329  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3330  func(st);
3331  }
3332  });
3333 }
3334 
3335 static void UpdateTownRating(Town *t)
3336 {
3337  /* Increase company ratings if they're low */
3338  for (const Company *c : Company::Iterate()) {
3339  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3340  t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3341  }
3342  }
3343 
3344  ForAllStationsNearTown(t, [&](const Station *st) {
3345  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3346  if (Company::IsValidID(st->owner)) {
3347  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3348  t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3349  }
3350  } else {
3351  if (Company::IsValidID(st->owner)) {
3352  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3353  t->ratings[st->owner] = max(new_rating, INT16_MIN);
3354  }
3355  }
3356  });
3357 
3358  /* clamp all ratings to valid values */
3359  for (uint i = 0; i < MAX_COMPANIES; i++) {
3360  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3361  }
3362 
3364 }
3365 
3366 
3373 static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
3374 {
3375  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3376  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3378  return;
3379  }
3380  t->grow_counter = RoundDivSU((uint32)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3381 }
3382 
3389 {
3390  int n = 0;
3391  ForAllStationsNearTown(t, [&](const Station * st) {
3392  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3393  n++;
3394  }
3395  });
3396  return n;
3397 }
3398 
3405 static uint GetNormalGrowthRate(Town *t)
3406 {
3412  static const uint16 _grow_count_values[2][6] = {
3413  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3414  { 320, 420, 300, 220, 160, 100 } // Normal values
3415  };
3416 
3417  int n = CountActiveStations(t);
3418  uint16 m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][min(n, 5)];
3419 
3420  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3421 
3422  m >>= growth_multiplier;
3423  if (t->larger_town) m /= 2;
3424 
3425  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3426 }
3427 
3433 {
3434  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3435  uint old_rate = t->growth_rate;
3437  UpdateTownGrowCounter(t, old_rate);
3439 }
3440 
3445 static void UpdateTownGrowth(Town *t)
3446 {
3448 
3451 
3452  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3453 
3454  if (t->fund_buildings_months == 0) {
3455  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3456  for (int i = TE_BEGIN; i < TE_END; i++) {
3457  switch (t->goal[i]) {
3458  case TOWN_GROWTH_WINTER:
3459  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3460  break;
3461  case TOWN_GROWTH_DESERT:
3462  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3463  break;
3464  default:
3465  if (t->goal[i] > t->received[i].old_act) return;
3466  break;
3467  }
3468  }
3469  }
3470 
3471  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3474  return;
3475  }
3476 
3477  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3478 
3481 }
3482 
3483 static void UpdateTownAmounts(Town *t)
3484 {
3485  for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3486  for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3487  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3488 
3490 }
3491 
3492 static void UpdateTownUnwanted(Town *t)
3493 {
3494  for (const Company *c : Company::Iterate()) {
3495  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3496  }
3497 }
3498 
3506 {
3508 
3510  if (t == nullptr) return CommandCost();
3511 
3512  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3513 
3514  SetDParam(0, t->index);
3515  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3516 }
3517 
3527 {
3528  if (Town::GetNumItems() == 0) return nullptr;
3529 
3530  TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
3531  Town *town = Town::Get(tid);
3532  if (DistanceManhattan(tile, town->xy) < threshold) return town;
3533  return nullptr;
3534 }
3535 
3544 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3545 {
3546  switch (GetTileType(tile)) {
3547  case MP_ROAD:
3548  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3549 
3550  if (!HasTownOwnedRoad(tile)) {
3551  TownID tid = GetTownIndex(tile);
3552 
3553  if (tid == INVALID_TOWN) {
3554  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3555  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3556  assert(Town::GetNumItems() == 0);
3557  return nullptr;
3558  }
3559 
3560  assert(Town::IsValidID(tid));
3561  Town *town = Town::Get(tid);
3562 
3563  if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3564 
3565  return town;
3566  }
3567  FALLTHROUGH;
3568 
3569  case MP_HOUSE:
3570  return Town::GetByTile(tile);
3571 
3572  default:
3573  return CalcClosestTownFromTile(tile, threshold);
3574  }
3575 }
3576 
3577 static bool _town_rating_test = false;
3579 
3585 void SetTownRatingTestMode(bool mode)
3586 {
3587  static int ref_count = 0; // Number of times test-mode is switched on.
3588  if (mode) {
3589  if (ref_count == 0) {
3590  _town_test_ratings.clear();
3591  }
3592  ref_count++;
3593  } else {
3594  assert(ref_count > 0);
3595  ref_count--;
3596  }
3597  _town_rating_test = !(ref_count == 0);
3598 }
3599 
3605 static int GetRating(const Town *t)
3606 {
3607  if (_town_rating_test) {
3608  SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3609  if (it != _town_test_ratings.End()) {
3610  return it->second;
3611  }
3612  }
3613  return t->ratings[_current_company];
3614 }
3615 
3624 {
3625  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3626  if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3628  (_cheats.magic_bulldozer.value && add < 0)) {
3629  return;
3630  }
3631 
3632  int rating = GetRating(t);
3633  if (add < 0) {
3634  if (rating > max) {
3635  rating += add;
3636  if (rating < max) rating = max;
3637  }
3638  } else {
3639  if (rating < max) {
3640  rating += add;
3641  if (rating > max) rating = max;
3642  }
3643  }
3644  if (_town_rating_test) {
3645  _town_test_ratings[t] = rating;
3646  } else {
3648  t->ratings[_current_company] = rating;
3650  }
3651 }
3652 
3661 {
3662  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3663  if (t == nullptr || !Company::IsValidID(_current_company) ||
3665  return CommandCost();
3666  }
3667 
3668  /* minimum rating needed to be allowed to remove stuff */
3669  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3670  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3674  };
3675 
3676  /* check if you're allowed to remove the road/bridge/tunnel
3677  * owned by a town no removal if rating is lower than ... depends now on
3678  * difficulty setting. Minimum town rating selected by difficulty level
3679  */
3680  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3681 
3682  if (GetRating(t) < needed) {
3683  SetDParam(0, t->index);
3684  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3685  }
3686 
3687  return CommandCost();
3688 }
3689 
3690 void TownsMonthlyLoop()
3691 {
3692  for (Town *t : Town::Iterate()) {
3693  if (t->road_build_months != 0) t->road_build_months--;
3694 
3695  if (t->exclusive_counter != 0) {
3696  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3697  }
3698 
3699  UpdateTownAmounts(t);
3700  UpdateTownGrowth(t);
3701  UpdateTownRating(t);
3702  UpdateTownUnwanted(t);
3703  UpdateTownCargoes(t);
3704  }
3705 
3707 }
3708 
3709 void TownsYearlyLoop()
3710 {
3711  /* Increment house ages */
3712  for (TileIndex t = 0; t < MapSize(); t++) {
3713  if (!IsTileType(t, MP_HOUSE)) continue;
3714  IncrementHouseAge(t);
3715  }
3716 }
3717 
3718 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3719 {
3720  if (AutoslopeEnabled()) {
3721  HouseID house = GetHouseType(tile);
3722  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3723  const HouseSpec *hs = HouseSpec::Get(house);
3724 
3725  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3726  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3727  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3728  bool allow_terraform = true;
3729 
3730  /* Call the autosloping callback per tile, not for the whole building at once. */
3731  house = GetHouseType(tile);
3732  hs = HouseSpec::Get(house);
3734  /* If the callback fails, allow autoslope. */
3735  uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3736  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3737  }
3738 
3739  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3740  }
3741  }
3742 
3743  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3744 }
3745 
3747 extern const TileTypeProcs _tile_type_town_procs = {
3748  DrawTile_Town, // draw_tile_proc
3749  GetSlopePixelZ_Town, // get_slope_z_proc
3750  ClearTile_Town, // clear_tile_proc
3751  AddAcceptedCargo_Town, // add_accepted_cargo_proc
3752  GetTileDesc_Town, // get_tile_desc_proc
3753  GetTileTrackStatus_Town, // get_tile_track_status_proc
3754  nullptr, // click_tile_proc
3755  AnimateTile_Town, // animate_tile_proc
3756  TileLoop_Town, // tile_loop_proc
3757  ChangeTileOwner_Town, // change_tile_owner_proc
3758  AddProducedCargo_Town, // add_produced_cargo_proc
3759  nullptr, // vehicle_enter_tile_proc
3760  GetFoundation_Town, // get_foundation_proc
3761  TerraformTile_Town, // terraform_tile_proc
3762 };
3763 
3764 
3765 HouseSpec _house_specs[NUM_HOUSES];
3766 
3767 void ResetHouses()
3768 {
3769  memset(&_house_specs, 0, sizeof(_house_specs));
3770  memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3771 
3772  /* Reset any overrides that have been set. */
3773  _house_mngr.ResetOverride();
3774 }
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:111
Functions related to OTTD&#39;s strings.
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
Owner
Enum for all companies/owners.
Definition: company_type.h:18
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:34
don&#39;t allow building on structures
Definition: command_type.h:347
Functions/types related to NewGRF debugging.
AcceptanceMatrix cargo_accepted
Bitmap of cargoes accepted by houses for each 4*4 map square of the town.
Definition: town.h:88
the north corner of the tile is raised
Definition: slope_type.h:53
do not change town rating
Definition: command_type.h:356
uint16 custom_town_number
manually entered number of towns
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:435
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
Source/destination is a town.
Definition: cargo_type.h:148
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
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:167
There can be only one stadium by town.
Definition: town.h:190
static Year GetHouseAge(TileIndex t)
Get the age of the house.
Definition: town_map.h:249
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:117
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:141
static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total=true)
Update accepted town cargoes around a specific tile.
Definition: town_cmd.cpp:809
Definition of stuff that is very close to a company, like the company struct itself.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:340
static void ChangePopulation(Town *t, int mod)
Change the towns population.
Definition: town_cmd.cpp:434
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1823
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1121
Number of town layouts.
Definition: town_type.h:87
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1288
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:238
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
static TransportType GetTunnelBridgeTransportType(TileIndex t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile.
Definition: town_cmd.cpp:902
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:79
Geometric 2x2 grid algorithm.
Definition: town_type.h:82
static TileArea GetAreaForTile(TileIndex tile, uint extend=0)
Get the area of the matrix square that contains a specific tile.
Tile information, used while rendering the tile.
Definition: tile_cmd.h:42
bool bribe
enable bribing the local authority
static const byte TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:23
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
CompanyMask statues
which companies have a statue?
Definition: town.h:69
south and east corner are raised
Definition: slope_type.h:57
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1183
bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:82
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:168
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:2147
the west corner of the tile is raised
Definition: slope_type.h:50
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3218
byte landscape
the landscape we&#39;re currently in
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet)...
decides accepted types
Tile is desert.
Definition: tile_type.h:71
Sprites to use and how to display them for town tiles.
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:2223
TownLayout layout
tells us what kind of town we&#39;re building
Definition: town_cmd.cpp:2022
Part of an industry.
Definition: tile_type.h:49
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
EconomySettings economy
settings to change the economy
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:48
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:154
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
Money GetAvailableMoneyForCommand()
Definition: command.cpp:523
Declarations for accessing the k-d tree of towns.
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if current town layout allows 2x2 building here.
Definition: town_cmd.cpp:2368
Functions related to dates.
Town * town
Town the object is built in.
Definition: object_base.h:25
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:61
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:97
Northwest.
Basic road type.
Definition: road_type.h:24
Random town layout.
Definition: town_type.h:85
West.
Called to determine if one can alter the ground below a house tile.
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if current town layout allows building here.
Definition: town_cmd.cpp:2337
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:63
Town * town
Nearest town.
Definition: industry.h:42
static bool HasTileRoadType(TileIndex t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:210
Used for iterations.
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:3068
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:415
byte flags
See TownFlags.
Definition: town.h:65
terraform a tile
Definition: command_type.h:186
uint8 unwanted[MAX_COMPANIES]
how many months companies aren&#39;t wanted by towns (bribe)
Definition: town.h:73
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:124
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3445
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3577
A tile with road (or tram tracks)
Definition: tile_type.h:43
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:23
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:45
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
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
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:56
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
Functions used internally by the roads.
no flag is set
Definition: command_type.h:345
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
CargoTypes cargo_produced
Bitmap of all cargoes produced by houses in this town.
Definition: town.h:87
Used for iterations.
Definition: road_type.h:26
Specification of a cargo type.
Definition: cargotype.h:55
std::vector< Pair >::const_iterator Find(const T &key) const
Finds given key in this map.
Road specific functions.
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
Definition: town_cmd.cpp:3432
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:386
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition: station.cpp:394
bool population_in_label
show the population of a town in his label?
Implementation of simple mapping class.
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
bool GenerateTownName(uint32 *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:119
static bool HasTileWaterGround(TileIndex t)
Checks whether the tile has water at the ground.
Definition: water_map.h:344
TownLayout
Town Layouts.
Definition: town_type.h:78
Build a statue.
Definition: town.h:226
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
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
South-west part.
Definition: road_type.h:53
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:111
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:382
TownFounding found_town
town founding.
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
Base for all depots (except hangars)
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:27
Opening of industries.
Definition: news_type.h:26
Defines the internal data of a functional industry.
Definition: industry.h:40
static SmallMap< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3578
demolish a tile
Definition: command_type.h:180
Tile description for the &#39;land area information&#39; tool.
Definition: tile_cmd.h:51
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:259
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
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:2316
the east corner of the tile is raised
Definition: slope_type.h:52
flag for invalid roadtype
Definition: road_type.h:27
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:380
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:103
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
Declarations for accessing the k-d tree of stations.
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:92
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Do a town action.
Definition: town_cmd.cpp:3301
Helper functions to extract data from command parameters.
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
Cargo behaves water-like.
Definition: cargotype.h:30
build a "half" road
Definition: command_type.h:201
Other expenses.
Definition: economy_type.h:161
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:2019
void NewMonth()
Update stats for a new month.
Definition: town_type.h:121
TownLayout town_layout
select town layout,
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else) ...
Definition: town_cmd.cpp:397
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Definition: kdtree.hpp:444
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Data that needs to be stored for company news messages.
Definition: news_type.h:148
A railway.
Definition: tile_type.h:42
Called to determine which cargoes a town building should accept.
byte dist_local_authority
distance for town local authority, default 20
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Functions related to world/map generation.
initial rating
Definition: town_type.h:44
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:82
Contains objects such as transmitters and owned land.
Definition: tile_type.h:51
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2453
Construction costs.
Definition: economy_type.h:149
south and west corner are raised
Definition: slope_type.h:56
Common return value for all commands.
Definition: command_type.h:23
static bool LiftHasDestination(TileIndex t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:82
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:223
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:388
RoadType
The different roadtypes we support.
Definition: road_type.h:22
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
static bool IsDriveThroughStopTile(TileIndex t)
Is tile t a drive through road stop station?
Definition: station_map.h:233
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Town directory; Window numbers:
Definition: window_type.h:247
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
uint32 population
Current population of people.
Definition: town.h:45
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:25
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:73
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1615
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
decides amount of cargo acceptance
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:2080
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:148
a flat tile
Definition: slope_type.h:49
int z
Height.
Definition: tile_cmd.h:47
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:13
static byte GetLiftDestination(TileIndex t)
Get the current destination for this lift.
Definition: town_map.h:104
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:470
Forbidden.
Definition: town_type.h:94
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:62
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:53
static int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:336
North.
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:950
Rebuild the roads.
Definition: town.h:225
this house will only appear during town generation in random games, thus the historical ...
Definition: house.h:90
north and east corner are raised
Definition: slope_type.h:58
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2610
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:110
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
Called to determine the type (if any) of foundation to draw for house tile.
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:462
Functions related to (drawing on) viewports.
Pseudo random number generator.
char company_name[64]
The name of the company.
Definition: news_type.h:149
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
static byte GetHouseBuildingStage(TileIndex t)
House Construction Scheme.
Definition: town_map.h:183
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:80
Invalid cargo type.
Definition: cargo_type.h:68
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile.
Definition: town_cmd.cpp:3505
static bool IsHouseCompleted(TileIndex t)
Get the completion of this house.
Definition: town_map.h:145
int16 y
The y value of the coordinate.
Definition: map_type.h:59
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:2872
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:335
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:85
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:161
bool exclusive_rights
allow buying exclusive rights
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:264
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TownActions
Town actions of a company.
Definition: town.h:219
Bit number for setting this roadtype as not house friendly.
Definition: road.h:41
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:89
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:24
town buildings
Definition: transparency.h:25
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
static void DrawTile_Town(TileInfo *ti)
House Tile drawing handler.
Definition: town_cmd.cpp:256
static uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:334
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:2021
Base for all objects.
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1163
Header of Action 04 "universal holder" structure and functions.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:279
90 degrees right
static byte GetHouseConstructionTick(TileIndex t)
Gets the construction stage of a house.
Definition: town_map.h:195
Tile animation!
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:224
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:76
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:24
Functions related to low-level strings.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
static RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:96
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:18
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:43
None of the directions are disallowed.
Definition: road_map.h:286
The tile has no ownership.
Definition: company_type.h:25
Full 4-way crossing.
Definition: road_type.h:64
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:341
Called on the Get Tile Description for an house tile.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:96
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
Types related to cheating.
Bit number for allowing towns to build this roadtype.
Definition: road.h:43
TileIndex xy
town center tile
Definition: town.h:54
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:1748
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
Southeast.
static CommandCost TownCanBePlacedHere(TileIndex tile)
Checks if it&#39;s possible to place a town at given tile.
Definition: town_cmd.cpp:1829
TileIndex tile
Tile index.
Definition: tile_cmd.h:46
Functions related to errors.
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:2430
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:445
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:2297
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:3544
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
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:2405
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:246
TownSize
Supported initial town sizes.
Definition: town_type.h:19
The client is spectating.
Definition: company_type.h:35
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:350
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:119
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3623
Information about GRF, used in the game and (part of it) in savegames.
Original algorithm (quadratic cargo by population)
Definition: town_type.h:103
Simple pair of data.
static bool IsUniqueTownName(const char *name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:1854
size_t Count() const
Get number of elements stored in tree.
Definition: kdtree.hpp:433
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:76
Generate towns.
Definition: genworld.h:72
Fund new buildings.
Definition: town.h:227
static bool HasTownOwnedRoad(TileIndex t)
Checks if given tile has town owned road.
Definition: road_map.h:279
East.
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:22
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Functions related to NewGRF houses.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
custom cargo production
DoCommandFlag
List of flags for a command.
Definition: command_type.h:344
char * GetTownName(char *buff, const TownNameParams *par, uint32 townnameparts, const char *last)
Fills buffer with specified town name.
Definition: townname.cpp:49
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:150
rating needed, "Permissive" difficulty settings
Definition: town_type.h:66
General news (from towns)
Definition: news_type.h:36
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3405
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
#define TILE_AREA_LOOP(var, ta)
A loop which iterates over the tiles of a TileArea.
Definition of base types and functions in a cross-platform compatible way.
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:52
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:154
Road at the two southern edges.
Definition: road_type.h:61
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including &#39;\0&#39;.
Definition: company_type.h:40
Map accessors for object tiles.
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:258
A number of safeguards to prevent using unsafe methods.
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:90
Road at the two eastern edges.
Definition: road_type.h:60
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
int16 x
The x value of the coordinate.
Definition: map_type.h:58
Number of available town sizes.
Definition: town_type.h:25
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
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:182
Water tile.
Definition: tile_type.h:47
Allowed, with custom town layout.
Definition: town_type.h:96
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:44
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding roads allows to build a house here.
Definition: town_cmd.cpp:1247
static byte GetLiftPosition(TileIndex t)
Get the position of the lift on this animated house.
Definition: town_map.h:125
static bool IsRoadDepotTile(TileIndex t)
Return whether a tile is a road depot tile.
Definition: road_map.h:115
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:50
Geometric 3x3 grid algorithm.
Definition: town_type.h:83
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:49
An object, such as transmitter, on the map.
Definition: object_base.h:23
rating needed, "Permissive" difficulty settings
Definition: town_type.h:59
Bit-counted algorithm (normal distribution from individual house population)
Definition: town_type.h:104
Empty reference.
Definition: news_type.h:50
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
No road-part is build.
Definition: road_type.h:51
void UpdateTownCargoBitmap()
Updates the bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:858
bool fund_roads
allow funding local road reconstruction
Represents the covered area of e.g.
Definition: tilearea_type.h:16
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:136
delete a town
Definition: command_type.h:269
Number of available town actions.
Definition: town.h:231
CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the growth rate of the town.
Definition: town_cmd.cpp:2803
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:81
Normal news item. (Newspaper with text only)
Definition: news_type.h:78
decides allowance of autosloping
static DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
don&#39;t allow building on water
Definition: command_type.h:349
... up to RATING_MEDIOCRE
Definition: town_type.h:53
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:2041
uint16 max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:139
North-east part.
Definition: road_type.h:55
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
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:448
South.
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:114
This structure is the same for both Industries and Houses.
Definition: sprite.h:67
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:213
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1629
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:1938
static DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:58
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2627
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:3067
Station view; Window numbers:
Definition: window_type.h:338
StringID building_name
building name
Definition: house.h:104
const TileArea & GetArea() const
Get the total covered area.
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town &#39;owns&#39; a bridge.
Definition: town_cmd.cpp:86
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:2912
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
bit mask containing all &#39;simple&#39; slopes
Definition: slope_type.h:61
static uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:316
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:184
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:2843
CargoTypes _town_cargoes_accepted
Bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:58
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:469
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:47
void FillData(const struct Company *c, const struct Company *other=nullptr)
Fill the CompanyNewsInformation struct with the required data.
CargoTypes cargo_accepted_total
NOSAVE: Bitmap of all cargoes accepted by houses in this town.
Definition: town.h:89
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
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition: road.cpp:47
Functions related to autoslope.
Year max_year
last year it can be built
Definition: house.h:101
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
byte number_towns
the amount of towns
Definition: settings_type.h:55
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:217
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Returns "growth" if a house was built, or no if the build failed.
Definition: town_cmd.cpp:1533
bool build_on_slopes
allow building on slopes
bool Failed() const
Did this command fail?
Definition: command_type.h:159
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2199
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
a steep slope falling to east (from west)
Definition: slope_type.h:66
static Axis GetBridgeAxis(TileIndex t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
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:659
uint8 town_growth_rate
town growth rate
bool has_newhouses
Set if there are any newhouses loaded.
Definition: newgrf.h:177
Empty action set.
Definition: town.h:220
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:33
static void SetRoadOwner(TileIndex t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:250
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3526
Number of town checking action types.
Definition: town.h:170
Base class for all pools.
Definition: pool_type.hpp:81
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:137
North-west part.
Definition: road_type.h:52
static bool IsSea(TileIndex t)
Is it a sea water tile?
Definition: water_map.h:152
Company news item. (Newspaper with face)
Definition: news_type.h:80
Road related functions.
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:984
Determine whether the house can be built on the specified tile.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
South-east part.
Definition: road_type.h:54
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:3069
uint16 override
id of the entity been replaced by
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:17
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:29
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:62
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:340
A pair-construct of a TileIndexDiff.
Definition: map_type.h:57
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:224
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
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:2247
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
static void MakeTownHouseBigger(TileIndex tile)
Make the house advance in its construction stages until completion.
Definition: town_cmd.cpp:507
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Definition: map_func.h:230
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
char * text
General text with additional information.
Definition: town.h:82
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:29
execute the given command
Definition: command_type.h:346
Station with an airport.
Definition: station_type.h:55
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, the function returns the same as GetTileSlope.
Definition: landscape.cpp:422
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:308
static void MakeSingleHouseBigger(TileIndex tile)
Helper function for house completion stages progression.
Definition: town_cmd.cpp:484
CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2746
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:35
static Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:256
uint16 growth_rate
town growth rate
Definition: town.h:95
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:3123
static void HaltLift(TileIndex t)
Stop the lift of this animated house from moving.
Definition: town_map.h:115
An invalid company.
Definition: company_type.h:30
Tile got trees.
Definition: tile_type.h:45
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:1491
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
static uint MapSize()
Get the size of the map.
Definition: map_func.h:92
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:66
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Definition: cargo_type.h:81
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:60
Used for iterations.
Definition: road_type.h:23
TownLayout layout
town specific road layout
Definition: town.h:101
static bool IsNormalRoadTile(TileIndex t)
Return whether a tile is a normal road tile.
Definition: road_map.h:73
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:522
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
There can be only one church by town.
Definition: town.h:189
Town authority; Window numbers:
Definition: window_type.h:187
GUISettings gui
settings related to the GUI
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:50
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
HouseExtraFlags extra_flags
some more flags
Definition: house.h:118
Invisible tiles at the SW and SE border.
Definition: tile_type.h:48
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:55
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
Definition: kdtree.hpp:365
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:57
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
static void SetLiftPosition(TileIndex t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:135
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:310
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:117
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:145
Oilrig airport.
Definition: airport.h:38
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
Functions related to objects.
Used for iterations.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:157
Cargo support for NewGRFs.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3605
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:359
static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the nearest land tile.
Definition: town_cmd.cpp:2063
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:122
Buy exclusive transport rights.
Definition: town.h:228
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:105
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
north and west corner are raised
Definition: slope_type.h:55
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:420
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
Random size, bigger than small, smaller than large.
Definition: town_type.h:23
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:69
Date introduction_date
Introduction date.
Definition: road.h:163
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3660
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:34
TransportType
Available types of transport.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint8 initial_city_size
multiplier for the initial size of the cities compared to towns
ObjectType type
Type of the object.
Definition: object_base.h:24
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Checks if a house can be built here.
Definition: town_cmd.cpp:2272
Town view; Window numbers:
Definition: window_type.h:326
Growth rate is controlled by GS.
Definition: town.h:191
A tile of a station.
Definition: tile_type.h:46
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:3002
TownCache cache
Container for all cacheable data.
Definition: town.h:56
uint8 larger_towns
the number of cities to build. These start off larger and grow twice as fast
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
Maximum number of companies.
Definition: company_type.h:23
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:384
Town data structure.
Definition: town.h:53
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:1062
#define MAX_DAY
The number of days till the last day.
Definition: date_type.h:97
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:75
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
Transport by road vehicle.
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:36
Functions related to OTTD&#39;s landscape.
static void ResetHouseAge(TileIndex t)
Sets the age of the house to zero.
Definition: town_map.h:226
byte town_name
the town name generator used for town names
static uint CountBits(T value)
Counts the number of set bits in a variable.
Base functions for all Games.
End of town effects.
Definition: cargotype.h:32
Functions related to commands.
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:80
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:100
char * name
Custom town name. If nullptr, the town was not renamed and uses the generated name.
Definition: town.h:62
Coordinates of a point in 2D.
a steep slope falling to south (from north)
Definition: slope_type.h:69
Large town.
Definition: town_type.h:22
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
Struct holding parameters used to generate town name.
Definition: townname_type.h:27
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:575
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:46
Owner owner
The owner of this station.
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:644
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:318
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:29
decides if default foundations need to be drawn
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:50
build a bridge
Definition: command_type.h:181
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:31
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including &#39;\0&#39;.
Definition: town_type.h:108
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
static bool TryClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:3058
ConstructionSettings construction
construction of things in-game
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
Functions that have tunnels and bridges in common.
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:179
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1819
Base of all industries.
static DisallowedRoadDirections GetDisallowedRoadDirections(TileIndex t)
Gets the disallowed directions.
Definition: road_map.h:301
const char * GetName() const
Get the name of this grf.
static TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition: map_func.h:370
K-dimensional tree, specialised for 2-dimensional space.
Definition: kdtree.hpp:38
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:815
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:114
void ResetOverride()
Resets the override, which is used while initializing game.
const struct GRFFile * grffile
grf file that introduced this entity
StringID str
Description of the tile.
Definition: tile_cmd.h:52
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:21
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3248
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback routine.
Definition: town_cmd.cpp:311
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Town name generator stuff.
void Restore()
Restore the variable.
DiagDirection
Enumeration for diagonal directions.
Base functions for all AIs.
Try to bribe the council.
Definition: town.h:229
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:790
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:1989
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:83
Base of the town class.
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:2020
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3388
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:78
GameCreationSettings game_creation
settings used during the creation of a game (map)
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:41
int _nb_orig_names
Number of original town names.
A house by a town.
Definition: tile_type.h:44
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:57
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
bool fund_buildings
allow funding new buildings
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the &#39;Square&#39; distance between the two given tiles.
Definition: map.cpp:174
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:59
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:114
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town...
Window functions not directly related to making/drawing windows.
~Town()
Destroy the town.
Definition: town_cmd.cpp:102
Called to determine how much cargo a town building produces.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
uint32 num_houses
Amount of houses.
Definition: town.h:44
a steep slope falling to west (from east)
Definition: slope_type.h:68
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:81
void UpdateTownCargoTotal(Town *t)
Update the total cargo acceptance of the whole town.
Definition: town_cmd.cpp:791
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:188
town rating does not disallow you from building
Definition: command_type.h:351
decide whether the house can be built on a given tile
#define TILE_ADD(x, y)
Adds to tiles together.
Definition: map_func.h:244
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:23
Called to decide how much cargo a town building can accept.
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:3080
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3246
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
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
Functions related to news.
Structure contains cached list of stations nearby.
Definition: station_type.h:100
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:2779
byte road_build_months
fund road reconstruction in action?
Definition: town.h:98
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename a town (server-only).
Definition: town_cmd.cpp:2695
Base classes/functions for stations.
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:58
static void SetTownIndex(TileIndex t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:34
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Date _date
Current date in days (day counter)
Definition: date.cpp:27
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:401
90 degrees left
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
CompanyID exclusivity
which company has exclusivity
Definition: town.h:74
bool allow_town_level_crossings
towns are allowed to build level crossings
the south corner of the tile is raised
Definition: slope_type.h:51
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:94
The object is owned by a superuser / goal script.
Definition: company_type.h:27
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Class for backupping variables and making sure they are restored later.
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:213
Station data structure.
Definition: station_base.h:450
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:48
static bool IsRoadDepot(TileIndex t)
Return whether a tile is a road depot.
Definition: road_map.h:105
Functions related to subsidies.
CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Create a new town.
Definition: town_cmd.cpp:1875
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:2007
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:163
static TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:316
static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3373
static void IncrementHouseAge(TileIndex t)
Increments the age of the house.
Definition: town_map.h:237
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2726
a steep slope falling to north (from south)
Definition: slope_type.h:67
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
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
RoadTypeLabel label
Unique 32 bit road type identifier.
Definition: road.h:144
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
CompanyMask have_ratings
which companies have a rating
Definition: town.h:72
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:658
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1600
Southwest.
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
Road at the two northern edges.
Definition: road_type.h:59
Road at the two western edges.
Definition: road_type.h:62
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
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
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:3585