town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 26346 2014-02-16 17:45:24Z frosch $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "road_internal.h" /* Cleaning up road bits */
00014 #include "road_cmd.h"
00015 #include "landscape.h"
00016 #include "viewport_func.h"
00017 #include "cmd_helper.h"
00018 #include "command_func.h"
00019 #include "industry.h"
00020 #include "station_base.h"
00021 #include "company_base.h"
00022 #include "news_func.h"
00023 #include "error.h"
00024 #include "object.h"
00025 #include "genworld.h"
00026 #include "newgrf_debug.h"
00027 #include "newgrf_house.h"
00028 #include "newgrf_text.h"
00029 #include "autoslope.h"
00030 #include "tunnelbridge_map.h"
00031 #include "strings_func.h"
00032 #include "window_func.h"
00033 #include "string_func.h"
00034 #include "newgrf_cargo.h"
00035 #include "cheat_type.h"
00036 #include "animated_tile_func.h"
00037 #include "date_func.h"
00038 #include "subsidy_func.h"
00039 #include "core/pool_func.hpp"
00040 #include "town.h"
00041 #include "townname_func.h"
00042 #include "core/random_func.hpp"
00043 #include "core/backup_type.hpp"
00044 #include "depot_base.h"
00045 #include "object_map.h"
00046 #include "object_base.h"
00047 #include "ai/ai.hpp"
00048 #include "game/game.hpp"
00049 
00050 #include "table/strings.h"
00051 #include "table/town_land.h"
00052 
00053 TownID _new_town_id;
00054 uint32 _town_cargoes_accepted; 
00055 
00056 /* Initialize the town-pool */
00057 TownPool _town_pool("Town");
00058 INSTANTIATE_POOL_METHODS(Town)
00059 
00060 Town::~Town()
00061 {
00062   free(this->name);
00063   free(this->text);
00064 
00065   if (CleaningPool()) return;
00066 
00067   /* Delete town authority window
00068    * and remove from list of sorted towns */
00069   DeleteWindowById(WC_TOWN_VIEW, this->index);
00070 
00071   /* Check no industry is related to us. */
00072   const Industry *i;
00073   FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00074 
00075   /* ... and no object is related to us. */
00076   const Object *o;
00077   FOR_ALL_OBJECTS(o) assert(o->town != this);
00078 
00079   /* Check no tile is related to us. */
00080   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00081     switch (GetTileType(tile)) {
00082       case MP_HOUSE:
00083         assert(GetTownIndex(tile) != this->index);
00084         break;
00085 
00086       case MP_ROAD:
00087         assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00088         break;
00089 
00090       case MP_TUNNELBRIDGE:
00091         assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00092         break;
00093 
00094       default:
00095         break;
00096     }
00097   }
00098 
00099   /* Clear the persistent storage list. */
00100   this->psa_list.clear();
00101 
00102   DeleteSubsidyWith(ST_TOWN, this->index);
00103   DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
00104   CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00105   MarkWholeScreenDirty();
00106 }
00107 
00108 
00114 void Town::PostDestructor(size_t index)
00115 {
00116   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00117   UpdateNearestTownForRoadTiles(false);
00118 
00119   /* Give objects a new home! */
00120   Object *o;
00121   FOR_ALL_OBJECTS(o) {
00122     if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00123   }
00124 }
00125 
00129 void Town::InitializeLayout(TownLayout layout)
00130 {
00131   if (layout != TL_RANDOM) {
00132     this->layout = layout;
00133     return;
00134   }
00135 
00136   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00137 }
00138 
00143 /* static */ Town *Town::GetRandom()
00144 {
00145   if (Town::GetNumItems() == 0) return NULL;
00146   int num = RandomRange((uint16)Town::GetNumItems());
00147   size_t index = MAX_UVALUE(size_t);
00148 
00149   while (num >= 0) {
00150     num--;
00151     index++;
00152 
00153     /* Make sure we have a valid town */
00154     while (!Town::IsValidID(index)) {
00155       index++;
00156       assert(index < Town::GetPoolSize());
00157     }
00158   }
00159 
00160   return Town::Get(index);
00161 }
00162 
00167 Money HouseSpec::GetRemovalCost() const
00168 {
00169   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00170 }
00171 
00172 // Local
00173 static int _grow_town_result;
00174 
00175 /* Describe the possible states */
00176 enum TownGrowthResult {
00177   GROWTH_SUCCEED         = -1,
00178   GROWTH_SEARCH_STOPPED  =  0
00179 //  GROWTH_SEARCH_RUNNING >=  1
00180 };
00181 
00182 static bool BuildTownHouse(Town *t, TileIndex tile);
00183 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00184 
00185 static void TownDrawHouseLift(const TileInfo *ti)
00186 {
00187   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00188 }
00189 
00190 typedef void TownDrawTileProc(const TileInfo *ti);
00191 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00192   TownDrawHouseLift
00193 };
00194 
00200 static inline DiagDirection RandomDiagDir()
00201 {
00202   return (DiagDirection)(3 & Random());
00203 }
00204 
00210 static void DrawTile_Town(TileInfo *ti)
00211 {
00212   HouseID house_id = GetHouseType(ti->tile);
00213 
00214   if (house_id >= NEW_HOUSE_OFFSET) {
00215     /* Houses don't necessarily need new graphics. If they don't have a
00216      * spritegroup associated with them, then the sprite for the substitute
00217      * house id is drawn instead. */
00218     if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00219       DrawNewHouseTile(ti, house_id);
00220       return;
00221     } else {
00222       house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00223     }
00224   }
00225 
00226   /* Retrieve pointer to the draw town tile struct */
00227   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00228 
00229   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00230 
00231   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00232 
00233   /* If houses are invisible, do not draw the upper part */
00234   if (IsInvisibilitySet(TO_HOUSES)) return;
00235 
00236   /* Add a house on top of the ground? */
00237   SpriteID image = dcts->building.sprite;
00238   if (image != 0) {
00239     AddSortableSpriteToDraw(image, dcts->building.pal,
00240       ti->x + dcts->subtile_x,
00241       ti->y + dcts->subtile_y,
00242       dcts->width,
00243       dcts->height,
00244       dcts->dz,
00245       ti->z,
00246       IsTransparencySet(TO_HOUSES)
00247     );
00248 
00249     if (IsTransparencySet(TO_HOUSES)) return;
00250   }
00251 
00252   {
00253     int proc = dcts->draw_proc - 1;
00254 
00255     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00256   }
00257 }
00258 
00259 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
00260 {
00261   return GetTileMaxPixelZ(tile);
00262 }
00263 
00265 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00266 {
00267   HouseID hid = GetHouseType(tile);
00268 
00269   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00270    * account for this, as other structures should
00271    * draw the wall of the foundation in this case.
00272    */
00273   if (hid >= NEW_HOUSE_OFFSET) {
00274     const HouseSpec *hs = HouseSpec::Get(hid);
00275     if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00276       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00277       if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
00278     }
00279   }
00280   return FlatteningFoundation(tileh);
00281 }
00282 
00289 static void AnimateTile_Town(TileIndex tile)
00290 {
00291   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00292     AnimateNewHouseTile(tile);
00293     return;
00294   }
00295 
00296   if (_tick_counter & 3) return;
00297 
00298   /* If the house is not one with a lift anymore, then stop this animating.
00299    * Not exactly sure when this happens, but probably when a house changes.
00300    * Before this was just a return...so it'd leak animated tiles..
00301    * That bug seems to have been here since day 1?? */
00302   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00303     DeleteAnimatedTile(tile);
00304     return;
00305   }
00306 
00307   if (!LiftHasDestination(tile)) {
00308     uint i;
00309 
00310     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00311      * This is due to the fact that the first floor is, in the graphics,
00312      *  the height of 2 'normal' floors.
00313      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00314     do {
00315       i = RandomRange(7);
00316     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00317 
00318     SetLiftDestination(tile, i);
00319   }
00320 
00321   int pos = GetLiftPosition(tile);
00322   int dest = GetLiftDestination(tile) * 6;
00323   pos += (pos < dest) ? 1 : -1;
00324   SetLiftPosition(tile, pos);
00325 
00326   if (pos == dest) {
00327     HaltLift(tile);
00328     DeleteAnimatedTile(tile);
00329   }
00330 
00331   MarkTileDirtyByTile(tile);
00332 }
00333 
00340 static bool IsCloseToTown(TileIndex tile, uint dist)
00341 {
00342   /* On a large map with many towns, it may be faster to check the surroundings of the tile.
00343    * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
00344   if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
00345     const int tx = TileX(tile);
00346     const int ty = TileY(tile);
00347     TileArea tile_area = TileArea(
00348       TileXY(max(0,         tx - (int) dist), max(0,         ty - (int) dist)),
00349       TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
00350     );
00351     TILE_AREA_LOOP(atile, tile_area) {
00352       if (GetTileType(atile) == MP_HOUSE) {
00353         Town *t = Town::GetByTile(atile);
00354         if (DistanceManhattan(tile, t->xy) < dist) return true;
00355       }
00356     }
00357     return false;
00358   }
00359 
00360   const Town *t;
00361 
00362   FOR_ALL_TOWNS(t) {
00363     if (DistanceManhattan(tile, t->xy) < dist) return true;
00364   }
00365   return false;
00366 }
00367 
00372 void Town::UpdateVirtCoord()
00373 {
00374   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00375   SetDParam(0, this->index);
00376   SetDParam(1, this->cache.population);
00377   this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
00378     _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00379 
00380   SetWindowDirty(WC_TOWN_VIEW, this->index);
00381 }
00382 
00384 void UpdateAllTownVirtCoords()
00385 {
00386   Town *t;
00387 
00388   FOR_ALL_TOWNS(t) {
00389     t->UpdateVirtCoord();
00390   }
00391 }
00392 
00398 static void ChangePopulation(Town *t, int mod)
00399 {
00400   t->cache.population += mod;
00401   InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
00402   t->UpdateVirtCoord();
00403 
00404   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00405 }
00406 
00412 uint32 GetWorldPopulation()
00413 {
00414   uint32 pop = 0;
00415   const Town *t;
00416 
00417   FOR_ALL_TOWNS(t) pop += t->cache.population;
00418   return pop;
00419 }
00420 
00425 static void MakeSingleHouseBigger(TileIndex tile)
00426 {
00427   assert(IsTileType(tile, MP_HOUSE));
00428 
00429   /* progress in construction stages */
00430   IncHouseConstructionTick(tile);
00431   if (GetHouseConstructionTick(tile) != 0) return;
00432 
00433   AnimateNewHouseConstruction(tile);
00434 
00435   if (IsHouseCompleted(tile)) {
00436     /* Now that construction is complete, we can add the population of the
00437      * building to the town. */
00438     ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00439     ResetHouseAge(tile);
00440   }
00441   MarkTileDirtyByTile(tile);
00442 }
00443 
00448 static void MakeTownHouseBigger(TileIndex tile)
00449 {
00450   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00451   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00452   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00453   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00454   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00455 }
00456 
00463 static void TileLoop_Town(TileIndex tile)
00464 {
00465   HouseID house_id = GetHouseType(tile);
00466 
00467   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00468    * doesn't exist any more, so don't continue here. */
00469   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00470 
00471   if (!IsHouseCompleted(tile)) {
00472     /* Construction is not completed. See if we can go further in construction*/
00473     MakeTownHouseBigger(tile);
00474     return;
00475   }
00476 
00477   const HouseSpec *hs = HouseSpec::Get(house_id);
00478 
00479   /* If the lift has a destination, it is already an animated tile. */
00480   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00481       house_id < NEW_HOUSE_OFFSET &&
00482       !LiftHasDestination(tile) &&
00483       Chance16(1, 2)) {
00484     AddAnimatedTile(tile);
00485   }
00486 
00487   Town *t = Town::GetByTile(tile);
00488   uint32 r = Random();
00489 
00490   StationFinder stations(TileArea(tile, 1, 1));
00491 
00492   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00493     for (uint i = 0; i < 256; i++) {
00494       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00495 
00496       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00497 
00498       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00499       if (cargo == CT_INVALID) continue;
00500 
00501       uint amt = GB(callback, 0, 8);
00502       if (amt == 0) continue;
00503 
00504       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00505 
00506       const CargoSpec *cs = CargoSpec::Get(cargo);
00507       t->supplied[cs->Index()].new_max += amt;
00508       t->supplied[cs->Index()].new_act += moved;
00509     }
00510   } else {
00511     if (GB(r, 0, 8) < hs->population) {
00512       uint amt = GB(r, 0, 8) / 8 + 1;
00513 
00514       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00515       t->supplied[CT_PASSENGERS].new_max += amt;
00516       t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00517     }
00518 
00519     if (GB(r, 8, 8) < hs->mail_generation) {
00520       uint amt = GB(r, 8, 8) / 8 + 1;
00521 
00522       if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00523       t->supplied[CT_MAIL].new_max += amt;
00524       t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00525     }
00526   }
00527 
00528   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00529 
00530   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00531       HasBit(t->flags, TOWN_IS_GROWING) &&
00532       CanDeleteHouse(tile) &&
00533       GetHouseAge(tile) >= hs->minimum_life &&
00534       --t->time_until_rebuild == 0) {
00535     t->time_until_rebuild = GB(r, 16, 8) + 192;
00536 
00537     ClearTownHouse(t, tile);
00538 
00539     /* Rebuild with another house? */
00540     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00541   }
00542 
00543   cur_company.Restore();
00544 }
00545 
00546 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00547 {
00548   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00549   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00550 
00551   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00552 
00553   CommandCost cost(EXPENSES_CONSTRUCTION);
00554   cost.AddCost(hs->GetRemovalCost());
00555 
00556   int rating = hs->remove_rating_decrease;
00557   Town *t = Town::GetByTile(tile);
00558 
00559   if (Company::IsValidID(_current_company)) {
00560     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00561       SetDParam(0, t->index);
00562       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00563     }
00564   }
00565 
00566   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00567   if (flags & DC_EXEC) {
00568     ClearTownHouse(t, tile);
00569   }
00570 
00571   return cost;
00572 }
00573 
00574 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00575 {
00576   HouseID house_id = GetHouseType(tile);
00577   const HouseSpec *hs = HouseSpec::Get(house_id);
00578   Town *t = Town::GetByTile(tile);
00579 
00580   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00581     for (uint i = 0; i < 256; i++) {
00582       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00583 
00584       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00585 
00586       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00587 
00588       if (cargo == CT_INVALID) continue;
00589       produced[cargo]++;
00590     }
00591   } else {
00592     if (hs->population > 0) {
00593       produced[CT_PASSENGERS]++;
00594     }
00595     if (hs->mail_generation > 0) {
00596       produced[CT_MAIL]++;
00597     }
00598   }
00599 }
00600 
00601 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00602 {
00603   if (cargo == CT_INVALID || amount == 0) return;
00604   acceptance[cargo] += amount;
00605   SetBit(*always_accepted, cargo);
00606 }
00607 
00608 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00609 {
00610   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00611   CargoID accepts[3];
00612 
00613   /* Set the initial accepted cargo types */
00614   for (uint8 i = 0; i < lengthof(accepts); i++) {
00615     accepts[i] = hs->accepts_cargo[i];
00616   }
00617 
00618   /* Check for custom accepted cargo types */
00619   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00620     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00621     if (callback != CALLBACK_FAILED) {
00622       /* Replace accepted cargo types with translated values from callback */
00623       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grf_prop.grffile);
00624       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grf_prop.grffile);
00625       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00626     }
00627   }
00628 
00629   /* Check for custom cargo acceptance */
00630   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00631     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00632     if (callback != CALLBACK_FAILED) {
00633       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00634       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00635       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00636         /* The 'S' bit indicates food instead of goods */
00637         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00638       } else {
00639         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00640       }
00641       return;
00642     }
00643   }
00644 
00645   /* No custom acceptance, so fill in with the default values */
00646   for (uint8 i = 0; i < lengthof(accepts); i++) {
00647     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00648   }
00649 }
00650 
00651 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00652 {
00653   const HouseID house = GetHouseType(tile);
00654   const HouseSpec *hs = HouseSpec::Get(house);
00655   bool house_completed = IsHouseCompleted(tile);
00656 
00657   td->str = hs->building_name;
00658 
00659   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00660   if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
00661     if (callback_res > 0x400) {
00662       ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
00663     } else {
00664       StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00665       if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00666         td->str = new_name;
00667       }
00668     }
00669   }
00670 
00671   if (!house_completed) {
00672     SetDParamX(td->dparam, 0, td->str);
00673     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00674   }
00675 
00676   if (hs->grf_prop.grffile != NULL) {
00677     const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00678     td->grf = gc->GetName();
00679   }
00680 
00681   td->owner[0] = OWNER_TOWN;
00682 }
00683 
00684 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00685 {
00686   /* not used */
00687   return 0;
00688 }
00689 
00690 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00691 {
00692   /* not used */
00693 }
00694 
00698 void UpdateTownCargoTotal(Town *t)
00699 {
00700   t->cargo_accepted_total = 0;
00701 
00702   const TileArea &area = t->cargo_accepted.GetArea();
00703   TILE_AREA_LOOP(tile, area) {
00704     if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00705       t->cargo_accepted_total |= t->cargo_accepted[tile];
00706     }
00707   }
00708 }
00709 
00716 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
00717 {
00718   CargoArray accepted, produced;
00719   uint32 dummy;
00720 
00721   /* Gather acceptance for all houses in an area around the start tile.
00722    * The area is composed of the square the tile is in, extended one square in all
00723    * directions as the coverage area of a single station is bigger than just one square. */
00724   TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
00725   TILE_AREA_LOOP(tile, area) {
00726     if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
00727 
00728     AddAcceptedCargo_Town(tile, accepted, &dummy);
00729     AddProducedCargo_Town(tile, produced);
00730   }
00731 
00732   /* Create bitmap of produced and accepted cargoes. */
00733   uint32 acc = 0;
00734   for (uint cid = 0; cid < NUM_CARGO; cid++) {
00735     if (accepted[cid] >= 8) SetBit(acc, cid);
00736     if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
00737   }
00738   t->cargo_accepted[start] = acc;
00739 
00740   if (update_total) UpdateTownCargoTotal(t);
00741 }
00742 
00746 void UpdateTownCargoes(Town *t)
00747 {
00748   t->cargo_produced = 0;
00749 
00750   const TileArea &area = t->cargo_accepted.GetArea();
00751   if (area.tile == INVALID_TILE) return;
00752 
00753   /* Update acceptance for each grid square. */
00754   TILE_AREA_LOOP(tile, area) {
00755     if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00756       UpdateTownCargoes(t, tile, false);
00757     }
00758   }
00759 
00760   /* Update the total acceptance. */
00761   UpdateTownCargoTotal(t);
00762 }
00763 
00765 void UpdateTownCargoBitmap()
00766 {
00767   Town *town;
00768   _town_cargoes_accepted = 0;
00769 
00770   FOR_ALL_TOWNS(town) {
00771     _town_cargoes_accepted |= town->cargo_accepted_total;
00772   }
00773 }
00774 
00775 static bool GrowTown(Town *t);
00776 
00777 static void TownTickHandler(Town *t)
00778 {
00779   if (HasBit(t->flags, TOWN_IS_GROWING)) {
00780     int i = t->grow_counter - 1;
00781     if (i < 0) {
00782       if (GrowTown(t)) {
00783         i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
00784       } else {
00785         i = 0;
00786       }
00787     }
00788     t->grow_counter = i;
00789   }
00790 }
00791 
00792 void OnTick_Town()
00793 {
00794   if (_game_mode == GM_EDITOR) return;
00795 
00796   Town *t;
00797   FOR_ALL_TOWNS(t) {
00798     /* Run town tick at regular intervals, but not all at once. */
00799     if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00800       TownTickHandler(t);
00801     }
00802   }
00803 }
00804 
00813 static RoadBits GetTownRoadBits(TileIndex tile)
00814 {
00815   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00816 
00817   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00818 }
00819 
00830 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00831 {
00832   if (!IsValidTile(tile)) return false;
00833 
00834   /* Lookup table for the used diff values */
00835   const TileIndexDiff tid_lt[3] = {
00836     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00837     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00838     TileOffsByDiagDir(ReverseDiagDir(dir)),
00839   };
00840 
00841   dist_multi = (dist_multi + 1) * 4;
00842   for (uint pos = 4; pos < dist_multi; pos++) {
00843     /* Go (pos / 4) tiles to the left or the right */
00844     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00845 
00846     /* Use the current tile as origin, or go one tile backwards */
00847     if (pos & 2) cur += tid_lt[2];
00848 
00849     /* Test for roadbit parallel to dir and facing towards the middle axis */
00850     if (IsValidTile(tile + cur) &&
00851         GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00852   }
00853   return false;
00854 }
00855 
00864 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00865 {
00866   if (DistanceFromEdge(tile) == 0) return false;
00867 
00868   /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
00869   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
00870 
00871   /* Check if there already is a road at this point? */
00872   if (GetTownRoadBits(tile) == ROAD_NONE) {
00873     /* No, try if we are able to build a road piece there.
00874      * If that fails clear the land, and if that fails exit.
00875      * This is to make sure that we can build a road here later. */
00876     if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00877         DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
00878       return false;
00879     }
00880   }
00881 
00882   Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
00883   bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00884   if (cur_slope == SLOPE_FLAT) return ret;
00885 
00886   /* If the tile is not a slope in the right direction, then
00887    * maybe terraform some. */
00888   Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00889   if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00890     if (Chance16(1, 8)) {
00891       CommandCost res = CMD_ERROR;
00892       if (!_generating_world && Chance16(1, 10)) {
00893         /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00894         res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00895             DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00896       }
00897       if (res.Failed() && Chance16(1, 3)) {
00898         /* We can consider building on the slope, though. */
00899         return ret;
00900       }
00901     }
00902     return false;
00903   }
00904   return ret;
00905 }
00906 
00907 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00908 {
00909   assert(tile < MapSize());
00910 
00911   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00912   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00913   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00914   return true;
00915 }
00916 
00917 static void LevelTownLand(TileIndex tile)
00918 {
00919   assert(tile < MapSize());
00920 
00921   /* Don't terraform if land is plain or if there's a house there. */
00922   if (IsTileType(tile, MP_HOUSE)) return;
00923   Slope tileh = GetTileSlope(tile);
00924   if (tileh == SLOPE_FLAT) return;
00925 
00926   /* First try up, then down */
00927   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00928     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00929   }
00930 }
00931 
00941 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00942 {
00943   /* align the grid to the downtown */
00944   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00945   RoadBits rcmd = ROAD_NONE;
00946 
00947   switch (t->layout) {
00948     default: NOT_REACHED();
00949 
00950     case TL_2X2_GRID:
00951       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00952       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00953       break;
00954 
00955     case TL_3X3_GRID:
00956       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00957       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00958       break;
00959   }
00960 
00961   /* Optimise only X-junctions */
00962   if (rcmd != ROAD_ALL) return rcmd;
00963 
00964   RoadBits rb_template;
00965 
00966   switch (GetTileSlope(tile)) {
00967     default:       rb_template = ROAD_ALL; break;
00968     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00969     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00970     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00971     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00972     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00973     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00974     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00975     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00976     case SLOPE_STEEP_W:
00977     case SLOPE_STEEP_S:
00978     case SLOPE_STEEP_E:
00979     case SLOPE_STEEP_N:
00980       rb_template = ROAD_NONE;
00981       break;
00982   }
00983 
00984   /* Stop if the template is compatible to the growth dir */
00985   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00986   /* If not generate a straight road in the direction of the growth */
00987   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00988 }
00989 
01000 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
01001 {
01002   /* We can't look further than that. */
01003   if (DistanceFromEdge(tile) == 0) return false;
01004 
01005   uint counter = 0; // counts the house neighbor tiles
01006 
01007   /* Check the tiles E,N,W and S of the current tile for houses */
01008   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
01009     /* Count both void and house tiles for checking whether there
01010      * are enough houses in the area. This to make it likely that
01011      * houses get build up to the edge of the map. */
01012     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
01013       case MP_HOUSE:
01014       case MP_VOID:
01015         counter++;
01016         break;
01017 
01018       default:
01019         break;
01020     }
01021 
01022     /* If there are enough neighbors stop here */
01023     if (counter >= 3) {
01024       if (BuildTownHouse(t, tile)) {
01025         _grow_town_result = GROWTH_SUCCEED;
01026         return true;
01027       }
01028       return false;
01029     }
01030   }
01031   return false;
01032 }
01033 
01042 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01043 {
01044   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01045     _grow_town_result = GROWTH_SUCCEED;
01046     return true;
01047   }
01048   return false;
01049 }
01050 
01061 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01062 {
01063   assert(bridge_dir < DIAGDIR_END);
01064 
01065   const Slope slope = GetTileSlope(tile);
01066 
01067   /* Make sure the direction is compatible with the slope.
01068    * Well we check if the slope has an up bit set in the
01069    * reverse direction. */
01070   if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
01071 
01072   /* Assure that the bridge is connectable to the start side */
01073   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01074 
01075   /* We are in the right direction */
01076   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
01077   TileIndex bridge_tile = tile; // Used to store the other waterside
01078 
01079   const int delta = TileOffsByDiagDir(bridge_dir);
01080 
01081   if (slope == SLOPE_FLAT) {
01082     /* Bridges starting on flat tiles are only allowed when crossing rivers. */
01083     do {
01084       if (bridge_length++ >= 4) {
01085         /* Allow to cross rivers, not big lakes. */
01086         return false;
01087       }
01088       bridge_tile += delta;
01089     } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
01090   } else {
01091     do {
01092       if (bridge_length++ >= 11) {
01093         /* Max 11 tile long bridges */
01094         return false;
01095       }
01096       bridge_tile += delta;
01097     } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
01098   }
01099 
01100   /* no water tiles in between? */
01101   if (bridge_length == 1) return false;
01102 
01103   for (uint8 times = 0; times <= 22; times++) {
01104     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01105 
01106     /* Can we actually build the bridge? */
01107     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01108       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01109       _grow_town_result = GROWTH_SUCCEED;
01110       return true;
01111     }
01112   }
01113   /* Quit if it selecting an appropriate bridge type fails a large number of times. */
01114   return false;
01115 }
01116 
01134 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01135 {
01136   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01137   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01138 
01139   assert(tile < MapSize());
01140 
01141   if (cur_rb == ROAD_NONE) {
01142     /* Tile has no road. First reset the status counter
01143      * to say that this is the last iteration. */
01144     _grow_town_result = GROWTH_SEARCH_STOPPED;
01145 
01146     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01147     if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01148 
01149     /* Remove hills etc */
01150     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01151 
01152     /* Is a road allowed here? */
01153     switch (t1->layout) {
01154       default: NOT_REACHED();
01155 
01156       case TL_3X3_GRID:
01157       case TL_2X2_GRID:
01158         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01159         if (rcmd == ROAD_NONE) return;
01160         break;
01161 
01162       case TL_BETTER_ROADS:
01163       case TL_ORIGINAL:
01164         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01165 
01166         DiagDirection source_dir = ReverseDiagDir(target_dir);
01167 
01168         if (Chance16(1, 4)) {
01169           /* Randomize a new target dir */
01170           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01171         }
01172 
01173         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01174           /* A road is not allowed to continue the randomized road,
01175            *  return if the road we're trying to build is curved. */
01176           if (target_dir != ReverseDiagDir(source_dir)) return;
01177 
01178           /* Return if neither side of the new road is a house */
01179           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01180               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01181             return;
01182           }
01183 
01184           /* That means that the road is only allowed if there is a house
01185            *  at any side of the new road. */
01186         }
01187 
01188         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01189         break;
01190     }
01191 
01192   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01193     /* Continue building on a partial road.
01194      * Should be always OK, so we only generate
01195      * the fitting RoadBits */
01196     _grow_town_result = GROWTH_SEARCH_STOPPED;
01197 
01198     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01199 
01200     switch (t1->layout) {
01201       default: NOT_REACHED();
01202 
01203       case TL_3X3_GRID:
01204       case TL_2X2_GRID:
01205         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01206         break;
01207 
01208       case TL_BETTER_ROADS:
01209       case TL_ORIGINAL:
01210         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01211         break;
01212     }
01213   } else {
01214     bool allow_house = true; // Value which decides if we want to construct a house
01215 
01216     /* Reached a tunnel/bridge? Then continue at the other side of it, unless
01217      * it is the starting tile. Half the time, we stay on this side then.*/
01218     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01219       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
01220         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01221       }
01222       return;
01223     }
01224 
01225     /* Possibly extend the road in a direction.
01226      * Randomize a direction and if it has a road, bail out. */
01227     target_dir = RandomDiagDir();
01228     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01229 
01230     /* This is the tile we will reach if we extend to this direction. */
01231     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01232 
01233     /* Don't walk into water. */
01234     if (HasTileWaterGround(house_tile)) return;
01235 
01236     if (!IsValidTile(house_tile)) return;
01237 
01238     if (_settings_game.economy.allow_town_roads || _generating_world) {
01239       switch (t1->layout) {
01240         default: NOT_REACHED();
01241 
01242         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01243           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01244           /* FALL THROUGH */
01245 
01246         case TL_2X2_GRID:
01247           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01248           allow_house = (rcmd == ROAD_NONE);
01249           break;
01250 
01251         case TL_BETTER_ROADS: // Use original afterwards!
01252           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01253           /* FALL THROUGH */
01254 
01255         case TL_ORIGINAL:
01256           /* Allow a house at the edge. 60% chance or
01257            * always ok if no road allowed. */
01258           rcmd = DiagDirToRoadBits(target_dir);
01259           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01260           break;
01261       }
01262     }
01263 
01264     if (allow_house) {
01265       /* Build a house, but not if there already is a house there. */
01266       if (!IsTileType(house_tile, MP_HOUSE)) {
01267         /* Level the land if possible */
01268         if (Chance16(1, 6)) LevelTownLand(house_tile);
01269 
01270         /* And build a house.
01271          * Set result to -1 if we managed to build it. */
01272         if (BuildTownHouse(t1, house_tile)) {
01273           _grow_town_result = GROWTH_SUCCEED;
01274         }
01275       }
01276       return;
01277     }
01278 
01279     _grow_town_result = GROWTH_SEARCH_STOPPED;
01280   }
01281 
01282   /* Return if a water tile */
01283   if (HasTileWaterGround(tile)) return;
01284 
01285   /* Make the roads look nicer */
01286   rcmd = CleanUpRoadBits(tile, rcmd);
01287   if (rcmd == ROAD_NONE) return;
01288 
01289   /* Only use the target direction for bridges to ensure they're connected.
01290    * The target_dir is as computed previously according to town layout, so
01291    * it will match it perfectly. */
01292   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01293 
01294   GrowTownWithRoad(t1, tile, rcmd);
01295 }
01296 
01303 static int GrowTownAtRoad(Town *t, TileIndex tile)
01304 {
01305   /* Special case.
01306    * @see GrowTownInTile Check the else if
01307    */
01308   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01309 
01310   assert(tile < MapSize());
01311 
01312   /* Number of times to search.
01313    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01314    * them a little handicap. */
01315   switch (t->layout) {
01316     case TL_BETTER_ROADS:
01317       _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
01318       break;
01319 
01320     case TL_3X3_GRID:
01321     case TL_2X2_GRID:
01322       _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
01323       break;
01324 
01325     default:
01326       _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
01327       break;
01328   }
01329 
01330   do {
01331     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01332 
01333     /* Try to grow the town from this point */
01334     GrowTownInTile(&tile, cur_rb, target_dir, t);
01335 
01336     /* Exclude the source position from the bitmask
01337      * and return if no more road blocks available */
01338     if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01339     if (cur_rb == ROAD_NONE) {
01340       return _grow_town_result;
01341     }
01342 
01343     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01344       /* Only build in the direction away from the tunnel or bridge. */
01345       target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
01346     } else {
01347       /* Select a random bit from the blockmask, walk a step
01348        * and continue the search from there. */
01349       do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01350     }
01351     tile = TileAddByDiagDir(tile, target_dir);
01352 
01353     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01354       /* Don't allow building over roads of other cities */
01355       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01356         _grow_town_result = GROWTH_SUCCEED;
01357       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01358         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01359          * owner :) (happy happy happy road now) */
01360         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01361         SetTownIndex(tile, t->index);
01362       }
01363     }
01364 
01365     /* Max number of times is checked. */
01366   } while (--_grow_town_result >= 0);
01367 
01368   return (_grow_town_result == -2);
01369 }
01370 
01378 static RoadBits GenRandomRoadBits()
01379 {
01380   uint32 r = Random();
01381   uint a = GB(r, 0, 2);
01382   uint b = GB(r, 8, 2);
01383   if (a == b) b ^= 2;
01384   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01385 }
01386 
01392 static bool GrowTown(Town *t)
01393 {
01394   static const TileIndexDiffC _town_coord_mod[] = {
01395     {-1,  0},
01396     { 1,  1},
01397     { 1, -1},
01398     {-1, -1},
01399     {-1,  0},
01400     { 0,  2},
01401     { 2,  0},
01402     { 0, -2},
01403     {-1, -1},
01404     {-2,  2},
01405     { 2,  2},
01406     { 2, -2},
01407     { 0,  0}
01408   };
01409 
01410   /* Current "company" is a town */
01411   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01412 
01413   TileIndex tile = t->xy; // The tile we are working with ATM
01414 
01415   /* Find a road that we can base the construction on. */
01416   const TileIndexDiffC *ptr;
01417   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01418     if (GetTownRoadBits(tile) != ROAD_NONE) {
01419       int r = GrowTownAtRoad(t, tile);
01420       cur_company.Restore();
01421       return r != 0;
01422     }
01423     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01424   }
01425 
01426   /* No road available, try to build a random road block by
01427    * clearing some land and then building a road there. */
01428   if (_settings_game.economy.allow_town_roads || _generating_world) {
01429     tile = t->xy;
01430     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01431       /* Only work with plain land that not already has a house */
01432       if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
01433         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01434           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01435           cur_company.Restore();
01436           return true;
01437         }
01438       }
01439       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01440     }
01441   }
01442 
01443   cur_company.Restore();
01444   return false;
01445 }
01446 
01447 void UpdateTownRadius(Town *t)
01448 {
01449   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01450     {  4,  0,  0,  0,  0}, // 0
01451     { 16,  0,  0,  0,  0},
01452     { 25,  0,  0,  0,  0},
01453     { 36,  0,  0,  0,  0},
01454     { 49,  0,  4,  0,  0},
01455     { 64,  0,  4,  0,  0}, // 20
01456     { 64,  0,  9,  0,  1},
01457     { 64,  0,  9,  0,  4},
01458     { 64,  0, 16,  0,  4},
01459     { 81,  0, 16,  0,  4},
01460     { 81,  0, 16,  0,  4}, // 40
01461     { 81,  0, 25,  0,  9},
01462     { 81, 36, 25,  0,  9},
01463     { 81, 36, 25, 16,  9},
01464     { 81, 49,  0, 25,  9},
01465     { 81, 64,  0, 25,  9}, // 60
01466     { 81, 64,  0, 36,  9},
01467     { 81, 64,  0, 36, 16},
01468     {100, 81,  0, 49, 16},
01469     {100, 81,  0, 49, 25},
01470     {121, 81,  0, 49, 25}, // 80
01471     {121, 81,  0, 49, 25},
01472     {121, 81,  0, 49, 36}, // 88
01473   };
01474 
01475   if (t->cache.num_houses < 92) {
01476     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));
01477   } else {
01478     int mass = t->cache.num_houses / 8;
01479     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01480      * The offsets are to make sure the radii do not decrease in size when going from the table
01481      * to the calculated value.*/
01482     t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
01483     t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
01484     t->cache.squared_town_zone_radius[2] = 0;
01485     t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
01486     t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
01487   }
01488 }
01489 
01490 void UpdateTownMaxPass(Town *t)
01491 {
01492   t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
01493   t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
01494 }
01495 
01507 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01508 {
01509   t->xy = tile;
01510   t->cache.num_houses = 0;
01511   t->time_until_rebuild = 10;
01512   UpdateTownRadius(t);
01513   t->flags = 0;
01514   t->cache.population = 0;
01515   t->grow_counter = 0;
01516   t->growth_rate = 250;
01517 
01518   /* Set the default cargo requirement for town growth */
01519   switch (_settings_game.game_creation.landscape) {
01520     case LT_ARCTIC:
01521       if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
01522       break;
01523 
01524     case LT_TROPIC:
01525       if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
01526       if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
01527       break;
01528   }
01529 
01530   t->fund_buildings_months = 0;
01531 
01532   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01533 
01534   t->have_ratings = 0;
01535   t->exclusivity = INVALID_COMPANY;
01536   t->exclusive_counter = 0;
01537   t->statues = 0;
01538 
01539   extern int _nb_orig_names;
01540   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01541     /* Original town name */
01542     t->townnamegrfid = 0;
01543     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01544   } else {
01545     /* Newgrf town name */
01546     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01547     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01548   }
01549   t->townnameparts = townnameparts;
01550 
01551   t->UpdateVirtCoord();
01552   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01553 
01554   t->InitializeLayout(layout);
01555 
01556   t->larger_town = city;
01557 
01558   int x = (int)size * 16 + 3;
01559   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01560   /* Don't create huge cities when founding town in-game */
01561   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01562 
01563   t->cache.num_houses += x;
01564   UpdateTownRadius(t);
01565 
01566   int i = x * 4;
01567   do {
01568     GrowTown(t);
01569   } while (--i);
01570 
01571   t->cache.num_houses -= x;
01572   UpdateTownRadius(t);
01573   UpdateTownMaxPass(t);
01574   UpdateAirportsNoise();
01575 }
01576 
01582 static CommandCost TownCanBePlacedHere(TileIndex tile)
01583 {
01584   /* Check if too close to the edge of map */
01585   if (DistanceFromEdge(tile) < 12) {
01586     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01587   }
01588 
01589   /* Check distance to all other towns. */
01590   if (IsCloseToTown(tile, 20)) {
01591     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01592   }
01593 
01594   /* Can only build on clear flat areas, possibly with trees. */
01595   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
01596     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01597   }
01598 
01599   return CommandCost(EXPENSES_OTHER);
01600 }
01601 
01607 static bool IsUniqueTownName(const char *name)
01608 {
01609   const Town *t;
01610 
01611   FOR_ALL_TOWNS(t) {
01612     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01613   }
01614 
01615   return true;
01616 }
01617 
01630 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01631 {
01632   TownSize size = Extract<TownSize, 0, 2>(p1);
01633   bool city = HasBit(p1, 2);
01634   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01635   TownNameParams par(_settings_game.game_creation.town_name);
01636   bool random = HasBit(p1, 6);
01637   uint32 townnameparts = p2;
01638 
01639   if (size >= TSZ_END) return CMD_ERROR;
01640   if (layout >= NUM_TLS) return CMD_ERROR;
01641 
01642   /* Some things are allowed only in the scenario editor and for game scripts. */
01643   if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
01644     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01645     if (size == TSZ_LARGE) return CMD_ERROR;
01646     if (random) return CMD_ERROR;
01647     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01648       return CMD_ERROR;
01649     }
01650   } else if (_current_company == OWNER_DEITY && random) {
01651     /* Random parameter is not allowed for Game Scripts. */
01652     return CMD_ERROR;
01653   }
01654 
01655   if (StrEmpty(text)) {
01656     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01657     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01658   } else {
01659     /* If name is not empty, it has to be unique custom name */
01660     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01661     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01662   }
01663 
01664   /* Allocate town struct */
01665   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01666 
01667   if (!random) {
01668     CommandCost ret = TownCanBePlacedHere(tile);
01669     if (ret.Failed()) return ret;
01670   }
01671 
01672   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01673   /* multidimensional arrays have to have defined length of non-first dimension */
01674   assert_compile(lengthof(price_mult[0]) == 4);
01675 
01676   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01677   byte mult = price_mult[city][size];
01678 
01679   cost.MultiplyCost(mult);
01680 
01681   /* Create the town */
01682   if (flags & DC_EXEC) {
01683     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01684       _additional_cash_required = cost.GetCost();
01685       return CommandCost(EXPENSES_OTHER);
01686     }
01687 
01688     Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
01689     UpdateNearestTownForRoadTiles(true);
01690     Town *t;
01691     if (random) {
01692       t = CreateRandomTown(20, townnameparts, size, city, layout);
01693       if (t == NULL) {
01694         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01695       } else {
01696         _new_town_id = t->index;
01697       }
01698     } else {
01699       t = new Town(tile);
01700       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01701     }
01702     UpdateNearestTownForRoadTiles(false);
01703     old_generating_world.Restore();
01704 
01705     if (t != NULL && !StrEmpty(text)) {
01706       t->name = strdup(text);
01707       t->UpdateVirtCoord();
01708     }
01709 
01710     if (_game_mode != GM_EDITOR) {
01711       /* 't' can't be NULL since 'random' is false outside scenedit */
01712       assert(!random);
01713       char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01714       SetDParam(0, _current_company);
01715       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01716 
01717       char *cn = strdup(company_name);
01718       SetDParamStr(0, cn);
01719       SetDParam(1, t->index);
01720 
01721       AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
01722       AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
01723       Game::NewEvent(new ScriptEventTownFounded(t->index));
01724     }
01725   }
01726   return cost;
01727 }
01728 
01738 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01739 {
01740   switch (layout) {
01741     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01742     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01743     default:          return tile;
01744   }
01745 }
01746 
01756 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01757 {
01758   switch (layout) {
01759     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01760     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01761     default:          return true;
01762   }
01763 }
01764 
01768 struct SpotData {
01769   TileIndex tile; 
01770   uint max_dist;  
01771   TownLayout layout; 
01772 };
01773 
01790 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01791 {
01792   SpotData *sp = (SpotData*)user_data;
01793   uint dist = GetClosestWaterDistance(tile, true);
01794 
01795   if (IsTileType(tile, MP_CLEAR) &&
01796       IsTileFlat(tile) &&
01797       IsTileAlignedToGrid(tile, sp->layout) &&
01798       dist > sp->max_dist) {
01799     sp->tile = tile;
01800     sp->max_dist = dist;
01801   }
01802 
01803   return false;
01804 }
01805 
01812 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01813 {
01814   return IsTileType(tile, MP_CLEAR);
01815 }
01816 
01829 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01830 {
01831   SpotData sp = { INVALID_TILE, 0, layout };
01832 
01833   TileIndex coast = tile;
01834   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01835     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01836     return sp.tile;
01837   }
01838 
01839   /* if we get here just give up */
01840   return INVALID_TILE;
01841 }
01842 
01843 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01844 {
01845   assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
01846 
01847   if (!Town::CanAllocateItem()) return NULL;
01848 
01849   do {
01850     /* Generate a tile index not too close from the edge */
01851     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01852 
01853     /* if we tried to place the town on water, slide it over onto
01854      * the nearest likely-looking spot */
01855     if (IsTileType(tile, MP_WATER)) {
01856       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01857       if (tile == INVALID_TILE) continue;
01858     }
01859 
01860     /* Make sure town can be placed here */
01861     if (TownCanBePlacedHere(tile).Failed()) continue;
01862 
01863     /* Allocate a town struct */
01864     Town *t = new Town(tile);
01865 
01866     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01867 
01868     /* if the population is still 0 at the point, then the
01869      * placement is so bad it couldn't grow at all */
01870     if (t->cache.population > 0) return t;
01871 
01872     Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01873     CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01874     cur_company.Restore();
01875     assert(rc.Succeeded());
01876 
01877     /* We already know that we can allocate a single town when
01878      * entering this function. However, we create and delete
01879      * a town which "resets" the allocation checks. As such we
01880      * need to check again when assertions are enabled. */
01881     assert(Town::CanAllocateItem());
01882   } while (--attempts != 0);
01883 
01884   return NULL;
01885 }
01886 
01887 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01888 
01896 bool GenerateTowns(TownLayout layout)
01897 {
01898   uint current_number = 0;
01899   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01900   uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01901   total = min(TownPool::MAX_SIZE, total);
01902   uint32 townnameparts;
01903   TownNames town_names;
01904 
01905   SetGeneratingWorldProgress(GWP_TOWN, total);
01906 
01907   /* First attempt will be made at creating the suggested number of towns.
01908    * Note that this is really a suggested value, not a required one.
01909    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01910   do {
01911     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01912     IncreaseGeneratingWorldProgress(GWP_TOWN);
01913     /* Get a unique name for the town. */
01914     if (!GenerateTownName(&townnameparts, &town_names)) continue;
01915     /* try 20 times to create a random-sized town for the first loop. */
01916     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
01917   } while (--total);
01918 
01919   town_names.clear();
01920 
01921   if (current_number != 0) return true;
01922 
01923   /* If current_number is still zero at this point, it means that not a single town has been created.
01924    * So give it a last try, but now more aggressive */
01925   if (GenerateTownName(&townnameparts) &&
01926       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01927     return true;
01928   }
01929 
01930   /* If there are no towns at all and we are generating new game, bail out */
01931   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01932     ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
01933   }
01934 
01935   return false;  // we are still without a town? we failed, simply
01936 }
01937 
01938 
01945 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01946 {
01947   uint dist = DistanceSquare(tile, t->xy);
01948 
01949   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01950 
01951   HouseZonesBits smallest = HZB_TOWN_EDGE;
01952   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01953     if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
01954   }
01955 
01956   return smallest;
01957 }
01958 
01969 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01970 {
01971   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01972 
01973   assert(cc.Succeeded());
01974 
01975   IncreaseBuildingCount(t, type);
01976   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01977   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01978 
01979   MarkTileDirtyByTile(tile);
01980 }
01981 
01982 
01993 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01994 {
01995   BuildingFlags size = HouseSpec::Get(type)->building_flags;
01996 
01997   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01998   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01999   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
02000   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
02001 }
02002 
02003 
02012 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
02013 {
02014   /* cannot build on these slopes... */
02015   Slope slope = GetTileSlope(tile);
02016   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
02017 
02018   /* building under a bridge? */
02019   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02020 
02021   /* do not try to build over house owned by another town */
02022   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
02023 
02024   /* can we clear the land? */
02025   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
02026 }
02027 
02028 
02038 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
02039 {
02040   if (!CanBuildHouseHere(tile, town, noslope)) return false;
02041 
02042   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
02043   if (GetTileMaxZ(tile) != z) return false;
02044 
02045   return true;
02046 }
02047 
02048 
02058 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
02059 {
02060   /* we need to check this tile too because we can be at different tile now */
02061   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02062 
02063   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02064     tile += TileOffsByDiagDir(d);
02065     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02066   }
02067 
02068   return true;
02069 }
02070 
02071 
02079 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02080 {
02081   /* Allow towns everywhere when we don't build roads */
02082   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02083 
02084   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02085 
02086   switch (t->layout) {
02087     case TL_2X2_GRID:
02088       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02089       break;
02090 
02091     case TL_3X3_GRID:
02092       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02093       break;
02094 
02095     default:
02096       break;
02097   }
02098 
02099   return true;
02100 }
02101 
02102 
02110 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02111 {
02112   /* Allow towns everywhere when we don't build roads */
02113   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02114 
02115   /* Compute relative position of tile. (Positive offsets are towards north) */
02116   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02117 
02118   switch (t->layout) {
02119     case TL_2X2_GRID:
02120       grid_pos.x %= 3;
02121       grid_pos.y %= 3;
02122       if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02123         (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02124       break;
02125 
02126     case TL_3X3_GRID:
02127       if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02128       break;
02129 
02130     default:
02131       break;
02132   }
02133 
02134   return true;
02135 }
02136 
02137 
02147 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
02148 {
02149   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02150 
02151   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02152   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02153 
02154   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02155   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02156     *tile = tile2;
02157     return true;
02158   }
02159 
02160   return false;
02161 }
02162 
02163 
02172 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
02173 {
02174   TileIndex tile2 = *tile;
02175 
02176   for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02177     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02178       *tile = tile2;
02179       return true;
02180     }
02181     if (d == DIAGDIR_END) break;
02182     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02183   }
02184 
02185   return false;
02186 }
02187 
02188 
02195 static bool BuildTownHouse(Town *t, TileIndex tile)
02196 {
02197   /* forbidden building here by town layout */
02198   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02199 
02200   /* no house allowed at all, bail out */
02201   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02202 
02203   Slope slope = GetTileSlope(tile);
02204   int maxz = GetTileMaxZ(tile);
02205 
02206   /* Get the town zone type of the current tile, as well as the climate.
02207    * This will allow to easily compare with the specs of the new house to build */
02208   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02209 
02210   /* Above snow? */
02211   int land = _settings_game.game_creation.landscape;
02212   if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
02213 
02214   uint bitmask = (1 << rad) + (1 << (land + 12));
02215 
02216   /* bits 0-4 are used
02217    * bits 11-15 are used
02218    * bits 5-10 are not used. */
02219   HouseID houses[NUM_HOUSES];
02220   uint num = 0;
02221   uint probs[NUM_HOUSES];
02222   uint probability_max = 0;
02223 
02224   /* Generate a list of all possible houses that can be built. */
02225   for (uint i = 0; i < NUM_HOUSES; i++) {
02226     const HouseSpec *hs = HouseSpec::Get(i);
02227 
02228     /* Verify that the candidate house spec matches the current tile status */
02229     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02230 
02231     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02232     if (hs->class_id != HOUSE_NO_CLASS) {
02233       /* id_count is always <= class_count, so it doesn't need to be checked */
02234       if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02235     } else {
02236       /* If the house has no class, check id_count instead */
02237       if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
02238     }
02239 
02240     /* Without NewHouses, all houses have probability '1' */
02241     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02242     probability_max += cur_prob;
02243     probs[num] = cur_prob;
02244     houses[num++] = (HouseID)i;
02245   }
02246 
02247   TileIndex baseTile = tile;
02248 
02249   while (probability_max > 0) {
02250     /* Building a multitile building can change the location of tile.
02251      * The building would still be built partially on that tile, but
02252      * its northern tile would be elsewhere. However, if the callback
02253      * fails we would be basing further work from the changed tile.
02254      * So a next 1x1 tile building could be built on the wrong tile. */
02255     tile = baseTile;
02256 
02257     uint r = RandomRange(probability_max);
02258     uint i;
02259     for (i = 0; i < num; i++) {
02260       if (probs[i] > r) break;
02261       r -= probs[i];
02262     }
02263 
02264     HouseID house = houses[i];
02265     probability_max -= probs[i];
02266 
02267     /* remove tested house from the set */
02268     num--;
02269     houses[i] = houses[num];
02270     probs[i] = probs[num];
02271 
02272     const HouseSpec *hs = HouseSpec::Get(house);
02273 
02274     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02275         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02276       continue;
02277     }
02278 
02279     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02280 
02281     /* Special houses that there can be only one of. */
02282     uint oneof = 0;
02283 
02284     if (hs->building_flags & BUILDING_IS_CHURCH) {
02285       SetBit(oneof, TOWN_HAS_CHURCH);
02286     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02287       SetBit(oneof, TOWN_HAS_STADIUM);
02288     }
02289 
02290     if (t->flags & oneof) continue;
02291 
02292     /* Make sure there is no slope? */
02293     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02294     if (noslope && slope != SLOPE_FLAT) continue;
02295 
02296     if (hs->building_flags & TILE_SIZE_2x2) {
02297       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02298     } else if (hs->building_flags & TILE_SIZE_2x1) {
02299       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02300     } else if (hs->building_flags & TILE_SIZE_1x2) {
02301       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02302     } else {
02303       /* 1x1 house checks are already done */
02304     }
02305 
02306     byte random_bits = Random();
02307 
02308     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02309       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02310       if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
02311     }
02312 
02313     /* build the house */
02314     t->cache.num_houses++;
02315 
02316     /* Special houses that there can be only one of. */
02317     t->flags |= oneof;
02318 
02319     byte construction_counter = 0;
02320     byte construction_stage = 0;
02321 
02322     if (_generating_world || _game_mode == GM_EDITOR) {
02323       uint32 r = Random();
02324 
02325       construction_stage = TOWN_HOUSE_COMPLETED;
02326       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02327 
02328       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02329         ChangePopulation(t, hs->population);
02330       } else {
02331         construction_counter = GB(r, 2, 2);
02332       }
02333     }
02334 
02335     MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02336     UpdateTownRadius(t);
02337     UpdateTownCargoes(t, tile);
02338 
02339     return true;
02340   }
02341 
02342   return false;
02343 }
02344 
02351 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02352 {
02353   assert(IsTileType(tile, MP_HOUSE));
02354   DecreaseBuildingCount(t, house);
02355   DoClearSquare(tile);
02356   DeleteAnimatedTile(tile);
02357 
02358   DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02359 }
02360 
02368 TileIndexDiff GetHouseNorthPart(HouseID &house)
02369 {
02370   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02371     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02372       house--;
02373       return TileDiffXY(-1, 0);
02374     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02375       house--;
02376       return TileDiffXY(0, -1);
02377     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02378       house -= 2;
02379       return TileDiffXY(-1, 0);
02380     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02381       house -= 3;
02382       return TileDiffXY(-1, -1);
02383     }
02384   }
02385   return 0;
02386 }
02387 
02388 void ClearTownHouse(Town *t, TileIndex tile)
02389 {
02390   assert(IsTileType(tile, MP_HOUSE));
02391 
02392   HouseID house = GetHouseType(tile);
02393 
02394   /* need to align the tile to point to the upper left corner of the house */
02395   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02396 
02397   const HouseSpec *hs = HouseSpec::Get(house);
02398 
02399   /* Remove population from the town if the house is finished. */
02400   if (IsHouseCompleted(tile)) {
02401     ChangePopulation(t, -hs->population);
02402   }
02403 
02404   t->cache.num_houses--;
02405 
02406   /* Clear flags for houses that only may exist once/town. */
02407   if (hs->building_flags & BUILDING_IS_CHURCH) {
02408     ClrBit(t->flags, TOWN_HAS_CHURCH);
02409   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02410     ClrBit(t->flags, TOWN_HAS_STADIUM);
02411   }
02412 
02413   /* Do the actual clearing of tiles */
02414   uint eflags = hs->building_flags;
02415   DoClearTownHouseHelper(tile, t, house);
02416   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02417   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02418   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02419 
02420   UpdateTownRadius(t);
02421 
02422   /* Update cargo acceptance. */
02423   UpdateTownCargoes(t, tile);
02424 }
02425 
02435 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02436 {
02437   Town *t = Town::GetIfValid(p1);
02438   if (t == NULL) return CMD_ERROR;
02439 
02440   bool reset = StrEmpty(text);
02441 
02442   if (!reset) {
02443     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02444     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02445   }
02446 
02447   if (flags & DC_EXEC) {
02448     free(t->name);
02449     t->name = reset ? NULL : strdup(text);
02450 
02451     t->UpdateVirtCoord();
02452     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02453     UpdateAllStationVirtCoords();
02454   }
02455   return CommandCost();
02456 }
02457 
02463 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
02464 {
02465   const CargoSpec *cs;
02466   FOR_ALL_CARGOSPECS(cs) {
02467     if (cs->town_effect == effect) return cs;
02468   }
02469   return NULL;
02470 }
02471 
02472 static void UpdateTownGrowRate(Town *t);
02473 
02485 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02486 {
02487   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02488 
02489   TownEffect te = (TownEffect)GB(p1, 16, 8);
02490   if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
02491 
02492   uint16 index = GB(p1, 0, 16);
02493   Town *t = Town::GetIfValid(index);
02494   if (t == NULL) return CMD_ERROR;
02495 
02496   /* Validate if there is a cargo which is the requested TownEffect */
02497   const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
02498   if (cargo == NULL) return CMD_ERROR;
02499 
02500   if (flags & DC_EXEC) {
02501     t->goal[te] = p2;
02502     UpdateTownGrowRate(t);
02503     InvalidateWindowData(WC_TOWN_VIEW, index);
02504   }
02505 
02506   return CommandCost();
02507 }
02508 
02518 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02519 {
02520   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02521   Town *t = Town::GetIfValid(p1);
02522   if (t == NULL) return CMD_ERROR;
02523 
02524   if (flags & DC_EXEC) {
02525     free(t->text);
02526     t->text = StrEmpty(text) ? NULL : strdup(text);
02527     InvalidateWindowData(WC_TOWN_VIEW, p1);
02528   }
02529 
02530   return CommandCost();
02531 }
02532 
02542 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02543 {
02544   if (_current_company != OWNER_DEITY) return CMD_ERROR;
02545   if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
02546   if (GB(p2, 16, 16) != 0) return CMD_ERROR;
02547 
02548   Town *t = Town::GetIfValid(p1);
02549   if (t == NULL) return CMD_ERROR;
02550 
02551   if (flags & DC_EXEC) {
02552     if (p2 == 0) {
02553       /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
02554       t->growth_rate = 0;
02555     } else {
02556       uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
02557       if (t->grow_counter >= old_rate) {
02558         /* This also catches old_rate == 0 */
02559         t->grow_counter = p2;
02560       } else {
02561         /* Scale grow_counter, so half finished houses stay half finished */
02562         t->grow_counter = t->grow_counter * p2 / old_rate;
02563       }
02564       t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
02565     }
02566     UpdateTownGrowRate(t);
02567     InvalidateWindowData(WC_TOWN_VIEW, p1);
02568   }
02569 
02570   return CommandCost();
02571 }
02572 
02582 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02583 {
02584   if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
02585   Town *t = Town::GetIfValid(p1);
02586   if (t == NULL) return CMD_ERROR;
02587 
02588   if (flags & DC_EXEC) {
02589     /* The more houses, the faster we grow */
02590     if (p2 == 0) {
02591       uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
02592       t->cache.num_houses += amount;
02593       UpdateTownRadius(t);
02594 
02595       uint n = amount * 10;
02596       do GrowTown(t); while (--n);
02597 
02598       t->cache.num_houses -= amount;
02599     } else {
02600       for (; p2 > 0; p2--) {
02601         /* Try several times to grow, as we are really suppose to grow */
02602         for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
02603       }
02604     }
02605     UpdateTownRadius(t);
02606 
02607     UpdateTownMaxPass(t);
02608   }
02609 
02610   return CommandCost();
02611 }
02612 
02622 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02623 {
02624   if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
02625   Town *t = Town::GetIfValid(p1);
02626   if (t == NULL) return CMD_ERROR;
02627 
02628   /* Stations refer to towns. */
02629   const Station *st;
02630   FOR_ALL_STATIONS(st) {
02631     if (st->town == t) {
02632       /* Non-oil rig stations are always a problem. */
02633       if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02634       /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
02635       CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02636       if (ret.Failed()) return ret;
02637     }
02638   }
02639 
02640   /* Depots refer to towns. */
02641   const Depot *d;
02642   FOR_ALL_DEPOTS(d) {
02643     if (d->town == t) return CMD_ERROR;
02644   }
02645 
02646   /* Check all tiles for town ownership. */
02647   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02648     bool try_clear = false;
02649     switch (GetTileType(tile)) {
02650       case MP_ROAD:
02651         try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02652         break;
02653 
02654       case MP_TUNNELBRIDGE:
02655         try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02656         break;
02657 
02658       case MP_HOUSE:
02659         try_clear = GetTownIndex(tile) == t->index;
02660         break;
02661 
02662       case MP_INDUSTRY:
02663         try_clear = Industry::GetByTile(tile)->town == t;
02664         break;
02665 
02666       case MP_OBJECT:
02667         if (Town::GetNumItems() == 1) {
02668           /* No towns will be left, remove it! */
02669           try_clear = true;
02670         } else {
02671           Object *o = Object::GetByTile(tile);
02672           if (o->town == t) {
02673             if (o->type == OBJECT_STATUE) {
02674               /* Statue... always remove. */
02675               try_clear = true;
02676             } else {
02677               /* Tell to find a new town. */
02678               if (flags & DC_EXEC) o->town = NULL;
02679             }
02680           }
02681         }
02682         break;
02683 
02684       default:
02685         break;
02686     }
02687     if (try_clear) {
02688       CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02689       if (ret.Failed()) return ret;
02690     }
02691   }
02692 
02693   /* The town destructor will delete the other things related to the town. */
02694   if (flags & DC_EXEC) delete t;
02695 
02696   return CommandCost();
02697 }
02698 
02703 const byte _town_action_costs[TACT_COUNT] = {
02704   2, 4, 9, 35, 48, 53, 117, 175
02705 };
02706 
02707 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02708 {
02709   if (flags & DC_EXEC) {
02710     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02711   }
02712   return CommandCost();
02713 }
02714 
02715 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02716 {
02717   if (flags & DC_EXEC) {
02718     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02719   }
02720   return CommandCost();
02721 }
02722 
02723 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02724 {
02725   if (flags & DC_EXEC) {
02726     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02727   }
02728   return CommandCost();
02729 }
02730 
02731 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02732 {
02733   /* Check if the company is allowed to fund new roads. */
02734   if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02735 
02736   if (flags & DC_EXEC) {
02737     t->road_build_months = 6;
02738 
02739     char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02740     SetDParam(0, _current_company);
02741     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02742 
02743     char *cn = strdup(company_name);
02744     SetDParam(0, t->index);
02745     SetDParamStr(1, cn);
02746 
02747     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02748     AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02749     Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02750   }
02751   return CommandCost();
02752 }
02753 
02759 static bool TryClearTile(TileIndex tile)
02760 {
02761   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02762   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02763   cur_company.Restore();
02764   return r.Succeeded();
02765 }
02766 
02768 struct StatueBuildSearchData {
02769   TileIndex best_position; 
02770   int tile_count;          
02771 
02772   StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
02773 };
02774 
02781 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02782 {
02783   static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
02784 
02785   StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
02786   statue_data->tile_count++;
02787 
02788   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02789   if (IsSteepSlope(GetTileSlope(tile))) return false;
02790   /* Don't build statues under bridges. */
02791   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02792 
02793   /* A clear-able open space is always preferred. */
02794   if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
02795     statue_data->best_position = tile;
02796     return true;
02797   }
02798 
02799   bool house = IsTileType(tile, MP_HOUSE);
02800 
02801   /* Searching inside the inner circle. */
02802   if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
02803     /* Save first house in inner circle. */
02804     if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
02805       statue_data->best_position = tile;
02806     }
02807 
02808     /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
02809     return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
02810   }
02811 
02812   /* Searching outside the circle, just pick the first possible spot. */
02813   statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
02814   return house && TryClearTile(tile);
02815 }
02816 
02824 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02825 {
02826   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02827 
02828   TileIndex tile = t->xy;
02829   StatueBuildSearchData statue_data(INVALID_TILE, 0);
02830   if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02831 
02832   if (flags & DC_EXEC) {
02833     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02834     DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02835     cur_company.Restore();
02836     BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
02837     SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02838     MarkTileDirtyByTile(statue_data.best_position);
02839   }
02840   return CommandCost();
02841 }
02842 
02843 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02844 {
02845   /* Check if it's allowed to buy the rights */
02846   if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
02847 
02848   if (flags & DC_EXEC) {
02849     /* Build next tick */
02850     t->grow_counter = 1;
02851     /* And grow for 3 months */
02852     t->fund_buildings_months = 3;
02853 
02854     /* Enable growth (also checking GameScript's opinion) */
02855     UpdateTownGrowRate(t);
02856 
02857     SetWindowDirty(WC_TOWN_VIEW, t->index);
02858   }
02859   return CommandCost();
02860 }
02861 
02862 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02863 {
02864   /* Check if it's allowed to buy the rights */
02865   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02866 
02867   if (flags & DC_EXEC) {
02868     t->exclusive_counter = 12;
02869     t->exclusivity = _current_company;
02870 
02871     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02872 
02873     SetWindowClassesDirty(WC_STATION_VIEW);
02874 
02875     /* Spawn news message */
02876     CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
02877     cni->FillData(Company::Get(_current_company));
02878     SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
02879     SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
02880     SetDParam(2, t->index);
02881     SetDParamStr(3, cni->company_name);
02882     AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
02883     AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02884     Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02885   }
02886   return CommandCost();
02887 }
02888 
02889 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02890 {
02891   if (flags & DC_EXEC) {
02892     if (Chance16(1, 14)) {
02893       /* set as unwanted for 6 months */
02894       t->unwanted[_current_company] = 6;
02895 
02896       /* set all close by station ratings to 0 */
02897       Station *st;
02898       FOR_ALL_STATIONS(st) {
02899         if (st->town == t && st->owner == _current_company) {
02900           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02901         }
02902       }
02903 
02904       /* only show error message to the executing player. All errors are handled command.c
02905        * but this is special, because it can only 'fail' on a DC_EXEC */
02906       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
02907 
02908       /* decrease by a lot!
02909        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02910        * be independent of any cheat settings
02911        */
02912       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02913         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02914         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02915       }
02916     } else {
02917       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02918     }
02919   }
02920   return CommandCost();
02921 }
02922 
02923 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02924 static TownActionProc * const _town_action_proc[] = {
02925   TownActionAdvertiseSmall,
02926   TownActionAdvertiseMedium,
02927   TownActionAdvertiseLarge,
02928   TownActionRoadRebuild,
02929   TownActionBuildStatue,
02930   TownActionFundBuildings,
02931   TownActionBuyRights,
02932   TownActionBribe
02933 };
02934 
02942 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02943 {
02944   int num = 0;
02945   TownActions buttons = TACT_NONE;
02946 
02947   /* Spectators and unwanted have no options */
02948   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02949 
02950     /* Things worth more than this are not shown */
02951     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02952 
02953     /* Check the action bits for validity and
02954      * if they are valid add them */
02955     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02956       const TownActions cur = (TownActions)(1 << i);
02957 
02958       /* Is the company not able to bribe ? */
02959       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02960 
02961       /* Is the company not able to buy exclusive rights ? */
02962       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02963 
02964       /* Is the company not able to fund buildings ? */
02965       if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
02966 
02967       /* Is the company not able to fund local road reconstruction? */
02968       if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02969 
02970       /* Is the company not able to build a statue ? */
02971       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02972 
02973       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02974         buttons |= cur;
02975         num++;
02976       }
02977     }
02978   }
02979 
02980   if (nump != NULL) *nump = num;
02981   return buttons;
02982 }
02983 
02995 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02996 {
02997   Town *t = Town::GetIfValid(p1);
02998   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02999 
03000   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
03001 
03002   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
03003 
03004   CommandCost ret = _town_action_proc[p2](t, flags);
03005   if (ret.Failed()) return ret;
03006 
03007   if (flags & DC_EXEC) {
03008     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
03009   }
03010 
03011   return cost;
03012 }
03013 
03014 static void UpdateTownRating(Town *t)
03015 {
03016   /* Increase company ratings if they're low */
03017   const Company *c;
03018   FOR_ALL_COMPANIES(c) {
03019     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
03020       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
03021     }
03022   }
03023 
03024   const Station *st;
03025   FOR_ALL_STATIONS(st) {
03026     if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
03027       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
03028         if (Company::IsValidID(st->owner)) {
03029           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
03030           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
03031         }
03032       } else {
03033         if (Company::IsValidID(st->owner)) {
03034           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
03035           t->ratings[st->owner] = max(new_rating, INT16_MIN);
03036         }
03037       }
03038     }
03039   }
03040 
03041   /* clamp all ratings to valid values */
03042   for (uint i = 0; i < MAX_COMPANIES; i++) {
03043     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
03044   }
03045 
03046   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03047 }
03048 
03049 static void UpdateTownGrowRate(Town *t)
03050 {
03051   ClrBit(t->flags, TOWN_IS_GROWING);
03052   SetWindowDirty(WC_TOWN_VIEW, t->index);
03053 
03054   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
03055 
03056   if (t->fund_buildings_months == 0) {
03057     /* Check if all goals are reached for this town to grow (given we are not funding it) */
03058     for (int i = TE_BEGIN; i < TE_END; i++) {
03059       switch (t->goal[i]) {
03060         case TOWN_GROWTH_WINTER:
03061           if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
03062           break;
03063         case TOWN_GROWTH_DESERT:
03064           if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
03065           break;
03066         default:
03067           if (t->goal[i] > t->received[i].old_act) return;
03068           break;
03069       }
03070     }
03071   }
03072 
03073   if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
03074     if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
03075     SetWindowDirty(WC_TOWN_VIEW, t->index);
03076     return;
03077   }
03078 
03083   static const uint16 _grow_count_values[2][6] = {
03084     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
03085     { 320, 420, 300, 220, 160, 100 }  // Normal values
03086   };
03087 
03088   int n = 0;
03089 
03090   const Station *st;
03091   FOR_ALL_STATIONS(st) {
03092     if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
03093       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
03094         n++;
03095       }
03096     }
03097   }
03098 
03099   uint16 m;
03100 
03101   if (t->fund_buildings_months != 0) {
03102     m = _grow_count_values[0][min(n, 5)];
03103   } else {
03104     m = _grow_count_values[1][min(n, 5)];
03105     if (n == 0 && !Chance16(1, 12)) return;
03106   }
03107 
03108   /* Use the normal growth rate values if new buildings have been funded in
03109    * this town and the growth rate is set to none. */
03110   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
03111 
03112   m >>= growth_multiplier;
03113   if (t->larger_town) m /= 2;
03114 
03115   t->growth_rate = m / (t->cache.num_houses / 50 + 1);
03116   if (m <= t->grow_counter) {
03117     t->grow_counter = m;
03118   }
03119 
03120   SetBit(t->flags, TOWN_IS_GROWING);
03121   SetWindowDirty(WC_TOWN_VIEW, t->index);
03122 }
03123 
03124 static void UpdateTownAmounts(Town *t)
03125 {
03126   for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
03127   for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
03128   if (t->fund_buildings_months != 0) t->fund_buildings_months--;
03129 
03130   SetWindowDirty(WC_TOWN_VIEW, t->index);
03131 }
03132 
03133 static void UpdateTownUnwanted(Town *t)
03134 {
03135   const Company *c;
03136 
03137   FOR_ALL_COMPANIES(c) {
03138     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
03139   }
03140 }
03141 
03148 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
03149 {
03150   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
03151 
03152   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
03153   if (t == NULL) return CommandCost();
03154 
03155   if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
03156 
03157   SetDParam(0, t->index);
03158   return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03159 }
03160 
03169 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
03170 {
03171   Town *t;
03172   uint best = threshold;
03173   Town *best_town = NULL;
03174 
03175   FOR_ALL_TOWNS(t) {
03176     uint dist = DistanceManhattan(tile, t->xy);
03177     if (dist < best) {
03178       best = dist;
03179       best_town = t;
03180     }
03181   }
03182 
03183   return best_town;
03184 }
03185 
03194 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
03195 {
03196   switch (GetTileType(tile)) {
03197     case MP_ROAD:
03198       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
03199 
03200       if (!HasTownOwnedRoad(tile)) {
03201         TownID tid = GetTownIndex(tile);
03202 
03203         if (tid == (TownID)INVALID_TOWN) {
03204           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
03205           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03206           assert(Town::GetNumItems() == 0);
03207           return NULL;
03208         }
03209 
03210         assert(Town::IsValidID(tid));
03211         Town *town = Town::Get(tid);
03212 
03213         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03214 
03215         return town;
03216       }
03217       /* FALL THROUGH */
03218 
03219     case MP_HOUSE:
03220       return Town::GetByTile(tile);
03221 
03222     default:
03223       return CalcClosestTownFromTile(tile, threshold);
03224   }
03225 }
03226 
03227 static bool _town_rating_test = false; 
03228 static SmallMap<const Town *, int, 4> _town_test_ratings; 
03229 
03235 void SetTownRatingTestMode(bool mode)
03236 {
03237   static int ref_count = 0; // Number of times test-mode is switched on.
03238   if (mode) {
03239     if (ref_count == 0) {
03240       _town_test_ratings.Clear();
03241     }
03242     ref_count++;
03243   } else {
03244     assert(ref_count > 0);
03245     ref_count--;
03246   }
03247   _town_rating_test = !(ref_count == 0);
03248 }
03249 
03255 static int GetRating(const Town *t)
03256 {
03257   if (_town_rating_test) {
03258     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03259     if (it != _town_test_ratings.End()) {
03260       return it->second;
03261     }
03262   }
03263   return t->ratings[_current_company];
03264 }
03265 
03273 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03274 {
03275   /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
03276   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03277       !Company::IsValidID(_current_company) ||
03278       (_cheats.magic_bulldozer.value && add < 0)) {
03279     return;
03280   }
03281 
03282   int rating = GetRating(t);
03283   if (add < 0) {
03284     if (rating > max) {
03285       rating += add;
03286       if (rating < max) rating = max;
03287     }
03288   } else {
03289     if (rating < max) {
03290       rating += add;
03291       if (rating > max) rating = max;
03292     }
03293   }
03294   if (_town_rating_test) {
03295     _town_test_ratings[t] = rating;
03296   } else {
03297     SetBit(t->have_ratings, _current_company);
03298     t->ratings[_current_company] = rating;
03299     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03300   }
03301 }
03302 
03310 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03311 {
03312   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
03313   if (t == NULL || !Company::IsValidID(_current_company) ||
03314       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03315     return CommandCost();
03316   }
03317 
03318   /* minimum rating needed to be allowed to remove stuff */
03319   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03320     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
03321     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
03322     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
03323     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
03324   };
03325 
03326   /* check if you're allowed to remove the road/bridge/tunnel
03327    * owned by a town no removal if rating is lower than ... depends now on
03328    * difficulty setting. Minimum town rating selected by difficulty level
03329    */
03330   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03331 
03332   if (GetRating(t) < needed) {
03333     SetDParam(0, t->index);
03334     return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03335   }
03336 
03337   return CommandCost();
03338 }
03339 
03340 void TownsMonthlyLoop()
03341 {
03342   Town *t;
03343 
03344   FOR_ALL_TOWNS(t) {
03345     if (t->road_build_months != 0) t->road_build_months--;
03346 
03347     if (t->exclusive_counter != 0) {
03348       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03349     }
03350 
03351     UpdateTownAmounts(t);
03352     UpdateTownRating(t);
03353     UpdateTownGrowRate(t);
03354     UpdateTownUnwanted(t);
03355     UpdateTownCargoes(t);
03356   }
03357 
03358   UpdateTownCargoBitmap();
03359 }
03360 
03361 void TownsYearlyLoop()
03362 {
03363   /* Increment house ages */
03364   for (TileIndex t = 0; t < MapSize(); t++) {
03365     if (!IsTileType(t, MP_HOUSE)) continue;
03366     IncrementHouseAge(t);
03367   }
03368 }
03369 
03370 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03371 {
03372   if (AutoslopeEnabled()) {
03373     HouseID house = GetHouseType(tile);
03374     GetHouseNorthPart(house); // modifies house to the ID of the north tile
03375     const HouseSpec *hs = HouseSpec::Get(house);
03376 
03377     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
03378     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03379         (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03380       bool allow_terraform = true;
03381 
03382       /* Call the autosloping callback per tile, not for the whole building at once. */
03383       house = GetHouseType(tile);
03384       hs = HouseSpec::Get(house);
03385       if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03386         /* If the callback fails, allow autoslope. */
03387         uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03388         if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
03389       }
03390 
03391       if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03392     }
03393   }
03394 
03395   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03396 }
03397 
03399 extern const TileTypeProcs _tile_type_town_procs = {
03400   DrawTile_Town,           // draw_tile_proc
03401   GetSlopePixelZ_Town,     // get_slope_z_proc
03402   ClearTile_Town,          // clear_tile_proc
03403   AddAcceptedCargo_Town,   // add_accepted_cargo_proc
03404   GetTileDesc_Town,        // get_tile_desc_proc
03405   GetTileTrackStatus_Town, // get_tile_track_status_proc
03406   NULL,                    // click_tile_proc
03407   AnimateTile_Town,        // animate_tile_proc
03408   TileLoop_Town,           // tile_loop_proc
03409   ChangeTileOwner_Town,    // change_tile_owner_proc
03410   AddProducedCargo_Town,   // add_produced_cargo_proc
03411   NULL,                    // vehicle_enter_tile_proc
03412   GetFoundation_Town,      // get_foundation_proc
03413   TerraformTile_Town,      // terraform_tile_proc
03414 };
03415 
03416 
03417 HouseSpec _house_specs[NUM_HOUSES];
03418 
03419 void ResetHouses()
03420 {
03421   memset(&_house_specs, 0, sizeof(_house_specs));
03422   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03423 
03424   /* Reset any overrides that have been set. */
03425   _house_mngr.ResetOverride();
03426 }