OpenTTD
town_cmd.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "road.h"
14 #include "road_internal.h" /* Cleaning up road bits */
15 #include "road_cmd.h"
16 #include "landscape.h"
17 #include "viewport_func.h"
18 #include "viewport_kdtree.h"
19 #include "cmd_helper.h"
20 #include "command_func.h"
21 #include "industry.h"
22 #include "station_base.h"
23 #include "station_kdtree.h"
24 #include "company_base.h"
25 #include "news_func.h"
26 #include "error.h"
27 #include "object.h"
28 #include "genworld.h"
29 #include "newgrf_debug.h"
30 #include "newgrf_house.h"
31 #include "newgrf_text.h"
32 #include "autoslope.h"
33 #include "tunnelbridge_map.h"
34 #include "strings_func.h"
35 #include "window_func.h"
36 #include "string_func.h"
37 #include "newgrf_cargo.h"
38 #include "cheat_type.h"
39 #include "animated_tile_func.h"
40 #include "date_func.h"
41 #include "subsidy_func.h"
42 #include "core/pool_func.hpp"
43 #include "town.h"
44 #include "town_kdtree.h"
45 #include "townname_func.h"
46 #include "core/random_func.hpp"
47 #include "core/backup_type.hpp"
48 #include "depot_base.h"
49 #include "object_map.h"
50 #include "object_base.h"
51 #include "ai/ai.hpp"
52 #include "game/game.hpp"
53 
54 #include "table/strings.h"
55 #include "table/town_land.h"
56 
57 #include "safeguards.h"
58 
59 TownID _new_town_id;
61 
62 /* Initialize the town-pool */
63 TownPool _town_pool("Town");
65 
66 
67 TownKdtree _town_kdtree(&Kdtree_TownXYFunc);
68 
69 void RebuildTownKdtree()
70 {
71  std::vector<TownID> townids;
72  Town *town;
73  FOR_ALL_TOWNS(town) {
74  townids.push_back(town->index);
75  }
76  _town_kdtree.Build(townids.begin(), townids.end());
77 }
78 
79 
89 static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
90 {
91  if (!IsTileOwner(tile, OWNER_TOWN)) return false;
92 
94  bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
95 
96  if (!town_owned) {
97  /* Or other adjacent road */
99  town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
100  }
101 
102  return town_owned;
103 }
104 
106 {
107  free(this->name);
108  free(this->text);
109 
110  if (CleaningPool()) return;
111 
112  /* Delete town authority window
113  * and remove from list of sorted towns */
115 
116  /* Check no industry is related to us. */
117  const Industry *i;
118  FOR_ALL_INDUSTRIES(i) assert(i->town != this);
119 
120  /* ... and no object is related to us. */
121  const Object *o;
122  FOR_ALL_OBJECTS(o) assert(o->town != this);
123 
124  /* Check no tile is related to us. */
125  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
126  switch (GetTileType(tile)) {
127  case MP_HOUSE:
128  assert(GetTownIndex(tile) != this->index);
129  break;
130 
131  case MP_ROAD:
132  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
133  break;
134 
135  case MP_TUNNELBRIDGE:
136  assert(!TestTownOwnsBridge(tile, this));
137  break;
138 
139  default:
140  break;
141  }
142  }
143 
144  /* Clear the persistent storage list. */
145  this->psa_list.clear();
146 
151 }
152 
153 
160 {
163 
164  /* Give objects a new home! */
165  Object *o;
166  FOR_ALL_OBJECTS(o) {
167  if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
168  }
169 }
170 
175 {
176  if (layout != TL_RANDOM) {
177  this->layout = layout;
178  return;
179  }
180 
181  this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
182 }
183 
188 /* static */ Town *Town::GetRandom()
189 {
190  if (Town::GetNumItems() == 0) return nullptr;
191  int num = RandomRange((uint16)Town::GetNumItems());
192  size_t index = MAX_UVALUE(size_t);
193 
194  while (num >= 0) {
195  num--;
196  index++;
197 
198  /* Make sure we have a valid town */
199  while (!Town::IsValidID(index)) {
200  index++;
201  assert(index < Town::GetPoolSize());
202  }
203  }
204 
205  return Town::Get(index);
206 }
207 
213 {
214  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
215 }
216 
217 /* Local */
218 static int _grow_town_result;
219 
220 /* Describe the possible states */
221 enum TownGrowthResult {
222  GROWTH_SUCCEED = -1,
223  GROWTH_SEARCH_STOPPED = 0
224 // GROWTH_SEARCH_RUNNING >= 1
225 };
226 
227 static bool BuildTownHouse(Town *t, TileIndex tile);
228 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
229 
230 static void TownDrawHouseLift(const TileInfo *ti)
231 {
232  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
233 }
234 
235 typedef void TownDrawTileProc(const TileInfo *ti);
236 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
237  TownDrawHouseLift
238 };
239 
246 {
247  return (DiagDirection)(3 & Random());
248 }
249 
255 static void DrawTile_Town(TileInfo *ti)
256 {
257  HouseID house_id = GetHouseType(ti->tile);
258 
259  if (house_id >= NEW_HOUSE_OFFSET) {
260  /* Houses don't necessarily need new graphics. If they don't have a
261  * spritegroup associated with them, then the sprite for the substitute
262  * house id is drawn instead. */
263  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
264  DrawNewHouseTile(ti, house_id);
265  return;
266  } else {
267  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
268  }
269  }
270 
271  /* Retrieve pointer to the draw town tile struct */
272  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
273 
275 
276  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
277 
278  /* If houses are invisible, do not draw the upper part */
279  if (IsInvisibilitySet(TO_HOUSES)) return;
280 
281  /* Add a house on top of the ground? */
282  SpriteID image = dcts->building.sprite;
283  if (image != 0) {
284  AddSortableSpriteToDraw(image, dcts->building.pal,
285  ti->x + dcts->subtile_x,
286  ti->y + dcts->subtile_y,
287  dcts->width,
288  dcts->height,
289  dcts->dz,
290  ti->z,
292  );
293 
294  if (IsTransparencySet(TO_HOUSES)) return;
295  }
296 
297  {
298  int proc = dcts->draw_proc - 1;
299 
300  if (proc >= 0) _town_draw_tile_procs[proc](ti);
301  }
302 }
303 
304 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
305 {
306  return GetTileMaxPixelZ(tile);
307 }
308 
311 {
312  HouseID hid = GetHouseType(tile);
313 
314  /* For NewGRF house tiles we might not be drawing a foundation. We need to
315  * account for this, as other structures should
316  * draw the wall of the foundation in this case.
317  */
318  if (hid >= NEW_HOUSE_OFFSET) {
319  const HouseSpec *hs = HouseSpec::Get(hid);
320  if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
321  uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
322  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
323  }
324  }
325  return FlatteningFoundation(tileh);
326 }
327 
334 static void AnimateTile_Town(TileIndex tile)
335 {
336  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
337  AnimateNewHouseTile(tile);
338  return;
339  }
340 
341  if (_tick_counter & 3) return;
342 
343  /* If the house is not one with a lift anymore, then stop this animating.
344  * Not exactly sure when this happens, but probably when a house changes.
345  * Before this was just a return...so it'd leak animated tiles..
346  * That bug seems to have been here since day 1?? */
347  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
348  DeleteAnimatedTile(tile);
349  return;
350  }
351 
352  if (!LiftHasDestination(tile)) {
353  uint i;
354 
355  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
356  * This is due to the fact that the first floor is, in the graphics,
357  * the height of 2 'normal' floors.
358  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
359  do {
360  i = RandomRange(7);
361  } while (i == 1 || i * 6 == GetLiftPosition(tile));
362 
363  SetLiftDestination(tile, i);
364  }
365 
366  int pos = GetLiftPosition(tile);
367  int dest = GetLiftDestination(tile) * 6;
368  pos += (pos < dest) ? 1 : -1;
369  SetLiftPosition(tile, pos);
370 
371  if (pos == dest) {
372  HaltLift(tile);
373  DeleteAnimatedTile(tile);
374  }
375 
376  MarkTileDirtyByTile(tile);
377 }
378 
385 static bool IsCloseToTown(TileIndex tile, uint dist)
386 {
387  if (_town_kdtree.Count() == 0) return false;
388  Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
389  return DistanceManhattan(tile, t->xy) < dist;
390 }
391 
397 {
398  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
399  SetDParam(0, this->index);
400  SetDParam(1, this->cache.population);
401  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
402  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
403  STR_VIEWPORT_TOWN);
404 
406 }
407 
410 {
411  Town *t;
412 
413  FOR_ALL_TOWNS(t) {
414  t->UpdateVirtCoord();
415  }
416 }
417 
423 static void ChangePopulation(Town *t, int mod)
424 {
425  t->cache.population += mod;
426  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
428 
430 }
431 
438 {
439  uint32 pop = 0;
440  const Town *t;
441 
442  FOR_ALL_TOWNS(t) pop += t->cache.population;
443  return pop;
444 }
445 
450 static void RemoveNearbyStations(Town *t)
451 {
452  for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
453  const Station *st = *it;
454  if (!st->CatchmentCoversTown(t->index)) {
455  it = t->stations_near.erase(it);
456  } else {
457  ++it;
458  }
459  }
460 }
461 
467 {
468  assert(IsTileType(tile, MP_HOUSE));
469 
470  /* progress in construction stages */
472  if (GetHouseConstructionTick(tile) != 0) return;
473 
474  AnimateNewHouseConstruction(tile);
475 
476  if (IsHouseCompleted(tile)) {
477  /* Now that construction is complete, we can add the population of the
478  * building to the town. */
479  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
480  ResetHouseAge(tile);
481  }
482  MarkTileDirtyByTile(tile);
483 }
484 
490 {
491  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
492  if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
493  if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
494  if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
495  if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
496 }
497 
504 static void TileLoop_Town(TileIndex tile)
505 {
506  HouseID house_id = GetHouseType(tile);
507 
508  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
509  * doesn't exist any more, so don't continue here. */
510  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
511 
512  if (!IsHouseCompleted(tile)) {
513  /* Construction is not completed. See if we can go further in construction*/
514  MakeTownHouseBigger(tile);
515  return;
516  }
517 
518  const HouseSpec *hs = HouseSpec::Get(house_id);
519 
520  /* If the lift has a destination, it is already an animated tile. */
521  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
522  house_id < NEW_HOUSE_OFFSET &&
523  !LiftHasDestination(tile) &&
524  Chance16(1, 2)) {
525  AddAnimatedTile(tile);
526  }
527 
528  Town *t = Town::GetByTile(tile);
529  uint32 r = Random();
530 
531  StationFinder stations(TileArea(tile, 1, 1));
532 
534  for (uint i = 0; i < 256; i++) {
535  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
536 
537  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
538 
539  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
540  if (cargo == CT_INVALID) continue;
541 
542  uint amt = GB(callback, 0, 8);
543  if (amt == 0) continue;
544 
545  uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
546 
547  const CargoSpec *cs = CargoSpec::Get(cargo);
548  t->supplied[cs->Index()].new_max += amt;
549  t->supplied[cs->Index()].new_act += moved;
550  }
551  } else {
553  case TCGM_ORIGINAL:
554  /* Original (quadratic) cargo generation algorithm */
555  if (GB(r, 0, 8) < hs->population) {
556  uint amt = GB(r, 0, 8) / 8 + 1;
557 
558  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
559  t->supplied[CT_PASSENGERS].new_max += amt;
560  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
561  }
562 
563  if (GB(r, 8, 8) < hs->mail_generation) {
564  uint amt = GB(r, 8, 8) / 8 + 1;
565 
566  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
567  t->supplied[CT_MAIL].new_max += amt;
568  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
569  }
570  break;
571 
572  case TCGM_BITCOUNT:
573  /* Binomial distribution per tick, by a series of coin flips */
574  /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
575  * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
576  if (GB(_tick_counter, 8, 2) == GB(tile, 0, 2)) {
577  /* Make a bitmask with up to 32 bits set, one for each potential pax */
578  int genmax = (hs->population + 7) / 8;
579  uint32 genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
580  /* Mask random value by potential pax and count number of actual pax */
581  uint amt = CountBits(r & genmask);
582  /* Adjust and apply */
583  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
584  t->supplied[CT_PASSENGERS].new_max += amt;
585  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
586 
587  /* Do the same for mail, with a fresh random */
588  r = Random();
589  genmax = (hs->mail_generation + 7) / 8;
590  genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
591  amt = CountBits(r & genmask);
592  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
593  t->supplied[CT_MAIL].new_max += amt;
594  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
595  }
596  break;
597 
598  default:
599  NOT_REACHED();
600  }
601  }
602 
603  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
604 
605  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
607  CanDeleteHouse(tile) &&
608  GetHouseAge(tile) >= hs->minimum_life &&
609  --t->time_until_rebuild == 0) {
610  t->time_until_rebuild = GB(r, 16, 8) + 192;
611 
612  ClearTownHouse(t, tile);
613 
614  /* Rebuild with another house? */
615  if (GB(r, 24, 8) < 12 || !BuildTownHouse(t, tile))
616  {
617  /* House wasn't replaced, so remove it */
619  }
620  }
621 
622  cur_company.Restore();
623 }
624 
625 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
626 {
627  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
628  if (!CanDeleteHouse(tile)) return CMD_ERROR;
629 
630  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
631 
633  cost.AddCost(hs->GetRemovalCost());
634 
635  int rating = hs->remove_rating_decrease;
636  Town *t = Town::GetByTile(tile);
637 
639  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
640  SetDParam(0, t->index);
641  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
642  }
643  }
644 
645  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
646  if (flags & DC_EXEC) {
647  ClearTownHouse(t, tile);
649  }
650 
651  return cost;
652 }
653 
654 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
655 {
656  HouseID house_id = GetHouseType(tile);
657  const HouseSpec *hs = HouseSpec::Get(house_id);
658  Town *t = Town::GetByTile(tile);
659 
661  for (uint i = 0; i < 256; i++) {
662  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
663 
664  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
665 
666  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
667 
668  if (cargo == CT_INVALID) continue;
669  produced[cargo]++;
670  }
671  } else {
672  if (hs->population > 0) {
673  produced[CT_PASSENGERS]++;
674  }
675  if (hs->mail_generation > 0) {
676  produced[CT_MAIL]++;
677  }
678  }
679 }
680 
681 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
682 {
683  if (cargo == CT_INVALID || amount == 0) return;
684  acceptance[cargo] += amount;
685  SetBit(*always_accepted, cargo);
686 }
687 
688 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
689 {
690  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
691  CargoID accepts[lengthof(hs->accepts_cargo)];
692 
693  /* Set the initial accepted cargo types */
694  for (uint8 i = 0; i < lengthof(accepts); i++) {
695  accepts[i] = hs->accepts_cargo[i];
696  }
697 
698  /* Check for custom accepted cargo types */
700  uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
701  if (callback != CALLBACK_FAILED) {
702  /* Replace accepted cargo types with translated values from callback */
703  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
704  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
705  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
706  }
707  }
708 
709  /* Check for custom cargo acceptance */
711  uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
712  if (callback != CALLBACK_FAILED) {
713  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
714  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
715  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
716  /* The 'S' bit indicates food instead of goods */
717  AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
718  } else {
719  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
720  }
721  return;
722  }
723  }
724 
725  /* No custom acceptance, so fill in with the default values */
726  for (uint8 i = 0; i < lengthof(accepts); i++) {
727  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
728  }
729 }
730 
731 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
732 {
733  const HouseID house = GetHouseType(tile);
734  const HouseSpec *hs = HouseSpec::Get(house);
735  bool house_completed = IsHouseCompleted(tile);
736 
737  td->str = hs->building_name;
738 
739  uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
740  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
741  if (callback_res > 0x400) {
743  } else {
744  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
745  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
746  td->str = new_name;
747  }
748  }
749  }
750 
751  if (!house_completed) {
752  SetDParamX(td->dparam, 0, td->str);
753  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
754  }
755 
756  if (hs->grf_prop.grffile != nullptr) {
757  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
758  td->grf = gc->GetName();
759  }
760 
761  td->owner[0] = OWNER_TOWN;
762 }
763 
764 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
765 {
766  /* not used */
767  return 0;
768 }
769 
770 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
771 {
772  /* not used */
773 }
774 
779 {
780  t->cargo_accepted_total = 0;
781 
782  const TileArea &area = t->cargo_accepted.GetArea();
783  TILE_AREA_LOOP(tile, area) {
784  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
785  t->cargo_accepted_total |= t->cargo_accepted[tile];
786  }
787  }
788 }
789 
796 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
797 {
798  CargoArray accepted, produced;
799  CargoTypes dummy = 0;
800 
801  /* Gather acceptance for all houses in an area around the start tile.
802  * The area is composed of the square the tile is in, extended one square in all
803  * directions as the coverage area of a single station is bigger than just one square. */
805  TILE_AREA_LOOP(tile, area) {
806  if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
807 
808  AddAcceptedCargo_Town(tile, accepted, &dummy);
809  AddProducedCargo_Town(tile, produced);
810  }
811 
812  /* Create bitmap of produced and accepted cargoes. */
813  CargoTypes acc = 0;
814  for (uint cid = 0; cid < NUM_CARGO; cid++) {
815  if (accepted[cid] >= 8) SetBit(acc, cid);
816  if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
817  }
818  t->cargo_accepted[start] = acc;
819 
820  if (update_total) UpdateTownCargoTotal(t);
821 }
822 
827 {
828  t->cargo_produced = 0;
829 
830  const TileArea &area = t->cargo_accepted.GetArea();
831  if (area.tile == INVALID_TILE) return;
832 
833  /* Update acceptance for each grid square. */
834  TILE_AREA_LOOP(tile, area) {
835  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
836  UpdateTownCargoes(t, tile, false);
837  }
838  }
839 
840  /* Update the total acceptance. */
842 }
843 
846 {
847  Town *town;
849 
850  FOR_ALL_TOWNS(town) {
852  }
853 }
854 
855 static bool GrowTown(Town *t);
856 
857 static void TownTickHandler(Town *t)
858 {
859  if (HasBit(t->flags, TOWN_IS_GROWING)) {
860  int i = (int)t->grow_counter - 1;
861  if (i < 0) {
862  if (GrowTown(t)) {
863  i = t->growth_rate;
864  } else {
865  /* If growth failed wait a bit before retrying */
866  i = min(t->growth_rate, TOWN_GROWTH_TICKS - 1);
867  }
868  }
869  t->grow_counter = i;
870  }
871 }
872 
873 void OnTick_Town()
874 {
875  if (_game_mode == GM_EDITOR) return;
876 
877  Town *t;
878  FOR_ALL_TOWNS(t) {
879  TownTickHandler(t);
880  }
881 }
882 
892 {
893  if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
894 
895  return GetAnyRoadBits(tile, RTT_ROAD, true);
896 }
897 
898 RoadType GetTownRoadType(const Town *t)
899 {
900  RoadType best_rt = ROADTYPE_ROAD;
901  const RoadTypeInfo *best = nullptr;
902  const uint16 assume_max_speed = 50;
903 
904  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
905  if (RoadTypeIsTram(rt)) continue;
906 
907  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
908 
909  /* Unused road type. */
910  if (rti->label == 0) continue;
911 
912  /* Can town build this road. */
913  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
914 
915  /* Not yet introduced at this date. */
916  if (IsInsideMM(rti->introduction_date, 0, MAX_DAY) && rti->introduction_date > _date) continue;
917 
918  if (best != nullptr) {
919  if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
920  }
921 
922  best_rt = rt;
923  best = rti;
924  }
925 
926  return best_rt;
927 }
928 
939 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
940 {
941  if (!IsValidTile(tile)) return false;
942 
943  /* Lookup table for the used diff values */
944  const TileIndexDiff tid_lt[3] = {
948  };
949 
950  dist_multi = (dist_multi + 1) * 4;
951  for (uint pos = 4; pos < dist_multi; pos++) {
952  /* Go (pos / 4) tiles to the left or the right */
953  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
954 
955  /* Use the current tile as origin, or go one tile backwards */
956  if (pos & 2) cur += tid_lt[2];
957 
958  /* Test for roadbit parallel to dir and facing towards the middle axis */
959  if (IsValidTile(tile + cur) &&
960  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
961  }
962  return false;
963 }
964 
973 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
974 {
975  if (DistanceFromEdge(tile) == 0) return false;
976 
977  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
978  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
979 
980  /* Check if there already is a road at this point? */
981  if (GetTownRoadBits(tile) == ROAD_NONE) {
982  /* No, try if we are able to build a road piece there.
983  * If that fails clear the land, and if that fails exit.
984  * This is to make sure that we can build a road here later. */
985  RoadType rt = GetTownRoadType(t);
986  if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X) | (rt << 4), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
987  DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
988  return false;
989  }
990  }
991 
993  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
994  if (cur_slope == SLOPE_FLAT) return ret;
995 
996  /* If the tile is not a slope in the right direction, then
997  * maybe terraform some. */
998  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
999  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
1000  if (Chance16(1, 8)) {
1001  CommandCost res = CMD_ERROR;
1002  if (!_generating_world && Chance16(1, 10)) {
1003  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
1004  res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
1006  }
1007  if (res.Failed() && Chance16(1, 3)) {
1008  /* We can consider building on the slope, though. */
1009  return ret;
1010  }
1011  }
1012  return false;
1013  }
1014  return ret;
1015 }
1016 
1017 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
1018 {
1019  assert(tile < MapSize());
1020 
1021  CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
1022  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
1023  DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
1024  return true;
1025 }
1026 
1027 static void LevelTownLand(TileIndex tile)
1028 {
1029  assert(tile < MapSize());
1030 
1031  /* Don't terraform if land is plain or if there's a house there. */
1032  if (IsTileType(tile, MP_HOUSE)) return;
1033  Slope tileh = GetTileSlope(tile);
1034  if (tileh == SLOPE_FLAT) return;
1035 
1036  /* First try up, then down */
1037  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
1038  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
1039  }
1040 }
1041 
1052 {
1053  /* align the grid to the downtown */
1054  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1055  RoadBits rcmd = ROAD_NONE;
1056 
1057  switch (t->layout) {
1058  default: NOT_REACHED();
1059 
1060  case TL_2X2_GRID:
1061  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1062  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1063  break;
1064 
1065  case TL_3X3_GRID:
1066  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1067  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1068  break;
1069  }
1070 
1071  /* Optimise only X-junctions */
1072  if (rcmd != ROAD_ALL) return rcmd;
1073 
1074  RoadBits rb_template;
1075 
1076  switch (GetTileSlope(tile)) {
1077  default: rb_template = ROAD_ALL; break;
1078  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1079  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1080  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1081  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1082  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1083  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1084  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1085  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1086  case SLOPE_STEEP_W:
1087  case SLOPE_STEEP_S:
1088  case SLOPE_STEEP_E:
1089  case SLOPE_STEEP_N:
1090  rb_template = ROAD_NONE;
1091  break;
1092  }
1093 
1094  /* Stop if the template is compatible to the growth dir */
1095  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1096  /* If not generate a straight road in the direction of the growth */
1098 }
1099 
1111 {
1112  /* We can't look further than that. */
1113  if (DistanceFromEdge(tile) == 0) return false;
1114 
1115  uint counter = 0; // counts the house neighbor tiles
1116 
1117  /* Check the tiles E,N,W and S of the current tile for houses */
1118  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1119  /* Count both void and house tiles for checking whether there
1120  * are enough houses in the area. This to make it likely that
1121  * houses get build up to the edge of the map. */
1122  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1123  case MP_HOUSE:
1124  case MP_VOID:
1125  counter++;
1126  break;
1127 
1128  default:
1129  break;
1130  }
1131 
1132  /* If there are enough neighbors stop here */
1133  if (counter >= 3) {
1134  if (BuildTownHouse(t, tile)) {
1135  _grow_town_result = GROWTH_SUCCEED;
1136  return true;
1137  }
1138  return false;
1139  }
1140  }
1141  return false;
1142 }
1143 
1152 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1153 {
1154  RoadType rt = GetTownRoadType(t);
1155  if (DoCommand(tile, rcmd | (rt << 4), t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1156  _grow_town_result = GROWTH_SUCCEED;
1157  return true;
1158  }
1159  return false;
1160 }
1161 
1172 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1173 {
1174  assert(bridge_dir < DIAGDIR_END);
1175 
1176  const Slope slope = GetTileSlope(tile);
1177 
1178  /* Make sure the direction is compatible with the slope.
1179  * Well we check if the slope has an up bit set in the
1180  * reverse direction. */
1181  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1182 
1183  /* Assure that the bridge is connectable to the start side */
1184  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1185 
1186  /* We are in the right direction */
1187  uint8 bridge_length = 0; // This value stores the length of the possible bridge
1188  TileIndex bridge_tile = tile; // Used to store the other waterside
1189 
1190  const int delta = TileOffsByDiagDir(bridge_dir);
1191 
1192  if (slope == SLOPE_FLAT) {
1193  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1194  do {
1195  if (bridge_length++ >= 4) {
1196  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1197  return false;
1198  }
1199  bridge_tile += delta;
1200  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1201  } else {
1202  do {
1203  if (bridge_length++ >= 11) {
1204  /* Max 11 tile long bridges */
1205  return false;
1206  }
1207  bridge_tile += delta;
1208  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1209  }
1210 
1211  /* no water tiles in between? */
1212  if (bridge_length == 1) return false;
1213 
1214  for (uint8 times = 0; times <= 22; times++) {
1215  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1216 
1217  /* Can we actually build the bridge? */
1218  RoadType rt = GetTownRoadType(t);
1219  if (DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1220  DoCommand(tile, bridge_tile, bridge_type | rt << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1221  _grow_town_result = GROWTH_SUCCEED;
1222  return true;
1223  }
1224  }
1225  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1226  return false;
1227 }
1228 
1229 
1236 static inline bool RoadTypesAllowHouseHere(TileIndex t)
1237 {
1238  static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1239  bool allow = false;
1240 
1241  for (const TileIndexDiffC *ptr = tiles; ptr != endof(tiles); ++ptr) {
1242  TileIndex cur_tile = t + ToTileIndexDiff(*ptr);
1243  if (!IsValidTile(cur_tile)) continue;
1244 
1245  if (!(IsTileType(cur_tile, MP_ROAD) || IsTileType(cur_tile, MP_STATION))) continue;
1246  allow = true;
1247 
1248  RoadType road_rt = GetRoadTypeRoad(cur_tile);
1249  RoadType tram_rt = GetRoadTypeTram(cur_tile);
1250  if (road_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(road_rt)->flags, ROTF_NO_HOUSES)) return true;
1251  if (tram_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(tram_rt)->flags, ROTF_NO_HOUSES)) return true;
1252  }
1253 
1254  /* If no road was found surrounding the tile we can allow building the house since there is
1255  * nothing which forbids it, if a road was found but the execution reached this point, then
1256  * all the found roads don't allow houses to be built */
1257  return !allow;
1258 }
1259 
1277 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1278 {
1279  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1280  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1281 
1282  assert(tile < MapSize());
1283 
1284  if (cur_rb == ROAD_NONE) {
1285  /* Tile has no road. First reset the status counter
1286  * to say that this is the last iteration. */
1287  _grow_town_result = GROWTH_SEARCH_STOPPED;
1288 
1291 
1292  /* Remove hills etc */
1293  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1294 
1295  /* Is a road allowed here? */
1296  switch (t1->layout) {
1297  default: NOT_REACHED();
1298 
1299  case TL_3X3_GRID:
1300  case TL_2X2_GRID:
1301  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1302  if (rcmd == ROAD_NONE) return;
1303  break;
1304 
1305  case TL_BETTER_ROADS:
1306  case TL_ORIGINAL:
1307  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1308 
1309  DiagDirection source_dir = ReverseDiagDir(target_dir);
1310 
1311  if (Chance16(1, 4)) {
1312  /* Randomize a new target dir */
1313  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1314  }
1315 
1316  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1317  /* A road is not allowed to continue the randomized road,
1318  * return if the road we're trying to build is curved. */
1319  if (target_dir != ReverseDiagDir(source_dir)) return;
1320 
1321  /* Return if neither side of the new road is a house */
1324  return;
1325  }
1326 
1327  /* That means that the road is only allowed if there is a house
1328  * at any side of the new road. */
1329  }
1330 
1331  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1332  break;
1333  }
1334 
1335  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1336  /* Continue building on a partial road.
1337  * Should be always OK, so we only generate
1338  * the fitting RoadBits */
1339  _grow_town_result = GROWTH_SEARCH_STOPPED;
1340 
1342 
1343  switch (t1->layout) {
1344  default: NOT_REACHED();
1345 
1346  case TL_3X3_GRID:
1347  case TL_2X2_GRID:
1348  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1349  break;
1350 
1351  case TL_BETTER_ROADS:
1352  case TL_ORIGINAL:
1353  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1354  break;
1355  }
1356  } else {
1357  bool allow_house = true; // Value which decides if we want to construct a house
1358 
1359  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1360  * it is the starting tile. Half the time, we stay on this side then.*/
1361  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1362  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1363  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1364  }
1365  return;
1366  }
1367 
1368  /* Possibly extend the road in a direction.
1369  * Randomize a direction and if it has a road, bail out. */
1370  target_dir = RandomDiagDir();
1371  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1372  TileIndex house_tile; // position of a possible house
1373 
1374  if (cur_rb & target_rb) {
1375  /* If it's a road turn possibly build a house in a corner.
1376  * Use intersection with straight road as an indicator
1377  * that we randomed corner house position.
1378  * A turn (and we check for that later) always has only
1379  * one common bit with a straight road so it has the same
1380  * chance to be chosen as the house on the side of a road.
1381  */
1382  if ((cur_rb & ROAD_X) != target_rb) return;
1383 
1384  /* Check whether it is a turn and if so determine
1385  * position of the corner tile */
1386  switch (cur_rb) {
1387  case ROAD_N:
1388  house_tile = TileAddByDir(tile, DIR_S);
1389  break;
1390  case ROAD_S:
1391  house_tile = TileAddByDir(tile, DIR_N);
1392  break;
1393  case ROAD_E:
1394  house_tile = TileAddByDir(tile, DIR_W);
1395  break;
1396  case ROAD_W:
1397  house_tile = TileAddByDir(tile, DIR_E);
1398  break;
1399  default:
1400  return; // not a turn
1401  }
1402  target_dir = DIAGDIR_END;
1403  } else {
1404  house_tile = TileAddByDiagDir(tile, target_dir);
1405  }
1406 
1407  /* Don't walk into water. */
1408  if (HasTileWaterGround(house_tile)) return;
1409 
1410  if (!IsValidTile(house_tile)) return;
1411 
1413  switch (t1->layout) {
1414  default: NOT_REACHED();
1415 
1416  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1417  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1418  FALLTHROUGH;
1419 
1420  case TL_2X2_GRID:
1421  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1422  allow_house = (rcmd & target_rb) == ROAD_NONE;
1423  break;
1424 
1425  case TL_BETTER_ROADS: // Use original afterwards!
1426  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1427  FALLTHROUGH;
1428 
1429  case TL_ORIGINAL:
1430  /* Allow a house at the edge. 60% chance or
1431  * always ok if no road allowed. */
1432  rcmd = target_rb;
1433  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1434  break;
1435  }
1436  }
1437 
1438  allow_house &= RoadTypesAllowHouseHere(house_tile);
1439 
1440  if (allow_house) {
1441  /* Build a house, but not if there already is a house there. */
1442  if (!IsTileType(house_tile, MP_HOUSE)) {
1443  /* Level the land if possible */
1444  if (Chance16(1, 6)) LevelTownLand(house_tile);
1445 
1446  /* And build a house.
1447  * Set result to -1 if we managed to build it. */
1448  if (BuildTownHouse(t1, house_tile)) {
1449  _grow_town_result = GROWTH_SUCCEED;
1450  }
1451  }
1452  return;
1453  }
1454 
1455  _grow_town_result = GROWTH_SEARCH_STOPPED;
1456  }
1457 
1458  /* Return if a water tile */
1459  if (HasTileWaterGround(tile)) return;
1460 
1461  /* Make the roads look nicer */
1462  rcmd = CleanUpRoadBits(tile, rcmd);
1463  if (rcmd == ROAD_NONE) return;
1464 
1465  /* Only use the target direction for bridges to ensure they're connected.
1466  * The target_dir is as computed previously according to town layout, so
1467  * it will match it perfectly. */
1468  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1469 
1470  GrowTownWithRoad(t1, tile, rcmd);
1471 }
1472 
1480 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1481 {
1482  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1483  if (!IsValidTile(target_tile)) return false;
1484  if (HasTileWaterGround(target_tile)) return false;
1485 
1486  RoadBits target_rb = GetTownRoadBits(target_tile);
1488  /* Check whether a road connection exists or can be build. */
1489  switch (GetTileType(target_tile)) {
1490  case MP_ROAD:
1491  return target_rb != ROAD_NONE;
1492 
1493  case MP_STATION:
1494  return IsDriveThroughStopTile(target_tile);
1495 
1496  case MP_TUNNELBRIDGE:
1497  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1498 
1499  case MP_HOUSE:
1500  case MP_INDUSTRY:
1501  case MP_OBJECT:
1502  return false;
1503 
1504  default:
1505  /* Checked for void and water earlier */
1506  return true;
1507  }
1508  } else {
1509  /* Check whether a road connection already exists,
1510  * and it leads somewhere else. */
1511  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1512  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1513  }
1514 }
1515 
1522 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1523 {
1524  /* Special case.
1525  * @see GrowTownInTile Check the else if
1526  */
1527  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1528 
1529  assert(tile < MapSize());
1530 
1531  /* Number of times to search.
1532  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1533  * them a little handicap. */
1534  switch (t->layout) {
1535  case TL_BETTER_ROADS:
1536  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1537  break;
1538 
1539  case TL_3X3_GRID:
1540  case TL_2X2_GRID:
1541  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1542  break;
1543 
1544  default:
1545  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1546  break;
1547  }
1548 
1549  do {
1550  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1551 
1552  /* Try to grow the town from this point */
1553  GrowTownInTile(&tile, cur_rb, target_dir, t);
1554  if (_grow_town_result == GROWTH_SUCCEED) return true;
1555 
1556  /* Exclude the source position from the bitmask
1557  * and return if no more road blocks available */
1558  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1559  if (cur_rb == ROAD_NONE) return false;
1560 
1561  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1562  /* Only build in the direction away from the tunnel or bridge. */
1563  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1564  } else {
1565  /* Select a random bit from the blockmask, walk a step
1566  * and continue the search from there. */
1567  do {
1568  if (cur_rb == ROAD_NONE) return false;
1569  RoadBits target_bits;
1570  do {
1571  target_dir = RandomDiagDir();
1572  target_bits = DiagDirToRoadBits(target_dir);
1573  } while (!(cur_rb & target_bits));
1574  cur_rb &= ~target_bits;
1575  } while (!CanFollowRoad(tile, target_dir));
1576  }
1577  tile = TileAddByDiagDir(tile, target_dir);
1578 
1579  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, RTT_ROAD)) {
1580  /* Don't allow building over roads of other cities */
1581  if (IsRoadOwner(tile, RTT_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1582  return false;
1583  } else if (IsRoadOwner(tile, RTT_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1584  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1585  * owner :) (happy happy happy road now) */
1586  SetRoadOwner(tile, RTT_ROAD, OWNER_TOWN);
1587  SetTownIndex(tile, t->index);
1588  }
1589  }
1590 
1591  /* Max number of times is checked. */
1592  } while (--_grow_town_result >= 0);
1593 
1594  return false;
1595 }
1596 
1605 {
1606  uint32 r = Random();
1607  uint a = GB(r, 0, 2);
1608  uint b = GB(r, 8, 2);
1609  if (a == b) b ^= 2;
1610  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1611 }
1612 
1618 static bool GrowTown(Town *t)
1619 {
1620  static const TileIndexDiffC _town_coord_mod[] = {
1621  {-1, 0},
1622  { 1, 1},
1623  { 1, -1},
1624  {-1, -1},
1625  {-1, 0},
1626  { 0, 2},
1627  { 2, 0},
1628  { 0, -2},
1629  {-1, -1},
1630  {-2, 2},
1631  { 2, 2},
1632  { 2, -2},
1633  { 0, 0}
1634  };
1635 
1636  /* Current "company" is a town */
1637  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1638 
1639  TileIndex tile = t->xy; // The tile we are working with ATM
1640 
1641  /* Find a road that we can base the construction on. */
1642  const TileIndexDiffC *ptr;
1643  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1644  if (GetTownRoadBits(tile) != ROAD_NONE) {
1645  bool success = GrowTownAtRoad(t, tile);
1646  cur_company.Restore();
1647  return success;
1648  }
1649  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1650  }
1651 
1652  /* No road available, try to build a random road block by
1653  * clearing some land and then building a road there. */
1655  tile = t->xy;
1656  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1657  /* Only work with plain land that not already has a house */
1658  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1659  if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1660  RoadType rt = GetTownRoadType(t);
1661  DoCommand(tile, GenRandomRoadBits() | (rt << 4), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1662  cur_company.Restore();
1663  return true;
1664  }
1665  }
1666  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1667  }
1668  }
1669 
1670  cur_company.Restore();
1671  return false;
1672 }
1673 
1674 void UpdateTownRadius(Town *t)
1675 {
1676  static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1677  { 4, 0, 0, 0, 0}, // 0
1678  { 16, 0, 0, 0, 0},
1679  { 25, 0, 0, 0, 0},
1680  { 36, 0, 0, 0, 0},
1681  { 49, 0, 4, 0, 0},
1682  { 64, 0, 4, 0, 0}, // 20
1683  { 64, 0, 9, 0, 1},
1684  { 64, 0, 9, 0, 4},
1685  { 64, 0, 16, 0, 4},
1686  { 81, 0, 16, 0, 4},
1687  { 81, 0, 16, 0, 4}, // 40
1688  { 81, 0, 25, 0, 9},
1689  { 81, 36, 25, 0, 9},
1690  { 81, 36, 25, 16, 9},
1691  { 81, 49, 0, 25, 9},
1692  { 81, 64, 0, 25, 9}, // 60
1693  { 81, 64, 0, 36, 9},
1694  { 81, 64, 0, 36, 16},
1695  {100, 81, 0, 49, 16},
1696  {100, 81, 0, 49, 25},
1697  {121, 81, 0, 49, 25}, // 80
1698  {121, 81, 0, 49, 25},
1699  {121, 81, 0, 49, 36}, // 88
1700  };
1701 
1702  if (t->cache.num_houses < 92) {
1703  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));
1704  } else {
1705  int mass = t->cache.num_houses / 8;
1706  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1707  * The offsets are to make sure the radii do not decrease in size when going from the table
1708  * to the calculated value.*/
1709  t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1710  t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1711  t->cache.squared_town_zone_radius[2] = 0;
1712  t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1713  t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1714  }
1715 }
1716 
1717 void UpdateTownMaxPass(Town *t)
1718 {
1719  t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1720  t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1721 }
1722 
1723 static void UpdateTownGrowthRate(Town *t);
1724 static void UpdateTownGrowth(Town *t);
1725 
1737 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1738 {
1739  t->xy = tile;
1740  t->cache.num_houses = 0;
1741  t->time_until_rebuild = 10;
1742  UpdateTownRadius(t);
1743  t->flags = 0;
1744  t->cache.population = 0;
1745  /* Spread growth across ticks so even if there are many
1746  * similar towns they're unlikely to grow all in one tick */
1748  t->growth_rate = TownTicksToGameTicks(250);
1749  t->show_zone = false;
1750 
1751  _town_kdtree.Insert(t->index);
1752 
1753  /* Set the default cargo requirement for town growth */
1755  case LT_ARCTIC:
1757  break;
1758 
1759  case LT_TROPIC:
1762  break;
1763  }
1764 
1765  t->fund_buildings_months = 0;
1766 
1767  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1768 
1769  t->have_ratings = 0;
1771  t->exclusive_counter = 0;
1772  t->statues = 0;
1773 
1774  extern int _nb_orig_names;
1776  /* Original town name */
1777  t->townnamegrfid = 0;
1778  t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1779  } else {
1780  /* Newgrf town name */
1781  t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1782  t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1783  }
1784  t->townnameparts = townnameparts;
1785 
1786  t->UpdateVirtCoord();
1787  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(t->index));
1789 
1790  t->InitializeLayout(layout);
1791 
1792  t->larger_town = city;
1793 
1794  int x = (int)size * 16 + 3;
1795  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1796  /* Don't create huge cities when founding town in-game */
1797  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1798 
1799  t->cache.num_houses += x;
1800  UpdateTownRadius(t);
1801 
1802  int i = x * 4;
1803  do {
1804  GrowTown(t);
1805  } while (--i);
1806 
1807  t->cache.num_houses -= x;
1808  UpdateTownRadius(t);
1810  UpdateTownMaxPass(t);
1812 }
1813 
1820 {
1821  /* Check if too close to the edge of map */
1822  if (DistanceFromEdge(tile) < 12) {
1823  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1824  }
1825 
1826  /* Check distance to all other towns. */
1827  if (IsCloseToTown(tile, 20)) {
1828  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1829  }
1830 
1831  /* Can only build on clear flat areas, possibly with trees. */
1832  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1833  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1834  }
1835 
1836  return CommandCost(EXPENSES_OTHER);
1837 }
1838 
1844 static bool IsUniqueTownName(const char *name)
1845 {
1846  const Town *t;
1847 
1848  FOR_ALL_TOWNS(t) {
1849  if (t->name != nullptr && strcmp(t->name, name) == 0) return false;
1850  }
1851 
1852  return true;
1853 }
1854 
1867 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1868 {
1869  TownSize size = Extract<TownSize, 0, 2>(p1);
1870  bool city = HasBit(p1, 2);
1871  TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1873  bool random = HasBit(p1, 6);
1874  uint32 townnameparts = p2;
1875 
1876  if (size >= TSZ_END) return CMD_ERROR;
1877  if (layout >= NUM_TLS) return CMD_ERROR;
1878 
1879  /* Some things are allowed only in the scenario editor and for game scripts. */
1880  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1882  if (size == TSZ_LARGE) return CMD_ERROR;
1883  if (random) return CMD_ERROR;
1885  return CMD_ERROR;
1886  }
1887  } else if (_current_company == OWNER_DEITY && random) {
1888  /* Random parameter is not allowed for Game Scripts. */
1889  return CMD_ERROR;
1890  }
1891 
1892  if (StrEmpty(text)) {
1893  /* If supplied name is empty, townnameparts has to generate unique automatic name */
1894  if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1895  } else {
1896  /* If name is not empty, it has to be unique custom name */
1898  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1899  }
1900 
1901  /* Allocate town struct */
1902  if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1903 
1904  if (!random) {
1905  CommandCost ret = TownCanBePlacedHere(tile);
1906  if (ret.Failed()) return ret;
1907  }
1908 
1909  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1910  /* multidimensional arrays have to have defined length of non-first dimension */
1911  assert_compile(lengthof(price_mult[0]) == 4);
1912 
1913  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1914  byte mult = price_mult[city][size];
1915 
1916  cost.MultiplyCost(mult);
1917 
1918  /* Create the town */
1919  if (flags & DC_EXEC) {
1920  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1921  _additional_cash_required = cost.GetCost();
1922  return CommandCost(EXPENSES_OTHER);
1923  }
1924 
1925  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1927  Town *t;
1928  if (random) {
1929  t = CreateRandomTown(20, townnameparts, size, city, layout);
1930  if (t == nullptr) {
1931  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1932  } else {
1933  _new_town_id = t->index;
1934  }
1935  } else {
1936  t = new Town(tile);
1937  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1938  }
1940  old_generating_world.Restore();
1941 
1942  if (t != nullptr && !StrEmpty(text)) {
1943  t->name = stredup(text);
1944  t->UpdateVirtCoord();
1945  }
1946 
1947  if (_game_mode != GM_EDITOR) {
1948  /* 't' can't be nullptr since 'random' is false outside scenedit */
1949  assert(!random);
1950 
1951  if (_current_company == OWNER_DEITY) {
1952  SetDParam(0, t->index);
1953  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
1954  } else {
1955  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1957  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1958 
1959  char *cn = stredup(company_name);
1960  SetDParamStr(0, cn);
1961  SetDParam(1, t->index);
1962 
1963  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1964  }
1965  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1966  Game::NewEvent(new ScriptEventTownFounded(t->index));
1967  }
1968  }
1969  return cost;
1970 }
1971 
1982 {
1983  switch (layout) {
1984  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1985  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1986  default: return tile;
1987  }
1988 }
1989 
1999 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
2000 {
2001  switch (layout) {
2002  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2003  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2004  default: return true;
2005  }
2006 }
2007 
2011 struct SpotData {
2013  uint max_dist;
2015 };
2016 
2033 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
2034 {
2035  SpotData *sp = (SpotData*)user_data;
2036  uint dist = GetClosestWaterDistance(tile, true);
2037 
2038  if (IsTileType(tile, MP_CLEAR) &&
2039  IsTileFlat(tile) &&
2040  IsTileAlignedToGrid(tile, sp->layout) &&
2041  dist > sp->max_dist) {
2042  sp->tile = tile;
2043  sp->max_dist = dist;
2044  }
2045 
2046  return false;
2047 }
2048 
2055 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
2056 {
2057  return IsTileType(tile, MP_CLEAR);
2058 }
2059 
2073 {
2074  SpotData sp = { INVALID_TILE, 0, layout };
2075 
2076  TileIndex coast = tile;
2077  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
2078  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
2079  return sp.tile;
2080  }
2081 
2082  /* if we get here just give up */
2083  return INVALID_TILE;
2084 }
2085 
2086 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
2087 {
2088  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
2089 
2090  if (!Town::CanAllocateItem()) return nullptr;
2091 
2092  do {
2093  /* Generate a tile index not too close from the edge */
2094  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2095 
2096  /* if we tried to place the town on water, slide it over onto
2097  * the nearest likely-looking spot */
2098  if (IsTileType(tile, MP_WATER)) {
2099  tile = FindNearestGoodCoastalTownSpot(tile, layout);
2100  if (tile == INVALID_TILE) continue;
2101  }
2102 
2103  /* Make sure town can be placed here */
2104  if (TownCanBePlacedHere(tile).Failed()) continue;
2105 
2106  /* Allocate a town struct */
2107  Town *t = new Town(tile);
2108 
2109  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2110 
2111  /* if the population is still 0 at the point, then the
2112  * placement is so bad it couldn't grow at all */
2113  if (t->cache.population > 0) return t;
2114 
2115  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2117  cur_company.Restore();
2118  assert(rc.Succeeded());
2119 
2120  /* We already know that we can allocate a single town when
2121  * entering this function. However, we create and delete
2122  * a town which "resets" the allocation checks. As such we
2123  * need to check again when assertions are enabled. */
2124  assert(Town::CanAllocateItem());
2125  } while (--attempts != 0);
2126 
2127  return nullptr;
2128 }
2129 
2130 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2131 
2140 {
2141  uint current_number = 0;
2142  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2143  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
2144  total = min(TownPool::MAX_SIZE, total);
2145  uint32 townnameparts;
2146  TownNames town_names;
2147 
2149 
2150  /* First attempt will be made at creating the suggested number of towns.
2151  * Note that this is really a suggested value, not a required one.
2152  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2153  do {
2156  /* Get a unique name for the town. */
2157  if (!GenerateTownName(&townnameparts, &town_names)) continue;
2158  /* try 20 times to create a random-sized town for the first loop. */
2159  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2160  } while (--total);
2161 
2162  town_names.clear();
2163 
2164  /* Build the town k-d tree again to make sure it's well balanced */
2165  RebuildTownKdtree();
2166 
2167  if (current_number != 0) return true;
2168 
2169  /* If current_number is still zero at this point, it means that not a single town has been created.
2170  * So give it a last try, but now more aggressive */
2171  if (GenerateTownName(&townnameparts) &&
2172  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2173  return true;
2174  }
2175 
2176  /* If there are no towns at all and we are generating new game, bail out */
2177  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2178  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2179  }
2180 
2181  return false; // we are still without a town? we failed, simply
2182 }
2183 
2184 
2191 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2192 {
2193  uint dist = DistanceSquare(tile, t->xy);
2194 
2195  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2196 
2197  HouseZonesBits smallest = HZB_TOWN_EDGE;
2198  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2199  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2200  }
2201 
2202  return smallest;
2203 }
2204 
2215 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2216 {
2218 
2219  assert(cc.Succeeded());
2220 
2221  IncreaseBuildingCount(t, type);
2222  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2223  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2224 
2225  MarkTileDirtyByTile(tile);
2226 }
2227 
2228 
2239 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2240 {
2241  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2242 
2243  ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2244  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2245  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2246  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2247 
2248  if (!_generating_world) FindStationsAroundTiles(TileArea(t, (size & BUILDING_2_TILES_X) ? 2 : 1, (size & BUILDING_2_TILES_Y) ? 2 : 1), &town->stations_near, false);
2249 }
2250 
2251 
2259 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2260 {
2261  /* cannot build on these slopes... */
2262  Slope slope = GetTileSlope(tile);
2263  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2264 
2265  /* at least one RoadTypes allow building the house here? */
2266  if (!RoadTypesAllowHouseHere(tile)) return false;
2267 
2268  /* building under a bridge? */
2269  if (IsBridgeAbove(tile)) return false;
2270 
2271  /* can we clear the land? */
2272  return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2273 }
2274 
2275 
2284 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2285 {
2286  if (!CanBuildHouseHere(tile, noslope)) return false;
2287 
2288  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2289  if (GetTileMaxZ(tile) != z) return false;
2290 
2291  return true;
2292 }
2293 
2294 
2303 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2304 {
2305  /* we need to check this tile too because we can be at different tile now */
2306  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2307 
2308  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2309  tile += TileOffsByDiagDir(d);
2310  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2311  }
2312 
2313  return true;
2314 }
2315 
2316 
2324 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2325 {
2326  /* Allow towns everywhere when we don't build roads */
2328 
2329  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2330 
2331  switch (t->layout) {
2332  case TL_2X2_GRID:
2333  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2334  break;
2335 
2336  case TL_3X3_GRID:
2337  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2338  break;
2339 
2340  default:
2341  break;
2342  }
2343 
2344  return true;
2345 }
2346 
2347 
2355 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2356 {
2357  /* Allow towns everywhere when we don't build roads */
2359 
2360  /* Compute relative position of tile. (Positive offsets are towards north) */
2361  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2362 
2363  switch (t->layout) {
2364  case TL_2X2_GRID:
2365  grid_pos.x %= 3;
2366  grid_pos.y %= 3;
2367  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2368  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2369  break;
2370 
2371  case TL_3X3_GRID:
2372  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2373  break;
2374 
2375  default:
2376  break;
2377  }
2378 
2379  return true;
2380 }
2381 
2382 
2392 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2393 {
2394  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2395 
2396  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2397  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2398 
2399  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2400  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2401  *tile = tile2;
2402  return true;
2403  }
2404 
2405  return false;
2406 }
2407 
2408 
2417 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2418 {
2419  TileIndex tile2 = *tile;
2420 
2421  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2422  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2423  *tile = tile2;
2424  return true;
2425  }
2426  if (d == DIAGDIR_END) break;
2427  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2428  }
2429 
2430  return false;
2431 }
2432 
2433 
2440 static bool BuildTownHouse(Town *t, TileIndex tile)
2441 {
2442  /* forbidden building here by town layout */
2443  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2444 
2445  /* no house allowed at all, bail out */
2446  if (!CanBuildHouseHere(tile, false)) return false;
2447 
2448  Slope slope = GetTileSlope(tile);
2449  int maxz = GetTileMaxZ(tile);
2450 
2451  /* Get the town zone type of the current tile, as well as the climate.
2452  * This will allow to easily compare with the specs of the new house to build */
2453  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2454 
2455  /* Above snow? */
2457  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2458 
2459  uint bitmask = (1 << rad) + (1 << (land + 12));
2460 
2461  /* bits 0-4 are used
2462  * bits 11-15 are used
2463  * bits 5-10 are not used. */
2464  HouseID houses[NUM_HOUSES];
2465  uint num = 0;
2466  uint probs[NUM_HOUSES];
2467  uint probability_max = 0;
2468 
2469  /* Generate a list of all possible houses that can be built. */
2470  for (uint i = 0; i < NUM_HOUSES; i++) {
2471  const HouseSpec *hs = HouseSpec::Get(i);
2472 
2473  /* Verify that the candidate house spec matches the current tile status */
2474  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2475 
2476  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2477  if (hs->class_id != HOUSE_NO_CLASS) {
2478  /* id_count is always <= class_count, so it doesn't need to be checked */
2479  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2480  } else {
2481  /* If the house has no class, check id_count instead */
2482  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2483  }
2484 
2485  /* Without NewHouses, all houses have probability '1' */
2486  uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2487  probability_max += cur_prob;
2488  probs[num] = cur_prob;
2489  houses[num++] = (HouseID)i;
2490  }
2491 
2492  TileIndex baseTile = tile;
2493 
2494  while (probability_max > 0) {
2495  /* Building a multitile building can change the location of tile.
2496  * The building would still be built partially on that tile, but
2497  * its northern tile would be elsewhere. However, if the callback
2498  * fails we would be basing further work from the changed tile.
2499  * So a next 1x1 tile building could be built on the wrong tile. */
2500  tile = baseTile;
2501 
2502  uint r = RandomRange(probability_max);
2503  uint i;
2504  for (i = 0; i < num; i++) {
2505  if (probs[i] > r) break;
2506  r -= probs[i];
2507  }
2508 
2509  HouseID house = houses[i];
2510  probability_max -= probs[i];
2511 
2512  /* remove tested house from the set */
2513  num--;
2514  houses[i] = houses[num];
2515  probs[i] = probs[num];
2516 
2517  const HouseSpec *hs = HouseSpec::Get(house);
2518 
2520  _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2521  continue;
2522  }
2523 
2524  if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2525 
2526  /* Special houses that there can be only one of. */
2527  uint oneof = 0;
2528 
2529  if (hs->building_flags & BUILDING_IS_CHURCH) {
2530  SetBit(oneof, TOWN_HAS_CHURCH);
2531  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2532  SetBit(oneof, TOWN_HAS_STADIUM);
2533  }
2534 
2535  if (t->flags & oneof) continue;
2536 
2537  /* Make sure there is no slope? */
2538  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2539  if (noslope && slope != SLOPE_FLAT) continue;
2540 
2541  if (hs->building_flags & TILE_SIZE_2x2) {
2542  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2543  } else if (hs->building_flags & TILE_SIZE_2x1) {
2544  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2545  } else if (hs->building_flags & TILE_SIZE_1x2) {
2546  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2547  } else {
2548  /* 1x1 house checks are already done */
2549  }
2550 
2551  byte random_bits = Random();
2552 
2554  uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2555  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2556  }
2557 
2558  /* build the house */
2559  t->cache.num_houses++;
2560 
2561  /* Special houses that there can be only one of. */
2562  t->flags |= oneof;
2563 
2564  byte construction_counter = 0;
2565  byte construction_stage = 0;
2566 
2567  if (_generating_world || _game_mode == GM_EDITOR) {
2568  uint32 r = Random();
2569 
2570  construction_stage = TOWN_HOUSE_COMPLETED;
2571  if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2572 
2573  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2574  ChangePopulation(t, hs->population);
2575  } else {
2576  construction_counter = GB(r, 2, 2);
2577  }
2578  }
2579 
2580  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2581  UpdateTownRadius(t);
2583  UpdateTownCargoes(t, tile);
2584 
2585  return true;
2586  }
2587 
2588  return false;
2589 }
2590 
2597 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2598 {
2599  assert(IsTileType(tile, MP_HOUSE));
2600  DecreaseBuildingCount(t, house);
2601  DoClearSquare(tile);
2602  DeleteAnimatedTile(tile);
2603 
2604  DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2605 }
2606 
2615 {
2616  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2617  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2618  house--;
2619  return TileDiffXY(-1, 0);
2620  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2621  house--;
2622  return TileDiffXY(0, -1);
2623  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2624  house -= 2;
2625  return TileDiffXY(-1, 0);
2626  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2627  house -= 3;
2628  return TileDiffXY(-1, -1);
2629  }
2630  }
2631  return 0;
2632 }
2633 
2634 void ClearTownHouse(Town *t, TileIndex tile)
2635 {
2636  assert(IsTileType(tile, MP_HOUSE));
2637 
2638  HouseID house = GetHouseType(tile);
2639 
2640  /* need to align the tile to point to the upper left corner of the house */
2641  tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2642 
2643  const HouseSpec *hs = HouseSpec::Get(house);
2644 
2645  /* Remove population from the town if the house is finished. */
2646  if (IsHouseCompleted(tile)) {
2647  ChangePopulation(t, -hs->population);
2648  }
2649 
2650  t->cache.num_houses--;
2651 
2652  /* Clear flags for houses that only may exist once/town. */
2653  if (hs->building_flags & BUILDING_IS_CHURCH) {
2655  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2657  }
2658 
2659  /* Do the actual clearing of tiles */
2660  uint eflags = hs->building_flags;
2661  DoClearTownHouseHelper(tile, t, house);
2662  if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2663  if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2664  if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2665 
2666  UpdateTownRadius(t);
2667 
2668  /* Update cargo acceptance. */
2669  UpdateTownCargoes(t, tile);
2670 }
2671 
2681 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2682 {
2683  Town *t = Town::GetIfValid(p1);
2684  if (t == nullptr) return CMD_ERROR;
2685 
2686  bool reset = StrEmpty(text);
2687 
2688  if (!reset) {
2690  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2691  }
2692 
2693  if (flags & DC_EXEC) {
2694  free(t->name);
2695  t->name = reset ? nullptr : stredup(text);
2696 
2697  t->UpdateVirtCoord();
2700  }
2701  return CommandCost();
2702 }
2703 
2710 {
2711  const CargoSpec *cs;
2712  FOR_ALL_CARGOSPECS(cs) {
2713  if (cs->town_effect == effect) return cs;
2714  }
2715  return nullptr;
2716 }
2717 
2729 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2730 {
2731  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2732 
2733  TownEffect te = (TownEffect)GB(p1, 16, 8);
2734  if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2735 
2736  uint16 index = GB(p1, 0, 16);
2737  Town *t = Town::GetIfValid(index);
2738  if (t == nullptr) return CMD_ERROR;
2739 
2740  /* Validate if there is a cargo which is the requested TownEffect */
2741  const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2742  if (cargo == nullptr) return CMD_ERROR;
2743 
2744  if (flags & DC_EXEC) {
2745  t->goal[te] = p2;
2746  UpdateTownGrowth(t);
2748  }
2749 
2750  return CommandCost();
2751 }
2752 
2762 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2763 {
2764  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2765  Town *t = Town::GetIfValid(p1);
2766  if (t == nullptr) return CMD_ERROR;
2767 
2768  if (flags & DC_EXEC) {
2769  free(t->text);
2770  t->text = StrEmpty(text) ? nullptr : stredup(text);
2772  }
2773 
2774  return CommandCost();
2775 }
2776 
2786 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2787 {
2788  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2789  if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2790 
2791  Town *t = Town::GetIfValid(p1);
2792  if (t == nullptr) return CMD_ERROR;
2793 
2794  if (flags & DC_EXEC) {
2795  if (p2 == 0) {
2796  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
2798  } else {
2799  uint old_rate = t->growth_rate;
2800  if (t->grow_counter >= old_rate) {
2801  /* This also catches old_rate == 0 */
2802  t->grow_counter = p2;
2803  } else {
2804  /* Scale grow_counter, so half finished houses stay half finished */
2805  t->grow_counter = t->grow_counter * p2 / old_rate;
2806  }
2807  t->growth_rate = p2;
2809  }
2810  UpdateTownGrowth(t);
2812  }
2813 
2814  return CommandCost();
2815 }
2816 
2826 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2827 {
2828  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2829  Town *t = Town::GetIfValid(p1);
2830  if (t == nullptr) return CMD_ERROR;
2831 
2832  if (flags & DC_EXEC) {
2833  /* The more houses, the faster we grow */
2834  if (p2 == 0) {
2835  uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2836  t->cache.num_houses += amount;
2837  UpdateTownRadius(t);
2838 
2839  uint n = amount * 10;
2840  do GrowTown(t); while (--n);
2841 
2842  t->cache.num_houses -= amount;
2843  } else {
2844  for (; p2 > 0; p2--) {
2845  /* Try several times to grow, as we are really suppose to grow */
2846  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2847  }
2848  }
2849  UpdateTownRadius(t);
2850 
2851  UpdateTownMaxPass(t);
2852  }
2853 
2854  return CommandCost();
2855 }
2856 
2866 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2867 {
2868  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2869  Town *t = Town::GetIfValid(p1);
2870  if (t == nullptr) return CMD_ERROR;
2871 
2872  /* Stations refer to towns. */
2873  const Station *st;
2874  FOR_ALL_STATIONS(st) {
2875  if (st->town == t) {
2876  /* Non-oil rig stations are always a problem. */
2877  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2878  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2879  CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2880  if (ret.Failed()) return ret;
2881  }
2882  }
2883 
2884  /* Depots refer to towns. */
2885  const Depot *d;
2886  FOR_ALL_DEPOTS(d) {
2887  if (d->town == t) return CMD_ERROR;
2888  }
2889 
2890  /* Check all tiles for town ownership. First check for bridge tiles, as
2891  * these do not directly have an owner so we need to check adjacent
2892  * tiles. This won't work correctly in the same loop if the adjacent
2893  * tile was already deleted earlier in the loop. */
2894  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2895  if (IsTileType(tile, MP_TUNNELBRIDGE) && TestTownOwnsBridge(tile, t)) {
2896  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2897  if (ret.Failed()) return ret;
2898  }
2899  }
2900 
2901  /* Check all remaining tiles for town ownership. */
2902  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2903  bool try_clear = false;
2904  switch (GetTileType(tile)) {
2905  case MP_ROAD:
2906  try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2907  break;
2908 
2909  case MP_HOUSE:
2910  try_clear = GetTownIndex(tile) == t->index;
2911  break;
2912 
2913  case MP_INDUSTRY:
2914  try_clear = Industry::GetByTile(tile)->town == t;
2915  break;
2916 
2917  case MP_OBJECT:
2918  if (Town::GetNumItems() == 1) {
2919  /* No towns will be left, remove it! */
2920  try_clear = true;
2921  } else {
2922  Object *o = Object::GetByTile(tile);
2923  if (o->town == t) {
2924  if (o->type == OBJECT_STATUE) {
2925  /* Statue... always remove. */
2926  try_clear = true;
2927  } else {
2928  /* Tell to find a new town. */
2929  if (flags & DC_EXEC) o->town = nullptr;
2930  }
2931  }
2932  }
2933  break;
2934 
2935  default:
2936  break;
2937  }
2938  if (try_clear) {
2939  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2940  if (ret.Failed()) return ret;
2941  }
2942  }
2943 
2944  /* The town destructor will delete the other things related to the town. */
2945  if (flags & DC_EXEC) {
2946  _town_kdtree.Remove(t->index);
2947  _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
2948  delete t;
2949  }
2950 
2951  return CommandCost();
2952 }
2953 
2959  2, 4, 9, 35, 48, 53, 117, 175
2960 };
2961 
2962 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2963 {
2964  if (flags & DC_EXEC) {
2965  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2966  }
2967  return CommandCost();
2968 }
2969 
2970 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2971 {
2972  if (flags & DC_EXEC) {
2973  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2974  }
2975  return CommandCost();
2976 }
2977 
2978 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2979 {
2980  if (flags & DC_EXEC) {
2981  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2982  }
2983  return CommandCost();
2984 }
2985 
2986 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2987 {
2988  /* Check if the company is allowed to fund new roads. */
2990 
2991  if (flags & DC_EXEC) {
2992  t->road_build_months = 6;
2993 
2994  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2996  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2997 
2998  char *cn = stredup(company_name);
2999  SetDParam(0, t->index);
3000  SetDParamStr(1, cn);
3001 
3002  AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
3003  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3004  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3005  }
3006  return CommandCost();
3007 }
3008 
3014 static bool TryClearTile(TileIndex tile)
3015 {
3016  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3018  cur_company.Restore();
3019  return r.Succeeded();
3020 }
3021 
3026 
3027  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
3028 };
3029 
3036 static bool SearchTileForStatue(TileIndex tile, void *user_data)
3037 {
3038  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3039 
3040  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
3041  statue_data->tile_count++;
3042 
3043  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3044  if (IsSteepSlope(GetTileSlope(tile))) return false;
3045  /* Don't build statues under bridges. */
3046  if (IsBridgeAbove(tile)) return false;
3047 
3048  /* A clear-able open space is always preferred. */
3049  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
3050  statue_data->best_position = tile;
3051  return true;
3052  }
3053 
3054  bool house = IsTileType(tile, MP_HOUSE);
3055 
3056  /* Searching inside the inner circle. */
3057  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
3058  /* Save first house in inner circle. */
3059  if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
3060  statue_data->best_position = tile;
3061  }
3062 
3063  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3064  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
3065  }
3066 
3067  /* Searching outside the circle, just pick the first possible spot. */
3068  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
3069  return house && TryClearTile(tile);
3070 }
3071 
3080 {
3081  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
3082 
3083  TileIndex tile = t->xy;
3084  StatueBuildSearchData statue_data(INVALID_TILE, 0);
3085  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3086 
3087  if (flags & DC_EXEC) {
3088  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3089  DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
3090  cur_company.Restore();
3092  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
3093  MarkTileDirtyByTile(statue_data.best_position);
3094  }
3095  return CommandCost();
3096 }
3097 
3098 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
3099 {
3100  /* Check if it's allowed to buy the rights */
3102 
3103  if (flags & DC_EXEC) {
3104  /* And grow for 3 months */
3105  t->fund_buildings_months = 3;
3106 
3107  /* Enable growth (also checking GameScript's opinion) */
3108  UpdateTownGrowth(t);
3109 
3110  /* Build a new house, but add a small delay to make sure
3111  * that spamming funding doesn't let town grow any faster
3112  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3113  * Also emulate original behaviour when town was only growing in
3114  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3115  * tick-perfect and gives player some time window where he can
3116  * spam funding with the exact same efficiency.
3117  */
3119 
3121  }
3122  return CommandCost();
3123 }
3124 
3125 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
3126 {
3127  /* Check if it's allowed to buy the rights */
3129 
3130  if (flags & DC_EXEC) {
3131  t->exclusive_counter = 12;
3133 
3134  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3135 
3137 
3138  /* Spawn news message */
3139  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
3141  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3142  SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
3143  SetDParam(2, t->index);
3144  SetDParamStr(3, cni->company_name);
3145  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3146  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3147  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3148  }
3149  return CommandCost();
3150 }
3151 
3152 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
3153 {
3154  if (flags & DC_EXEC) {
3155  if (Chance16(1, 14)) {
3156  /* set as unwanted for 6 months */
3157  t->unwanted[_current_company] = 6;
3158 
3159  /* set all close by station ratings to 0 */
3160  Station *st;
3161  FOR_ALL_STATIONS(st) {
3162  if (st->town == t && st->owner == _current_company) {
3163  for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
3164  }
3165  }
3166 
3167  /* only show error message to the executing player. All errors are handled command.c
3168  * but this is special, because it can only 'fail' on a DC_EXEC */
3169  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3170 
3171  /* decrease by a lot!
3172  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3173  * be independent of any cheat settings
3174  */
3175  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3176  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3178  }
3179  } else {
3180  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3181  }
3182  }
3183  return CommandCost();
3184 }
3185 
3186 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3187 static TownActionProc * const _town_action_proc[] = {
3188  TownActionAdvertiseSmall,
3189  TownActionAdvertiseMedium,
3190  TownActionAdvertiseLarge,
3191  TownActionRoadRebuild,
3193  TownActionFundBuildings,
3194  TownActionBuyRights,
3195  TownActionBribe
3196 };
3197 
3205 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3206 {
3207  int num = 0;
3208  TownActions buttons = TACT_NONE;
3209 
3210  /* Spectators and unwanted have no options */
3211  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3212 
3213  /* Things worth more than this are not shown */
3214  Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3215 
3216  /* Check the action bits for validity and
3217  * if they are valid add them */
3218  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3219  const TownActions cur = (TownActions)(1 << i);
3220 
3221  /* Is the company not able to bribe ? */
3222  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3223 
3224  /* Is the company not able to buy exclusive rights ? */
3225  if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3226 
3227  /* Is the company not able to fund buildings ? */
3228  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3229 
3230  /* Is the company not able to fund local road reconstruction? */
3231  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3232 
3233  /* Is the company not able to build a statue ? */
3234  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3235 
3236  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3237  buttons |= cur;
3238  num++;
3239  }
3240  }
3241  }
3242 
3243  if (nump != nullptr) *nump = num;
3244  return buttons;
3245 }
3246 
3258 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3259 {
3260  Town *t = Town::GetIfValid(p1);
3261  if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3262 
3263  if (!HasBit(GetMaskOfTownActions(nullptr, _current_company, t), p2)) return CMD_ERROR;
3264 
3265  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3266 
3267  CommandCost ret = _town_action_proc[p2](t, flags);
3268  if (ret.Failed()) return ret;
3269 
3270  if (flags & DC_EXEC) {
3272  }
3273 
3274  return cost;
3275 }
3276 
3277 template <typename Func>
3278 static void ForAllStationsNearTown(Town *t, Func func)
3279 {
3280  /* Ideally the search radius should be close to the actual town zone 0 radius.
3281  * The true radius is not stored or calculated anywhere, only the squared radius. */
3282  /* The efficiency of this search might be improved for large towns and many stations on the map,
3283  * by using an integer square root approximation giving a value not less than the true square root. */
3284  uint search_radius = t->cache.squared_town_zone_radius[0] / 2;
3285  ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3286  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3287  func(st);
3288  }
3289  });
3290 }
3291 
3292 static void UpdateTownRating(Town *t)
3293 {
3294  /* Increase company ratings if they're low */
3295  const Company *c;
3296  FOR_ALL_COMPANIES(c) {
3297  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3299  }
3300  }
3301 
3302  ForAllStationsNearTown(t, [&](const Station *st) {
3303  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3304  if (Company::IsValidID(st->owner)) {
3305  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3306  t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3307  }
3308  } else {
3309  if (Company::IsValidID(st->owner)) {
3310  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3311  t->ratings[st->owner] = max(new_rating, INT16_MIN);
3312  }
3313  }
3314  });
3315 
3316  /* clamp all ratings to valid values */
3317  for (uint i = 0; i < MAX_COMPANIES; i++) {
3318  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3319  }
3320 
3322 }
3323 
3324 
3331 static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
3332 {
3333  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3334  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3336  return;
3337  }
3338  t->grow_counter = RoundDivSU((uint32)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3339 }
3340 
3347 {
3348  int n = 0;
3349  ForAllStationsNearTown(t, [&](const Station * st) {
3350  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3351  n++;
3352  }
3353  });
3354  return n;
3355 }
3356 
3363 static uint GetNormalGrowthRate(Town *t)
3364 {
3365  static const uint16 _grow_count_values[2][6] = {
3366  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3367  { 320, 420, 300, 220, 160, 100 } // Normal values
3368  };
3369 
3370  int n = CountActiveStations(t);
3371  uint16 m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][min(n, 5)];
3372 
3373  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3374 
3375  m >>= growth_multiplier;
3376  if (t->larger_town) m /= 2;
3377 
3378  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3379 }
3380 
3386 {
3387  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3388  uint old_rate = t->growth_rate;
3390  UpdateTownGrowCounter(t, old_rate);
3392 }
3393 
3398 static void UpdateTownGrowth(Town *t)
3399 {
3401 
3404 
3405  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3406 
3407  if (t->fund_buildings_months == 0) {
3408  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3409  for (int i = TE_BEGIN; i < TE_END; i++) {
3410  switch (t->goal[i]) {
3411  case TOWN_GROWTH_WINTER:
3412  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3413  break;
3414  case TOWN_GROWTH_DESERT:
3415  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3416  break;
3417  default:
3418  if (t->goal[i] > t->received[i].old_act) return;
3419  break;
3420  }
3421  }
3422  }
3423 
3424  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3427  return;
3428  }
3429 
3430  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3431 
3434 }
3435 
3436 static void UpdateTownAmounts(Town *t)
3437 {
3438  for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3439  for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3440  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3441 
3443 }
3444 
3445 static void UpdateTownUnwanted(Town *t)
3446 {
3447  const Company *c;
3448 
3449  FOR_ALL_COMPANIES(c) {
3450  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3451  }
3452 }
3453 
3461 {
3463 
3465  if (t == nullptr) return CommandCost();
3466 
3467  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3468 
3469  SetDParam(0, t->index);
3470  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3471 }
3472 
3482 {
3483  if (Town::GetNumItems() == 0) return nullptr;
3484 
3485  TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
3486  Town *town = Town::Get(tid);
3487  if (DistanceManhattan(tile, town->xy) < threshold) return town;
3488  return nullptr;
3489 }
3490 
3499 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3500 {
3501  switch (GetTileType(tile)) {
3502  case MP_ROAD:
3503  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3504 
3505  if (!HasTownOwnedRoad(tile)) {
3506  TownID tid = GetTownIndex(tile);
3507 
3508  if (tid == INVALID_TOWN) {
3509  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3510  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3511  assert(Town::GetNumItems() == 0);
3512  return nullptr;
3513  }
3514 
3515  assert(Town::IsValidID(tid));
3516  Town *town = Town::Get(tid);
3517 
3518  if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3519 
3520  return town;
3521  }
3522  FALLTHROUGH;
3523 
3524  case MP_HOUSE:
3525  return Town::GetByTile(tile);
3526 
3527  default:
3528  return CalcClosestTownFromTile(tile, threshold);
3529  }
3530 }
3531 
3532 static bool _town_rating_test = false;
3534 
3540 void SetTownRatingTestMode(bool mode)
3541 {
3542  static int ref_count = 0; // Number of times test-mode is switched on.
3543  if (mode) {
3544  if (ref_count == 0) {
3545  _town_test_ratings.clear();
3546  }
3547  ref_count++;
3548  } else {
3549  assert(ref_count > 0);
3550  ref_count--;
3551  }
3552  _town_rating_test = !(ref_count == 0);
3553 }
3554 
3560 static int GetRating(const Town *t)
3561 {
3562  if (_town_rating_test) {
3563  SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3564  if (it != _town_test_ratings.End()) {
3565  return it->second;
3566  }
3567  }
3568  return t->ratings[_current_company];
3569 }
3570 
3579 {
3580  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3581  if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3583  (_cheats.magic_bulldozer.value && add < 0)) {
3584  return;
3585  }
3586 
3587  int rating = GetRating(t);
3588  if (add < 0) {
3589  if (rating > max) {
3590  rating += add;
3591  if (rating < max) rating = max;
3592  }
3593  } else {
3594  if (rating < max) {
3595  rating += add;
3596  if (rating > max) rating = max;
3597  }
3598  }
3599  if (_town_rating_test) {
3600  _town_test_ratings[t] = rating;
3601  } else {
3603  t->ratings[_current_company] = rating;
3605  }
3606 }
3607 
3616 {
3617  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3618  if (t == nullptr || !Company::IsValidID(_current_company) ||
3620  return CommandCost();
3621  }
3622 
3623  /* minimum rating needed to be allowed to remove stuff */
3624  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3625  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3629  };
3630 
3631  /* check if you're allowed to remove the road/bridge/tunnel
3632  * owned by a town no removal if rating is lower than ... depends now on
3633  * difficulty setting. Minimum town rating selected by difficulty level
3634  */
3635  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3636 
3637  if (GetRating(t) < needed) {
3638  SetDParam(0, t->index);
3639  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3640  }
3641 
3642  return CommandCost();
3643 }
3644 
3645 void TownsMonthlyLoop()
3646 {
3647  Town *t;
3648 
3649  FOR_ALL_TOWNS(t) {
3650  if (t->road_build_months != 0) t->road_build_months--;
3651 
3652  if (t->exclusive_counter != 0) {
3653  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3654  }
3655 
3656  UpdateTownAmounts(t);
3657  UpdateTownGrowth(t);
3658  UpdateTownRating(t);
3659  UpdateTownUnwanted(t);
3660  UpdateTownCargoes(t);
3661  }
3662 
3664 }
3665 
3666 void TownsYearlyLoop()
3667 {
3668  /* Increment house ages */
3669  for (TileIndex t = 0; t < MapSize(); t++) {
3670  if (!IsTileType(t, MP_HOUSE)) continue;
3671  IncrementHouseAge(t);
3672  }
3673 }
3674 
3675 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3676 {
3677  if (AutoslopeEnabled()) {
3678  HouseID house = GetHouseType(tile);
3679  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3680  const HouseSpec *hs = HouseSpec::Get(house);
3681 
3682  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3683  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3684  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3685  bool allow_terraform = true;
3686 
3687  /* Call the autosloping callback per tile, not for the whole building at once. */
3688  house = GetHouseType(tile);
3689  hs = HouseSpec::Get(house);
3691  /* If the callback fails, allow autoslope. */
3692  uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3693  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3694  }
3695 
3696  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3697  }
3698  }
3699 
3700  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3701 }
3702 
3704 extern const TileTypeProcs _tile_type_town_procs = {
3705  DrawTile_Town, // draw_tile_proc
3706  GetSlopePixelZ_Town, // get_slope_z_proc
3707  ClearTile_Town, // clear_tile_proc
3708  AddAcceptedCargo_Town, // add_accepted_cargo_proc
3709  GetTileDesc_Town, // get_tile_desc_proc
3710  GetTileTrackStatus_Town, // get_tile_track_status_proc
3711  nullptr, // click_tile_proc
3712  AnimateTile_Town, // animate_tile_proc
3713  TileLoop_Town, // tile_loop_proc
3714  ChangeTileOwner_Town, // change_tile_owner_proc
3715  AddProducedCargo_Town, // add_produced_cargo_proc
3716  nullptr, // vehicle_enter_tile_proc
3717  GetFoundation_Town, // get_foundation_proc
3718  TerraformTile_Town, // terraform_tile_proc
3719 };
3720 
3721 
3722 HouseSpec _house_specs[NUM_HOUSES];
3723 
3724 void ResetHouses()
3725 {
3726  memset(&_house_specs, 0, sizeof(_house_specs));
3727  memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3728 
3729  /* Reset any overrides that have been set. */
3730  _house_mngr.ResetOverride();
3731 }
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:113
Functions related to OTTD&#39;s strings.
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:98
Owner
Enum for all companies/owners.
Definition: company_type.h:20
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:36
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:89
byte type
Type of this airport,.
Definition: station_base.h:311
the north corner of the tile is raised
Definition: slope_type.h:55
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:437
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
Source/destination is a town.
Definition: cargo_type.h:150
StationFacility facilities
The facilities that this station has.
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:39
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:157
There can be only one stadium by town.
Definition: town.h:179
static Year GetHouseAge(TileIndex t)
Get the age of the house.
Definition: town_map.h:251
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:119
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:81
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:143
static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total=true)
Update accepted town cargoes around a specific tile.
Definition: town_cmd.cpp:796
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:257
static void ChangePopulation(Town *t, int mod)
Change the towns population.
Definition: town_cmd.cpp:423
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1829
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1110
Number of town layouts.
Definition: town_type.h:89
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1277
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:240
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:891
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:80
Geometric 2x2 grid algorithm.
Definition: town_type.h:84
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:44
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:25
CompanyMask statues
which companies have a statue?
Definition: town.h:70
south and east corner are raised
Definition: slope_type.h:59
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1172
bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:84
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:174
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:2139
the west corner of the tile is raised
Definition: slope_type.h:52
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3199
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:73
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:2215
TownLayout layout
tells us what kind of town we&#39;re building
Definition: town_cmd.cpp:2014
Part of an industry.
Definition: tile_type.h:51
RoadBits GetAnyRoadBits(TileIndex tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:35
EconomySettings economy
settings to change the economy
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:50
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:156
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
Money GetAvailableMoneyForCommand()
Definition: command.cpp:521
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:2355
Functions related to dates.
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Town * town
Town the object is built in.
Definition: object_base.h:27
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:98
Northwest.
Basic road type.
Definition: road_type.h:29
Random town layout.
Definition: town_type.h:87
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:2324
Town * town
Nearest town.
Definition: industry.h:44
static bool HasTileRoadType(TileIndex t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:212
Used for iterations.
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:3024
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:409
byte flags
See TownFlags.
Definition: town.h:66
terraform a tile
Definition: command_type.h:188
uint8 unwanted[MAX_COMPANIES]
how many months companies aren&#39;t wanted by towns (bribe)
Definition: town.h:74
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:126
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3398
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:3532
A tile with road (or tram tracks)
Definition: tile_type.h:45
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:25
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:47
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:20
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
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:124
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:61
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:109
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:26
CargoTypes cargo_produced
Bitmap of all cargoes produced by houses in this town.
Definition: town.h:88
Used for iterations.
Definition: road_type.h:31
Specification of a cargo type.
Definition: cargotype.h:57
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:3385
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:385
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition: station.cpp:402
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:110
bool GenerateTownName(uint32 *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:122
static bool HasTileWaterGround(TileIndex t)
Checks whether the tile has water at the ground.
Definition: water_map.h:346
TownLayout
Town Layouts.
Definition: town_type.h:80
Build a statue.
Definition: town.h:218
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:354
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:207
South-west part.
Definition: road_type.h:58
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:112
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:384
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:162
Base for all depots (except hangars)
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:29
Opening of industries.
Definition: news_type.h:28
Defines the internal data of a functional industry.
Definition: industry.h:42
static SmallMap< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3533
demolish a tile
Definition: command_type.h:182
Tile description for the &#39;land area information&#39; tool.
Definition: tile_cmd.h:53
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:263
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
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:2303
the east corner of the tile is raised
Definition: slope_type.h:54
flag for invalid roadtype
Definition: road_type.h:32
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:382
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:38
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:104
Declarations for accessing the k-d tree of stations.
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:93
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Do a town action.
Definition: town_cmd.cpp:3258
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:269
Cargo behaves water-like.
Definition: cargotype.h:32
build a "half" road
Definition: command_type.h:203
Other expenses.
Definition: economy_type.h:163
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:2011
void NewMonth()
Update stats for a new month.
Definition: town_type.h:123
TownLayout town_layout
select town layout,
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else) ...
Definition: town_cmd.cpp:396
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:150
A railway.
Definition: tile_type.h:44
Called to determine which cargoes a town building should accept.
byte dist_local_authority
distance for town local authority, default 20
Functions related to world/map generation.
initial rating
Definition: town_type.h:46
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:84
Contains objects such as transmitters and owned land.
Definition: tile_type.h:53
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2440
Construction costs.
Definition: economy_type.h:151
south and west corner are raised
Definition: slope_type.h:58
Common return value for all commands.
Definition: command_type.h:25
static bool LiftHasDestination(TileIndex t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:84
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:225
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport.cpp:1444
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:117
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:386
RoadType
The different roadtypes we support.
Definition: road_type.h:27
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
static bool IsDriveThroughStopTile(TileIndex t)
Is tile t a drive through road stop station?
Definition: station_map.h:235
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:249
Town * town
The town this station is associated with.
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:15
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:47
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:75
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1604
Tstorage new_act
Actually transported this month.
Definition: town_type.h:118
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:102
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:2072
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:153
a flat tile
Definition: slope_type.h:51
int z
Height.
Definition: tile_cmd.h:49
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:481
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
static byte GetLiftDestination(TileIndex t)
Get the current destination for this lift.
Definition: town_map.h:106
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:83
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:31
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:472
Forbidden.
Definition: town_type.h:96
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:64
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
static int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:338
North.
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:939
Rebuild the roads.
Definition: town.h:217
this house will only appear during town generation in random games, thus the historical ...
Definition: house.h:92
north and east corner are raised
Definition: slope_type.h:60
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2597
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:112
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
Called to determine the type (if any) of foundation to draw for house tile.
Functions related to (drawing on) viewports.
Pseudo random number generator.
char company_name[64]
The name of the company.
Definition: news_type.h:151
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:104
static byte GetHouseBuildingStage(TileIndex t)
House Construction Scheme.
Definition: town_map.h:185
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:81
Invalid cargo type.
Definition: cargo_type.h:70
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:3460
static bool IsHouseCompleted(TileIndex t)
Get the completion of this house.
Definition: town_map.h:147
int16 y
The y value of the coordinate.
Definition: map_type.h:61
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:61
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:2826
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:334
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:87
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:163
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:266
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:47
TownActions
Town actions of a company.
Definition: town.h:211
Bit number for setting this roadtype as not house friendly.
Definition: road.h:43
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:91
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
town buildings
Definition: transparency.h:27
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:216
static void DrawTile_Town(TileInfo *ti)
House Tile drawing handler.
Definition: town_cmd.cpp:255
static uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:336
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:2013
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:1152
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:281
90 degrees right
static byte GetHouseConstructionTick(TileIndex t)
Gets the construction stage of a house.
Definition: town_map.h:197
void FindStationsAroundTiles(const TileArea &location, StationList *const stations, bool use_nearby)
Find all stations around a rectangular producer (industry, house, headquarter, ...)
Tile animation!
static const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:226
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:78
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:26
Functions related to low-level strings.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:20
static RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:98
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:45
None of the directions are disallowed.
Definition: road_map.h:288
byte rating
Station rating for this cargo.
Definition: station_base.h:237
The tile has no ownership.
Definition: company_type.h:27
Full 4-way crossing.
Definition: road_type.h:69
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:343
static void RemoveNearbyStations(Town *t)
Remove stations from nearby station list if a town is no longer in the catchment area of each...
Definition: town_cmd.cpp:450
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:98
Foundation
Enumeration for Foundations.
Definition: slope_type.h:95
Types related to cheating.
Bit number for allowing towns to build this roadtype.
Definition: road.h:45
TileIndex xy
town center tile
Definition: town.h:56
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:1737
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:108
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:152
Southeast.
ViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:48
static CommandCost TownCanBePlacedHere(TileIndex tile)
Checks if it&#39;s possible to place a town at given tile.
Definition: town_cmd.cpp:1819
TileIndex tile
Tile index.
Definition: tile_cmd.h:48
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:2417
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:443
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:2284
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:3499
The tile is leveled up to a flat slope.
Definition: slope_type.h:97
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:2392
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:245
TownSize
Supported initial town sizes.
Definition: town_type.h:21
The client is spectating.
Definition: company_type.h:37
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:267
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:121
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3578
Information about GRF, used in the game and (part of it) in savegames.
Original algorithm (quadratic cargo by population)
Definition: town_type.h:105
Simple pair of data.
static bool IsUniqueTownName(const char *name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:1844
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:77
Generate towns.
Definition: genworld.h:74
Fund new buildings.
Definition: town.h:219
static bool HasTownOwnedRoad(TileIndex t)
Checks if given tile has town owned road.
Definition: road_map.h:281
East.
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:24
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
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:80
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:152
rating needed, "Permissive" difficulty settings
Definition: town_type.h:68
General news (from towns)
Definition: news_type.h:38
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3363
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:54
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:159
Road at the two southern edges.
Definition: road_type.h:66
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:42
Map accessors for object tiles.
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:260
A number of safeguards to prevent using unsafe methods.
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:91
Road at the two eastern edges.
Definition: road_type.h:65
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:20
int16 x
The x value of the coordinate.
Definition: map_type.h:60
Number of available town sizes.
Definition: town_type.h:27
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:260
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:188
Water tile.
Definition: tile_type.h:49
Allowed, with custom town layout.
Definition: town_type.h:98
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:46
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding roads allows to build a house here.
Definition: town_cmd.cpp:1236
static byte GetLiftPosition(TileIndex t)
Get the position of the lift on this animated house.
Definition: town_map.h:127
static bool IsRoadDepotTile(TileIndex t)
Return whether a tile is a road depot tile.
Definition: road_map.h:117
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:55
Geometric 3x3 grid algorithm.
Definition: town_type.h:85
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:51
An object, such as transmitter, on the map.
Definition: object_base.h:25
rating needed, "Permissive" difficulty settings
Definition: town_type.h:61
Bit-counted algorithm (normal distribution from individual house population)
Definition: town_type.h:106
Empty reference.
Definition: news_type.h:52
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
No road-part is build.
Definition: road_type.h:56
void UpdateTownCargoBitmap()
Updates the bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:845
bool fund_roads
allow funding local road reconstruction
Represents the covered area of e.g.
Definition: tilearea_type.h:18
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
delete a town
Definition: command_type.h:269
Number of available town actions.
Definition: town.h:223
CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the growth rate of the town.
Definition: town_cmd.cpp:2786
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:83
Normal news item. (Newspaper with text only)
Definition: news_type.h:80
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:55
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:2033
uint16 max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:141
North-east part.
Definition: road_type.h:60
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:210
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:437
South.
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:116
This structure is the same for both Industries and Houses.
Definition: sprite.h:69
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:212
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1618
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:1940
static DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:60
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2614
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:3023
Station view; Window numbers:
Definition: window_type.h:340
StringID building_name
building name
Definition: house.h:106
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:89
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:2866
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
bit mask containing all &#39;simple&#39; slopes
Definition: slope_type.h:63
static uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:318
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:186
CargoTypes _town_cargoes_accepted
Bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:60
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:471
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:371
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
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:90
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:95
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition: road.cpp:49
Functions related to autoslope.
Year max_year
last year it can be built
Definition: house.h:103
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:62
byte number_towns
the amount of towns
Definition: settings_type.h:57
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:18
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:46
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:219
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Returns "growth" if a house was built, or no if the build failed.
Definition: town_cmd.cpp:1522
bool build_on_slopes
allow building on slopes
bool Failed() const
Did this command fail?
Definition: command_type.h:161
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:2191
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:111
a steep slope falling to east (from west)
Definition: slope_type.h:68
static Axis GetBridgeAxis(TileIndex t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:70
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:661
uint8 town_growth_rate
town growth rate
bool has_newhouses
Set if there are any newhouses loaded.
Definition: newgrf.h:179
Empty action set.
Definition: town.h:212
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:35
static void SetRoadOwner(TileIndex t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:252
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3481
Number of town checking action types.
Definition: town.h:160
Base class for all pools.
Definition: pool_type.hpp:83
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
North-west part.
Definition: road_type.h:57
static bool IsSea(TileIndex t)
Is it a sea water tile?
Definition: water_map.h:154
Company news item. (Newspaper with face)
Definition: news_type.h:82
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:973
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:59
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:3025
uint16 override
id of the entity been replaced by
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:64
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:342
A pair-construct of a TileIndexDiff.
Definition: map_type.h:59
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:226
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1146
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:2239
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:489
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Definition: map_func.h:232
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:83
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:31
execute the given command
Definition: command_type.h:346
Station with an airport.
Definition: station_type.h:57
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:424
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:225
static void MakeSingleHouseBigger(TileIndex tile)
Helper function for house completion stages progression.
Definition: town_cmd.cpp:466
CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2729
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:37
static Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:258
uint16 growth_rate
town growth rate
Definition: town.h:96
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:3079
static void HaltLift(TileIndex t)
Stop the lift of this animated house from moving.
Definition: town_map.h:117
An invalid company.
Definition: company_type.h:32
Tile got trees.
Definition: tile_type.h:47
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:1480
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:115
static uint MapSize()
Get the size of the map.
Definition: map_func.h:94
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:68
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:83
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
Used for iterations.
Definition: road_type.h:28
TownLayout layout
town specific road layout
Definition: town.h:102
static bool IsNormalRoadTile(TileIndex t)
Return whether a tile is a normal road tile.
Definition: road_map.h:75
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:504
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:178
Town authority; Window numbers:
Definition: window_type.h:189
GUISettings gui
settings related to the GUI
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:52
HouseExtraFlags extra_flags
some more flags
Definition: house.h:120
Invisible tiles at the SW and SE border.
Definition: tile_type.h:50
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:57
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:19
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:143
static void SetLiftPosition(TileIndex t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:137
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:312
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:119
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:147
Oilrig airport.
Definition: airport.h:40
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
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:159
Cargo support for NewGRFs.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3560
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:276
static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the nearest land tile.
Definition: town_cmd.cpp:2055
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:124
Buy exclusive transport rights.
Definition: town.h:220
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:107
static HouseID GetHouseType(TileIndex t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:61
north and west corner are raised
Definition: slope_type.h:57
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:217
Random size, bigger than small, smaller than large.
Definition: town_type.h:25
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:29
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:71
Date introduction_date
Introduction date.
Definition: road.h:165
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:96
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3615
TileArea location
Location of the object.
Definition: object_base.h:28
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:36
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:26
Slope
Enumeration for the slope-type.
Definition: slope_type.h:50
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Checks if a house can be built here.
Definition: town_cmd.cpp:2259
Town view; Window numbers:
Definition: window_type.h:328
Growth rate is controlled by GS.
Definition: town.h:180
A tile of a station.
Definition: tile_type.h:48
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:2958
TownCache cache
Container for all cacheable data.
Definition: town.h:58
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:30
Maximum number of companies.
Definition: company_type.h:25
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:386
Town data structure.
Definition: town.h:55
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:1051
#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:76
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
Transport by road vehicle.
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:38
Functions related to OTTD&#39;s landscape.
static void ResetHouseAge(TileIndex t)
Sets the age of the house to zero.
Definition: town_map.h:228
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:34
Functions related to commands.
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:82
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:101
char * name
Custom town name. If nullptr, the town was not renamed and uses the generated name.
Definition: town.h:64
Coordinates of a point in 2D.
a steep slope falling to south (from north)
Definition: slope_type.h:71
Large town.
Definition: town_type.h:24
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
Struct holding parameters used to generate town name.
Definition: townname_type.h:29
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:577
Owner owner
The owner of this station.
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:646
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:235
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:31
decides if default foundations need to be drawn
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:52
build a bridge
Definition: command_type.h:183
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:33
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:110
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:85
static bool TryClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:3014
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:19
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:181
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1821
Base of all industries.
static DisallowedRoadDirections GetDisallowedRoadDirections(TileIndex t)
Gets the disallowed directions.
Definition: road_map.h:303
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:372
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:817
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:116
Airport airport
Tile area the airport covers.
Definition: station_base.h:466
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:54
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:23
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3205
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback routine.
Definition: town_cmd.cpp:310
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:221
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:698
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:1981
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:85
Base of the town class.
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:2012
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3346
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:79
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:43
int _nb_orig_names
Number of original town names.
A house by a town.
Definition: tile_type.h:46
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:62
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
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:176
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:61
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:115
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:105
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:46
a steep slope falling to west (from east)
Definition: slope_type.h:70
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:78
void UpdateTownCargoTotal(Town *t)
Update the total cargo acceptance of the whole town.
Definition: town_cmd.cpp:778
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:177
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:246
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:25
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:3036
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3227
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:191
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:102
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:2762
byte road_build_months
fund road reconstruction in action?
Definition: town.h:99
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename a town (server-only).
Definition: town_cmd.cpp:2681
Base classes/functions for stations.
static void SetTownIndex(TileIndex t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:36
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:28
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:100
CompanyID exclusivity
which company has exclusivity
Definition: town.h:75
bool allow_town_level_crossings
towns are allowed to build level crossings
the south corner of the tile is raised
Definition: slope_type.h:53
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:95
The object is owned by a superuser / goal script.
Definition: company_type.h:29
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:215
Station data structure.
Definition: station_base.h:452
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:50
static bool IsRoadDepot(TileIndex t)
Return whether a tile is a road depot.
Definition: road_map.h:107
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:1867
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:1999
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:165
static TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:318
static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3331
static void IncrementHouseAge(TileIndex t)
Increments the age of the house.
Definition: town_map.h:239
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2709
a steep slope falling to north (from south)
Definition: slope_type.h:69
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:3300
RoadTypeLabel label
Unique 32 bit road type identifier.
Definition: road.h:146
Tstorage old_act
Actually transported last month.
Definition: town_type.h:117
CompanyMask have_ratings
which companies have a rating
Definition: town.h:73
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:660
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1459
Southwest.
Cheats _cheats
All the cheats.
Definition: cheat.cpp:18
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:306
Road at the two northern edges.
Definition: road_type.h:64
Road at the two western edges.
Definition: road_type.h:67
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:201
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:26
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:3540