# town_cmd.cpp

Go to the documentation of this file.

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