town_cmd.cpp

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

Generated on Sun Jan 9 16:02:03 2011 for OpenTTD by  doxygen 1.6.1