town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "gui.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 "newgrf_config.h"
00030 #include "autoslope.h"
00031 #include "tunnelbridge_map.h"
00032 #include "strings_func.h"
00033 #include "window_func.h"
00034 #include "string_func.h"
00035 #include "newgrf_cargo.h"
00036 #include "cheat_type.h"
00037 #include "animated_tile_func.h"
00038 #include "date_func.h"
00039 #include "subsidy_func.h"
00040 #include "core/pool_func.hpp"
00041 #include "town.h"
00042 #include "townname_func.h"
00043 #include "townname_type.h"
00044 #include "core/random_func.hpp"
00045 #include "core/backup_type.hpp"
00046 #include "depot_base.h"
00047 #include "object_map.h"
00048 #include "object_base.h"
00049 #include "ai/ai.hpp"
00050 
00051 #include "table/strings.h"
00052 #include "table/town_land.h"
00053 
00054 TownID _new_town_id;
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 
00064   if (CleaningPool()) return;
00065 
00066   /* Delete town authority window
00067    * and remove from list of sorted towns */
00068   DeleteWindowById(WC_TOWN_VIEW, this->index);
00069 
00070   /* Check no industry is related to us. */
00071   const Industry *i;
00072   FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00073 
00074   /* ... and no object is related to us. */
00075   const Object *o;
00076   FOR_ALL_OBJECTS(o) assert(o->town != this);
00077 
00078   /* Check no tile is related to us. */
00079   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00080     switch (GetTileType(tile)) {
00081       case MP_HOUSE:
00082         assert(GetTownIndex(tile) != this->index);
00083         break;
00084 
00085       case MP_ROAD:
00086         assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00087         break;
00088 
00089       case MP_TUNNELBRIDGE:
00090         assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00091         break;
00092 
00093       default:
00094         break;
00095     }
00096   }
00097 
00098   DeleteSubsidyWith(ST_TOWN, this->index);
00099   DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
00100   CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00101   MarkWholeScreenDirty();
00102 }
00103 
00104 
00110 void Town::PostDestructor(size_t index)
00111 {
00112   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00113   UpdateNearestTownForRoadTiles(false);
00114 
00115   /* Give objects a new home! */
00116   Object *o;
00117   FOR_ALL_OBJECTS(o) {
00118     if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00119   }
00120 }
00121 
00125 void Town::InitializeLayout(TownLayout layout)
00126 {
00127   if (layout != TL_RANDOM) {
00128     this->layout = layout;
00129     return;
00130   }
00131 
00132   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00133 }
00134 
00139 /* static */ Town *Town::GetRandom()
00140 {
00141   if (Town::GetNumItems() == 0) return NULL;
00142   int num = RandomRange((uint16)Town::GetNumItems());
00143   size_t index = MAX_UVALUE(size_t);
00144 
00145   while (num >= 0) {
00146     num--;
00147     index++;
00148 
00149     /* Make sure we have a valid town */
00150     while (!Town::IsValidID(index)) {
00151       index++;
00152       assert(index < Town::GetPoolSize());
00153     }
00154   }
00155 
00156   return Town::Get(index);
00157 }
00158 
00167 void Town::UpdateLabel()
00168 {
00169   if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
00170     int r = this->ratings[_local_company];
00171     (this->town_label = 0, r <= RATING_VERYPOOR)  || // Appalling and Very Poor
00172     (this->town_label++,   r <= RATING_MEDIOCRE)  || // Poor and Mediocre
00173     (this->town_label++,   r <= RATING_GOOD)      || // Good
00174     (this->town_label++,   r <= RATING_VERYGOOD)  || // Very Good
00175     (this->town_label++,   true);                    // Excellent and Outstanding
00176   }
00177 }
00178 
00183 Money HouseSpec::GetRemovalCost() const
00184 {
00185   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00186 }
00187 
00188 // Local
00189 static int _grow_town_result;
00190 
00191 /* Describe the possible states */
00192 enum TownGrowthResult {
00193   GROWTH_SUCCEED         = -1,
00194   GROWTH_SEARCH_STOPPED  =  0
00195 //  GROWTH_SEARCH_RUNNING >=  1
00196 };
00197 
00198 static bool BuildTownHouse(Town *t, TileIndex tile);
00199 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00200 
00201 static void TownDrawHouseLift(const TileInfo *ti)
00202 {
00203   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00204 }
00205 
00206 typedef void TownDrawTileProc(const TileInfo *ti);
00207 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00208   TownDrawHouseLift
00209 };
00210 
00216 static inline DiagDirection RandomDiagDir()
00217 {
00218   return (DiagDirection)(3 & Random());
00219 }
00220 
00226 static void DrawTile_Town(TileInfo *ti)
00227 {
00228   HouseID house_id = GetHouseType(ti->tile);
00229 
00230   if (house_id >= NEW_HOUSE_OFFSET) {
00231     /* Houses don't necessarily need new graphics. If they don't have a
00232      * spritegroup associated with them, then the sprite for the substitute
00233      * house id is drawn instead. */
00234     if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00235       DrawNewHouseTile(ti, house_id);
00236       return;
00237     } else {
00238       house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00239     }
00240   }
00241 
00242   /* Retrieve pointer to the draw town tile struct */
00243   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00244 
00245   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00246 
00247   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00248 
00249   /* If houses are invisible, do not draw the upper part */
00250   if (IsInvisibilitySet(TO_HOUSES)) return;
00251 
00252   /* Add a house on top of the ground? */
00253   SpriteID image = dcts->building.sprite;
00254   if (image != 0) {
00255     AddSortableSpriteToDraw(image, dcts->building.pal,
00256       ti->x + dcts->subtile_x,
00257       ti->y + dcts->subtile_y,
00258       dcts->width,
00259       dcts->height,
00260       dcts->dz,
00261       ti->z,
00262       IsTransparencySet(TO_HOUSES)
00263     );
00264 
00265     if (IsTransparencySet(TO_HOUSES)) return;
00266   }
00267 
00268   {
00269     int proc = dcts->draw_proc - 1;
00270 
00271     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00272   }
00273 }
00274 
00275 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00276 {
00277   return GetTileMaxZ(tile);
00278 }
00279 
00281 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00282 {
00283   HouseID hid = GetHouseType(tile);
00284 
00285   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00286    * account for this, as other structures should
00287    * draw the wall of the foundation in this case.
00288    */
00289   if (hid >= NEW_HOUSE_OFFSET) {
00290     const HouseSpec *hs = HouseSpec::Get(hid);
00291     if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00292       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00293       if (callback_res == 0) return FOUNDATION_NONE;
00294     }
00295   }
00296   return FlatteningFoundation(tileh);
00297 }
00298 
00305 static void AnimateTile_Town(TileIndex tile)
00306 {
00307   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00308     AnimateNewHouseTile(tile);
00309     return;
00310   }
00311 
00312   if (_tick_counter & 3) return;
00313 
00314   /* If the house is not one with a lift anymore, then stop this animating.
00315    * Not exactly sure when this happens, but probably when a house changes.
00316    * Before this was just a return...so it'd leak animated tiles..
00317    * That bug seems to have been here since day 1?? */
00318   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00319     DeleteAnimatedTile(tile);
00320     return;
00321   }
00322 
00323   if (!LiftHasDestination(tile)) {
00324     uint i;
00325 
00326     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00327      * This is due to the fact that the first floor is, in the graphics,
00328      *  the height of 2 'normal' floors.
00329      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00330     do {
00331       i = RandomRange(7);
00332     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00333 
00334     SetLiftDestination(tile, i);
00335   }
00336 
00337   int pos = GetLiftPosition(tile);
00338   int dest = GetLiftDestination(tile) * 6;
00339   pos += (pos < dest) ? 1 : -1;
00340   SetLiftPosition(tile, pos);
00341 
00342   if (pos == dest) {
00343     HaltLift(tile);
00344     DeleteAnimatedTile(tile);
00345   }
00346 
00347   MarkTileDirtyByTile(tile);
00348 }
00349 
00356 static bool IsCloseToTown(TileIndex tile, uint dist)
00357 {
00358   const Town *t;
00359 
00360   FOR_ALL_TOWNS(t) {
00361     if (DistanceManhattan(tile, t->xy) < dist) return true;
00362   }
00363   return false;
00364 }
00365 
00370 void Town::UpdateVirtCoord()
00371 {
00372   this->UpdateLabel();
00373   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00374   SetDParam(0, this->index);
00375   SetDParam(1, this->population);
00376   this->sign.UpdatePosition(pt.x, pt.y - 24, this->Label());
00377 
00378   SetWindowDirty(WC_TOWN_VIEW, this->index);
00379 }
00380 
00382 void UpdateAllTownVirtCoords()
00383 {
00384   Town *t;
00385 
00386   FOR_ALL_TOWNS(t) {
00387     t->UpdateVirtCoord();
00388   }
00389 }
00390 
00396 static void ChangePopulation(Town *t, int mod)
00397 {
00398   t->population += mod;
00399   InvalidateWindowData(WC_TOWN_VIEW, t->index);
00400   t->UpdateVirtCoord();
00401 
00402   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00403 }
00404 
00410 uint32 GetWorldPopulation()
00411 {
00412   uint32 pop = 0;
00413   const Town *t;
00414 
00415   FOR_ALL_TOWNS(t) pop += t->population;
00416   return pop;
00417 }
00418 
00423 static void MakeSingleHouseBigger(TileIndex tile)
00424 {
00425   assert(IsTileType(tile, MP_HOUSE));
00426 
00427   /* progress in construction stages */
00428   IncHouseConstructionTick(tile);
00429   if (GetHouseConstructionTick(tile) != 0) return;
00430 
00431   AnimateNewHouseConstruction(tile);
00432 
00433   if (IsHouseCompleted(tile)) {
00434     /* Now that construction is complete, we can add the population of the
00435      * building to the town. */
00436     ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00437     ResetHouseAge(tile);
00438   }
00439   MarkTileDirtyByTile(tile);
00440 }
00441 
00446 static void MakeTownHouseBigger(TileIndex tile)
00447 {
00448   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00449   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00450   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00451   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00452   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00453 }
00454 
00465 static void TownGenerateCargo (Town *t, CargoID ct, uint amount, StationFinder &stations)
00466 {
00467   /* custom cargo generation factor */
00468   int cf = _settings_game.economy.town_cargo_factor;
00469 
00470   /* when the economy flunctuates, everyone wants to stay at home */
00471   if (EconomyIsInRecession())
00472     amount = (amount + 1) >> 1; 
00473   
00474   /* apply custom factor? */
00475   if (cf < 0) {
00476     /* approx (amount / 2^cf)
00477      * adjust with a constant offset of {(2 ^ cf) - 1} (i.e. add cf * 1-bits) before dividing to ensure that it doesn't become zero
00478      * this skews the curve a little so that isn't entirely exponential, but will still decrease */
00479     amount = (amount + ((1 << -cf) - 1)) >> -cf;
00480   } else if (cf > 0) {
00481     /* approx (amount * 2^cf) */
00482     /* XXX: overflow? */
00483     amount = amount << cf;
00484   }
00485 
00486   /* with the adjustments above, this should never happen */
00487   assert(amount > 0);
00488   
00489   /* send cargo to station */
00490   uint moved = MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
00491   
00492   /* calculate for town stats */
00493   const CargoSpec *cs = CargoSpec::Get(ct);
00494   switch (cs->town_effect) {
00495     case TE_PASSENGERS:
00496       t->new_gen_max_pass += amount;
00497       t->new_gen_act_pass += moved;
00498       break;
00499 
00500     case TE_MAIL:
00501       t->new_gen_max_mail += amount;
00502       t->new_gen_act_mail += moved;
00503       break;
00504 
00505     default:
00506       break;
00507   }
00508 }
00509 
00516 static void TileLoop_Town(TileIndex tile)
00517 {
00518   HouseID house_id = GetHouseType(tile);
00519 
00520   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00521    * doesn't exist any more, so don't continue here. */
00522   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00523 
00524   if (!IsHouseCompleted(tile)) {
00525     /* Construction is not completed. See if we can go further in construction*/
00526     MakeTownHouseBigger(tile);
00527     return;
00528   }
00529 
00530   const HouseSpec *hs = HouseSpec::Get(house_id);
00531 
00532   /* If the lift has a destination, it is already an animated tile. */
00533   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00534       house_id < NEW_HOUSE_OFFSET &&
00535       !LiftHasDestination(tile) &&
00536       Chance16(1, 2)) {
00537     AddAnimatedTile(tile);
00538   }
00539 
00540   Town *t = Town::GetByTile(tile);
00541   uint32 r = Random();
00542 
00543   StationFinder stations(TileArea(tile, 1, 1));
00544 
00545   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00546     for (uint i = 0; i < 256; i++) {
00547       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00548 
00549       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00550 
00551       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00552       if (cargo == CT_INVALID) continue;
00553 
00554       uint amt = GB(callback, 0, 8);
00555       if (amt == 0) continue;
00556 
00557       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00558 
00559       const CargoSpec *cs = CargoSpec::Get(cargo);
00560       switch (cs->town_effect) {
00561         case TE_PASSENGERS:
00562           TownGenerateCargo(t, cargo, amt, stations); // XXX: no economy flunctuation for GRF cargos?
00563           t->new_max_pass += amt;
00564           t->new_act_pass += moved;
00565           break;
00566 
00567         case TE_MAIL:
00568           TownGenerateCargo(t, cargo, amt, stations); // XXX: no economy flunctuation for GRF cargos?
00569           t->new_max_mail += amt;
00570           t->new_act_mail += moved;
00571           break;
00572 
00573         case TE_FOOD:
00574           t->new_max_food += amt;
00575           t->new_act_food += moved;
00576           break;
00577 
00578         case TE_WATER:
00579           t->new_max_water += amt;
00580           t->new_act_water += moved;
00581           break;
00582 
00583         case TE_GOODS:
00584           t->new_max_goods += amt;
00585           t->new_act_goods += moved;
00586           break;
00587 
00588         default:
00589           break;
00590       }
00591     }
00592   } else {
00593     if (GB(r, 0, 8) < hs->population) {
00594       uint amt = GB(r, 0, 8) / 8 + 1;
00595       
00596       TownGenerateCargo(t, CT_PASSENGERS, amt, stations);
00597     }
00598 
00599     if (GB(r, 8, 8) < hs->mail_generation) {
00600       uint amt = GB(r, 8, 8) / 8 + 1;
00601 
00602       TownGenerateCargo(t, CT_MAIL, amt, stations);
00603     }
00604 
00605     UpdateTownDemands(t);
00606   }
00607 
00608   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00609 
00610   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00611       HasBit(t->flags, TOWN_IS_FUNDED) &&
00612       CanDeleteHouse(tile) &&
00613       GetHouseAge(tile) >= (hs->minimum_life  * _date_daylength_factor) &&
00614       --t->time_until_rebuild == 0) {
00615     t->time_until_rebuild = GB(r, 16, 8) + 192;
00616 
00617     ClearTownHouse(t, tile);
00618 
00619     /* Rebuild with another house? */
00620     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00621   }
00622 
00623   cur_company.Restore();
00624 }
00625 
00626 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00627 {
00628   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00629   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00630 
00631   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00632 
00633   CommandCost cost(EXPENSES_CONSTRUCTION);
00634   cost.AddCost(hs->GetRemovalCost());
00635 
00636   int rating = hs->remove_rating_decrease;
00637   Town *t = Town::GetByTile(tile);
00638 
00639   if (Company::IsValidID(_current_company)) {
00640     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00641       SetDParam(0, t->index);
00642       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00643     }
00644   }
00645 
00646   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00647   if (flags & DC_EXEC) {
00648     ClearTownHouse(t, tile);
00649   }
00650 
00651   return cost;
00652 }
00653 
00654 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00655 {
00656   HouseID house_id = GetHouseType(tile);
00657   const HouseSpec *hs = HouseSpec::Get(house_id);
00658   Town *t = Town::GetByTile(tile);
00659 
00660   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00661     for (uint i = 0; i < 256; i++) {
00662       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00663 
00664       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00665 
00666       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00667 
00668       if (cargo == CT_INVALID) continue;
00669       produced[cargo]++;
00670     }
00671   } else {
00672     if (hs->population > 0) {
00673       produced[CT_PASSENGERS]++;
00674     }
00675     if (hs->mail_generation > 0) {
00676       produced[CT_MAIL]++;
00677     }
00678   }
00679 }
00680 
00681 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00682 {
00683   if (cargo == CT_INVALID || amount == 0) return;
00684   acceptance[cargo] += amount;
00685   SetBit(*always_accepted, cargo);
00686 }
00687 
00688 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00689 {
00690   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00691   CargoID accepts[3];
00692 
00693   /* Set the initial accepted cargo types */
00694   for (uint8 i = 0; i < lengthof(accepts); i++) {
00695     accepts[i] = hs->accepts_cargo[i];
00696   }
00697 
00698   /* Check for custom accepted cargo types */
00699   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00700     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00701     if (callback != CALLBACK_FAILED) {
00702       /* Replace accepted cargo types with translated values from callback */
00703       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grf_prop.grffile);
00704       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grf_prop.grffile);
00705       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00706     }
00707   }
00708 
00709   /* Check for custom cargo acceptance */
00710   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00711     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00712     if (callback != CALLBACK_FAILED) {
00713       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00714       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00715       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00716         /* The 'S' bit indicates food instead of goods */
00717         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00718       } else {
00719         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00720       }
00721       return;
00722     }
00723   }
00724 
00725   /* No custom acceptance, so fill in with the default values */
00726   for (uint8 i = 0; i < lengthof(accepts); i++) {
00727     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00728   }
00729 }
00730 
00731 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00732 {
00733   const HouseID house = GetHouseType(tile);
00734   const HouseSpec *hs = HouseSpec::Get(house);
00735   bool house_completed = IsHouseCompleted(tile);
00736 
00737   td->str = hs->building_name;
00738 
00739   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00740   if (callback_res != CALLBACK_FAILED) {
00741     StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00742     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00743       td->str = new_name;
00744     }
00745   }
00746 
00747   if (!house_completed) {
00748     SetDParamX(td->dparam, 0, td->str);
00749     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00750   }
00751 
00752   if (hs->grf_prop.grffile != NULL) {
00753     const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00754     td->grf = gc->GetName();
00755   }
00756 
00757   td->owner[0] = OWNER_TOWN;
00758 }
00759 
00760 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00761 {
00762   /* not used */
00763   return 0;
00764 }
00765 
00766 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00767 {
00768   /* not used */
00769 }
00770 
00771 static bool GrowTown(Town *t);
00772 
00773 static void TownTickHandler(Town *t)
00774 {
00775   if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00776     int i = t->grow_counter - 1;
00777     if (i < 0) {
00778       if (GrowTown(t)) {
00779         i = t->growth_rate;
00780       } else {
00781         i = 0;
00782       }
00783     }
00784     t->grow_counter = i;
00785   }
00786 
00787   UpdateTownRadius(t);
00788 }
00789 
00790 void OnTick_Town()
00791 {
00792   if (_game_mode == GM_EDITOR) return;
00793 
00794   Town *t;
00795   FOR_ALL_TOWNS(t) {
00796     /* Run town tick at regular intervals, but not all at once. */
00797     if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00798       TownTickHandler(t);
00799     }
00800   }
00801 }
00802 
00811 static RoadBits GetTownRoadBits(TileIndex tile)
00812 {
00813   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00814 
00815   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00816 }
00817 
00828 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00829 {
00830   if (!IsValidTile(tile)) return false;
00831 
00832   /* Lookup table for the used diff values */
00833   const TileIndexDiff tid_lt[3] = {
00834     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00835     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00836     TileOffsByDiagDir(ReverseDiagDir(dir)),
00837   };
00838 
00839   dist_multi = (dist_multi + 1) * 4;
00840   for (uint pos = 4; pos < dist_multi; pos++) {
00841     /* Go (pos / 4) tiles to the left or the right */
00842     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00843 
00844     /* Use the current tile as origin, or go one tile backwards */
00845     if (pos & 2) cur += tid_lt[2];
00846 
00847     /* Test for roadbit parallel to dir and facing towards the middle axis */
00848     if (IsValidTile(tile + cur) &&
00849         GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00850   }
00851   return false;
00852 }
00853 
00862 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00863 {
00864   if (DistanceFromEdge(tile) == 0) return false;
00865 
00866   Slope cur_slope, desired_slope;
00867 
00868   for (;;) {
00869     /* Check if there already is a road at this point? */
00870     if (GetTownRoadBits(tile) == ROAD_NONE) {
00871       /* No, try if we are able to build a road piece there.
00872        * If that fails clear the land, and if that fails exit.
00873        * This is to make sure that we can build a road here later. */
00874       if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00875           DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00876         return false;
00877     }
00878 
00879     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00880     bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00881     if (cur_slope == SLOPE_FLAT) return ret;
00882 
00883     /* If the tile is not a slope in the right direction, then
00884      * maybe terraform some. */
00885     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00886     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00887       if (Chance16(1, 8)) {
00888         CommandCost res = CMD_ERROR;
00889         if (!_generating_world && Chance16(1, 10)) {
00890           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00891           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00892               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00893         }
00894         if (res.Failed() && Chance16(1, 3)) {
00895           /* We can consider building on the slope, though. */
00896           return ret;
00897         }
00898       }
00899       return false;
00900     }
00901     return ret;
00902   }
00903 }
00904 
00905 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00906 {
00907   assert(tile < MapSize());
00908 
00909   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00910   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00911   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00912   return true;
00913 }
00914 
00915 static void LevelTownLand(TileIndex tile)
00916 {
00917   assert(tile < MapSize());
00918 
00919   /* Don't terraform if land is plain or if there's a house there. */
00920   if (IsTileType(tile, MP_HOUSE)) return;
00921   Slope tileh = GetTileSlope(tile, NULL);
00922   if (tileh == SLOPE_FLAT) return;
00923 
00924   /* First try up, then down */
00925   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00926     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00927   }
00928 }
00929 
00939 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00940 {
00941   /* align the grid to the downtown */
00942   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00943   RoadBits rcmd = ROAD_NONE;
00944 
00945   switch (t->layout) {
00946     default: NOT_REACHED();
00947 
00948     case TL_2X2_GRID:
00949       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00950       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00951       break;
00952 
00953     case TL_3X3_GRID:
00954       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00955       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00956       break;
00957   }
00958 
00959   /* Optimise only X-junctions */
00960   if (rcmd != ROAD_ALL) return rcmd;
00961 
00962   RoadBits rb_template;
00963 
00964   switch (GetTileSlope(tile, NULL)) {
00965     default:       rb_template = ROAD_ALL; break;
00966     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00967     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00968     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00969     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00970     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00971     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00972     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00973     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00974     case SLOPE_STEEP_W:
00975     case SLOPE_STEEP_S:
00976     case SLOPE_STEEP_E:
00977     case SLOPE_STEEP_N:
00978       rb_template = ROAD_NONE;
00979       break;
00980   }
00981 
00982   /* Stop if the template is compatible to the growth dir */
00983   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00984   /* If not generate a straight road in the direction of the growth */
00985   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00986 }
00987 
00998 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00999 {
01000   /* We can't look further than that. */
01001   if (DistanceFromEdge(tile) == 0) return false;
01002 
01003   uint counter = 0; // counts the house neighbor tiles
01004 
01005   /* Check the tiles E,N,W and S of the current tile for houses */
01006   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
01007     /* Count both void and house tiles for checking whether there
01008      * are enough houses in the area. This to make it likely that
01009      * houses get build up to the edge of the map. */
01010     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
01011       case MP_HOUSE:
01012       case MP_VOID:
01013         counter++;
01014         break;
01015 
01016       default:
01017         break;
01018     }
01019 
01020     /* If there are enough neighbors stop here */
01021     if (counter >= 3) {
01022       if (BuildTownHouse(t, tile)) {
01023         _grow_town_result = GROWTH_SUCCEED;
01024         return true;
01025       }
01026       return false;
01027     }
01028   }
01029   return false;
01030 }
01031 
01040 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01041 {
01042   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01043     _grow_town_result = GROWTH_SUCCEED;
01044     return true;
01045   }
01046   return false;
01047 }
01048 
01059 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01060 {
01061   assert(bridge_dir < DIAGDIR_END);
01062 
01063   const Slope slope = GetTileSlope(tile, NULL);
01064   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
01065 
01066   /* Make sure the direction is compatible with the slope.
01067    * Well we check if the slope has an up bit set in the
01068    * reverse direction. */
01069   if (slope & InclinedSlope(bridge_dir)) return false;
01070 
01071   /* Assure that the bridge is connectable to the start side */
01072   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01073 
01074   /* We are in the right direction */
01075   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
01076   TileIndex bridge_tile = tile; // Used to store the other waterside
01077 
01078   const int delta = TileOffsByDiagDir(bridge_dir);
01079   do {
01080     if (bridge_length++ >= 11) {
01081       /* Max 11 tile long bridges */
01082       return false;
01083     }
01084     bridge_tile += delta;
01085   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
01086 
01087   /* no water tiles in between? */
01088   if (bridge_length == 1) return false;
01089 
01090   for (uint8 times = 0; times <= 22; times++) {
01091     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01092 
01093     /* Can we actually build the bridge? */
01094     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01095       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01096       _grow_town_result = GROWTH_SUCCEED;
01097       return true;
01098     }
01099   }
01100   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01101   return false;
01102 }
01103 
01121 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01122 {
01123   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01124   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01125 
01126   assert(tile < MapSize());
01127 
01128   if (cur_rb == ROAD_NONE) {
01129     /* Tile has no road. First reset the status counter
01130      * to say that this is the last iteration. */
01131     _grow_town_result = GROWTH_SEARCH_STOPPED;
01132 
01133     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01134     if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01135 
01136     /* Remove hills etc */
01137     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01138 
01139     /* Is a road allowed here? */
01140     switch (t1->layout) {
01141       default: NOT_REACHED();
01142 
01143       case TL_3X3_GRID:
01144       case TL_2X2_GRID:
01145         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01146         if (rcmd == ROAD_NONE) return;
01147         break;
01148 
01149       case TL_BETTER_ROADS:
01150       case TL_ORIGINAL:
01151         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01152 
01153         DiagDirection source_dir = ReverseDiagDir(target_dir);
01154 
01155         if (Chance16(1, 4)) {
01156           /* Randomize a new target dir */
01157           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01158         }
01159 
01160         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01161           /* A road is not allowed to continue the randomized road,
01162            *  return if the road we're trying to build is curved. */
01163           if (target_dir != ReverseDiagDir(source_dir)) return;
01164 
01165           /* Return if neither side of the new road is a house */
01166           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01167               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01168             return;
01169           }
01170 
01171           /* That means that the road is only allowed if there is a house
01172            *  at any side of the new road. */
01173         }
01174 
01175         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01176         break;
01177     }
01178 
01179   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01180     /* Continue building on a partial road.
01181      * Should be allways OK, so we only generate
01182      * the fitting RoadBits */
01183     _grow_town_result = GROWTH_SEARCH_STOPPED;
01184 
01185     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01186 
01187     switch (t1->layout) {
01188       default: NOT_REACHED();
01189 
01190       case TL_3X3_GRID:
01191       case TL_2X2_GRID:
01192         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01193         break;
01194 
01195       case TL_BETTER_ROADS:
01196       case TL_ORIGINAL:
01197         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01198         break;
01199     }
01200   } else {
01201     bool allow_house = true; // Value which decides if we want to construct a house
01202 
01203     /* Reached a tunnel/bridge? Then continue at the other side of it. */
01204     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01205       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01206         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01207       }
01208       return;
01209     }
01210 
01211     /* Possibly extend the road in a direction.
01212      * Randomize a direction and if it has a road, bail out. */
01213     target_dir = RandomDiagDir();
01214     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01215 
01216     /* This is the tile we will reach if we extend to this direction. */
01217     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01218 
01219     /* Don't walk into water. */
01220     if (HasTileWaterGround(house_tile)) return;
01221 
01222     if (!IsValidTile(house_tile)) return;
01223 
01224     if (_settings_game.economy.allow_town_roads || _generating_world) {
01225       switch (t1->layout) {
01226         default: NOT_REACHED();
01227 
01228         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01229           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01230           /* FALL THROUGH */
01231 
01232         case TL_2X2_GRID:
01233           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01234           allow_house = (rcmd == ROAD_NONE);
01235           break;
01236 
01237         case TL_BETTER_ROADS: // Use original afterwards!
01238           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01239           /* FALL THROUGH */
01240 
01241         case TL_ORIGINAL:
01242           /* Allow a house at the edge. 60% chance or
01243            * always ok if no road allowed. */
01244           rcmd = DiagDirToRoadBits(target_dir);
01245           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01246           break;
01247       }
01248     }
01249 
01250     if (allow_house) {
01251       /* Build a house, but not if there already is a house there. */
01252       if (!IsTileType(house_tile, MP_HOUSE)) {
01253         /* Level the land if possible */
01254         if (Chance16(1, 6)) LevelTownLand(house_tile);
01255 
01256         /* And build a house.
01257          * Set result to -1 if we managed to build it. */
01258         if (BuildTownHouse(t1, house_tile)) {
01259           _grow_town_result = GROWTH_SUCCEED;
01260         }
01261       }
01262       return;
01263     }
01264 
01265     _grow_town_result = GROWTH_SEARCH_STOPPED;
01266   }
01267 
01268   /* Return if a water tile */
01269   if (HasTileWaterGround(tile)) return;
01270 
01271   /* Make the roads look nicer */
01272   rcmd = CleanUpRoadBits(tile, rcmd);
01273   if (rcmd == ROAD_NONE) return;
01274 
01275   /* Only use the target direction for bridges to ensure they're connected.
01276    * The target_dir is as computed previously according to town layout, so
01277    * it will match it perfectly. */
01278   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01279 
01280   GrowTownWithRoad(t1, tile, rcmd);
01281 }
01282 
01289 static int GrowTownAtRoad(Town *t, TileIndex tile)
01290 {
01291   /* Special case.
01292    * @see GrowTownInTile Check the else if
01293    */
01294   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01295 
01296   assert(tile < MapSize());
01297 
01298   /* Number of times to search.
01299    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01300    * them a little handicap. */
01301   switch (t->layout) {
01302     case TL_BETTER_ROADS:
01303       _grow_town_result = 10 + t->num_houses * 2 / 9;
01304       break;
01305 
01306     case TL_3X3_GRID:
01307     case TL_2X2_GRID:
01308       _grow_town_result = 10 + t->num_houses * 1 / 9;
01309       break;
01310 
01311     default:
01312       _grow_town_result = 10 + t->num_houses * 4 / 9;
01313       break;
01314   }
01315 
01316   do {
01317     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01318 
01319     /* Try to grow the town from this point */
01320     GrowTownInTile(&tile, cur_rb, target_dir, t);
01321 
01322     /* Exclude the source position from the bitmask
01323      * and return if no more road blocks available */
01324     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01325     if (cur_rb == ROAD_NONE) {
01326       return _grow_town_result;
01327     }
01328 
01329     /* Select a random bit from the blockmask, walk a step
01330      * and continue the search from there. */
01331     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01332     tile = TileAddByDiagDir(tile, target_dir);
01333 
01334     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01335       /* Don't allow building over roads of other cities */
01336       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01337         _grow_town_result = GROWTH_SUCCEED;
01338       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01339         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01340          * owner :) (happy happy happy road now) */
01341         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01342         SetTownIndex(tile, t->index);
01343       }
01344     }
01345 
01346     /* Max number of times is checked. */
01347   } while (--_grow_town_result >= 0);
01348 
01349   return (_grow_town_result == -2);
01350 }
01351 
01359 static RoadBits GenRandomRoadBits()
01360 {
01361   uint32 r = Random();
01362   uint a = GB(r, 0, 2);
01363   uint b = GB(r, 8, 2);
01364   if (a == b) b ^= 2;
01365   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01366 }
01367 
01373 static bool GrowTown(Town *t)
01374 {
01375   static const TileIndexDiffC _town_coord_mod[] = {
01376     {-1,  0},
01377     { 1,  1},
01378     { 1, -1},
01379     {-1, -1},
01380     {-1,  0},
01381     { 0,  2},
01382     { 2,  0},
01383     { 0, -2},
01384     {-1, -1},
01385     {-2,  2},
01386     { 2,  2},
01387     { 2, -2},
01388     { 0,  0}
01389   };
01390 
01391   /* Current "company" is a town */
01392   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01393 
01394   TileIndex tile = t->xy; // The tile we are working with ATM
01395 
01396   /* Find a road that we can base the construction on. */
01397   const TileIndexDiffC *ptr;
01398   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01399     if (GetTownRoadBits(tile) != ROAD_NONE) {
01400       int r = GrowTownAtRoad(t, tile);
01401       cur_company.Restore();
01402       return r != 0;
01403     }
01404     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01405   }
01406 
01407   /* No road available, try to build a random road block by
01408    * clearing some land and then building a road there. */
01409   if (_settings_game.economy.allow_town_roads || _generating_world) {
01410     tile = t->xy;
01411     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01412       /* Only work with plain land that not already has a house */
01413       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01414         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01415           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01416           cur_company.Restore();
01417           return true;
01418         }
01419       }
01420       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01421     }
01422   }
01423 
01424   cur_company.Restore();
01425   return false;
01426 }
01427 
01428 void UpdateTownRadius(Town *t)
01429 {
01430   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01431     {  4,  0,  0,  0,  0}, // 0
01432     { 16,  0,  0,  0,  0},
01433     { 25,  0,  0,  0,  0},
01434     { 36,  0,  0,  0,  0},
01435     { 49,  0,  4,  0,  0},
01436     { 64,  0,  4,  0,  0}, // 20
01437     { 64,  0,  9,  0,  1},
01438     { 64,  0,  9,  0,  4},
01439     { 64,  0, 16,  0,  4},
01440     { 81,  0, 16,  0,  4},
01441     { 81,  0, 16,  0,  4}, // 40
01442     { 81,  0, 25,  0,  9},
01443     { 81, 36, 25,  0,  9},
01444     { 81, 36, 25, 16,  9},
01445     { 81, 49,  0, 25,  9},
01446     { 81, 64,  0, 25,  9}, // 60
01447     { 81, 64,  0, 36,  9},
01448     { 81, 64,  0, 36, 16},
01449     {100, 81,  0, 49, 16},
01450     {100, 81,  0, 49, 25},
01451     {121, 81,  0, 49, 25}, // 80
01452     {121, 81,  0, 49, 25},
01453     {121, 81,  0, 49, 36}, // 88
01454   };
01455 
01456   if (t->num_houses < 92) {
01457     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01458   } else {
01459     int mass = t->num_houses / 8;
01460     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01461      * The offsets are to make sure the radii do not decrease in size when going from the table
01462      * to the calculated value.*/
01463     t->squared_town_zone_radius[0] = mass * 15 - 40;
01464     t->squared_town_zone_radius[1] = mass * 9 - 15;
01465     t->squared_town_zone_radius[2] = 0;
01466     t->squared_town_zone_radius[3] = mass * 5 - 5;
01467     t->squared_town_zone_radius[4] = mass * 3 + 5;
01468   }
01469 }
01470 
01475 void UpdateTownGenCargo(Town *t)
01476 {
01477   t->gen_max_pass = t->population >> 3;
01478   t->gen_max_mail = t->population >> 4;
01479 }
01480 
01485 void UpdateTownDemands(Town *t)
01486 {
01487   byte dtg;
01488   if(!t->larger_town) {
01489     dtg = _difficulty_town_needed_for_growth[_settings_game.economy.town_growth_cargo];
01490   } else {
01491     dtg = _difficulty_town_needed_for_growth[_settings_game.economy.larger_town_growth_cargo];
01492   }
01493   int cf = _settings_game.economy.town_cargo_factor;
01494   uint popul = t->population;
01495   if (t->larger_town) popul *= 2;
01496 
01497   /* Devided by 4 before multiplying by difficulty so that "average" can be equal to max generated passengers and mail. */
01498   t->max_pass = ((popul >> 3) / 4 * dtg) * _date_daylength_factor;
01499   t->max_mail = ((popul >> 4) / 4 * dtg) * _date_daylength_factor;
01500   /* Apply town cargo generation factor for passengers and mail too. */
01501   if (cf < 0) {
01502     /* approx (amount / 2^cf)
01503      * adjust with a constant offset of {(2 ^ cf) - 1} (i.e. add cf * 1-bits) before dividing to ensure that it doesn't become zero
01504      * this skews the curve a little so that isn't entirely exponential, but will still decrease */
01505     t->max_pass = (t->max_pass + ((1 << -cf) - 1)) >> -cf;
01506     t->max_mail = (t->max_mail + ((1 << -cf) - 1)) >> -cf;
01507   } else if (cf > 0) {
01508     /* approx (amount * 2^cf) */
01509     /* XXX: overflow? */
01510     t->max_pass = t->max_pass << cf;
01511     t->max_mail = t->max_mail << cf;
01512   }
01513 
01514   t->max_food = ((popul >> 2) / 7 / 4) * dtg;
01515   t->max_water = ((popul >> 4) * 5 / 9 / 4) * dtg;
01516   t->max_goods = ((popul >> 2) / 5 / 4) * dtg;
01517 }
01518 
01530 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01531 {
01532   t->xy = tile;
01533   t->num_houses = 0;
01534   t->time_until_rebuild = 10 * _date_daylength_factor;
01535   UpdateTownRadius(t);
01536   t->flags = 0;
01537   t->population = 0;
01538   t->grow_counter = 0;
01539   t->growth_rate = 250;
01540 
01541   t->gen_act_pass = 0;
01542   t->gen_act_mail = 0;
01543   t->gen_max_pass = 0;
01544   t->gen_max_mail = 0;
01545   t->new_gen_max_pass = 0;
01546   t->new_gen_max_mail = 0;
01547   t->new_gen_act_pass = 0;
01548   t->new_gen_act_mail = 0;
01549 
01550   t->new_max_pass = 0;
01551   t->new_max_mail = 0;
01552   t->new_max_food = 0;
01553   t->new_max_water = 0;
01554   t->new_max_goods = 0;
01555   t->new_act_pass = 0;
01556   t->new_act_mail = 0;
01557   t->new_act_food = 0;
01558   t->new_act_water = 0;
01559   t->new_act_goods = 0;
01560   t->max_pass = 0;
01561   t->max_mail = 0;
01562   t->max_food = 0;
01563   t->max_water = 0;
01564   t->max_goods = 0;
01565   t->act_pass = 0;
01566   t->act_mail = 0;
01567   t->act_food = 0;
01568   t->act_water = 0;
01569   t->act_goods = 0;
01570 
01571   t->pct_pass_transported = 0;
01572   t->pct_mail_transported = 0;
01573   t->pct_food_transported = 0;
01574   t->pct_water_transported = 0;
01575   t->pct_goods_transported = 0;
01576 
01577   t->fund_buildings_months = 0;
01578 
01579   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01580 
01581   t->have_ratings = 0;
01582   t->exclusivity = INVALID_COMPANY;
01583   t->exclusive_counter = 0;
01584   t->statues = 0;
01585 
01586   extern int _nb_orig_names;
01587   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01588     /* Original town name */
01589     t->townnamegrfid = 0;
01590     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01591   } else {
01592     /* Newgrf town name */
01593     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01594     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01595   }
01596   t->townnameparts = townnameparts;
01597 
01598   t->UpdateVirtCoord();
01599   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01600 
01601   t->InitializeLayout(layout);
01602 
01603   t->larger_town = city;
01604 
01605   int x = (int)size * 16 + 3;
01606   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01607   /* Don't create huge cities when founding town in-game */
01608   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01609 
01610   t->num_houses += x;
01611   UpdateTownRadius(t);
01612 
01613   int i = x * 4;
01614   do {
01615     GrowTown(t);
01616   } while (--i);
01617 
01618   t->num_houses -= x;
01619   UpdateTownRadius(t);
01620   UpdateTownGenCargo(t);
01621   UpdateTownDemands(t);
01622   UpdateAirportsNoise();
01623 }
01624 
01630 static CommandCost TownCanBePlacedHere(TileIndex tile)
01631 {
01632   /* Check if too close to the edge of map */
01633   if (DistanceFromEdge(tile) < 12) {
01634     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01635   }
01636 
01637   /* Check distance to all other towns. */
01638   if (IsCloseToTown(tile, 20)) {
01639     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01640   }
01641 
01642   /* Can only build on clear flat areas, possibly with trees. */
01643   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01644     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01645   }
01646 
01647   return CommandCost(EXPENSES_OTHER);
01648 }
01649 
01655 static bool IsUniqueTownName(const char *name)
01656 {
01657   const Town *t;
01658 
01659   FOR_ALL_TOWNS(t) {
01660     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01661   }
01662 
01663   return true;
01664 }
01665 
01678 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01679 {
01680   TownSize size = Extract<TownSize, 0, 2>(p1);
01681   bool city = HasBit(p1, 2);
01682   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01683   TownNameParams par(_settings_game.game_creation.town_name);
01684   bool random = HasBit(p1, 6);
01685   uint32 townnameparts = p2;
01686 
01687   if (size >= TSZ_END) return CMD_ERROR;
01688   if (layout >= NUM_TLS) return CMD_ERROR;
01689 
01690   /* Some things are allowed only in the scenario editor */
01691   if (_game_mode != GM_EDITOR) {
01692     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01693     if (size == TSZ_LARGE) return CMD_ERROR;
01694     if (random) return CMD_ERROR;
01695     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01696       return CMD_ERROR;
01697     }
01698   }
01699 
01700   if (StrEmpty(text)) {
01701     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01702     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01703   } else {
01704     /* If name is not empty, it has to be unique custom name */
01705     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01706     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01707   }
01708 
01709   /* Allocate town struct */
01710   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01711 
01712   if (!random) {
01713     CommandCost ret = TownCanBePlacedHere(tile);
01714     if (ret.Failed()) return ret;
01715   }
01716 
01717   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01718   /* multidimensional arrays have to have defined length of non-first dimension */
01719   assert_compile(lengthof(price_mult[0]) == 4);
01720 
01721   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01722   byte mult = price_mult[city][size];
01723 
01724   cost.MultiplyCost(mult);
01725 
01726   /* Create the town */
01727   if (flags & DC_EXEC) {
01728     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01729       _additional_cash_required = cost.GetCost();
01730       return CommandCost(EXPENSES_OTHER);
01731     }
01732 
01733     _generating_world = true;
01734     UpdateNearestTownForRoadTiles(true);
01735     Town *t;
01736     if (random) {
01737       t = CreateRandomTown(20, townnameparts, size, city, layout);
01738       if (t == NULL) {
01739         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01740       } else {
01741         _new_town_id = t->index;
01742       }
01743     } else {
01744       t = new Town(tile);
01745       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01746     }
01747     UpdateNearestTownForRoadTiles(false);
01748     _generating_world = false;
01749 
01750     if (t != NULL && !StrEmpty(text)) {
01751       t->name = strdup(text);
01752       t->UpdateVirtCoord();
01753     }
01754 
01755     if (_game_mode != GM_EDITOR) {
01756       /* 't' can't be NULL since 'random' is false outside scenedit */
01757       assert(!random);
01758       char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01759       SetDParam(0, _current_company);
01760       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01761 
01762       char *cn = strdup(company_name);
01763       SetDParamStr(0, cn);
01764       SetDParam(1, t->index);
01765 
01766       AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01767       AI::BroadcastNewEvent(new AIEventTownFounded(t->index));
01768     }
01769   }
01770   return cost;
01771 }
01772 
01782 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01783 {
01784   switch (layout) {
01785     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01786     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01787     default:          return tile;
01788   }
01789 }
01790 
01800 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01801 {
01802   switch (layout) {
01803     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01804     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01805     default:          return true;
01806   }
01807 }
01808 
01812 struct SpotData {
01813   TileIndex tile; 
01814   uint max_dist;  
01815   TownLayout layout; 
01816 };
01817 
01834 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01835 {
01836   SpotData *sp = (SpotData*)user_data;
01837   uint dist = GetClosestWaterDistance(tile, true);
01838 
01839   if (IsTileType(tile, MP_CLEAR) &&
01840       GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01841       IsTileAlignedToGrid(tile, sp->layout) &&
01842       dist > sp->max_dist) {
01843     sp->tile = tile;
01844     sp->max_dist = dist;
01845   }
01846 
01847   return false;
01848 }
01849 
01856 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01857 {
01858   return IsTileType(tile, MP_CLEAR);
01859 }
01860 
01873 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01874 {
01875   SpotData sp = { INVALID_TILE, 0, layout };
01876 
01877   TileIndex coast = tile;
01878   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01879     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01880     return sp.tile;
01881   }
01882 
01883   /* if we get here just give up */
01884   return INVALID_TILE;
01885 }
01886 
01887 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01888 {
01889   if (!Town::CanAllocateItem()) return NULL;
01890 
01891   do {
01892     /* Generate a tile index not too close from the edge */
01893     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01894 
01895     /* if we tried to place the town on water, slide it over onto
01896      * the nearest likely-looking spot */
01897     if (IsTileType(tile, MP_WATER)) {
01898       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01899       if (tile == INVALID_TILE) continue;
01900     }
01901 
01902     /* Make sure town can be placed here */
01903     if (TownCanBePlacedHere(tile).Failed()) continue;
01904 
01905     /* Allocate a town struct */
01906     Town *t = new Town(tile);
01907 
01908     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01909 
01910     /* if the population is still 0 at the point, then the
01911      * placement is so bad it couldn't grow at all */
01912     if (t->population > 0) return t;
01913     DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01914 
01915     /* We already know that we can allocate a single town when
01916      * entering this function. However, we create and delete
01917      * a town which "resets" the allocation checks. As such we
01918      * need to check again when assertions are enabled. */
01919     assert(Town::CanAllocateItem());
01920   } while (--attempts != 0);
01921 
01922   return NULL;
01923 }
01924 
01925 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01926 
01934 bool GenerateTowns(TownLayout layout)
01935 {
01936   uint current_number = 0;
01937   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01938   uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01939   uint32 townnameparts;
01940 
01941   SetGeneratingWorldProgress(GWP_TOWN, total);
01942 
01943   /* First attempt will be made at creating the suggested number of towns.
01944    * Note that this is really a suggested value, not a required one.
01945    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01946   do {
01947     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01948     IncreaseGeneratingWorldProgress(GWP_TOWN);
01949     /* Get a unique name for the town. */
01950     if (!GenerateTownName(&townnameparts)) continue;
01951     /* try 20 times to create a random-sized town for the first loop. */
01952     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
01953   } while (--total);
01954 
01955   if (current_number != 0) return true;
01956 
01957   /* If current_number is still zero at this point, it means that not a single town has been created.
01958    * So give it a last try, but now more aggressive */
01959   if (GenerateTownName(&townnameparts) &&
01960       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01961     return true;
01962   }
01963 
01964   /* If there are no towns at all and we are generating new game, bail out */
01965   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01966     extern StringID _switch_mode_errorstr;
01967     _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01968   }
01969 
01970   return false;  // we are still without a town? we failed, simply
01971 }
01972 
01973 
01980 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01981 {
01982   uint dist = DistanceSquare(tile, t->xy);
01983 
01984   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01985 
01986   HouseZonesBits smallest = HZB_TOWN_EDGE;
01987   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01988     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01989   }
01990 
01991   return smallest;
01992 }
01993 
02004 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
02005 {
02006   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
02007 
02008   assert(cc.Succeeded());
02009 
02010   IncreaseBuildingCount(t, type);
02011   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
02012   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
02013 
02014   MarkTileDirtyByTile(tile);
02015 }
02016 
02017 
02028 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
02029 {
02030   BuildingFlags size = HouseSpec::Get(type)->building_flags;
02031 
02032   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
02033   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
02034   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
02035   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
02036 }
02037 
02038 
02047 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
02048 {
02049   /* cannot build on these slopes... */
02050   Slope slope = GetTileSlope(tile, NULL);
02051   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
02052 
02053   /* building under a bridge? */
02054   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02055 
02056   /* do not try to build over house owned by another town */
02057   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
02058 
02059   /* can we clear the land? */
02060   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
02061 }
02062 
02063 
02073 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
02074 {
02075   if (!CanBuildHouseHere(tile, town, noslope)) return false;
02076 
02077   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
02078   if (GetTileMaxZ(tile) != z) return false;
02079 
02080   return true;
02081 }
02082 
02083 
02093 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
02094 {
02095   /* we need to check this tile too because we can be at different tile now */
02096   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02097 
02098   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02099     tile += TileOffsByDiagDir(d);
02100     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02101   }
02102 
02103   return true;
02104 }
02105 
02106 
02114 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02115 {
02116   /* Allow towns everywhere when we don't build roads */
02117   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02118 
02119   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02120 
02121   switch (t->layout) {
02122     case TL_2X2_GRID:
02123       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02124       break;
02125 
02126     case TL_3X3_GRID:
02127       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02128       break;
02129 
02130     default:
02131       break;
02132   }
02133 
02134   return true;
02135 }
02136 
02137 
02145 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02146 {
02147   /* Allow towns everywhere when we don't build roads */
02148   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02149 
02150   /* Compute relative position of tile. (Positive offsets are towards north) */
02151   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02152 
02153   switch (t->layout) {
02154     case TL_2X2_GRID:
02155       grid_pos.x %= 3;
02156       grid_pos.y %= 3;
02157       if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02158         (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02159       break;
02160 
02161     case TL_3X3_GRID:
02162       if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02163       break;
02164 
02165     default:
02166       break;
02167   }
02168 
02169   return true;
02170 }
02171 
02172 
02182 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02183 {
02184   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02185 
02186   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02187   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02188 
02189   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02190   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02191     *tile = tile2;
02192     return true;
02193   }
02194 
02195   return false;
02196 }
02197 
02198 
02207 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02208 {
02209   TileIndex tile2 = *tile;
02210 
02211   for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02212     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02213       *tile = tile2;
02214       return true;
02215     }
02216     if (d == DIAGDIR_END) break;
02217     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02218   }
02219 
02220   return false;
02221 }
02222 
02223 
02230 static bool BuildTownHouse(Town *t, TileIndex tile)
02231 {
02232   /* forbidden building here by town layout */
02233   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02234 
02235   /* no house allowed at all, bail out */
02236   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02237 
02238   uint z;
02239   Slope slope = GetTileSlope(tile, &z);
02240 
02241   /* Get the town zone type of the current tile, as well as the climate.
02242    * This will allow to easily compare with the specs of the new house to build */
02243   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02244 
02245   /* Above snow? */
02246   int land = _settings_game.game_creation.landscape;
02247   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02248 
02249   uint bitmask = (1 << rad) + (1 << (land + 12));
02250 
02251   /* bits 0-4 are used
02252    * bits 11-15 are used
02253    * bits 5-10 are not used. */
02254   HouseID houses[HOUSE_MAX];
02255   uint num = 0;
02256   uint probs[HOUSE_MAX];
02257   uint probability_max = 0;
02258 
02259   /* Generate a list of all possible houses that can be built. */
02260   for (uint i = 0; i < HOUSE_MAX; i++) {
02261     const HouseSpec *hs = HouseSpec::Get(i);
02262 
02263     /* Verify that the candidate house spec matches the current tile status */
02264     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02265 
02266     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02267     if (hs->class_id != HOUSE_NO_CLASS) {
02268       /* id_count is always <= class_count, so it doesn't need to be checked */
02269       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02270     } else {
02271       /* If the house has no class, check id_count instead */
02272       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02273     }
02274 
02275     /* Without NewHouses, all houses have probability '1' */
02276     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02277     probability_max += cur_prob;
02278     probs[num] = cur_prob;
02279     houses[num++] = (HouseID)i;
02280   }
02281 
02282   uint maxz = GetTileMaxZ(tile);
02283 
02284   while (probability_max > 0) {
02285     uint r = RandomRange(probability_max);
02286     uint i;
02287     for (i = 0; i < num; i++) {
02288       if (probs[i] > r) break;
02289       r -= probs[i];
02290     }
02291 
02292     HouseID house = houses[i];
02293     probability_max -= probs[i];
02294 
02295     /* remove tested house from the set */
02296     num--;
02297     houses[i] = houses[num];
02298     probs[i] = probs[num];
02299 
02300     const HouseSpec *hs = HouseSpec::Get(house);
02301 
02302     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02303         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02304       continue;
02305     }
02306 
02307     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02308 
02309     /* Special houses that there can be only one of. */
02310     uint oneof = 0;
02311 
02312     if (hs->building_flags & BUILDING_IS_CHURCH) {
02313       SetBit(oneof, TOWN_HAS_CHURCH);
02314     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02315       SetBit(oneof, TOWN_HAS_STADIUM);
02316     }
02317 
02318     if (t->flags & oneof) continue;
02319 
02320     /* Make sure there is no slope? */
02321     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02322     if (noslope && slope != SLOPE_FLAT) continue;
02323 
02324     if (hs->building_flags & TILE_SIZE_2x2) {
02325       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02326     } else if (hs->building_flags & TILE_SIZE_2x1) {
02327       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02328     } else if (hs->building_flags & TILE_SIZE_1x2) {
02329       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02330     } else {
02331       /* 1x1 house checks are already done */
02332     }
02333 
02334     byte random_bits = Random();
02335 
02336     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02337       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02338       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02339     }
02340 
02341     /* build the house */
02342     t->num_houses++;
02343 
02344     /* Special houses that there can be only one of. */
02345     t->flags |= oneof;
02346 
02347     byte construction_counter = 0;
02348     byte construction_stage = 0;
02349 
02350     if (_generating_world || _game_mode == GM_EDITOR) {
02351       uint32 r = Random();
02352 
02353       construction_stage = TOWN_HOUSE_COMPLETED;
02354       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02355 
02356       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02357         ChangePopulation(t, hs->population);
02358       } else {
02359         construction_counter = GB(r, 2, 2);
02360       }
02361     }
02362 
02363     MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02364 
02365     return true;
02366   }
02367 
02368   return false;
02369 }
02370 
02377 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02378 {
02379   assert(IsTileType(tile, MP_HOUSE));
02380 
02381   DecreaseBuildingCount(t, house);
02382   DoClearSquare(tile);
02383   DeleteAnimatedTile(tile);
02384 
02385   DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02386 }
02387 
02395 TileIndexDiff GetHouseNorthPart(HouseID &house)
02396 {
02397   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02398     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02399       house--;
02400       return TileDiffXY(-1, 0);
02401     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02402       house--;
02403       return TileDiffXY(0, -1);
02404     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02405       house -= 2;
02406       return TileDiffXY(-1, 0);
02407     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02408       house -= 3;
02409       return TileDiffXY(-1, -1);
02410     }
02411   }
02412   return 0;
02413 }
02414 
02415 void ClearTownHouse(Town *t, TileIndex tile)
02416 {
02417   assert(IsTileType(tile, MP_HOUSE));
02418 
02419   HouseID house = GetHouseType(tile);
02420 
02421   /* need to align the tile to point to the upper left corner of the house */
02422   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02423 
02424   const HouseSpec *hs = HouseSpec::Get(house);
02425 
02426   /* Remove population from the town if the house is finished. */
02427   if (IsHouseCompleted(tile)) {
02428     ChangePopulation(t, -hs->population);
02429   }
02430 
02431   t->num_houses--;
02432 
02433   /* Clear flags for houses that only may exist once/town. */
02434   if (hs->building_flags & BUILDING_IS_CHURCH) {
02435     ClrBit(t->flags, TOWN_HAS_CHURCH);
02436   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02437     ClrBit(t->flags, TOWN_HAS_STADIUM);
02438   }
02439 
02440   /* Do the actual clearing of tiles */
02441   uint eflags = hs->building_flags;
02442   DoClearTownHouseHelper(tile, t, house);
02443   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02444   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02445   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02446 }
02447 
02457 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02458 {
02459   Town *t = Town::GetIfValid(p1);
02460   if (t == NULL) return CMD_ERROR;
02461 
02462   bool reset = StrEmpty(text);
02463 
02464   if (!reset) {
02465     if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02466     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02467   }
02468 
02469   if (flags & DC_EXEC) {
02470     free(t->name);
02471     t->name = reset ? NULL : strdup(text);
02472 
02473     t->UpdateVirtCoord();
02474     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02475     UpdateAllStationVirtCoords();
02476   }
02477   return CommandCost();
02478 }
02479 
02489 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02490 {
02491   if (_game_mode != GM_EDITOR) return CMD_ERROR;
02492   Town *t = Town::GetIfValid(p1);
02493   if (t == NULL) return CMD_ERROR;
02494 
02495   if (flags & DC_EXEC) {
02496     /* The more houses, the faster we grow */
02497     uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02498     t->num_houses += amount;
02499     UpdateTownRadius(t);
02500 
02501     uint n = amount * 10;
02502     do GrowTown(t); while (--n);
02503 
02504     t->num_houses -= amount;
02505     UpdateTownRadius(t);
02506 
02507     UpdateTownGenCargo(t);
02508     UpdateTownDemands(t);
02509   }
02510 
02511   return CommandCost();
02512 }
02513 
02523 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02524 {
02525   if (_game_mode != GM_EDITOR) return CMD_ERROR;
02526   Town *t = Town::GetIfValid(p1);
02527   if (t == NULL) return CMD_ERROR;
02528 
02529   /* Stations refer to towns. */
02530   const Station *st;
02531   FOR_ALL_STATIONS(st) {
02532     if (st->town == t) {
02533       /* Non-oil rig stations are always a problem. */
02534       if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02535       /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
02536       CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02537       if (ret.Failed()) return ret;
02538     }
02539   }
02540 
02541   /* Depots refer to towns. */
02542   const Depot *d;
02543   FOR_ALL_DEPOTS(d) {
02544     if (d->town == t) return CMD_ERROR;
02545   }
02546 
02547   /* Check all tiles for town ownership. */
02548   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02549     bool try_clear = false;
02550     switch (GetTileType(tile)) {
02551       case MP_ROAD:
02552         try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02553         break;
02554 
02555       case MP_TUNNELBRIDGE:
02556         try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02557         break;
02558 
02559       case MP_HOUSE:
02560         try_clear = GetTownIndex(tile) == t->index;
02561         break;
02562 
02563       case MP_INDUSTRY:
02564         try_clear = Industry::GetByTile(tile)->town == t;
02565         break;
02566 
02567       case MP_OBJECT:
02568         if (Town::GetNumItems() == 1) {
02569           /* No towns will be left, remove it! */
02570           try_clear = true;
02571         } else {
02572           Object *o = Object::GetByTile(tile);
02573           if (o->town == t) {
02574             if (GetObjectType(tile) == OBJECT_STATUE) {
02575               /* Statue... always remove. */
02576               try_clear = true;
02577             } else {
02578               /* Tell to find a new town. */
02579               if (flags & DC_EXEC) o->town = NULL;
02580             }
02581           }
02582         }
02583         break;
02584 
02585       default:
02586         break;
02587     }
02588     if (try_clear) {
02589       CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02590       if (ret.Failed()) return ret;
02591     }
02592   }
02593 
02594   /* The town destructor will delete the other things related to the town. */
02595   if (flags & DC_EXEC) delete t;
02596 
02597   return CommandCost();
02598 }
02599 
02604 const byte _town_action_costs[TACT_COUNT] = {
02605   2, 4, 9, 35, 48, 53, 117, 175
02606 };
02607 
02608 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02609 {
02610   if (flags & DC_EXEC) {
02611     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02612   }
02613   return CommandCost();
02614 }
02615 
02616 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02617 {
02618   if (flags & DC_EXEC) {
02619     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02620   }
02621   return CommandCost();
02622 }
02623 
02624 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02625 {
02626   if (flags & DC_EXEC) {
02627     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02628   }
02629   return CommandCost();
02630 }
02631 
02632 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02633 {
02634   /* Check if the company is allowed to fund new roads. */
02635   if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02636 
02637   if (flags & DC_EXEC) {
02638     t->road_build_months = 6;
02639 
02640     char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02641     SetDParam(0, _current_company);
02642     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02643 
02644     char *cn = strdup(company_name);
02645     SetDParam(0, t->index);
02646     SetDParamStr(1, cn);
02647 
02648     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02649   }
02650   return CommandCost();
02651 }
02652 
02659 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02660 {
02661   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02662   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02663   /* Don't build statues under bridges. */
02664   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02665 
02666   if (!IsTileType(tile, MP_HOUSE) &&
02667       !IsTileType(tile, MP_CLEAR) &&
02668       !IsTileType(tile, MP_TREES)) {
02669     return false;
02670   }
02671 
02672   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02673   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02674   cur_company.Restore();
02675 
02676   if (r.Failed()) return false;
02677 
02678   return true;
02679 }
02680 
02688 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02689 {
02690   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02691 
02692   TileIndex tile = t->xy;
02693   if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02694     if (flags & DC_EXEC) {
02695       Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02696       DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02697       cur_company.Restore();
02698       BuildObject(OBJECT_STATUE, tile, _current_company, t);
02699       SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02700       MarkTileDirtyByTile(tile);
02701     }
02702     return CommandCost();
02703   }
02704   return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02705 }
02706 
02707 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02708 {
02709   if (flags & DC_EXEC) {
02710     /* Build next tick */
02711     t->grow_counter = 1;
02712     /* If we were not already growing */
02713     SetBit(t->flags, TOWN_IS_FUNDED);
02714     /* And grow for 3 months */
02715     t->fund_buildings_months = 3;
02716   }
02717   return CommandCost();
02718 }
02719 
02720 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02721 {
02722   /* Check if it's allowed to buy the rights */
02723   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02724 
02725   if (flags & DC_EXEC) {
02726     t->exclusive_counter = 12 * _date_daylength_factor;
02727     t->exclusivity = _current_company;
02728 
02729     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02730   }
02731   return CommandCost();
02732 }
02733 
02734 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02735 {
02736   if (flags & DC_EXEC) {
02737     if (Chance16(1, 14)) {
02738       /* set as unwanted for 6 months */
02739       t->unwanted[_current_company] = 6;
02740 
02741       /* set all close by station ratings to 0 */
02742       Station *st;
02743       FOR_ALL_STATIONS(st) {
02744         if (st->town == t && st->owner == _current_company) {
02745           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02746         }
02747       }
02748 
02749       /* only show errormessage to the executing player. All errors are handled command.c
02750        * but this is special, because it can only 'fail' on a DC_EXEC */
02751       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, WL_INFO);
02752 
02753       /* decrease by a lot!
02754        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02755        * be independent of any cheat settings
02756        */
02757       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02758         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02759         t->UpdateVirtCoord();
02760         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02761       }
02762     } else {
02763       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02764     }
02765   }
02766   return CommandCost();
02767 }
02768 
02769 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02770 static TownActionProc * const _town_action_proc[] = {
02771   TownActionAdvertiseSmall,
02772   TownActionAdvertiseMedium,
02773   TownActionAdvertiseLarge,
02774   TownActionRoadRebuild,
02775   TownActionBuildStatue,
02776   TownActionFundBuildings,
02777   TownActionBuyRights,
02778   TownActionBribe
02779 };
02780 
02788 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02789 {
02790   int num = 0;
02791   TownActions buttons = TACT_NONE;
02792 
02793   /* Spectators and unwanted have no options */
02794   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02795 
02796     /* Things worth more than this are not shown */
02797     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02798 
02799     /* Check the action bits for validity and
02800      * if they are valid add them */
02801     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02802       const TownActions cur = (TownActions)(1 << i);
02803 
02804       /* Is the company not able to bribe ? */
02805       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02806 
02807       /* Is the company not able to buy exclusive rights ? */
02808       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02809 
02810       /* Is the company not able to fund local road reconstruction? */
02811       if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02812 
02813       /* Is the company not able to build a statue ? */
02814       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02815 
02816       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02817         buttons |= cur;
02818         num++;
02819       }
02820     }
02821   }
02822 
02823   if (nump != NULL) *nump = num;
02824   return buttons;
02825 }
02826 
02838 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02839 {
02840   Town *t = Town::GetIfValid(p1);
02841   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02842 
02843   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02844 
02845   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02846 
02847   CommandCost ret = _town_action_proc[p2](t, flags);
02848   if (ret.Failed()) return ret;
02849 
02850   if (flags & DC_EXEC) {
02851     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02852   }
02853 
02854   return cost;
02855 }
02856 
02857 static void UpdateTownGrowRate(Town *t)
02858 {
02859   /* Increase company ratings if they're low */
02860   const Company *c;
02861   FOR_ALL_COMPANIES(c) {
02862     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02863       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02864     }
02865   }
02866 
02867   int n = 0; 
02868 
02869   /* Calculate the number of well serviced stations. */
02870   const Station *st;
02871   FOR_ALL_STATIONS(st) {
02872     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02873       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02874         n++;
02875         if (Company::IsValidID(st->owner)) {
02876           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02877           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02878         }
02879       } else {
02880         if (Company::IsValidID(st->owner)) {
02881           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02882           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02883         }
02884       }
02885     }
02886   }
02887 
02888   /* clamp all ratings to valid values */
02889   for (uint i = 0; i < MAX_COMPANIES; i++) {
02890     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02891   }
02892 
02893   t->UpdateVirtCoord();
02894   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02895 
02896   ClrBit(t->flags, TOWN_IS_FUNDED);
02897   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02898 
02903   static const uint16 _grow_count_values[2][6] = {
02904     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02905     { 320, 420, 300, 220, 160, 100 }  // Normal values
02906   };
02907 
02908   uint16 m;
02909 
02910   if (t->fund_buildings_months != 0) {
02911     m = _grow_count_values[0][min(n, 5)];
02912     t->fund_buildings_months--;
02913   } else {
02914     m = _grow_count_values[1][min(n, 5)];
02915     if (n == 0 && !Chance16(1, 12)) return;
02916   }
02917 
02918   uint32 ratio = 1; // 1 in case the towngrowth patch is off, else we calculate the value below
02919 
02920   if ((!t->larger_town && _settings_game.economy.town_growth_cargo) ||
02921       (t->larger_town && _settings_game.economy.larger_town_growth_cargo)) {
02922     ratio                = 0;   
02923     uint32 current_ratio = 0;   
02924     byte previous_ratio  = 100; 
02925 
02926     /* Calculate current growth ratio based on transported cargo.
02927      * First we add all the individual values per cargo type (and number of stations).
02928      * Then we devide by the number of requirements dependant on climate and location to get the mean value.
02929      * Finally we devide by 100 so we can use it as a multiplier. */
02930     if ((!t->larger_town && t->population > _settings_game.economy.town_pop_need_goods) ||
02931         (t->larger_town && t->population > _settings_game.economy.larger_town_pop_need_goods)) {
02932 
02933       /* Calculate the number of required well serviced stations based on population.*/
02934       static const uint32 _populations[] = {
02935         5500, 9000, 12500, 17000, 21500, 27000, 31500, 37000, 42500, 48000, 54500, 61000, 67500, 77500, 88500, 99500, 105500,
02936       };
02937 
02938       byte required_stations = 5; 
02939 
02940       for (const uint32 *p = _populations; p < endof(_populations); p++) {
02941         if (t->population < *p) break;
02942         required_stations++;
02943       }
02944 
02945       /* Add a few required stations as per dificulty level */
02946       if (t->population >= 5500) {
02947         if (!t->larger_town) {
02948           required_stations += _settings_game.economy.town_growth_cargo;
02949         } else {
02950           required_stations += _settings_game.economy.larger_town_growth_cargo;
02951         }
02952       }
02953 
02954       /* Do we need more serviced station for growth? */
02955       current_ratio = n / required_stations * 100;
02956       if (current_ratio > 100) current_ratio = 100;
02957       if (current_ratio < 100 && current_ratio < previous_ratio) {
02958         previous_ratio = current_ratio;
02959         t->needed_for_growth = GROWTH_NEED_STATION;
02960       }
02961       ratio += current_ratio;
02962 
02963       /* Slow growth if transported passengers ratio is bad in big town. */
02964       current_ratio = t->act_pass / t->max_pass * 100;
02965       if (current_ratio > 100) current_ratio = 100;
02966       if (current_ratio < 100 && current_ratio < previous_ratio) {
02967         previous_ratio = current_ratio;
02968         t->needed_for_growth = GROWTH_NEED_MORE_PASS;
02969       }
02970       ratio += current_ratio;
02971 
02972       /* Slow growth if transported mail ratio is bad in big town. */
02973       current_ratio = t->act_mail / t->max_mail * 100;
02974       if (current_ratio > 100) current_ratio = 100;
02975       if (current_ratio < 100 && current_ratio < previous_ratio) {
02976         previous_ratio = current_ratio;
02977         t->needed_for_growth = GROWTH_NEED_MORE_MAIL;
02978       }
02979       ratio += current_ratio;
02980 
02981       /* Slow growth if transported food ratio is bad in big town.
02982        * @note in toyland food is Fizzy drinks. */
02983       if ((_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine()) ||
02984           (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) ||
02985           (_settings_game.game_creation.landscape == LT_TOYLAND)) {
02986         current_ratio = t->act_food / t->max_food * 100;
02987         if (ratio > 100) current_ratio = 100;
02988         if (ratio < 100 && current_ratio < previous_ratio) {
02989           previous_ratio = current_ratio;
02990           t->needed_for_growth = GROWTH_NEED_MORE_FOOD;
02991         }
02992         ratio += current_ratio;
02993       }
02994 
02995       /* Slow growth if transported water is bad in big town. */
02996       if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) {
02997         current_ratio = t->act_water / t->max_water * 100;
02998         if (current_ratio > 100) current_ratio = 100;
02999         if (current_ratio < 100 && current_ratio < previous_ratio) {
03000           previous_ratio = current_ratio;
03001           t->needed_for_growth = GROWTH_NEED_MORE_WATER;
03002         }
03003         ratio += current_ratio;
03004       }
03005 
03006       /* Slow growth if transported goods ratio is bad in big town.
03007        * @note: in Toyland goods is sweets.*/
03008       current_ratio = t->act_goods / t->max_goods * 100;
03009       if (current_ratio > 100) current_ratio = 100;
03010       if (current_ratio < 100 && current_ratio < previous_ratio) {
03011         previous_ratio = current_ratio;
03012         t->needed_for_growth = GROWTH_NEED_MORE_GOODS;
03013       }
03014       ratio += current_ratio;
03015 
03016       /* At this point ratio is the sum of the transported ratios of all requirements.*/
03017       /* Now we calculate the mean percentage of transported ratio for all transported cargos. */
03018       byte number_of_required = 4;   
03019       if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) number_of_required += 2;
03020       if (_settings_game.game_creation.landscape == LT_TOYLAND || (_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine())) number_of_required += 1;
03021       ratio /= number_of_required;
03022 
03023       /* Now we do two things to the ratio. */
03024       t->transported_goods_percent = ratio; // 1. Display the ratio in the gui.
03025       ratio /= 100;                         // 2. Devide the ratio by hundred so we can use it as a multiplier later in the code.
03026 
03027       /* If a required cargo is not transported to big town ask for the service to be provided. */
03028       if (t->act_pass == 0) {
03029         t->needed_for_growth = GROWTH_NEED_PASS ;
03030         return;
03031       }
03032 
03033       if (t->act_mail == 0) {
03034         t->needed_for_growth = GROWTH_NEED_MAIL ;
03035         return;
03036       }
03037 
03038       if (((_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine()) ||
03039           (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) ||
03040           (_settings_game.game_creation.landscape == LT_TOYLAND)) &&
03041           t->act_food == 0) {
03042         t->needed_for_growth = GROWTH_NEED_FOOD;
03043         return;
03044       }
03045 
03046       if (_settings_game.game_creation.landscape == LT_TROPIC &&
03047           GetTropicZone(t->xy) == TROPICZONE_DESERT &&
03048           t->act_water == 0) {
03049         t->needed_for_growth = GROWTH_NEED_WATER;
03050         return;
03051       }
03052 
03053       if (t->act_goods == 0) {
03054         t->needed_for_growth = GROWTH_NEED_GOODS ;
03055         return;
03056       }
03057     }
03058   }
03059 
03060   /* The old way if town growth patch is off.*/
03061   if ((!t->larger_town && !_settings_game.economy.town_growth_cargo) ||
03062       (t->larger_town && !_settings_game.economy.larger_town_growth_cargo)) {
03063     if (_settings_game.game_creation.landscape == LT_ARCTIC) {
03064       if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90) {
03065         t->needed_for_growth = GROWTH_NEED_FOOD;
03066         return;
03067       }
03068     } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
03069       if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->act_food == 0 && t->population > 60) {
03070         t->needed_for_growth = GROWTH_NEED_FOOD;
03071         return;
03072       }
03073       if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->act_water == 0 && t->population > 60) {
03074         t->needed_for_growth = GROWTH_NEED_WATER;
03075         return;
03076       }
03077     }
03078   }
03079 
03080   /* Use the normal growth rate values if new buildings have been funded in
03081    * this town and the growth rate is set to none.
03082    * Else we multiply the growth rate by the ratio of all transported goods, calculated above by devided by 100..*/
03083 
03084   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
03085 
03086   m >>= growth_multiplier;
03087   if (t->larger_town) m /= 2;
03088 
03089   /* if ratio is smaller than 1 reduce towngrowth. */
03090   if ((!t->larger_town && !_settings_game.economy.town_growth_cargo) ||
03091       (t->larger_town && !_settings_game.economy.larger_town_growth_cargo) ||
03092       (!t->larger_town && t->population < _settings_game.economy.town_pop_need_goods) ||
03093       (t->larger_town && t->population < _settings_game.economy.larger_town_pop_need_goods)) {
03094     t->growth_rate = m / (t->num_houses / 50 + 1);
03095   } else {
03096     t->growth_rate = m / (t->num_houses / 50 + 1) * ratio;
03097   }
03098 
03099   if (m <= t->grow_counter) {
03100     t->grow_counter = m;
03101   }
03102 
03103   SetBit(t->flags, TOWN_IS_FUNDED);
03104 }
03105 
03106 static void UpdateTownAmounts(Town *t)
03107 {
03108   /* Using +1 here to prevent overflow and division by zero */
03109   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
03110   t->gen_max_pass = t->new_gen_max_pass; t->new_gen_max_pass = 0; // Town generated passengers - maximum.
03111   t->gen_act_pass = t->new_gen_act_pass; t->new_gen_act_pass = 0; // Town generated passengers - actually generated (amount that could be moved to stations).
03112   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
03113   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
03114 
03115   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
03116   t->gen_max_mail = t->new_gen_max_mail; t->new_gen_max_mail = 0; // Town generated mail - maximum.
03117   t->gen_act_mail = t->new_gen_act_mail; t->new_gen_act_mail = 0; // Town generated mail - actually generated (amount that could be moved to stations).
03118   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
03119   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
03120 
03121   t->pct_food_transported = t->new_act_food * 256 / (t->new_max_food + 1);
03122   t->max_food = t->new_max_food; t->new_max_food = 0;
03123   t->act_food = t->new_act_food; t->new_act_food = 0;
03124 
03125   t->pct_water_transported = t->new_act_water * 256 / (t->new_max_water + 1);
03126   t->max_water = t->new_max_water; t->new_max_water = 0;
03127   t->act_water = t->new_act_water; t->new_act_water = 0;
03128 
03129   t->pct_goods_transported = t->new_act_goods * 256 / (t->new_max_goods + 1);
03130   t->max_goods = t->new_max_goods; t->new_max_goods = 0;
03131   t->act_goods = t->new_act_goods; t->new_act_goods = 0;
03132 
03133   SetWindowDirty(WC_TOWN_VIEW, t->index);
03134 }
03135 
03136 static void UpdateTownUnwanted(Town *t)
03137 {
03138   const Company *c;
03139 
03140   FOR_ALL_COMPANIES(c) {
03141     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
03142   }
03143 }
03144 
03151 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
03152 {
03153   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
03154 
03155   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
03156   if (t == NULL) return CommandCost();
03157 
03158   if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
03159 
03160   SetDParam(0, t->index);
03161   return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03162 }
03163 
03172 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
03173 {
03174   Town *t;
03175   uint best = threshold;
03176   Town *best_town = NULL;
03177 
03178   FOR_ALL_TOWNS(t) {
03179     uint dist = DistanceManhattan(tile, t->xy);
03180     if (dist < best) {
03181       best = dist;
03182       best_town = t;
03183     }
03184   }
03185 
03186   return best_town;
03187 }
03188 
03197 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
03198 {
03199   switch (GetTileType(tile)) {
03200     case MP_ROAD:
03201       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
03202 
03203       if (!HasTownOwnedRoad(tile)) {
03204         TownID tid = GetTownIndex(tile);
03205 
03206         if (tid == (TownID)INVALID_TOWN) {
03207           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
03208           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03209           assert(Town::GetNumItems() == 0);
03210           return NULL;
03211         }
03212 
03213         assert(Town::IsValidID(tid));
03214         Town *town = Town::Get(tid);
03215 
03216         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03217 
03218         return town;
03219       }
03220       /* FALL THROUGH */
03221 
03222     case MP_HOUSE:
03223       return Town::GetByTile(tile);
03224 
03225     default:
03226       return CalcClosestTownFromTile(tile, threshold);
03227   }
03228 }
03229 
03230 static bool _town_rating_test = false; 
03231 static SmallMap<const Town *, int, 4> _town_test_ratings; 
03232 
03238 void SetTownRatingTestMode(bool mode)
03239 {
03240   static int ref_count = 0; // Number of times test-mode is switched on.
03241   if (mode) {
03242     if (ref_count == 0) {
03243       _town_test_ratings.Clear();
03244     }
03245     ref_count++;
03246   } else {
03247     assert(ref_count > 0);
03248     ref_count--;
03249   }
03250   _town_rating_test = !(ref_count == 0);
03251 }
03252 
03258 static int GetRating(const Town *t)
03259 {
03260   if (_town_rating_test) {
03261     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03262     if (it != _town_test_ratings.End()) {
03263       return it->second;
03264     }
03265   }
03266   return t->ratings[_current_company];
03267 }
03268 
03276 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03277 {
03278   /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
03279   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03280       !Company::IsValidID(_current_company) ||
03281       (_cheats.magic_bulldozer.value && add < 0)) {
03282     return;
03283   }
03284 
03285   int rating = GetRating(t);
03286   if (add < 0) {
03287     if (rating > max) {
03288       rating += add;
03289       if (rating < max) rating = max;
03290     }
03291   } else {
03292     if (rating < max) {
03293       rating += add;
03294       if (rating > max) rating = max;
03295     }
03296   }
03297   if (_town_rating_test) {
03298     _town_test_ratings[t] = rating;
03299   } else {
03300     SetBit(t->have_ratings, _current_company);
03301     t->ratings[_current_company] = rating;
03302     t->UpdateVirtCoord();
03303     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03304   }
03305 }
03306 
03314 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03315 {
03316   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
03317   if (t == NULL || !Company::IsValidID(_current_company) ||
03318       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03319     return CommandCost();
03320   }
03321 
03322   /* minimum rating needed to be allowed to remove stuff */
03323   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03324     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
03325     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
03326     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
03327     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
03328   };
03329 
03330   /* check if you're allowed to remove the road/bridge/tunnel
03331    * owned by a town no removal if rating is lower than ... depends now on
03332    * difficulty setting. Minimum town rating selected by difficulty level
03333    */
03334   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03335 
03336   if (GetRating(t) < needed) {
03337     SetDParam(0, t->index);
03338     return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03339   }
03340 
03341   return CommandCost();
03342 }
03343 
03344 void TownsMonthlyLoop()
03345 {
03346   Town *t;
03347 
03348   FOR_ALL_TOWNS(t) {
03349     if (t->road_build_months != 0) t->road_build_months--;
03350 
03351     if (t->exclusive_counter != 0) {
03352       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03353     }
03354 
03355     UpdateTownGrowRate(t);
03356     UpdateTownAmounts(t);
03357     UpdateTownUnwanted(t);
03358   }
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, uint 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 != 0) && (res != CALLBACK_FAILED)) 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   GetSlopeZ_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_clear
03409   ChangeTileOwner_Town,    // change_tile_owner_clear
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[HOUSE_MAX];
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 }