OpenTTD
town_cmd.cpp
Go to the documentation of this file.
1 /* $Id: town_cmd.cpp 27273 2015-05-08 17:37:48Z frosch $ */
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_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
49 
50 #include "table/strings.h"
51 #include "table/town_land.h"
52 
53 #include "safeguards.h"
54 
55 TownID _new_town_id;
57 
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
61 
63 {
64  free(this->name);
65  free(this->text);
66 
67  if (CleaningPool()) return;
68 
69  /* Delete town authority window
70  * and remove from list of sorted towns */
71  DeleteWindowById(WC_TOWN_VIEW, this->index);
72 
73  /* Check no industry is related to us. */
74  const Industry *i;
75  FOR_ALL_INDUSTRIES(i) assert(i->town != this);
76 
77  /* ... and no object is related to us. */
78  const Object *o;
79  FOR_ALL_OBJECTS(o) assert(o->town != this);
80 
81  /* Check no tile is related to us. */
82  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83  switch (GetTileType(tile)) {
84  case MP_HOUSE:
85  assert(GetTownIndex(tile) != this->index);
86  break;
87 
88  case MP_ROAD:
89  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90  break;
91 
92  case MP_TUNNELBRIDGE:
93  assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94  break;
95 
96  default:
97  break;
98  }
99  }
100 
101  /* Clear the persistent storage list. */
102  this->psa_list.clear();
103 
104  DeleteSubsidyWith(ST_TOWN, this->index);
108 }
109 
110 
116 void Town::PostDestructor(size_t index)
117 {
120 
121  /* Give objects a new home! */
122  Object *o;
123  FOR_ALL_OBJECTS(o) {
124  if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
125  }
126 }
127 
132 {
133  if (layout != TL_RANDOM) {
134  this->layout = layout;
135  return;
136  }
137 
138  this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
139 }
140 
145 /* static */ Town *Town::GetRandom()
146 {
147  if (Town::GetNumItems() == 0) return NULL;
148  int num = RandomRange((uint16)Town::GetNumItems());
149  size_t index = MAX_UVALUE(size_t);
150 
151  while (num >= 0) {
152  num--;
153  index++;
154 
155  /* Make sure we have a valid town */
156  while (!Town::IsValidID(index)) {
157  index++;
158  assert(index < Town::GetPoolSize());
159  }
160  }
161 
162  return Town::Get(index);
163 }
164 
170 {
171  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
172 }
173 
174 /* Local */
175 static int _grow_town_result;
176 
177 /* Describe the possible states */
178 enum TownGrowthResult {
179  GROWTH_SUCCEED = -1,
180  GROWTH_SEARCH_STOPPED = 0
181 // GROWTH_SEARCH_RUNNING >= 1
182 };
183 
184 static bool BuildTownHouse(Town *t, TileIndex tile);
185 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
186 
187 static void TownDrawHouseLift(const TileInfo *ti)
188 {
189  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
190 }
191 
192 typedef void TownDrawTileProc(const TileInfo *ti);
193 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
194  TownDrawHouseLift
195 };
196 
203 {
204  return (DiagDirection)(3 & Random());
205 }
206 
212 static void DrawTile_Town(TileInfo *ti)
213 {
214  HouseID house_id = GetHouseType(ti->tile);
215 
216  if (house_id >= NEW_HOUSE_OFFSET) {
217  /* Houses don't necessarily need new graphics. If they don't have a
218  * spritegroup associated with them, then the sprite for the substitute
219  * house id is drawn instead. */
220  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
221  DrawNewHouseTile(ti, house_id);
222  return;
223  } else {
224  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
225  }
226  }
227 
228  /* Retrieve pointer to the draw town tile struct */
229  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
230 
232 
233  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
234 
235  /* If houses are invisible, do not draw the upper part */
236  if (IsInvisibilitySet(TO_HOUSES)) return;
237 
238  /* Add a house on top of the ground? */
239  SpriteID image = dcts->building.sprite;
240  if (image != 0) {
241  AddSortableSpriteToDraw(image, dcts->building.pal,
242  ti->x + dcts->subtile_x,
243  ti->y + dcts->subtile_y,
244  dcts->width,
245  dcts->height,
246  dcts->dz,
247  ti->z,
249  );
250 
251  if (IsTransparencySet(TO_HOUSES)) return;
252  }
253 
254  {
255  int proc = dcts->draw_proc - 1;
256 
257  if (proc >= 0) _town_draw_tile_procs[proc](ti);
258  }
259 }
260 
261 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
262 {
263  return GetTileMaxPixelZ(tile);
264 }
265 
268 {
269  HouseID hid = GetHouseType(tile);
270 
271  /* For NewGRF house tiles we might not be drawing a foundation. We need to
272  * account for this, as other structures should
273  * draw the wall of the foundation in this case.
274  */
275  if (hid >= NEW_HOUSE_OFFSET) {
276  const HouseSpec *hs = HouseSpec::Get(hid);
278  uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
279  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
280  }
281  }
282  return FlatteningFoundation(tileh);
283 }
284 
291 static void AnimateTile_Town(TileIndex tile)
292 {
293  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
294  AnimateNewHouseTile(tile);
295  return;
296  }
297 
298  if (_tick_counter & 3) return;
299 
300  /* If the house is not one with a lift anymore, then stop this animating.
301  * Not exactly sure when this happens, but probably when a house changes.
302  * Before this was just a return...so it'd leak animated tiles..
303  * That bug seems to have been here since day 1?? */
304  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
305  DeleteAnimatedTile(tile);
306  return;
307  }
308 
309  if (!LiftHasDestination(tile)) {
310  uint i;
311 
312  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
313  * This is due to the fact that the first floor is, in the graphics,
314  * the height of 2 'normal' floors.
315  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
316  do {
317  i = RandomRange(7);
318  } while (i == 1 || i * 6 == GetLiftPosition(tile));
319 
320  SetLiftDestination(tile, i);
321  }
322 
323  int pos = GetLiftPosition(tile);
324  int dest = GetLiftDestination(tile) * 6;
325  pos += (pos < dest) ? 1 : -1;
326  SetLiftPosition(tile, pos);
327 
328  if (pos == dest) {
329  HaltLift(tile);
330  DeleteAnimatedTile(tile);
331  }
332 
333  MarkTileDirtyByTile(tile);
334 }
335 
342 static bool IsCloseToTown(TileIndex tile, uint dist)
343 {
344  /* On a large map with many towns, it may be faster to check the surroundings of the tile.
345  * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
346  if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
347  const int tx = TileX(tile);
348  const int ty = TileY(tile);
349  TileArea tile_area = TileArea(
350  TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
351  TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
352  );
353  TILE_AREA_LOOP(atile, tile_area) {
354  if (GetTileType(atile) == MP_HOUSE) {
355  Town *t = Town::GetByTile(atile);
356  if (DistanceManhattan(tile, t->xy) < dist) return true;
357  }
358  }
359  return false;
360  }
361 
362  const Town *t;
363 
364  FOR_ALL_TOWNS(t) {
365  if (DistanceManhattan(tile, t->xy) < dist) return true;
366  }
367  return false;
368 }
369 
375 {
376  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
377  SetDParam(0, this->index);
378  SetDParam(1, this->cache.population);
379  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
380  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
381  STR_VIEWPORT_TOWN);
382 
384 }
385 
388 {
389  Town *t;
390 
391  FOR_ALL_TOWNS(t) {
392  t->UpdateVirtCoord();
393  }
394 }
395 
401 static void ChangePopulation(Town *t, int mod)
402 {
403  t->cache.population += mod;
404  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
405  t->UpdateVirtCoord();
406 
408 }
409 
416 {
417  uint32 pop = 0;
418  const Town *t;
419 
420  FOR_ALL_TOWNS(t) pop += t->cache.population;
421  return pop;
422 }
423 
429 {
430  assert(IsTileType(tile, MP_HOUSE));
431 
432  /* progress in construction stages */
434  if (GetHouseConstructionTick(tile) != 0) return;
435 
436  AnimateNewHouseConstruction(tile);
437 
438  if (IsHouseCompleted(tile)) {
439  /* Now that construction is complete, we can add the population of the
440  * building to the town. */
441  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
442  ResetHouseAge(tile);
443  }
444  MarkTileDirtyByTile(tile);
445 }
446 
452 {
453  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
454  if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
455  if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
456  if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
457  if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
458 }
459 
466 static void TileLoop_Town(TileIndex tile)
467 {
468  HouseID house_id = GetHouseType(tile);
469 
470  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
471  * doesn't exist any more, so don't continue here. */
472  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
473 
474  if (!IsHouseCompleted(tile)) {
475  /* Construction is not completed. See if we can go further in construction*/
476  MakeTownHouseBigger(tile);
477  return;
478  }
479 
480  const HouseSpec *hs = HouseSpec::Get(house_id);
481 
482  /* If the lift has a destination, it is already an animated tile. */
483  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
484  house_id < NEW_HOUSE_OFFSET &&
485  !LiftHasDestination(tile) &&
486  Chance16(1, 2)) {
487  AddAnimatedTile(tile);
488  }
489 
490  Town *t = Town::GetByTile(tile);
491  uint32 r = Random();
492 
493  StationFinder stations(TileArea(tile, 1, 1));
494 
496  for (uint i = 0; i < 256; i++) {
497  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
498 
499  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
500 
501  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
502  if (cargo == CT_INVALID) continue;
503 
504  uint amt = GB(callback, 0, 8);
505  if (amt == 0) continue;
506 
507  uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
508 
509  const CargoSpec *cs = CargoSpec::Get(cargo);
510  t->supplied[cs->Index()].new_max += amt;
511  t->supplied[cs->Index()].new_act += moved;
512  }
513  } else {
514  if (GB(r, 0, 8) < hs->population) {
515  uint amt = GB(r, 0, 8) / 8 + 1;
516 
517  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
518  t->supplied[CT_PASSENGERS].new_max += amt;
519  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
520  }
521 
522  if (GB(r, 8, 8) < hs->mail_generation) {
523  uint amt = GB(r, 8, 8) / 8 + 1;
524 
525  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
526  t->supplied[CT_MAIL].new_max += amt;
527  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
528  }
529  }
530 
531  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
532 
533  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
535  CanDeleteHouse(tile) &&
536  GetHouseAge(tile) >= hs->minimum_life &&
537  --t->time_until_rebuild == 0) {
538  t->time_until_rebuild = GB(r, 16, 8) + 192;
539 
540  ClearTownHouse(t, tile);
541 
542  /* Rebuild with another house? */
543  if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
544  }
545 
546  cur_company.Restore();
547 }
548 
549 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
550 {
551  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
552  if (!CanDeleteHouse(tile)) return CMD_ERROR;
553 
554  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
555 
557  cost.AddCost(hs->GetRemovalCost());
558 
559  int rating = hs->remove_rating_decrease;
560  Town *t = Town::GetByTile(tile);
561 
563  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
564  SetDParam(0, t->index);
565  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
566  }
567  }
568 
569  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
570  if (flags & DC_EXEC) {
571  ClearTownHouse(t, tile);
572  }
573 
574  return cost;
575 }
576 
577 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
578 {
579  HouseID house_id = GetHouseType(tile);
580  const HouseSpec *hs = HouseSpec::Get(house_id);
581  Town *t = Town::GetByTile(tile);
582 
584  for (uint i = 0; i < 256; i++) {
585  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
586 
587  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
588 
589  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
590 
591  if (cargo == CT_INVALID) continue;
592  produced[cargo]++;
593  }
594  } else {
595  if (hs->population > 0) {
596  produced[CT_PASSENGERS]++;
597  }
598  if (hs->mail_generation > 0) {
599  produced[CT_MAIL]++;
600  }
601  }
602 }
603 
604 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
605 {
606  if (cargo == CT_INVALID || amount == 0) return;
607  acceptance[cargo] += amount;
608  SetBit(*always_accepted, cargo);
609 }
610 
611 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
612 {
613  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
614  CargoID accepts[3];
615 
616  /* Set the initial accepted cargo types */
617  for (uint8 i = 0; i < lengthof(accepts); i++) {
618  accepts[i] = hs->accepts_cargo[i];
619  }
620 
621  /* Check for custom accepted cargo types */
623  uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
624  if (callback != CALLBACK_FAILED) {
625  /* Replace accepted cargo types with translated values from callback */
626  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
627  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
628  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
629  }
630  }
631 
632  /* Check for custom cargo acceptance */
634  uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
635  if (callback != CALLBACK_FAILED) {
636  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
637  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
638  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
639  /* The 'S' bit indicates food instead of goods */
640  AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
641  } else {
642  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
643  }
644  return;
645  }
646  }
647 
648  /* No custom acceptance, so fill in with the default values */
649  for (uint8 i = 0; i < lengthof(accepts); i++) {
650  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
651  }
652 }
653 
654 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
655 {
656  const HouseID house = GetHouseType(tile);
657  const HouseSpec *hs = HouseSpec::Get(house);
658  bool house_completed = IsHouseCompleted(tile);
659 
660  td->str = hs->building_name;
661 
662  uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
663  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
664  if (callback_res > 0x400) {
666  } else {
667  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
668  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
669  td->str = new_name;
670  }
671  }
672  }
673 
674  if (!house_completed) {
675  SetDParamX(td->dparam, 0, td->str);
676  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
677  }
678 
679  if (hs->grf_prop.grffile != NULL) {
680  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
681  td->grf = gc->GetName();
682  }
683 
684  td->owner[0] = OWNER_TOWN;
685 }
686 
687 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
688 {
689  /* not used */
690  return 0;
691 }
692 
693 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
694 {
695  /* not used */
696 }
697 
702 {
703  t->cargo_accepted_total = 0;
704 
705  const TileArea &area = t->cargo_accepted.GetArea();
706  TILE_AREA_LOOP(tile, area) {
707  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
708  t->cargo_accepted_total |= t->cargo_accepted[tile];
709  }
710  }
711 }
712 
719 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
720 {
721  CargoArray accepted, produced;
722  uint32 dummy;
723 
724  /* Gather acceptance for all houses in an area around the start tile.
725  * The area is composed of the square the tile is in, extended one square in all
726  * directions as the coverage area of a single station is bigger than just one square. */
728  TILE_AREA_LOOP(tile, area) {
729  if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
730 
731  AddAcceptedCargo_Town(tile, accepted, &dummy);
732  AddProducedCargo_Town(tile, produced);
733  }
734 
735  /* Create bitmap of produced and accepted cargoes. */
736  uint32 acc = 0;
737  for (uint cid = 0; cid < NUM_CARGO; cid++) {
738  if (accepted[cid] >= 8) SetBit(acc, cid);
739  if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
740  }
741  t->cargo_accepted[start] = acc;
742 
743  if (update_total) UpdateTownCargoTotal(t);
744 }
745 
750 {
751  t->cargo_produced = 0;
752 
753  const TileArea &area = t->cargo_accepted.GetArea();
754  if (area.tile == INVALID_TILE) return;
755 
756  /* Update acceptance for each grid square. */
757  TILE_AREA_LOOP(tile, area) {
758  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
759  UpdateTownCargoes(t, tile, false);
760  }
761  }
762 
763  /* Update the total acceptance. */
765 }
766 
769 {
770  Town *town;
772 
773  FOR_ALL_TOWNS(town) {
775  }
776 }
777 
778 static bool GrowTown(Town *t);
779 
780 static void TownTickHandler(Town *t)
781 {
782  if (HasBit(t->flags, TOWN_IS_GROWING)) {
783  int i = t->grow_counter - 1;
784  if (i < 0) {
785  if (GrowTown(t)) {
787  } else {
788  i = 0;
789  }
790  }
791  t->grow_counter = i;
792  }
793 }
794 
795 void OnTick_Town()
796 {
797  if (_game_mode == GM_EDITOR) return;
798 
799  Town *t;
800  FOR_ALL_TOWNS(t) {
801  /* Run town tick at regular intervals, but not all at once. */
802  if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
803  TownTickHandler(t);
804  }
805  }
806 }
807 
817 {
818  if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
819 
820  return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
821 }
822 
833 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
834 {
835  if (!IsValidTile(tile)) return false;
836 
837  /* Lookup table for the used diff values */
838  const TileIndexDiff tid_lt[3] = {
842  };
843 
844  dist_multi = (dist_multi + 1) * 4;
845  for (uint pos = 4; pos < dist_multi; pos++) {
846  /* Go (pos / 4) tiles to the left or the right */
847  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
848 
849  /* Use the current tile as origin, or go one tile backwards */
850  if (pos & 2) cur += tid_lt[2];
851 
852  /* Test for roadbit parallel to dir and facing towards the middle axis */
853  if (IsValidTile(tile + cur) &&
854  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
855  }
856  return false;
857 }
858 
867 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
868 {
869  if (DistanceFromEdge(tile) == 0) return false;
870 
871  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
872  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
873 
874  /* Check if there already is a road at this point? */
875  if (GetTownRoadBits(tile) == ROAD_NONE) {
876  /* No, try if we are able to build a road piece there.
877  * If that fails clear the land, and if that fails exit.
878  * This is to make sure that we can build a road here later. */
879  if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
880  DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
881  return false;
882  }
883  }
884 
886  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
887  if (cur_slope == SLOPE_FLAT) return ret;
888 
889  /* If the tile is not a slope in the right direction, then
890  * maybe terraform some. */
891  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
892  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
893  if (Chance16(1, 8)) {
894  CommandCost res = CMD_ERROR;
895  if (!_generating_world && Chance16(1, 10)) {
896  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
897  res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
898  DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
899  }
900  if (res.Failed() && Chance16(1, 3)) {
901  /* We can consider building on the slope, though. */
902  return ret;
903  }
904  }
905  return false;
906  }
907  return ret;
908 }
909 
910 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
911 {
912  assert(tile < MapSize());
913 
914  CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
915  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
916  DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
917  return true;
918 }
919 
920 static void LevelTownLand(TileIndex tile)
921 {
922  assert(tile < MapSize());
923 
924  /* Don't terraform if land is plain or if there's a house there. */
925  if (IsTileType(tile, MP_HOUSE)) return;
926  Slope tileh = GetTileSlope(tile);
927  if (tileh == SLOPE_FLAT) return;
928 
929  /* First try up, then down */
930  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
931  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
932  }
933 }
934 
945 {
946  /* align the grid to the downtown */
947  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
948  RoadBits rcmd = ROAD_NONE;
949 
950  switch (t->layout) {
951  default: NOT_REACHED();
952 
953  case TL_2X2_GRID:
954  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
955  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
956  break;
957 
958  case TL_3X3_GRID:
959  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
960  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
961  break;
962  }
963 
964  /* Optimise only X-junctions */
965  if (rcmd != ROAD_ALL) return rcmd;
966 
967  RoadBits rb_template;
968 
969  switch (GetTileSlope(tile)) {
970  default: rb_template = ROAD_ALL; break;
971  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
972  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
973  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
974  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
975  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
976  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
977  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
978  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
979  case SLOPE_STEEP_W:
980  case SLOPE_STEEP_S:
981  case SLOPE_STEEP_E:
982  case SLOPE_STEEP_N:
983  rb_template = ROAD_NONE;
984  break;
985  }
986 
987  /* Stop if the template is compatible to the growth dir */
988  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
989  /* If not generate a straight road in the direction of the growth */
991 }
992 
1004 {
1005  /* We can't look further than that. */
1006  if (DistanceFromEdge(tile) == 0) return false;
1007 
1008  uint counter = 0; // counts the house neighbor tiles
1009 
1010  /* Check the tiles E,N,W and S of the current tile for houses */
1011  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1012  /* Count both void and house tiles for checking whether there
1013  * are enough houses in the area. This to make it likely that
1014  * houses get build up to the edge of the map. */
1015  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1016  case MP_HOUSE:
1017  case MP_VOID:
1018  counter++;
1019  break;
1020 
1021  default:
1022  break;
1023  }
1024 
1025  /* If there are enough neighbors stop here */
1026  if (counter >= 3) {
1027  if (BuildTownHouse(t, tile)) {
1028  _grow_town_result = GROWTH_SUCCEED;
1029  return true;
1030  }
1031  return false;
1032  }
1033  }
1034  return false;
1035 }
1036 
1045 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1046 {
1047  if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1048  _grow_town_result = GROWTH_SUCCEED;
1049  return true;
1050  }
1051  return false;
1052 }
1053 
1064 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1065 {
1066  assert(bridge_dir < DIAGDIR_END);
1067 
1068  const Slope slope = GetTileSlope(tile);
1069 
1070  /* Make sure the direction is compatible with the slope.
1071  * Well we check if the slope has an up bit set in the
1072  * reverse direction. */
1073  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1074 
1075  /* Assure that the bridge is connectable to the start side */
1076  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1077 
1078  /* We are in the right direction */
1079  uint8 bridge_length = 0; // This value stores the length of the possible bridge
1080  TileIndex bridge_tile = tile; // Used to store the other waterside
1081 
1082  const int delta = TileOffsByDiagDir(bridge_dir);
1083 
1084  if (slope == SLOPE_FLAT) {
1085  /* Bridges starting on flat tiles are only allowed when crossing rivers. */
1086  do {
1087  if (bridge_length++ >= 4) {
1088  /* Allow to cross rivers, not big lakes. */
1089  return false;
1090  }
1091  bridge_tile += delta;
1092  } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
1093  } else {
1094  do {
1095  if (bridge_length++ >= 11) {
1096  /* Max 11 tile long bridges */
1097  return false;
1098  }
1099  bridge_tile += delta;
1100  } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
1101  }
1102 
1103  /* no water tiles in between? */
1104  if (bridge_length == 1) return false;
1105 
1106  for (uint8 times = 0; times <= 22; times++) {
1107  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1108 
1109  /* Can we actually build the bridge? */
1110  if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1112  _grow_town_result = GROWTH_SUCCEED;
1113  return true;
1114  }
1115  }
1116  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1117  return false;
1118 }
1119 
1137 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1138 {
1139  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1140  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1141 
1142  assert(tile < MapSize());
1143 
1144  if (cur_rb == ROAD_NONE) {
1145  /* Tile has no road. First reset the status counter
1146  * to say that this is the last iteration. */
1147  _grow_town_result = GROWTH_SEARCH_STOPPED;
1148 
1151 
1152  /* Remove hills etc */
1153  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1154 
1155  /* Is a road allowed here? */
1156  switch (t1->layout) {
1157  default: NOT_REACHED();
1158 
1159  case TL_3X3_GRID:
1160  case TL_2X2_GRID:
1161  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1162  if (rcmd == ROAD_NONE) return;
1163  break;
1164 
1165  case TL_BETTER_ROADS:
1166  case TL_ORIGINAL:
1167  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1168 
1169  DiagDirection source_dir = ReverseDiagDir(target_dir);
1170 
1171  if (Chance16(1, 4)) {
1172  /* Randomize a new target dir */
1173  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1174  }
1175 
1176  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1177  /* A road is not allowed to continue the randomized road,
1178  * return if the road we're trying to build is curved. */
1179  if (target_dir != ReverseDiagDir(source_dir)) return;
1180 
1181  /* Return if neither side of the new road is a house */
1184  return;
1185  }
1186 
1187  /* That means that the road is only allowed if there is a house
1188  * at any side of the new road. */
1189  }
1190 
1191  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1192  break;
1193  }
1194 
1195  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1196  /* Continue building on a partial road.
1197  * Should be always OK, so we only generate
1198  * the fitting RoadBits */
1199  _grow_town_result = GROWTH_SEARCH_STOPPED;
1200 
1202 
1203  switch (t1->layout) {
1204  default: NOT_REACHED();
1205 
1206  case TL_3X3_GRID:
1207  case TL_2X2_GRID:
1208  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1209  break;
1210 
1211  case TL_BETTER_ROADS:
1212  case TL_ORIGINAL:
1213  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1214  break;
1215  }
1216  } else {
1217  bool allow_house = true; // Value which decides if we want to construct a house
1218 
1219  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1220  * it is the starting tile. Half the time, we stay on this side then.*/
1221  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1222  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1223  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1224  }
1225  return;
1226  }
1227 
1228  /* Possibly extend the road in a direction.
1229  * Randomize a direction and if it has a road, bail out. */
1230  target_dir = RandomDiagDir();
1231  if (cur_rb & DiagDirToRoadBits(target_dir)) return;
1232 
1233  /* This is the tile we will reach if we extend to this direction. */
1234  TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1235 
1236  /* Don't walk into water. */
1237  if (HasTileWaterGround(house_tile)) return;
1238 
1239  if (!IsValidTile(house_tile)) return;
1240 
1242  switch (t1->layout) {
1243  default: NOT_REACHED();
1244 
1245  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1246  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1247  /* FALL THROUGH */
1248 
1249  case TL_2X2_GRID:
1250  rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
1251  allow_house = (rcmd == ROAD_NONE);
1252  break;
1253 
1254  case TL_BETTER_ROADS: // Use original afterwards!
1255  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1256  /* FALL THROUGH */
1257 
1258  case TL_ORIGINAL:
1259  /* Allow a house at the edge. 60% chance or
1260  * always ok if no road allowed. */
1261  rcmd = DiagDirToRoadBits(target_dir);
1262  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1263  break;
1264  }
1265  }
1266 
1267  if (allow_house) {
1268  /* Build a house, but not if there already is a house there. */
1269  if (!IsTileType(house_tile, MP_HOUSE)) {
1270  /* Level the land if possible */
1271  if (Chance16(1, 6)) LevelTownLand(house_tile);
1272 
1273  /* And build a house.
1274  * Set result to -1 if we managed to build it. */
1275  if (BuildTownHouse(t1, house_tile)) {
1276  _grow_town_result = GROWTH_SUCCEED;
1277  }
1278  }
1279  return;
1280  }
1281 
1282  _grow_town_result = GROWTH_SEARCH_STOPPED;
1283  }
1284 
1285  /* Return if a water tile */
1286  if (HasTileWaterGround(tile)) return;
1287 
1288  /* Make the roads look nicer */
1289  rcmd = CleanUpRoadBits(tile, rcmd);
1290  if (rcmd == ROAD_NONE) return;
1291 
1292  /* Only use the target direction for bridges to ensure they're connected.
1293  * The target_dir is as computed previously according to town layout, so
1294  * it will match it perfectly. */
1295  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1296 
1297  GrowTownWithRoad(t1, tile, rcmd);
1298 }
1299 
1307 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1308 {
1309  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1310  if (!IsValidTile(target_tile)) return false;
1311  if (HasTileWaterGround(target_tile)) return false;
1312 
1313  RoadBits target_rb = GetTownRoadBits(target_tile);
1315  /* Check whether a road connection exists or can be build. */
1316  switch (GetTileType(target_tile)) {
1317  case MP_ROAD:
1318  return target_rb != ROAD_NONE;
1319 
1320  case MP_HOUSE:
1321  case MP_STATION:
1322  case MP_INDUSTRY:
1323  case MP_OBJECT:
1324  return false;
1325 
1326  default:
1327  /* Checked for void and water earlier */
1328  return true;
1329  }
1330  } else {
1331  /* Check whether a road connection already exists,
1332  * and it leads somewhere else. */
1333  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1334  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1335  }
1336 }
1337 
1344 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1345 {
1346  /* Special case.
1347  * @see GrowTownInTile Check the else if
1348  */
1349  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1350 
1351  assert(tile < MapSize());
1352 
1353  /* Number of times to search.
1354  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1355  * them a little handicap. */
1356  switch (t->layout) {
1357  case TL_BETTER_ROADS:
1358  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1359  break;
1360 
1361  case TL_3X3_GRID:
1362  case TL_2X2_GRID:
1363  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1364  break;
1365 
1366  default:
1367  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1368  break;
1369  }
1370 
1371  do {
1372  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1373 
1374  /* Try to grow the town from this point */
1375  GrowTownInTile(&tile, cur_rb, target_dir, t);
1376 
1377  /* Exclude the source position from the bitmask
1378  * and return if no more road blocks available */
1379  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1380  if (cur_rb == ROAD_NONE) {
1381  return _grow_town_result == GROWTH_SUCCEED;
1382  }
1383 
1384  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1385  /* Only build in the direction away from the tunnel or bridge. */
1386  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1387  } else {
1388  /* Select a random bit from the blockmask, walk a step
1389  * and continue the search from there. */
1390  do {
1391  if (cur_rb == ROAD_NONE) return false;
1392  RoadBits target_bits;
1393  do {
1394  target_dir = RandomDiagDir();
1395  target_bits = DiagDirToRoadBits(target_dir);
1396  } while (!(cur_rb & target_bits));
1397  cur_rb &= ~target_bits;
1398  } while (!CanFollowRoad(tile, target_dir));
1399  }
1400  tile = TileAddByDiagDir(tile, target_dir);
1401 
1402  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1403  /* Don't allow building over roads of other cities */
1404  if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1405  return false;
1406  } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1407  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1408  * owner :) (happy happy happy road now) */
1410  SetTownIndex(tile, t->index);
1411  }
1412  }
1413 
1414  /* Max number of times is checked. */
1415  } while (--_grow_town_result >= 0);
1416 
1417  return _grow_town_result == GROWTH_SUCCEED - 1;
1418 }
1419 
1428 {
1429  uint32 r = Random();
1430  uint a = GB(r, 0, 2);
1431  uint b = GB(r, 8, 2);
1432  if (a == b) b ^= 2;
1433  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1434 }
1435 
1441 static bool GrowTown(Town *t)
1442 {
1443  static const TileIndexDiffC _town_coord_mod[] = {
1444  {-1, 0},
1445  { 1, 1},
1446  { 1, -1},
1447  {-1, -1},
1448  {-1, 0},
1449  { 0, 2},
1450  { 2, 0},
1451  { 0, -2},
1452  {-1, -1},
1453  {-2, 2},
1454  { 2, 2},
1455  { 2, -2},
1456  { 0, 0}
1457  };
1458 
1459  /* Current "company" is a town */
1460  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1461 
1462  TileIndex tile = t->xy; // The tile we are working with ATM
1463 
1464  /* Find a road that we can base the construction on. */
1465  const TileIndexDiffC *ptr;
1466  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1467  if (GetTownRoadBits(tile) != ROAD_NONE) {
1468  bool success = GrowTownAtRoad(t, tile);
1469  cur_company.Restore();
1470  return success;
1471  }
1472  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1473  }
1474 
1475  /* No road available, try to build a random road block by
1476  * clearing some land and then building a road there. */
1478  tile = t->xy;
1479  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1480  /* Only work with plain land that not already has a house */
1481  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1482  if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1483  DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1484  cur_company.Restore();
1485  return true;
1486  }
1487  }
1488  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1489  }
1490  }
1491 
1492  cur_company.Restore();
1493  return false;
1494 }
1495 
1496 void UpdateTownRadius(Town *t)
1497 {
1498  static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1499  { 4, 0, 0, 0, 0}, // 0
1500  { 16, 0, 0, 0, 0},
1501  { 25, 0, 0, 0, 0},
1502  { 36, 0, 0, 0, 0},
1503  { 49, 0, 4, 0, 0},
1504  { 64, 0, 4, 0, 0}, // 20
1505  { 64, 0, 9, 0, 1},
1506  { 64, 0, 9, 0, 4},
1507  { 64, 0, 16, 0, 4},
1508  { 81, 0, 16, 0, 4},
1509  { 81, 0, 16, 0, 4}, // 40
1510  { 81, 0, 25, 0, 9},
1511  { 81, 36, 25, 0, 9},
1512  { 81, 36, 25, 16, 9},
1513  { 81, 49, 0, 25, 9},
1514  { 81, 64, 0, 25, 9}, // 60
1515  { 81, 64, 0, 36, 9},
1516  { 81, 64, 0, 36, 16},
1517  {100, 81, 0, 49, 16},
1518  {100, 81, 0, 49, 25},
1519  {121, 81, 0, 49, 25}, // 80
1520  {121, 81, 0, 49, 25},
1521  {121, 81, 0, 49, 36}, // 88
1522  };
1523 
1524  if (t->cache.num_houses < 92) {
1525  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));
1526  } else {
1527  int mass = t->cache.num_houses / 8;
1528  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1529  * The offsets are to make sure the radii do not decrease in size when going from the table
1530  * to the calculated value.*/
1531  t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1532  t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1533  t->cache.squared_town_zone_radius[2] = 0;
1534  t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1535  t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1536  }
1537 }
1538 
1539 void UpdateTownMaxPass(Town *t)
1540 {
1541  t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1542  t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1543 }
1544 
1556 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1557 {
1558  t->xy = tile;
1559  t->cache.num_houses = 0;
1560  t->time_until_rebuild = 10;
1561  UpdateTownRadius(t);
1562  t->flags = 0;
1563  t->cache.population = 0;
1564  t->grow_counter = 0;
1565  t->growth_rate = 250;
1566 
1567  /* Set the default cargo requirement for town growth */
1569  case LT_ARCTIC:
1571  break;
1572 
1573  case LT_TROPIC:
1576  break;
1577  }
1578 
1579  t->fund_buildings_months = 0;
1580 
1581  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1582 
1583  t->have_ratings = 0;
1585  t->exclusive_counter = 0;
1586  t->statues = 0;
1587 
1588  extern int _nb_orig_names;
1590  /* Original town name */
1591  t->townnamegrfid = 0;
1592  t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1593  } else {
1594  /* Newgrf town name */
1595  t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1596  t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1597  }
1598  t->townnameparts = townnameparts;
1599 
1600  t->UpdateVirtCoord();
1602 
1603  t->InitializeLayout(layout);
1604 
1605  t->larger_town = city;
1606 
1607  int x = (int)size * 16 + 3;
1608  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1609  /* Don't create huge cities when founding town in-game */
1610  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1611 
1612  t->cache.num_houses += x;
1613  UpdateTownRadius(t);
1614 
1615  int i = x * 4;
1616  do {
1617  GrowTown(t);
1618  } while (--i);
1619 
1620  t->cache.num_houses -= x;
1621  UpdateTownRadius(t);
1622  UpdateTownMaxPass(t);
1624 }
1625 
1632 {
1633  /* Check if too close to the edge of map */
1634  if (DistanceFromEdge(tile) < 12) {
1635  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1636  }
1637 
1638  /* Check distance to all other towns. */
1639  if (IsCloseToTown(tile, 20)) {
1640  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1641  }
1642 
1643  /* Can only build on clear flat areas, possibly with trees. */
1644  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1645  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1646  }
1647 
1648  return CommandCost(EXPENSES_OTHER);
1649 }
1650 
1656 static bool IsUniqueTownName(const char *name)
1657 {
1658  const Town *t;
1659 
1660  FOR_ALL_TOWNS(t) {
1661  if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1662  }
1663 
1664  return true;
1665 }
1666 
1679 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1680 {
1681  TownSize size = Extract<TownSize, 0, 2>(p1);
1682  bool city = HasBit(p1, 2);
1683  TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1685  bool random = HasBit(p1, 6);
1686  uint32 townnameparts = p2;
1687 
1688  if (size >= TSZ_END) return CMD_ERROR;
1689  if (layout >= NUM_TLS) return CMD_ERROR;
1690 
1691  /* Some things are allowed only in the scenario editor and for game scripts. */
1692  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1694  if (size == TSZ_LARGE) return CMD_ERROR;
1695  if (random) return CMD_ERROR;
1697  return CMD_ERROR;
1698  }
1699  } else if (_current_company == OWNER_DEITY && random) {
1700  /* Random parameter is not allowed for Game Scripts. */
1701  return CMD_ERROR;
1702  }
1703 
1704  if (StrEmpty(text)) {
1705  /* If supplied name is empty, townnameparts has to generate unique automatic name */
1706  if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1707  } else {
1708  /* If name is not empty, it has to be unique custom name */
1710  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1711  }
1712 
1713  /* Allocate town struct */
1714  if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1715 
1716  if (!random) {
1717  CommandCost ret = TownCanBePlacedHere(tile);
1718  if (ret.Failed()) return ret;
1719  }
1720 
1721  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1722  /* multidimensional arrays have to have defined length of non-first dimension */
1723  assert_compile(lengthof(price_mult[0]) == 4);
1724 
1725  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1726  byte mult = price_mult[city][size];
1727 
1728  cost.MultiplyCost(mult);
1729 
1730  /* Create the town */
1731  if (flags & DC_EXEC) {
1732  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1733  _additional_cash_required = cost.GetCost();
1734  return CommandCost(EXPENSES_OTHER);
1735  }
1736 
1737  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1739  Town *t;
1740  if (random) {
1741  t = CreateRandomTown(20, townnameparts, size, city, layout);
1742  if (t == NULL) {
1743  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1744  } else {
1745  _new_town_id = t->index;
1746  }
1747  } else {
1748  t = new Town(tile);
1749  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1750  }
1752  old_generating_world.Restore();
1753 
1754  if (t != NULL && !StrEmpty(text)) {
1755  t->name = stredup(text);
1756  t->UpdateVirtCoord();
1757  }
1758 
1759  if (_game_mode != GM_EDITOR) {
1760  /* 't' can't be NULL since 'random' is false outside scenedit */
1761  assert(!random);
1762  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1764  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1765 
1766  char *cn = stredup(company_name);
1767  SetDParamStr(0, cn);
1768  SetDParam(1, t->index);
1769 
1770  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1771  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1772  Game::NewEvent(new ScriptEventTownFounded(t->index));
1773  }
1774  }
1775  return cost;
1776 }
1777 
1788 {
1789  switch (layout) {
1790  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1791  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1792  default: return tile;
1793  }
1794 }
1795 
1805 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1806 {
1807  switch (layout) {
1808  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1809  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1810  default: return true;
1811  }
1812 }
1813 
1817 struct SpotData {
1819  uint max_dist;
1821 };
1822 
1839 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1840 {
1841  SpotData *sp = (SpotData*)user_data;
1842  uint dist = GetClosestWaterDistance(tile, true);
1843 
1844  if (IsTileType(tile, MP_CLEAR) &&
1845  IsTileFlat(tile) &&
1846  IsTileAlignedToGrid(tile, sp->layout) &&
1847  dist > sp->max_dist) {
1848  sp->tile = tile;
1849  sp->max_dist = dist;
1850  }
1851 
1852  return false;
1853 }
1854 
1861 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1862 {
1863  return IsTileType(tile, MP_CLEAR);
1864 }
1865 
1879 {
1880  SpotData sp = { INVALID_TILE, 0, layout };
1881 
1882  TileIndex coast = tile;
1883  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
1884  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1885  return sp.tile;
1886  }
1887 
1888  /* if we get here just give up */
1889  return INVALID_TILE;
1890 }
1891 
1892 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1893 {
1894  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1895 
1896  if (!Town::CanAllocateItem()) return NULL;
1897 
1898  do {
1899  /* Generate a tile index not too close from the edge */
1900  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1901 
1902  /* if we tried to place the town on water, slide it over onto
1903  * the nearest likely-looking spot */
1904  if (IsTileType(tile, MP_WATER)) {
1905  tile = FindNearestGoodCoastalTownSpot(tile, layout);
1906  if (tile == INVALID_TILE) continue;
1907  }
1908 
1909  /* Make sure town can be placed here */
1910  if (TownCanBePlacedHere(tile).Failed()) continue;
1911 
1912  /* Allocate a town struct */
1913  Town *t = new Town(tile);
1914 
1915  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
1916 
1917  /* if the population is still 0 at the point, then the
1918  * placement is so bad it couldn't grow at all */
1919  if (t->cache.population > 0) return t;
1920 
1921  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1923  cur_company.Restore();
1924  assert(rc.Succeeded());
1925 
1926  /* We already know that we can allocate a single town when
1927  * entering this function. However, we create and delete
1928  * a town which "resets" the allocation checks. As such we
1929  * need to check again when assertions are enabled. */
1930  assert(Town::CanAllocateItem());
1931  } while (--attempts != 0);
1932 
1933  return NULL;
1934 }
1935 
1936 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
1937 
1946 {
1947  uint current_number = 0;
1948  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
1949  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
1950  total = min(TownPool::MAX_SIZE, total);
1951  uint32 townnameparts;
1952  TownNames town_names;
1953 
1955 
1956  /* First attempt will be made at creating the suggested number of towns.
1957  * Note that this is really a suggested value, not a required one.
1958  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
1959  do {
1962  /* Get a unique name for the town. */
1963  if (!GenerateTownName(&townnameparts, &town_names)) continue;
1964  /* try 20 times to create a random-sized town for the first loop. */
1965  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
1966  } while (--total);
1967 
1968  town_names.clear();
1969 
1970  if (current_number != 0) return true;
1971 
1972  /* If current_number is still zero at this point, it means that not a single town has been created.
1973  * So give it a last try, but now more aggressive */
1974  if (GenerateTownName(&townnameparts) &&
1975  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
1976  return true;
1977  }
1978 
1979  /* If there are no towns at all and we are generating new game, bail out */
1980  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
1981  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
1982  }
1983 
1984  return false; // we are still without a town? we failed, simply
1985 }
1986 
1987 
1994 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
1995 {
1996  uint dist = DistanceSquare(tile, t->xy);
1997 
1998  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
1999 
2000  HouseZonesBits smallest = HZB_TOWN_EDGE;
2001  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2002  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2003  }
2004 
2005  return smallest;
2006 }
2007 
2018 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2019 {
2020  CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
2021 
2022  assert(cc.Succeeded());
2023 
2024  IncreaseBuildingCount(t, type);
2025  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2026  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2027 
2028  MarkTileDirtyByTile(tile);
2029 }
2030 
2031 
2042 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2043 {
2044  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2045 
2046  ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2047  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2048  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2049  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2050 }
2051 
2052 
2061 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
2062 {
2063  /* cannot build on these slopes... */
2064  Slope slope = GetTileSlope(tile);
2065  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2066 
2067  /* building under a bridge? */
2068  if (IsBridgeAbove(tile)) return false;
2069 
2070  /* do not try to build over house owned by another town */
2071  if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
2072 
2073  /* can we clear the land? */
2074  return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2075 }
2076 
2077 
2087 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
2088 {
2089  if (!CanBuildHouseHere(tile, town, noslope)) return false;
2090 
2091  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2092  if (GetTileMaxZ(tile) != z) return false;
2093 
2094  return true;
2095 }
2096 
2097 
2107 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
2108 {
2109  /* we need to check this tile too because we can be at different tile now */
2110  if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
2111 
2112  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2113  tile += TileOffsByDiagDir(d);
2114  if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
2115  }
2116 
2117  return true;
2118 }
2119 
2120 
2128 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2129 {
2130  /* Allow towns everywhere when we don't build roads */
2132 
2133  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2134 
2135  switch (t->layout) {
2136  case TL_2X2_GRID:
2137  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2138  break;
2139 
2140  case TL_3X3_GRID:
2141  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2142  break;
2143 
2144  default:
2145  break;
2146  }
2147 
2148  return true;
2149 }
2150 
2151 
2159 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2160 {
2161  /* Allow towns everywhere when we don't build roads */
2163 
2164  /* Compute relative position of tile. (Positive offsets are towards north) */
2165  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2166 
2167  switch (t->layout) {
2168  case TL_2X2_GRID:
2169  grid_pos.x %= 3;
2170  grid_pos.y %= 3;
2171  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2172  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2173  break;
2174 
2175  case TL_3X3_GRID:
2176  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2177  break;
2178 
2179  default:
2180  break;
2181  }
2182 
2183  return true;
2184 }
2185 
2186 
2196 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2197 {
2198  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2199 
2200  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2201  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
2202 
2203  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2204  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
2205  *tile = tile2;
2206  return true;
2207  }
2208 
2209  return false;
2210 }
2211 
2212 
2221 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2222 {
2223  TileIndex tile2 = *tile;
2224 
2225  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2226  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
2227  *tile = tile2;
2228  return true;
2229  }
2230  if (d == DIAGDIR_END) break;
2231  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2232  }
2233 
2234  return false;
2235 }
2236 
2237 
2244 static bool BuildTownHouse(Town *t, TileIndex tile)
2245 {
2246  /* forbidden building here by town layout */
2247  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2248 
2249  /* no house allowed at all, bail out */
2250  if (!CanBuildHouseHere(tile, t->index, false)) return false;
2251 
2252  Slope slope = GetTileSlope(tile);
2253  int maxz = GetTileMaxZ(tile);
2254 
2255  /* Get the town zone type of the current tile, as well as the climate.
2256  * This will allow to easily compare with the specs of the new house to build */
2257  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2258 
2259  /* Above snow? */
2261  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2262 
2263  uint bitmask = (1 << rad) + (1 << (land + 12));
2264 
2265  /* bits 0-4 are used
2266  * bits 11-15 are used
2267  * bits 5-10 are not used. */
2268  HouseID houses[NUM_HOUSES];
2269  uint num = 0;
2270  uint probs[NUM_HOUSES];
2271  uint probability_max = 0;
2272 
2273  /* Generate a list of all possible houses that can be built. */
2274  for (uint i = 0; i < NUM_HOUSES; i++) {
2275  const HouseSpec *hs = HouseSpec::Get(i);
2276 
2277  /* Verify that the candidate house spec matches the current tile status */
2278  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2279 
2280  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2281  if (hs->class_id != HOUSE_NO_CLASS) {
2282  /* id_count is always <= class_count, so it doesn't need to be checked */
2283  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2284  } else {
2285  /* If the house has no class, check id_count instead */
2286  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2287  }
2288 
2289  /* Without NewHouses, all houses have probability '1' */
2290  uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2291  probability_max += cur_prob;
2292  probs[num] = cur_prob;
2293  houses[num++] = (HouseID)i;
2294  }
2295 
2296  TileIndex baseTile = tile;
2297 
2298  while (probability_max > 0) {
2299  /* Building a multitile building can change the location of tile.
2300  * The building would still be built partially on that tile, but
2301  * its northern tile would be elsewhere. However, if the callback
2302  * fails we would be basing further work from the changed tile.
2303  * So a next 1x1 tile building could be built on the wrong tile. */
2304  tile = baseTile;
2305 
2306  uint r = RandomRange(probability_max);
2307  uint i;
2308  for (i = 0; i < num; i++) {
2309  if (probs[i] > r) break;
2310  r -= probs[i];
2311  }
2312 
2313  HouseID house = houses[i];
2314  probability_max -= probs[i];
2315 
2316  /* remove tested house from the set */
2317  num--;
2318  houses[i] = houses[num];
2319  probs[i] = probs[num];
2320 
2321  const HouseSpec *hs = HouseSpec::Get(house);
2322 
2324  _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2325  continue;
2326  }
2327 
2328  if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2329 
2330  /* Special houses that there can be only one of. */
2331  uint oneof = 0;
2332 
2333  if (hs->building_flags & BUILDING_IS_CHURCH) {
2334  SetBit(oneof, TOWN_HAS_CHURCH);
2335  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2336  SetBit(oneof, TOWN_HAS_STADIUM);
2337  }
2338 
2339  if (t->flags & oneof) continue;
2340 
2341  /* Make sure there is no slope? */
2342  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2343  if (noslope && slope != SLOPE_FLAT) continue;
2344 
2345  if (hs->building_flags & TILE_SIZE_2x2) {
2346  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2347  } else if (hs->building_flags & TILE_SIZE_2x1) {
2348  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2349  } else if (hs->building_flags & TILE_SIZE_1x2) {
2350  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2351  } else {
2352  /* 1x1 house checks are already done */
2353  }
2354 
2355  byte random_bits = Random();
2356 
2358  uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2359  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2360  }
2361 
2362  /* build the house */
2363  t->cache.num_houses++;
2364 
2365  /* Special houses that there can be only one of. */
2366  t->flags |= oneof;
2367 
2368  byte construction_counter = 0;
2369  byte construction_stage = 0;
2370 
2371  if (_generating_world || _game_mode == GM_EDITOR) {
2372  uint32 r = Random();
2373 
2374  construction_stage = TOWN_HOUSE_COMPLETED;
2375  if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2376 
2377  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2378  ChangePopulation(t, hs->population);
2379  } else {
2380  construction_counter = GB(r, 2, 2);
2381  }
2382  }
2383 
2384  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2385  UpdateTownRadius(t);
2386  UpdateTownCargoes(t, tile);
2387 
2388  return true;
2389  }
2390 
2391  return false;
2392 }
2393 
2400 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2401 {
2402  assert(IsTileType(tile, MP_HOUSE));
2403  DecreaseBuildingCount(t, house);
2404  DoClearSquare(tile);
2405  DeleteAnimatedTile(tile);
2406 
2407  DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2408 }
2409 
2418 {
2419  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2420  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2421  house--;
2422  return TileDiffXY(-1, 0);
2423  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2424  house--;
2425  return TileDiffXY(0, -1);
2426  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2427  house -= 2;
2428  return TileDiffXY(-1, 0);
2429  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2430  house -= 3;
2431  return TileDiffXY(-1, -1);
2432  }
2433  }
2434  return 0;
2435 }
2436 
2437 void ClearTownHouse(Town *t, TileIndex tile)
2438 {
2439  assert(IsTileType(tile, MP_HOUSE));
2440 
2441  HouseID house = GetHouseType(tile);
2442 
2443  /* need to align the tile to point to the upper left corner of the house */
2444  tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2445 
2446  const HouseSpec *hs = HouseSpec::Get(house);
2447 
2448  /* Remove population from the town if the house is finished. */
2449  if (IsHouseCompleted(tile)) {
2450  ChangePopulation(t, -hs->population);
2451  }
2452 
2453  t->cache.num_houses--;
2454 
2455  /* Clear flags for houses that only may exist once/town. */
2456  if (hs->building_flags & BUILDING_IS_CHURCH) {
2458  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2460  }
2461 
2462  /* Do the actual clearing of tiles */
2463  uint eflags = hs->building_flags;
2464  DoClearTownHouseHelper(tile, t, house);
2465  if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2466  if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2467  if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2468 
2469  UpdateTownRadius(t);
2470 
2471  /* Update cargo acceptance. */
2472  UpdateTownCargoes(t, tile);
2473 }
2474 
2484 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2485 {
2486  Town *t = Town::GetIfValid(p1);
2487  if (t == NULL) return CMD_ERROR;
2488 
2489  bool reset = StrEmpty(text);
2490 
2491  if (!reset) {
2493  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2494  }
2495 
2496  if (flags & DC_EXEC) {
2497  free(t->name);
2498  t->name = reset ? NULL : stredup(text);
2499 
2500  t->UpdateVirtCoord();
2503  }
2504  return CommandCost();
2505 }
2506 
2513 {
2514  const CargoSpec *cs;
2515  FOR_ALL_CARGOSPECS(cs) {
2516  if (cs->town_effect == effect) return cs;
2517  }
2518  return NULL;
2519 }
2520 
2521 static void UpdateTownGrowRate(Town *t);
2522 
2534 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2535 {
2536  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2537 
2538  TownEffect te = (TownEffect)GB(p1, 16, 8);
2539  if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2540 
2541  uint16 index = GB(p1, 0, 16);
2542  Town *t = Town::GetIfValid(index);
2543  if (t == NULL) return CMD_ERROR;
2544 
2545  /* Validate if there is a cargo which is the requested TownEffect */
2546  const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2547  if (cargo == NULL) return CMD_ERROR;
2548 
2549  if (flags & DC_EXEC) {
2550  t->goal[te] = p2;
2551  UpdateTownGrowRate(t);
2553  }
2554 
2555  return CommandCost();
2556 }
2557 
2567 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2568 {
2569  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2570  Town *t = Town::GetIfValid(p1);
2571  if (t == NULL) return CMD_ERROR;
2572 
2573  if (flags & DC_EXEC) {
2574  free(t->text);
2575  t->text = StrEmpty(text) ? NULL : stredup(text);
2577  }
2578 
2579  return CommandCost();
2580 }
2581 
2591 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2592 {
2593  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2594  if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
2595  if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2596 
2597  Town *t = Town::GetIfValid(p1);
2598  if (t == NULL) return CMD_ERROR;
2599 
2600  if (flags & DC_EXEC) {
2601  if (p2 == 0) {
2602  /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2603  t->growth_rate = 0;
2604  } else {
2605  uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
2606  if (t->grow_counter >= old_rate) {
2607  /* This also catches old_rate == 0 */
2608  t->grow_counter = p2;
2609  } else {
2610  /* Scale grow_counter, so half finished houses stay half finished */
2611  t->grow_counter = t->grow_counter * p2 / old_rate;
2612  }
2614  }
2615  UpdateTownGrowRate(t);
2617  }
2618 
2619  return CommandCost();
2620 }
2621 
2631 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2632 {
2633  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2634  Town *t = Town::GetIfValid(p1);
2635  if (t == NULL) return CMD_ERROR;
2636 
2637  if (flags & DC_EXEC) {
2638  /* The more houses, the faster we grow */
2639  if (p2 == 0) {
2640  uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2641  t->cache.num_houses += amount;
2642  UpdateTownRadius(t);
2643 
2644  uint n = amount * 10;
2645  do GrowTown(t); while (--n);
2646 
2647  t->cache.num_houses -= amount;
2648  } else {
2649  for (; p2 > 0; p2--) {
2650  /* Try several times to grow, as we are really suppose to grow */
2651  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2652  }
2653  }
2654  UpdateTownRadius(t);
2655 
2656  UpdateTownMaxPass(t);
2657  }
2658 
2659  return CommandCost();
2660 }
2661 
2671 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2672 {
2673  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2674  Town *t = Town::GetIfValid(p1);
2675  if (t == NULL) return CMD_ERROR;
2676 
2677  /* Stations refer to towns. */
2678  const Station *st;
2679  FOR_ALL_STATIONS(st) {
2680  if (st->town == t) {
2681  /* Non-oil rig stations are always a problem. */
2682  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2683  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2684  CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2685  if (ret.Failed()) return ret;
2686  }
2687  }
2688 
2689  /* Depots refer to towns. */
2690  const Depot *d;
2691  FOR_ALL_DEPOTS(d) {
2692  if (d->town == t) return CMD_ERROR;
2693  }
2694 
2695  /* Check all tiles for town ownership. */
2696  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2697  bool try_clear = false;
2698  switch (GetTileType(tile)) {
2699  case MP_ROAD:
2700  try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2701  break;
2702 
2703  case MP_TUNNELBRIDGE:
2704  try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2705  break;
2706 
2707  case MP_HOUSE:
2708  try_clear = GetTownIndex(tile) == t->index;
2709  break;
2710 
2711  case MP_INDUSTRY:
2712  try_clear = Industry::GetByTile(tile)->town == t;
2713  break;
2714 
2715  case MP_OBJECT:
2716  if (Town::GetNumItems() == 1) {
2717  /* No towns will be left, remove it! */
2718  try_clear = true;
2719  } else {
2720  Object *o = Object::GetByTile(tile);
2721  if (o->town == t) {
2722  if (o->type == OBJECT_STATUE) {
2723  /* Statue... always remove. */
2724  try_clear = true;
2725  } else {
2726  /* Tell to find a new town. */
2727  if (flags & DC_EXEC) o->town = NULL;
2728  }
2729  }
2730  }
2731  break;
2732 
2733  default:
2734  break;
2735  }
2736  if (try_clear) {
2737  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2738  if (ret.Failed()) return ret;
2739  }
2740  }
2741 
2742  /* The town destructor will delete the other things related to the town. */
2743  if (flags & DC_EXEC) delete t;
2744 
2745  return CommandCost();
2746 }
2747 
2753  2, 4, 9, 35, 48, 53, 117, 175
2754 };
2755 
2756 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2757 {
2758  if (flags & DC_EXEC) {
2759  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2760  }
2761  return CommandCost();
2762 }
2763 
2764 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2765 {
2766  if (flags & DC_EXEC) {
2767  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2768  }
2769  return CommandCost();
2770 }
2771 
2772 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2773 {
2774  if (flags & DC_EXEC) {
2775  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2776  }
2777  return CommandCost();
2778 }
2779 
2780 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2781 {
2782  /* Check if the company is allowed to fund new roads. */
2784 
2785  if (flags & DC_EXEC) {
2786  t->road_build_months = 6;
2787 
2788  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2790  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2791 
2792  char *cn = stredup(company_name);
2793  SetDParam(0, t->index);
2794  SetDParamStr(1, cn);
2795 
2796  AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2797  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2798  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2799  }
2800  return CommandCost();
2801 }
2802 
2808 static bool TryClearTile(TileIndex tile)
2809 {
2810  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2812  cur_company.Restore();
2813  return r.Succeeded();
2814 }
2815 
2820 
2821  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2822 };
2823 
2830 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2831 {
2832  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2833 
2834  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2835  statue_data->tile_count++;
2836 
2837  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2838  if (IsSteepSlope(GetTileSlope(tile))) return false;
2839  /* Don't build statues under bridges. */
2840  if (IsBridgeAbove(tile)) return false;
2841 
2842  /* A clear-able open space is always preferred. */
2843  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2844  statue_data->best_position = tile;
2845  return true;
2846  }
2847 
2848  bool house = IsTileType(tile, MP_HOUSE);
2849 
2850  /* Searching inside the inner circle. */
2851  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2852  /* Save first house in inner circle. */
2853  if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2854  statue_data->best_position = tile;
2855  }
2856 
2857  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2858  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2859  }
2860 
2861  /* Searching outside the circle, just pick the first possible spot. */
2862  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2863  return house && TryClearTile(tile);
2864 }
2865 
2874 {
2875  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2876 
2877  TileIndex tile = t->xy;
2878  StatueBuildSearchData statue_data(INVALID_TILE, 0);
2879  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2880 
2881  if (flags & DC_EXEC) {
2882  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2883  DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2884  cur_company.Restore();
2886  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2887  MarkTileDirtyByTile(statue_data.best_position);
2888  }
2889  return CommandCost();
2890 }
2891 
2892 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2893 {
2894  /* Check if it's allowed to buy the rights */
2896 
2897  if (flags & DC_EXEC) {
2898  /* Build next tick */
2899  t->grow_counter = 1;
2900  /* And grow for 3 months */
2901  t->fund_buildings_months = 3;
2902 
2903  /* Enable growth (also checking GameScript's opinion) */
2904  UpdateTownGrowRate(t);
2905 
2907  }
2908  return CommandCost();
2909 }
2910 
2911 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2912 {
2913  /* Check if it's allowed to buy the rights */
2915 
2916  if (flags & DC_EXEC) {
2917  t->exclusive_counter = 12;
2919 
2920  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
2921 
2923 
2924  /* Spawn news message */
2925  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2927  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
2928  SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
2929  SetDParam(2, t->index);
2930  SetDParamStr(3, cni->company_name);
2931  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
2932  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2933  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2934  }
2935  return CommandCost();
2936 }
2937 
2938 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
2939 {
2940  if (flags & DC_EXEC) {
2941  if (Chance16(1, 14)) {
2942  /* set as unwanted for 6 months */
2943  t->unwanted[_current_company] = 6;
2944 
2945  /* set all close by station ratings to 0 */
2946  Station *st;
2947  FOR_ALL_STATIONS(st) {
2948  if (st->town == t && st->owner == _current_company) {
2949  for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
2950  }
2951  }
2952 
2953  /* only show error message to the executing player. All errors are handled command.c
2954  * but this is special, because it can only 'fail' on a DC_EXEC */
2955  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
2956 
2957  /* decrease by a lot!
2958  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
2959  * be independent of any cheat settings
2960  */
2961  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
2962  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
2964  }
2965  } else {
2966  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
2967  }
2968  }
2969  return CommandCost();
2970 }
2971 
2972 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
2973 static TownActionProc * const _town_action_proc[] = {
2974  TownActionAdvertiseSmall,
2975  TownActionAdvertiseMedium,
2976  TownActionAdvertiseLarge,
2977  TownActionRoadRebuild,
2979  TownActionFundBuildings,
2980  TownActionBuyRights,
2981  TownActionBribe
2982 };
2983 
2991 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
2992 {
2993  int num = 0;
2994  TownActions buttons = TACT_NONE;
2995 
2996  /* Spectators and unwanted have no options */
2997  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
2998 
2999  /* Things worth more than this are not shown */
3000  Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3001 
3002  /* Check the action bits for validity and
3003  * if they are valid add them */
3004  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3005  const TownActions cur = (TownActions)(1 << i);
3006 
3007  /* Is the company not able to bribe ? */
3008  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3009 
3010  /* Is the company not able to buy exclusive rights ? */
3011  if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3012 
3013  /* Is the company not able to fund buildings ? */
3014  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3015 
3016  /* Is the company not able to fund local road reconstruction? */
3017  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3018 
3019  /* Is the company not able to build a statue ? */
3020  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3021 
3022  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3023  buttons |= cur;
3024  num++;
3025  }
3026  }
3027  }
3028 
3029  if (nump != NULL) *nump = num;
3030  return buttons;
3031 }
3032 
3044 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3045 {
3046  Town *t = Town::GetIfValid(p1);
3047  if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3048 
3049  if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3050 
3051  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3052 
3053  CommandCost ret = _town_action_proc[p2](t, flags);
3054  if (ret.Failed()) return ret;
3055 
3056  if (flags & DC_EXEC) {
3058  }
3059 
3060  return cost;
3061 }
3062 
3063 static void UpdateTownRating(Town *t)
3064 {
3065  /* Increase company ratings if they're low */
3066  const Company *c;
3067  FOR_ALL_COMPANIES(c) {
3068  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3070  }
3071  }
3072 
3073  const Station *st;
3074  FOR_ALL_STATIONS(st) {
3075  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3076  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3077  if (Company::IsValidID(st->owner)) {
3078  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3079  t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3080  }
3081  } else {
3082  if (Company::IsValidID(st->owner)) {
3083  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3084  t->ratings[st->owner] = max(new_rating, INT16_MIN);
3085  }
3086  }
3087  }
3088  }
3089 
3090  /* clamp all ratings to valid values */
3091  for (uint i = 0; i < MAX_COMPANIES; i++) {
3092  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3093  }
3094 
3096 }
3097 
3098 static void UpdateTownGrowRate(Town *t)
3099 {
3102 
3103  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3104 
3105  if (t->fund_buildings_months == 0) {
3106  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3107  for (int i = TE_BEGIN; i < TE_END; i++) {
3108  switch (t->goal[i]) {
3109  case TOWN_GROWTH_WINTER:
3110  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3111  break;
3112  case TOWN_GROWTH_DESERT:
3113  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3114  break;
3115  default:
3116  if (t->goal[i] > t->received[i].old_act) return;
3117  break;
3118  }
3119  }
3120  }
3121 
3122  if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
3125  return;
3126  }
3127 
3132  static const uint16 _grow_count_values[2][6] = {
3133  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3134  { 320, 420, 300, 220, 160, 100 } // Normal values
3135  };
3136 
3137  int n = 0;
3138 
3139  const Station *st;
3140  FOR_ALL_STATIONS(st) {
3141  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3142  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3143  n++;
3144  }
3145  }
3146  }
3147 
3148  uint16 m;
3149 
3150  if (t->fund_buildings_months != 0) {
3151  m = _grow_count_values[0][min(n, 5)];
3152  } else {
3153  m = _grow_count_values[1][min(n, 5)];
3154  if (n == 0 && !Chance16(1, 12)) return;
3155  }
3156 
3157  /* Use the normal growth rate values if new buildings have been funded in
3158  * this town and the growth rate is set to none. */
3159  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3160 
3161  m >>= growth_multiplier;
3162  if (t->larger_town) m /= 2;
3163 
3164  t->growth_rate = m / (t->cache.num_houses / 50 + 1);
3166 
3169 }
3170 
3171 static void UpdateTownAmounts(Town *t)
3172 {
3173  for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3174  for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3175  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3176 
3178 }
3179 
3180 static void UpdateTownUnwanted(Town *t)
3181 {
3182  const Company *c;
3183 
3184  FOR_ALL_COMPANIES(c) {
3185  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3186  }
3187 }
3188 
3196 {
3198 
3200  if (t == NULL) return CommandCost();
3201 
3202  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3203 
3204  SetDParam(0, t->index);
3205  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3206 }
3207 
3217 {
3218  Town *t;
3219  uint best = threshold;
3220  Town *best_town = NULL;
3221 
3222  FOR_ALL_TOWNS(t) {
3223  uint dist = DistanceManhattan(tile, t->xy);
3224  if (dist < best) {
3225  best = dist;
3226  best_town = t;
3227  }
3228  }
3229 
3230  return best_town;
3231 }
3232 
3241 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3242 {
3243  switch (GetTileType(tile)) {
3244  case MP_ROAD:
3245  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3246 
3247  if (!HasTownOwnedRoad(tile)) {
3248  TownID tid = GetTownIndex(tile);
3249 
3250  if (tid == (TownID)INVALID_TOWN) {
3251  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3252  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3253  assert(Town::GetNumItems() == 0);
3254  return NULL;
3255  }
3256 
3257  assert(Town::IsValidID(tid));
3258  Town *town = Town::Get(tid);
3259 
3260  if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3261 
3262  return town;
3263  }
3264  /* FALL THROUGH */
3265 
3266  case MP_HOUSE:
3267  return Town::GetByTile(tile);
3268 
3269  default:
3270  return CalcClosestTownFromTile(tile, threshold);
3271  }
3272 }
3273 
3274 static bool _town_rating_test = false;
3276 
3282 void SetTownRatingTestMode(bool mode)
3283 {
3284  static int ref_count = 0; // Number of times test-mode is switched on.
3285  if (mode) {
3286  if (ref_count == 0) {
3287  _town_test_ratings.Clear();
3288  }
3289  ref_count++;
3290  } else {
3291  assert(ref_count > 0);
3292  ref_count--;
3293  }
3294  _town_rating_test = !(ref_count == 0);
3295 }
3296 
3302 static int GetRating(const Town *t)
3303 {
3304  if (_town_rating_test) {
3305  SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3306  if (it != _town_test_ratings.End()) {
3307  return it->second;
3308  }
3309  }
3310  return t->ratings[_current_company];
3311 }
3312 
3320 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3321 {
3322  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3323  if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3325  (_cheats.magic_bulldozer.value && add < 0)) {
3326  return;
3327  }
3328 
3329  int rating = GetRating(t);
3330  if (add < 0) {
3331  if (rating > max) {
3332  rating += add;
3333  if (rating < max) rating = max;
3334  }
3335  } else {
3336  if (rating < max) {
3337  rating += add;
3338  if (rating > max) rating = max;
3339  }
3340  }
3341  if (_town_rating_test) {
3342  _town_test_ratings[t] = rating;
3343  } else {
3345  t->ratings[_current_company] = rating;
3347  }
3348 }
3349 
3358 {
3359  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3360  if (t == NULL || !Company::IsValidID(_current_company) ||
3362  return CommandCost();
3363  }
3364 
3365  /* minimum rating needed to be allowed to remove stuff */
3366  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3367  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3371  };
3372 
3373  /* check if you're allowed to remove the road/bridge/tunnel
3374  * owned by a town no removal if rating is lower than ... depends now on
3375  * difficulty setting. Minimum town rating selected by difficulty level
3376  */
3377  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3378 
3379  if (GetRating(t) < needed) {
3380  SetDParam(0, t->index);
3381  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3382  }
3383 
3384  return CommandCost();
3385 }
3386 
3387 void TownsMonthlyLoop()
3388 {
3389  Town *t;
3390 
3391  FOR_ALL_TOWNS(t) {
3392  if (t->road_build_months != 0) t->road_build_months--;
3393 
3394  if (t->exclusive_counter != 0) {
3395  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3396  }
3397 
3398  UpdateTownAmounts(t);
3399  UpdateTownRating(t);
3400  UpdateTownGrowRate(t);
3401  UpdateTownUnwanted(t);
3402  UpdateTownCargoes(t);
3403  }
3404 
3406 }
3407 
3408 void TownsYearlyLoop()
3409 {
3410  /* Increment house ages */
3411  for (TileIndex t = 0; t < MapSize(); t++) {
3412  if (!IsTileType(t, MP_HOUSE)) continue;
3413  IncrementHouseAge(t);
3414  }
3415 }
3416 
3417 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3418 {
3419  if (AutoslopeEnabled()) {
3420  HouseID house = GetHouseType(tile);
3421  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3422  const HouseSpec *hs = HouseSpec::Get(house);
3423 
3424  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3425  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3426  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3427  bool allow_terraform = true;
3428 
3429  /* Call the autosloping callback per tile, not for the whole building at once. */
3430  house = GetHouseType(tile);
3431  hs = HouseSpec::Get(house);
3433  /* If the callback fails, allow autoslope. */
3434  uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3435  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3436  }
3437 
3438  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3439  }
3440  }
3441 
3442  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3443 }
3444 
3446 extern const TileTypeProcs _tile_type_town_procs = {
3447  DrawTile_Town, // draw_tile_proc
3448  GetSlopePixelZ_Town, // get_slope_z_proc
3449  ClearTile_Town, // clear_tile_proc
3450  AddAcceptedCargo_Town, // add_accepted_cargo_proc
3451  GetTileDesc_Town, // get_tile_desc_proc
3452  GetTileTrackStatus_Town, // get_tile_track_status_proc
3453  NULL, // click_tile_proc
3454  AnimateTile_Town, // animate_tile_proc
3455  TileLoop_Town, // tile_loop_proc
3456  ChangeTileOwner_Town, // change_tile_owner_proc
3457  AddProducedCargo_Town, // add_produced_cargo_proc
3458  NULL, // vehicle_enter_tile_proc
3459  GetFoundation_Town, // get_foundation_proc
3460  TerraformTile_Town, // terraform_tile_proc
3461 };
3462 
3463 
3464 HouseSpec _house_specs[NUM_HOUSES];
3465 
3466 void ResetHouses()
3467 {
3468  memset(&_house_specs, 0, sizeof(_house_specs));
3469  memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3470 
3471  /* Reset any overrides that have been set. */
3472  _house_mngr.ResetOverride();
3473 }