town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 20870 2010-10-02 14:34:00Z rubidium $ */
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 "unmovable_map.h"
00025 #include "variables.h"
00026 #include "genworld.h"
00027 #include "newgrf.h"
00028 #include "newgrf_house.h"
00029 #include "newgrf_commons.h"
00030 #include "newgrf_text.h"
00031 #include "autoslope.h"
00032 #include "tunnelbridge_map.h"
00033 #include "unmovable_map.h"
00034 #include "strings_func.h"
00035 #include "window_func.h"
00036 #include "string_func.h"
00037 #include "newgrf_cargo.h"
00038 #include "cheat_type.h"
00039 #include "functions.h"
00040 #include "animated_tile_func.h"
00041 #include "date_func.h"
00042 #include "subsidy_func.h"
00043 #include "core/smallmap_type.hpp"
00044 #include "core/pool_func.hpp"
00045 #include "town.h"
00046 #include "townname_func.h"
00047 #include "townname_type.h"
00048 #include "core/random_func.hpp"
00049 
00050 #include "table/strings.h"
00051 #include "table/town_land.h"
00052 
00053 static Town *_cleared_town;
00054 static int _cleared_town_rating;
00055 TownID _new_town_id;
00056 
00057 /* Initialize the town-pool */
00058 TownPool _town_pool("Town");
00059 INSTANTIATE_POOL_METHODS(Town)
00060 
00061 Town::~Town()
00062 {
00063   free(this->name);
00064 
00065   if (CleaningPool()) return;
00066 
00067   Industry *i;
00068 
00069   /* Delete town authority window
00070    * and remove from list of sorted towns */
00071   DeleteWindowById(WC_TOWN_VIEW, this->index);
00072 
00073   /* Delete all industries belonging to the town */
00074   FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00075 
00076   /* Go through all tiles and delete those belonging to the town */
00077   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00078     switch (GetTileType(tile)) {
00079       case MP_HOUSE:
00080         if (Town::GetByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00081         break;
00082 
00083       case MP_ROAD:
00084         /* Cached nearest town is updated later (after this town has been deleted) */
00085         if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00086           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00087         }
00088         break;
00089 
00090       case MP_TUNNELBRIDGE:
00091         if (IsTileOwner(tile, OWNER_TOWN) &&
00092             ClosestTownFromTile(tile, UINT_MAX) == this)
00093           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00094         break;
00095 
00096       case MP_UNMOVABLE:
00097         if (GetUnmovableType(tile) == UNMOVABLE_STATUE && GetStatueTownID(tile) == this->index) {
00098           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00099         }
00100         break;
00101 
00102       default:
00103         break;
00104     }
00105   }
00106 
00107   DeleteSubsidyWith(ST_TOWN, this->index);
00108   CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00109   MarkWholeScreenDirty();
00110 }
00111 
00112 
00118 void Town::PostDestructor(size_t index)
00119 {
00120   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00121   UpdateNearestTownForRoadTiles(false);
00122 }
00123 
00127 void Town::InitializeLayout(TownLayout layout)
00128 {
00129   if (layout != TL_RANDOM) {
00130     this->layout = layout;
00131     return;
00132   }
00133 
00134   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00135 }
00136 
00141 /* static */ Town *Town::GetRandom()
00142 {
00143   if (Town::GetNumItems() == 0) return NULL;
00144   int num = RandomRange((uint16)Town::GetNumItems());
00145   size_t index = MAX_UVALUE(size_t);
00146 
00147   while (num >= 0) {
00148     num--;
00149     index++;
00150 
00151     /* Make sure we have a valid town */
00152     while (!Town::IsValidID(index)) {
00153       index++;
00154       assert(index < Town::GetPoolSize());
00155     }
00156   }
00157 
00158   return Town::Get(index);
00159 }
00160 
00161 Money HouseSpec::GetRemovalCost() const
00162 {
00163   return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00164 }
00165 
00166 // Local
00167 static int _grow_town_result;
00168 
00169 /* Describe the possible states */
00170 enum TownGrowthResult {
00171   GROWTH_SUCCEED         = -1,
00172   GROWTH_SEARCH_STOPPED  =  0
00173 //  GROWTH_SEARCH_RUNNING >=  1
00174 };
00175 
00176 static bool BuildTownHouse(Town *t, TileIndex tile);
00177 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00178 
00179 static void TownDrawHouseLift(const TileInfo *ti)
00180 {
00181   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00182 }
00183 
00184 typedef void TownDrawTileProc(const TileInfo *ti);
00185 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00186   TownDrawHouseLift
00187 };
00188 
00194 static inline DiagDirection RandomDiagDir()
00195 {
00196   return (DiagDirection)(3 & Random());
00197 }
00198 
00204 static void DrawTile_Town(TileInfo *ti)
00205 {
00206   HouseID house_id = GetHouseType(ti->tile);
00207 
00208   if (house_id >= NEW_HOUSE_OFFSET) {
00209     /* Houses don't necessarily need new graphics. If they don't have a
00210      * spritegroup associated with them, then the sprite for the substitute
00211      * house id is drawn instead. */
00212     if (HouseSpec::Get(house_id)->spritegroup != NULL) {
00213       DrawNewHouseTile(ti, house_id);
00214       return;
00215     } else {
00216       house_id = HouseSpec::Get(house_id)->substitute_id;
00217     }
00218   }
00219 
00220   /* Retrieve pointer to the draw town tile struct */
00221   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00222 
00223   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00224 
00225   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00226 
00227   /* If houses are invisible, do not draw the upper part */
00228   if (IsInvisibilitySet(TO_HOUSES)) return;
00229 
00230   /* Add a house on top of the ground? */
00231   SpriteID image = dcts->building.sprite;
00232   if (image != 0) {
00233     AddSortableSpriteToDraw(image, dcts->building.pal,
00234       ti->x + dcts->subtile_x,
00235       ti->y + dcts->subtile_y,
00236       dcts->width,
00237       dcts->height,
00238       dcts->dz,
00239       ti->z,
00240       IsTransparencySet(TO_HOUSES)
00241     );
00242 
00243     if (IsTransparencySet(TO_HOUSES)) return;
00244   }
00245 
00246   {
00247     int proc = dcts->draw_proc - 1;
00248 
00249     if (proc >= 0) _town_draw_tile_procs[proc](ti);
00250   }
00251 }
00252 
00253 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00254 {
00255   return GetTileMaxZ(tile);
00256 }
00257 
00259 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00260 {
00261   HouseID hid = GetHouseType(tile);
00262 
00263   /* For NewGRF house tiles we might not be drawing a foundation. We need to
00264    * account for this, as other structures should
00265    * draw the wall of the foundation in this case.
00266    */
00267   if (hid >= NEW_HOUSE_OFFSET) {
00268     const HouseSpec *hs = HouseSpec::Get(hid);
00269     if (hs->spritegroup != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00270       uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00271       if (callback_res == 0) return FOUNDATION_NONE;
00272     }
00273   }
00274   return FlatteningFoundation(tileh);
00275 }
00276 
00283 static void AnimateTile_Town(TileIndex tile)
00284 {
00285   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00286     AnimateNewHouseTile(tile);
00287     return;
00288   }
00289 
00290   if (_tick_counter & 3) return;
00291 
00292   /* If the house is not one with a lift anymore, then stop this animating.
00293    * Not exactly sure when this happens, but probably when a house changes.
00294    * Before this was just a return...so it'd leak animated tiles..
00295    * That bug seems to have been here since day 1?? */
00296   if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00297     DeleteAnimatedTile(tile);
00298     return;
00299   }
00300 
00301   if (!LiftHasDestination(tile)) {
00302     uint i;
00303 
00304     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
00305      * This is due to the fact that the first floor is, in the graphics,
00306      *  the height of 2 'normal' floors.
00307      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
00308     do {
00309       i = RandomRange(7);
00310     } while (i == 1 || i * 6 == GetLiftPosition(tile));
00311 
00312     SetLiftDestination(tile, i);
00313   }
00314 
00315   int pos = GetLiftPosition(tile);
00316   int dest = GetLiftDestination(tile) * 6;
00317   pos += (pos < dest) ? 1 : -1;
00318   SetLiftPosition(tile, pos);
00319 
00320   if (pos == dest) {
00321     HaltLift(tile);
00322     DeleteAnimatedTile(tile);
00323   }
00324 
00325   MarkTileDirtyByTile(tile);
00326 }
00327 
00334 static bool IsCloseToTown(TileIndex tile, uint dist)
00335 {
00336   const Town *t;
00337 
00338   FOR_ALL_TOWNS(t) {
00339     if (DistanceManhattan(tile, t->xy) < dist) return true;
00340   }
00341   return false;
00342 }
00343 
00348 void Town::UpdateVirtCoord()
00349 {
00350   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00351   SetDParam(0, this->index);
00352   SetDParam(1, this->population);
00353   this->sign.UpdatePosition(pt.x, pt.y - 24,
00354     _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00355 
00356   SetWindowDirty(WC_TOWN_VIEW, this->index);
00357 }
00358 
00360 void UpdateAllTownVirtCoords()
00361 {
00362   Town *t;
00363 
00364   FOR_ALL_TOWNS(t) {
00365     t->UpdateVirtCoord();
00366   }
00367 }
00368 
00374 static void ChangePopulation(Town *t, int mod)
00375 {
00376   t->population += mod;
00377   SetWindowDirty(WC_TOWN_VIEW, t->index);
00378   t->UpdateVirtCoord();
00379 
00380   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00381 }
00382 
00388 uint32 GetWorldPopulation()
00389 {
00390   uint32 pop = 0;
00391   const Town *t;
00392 
00393   FOR_ALL_TOWNS(t) pop += t->population;
00394   return pop;
00395 }
00396 
00401 static void MakeSingleHouseBigger(TileIndex tile)
00402 {
00403   assert(IsTileType(tile, MP_HOUSE));
00404 
00405   /* progress in construction stages */
00406   IncHouseConstructionTick(tile);
00407   if (GetHouseConstructionTick(tile) != 0) return;
00408 
00409   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00410 
00411   /* Check and/or  */
00412   if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00413     uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00414     if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00415   }
00416 
00417   if (IsHouseCompleted(tile)) {
00418     /* Now that construction is complete, we can add the population of the
00419      * building to the town. */
00420     ChangePopulation(Town::GetByTile(tile), hs->population);
00421     ResetHouseAge(tile);
00422   }
00423   MarkTileDirtyByTile(tile);
00424 }
00425 
00429 static void MakeTownHouseBigger(TileIndex tile)
00430 {
00431   uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00432   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00433   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00434   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00435   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00436 }
00437 
00444 static void TileLoop_Town(TileIndex tile)
00445 {
00446   HouseID house_id = GetHouseType(tile);
00447 
00448   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
00449    * doesn't exist any more, so don't continue here. */
00450   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00451 
00452   if (!IsHouseCompleted(tile)) {
00453     /* Construction is not completed. See if we can go further in construction*/
00454     MakeTownHouseBigger(tile);
00455     return;
00456   }
00457 
00458   const HouseSpec *hs = HouseSpec::Get(house_id);
00459 
00460   /* If the lift has a destination, it is already an animated tile. */
00461   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00462       house_id < NEW_HOUSE_OFFSET &&
00463       !LiftHasDestination(tile) &&
00464       Chance16(1, 2)) {
00465     AddAnimatedTile(tile);
00466   }
00467 
00468   Town *t = Town::GetByTile(tile);
00469   uint32 r = Random();
00470 
00471   StationFinder stations(TileArea(tile, 1, 1));
00472 
00473   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00474     for (uint i = 0; i < 256; i++) {
00475       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00476 
00477       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00478 
00479       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00480       if (cargo == CT_INVALID) continue;
00481 
00482       uint amt = GB(callback, 0, 8);
00483       if (amt == 0) continue;
00484 
00485       uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00486 
00487       const CargoSpec *cs = CargoSpec::Get(cargo);
00488       switch (cs->town_effect) {
00489         case TE_PASSENGERS:
00490           t->new_max_pass += amt;
00491           t->new_act_pass += moved;
00492           break;
00493 
00494         case TE_MAIL:
00495           t->new_max_mail += amt;
00496           t->new_act_mail += moved;
00497           break;
00498 
00499         default:
00500           break;
00501       }
00502     }
00503   } else {
00504     if (GB(r, 0, 8) < hs->population) {
00505       uint amt = GB(r, 0, 8) / 8 + 1;
00506 
00507       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00508       t->new_max_pass += amt;
00509       t->new_act_pass += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00510     }
00511 
00512     if (GB(r, 8, 8) < hs->mail_generation) {
00513       uint amt = GB(r, 8, 8) / 8 + 1;
00514 
00515       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00516       t->new_max_mail += amt;
00517       t->new_act_mail += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00518     }
00519   }
00520 
00521   _current_company = OWNER_TOWN;
00522 
00523   if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00524       HasBit(t->flags, TOWN_IS_FUNDED) &&
00525       CanDeleteHouse(tile) &&
00526       GetHouseAge(tile) >= hs->minimum_life &&
00527       --t->time_until_rebuild == 0) {
00528     t->time_until_rebuild = GB(r, 16, 8) + 192;
00529 
00530     ClearTownHouse(t, tile);
00531 
00532     /* Rebuild with another house? */
00533     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00534   }
00535 
00536   _current_company = OWNER_NONE;
00537 }
00538 
00539 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00540 {
00541   if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00542   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00543 
00544   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00545 
00546   CommandCost cost(EXPENSES_CONSTRUCTION);
00547   cost.AddCost(hs->GetRemovalCost());
00548 
00549   int rating = hs->remove_rating_decrease;
00550   _cleared_town_rating += rating;
00551   Town *t = _cleared_town = Town::GetByTile(tile);
00552 
00553   if (Company::IsValidID(_current_company)) {
00554     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00555       SetDParam(0, t->index);
00556       return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00557     }
00558   }
00559 
00560   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00561   if (flags & DC_EXEC) {
00562     ClearTownHouse(t, tile);
00563   }
00564 
00565   return cost;
00566 }
00567 
00568 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00569 {
00570   HouseID house_id = GetHouseType(tile);
00571   const HouseSpec *hs = HouseSpec::Get(house_id);
00572   Town *t = Town::GetByTile(tile);
00573 
00574   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00575     for (uint i = 0; i < 256; i++) {
00576       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00577 
00578       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00579 
00580       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00581 
00582       if (cargo == CT_INVALID) continue;
00583       produced[cargo]++;
00584     }
00585   } else {
00586     if (hs->population > 0) {
00587       produced[CT_PASSENGERS]++;
00588     }
00589     if (hs->mail_generation > 0) {
00590       produced[CT_MAIL]++;
00591     }
00592   }
00593 }
00594 
00595 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00596 {
00597   if (cargo == CT_INVALID || amount == 0) return;
00598   acceptance[cargo] += amount;
00599   SetBit(*always_accepted, cargo);
00600 }
00601 
00602 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00603 {
00604   const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00605   CargoID accepts[3];
00606 
00607   /* Set the initial accepted cargo types */
00608   for (uint8 i = 0; i < lengthof(accepts); i++) {
00609     accepts[i] = hs->accepts_cargo[i];
00610   }
00611 
00612   /* Check for custom accepted cargo types */
00613   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00614     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00615     if (callback != CALLBACK_FAILED) {
00616       /* Replace accepted cargo types with translated values from callback */
00617       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grffile);
00618       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grffile);
00619       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00620     }
00621   }
00622 
00623   /* Check for custom cargo acceptance */
00624   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00625     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00626     if (callback != CALLBACK_FAILED) {
00627       AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00628       AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00629       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00630         /* The 'S' bit indicates food instead of goods */
00631         AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00632       } else {
00633         AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00634       }
00635       return;
00636     }
00637   }
00638 
00639   /* No custom acceptance, so fill in with the default values */
00640   for (uint8 i = 0; i < lengthof(accepts); i++) {
00641     AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00642   }
00643 }
00644 
00645 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00646 {
00647   const HouseID house = GetHouseType(tile);
00648   const HouseSpec *hs = HouseSpec::Get(house);
00649   bool house_completed = IsHouseCompleted(tile);
00650 
00651   td->str = hs->building_name;
00652 
00653   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00654   if (callback_res != CALLBACK_FAILED) {
00655     StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00656     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00657       td->str = new_name;
00658     }
00659   }
00660 
00661   if (!house_completed) {
00662     SetDParamX(td->dparam, 0, td->str);
00663     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00664   }
00665 
00666   if (hs->grffile != NULL) {
00667     const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00668     td->grf = gc->name;
00669   }
00670 
00671   td->owner[0] = OWNER_TOWN;
00672 }
00673 
00674 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00675 {
00676   /* not used */
00677   return 0;
00678 }
00679 
00680 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00681 {
00682   /* not used */
00683 }
00684 
00685 static bool GrowTown(Town *t);
00686 
00687 static void TownTickHandler(Town *t)
00688 {
00689   if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00690     int i = t->grow_counter - 1;
00691     if (i < 0) {
00692       if (GrowTown(t)) {
00693         i = t->growth_rate;
00694       } else {
00695         i = 0;
00696       }
00697     }
00698     t->grow_counter = i;
00699   }
00700 
00701   UpdateTownRadius(t);
00702 }
00703 
00704 void OnTick_Town()
00705 {
00706   if (_game_mode == GM_EDITOR) return;
00707 
00708   Town *t;
00709   FOR_ALL_TOWNS(t) {
00710     /* Run town tick at regular intervals, but not all at once. */
00711     if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00712       TownTickHandler(t);
00713     }
00714   }
00715 }
00716 
00725 static RoadBits GetTownRoadBits(TileIndex tile)
00726 {
00727   if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00728 
00729   return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00730 }
00731 
00742 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00743 {
00744   if (!IsValidTile(tile)) return false;
00745 
00746   /* Lookup table for the used diff values */
00747   const TileIndexDiff tid_lt[3] = {
00748     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00749     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00750     TileOffsByDiagDir(ReverseDiagDir(dir)),
00751   };
00752 
00753   dist_multi = (dist_multi + 1) * 4;
00754   for (uint pos = 4; pos < dist_multi; pos++) {
00755     /* Go (pos / 4) tiles to the left or the right */
00756     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00757 
00758     /* Use the current tile as origin, or go one tile backwards */
00759     if (pos & 2) cur += tid_lt[2];
00760 
00761     /* Test for roadbit parallel to dir and facing towards the middle axis */
00762     if (IsValidTile(tile + cur) &&
00763       GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00764   }
00765   return false;
00766 }
00767 
00776 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00777 {
00778   if (DistanceFromEdge(tile) == 0) return false;
00779 
00780   Slope cur_slope, desired_slope;
00781 
00782   for (;;) {
00783     /* Check if there already is a road at this point? */
00784     if (GetTownRoadBits(tile) == ROAD_NONE) {
00785       /* No, try if we are able to build a road piece there.
00786        * If that fails clear the land, and if that fails exit.
00787        * This is to make sure that we can build a road here later. */
00788       if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00789           DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00790         return false;
00791     }
00792 
00793     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00794     bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00795     if (cur_slope == SLOPE_FLAT) return ret;
00796 
00797     /* If the tile is not a slope in the right direction, then
00798      * maybe terraform some. */
00799     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00800     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00801       if (Chance16(1, 8)) {
00802         CommandCost res = CMD_ERROR;
00803         if (!_generating_world && Chance16(1, 10)) {
00804           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00805           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00806               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00807         }
00808         if (res.Failed() && Chance16(1, 3)) {
00809           /* We can consider building on the slope, though. */
00810           return ret;
00811         }
00812       }
00813       return false;
00814     }
00815     return ret;
00816   }
00817 }
00818 
00819 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00820 {
00821   assert(tile < MapSize());
00822 
00823   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00824   if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00825   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00826   return true;
00827 }
00828 
00829 static void LevelTownLand(TileIndex tile)
00830 {
00831   assert(tile < MapSize());
00832 
00833   /* Don't terraform if land is plain or if there's a house there. */
00834   if (IsTileType(tile, MP_HOUSE)) return;
00835   Slope tileh = GetTileSlope(tile, NULL);
00836   if (tileh == SLOPE_FLAT) return;
00837 
00838   /* First try up, then down */
00839   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00840     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00841   }
00842 }
00843 
00853 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00854 {
00855   /* align the grid to the downtown */
00856   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00857   RoadBits rcmd = ROAD_NONE;
00858 
00859   switch (t->layout) {
00860     default: NOT_REACHED();
00861 
00862     case TL_2X2_GRID:
00863       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00864       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00865       break;
00866 
00867     case TL_3X3_GRID:
00868       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00869       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00870       break;
00871   }
00872 
00873   /* Optimise only X-junctions */
00874   if (rcmd != ROAD_ALL) return rcmd;
00875 
00876   RoadBits rb_template;
00877 
00878   switch (GetTileSlope(tile, NULL)) {
00879     default:       rb_template = ROAD_ALL; break;
00880     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00881     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00882     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00883     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00884     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00885     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00886     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00887     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00888     case SLOPE_STEEP_W:
00889     case SLOPE_STEEP_S:
00890     case SLOPE_STEEP_E:
00891     case SLOPE_STEEP_N:
00892       rb_template = ROAD_NONE;
00893       break;
00894   }
00895 
00896   /* Stop if the template is compatible to the growth dir */
00897   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00898   /* If not generate a straight road in the direction of the growth */
00899   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00900 }
00901 
00912 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00913 {
00914   /* We can't look further than that. */
00915   if (DistanceFromEdge(tile) == 0) return false;
00916 
00917   uint counter = 0; // counts the house neighbor tiles
00918 
00919   /* Check the tiles E,N,W and S of the current tile for houses */
00920   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00921     /* Count both void and house tiles for checking whether there
00922      * are enough houses in the area. This to make it likely that
00923      * houses get build up to the edge of the map. */
00924     switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00925       case MP_HOUSE:
00926       case MP_VOID:
00927         counter++;
00928         break;
00929 
00930       default:
00931         break;
00932     }
00933 
00934     /* If there are enough neighbors stop here */
00935     if (counter >= 3) {
00936       if (BuildTownHouse(t, tile)) {
00937         _grow_town_result = GROWTH_SUCCEED;
00938         return true;
00939       }
00940       return false;
00941     }
00942   }
00943   return false;
00944 }
00945 
00954 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00955 {
00956   if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
00957     _grow_town_result = GROWTH_SUCCEED;
00958     return true;
00959   }
00960   return false;
00961 }
00962 
00973 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00974 {
00975   assert(bridge_dir < DIAGDIR_END);
00976 
00977   const Slope slope = GetTileSlope(tile, NULL);
00978   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
00979 
00980   /* Make sure the direction is compatible with the slope.
00981    * Well we check if the slope has an up bit set in the
00982    * reverse direction. */
00983   if (slope & InclinedSlope(bridge_dir)) return false;
00984 
00985   /* Assure that the bridge is connectable to the start side */
00986   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00987 
00988   /* We are in the right direction */
00989   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
00990   TileIndex bridge_tile = tile; // Used to store the other waterside
00991 
00992   const int delta = TileOffsByDiagDir(bridge_dir);
00993   do {
00994     if (bridge_length++ >= 11) {
00995       /* Max 11 tile long bridges */
00996       return false;
00997     }
00998     bridge_tile += delta;
00999   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
01000 
01001   /* no water tiles in between? */
01002   if (bridge_length == 1) return false;
01003 
01004   for (uint8 times = 0; times <= 22; times++) {
01005     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01006 
01007     /* Can we actually build the bridge? */
01008     if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE).Succeeded()) {
01009       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
01010       _grow_town_result = GROWTH_SUCCEED;
01011       return true;
01012     }
01013   }
01014   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01015   return false;
01016 }
01017 
01035 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01036 {
01037   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01038   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01039 
01040   assert(tile < MapSize());
01041 
01042   if (cur_rb == ROAD_NONE) {
01043     /* Tile has no road. First reset the status counter
01044      * to say that this is the last iteration. */
01045     _grow_town_result = GROWTH_SEARCH_STOPPED;
01046 
01047     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01048 
01049     /* Remove hills etc */
01050     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01051 
01052     /* Is a road allowed here? */
01053     switch (t1->layout) {
01054       default: NOT_REACHED();
01055 
01056       case TL_3X3_GRID:
01057       case TL_2X2_GRID:
01058         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01059         if (rcmd == ROAD_NONE) return;
01060         break;
01061 
01062       case TL_BETTER_ROADS:
01063       case TL_ORIGINAL:
01064         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01065 
01066         DiagDirection source_dir = ReverseDiagDir(target_dir);
01067 
01068         if (Chance16(1, 4)) {
01069           /* Randomize a new target dir */
01070           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01071         }
01072 
01073         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01074           /* A road is not allowed to continue the randomized road,
01075            *  return if the road we're trying to build is curved. */
01076           if (target_dir != ReverseDiagDir(source_dir)) return;
01077 
01078           /* Return if neither side of the new road is a house */
01079           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01080               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01081             return;
01082           }
01083 
01084           /* That means that the road is only allowed if there is a house
01085            *  at any side of the new road. */
01086         }
01087 
01088         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01089         break;
01090     }
01091 
01092   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01093     /* Continue building on a partial road.
01094      * Should be allways OK, so we only generate
01095      * the fitting RoadBits */
01096     _grow_town_result = GROWTH_SEARCH_STOPPED;
01097 
01098     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01099 
01100     switch (t1->layout) {
01101       default: NOT_REACHED();
01102 
01103       case TL_3X3_GRID:
01104       case TL_2X2_GRID:
01105         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01106         break;
01107 
01108       case TL_BETTER_ROADS:
01109       case TL_ORIGINAL:
01110         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01111         break;
01112     }
01113   } else {
01114     bool allow_house = true; // Value which decides if we want to construct a house
01115 
01116     /* Reached a tunnel/bridge? Then continue at the other side of it. */
01117     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01118       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01119         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01120       }
01121       return;
01122     }
01123 
01124     /* Possibly extend the road in a direction.
01125      * Randomize a direction and if it has a road, bail out. */
01126     target_dir = RandomDiagDir();
01127     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01128 
01129     /* This is the tile we will reach if we extend to this direction. */
01130     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01131 
01132     /* Don't walk into water. */
01133     if (IsWaterTile(house_tile)) return;
01134 
01135     if (!IsValidTile(house_tile)) return;
01136 
01137     if (_settings_game.economy.allow_town_roads || _generating_world) {
01138       switch (t1->layout) {
01139         default: NOT_REACHED();
01140 
01141         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01142           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01143           /* FALL THROUGH */
01144 
01145         case TL_2X2_GRID:
01146           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01147           allow_house = (rcmd == ROAD_NONE);
01148           break;
01149 
01150         case TL_BETTER_ROADS: // Use original afterwards!
01151           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01152           /* FALL THROUGH */
01153 
01154         case TL_ORIGINAL:
01155           /* Allow a house at the edge. 60% chance or
01156            * always ok if no road allowed. */
01157           rcmd = DiagDirToRoadBits(target_dir);
01158           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01159           break;
01160       }
01161     }
01162 
01163     if (allow_house) {
01164       /* Build a house, but not if there already is a house there. */
01165       if (!IsTileType(house_tile, MP_HOUSE)) {
01166         /* Level the land if possible */
01167         if (Chance16(1, 6)) LevelTownLand(house_tile);
01168 
01169         /* And build a house.
01170          * Set result to -1 if we managed to build it. */
01171         if (BuildTownHouse(t1, house_tile)) {
01172           _grow_town_result = GROWTH_SUCCEED;
01173         }
01174       }
01175       return;
01176     }
01177 
01178     _grow_town_result = GROWTH_SEARCH_STOPPED;
01179   }
01180 
01181   /* Return if a water tile */
01182   if (IsWaterTile(tile)) return;
01183 
01184   /* Make the roads look nicer */
01185   rcmd = CleanUpRoadBits(tile, rcmd);
01186   if (rcmd == ROAD_NONE) return;
01187 
01188   /* Only use the target direction for bridges to ensure they're connected.
01189    * The target_dir is as computed previously according to town layout, so
01190    * it will match it perfectly. */
01191   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01192 
01193   GrowTownWithRoad(t1, tile, rcmd);
01194 }
01195 
01201 static int GrowTownAtRoad(Town *t, TileIndex tile)
01202 {
01203   /* Special case.
01204    * @see GrowTownInTile Check the else if
01205    */
01206   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01207 
01208   assert(tile < MapSize());
01209 
01210   /* Number of times to search.
01211    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01212    * them a little handicap. */
01213   switch (t->layout) {
01214     case TL_BETTER_ROADS:
01215       _grow_town_result = 10 + t->num_houses * 2 / 9;
01216       break;
01217 
01218     case TL_3X3_GRID:
01219     case TL_2X2_GRID:
01220       _grow_town_result = 10 + t->num_houses * 1 / 9;
01221       break;
01222 
01223     default:
01224       _grow_town_result = 10 + t->num_houses * 4 / 9;
01225       break;
01226   }
01227 
01228   do {
01229     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01230 
01231     /* Try to grow the town from this point */
01232     GrowTownInTile(&tile, cur_rb, target_dir, t);
01233 
01234     /* Exclude the source position from the bitmask
01235      * and return if no more road blocks available */
01236     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01237     if (cur_rb == ROAD_NONE)
01238       return _grow_town_result;
01239 
01240     /* Select a random bit from the blockmask, walk a step
01241      * and continue the search from there. */
01242     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01243     tile = TileAddByDiagDir(tile, target_dir);
01244 
01245     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01246       /* Don't allow building over roads of other cities */
01247       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01248         _grow_town_result = GROWTH_SUCCEED;
01249       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01250         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01251          * owner :) (happy happy happy road now) */
01252         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01253         SetTownIndex(tile, t->index);
01254       }
01255     }
01256 
01257     /* Max number of times is checked. */
01258   } while (--_grow_town_result >= 0);
01259 
01260   return (_grow_town_result == -2);
01261 }
01262 
01270 static RoadBits GenRandomRoadBits()
01271 {
01272   uint32 r = Random();
01273   uint a = GB(r, 0, 2);
01274   uint b = GB(r, 8, 2);
01275   if (a == b) b ^= 2;
01276   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01277 }
01278 
01283 static bool GrowTown(Town *t)
01284 {
01285   static const TileIndexDiffC _town_coord_mod[] = {
01286     {-1,  0},
01287     { 1,  1},
01288     { 1, -1},
01289     {-1, -1},
01290     {-1,  0},
01291     { 0,  2},
01292     { 2,  0},
01293     { 0, -2},
01294     {-1, -1},
01295     {-2,  2},
01296     { 2,  2},
01297     { 2, -2},
01298     { 0,  0}
01299   };
01300 
01301   /* Current "company" is a town */
01302   CompanyID old_company = _current_company;
01303   _current_company = OWNER_TOWN;
01304 
01305   TileIndex tile = t->xy; // The tile we are working with ATM
01306 
01307   /* Find a road that we can base the construction on. */
01308   const TileIndexDiffC *ptr;
01309   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01310     if (GetTownRoadBits(tile) != ROAD_NONE) {
01311       int r = GrowTownAtRoad(t, tile);
01312       _current_company = old_company;
01313       return r != 0;
01314     }
01315     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01316   }
01317 
01318   /* No road available, try to build a random road block by
01319    * clearing some land and then building a road there. */
01320   if (_settings_game.economy.allow_town_roads || _generating_world) {
01321     tile = t->xy;
01322     for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01323       /* Only work with plain land that not already has a house */
01324       if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01325         if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01326           DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01327           _current_company = old_company;
01328           return true;
01329         }
01330       }
01331       tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01332     }
01333   }
01334 
01335   _current_company = old_company;
01336   return false;
01337 }
01338 
01339 void UpdateTownRadius(Town *t)
01340 {
01341   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01342     {  4,  0,  0,  0,  0}, // 0
01343     { 16,  0,  0,  0,  0},
01344     { 25,  0,  0,  0,  0},
01345     { 36,  0,  0,  0,  0},
01346     { 49,  0,  4,  0,  0},
01347     { 64,  0,  4,  0,  0}, // 20
01348     { 64,  0,  9,  0,  1},
01349     { 64,  0,  9,  0,  4},
01350     { 64,  0, 16,  0,  4},
01351     { 81,  0, 16,  0,  4},
01352     { 81,  0, 16,  0,  4}, // 40
01353     { 81,  0, 25,  0,  9},
01354     { 81, 36, 25,  0,  9},
01355     { 81, 36, 25, 16,  9},
01356     { 81, 49,  0, 25,  9},
01357     { 81, 64,  0, 25,  9}, // 60
01358     { 81, 64,  0, 36,  9},
01359     { 81, 64,  0, 36, 16},
01360     {100, 81,  0, 49, 16},
01361     {100, 81,  0, 49, 25},
01362     {121, 81,  0, 49, 25}, // 80
01363     {121, 81,  0, 49, 25},
01364     {121, 81,  0, 49, 36}, // 88
01365   };
01366 
01367   if (t->num_houses < 92) {
01368     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01369   } else {
01370     int mass = t->num_houses / 8;
01371     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01372      * The offsets are to make sure the radii do not decrease in size when going from the table
01373      * to the calculated value.*/
01374     t->squared_town_zone_radius[0] = mass * 15 - 40;
01375     t->squared_town_zone_radius[1] = mass * 9 - 15;
01376     t->squared_town_zone_radius[2] = 0;
01377     t->squared_town_zone_radius[3] = mass * 5 - 5;
01378     t->squared_town_zone_radius[4] = mass * 3 + 5;
01379   }
01380 }
01381 
01382 void UpdateTownMaxPass(Town *t)
01383 {
01384   t->max_pass = t->population >> 3;
01385   t->max_mail = t->population >> 4;
01386 }
01387 
01399 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01400 {
01401   t->xy = tile;
01402   t->num_houses = 0;
01403   t->time_until_rebuild = 10;
01404   UpdateTownRadius(t);
01405   t->flags = 0;
01406   t->population = 0;
01407   t->grow_counter = 0;
01408   t->growth_rate = 250;
01409   t->new_max_pass = 0;
01410   t->new_max_mail = 0;
01411   t->new_act_pass = 0;
01412   t->new_act_mail = 0;
01413   t->max_pass = 0;
01414   t->max_mail = 0;
01415   t->act_pass = 0;
01416   t->act_mail = 0;
01417 
01418   t->pct_pass_transported = 0;
01419   t->pct_mail_transported = 0;
01420   t->fund_buildings_months = 0;
01421   t->new_act_food = 0;
01422   t->new_act_water = 0;
01423   t->act_food = 0;
01424   t->act_water = 0;
01425 
01426   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01427 
01428   t->have_ratings = 0;
01429   t->exclusivity = INVALID_COMPANY;
01430   t->exclusive_counter = 0;
01431   t->statues = 0;
01432 
01433   extern int _nb_orig_names;
01434   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01435     /* Original town name */
01436     t->townnamegrfid = 0;
01437     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01438   } else {
01439     /* Newgrf town name */
01440     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01441     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01442   }
01443   t->townnameparts = townnameparts;
01444 
01445   t->UpdateVirtCoord();
01446   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01447 
01448   t->InitializeLayout(layout);
01449 
01450   t->larger_town = city;
01451 
01452   int x = (int)size * 16 + 3;
01453   if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01454   /* Don't create huge cities when founding town in-game */
01455   if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01456 
01457   t->num_houses += x;
01458   UpdateTownRadius(t);
01459 
01460   int i = x * 4;
01461   do {
01462     GrowTown(t);
01463   } while (--i);
01464 
01465   t->num_houses -= x;
01466   UpdateTownRadius(t);
01467   UpdateTownMaxPass(t);
01468   UpdateAirportsNoise();
01469 }
01470 
01476 static CommandCost TownCanBePlacedHere(TileIndex tile)
01477 {
01478   /* Check if too close to the edge of map */
01479   if (DistanceFromEdge(tile) < 12) {
01480     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01481   }
01482 
01483   /* Check distance to all other towns. */
01484   if (IsCloseToTown(tile, 20)) {
01485     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01486   }
01487 
01488   /* Can only build on clear flat areas, possibly with trees. */
01489   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01490     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01491   }
01492 
01493   return CommandCost(EXPENSES_OTHER);
01494 }
01495 
01501 static bool IsUniqueTownName(const char *name)
01502 {
01503   const Town *t;
01504 
01505   FOR_ALL_TOWNS(t) {
01506     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01507   }
01508 
01509   return true;
01510 }
01511 
01524 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01525 {
01526   TownSize size = Extract<TownSize, 0, 2>(p1);
01527   bool city = HasBit(p1, 2);
01528   TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01529   TownNameParams par(_settings_game.game_creation.town_name);
01530   bool random = HasBit(p1, 6);
01531   uint32 townnameparts = p2;
01532 
01533   if (size > TSZ_RANDOM) return CMD_ERROR;
01534   if (layout > TL_RANDOM) return CMD_ERROR;
01535 
01536   /* Some things are allowed only in the scenario editor */
01537   if (_game_mode != GM_EDITOR) {
01538     if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01539     if (size == TSZ_LARGE) return CMD_ERROR;
01540     if (random) return CMD_ERROR;
01541     if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01542       return CMD_ERROR;
01543     }
01544   }
01545 
01546   if (StrEmpty(text)) {
01547     /* If supplied name is empty, townnameparts has to generate unique automatic name */
01548     if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01549   } else {
01550     /* If name is not empty, it has to be unique custom name */
01551     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
01552     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01553   }
01554 
01555   /* Allocate town struct */
01556   if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01557 
01558   if (!random) {
01559     CommandCost ret = TownCanBePlacedHere(tile);
01560     if (ret.Failed()) return ret;
01561   }
01562 
01563   static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01564   /* multidimensional arrays have to have defined length of non-first dimension */
01565   assert_compile(lengthof(price_mult[0]) == 4);
01566 
01567   CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01568   byte mult = price_mult[city][size];
01569 
01570   cost.MultiplyCost(mult);
01571 
01572   /* Create the town */
01573   if (flags & DC_EXEC) {
01574     if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01575       _additional_cash_required = cost.GetCost();
01576       return CommandCost(EXPENSES_OTHER);
01577     }
01578 
01579     _generating_world = true;
01580     UpdateNearestTownForRoadTiles(true);
01581     Town *t;
01582     if (random) {
01583       t = CreateRandomTown(20, townnameparts, size, city, layout);
01584       if (t == NULL) {
01585         cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01586       } else {
01587         _new_town_id = t->index;
01588       }
01589     } else {
01590       t = new Town(tile);
01591       DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01592     }
01593     UpdateNearestTownForRoadTiles(false);
01594     _generating_world = false;
01595 
01596     if (t != NULL && !StrEmpty(text)) {
01597       t->name = strdup(text);
01598       t->UpdateVirtCoord();
01599     }
01600 
01601     if (_game_mode != GM_EDITOR) {
01602       /* 't' can't be NULL since 'random' is false outside scenedit */
01603       assert(!random);
01604       char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
01605       SetDParam(0, _current_company);
01606       GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01607 
01608       char *cn = strdup(company_name);
01609       SetDParamStr(0, cn);
01610       SetDParam(1, t->index);
01611 
01612       AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01613     }
01614   }
01615   return cost;
01616 }
01617 
01627 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01628 {
01629   switch (layout) {
01630     case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01631     case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01632     default:          return tile;
01633   }
01634 }
01635 
01645 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01646 {
01647   switch (layout) {
01648     case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01649     case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01650     default:          return true;
01651   }
01652 }
01653 
01657 struct SpotData {
01658   TileIndex tile; 
01659   uint max_dist;  
01660   TownLayout layout; 
01661 };
01662 
01679 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01680 {
01681   SpotData *sp = (SpotData*)user_data;
01682   uint dist = GetClosestWaterDistance(tile, true);
01683 
01684   if (IsTileType(tile, MP_CLEAR) &&
01685       GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01686       IsTileAlignedToGrid(tile, sp->layout) &&
01687       dist > sp->max_dist) {
01688     sp->tile = tile;
01689     sp->max_dist = dist;
01690   }
01691 
01692   return false;
01693 }
01694 
01701 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01702 {
01703   return IsTileType(tile, MP_CLEAR);
01704 }
01705 
01718 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01719 {
01720   SpotData sp = { INVALID_TILE, 0, layout };
01721 
01722   TileIndex coast = tile;
01723   if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01724     CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01725     return sp.tile;
01726   }
01727 
01728   /* if we get here just give up */
01729   return INVALID_TILE;
01730 }
01731 
01732 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01733 {
01734   if (!Town::CanAllocateItem()) return NULL;
01735 
01736   do {
01737     /* Generate a tile index not too close from the edge */
01738     TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01739 
01740     /* if we tried to place the town on water, slide it over onto
01741      * the nearest likely-looking spot */
01742     if (IsTileType(tile, MP_WATER)) {
01743       tile = FindNearestGoodCoastalTownSpot(tile, layout);
01744       if (tile == INVALID_TILE) continue;
01745     }
01746 
01747     /* Make sure town can be placed here */
01748     if (TownCanBePlacedHere(tile).Failed()) continue;
01749 
01750     /* Allocate a town struct */
01751     Town *t = new Town(tile);
01752 
01753     DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01754 
01755     /* if the population is still 0 at the point, then the
01756      * placement is so bad it couldn't grow at all */
01757     if (t->population > 0) return t;
01758     delete t;
01759   } while (--attempts != 0);
01760 
01761   return NULL;
01762 }
01763 
01764 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01765 
01772 bool GenerateTowns(TownLayout layout)
01773 {
01774   uint num = 0;
01775   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01776   uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01777   uint32 townnameparts;
01778 
01779   SetGeneratingWorldProgress(GWP_TOWN, n);
01780 
01781   /* First attempt will be made at creating the suggested number of towns.
01782    * Note that this is really a suggested value, not a required one.
01783    * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
01784   do {
01785     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01786     IncreaseGeneratingWorldProgress(GWP_TOWN);
01787     /* Get a unique name for the town. */
01788     if (!GenerateTownName(&townnameparts)) continue;
01789     /* try 20 times to create a random-sized town for the first loop. */
01790     if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) num++; // If creation was successful, raise a flag.
01791   } while (--n);
01792 
01793   if (num != 0) return true;
01794 
01795   /* If num is still zero at this point, it means that not a single town has been created.
01796    * So give it a last try, but now more aggressive */
01797   if (GenerateTownName(&townnameparts) &&
01798       CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01799     return true;
01800   }
01801 
01802   /* If there are no towns at all and we are generating new game, bail out */
01803   if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01804     extern StringID _switch_mode_errorstr;
01805     _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01806   }
01807 
01808   return false;  // we are still without a town? we failed, simply
01809 }
01810 
01811 
01817 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01818 {
01819   uint dist = DistanceSquare(tile, t->xy);
01820 
01821   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01822 
01823   HouseZonesBits smallest = HZB_TOWN_EDGE;
01824   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01825     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01826   }
01827 
01828   return smallest;
01829 }
01830 
01841 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01842 {
01843   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01844 
01845   assert(cc.Succeeded());
01846 
01847   IncreaseBuildingCount(t, type);
01848   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01849   if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01850 
01851   MarkTileDirtyByTile(tile);
01852 }
01853 
01854 
01865 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01866 {
01867   BuildingFlags size = HouseSpec::Get(type)->building_flags;
01868 
01869   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01870   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01871   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01872   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01873 }
01874 
01875 
01884 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01885 {
01886   /* cannot build on these slopes... */
01887   Slope slope = GetTileSlope(tile, NULL);
01888   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01889 
01890   /* building under a bridge? */
01891   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01892 
01893   /* do not try to build over house owned by another town */
01894   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01895 
01896   /* can we clear the land? */
01897   return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01898 }
01899 
01900 
01910 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01911 {
01912   if (!CanBuildHouseHere(tile, town, noslope)) return false;
01913 
01914   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
01915   if (GetTileMaxZ(tile) != z) return false;
01916 
01917   return true;
01918 }
01919 
01920 
01930 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01931 {
01932   /* we need to check this tile too because we can be at different tile now */
01933   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01934 
01935   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01936     tile += TileOffsByDiagDir(d);
01937     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01938   }
01939 
01940   return true;
01941 }
01942 
01943 
01951 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01952 {
01953   /* Allow towns everywhere when we don't build roads */
01954   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01955 
01956   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01957 
01958   switch (t->layout) {
01959     case TL_2X2_GRID:
01960       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01961       break;
01962 
01963     case TL_3X3_GRID:
01964       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01965       break;
01966 
01967     default:
01968       break;
01969   }
01970 
01971   return true;
01972 }
01973 
01974 
01982 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01983 {
01984   /* Allow towns everywhere when we don't build roads */
01985   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01986 
01987   /* Compute relative position of tile. (Positive offsets are towards north) */
01988   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01989 
01990   switch (t->layout) {
01991     case TL_2X2_GRID:
01992       grid_pos.x %= 3;
01993       grid_pos.y %= 3;
01994       if ((grid_pos.x != 2 && grid_pos.x != -1) ||
01995         (grid_pos.y != 2 && grid_pos.y != -1)) return false;
01996       break;
01997 
01998     case TL_3X3_GRID:
01999       if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02000       break;
02001 
02002     default:
02003       break;
02004   }
02005 
02006   return true;
02007 }
02008 
02009 
02019 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02020 {
02021   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
02022 
02023   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02024   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02025 
02026   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02027   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02028     *tile = tile2;
02029     return true;
02030   }
02031 
02032   return false;
02033 }
02034 
02035 
02044 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02045 {
02046   TileIndex tile2 = *tile;
02047 
02048   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
02049     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02050       *tile = tile2;
02051       return true;
02052     }
02053     if (d == DIAGDIR_END) break;
02054     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
02055   }
02056 
02057   return false;
02058 }
02059 
02060 
02067 static bool BuildTownHouse(Town *t, TileIndex tile)
02068 {
02069   /* forbidden building here by town layout */
02070   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02071 
02072   /* no house allowed at all, bail out */
02073   if (!CanBuildHouseHere(tile, t->index, false)) return false;
02074 
02075   uint z;
02076   Slope slope = GetTileSlope(tile, &z);
02077 
02078   /* Get the town zone type of the current tile, as well as the climate.
02079    * This will allow to easily compare with the specs of the new house to build */
02080   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02081 
02082   /* Above snow? */
02083   int land = _settings_game.game_creation.landscape;
02084   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02085 
02086   uint bitmask = (1 << rad) + (1 << (land + 12));
02087 
02088   /* bits 0-4 are used
02089    * bits 11-15 are used
02090    * bits 5-10 are not used. */
02091   HouseID houses[HOUSE_MAX];
02092   uint num = 0;
02093   uint probs[HOUSE_MAX];
02094   uint probability_max = 0;
02095 
02096   /* Generate a list of all possible houses that can be built. */
02097   for (uint i = 0; i < HOUSE_MAX; i++) {
02098     const HouseSpec *hs = HouseSpec::Get(i);
02099 
02100     /* Verify that the candidate house spec matches the current tile status */
02101     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->override != INVALID_HOUSE_ID) continue;
02102 
02103     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
02104     if (hs->class_id != HOUSE_NO_CLASS) {
02105       /* id_count is always <= class_count, so it doesn't need to be checked */
02106       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02107     } else {
02108       /* If the house has no class, check id_count instead */
02109       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02110     }
02111 
02112     /* Without NewHouses, all houses have probability '1' */
02113     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02114     probability_max += cur_prob;
02115     probs[num] = cur_prob;
02116     houses[num++] = (HouseID)i;
02117   }
02118 
02119   uint maxz = GetTileMaxZ(tile);
02120 
02121   while (probability_max > 0) {
02122     uint r = RandomRange(probability_max);
02123     uint i;
02124     for (i = 0; i < num; i++) {
02125       if (probs[i] > r) break;
02126       r -= probs[i];
02127     }
02128 
02129     HouseID house = houses[i];
02130     probability_max -= probs[i];
02131 
02132     /* remove tested house from the set */
02133     num--;
02134     houses[i] = houses[num];
02135     probs[i] = probs[num];
02136 
02137     const HouseSpec *hs = HouseSpec::Get(house);
02138 
02139     if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02140         _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02141       continue;
02142     }
02143 
02144     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02145 
02146     /* Special houses that there can be only one of. */
02147     uint oneof = 0;
02148 
02149     if (hs->building_flags & BUILDING_IS_CHURCH) {
02150       SetBit(oneof, TOWN_HAS_CHURCH);
02151     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02152       SetBit(oneof, TOWN_HAS_STADIUM);
02153     }
02154 
02155     if (t->flags & oneof) continue;
02156 
02157     /* Make sure there is no slope? */
02158     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02159     if (noslope && slope != SLOPE_FLAT) continue;
02160 
02161     if (hs->building_flags & TILE_SIZE_2x2) {
02162       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02163     } else if (hs->building_flags & TILE_SIZE_2x1) {
02164       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02165     } else if (hs->building_flags & TILE_SIZE_1x2) {
02166       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02167     } else {
02168       /* 1x1 house checks are already done */
02169     }
02170 
02171     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02172       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true);
02173       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02174     }
02175 
02176     /* build the house */
02177     t->num_houses++;
02178 
02179     /* Special houses that there can be only one of. */
02180     t->flags |= oneof;
02181 
02182     byte construction_counter = 0;
02183     byte construction_stage = 0;
02184 
02185     if (_generating_world || _game_mode == GM_EDITOR) {
02186       uint32 r = Random();
02187 
02188       construction_stage = TOWN_HOUSE_COMPLETED;
02189       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02190 
02191       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02192         ChangePopulation(t, hs->population);
02193       } else {
02194         construction_counter = GB(r, 2, 2);
02195       }
02196     }
02197 
02198     MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02199 
02200     return true;
02201   }
02202 
02203   return false;
02204 }
02205 
02212 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02213 {
02214   assert(IsTileType(tile, MP_HOUSE));
02215   DecreaseBuildingCount(t, house);
02216   DoClearSquare(tile);
02217   DeleteAnimatedTile(tile);
02218 }
02219 
02227 TileIndexDiff GetHouseNorthPart(HouseID &house)
02228 {
02229   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02230     if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02231       house--;
02232       return TileDiffXY(-1, 0);
02233     } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02234       house--;
02235       return TileDiffXY(0, -1);
02236     } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02237       house -= 2;
02238       return TileDiffXY(-1, 0);
02239     } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02240       house -= 3;
02241       return TileDiffXY(-1, -1);
02242     }
02243   }
02244   return 0;
02245 }
02246 
02247 void ClearTownHouse(Town *t, TileIndex tile)
02248 {
02249   assert(IsTileType(tile, MP_HOUSE));
02250 
02251   HouseID house = GetHouseType(tile);
02252 
02253   /* need to align the tile to point to the upper left corner of the house */
02254   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02255 
02256   const HouseSpec *hs = HouseSpec::Get(house);
02257 
02258   /* Remove population from the town if the house is finished. */
02259   if (IsHouseCompleted(tile)) {
02260     ChangePopulation(t, -hs->population);
02261   }
02262 
02263   t->num_houses--;
02264 
02265   /* Clear flags for houses that only may exist once/town. */
02266   if (hs->building_flags & BUILDING_IS_CHURCH) {
02267     ClrBit(t->flags, TOWN_HAS_CHURCH);
02268   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02269     ClrBit(t->flags, TOWN_HAS_STADIUM);
02270   }
02271 
02272   /* Do the actual clearing of tiles */
02273   uint eflags = hs->building_flags;
02274   DoClearTownHouseHelper(tile, t, house);
02275   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02276   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02277   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02278 }
02279 
02288 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02289 {
02290   Town *t = Town::GetIfValid(p1);
02291   if (t == NULL) return CMD_ERROR;
02292 
02293   bool reset = StrEmpty(text);
02294 
02295   if (!reset) {
02296     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02297     if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02298   }
02299 
02300   if (flags & DC_EXEC) {
02301     free(t->name);
02302     t->name = reset ? NULL : strdup(text);
02303 
02304     t->UpdateVirtCoord();
02305     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02306     UpdateAllStationVirtCoords();
02307   }
02308   return CommandCost();
02309 }
02310 
02312 void ExpandTown(Town *t)
02313 {
02314   /* Warn the users if towns are not allowed to build roads,
02315    * but do this only onces per openttd run. */
02316   static bool warned_no_roads = false;
02317   if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02318     ShowErrorMessage(STR_ERROR_TOWN_EXPAND_WARN_NO_ROADS, INVALID_STRING_ID, 0, 0);
02319     warned_no_roads = true;
02320   }
02321 
02322   /* The more houses, the faster we grow */
02323   uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02324   t->num_houses += amount;
02325   UpdateTownRadius(t);
02326 
02327   uint n = amount * 10;
02328   do GrowTown(t); while (--n);
02329 
02330   t->num_houses -= amount;
02331   UpdateTownRadius(t);
02332 
02333   UpdateTownMaxPass(t);
02334 }
02335 
02339 const byte _town_action_costs[TACT_COUNT] = {
02340   2, 4, 9, 35, 48, 53, 117, 175
02341 };
02342 
02343 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02344 {
02345   if (flags & DC_EXEC) {
02346     ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02347   }
02348   return CommandCost();
02349 }
02350 
02351 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02352 {
02353   if (flags & DC_EXEC) {
02354     ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02355   }
02356   return CommandCost();
02357 }
02358 
02359 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02360 {
02361   if (flags & DC_EXEC) {
02362     ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02363   }
02364   return CommandCost();
02365 }
02366 
02367 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02368 {
02369   if (flags & DC_EXEC) {
02370     t->road_build_months = 6;
02371 
02372     char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02373     SetDParam(0, _current_company);
02374     GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02375 
02376     char *cn = strdup(company_name);
02377     SetDParam(0, t->index);
02378     SetDParamStr(1, cn);
02379 
02380     AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02381   }
02382   return CommandCost();
02383 }
02384 
02391 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02392 {
02393   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02394   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02395   /* Don't build statues under bridges. */
02396   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02397 
02398   if (!IsTileType(tile, MP_HOUSE) &&
02399       !IsTileType(tile, MP_CLEAR) &&
02400       !IsTileType(tile, MP_TREES)) {
02401     return false;
02402   }
02403 
02404   CompanyID old = _current_company;
02405   _current_company = OWNER_NONE;
02406   CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02407   _current_company = old;
02408 
02409   if (r.Failed()) return false;
02410 
02411   return true;
02412 }
02413 
02421 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02422 {
02423   TileIndex tile = t->xy;
02424   if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02425     if (flags & DC_EXEC) {
02426       CompanyID old = _current_company;
02427       _current_company = OWNER_NONE;
02428       DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02429       _current_company = old;
02430       MakeStatue(tile, _current_company, t->index);
02431       SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
02432       MarkTileDirtyByTile(tile);
02433     }
02434     return CommandCost();
02435   }
02436   return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02437 }
02438 
02439 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02440 {
02441   if (flags & DC_EXEC) {
02442     /* Build next tick */
02443     t->grow_counter = 1;
02444     /* If we were not already growing */
02445     SetBit(t->flags, TOWN_IS_FUNDED);
02446     /* And grow for 3 months */
02447     t->fund_buildings_months = 3;
02448   }
02449   return CommandCost();
02450 }
02451 
02452 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02453 {
02454   /* Check if it's allowed to by the rights */
02455   if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02456 
02457   if (flags & DC_EXEC) {
02458     t->exclusive_counter = 12;
02459     t->exclusivity = _current_company;
02460 
02461     ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02462   }
02463   return CommandCost();
02464 }
02465 
02466 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02467 {
02468   if (flags & DC_EXEC) {
02469     if (Chance16(1, 14)) {
02470       /* set as unwanted for 6 months */
02471       t->unwanted[_current_company] = 6;
02472 
02473       /* set all close by station ratings to 0 */
02474       Station *st;
02475       FOR_ALL_STATIONS(st) {
02476         if (st->town == t && st->owner == _current_company) {
02477           for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02478         }
02479       }
02480 
02481       /* only show errormessage to the executing player. All errors are handled command.c
02482        * but this is special, because it can only 'fail' on a DC_EXEC */
02483       if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, 0, 0);
02484 
02485       /* decrease by a lot!
02486        * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02487        * be independent of any cheat settings
02488        */
02489       if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02490         t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02491         SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02492       }
02493     } else {
02494       ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02495     }
02496   }
02497   return CommandCost();
02498 }
02499 
02500 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02501 static TownActionProc * const _town_action_proc[] = {
02502   TownActionAdvertiseSmall,
02503   TownActionAdvertiseMedium,
02504   TownActionAdvertiseLarge,
02505   TownActionRoadRebuild,
02506   TownActionBuildStatue,
02507   TownActionFundBuildings,
02508   TownActionBuyRights,
02509   TownActionBribe
02510 };
02511 
02518 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02519 {
02520   int num = 0;
02521   TownActions buttons = TACT_NONE;
02522 
02523   /* Spectators and unwanted have no options */
02524   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02525 
02526     /* Things worth more than this are not shown */
02527     Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02528 
02529     /* Check the action bits for validity and
02530      * if they are valid add them */
02531     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02532       const TownActions cur = (TownActions)(1 << i);
02533 
02534       /* Is the company not able to bribe ? */
02535       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02536         continue;
02537 
02538       /* Is the company not able to buy exclusive rights ? */
02539       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02540         continue;
02541 
02542       /* Is the company not able to build a statue ? */
02543       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02544         continue;
02545 
02546       if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02547         buttons |= cur;
02548         num++;
02549       }
02550     }
02551   }
02552 
02553   if (nump != NULL) *nump = num;
02554   return buttons;
02555 }
02556 
02567 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02568 {
02569   Town *t = Town::GetIfValid(p1);
02570   if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02571 
02572   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02573 
02574   CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02575 
02576   CommandCost ret = _town_action_proc[p2](t, flags);
02577   if (ret.Failed()) return ret;
02578 
02579   if (flags & DC_EXEC) {
02580     SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02581   }
02582 
02583   return cost;
02584 }
02585 
02586 static void UpdateTownGrowRate(Town *t)
02587 {
02588   /* Increase company ratings if they're low */
02589   const Company *c;
02590   FOR_ALL_COMPANIES(c) {
02591     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02592       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02593     }
02594   }
02595 
02596   int n = 0;
02597 
02598   const Station *st;
02599   FOR_ALL_STATIONS(st) {
02600     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02601       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02602         n++;
02603         if (Company::IsValidID(st->owner)) {
02604           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02605           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02606         }
02607       } else {
02608         if (Company::IsValidID(st->owner)) {
02609           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02610           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02611         }
02612       }
02613     }
02614   }
02615 
02616   /* clamp all ratings to valid values */
02617   for (uint i = 0; i < MAX_COMPANIES; i++) {
02618     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02619   }
02620 
02621   SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02622 
02623   ClrBit(t->flags, TOWN_IS_FUNDED);
02624   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02625 
02628   static const uint16 _grow_count_values[2][6] = {
02629     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02630     { 320, 420, 300, 220, 160, 100 }  // Normal values
02631   };
02632 
02633   uint16 m;
02634 
02635   if (t->fund_buildings_months != 0) {
02636     m = _grow_count_values[0][min(n, 5)];
02637     t->fund_buildings_months--;
02638   } else {
02639     m = _grow_count_values[1][min(n, 5)];
02640     if (n == 0 && !Chance16(1, 12)) return;
02641   }
02642 
02643   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02644     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02645       return;
02646   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02647     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02648       return;
02649   }
02650 
02651   /* Use the normal growth rate values if new buildings have been funded in
02652    * this town and the growth rate is set to none. */
02653   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02654 
02655   m >>= growth_multiplier;
02656   if (t->larger_town) m /= 2;
02657 
02658   t->growth_rate = m / (t->num_houses / 50 + 1);
02659   if (m <= t->grow_counter)
02660     t->grow_counter = m;
02661 
02662   SetBit(t->flags, TOWN_IS_FUNDED);
02663 }
02664 
02665 static void UpdateTownAmounts(Town *t)
02666 {
02667   /* Using +1 here to prevent overflow and division by zero */
02668   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02669 
02670   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02671   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02672   t->act_food = t->new_act_food; t->new_act_food = 0;
02673   t->act_water = t->new_act_water; t->new_act_water = 0;
02674 
02675   /* Using +1 here to prevent overflow and division by zero */
02676   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02677   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02678   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02679 
02680   SetWindowDirty(WC_TOWN_VIEW, t->index);
02681 }
02682 
02683 static void UpdateTownUnwanted(Town *t)
02684 {
02685   const Company *c;
02686 
02687   FOR_ALL_COMPANIES(c) {
02688     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02689   }
02690 }
02691 
02697 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02698 {
02699   if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02700 
02701   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02702   if (t == NULL) return true;
02703 
02704   if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02705 
02706   _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02707   SetDParam(0, t->index);
02708 
02709   return false;
02710 }
02711 
02712 
02713 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02714 {
02715   Town *t;
02716   uint best = threshold;
02717   Town *best_town = NULL;
02718 
02719   FOR_ALL_TOWNS(t) {
02720     uint dist = DistanceManhattan(tile, t->xy);
02721     if (dist < best) {
02722       best = dist;
02723       best_town = t;
02724     }
02725   }
02726 
02727   return best_town;
02728 }
02729 
02730 
02731 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02732 {
02733   switch (GetTileType(tile)) {
02734     case MP_ROAD:
02735       if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02736 
02737       if (!HasTownOwnedRoad(tile)) {
02738         TownID tid = GetTownIndex(tile);
02739 
02740         if (tid == (TownID)INVALID_TOWN) {
02741           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
02742           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02743           assert(Town::GetNumItems() == 0);
02744           return NULL;
02745         }
02746 
02747         assert(Town::IsValidID(tid));
02748         Town *town = Town::Get(tid);
02749 
02750         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02751 
02752         return town;
02753       }
02754       /* FALL THROUGH */
02755 
02756     case MP_HOUSE:
02757       return Town::GetByTile(tile);
02758 
02759     default:
02760       return CalcClosestTownFromTile(tile, threshold);
02761   }
02762 }
02763 
02764 static bool _town_rating_test = false;
02765 static SmallMap<const Town *, int, 4> _town_test_ratings;
02766 
02767 void SetTownRatingTestMode(bool mode)
02768 {
02769   static int ref_count = 0;
02770   if (mode) {
02771     if (ref_count == 0) {
02772       _town_test_ratings.Clear();
02773     }
02774     ref_count++;
02775   } else {
02776     assert(ref_count > 0);
02777     ref_count--;
02778   }
02779   _town_rating_test = !(ref_count == 0);
02780 }
02781 
02782 static int GetRating(const Town *t)
02783 {
02784   if (_town_rating_test) {
02785     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02786     if (it != _town_test_ratings.End()) {
02787       return it->second;
02788     }
02789   }
02790   return t->ratings[_current_company];
02791 }
02792 
02800 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02801 {
02802   /* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
02803   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02804       !Company::IsValidID(_current_company) ||
02805       (_cheats.magic_bulldozer.value && add < 0)) {
02806     return;
02807   }
02808 
02809   int rating = GetRating(t);
02810   if (add < 0) {
02811     if (rating > max) {
02812       rating += add;
02813       if (rating < max) rating = max;
02814     }
02815   } else {
02816     if (rating < max) {
02817       rating += add;
02818       if (rating > max) rating = max;
02819     }
02820   }
02821   if (_town_rating_test) {
02822     _town_test_ratings[t] = rating;
02823   } else {
02824     SetBit(t->have_ratings, _current_company);
02825     t->ratings[_current_company] = rating;
02826     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02827   }
02828 }
02829 
02830 bool CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
02831 {
02832   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
02833   if (t == NULL || !Company::IsValidID(_current_company) ||
02834       _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
02835     return true;
02836   }
02837 
02838   /* minimum rating needed to be allowed to remove stuff */
02839   static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
02840     /*                  ROAD_REMOVE,                    TUNNELBRIDGE_REMOVE */
02841     { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
02842     {    RATING_ROAD_NEEDED_NEUTRAL,    RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
02843     {    RATING_ROAD_NEEDED_HOSTILE,    RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
02844   };
02845 
02846   /* check if you're allowed to remove the road/bridge/tunnel
02847    * owned by a town no removal if rating is lower than ... depends now on
02848    * difficulty setting. Minimum town rating selected by difficulty level
02849    */
02850   int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
02851 
02852   if (GetRating(t) < needed) {
02853     SetDParam(0, t->index);
02854     _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02855     return false;
02856   }
02857 
02858   return true;
02859 }
02860 
02861 void TownsMonthlyLoop()
02862 {
02863   Town *t;
02864 
02865   FOR_ALL_TOWNS(t) {
02866     if (t->road_build_months != 0) t->road_build_months--;
02867 
02868     if (t->exclusive_counter != 0)
02869       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02870 
02871     UpdateTownGrowRate(t);
02872     UpdateTownAmounts(t);
02873     UpdateTownUnwanted(t);
02874   }
02875 }
02876 
02877 void TownsYearlyLoop()
02878 {
02879   /* Increment house ages */
02880   for (TileIndex t = 0; t < MapSize(); t++) {
02881     if (!IsTileType(t, MP_HOUSE)) continue;
02882     IncrementHouseAge(t);
02883   }
02884 }
02885 
02886 void InitializeTowns()
02887 {
02888   _town_pool.CleanPool();
02889 }
02890 
02891 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02892 {
02893   if (AutoslopeEnabled()) {
02894     HouseID house = GetHouseType(tile);
02895     GetHouseNorthPart(house); // modifies house to the ID of the north tile
02896     const HouseSpec *hs = HouseSpec::Get(house);
02897 
02898     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
02899     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02900         (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
02901       bool allow_terraform = true;
02902 
02903       /* Call the autosloping callback per tile, not for the whole building at once. */
02904       house = GetHouseType(tile);
02905       hs = HouseSpec::Get(house);
02906       if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
02907         /* If the callback fails, allow autoslope. */
02908         uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
02909         if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
02910       }
02911 
02912       if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
02913     }
02914   }
02915 
02916   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02917 }
02918 
02920 extern const TileTypeProcs _tile_type_town_procs = {
02921   DrawTile_Town,           // draw_tile_proc
02922   GetSlopeZ_Town,          // get_slope_z_proc
02923   ClearTile_Town,          // clear_tile_proc
02924   AddAcceptedCargo_Town,   // add_accepted_cargo_proc
02925   GetTileDesc_Town,        // get_tile_desc_proc
02926   GetTileTrackStatus_Town, // get_tile_track_status_proc
02927   NULL,                    // click_tile_proc
02928   AnimateTile_Town,        // animate_tile_proc
02929   TileLoop_Town,           // tile_loop_clear
02930   ChangeTileOwner_Town,    // change_tile_owner_clear
02931   AddProducedCargo_Town,   // add_produced_cargo_proc
02932   NULL,                    // vehicle_enter_tile_proc
02933   GetFoundation_Town,      // get_foundation_proc
02934   TerraformTile_Town,      // terraform_tile_proc
02935 };
02936 
02937 
02938 HouseSpec _house_specs[HOUSE_MAX];
02939 
02940 void ResetHouses()
02941 {
02942   memset(&_house_specs, 0, sizeof(_house_specs));
02943   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02944 
02945   /* Reset any overrides that have been set. */
02946   _house_mngr.ResetOverride();
02947 }

Generated on Sun Nov 14 14:41:58 2010 for OpenTTD by  doxygen 1.6.1