# town_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: town_cmd.cpp 15729 2009-03-15 21:16:07Z rubidium $ */
    00002
    00005 #include "stdafx.h"
    00006 #include "openttd.h"
    00007 #include "road_type.h"
    00008 #include "road_internal.h" /* Cleaning up road bits */
    00009 #include "road_cmd.h"
    00010 #include "landscape.h"
    00011 #include "town_map.h"
    00012 #include "viewport_func.h"
    00013 #include "command_func.h"
    00014 #include "industry.h"
    00015 #include "station_base.h"
    00016 #include "company_base.h"
    00017 #include "news_func.h"
    00018 #include "gui.h"
    00019 #include "unmovable_map.h"
    00020 #include "water_map.h"
    00021 #include "variables.h"
    00022 #include "slope_func.h"
    00023 #include "genworld.h"
    00024 #include "newgrf.h"
    00025 #include "newgrf_house.h"
    00026 #include "newgrf_commons.h"
    00027 #include "newgrf_townname.h"
    00028 #include "newgrf_text.h"
    00029 #include "autoslope.h"
    00030 #include "waypoint.h"
    00031 #include "transparency.h"
    00032 #include "tunnelbridge_map.h"
    00033 #include "strings_func.h"
    00034 #include "window_func.h"
    00035 #include "string_func.h"
    00036 #include "newgrf_cargo.h"
    00037 #include "oldpool_func.h"
    00038 #include "economy_func.h"
    00039 #include "station_func.h"
    00040 #include "cheat_type.h"
    00041 #include "functions.h"
    00042 #include "animated_tile_func.h"
    00043 #include "date_func.h"
    00044 #include "core/smallmap_type.hpp"
    00045
    00046 #include "table/strings.h"
    00047 #include "table/town_land.h"
    00048
    00049 uint _total_towns;
    00050 HouseSpec _house_specs[HOUSE_MAX];
    00051
    00052 Town *_cleared_town;
    00053 int _cleared_town_rating;
    00054
    00055 uint32 _cur_town_ctr;
    00056 uint32 _cur_town_iter;
    00057
    00058 /* Initialize the town-pool */
    00059 DEFINE_OLD_POOL_GENERIC(Town, Town)
    00060
    00061 Town::Town(TileIndex tile)
    00062 {
    00063   if (tile != INVALID_TILE) _total_towns++;
    00064   this->xy = tile;
    00065 }
    00066
    00067 Town::~Town()
    00068 {
    00069   free(this->name);
    00070
    00071   if (CleaningPool()) return;
    00072
    00073   Industry *i;
    00074
    00075   /* Delete town authority window
    00076    * and remove from list of sorted towns */
    00077   DeleteWindowById(WC_TOWN_VIEW, this->index);
    00078   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
    00079   _total_towns--;
    00080
    00081   /* Delete all industries belonging to the town */
    00082   FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
    00083
    00084   /* Go through all tiles and delete those belonging to the town */
    00085   for (TileIndex tile = 0; tile < MapSize(); ++tile) {
    00086     switch (GetTileType(tile)) {
    00087       case MP_HOUSE:
    00088         if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
    00089         break;
    00090
    00091       case MP_ROAD:
    00092         /* Cached nearest town is updated later (after this town has been deleted) */
    00093         if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
    00094           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
    00095         }
    00096         break;
    00097
    00098       case MP_TUNNELBRIDGE:
    00099         if (IsTileOwner(tile, OWNER_TOWN) &&
    00100             ClosestTownFromTile(tile, UINT_MAX) == this)
    00101           DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
    00102         break;
    00103
    00104       default:
    00105         break;
    00106     }
    00107   }
    00108
    00109   DeleteSubsidyWithTown(this->index);
    00110
    00111   MarkWholeScreenDirty();
    00112
    00113   this->xy = INVALID_TILE;
    00114
    00115   UpdateNearestTownForRoadTiles(false);
    00116 }
    00117
    00121 void Town::InitializeLayout(TownLayout layout)
    00122 {
    00123   if (layout != TL_RANDOM) {
    00124     this->layout = layout;
    00125     return;
    00126   }
    00127
    00128   this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
    00129 }
    00130
    00131 Money HouseSpec::GetRemovalCost() const
    00132 {
    00133   return (_price.remove_house * this->removal_cost) >> 8;
    00134 }
    00135
    00136 // Local
    00137 static int _grow_town_result;
    00138
    00139 /* Describe the possible states */
    00140 enum TownGrowthResult {
    00141   GROWTH_SUCCEED         = -1,
    00142   GROWTH_SEARCH_STOPPED  =  0
    00143 //  GROWTH_SEARCH_RUNNING >=  1
    00144 };
    00145
    00146 static bool BuildTownHouse(Town *t, TileIndex tile);
    00147
    00148 static void TownDrawHouseLift(const TileInfo *ti)
    00149 {
    00150   AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
    00151 }
    00152
    00153 typedef void TownDrawTileProc(const TileInfo *ti);
    00154 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
    00155   TownDrawHouseLift
    00156 };
    00157
    00163 static inline DiagDirection RandomDiagDir()
    00164 {
    00165   return (DiagDirection)(3 & Random());
    00166 }
    00167
    00173 static void DrawTile_Town(TileInfo *ti)
    00174 {
    00175   HouseID house_id = GetHouseType(ti->tile);
    00176
    00177   if (house_id >= NEW_HOUSE_OFFSET) {
    00178     /* Houses don't necessarily need new graphics. If they don't have a
    00179      * spritegroup associated with them, then the sprite for the substitute
    00180      * house id is drawn instead. */
    00181     if (GetHouseSpecs(house_id)->spritegroup != NULL) {
    00182       DrawNewHouseTile(ti, house_id);
    00183       return;
    00184     } else {
    00185       house_id = GetHouseSpecs(house_id)->substitute_id;
    00186     }
    00187   }
    00188
    00189   /* Retrieve pointer to the draw town tile struct */
    00190   const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
    00191
    00192   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
    00193
    00194   DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
    00195
    00196   /* If houses are invisible, do not draw the upper part */
    00197   if (IsInvisibilitySet(TO_HOUSES)) return;
    00198
    00199   /* Add a house on top of the ground? */
    00200   SpriteID image = dcts->building.sprite;
    00201   if (image != 0) {
    00202     AddSortableSpriteToDraw(image, dcts->building.pal,
    00203       ti->x + dcts->subtile_x,
    00204       ti->y + dcts->subtile_y,
    00205       dcts->width,
    00206       dcts->height,
    00207       dcts->dz,
    00208       ti->z,
    00209       IsTransparencySet(TO_HOUSES)
    00210     );
    00211
    00212     if (IsTransparencySet(TO_HOUSES)) return;
    00213   }
    00214
    00215   {
    00216     int proc = dcts->draw_proc - 1;
    00217
    00218     if (proc >= 0) _town_draw_tile_procs[proc](ti);
    00219   }
    00220 }
    00221
    00222 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
    00223 {
    00224   return GetTileMaxZ(tile);
    00225 }
    00226
    00228 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
    00229 {
    00230   return FlatteningFoundation(tileh);
    00231 }
    00232
    00239 static void AnimateTile_Town(TileIndex tile)
    00240 {
    00241   if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
    00242     AnimateNewHouseTile(tile);
    00243     return;
    00244   }
    00245
    00246   if (_tick_counter & 3) return;
    00247
    00248   /* If the house is not one with a lift anymore, then stop this animating.
    00249    * Not exactly sure when this happens, but probably when a house changes.
    00250    * Before this was just a return...so it'd leak animated tiles..
    00251    * That bug seems to have been here since day 1?? */
    00252   if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
    00253     DeleteAnimatedTile(tile);
    00254     return;
    00255   }
    00256
    00257   if (!LiftHasDestination(tile)) {
    00258     uint i;
    00259
    00260     /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
    00261      * This is due to the fact that the first floor is, in the graphics,
    00262      *  the height of 2 'normal' floors.
    00263      * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
    00264     do {
    00265       i = RandomRange(7);
    00266     } while (i == 1 || i * 6 == GetLiftPosition(tile));
    00267
    00268     SetLiftDestination(tile, i);
    00269   }
    00270
    00271   int pos = GetLiftPosition(tile);
    00272   int dest = GetLiftDestination(tile) * 6;
    00273   pos += (pos < dest) ? 1 : -1;
    00274   SetLiftPosition(tile, pos);
    00275
    00276   if (pos == dest) {
    00277     HaltLift(tile);
    00278     DeleteAnimatedTile(tile);
    00279   }
    00280
    00281   MarkTileDirtyByTile(tile);
    00282 }
    00283
    00290 static bool IsCloseToTown(TileIndex tile, uint dist)
    00291 {
    00292   const Town *t;
    00293
    00294   FOR_ALL_TOWNS(t) {
    00295     if (DistanceManhattan(tile, t->xy) < dist) return true;
    00296   }
    00297   return false;
    00298 }
    00299
    00308 static void MarkTownSignDirty(Town *t)
    00309 {
    00310   MarkAllViewportsDirty(
    00311     t->sign.left - 6,
    00312     t->sign.top - 3,
    00313     t->sign.left + t->sign.width_1 * 4 + 12,
    00314     t->sign.top + 45
    00315   );
    00316 }
    00317
    00323 void UpdateTownVirtCoord(Town *t)
    00324 {
    00325   MarkTownSignDirty(t);
    00326   Point pt = RemapCoords2(TileX(t->xy) * TILE_SIZE, TileY(t->xy) * TILE_SIZE);
    00327   SetDParam(0, t->index);
    00328   SetDParam(1, t->population);
    00329   UpdateViewportSignPos(&t->sign, pt.x, pt.y - 24,
    00330     _settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL);
    00331   MarkTownSignDirty(t);
    00332 }
    00333
    00335 void UpdateAllTownVirtCoords()
    00336 {
    00337   Town *t;
    00338   FOR_ALL_TOWNS(t) {
    00339     UpdateTownVirtCoord(t);
    00340   }
    00341 }
    00342
    00348 static void ChangePopulation(Town *t, int mod)
    00349 {
    00350   t->population += mod;
    00351   InvalidateWindow(WC_TOWN_VIEW, t->index);
    00352   UpdateTownVirtCoord(t);
    00353
    00354   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
    00355 }
    00356
    00362 uint32 GetWorldPopulation()
    00363 {
    00364   uint32 pop = 0;
    00365   const Town *t;
    00366
    00367   FOR_ALL_TOWNS(t) pop += t->population;
    00368   return pop;
    00369 }
    00370
    00375 static void MakeSingleHouseBigger(TileIndex tile)
    00376 {
    00377   assert(IsTileType(tile, MP_HOUSE));
    00378
    00379   /* means it is completed, get out. */
    00380   if (LiftHasDestination(tile)) return;
    00381
    00382   /* progress in construction stages */
    00383   IncHouseConstructionTick(tile);
    00384   if (GetHouseConstructionTick(tile) != 0) return;
    00385
    00386   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
    00387
    00388   /* Check and/or  */
    00389   if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
    00390     uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
    00391     if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
    00392   }
    00393
    00394   if (IsHouseCompleted(tile)) {
    00395     /* Now that construction is complete, we can add the population of the
    00396      * building to the town. */
    00397     ChangePopulation(GetTownByTile(tile), hs->population);
    00398     ResetHouseAge(tile);
    00399   }
    00400   MarkTileDirtyByTile(tile);
    00401 }
    00402
    00406 static void MakeTownHouseBigger(TileIndex tile)
    00407 {
    00408   uint flags = GetHouseSpecs(GetHouseType(tile))->building_flags;
    00409   if (flags & BUILDING_HAS_1_TILE)  MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
    00410   if (flags & BUILDING_2_TILES_Y)   MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
    00411   if (flags & BUILDING_2_TILES_X)   MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
    00412   if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
    00413 }
    00414
    00421 static void TileLoop_Town(TileIndex tile)
    00422 {
    00423   HouseID house_id = GetHouseType(tile);
    00424
    00425   /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
    00426    * doesn't exist any more, so don't continue here. */
    00427   if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
    00428
    00429   if (!IsHouseCompleted(tile)) {
    00430     /* Construction is not completed. See if we can go further in construction*/
    00431     MakeTownHouseBigger(tile);
    00432     return;
    00433   }
    00434
    00435   const HouseSpec *hs = GetHouseSpecs(house_id);
    00436
    00437   /* If the lift has a destination, it is already an animated tile. */
    00438   if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
    00439       house_id < NEW_HOUSE_OFFSET &&
    00440       !LiftHasDestination(tile) &&
    00441       Chance16(1, 2)) {
    00442     AddAnimatedTile(tile);
    00443   }
    00444
    00445   Town *t = GetTownByTile(tile);
    00446   uint32 r = Random();
    00447
    00448   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
    00449     for (uint i = 0; i < 256; i++) {
    00450       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
    00451
    00452       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
    00453
    00454       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
    00455       if (cargo == CT_INVALID) continue;
    00456
    00457       uint amt = GB(callback, 0, 8);
    00458       uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
    00459
    00460       const CargoSpec *cs = GetCargo(cargo);
    00461       switch (cs->town_effect) {
    00462         case TE_PASSENGERS:
    00463           t->new_max_pass += amt;
    00464           t->new_act_pass += moved;
    00465           break;
    00466
    00467         case TE_MAIL:
    00468           t->new_max_mail += amt;
    00469           t->new_act_mail += moved;
    00470           break;
    00471
    00472         default:
    00473           break;
    00474       }
    00475     }
    00476   } else {
    00477     if (GB(r, 0, 8) < hs->population) {
    00478       uint amt = GB(r, 0, 8) / 8 + 1;
    00479
    00480       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
    00481       t->new_max_pass += amt;
    00482       t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
    00483     }
    00484
    00485     if (GB(r, 8, 8) < hs->mail_generation) {
    00486       uint amt = GB(r, 8, 8) / 8 + 1;
    00487
    00488       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
    00489       t->new_max_mail += amt;
    00490       t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
    00491     }
    00492   }
    00493
    00494   _current_company = OWNER_TOWN;
    00495
    00496   if (hs->building_flags & BUILDING_HAS_1_TILE &&
    00497       HasBit(t->flags12, TOWN_IS_FUNDED) &&
    00498       CanDeleteHouse(tile) &&
    00499       GetHouseAge(tile) >= hs->minimum_life &&
    00500       --t->time_until_rebuild == 0) {
    00501     t->time_until_rebuild = GB(r, 16, 8) + 192;
    00502
    00503     ClearTownHouse(t, tile);
    00504
    00505     /* Rebuild with another house? */
    00506     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
    00507   }
    00508
    00509   _current_company = OWNER_NONE;
    00510 }
    00511
    00516 static bool ClickTile_Town(TileIndex tile)
    00517 {
    00518   /* not used */
    00519   return false;
    00520 }
    00521
    00522 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
    00523 {
    00524   if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
    00525   if (!CanDeleteHouse(tile)) return CMD_ERROR;
    00526
    00527   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
    00528
    00529   CommandCost cost(EXPENSES_CONSTRUCTION);
    00530   cost.AddCost(hs->GetRemovalCost());
    00531
    00532   int rating = hs->remove_rating_decrease;
    00533   _cleared_town_rating += rating;
    00534   Town *t = _cleared_town = GetTownByTile(tile);
    00535
    00536   if (IsValidCompanyID(_current_company)) {
    00537     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
    00538       SetDParam(0, t->index);
    00539       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
    00540     }
    00541   }
    00542
    00543   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
    00544   if (flags & DC_EXEC) {
    00545     ClearTownHouse(t, tile);
    00546   }
    00547
    00548   return cost;
    00549 }
    00550
    00551 static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
    00552 {
    00553   HouseID house_id = GetHouseType(tile);
    00554   const HouseSpec *hs = GetHouseSpecs(house_id);
    00555   Town *t = GetTownByTile(tile);
    00556
    00557   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
    00558     for (uint i = 0; i < 256; i++) {
    00559       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
    00560
    00561       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
    00562
    00563       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
    00564
    00565       if (cargo == CT_INVALID) continue;
    00566       *(b++) = cargo;
    00567     }
    00568   } else {
    00569     if (hs->population > 0) {
    00570       *(b++) = CT_PASSENGERS;
    00571     }
    00572     if (hs->mail_generation > 0) {
    00573       *(b++) = CT_MAIL;
    00574     }
    00575   }
    00576 }
    00577
    00578 static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
    00579 {
    00580   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
    00581   CargoID accepts[3];
    00582
    00583   /* Set the initial accepted cargo types */
    00584   for (uint8 i = 0; i < lengthof(accepts); i++) {
    00585     accepts[i] = hs->accepts_cargo[i];
    00586   }
    00587
    00588   /* Check for custom accepted cargo types */
    00589   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
    00590     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
    00591     if (callback != CALLBACK_FAILED) {
    00592       /* Replace accepted cargo types with translated values from callback */
    00593       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grffile);
    00594       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grffile);
    00595       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
    00596     }
    00597   }
    00598
    00599   /* Check for custom cargo acceptance */
    00600   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
    00601     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
    00602     if (callback != CALLBACK_FAILED) {
    00603       if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
    00604       if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
    00605       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
    00606         /* The 'S' bit indicates food instead of goods */
    00607         ac[CT_FOOD] = GB(callback, 8, 4);
    00608       } else {
    00609         if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
    00610       }
    00611       return;
    00612     }
    00613   }
    00614
    00615   /* No custom acceptance, so fill in with the default values */
    00616   for (uint8 i = 0; i < lengthof(accepts); i++) {
    00617     if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
    00618   }
    00619 }
    00620
    00621 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
    00622 {
    00623   const HouseID house = GetHouseType(tile);
    00624   const HouseSpec *hs = GetHouseSpecs(house);
    00625   bool house_completed = IsHouseCompleted(tile);
    00626
    00627   td->str = hs->building_name;
    00628
    00629   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
    00630   if (callback_res != CALLBACK_FAILED) {
    00631     StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
    00632     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
    00633       td->str = new_name;
    00634     }
    00635   }
    00636
    00637   if (!house_completed) {
    00638     SetDParamX(td->dparam, 0, td->str);
    00639     td->str = STR_2058_UNDER_CONSTRUCTION;
    00640   }
    00641
    00642   if (hs->grffile != NULL) {
    00643     const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
    00644     td->grf = gc->name;
    00645   }
    00646
    00647   td->owner[0] = OWNER_TOWN;
    00648 }
    00649
    00650 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    00651 {
    00652   /* not used */
    00653   return 0;
    00654 }
    00655
    00656 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
    00657 {
    00658   /* not used */
    00659 }
    00660
    00661 static bool GrowTown(Town *t);
    00662
    00663 static void TownTickHandler(Town *t)
    00664 {
    00665   if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
    00666     int i = t->grow_counter - 1;
    00667     if (i < 0) {
    00668       if (GrowTown(t)) {
    00669         i = t->growth_rate;
    00670       } else {
    00671         i = 0;
    00672       }
    00673     }
    00674     t->grow_counter = i;
    00675   }
    00676
    00677   UpdateTownRadius(t);
    00678 }
    00679
    00680 void OnTick_Town()
    00681 {
    00682   if (_game_mode == GM_EDITOR) return;
    00683
    00684   /* Make sure each town's tickhandler invocation frequency is about the
    00685    * same - TOWN_GROWTH_FREQUENCY - independent on the number of towns. */
    00686   for (_cur_town_iter += GetMaxTownIndex() + 1;
    00687        _cur_town_iter >= TOWN_GROWTH_FREQUENCY;
    00688        _cur_town_iter -= TOWN_GROWTH_FREQUENCY) {
    00689     uint32 i = _cur_town_ctr;
    00690
    00691     if (++_cur_town_ctr > GetMaxTownIndex())
    00692       _cur_town_ctr = 0;
    00693
    00694     if (IsValidTownID(i)) TownTickHandler(GetTown(i));
    00695   }
    00696 }
    00697
    00706 static RoadBits GetTownRoadBits(TileIndex tile)
    00707 {
    00708   TrackBits b = GetAnyRoadTrackBits(tile, ROADTYPE_ROAD);
    00709   RoadBits r = ROAD_NONE;
    00710
    00711   if (b == TRACK_BIT_NONE) return r;
    00712   if (b & TRACK_BIT_X)     r |= ROAD_X;
    00713   if (b & TRACK_BIT_Y)     r |= ROAD_Y;
    00714   if (b & TRACK_BIT_UPPER) r |= ROAD_NE | ROAD_NW;
    00715   if (b & TRACK_BIT_LOWER) r |= ROAD_SE | ROAD_SW;
    00716   if (b & TRACK_BIT_LEFT)  r |= ROAD_NW | ROAD_SW;
    00717   if (b & TRACK_BIT_RIGHT) r |= ROAD_NE | ROAD_SE;
    00718   return r;
    00719 }
    00720
    00731 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
    00732 {
    00733   if (!IsValidTile(tile)) return false;
    00734
    00735   /* Lookup table for the used diff values */
    00736   const TileIndexDiff tid_lt[3] = {
    00737     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
    00738     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
    00739     TileOffsByDiagDir(ReverseDiagDir(dir)),
    00740   };
    00741
    00742   dist_multi = (dist_multi + 1) * 4;
    00743   for (uint pos = 4; pos < dist_multi; pos++) {
    00744     /* Go (pos / 4) tiles to the left or the right */
    00745     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
    00746
    00747     /* Use the current tile as origin, or go one tile backwards */
    00748     if (pos & 2) cur += tid_lt[2];
    00749
    00750     /* Test for roadbit parallel to dir and facing towards the middle axis */
    00751     if (IsValidTile(tile + cur) &&
    00752       GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
    00753   }
    00754   return false;
    00755 }
    00756
    00765 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
    00766 {
    00767   if (TileX(tile) < 2 || TileX(tile) >= MapMaxX() || TileY(tile) < 2 || TileY(tile) >= MapMaxY()) return false;
    00768
    00769   Slope cur_slope, desired_slope;
    00770
    00771   for (;;) {
    00772     /* Check if there already is a road at this point? */
    00773     if (GetTownRoadBits(tile) == ROAD_NONE) {
    00774       /* No, try if we are able to build a road piece there.
    00775        * If that fails clear the land, and if that fails exit.
    00776        * This is to make sure that we can build a road here later. */
    00777       if (CmdFailed(DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
    00778           CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
    00779         return false;
    00780     }
    00781
    00782     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
    00783     if (cur_slope == SLOPE_FLAT) {
    00784 no_slope:
    00785       /* Tile has no slope */
    00786       switch (t->layout) {
    00787         default: NOT_REACHED();
    00788
    00789         case TL_ORIGINAL: // Disallow the road if any neighboring tile has a road (distance: 1)
    00790           return !IsNeighborRoadTile(tile, dir, 1);
    00791
    00792         case TL_BETTER_ROADS: // Disallow the road if any neighboring tile has a road (distance: 1 and 2).
    00793           return !IsNeighborRoadTile(tile, dir, 2);
    00794       }
    00795     }
    00796
    00797     /* If the tile is not a slope in the right direction, then
    00798      * maybe terraform some. */
    00799     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
    00800     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
    00801       if (Chance16(1, 8)) {
    00802         CommandCost res = CMD_ERROR;
    00803         if (!_generating_world && Chance16(1, 10)) {
    00804           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
    00805           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
    00806               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
    00807         }
    00808         if (CmdFailed(res) && Chance16(1, 3)) {
    00809           /* We can consider building on the slope, though. */
    00810           goto no_slope;
    00811         }
    00812       }
    00813       return false;
    00814     }
    00815     return true;
    00816   }
    00817 }
    00818
    00819 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
    00820 {
    00821   assert(tile < MapSize());
    00822
    00823   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
    00824   if (CmdFailed(r) || r.GetCost() >= (_price.terraform + 2) * 8) return false;
    00825   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
    00826   return true;
    00827 }
    00828
    00829 static void LevelTownLand(TileIndex tile)
    00830 {
    00831   assert(tile < MapSize());
    00832
    00833   /* Don't terraform if land is plain or if there's a house there. */
    00834   if (IsTileType(tile, MP_HOUSE)) return;
    00835   Slope tileh = GetTileSlope(tile, NULL);
    00836   if (tileh == SLOPE_FLAT) return;
    00837
    00838   /* First try up, then down */
    00839   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
    00840     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
    00841   }
    00842 }
    00843
    00853 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
    00854 {
    00855   /* align the grid to the downtown */
    00856   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
    00857   RoadBits rcmd = ROAD_NONE;
    00858
    00859   switch (t->layout) {
    00860     default: NOT_REACHED();
    00861
    00862     case TL_2X2_GRID:
    00863       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
    00864       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
    00865       break;
    00866
    00867     case TL_3X3_GRID:
    00868       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
    00869       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
    00870       break;
    00871   }
    00872
    00873   /* Optimise only X-junctions */
    00874   if (rcmd != ROAD_ALL) return rcmd;
    00875
    00876   RoadBits rb_template;
    00877
    00878   switch (GetTileSlope(tile, NULL)) {
    00879     default:       rb_template = ROAD_ALL; break;
    00880     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
    00881     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
    00882     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
    00883     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
    00884     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
    00885     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
    00886     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
    00887     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
    00888     case SLOPE_STEEP_W:
    00889     case SLOPE_STEEP_S:
    00890     case SLOPE_STEEP_E:
    00891     case SLOPE_STEEP_N:
    00892       rb_template = ROAD_NONE;
    00893       break;
    00894   }
    00895
    00896   /* Stop if the template is compatible to the growth dir */
    00897   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
    00898   /* If not generate a straight road in the direction of the growth */
    00899   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
    00900 }
    00901
    00912 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
    00913 {
    00914   /* We can't look further than that. */
    00915   if (TileX(tile) < 2 || TileY(tile) < 2 || MapMaxX() <= TileX(tile) || MapMaxY() <= TileY(tile)) return false;
    00916
    00917   uint counter = 0; // counts the house neighbor tiles
    00918
    00919   /* Check the tiles E,N,W and S of the current tile for houses */
    00920   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
    00921
    00922     if (IsTileType(TileAddByDiagDir(tile, dir), MP_HOUSE)) counter++;
    00923
    00924     /* If there are enough neighbors stop here */
    00925     if (counter >= 3) {
    00926       if (BuildTownHouse(t, tile)) {
    00927         _grow_town_result = GROWTH_SUCCEED;
    00928         return true;
    00929       }
    00930       return false;
    00931     }
    00932   }
    00933   return false;
    00934 }
    00935
    00944 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
    00945 {
    00946   if (CmdSucceeded(DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD))) {
    00947     _grow_town_result = GROWTH_SUCCEED;
    00948     return true;
    00949   }
    00950   return false;
    00951 }
    00952
    00963 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
    00964 {
    00965   assert(bridge_dir < DIAGDIR_END);
    00966
    00967   const Slope slope = GetTileSlope(tile, NULL);
    00968   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
    00969
    00970   /* Make sure the direction is compatible with the slope.
    00971    * Well we check if the slope has an up bit set in the
    00972    * reverse direction. */
    00973   if (HASBITS(slope, InclinedSlope(bridge_dir))) return false;
    00974
    00975   /* Assure that the bridge is connectable to the start side */
    00976   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
    00977
    00978   /* We are in the right direction */
    00979   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
    00980   TileIndex bridge_tile = tile; // Used to store the other waterside
    00981
    00982   const int delta = TileOffsByDiagDir(bridge_dir);
    00983   do {
    00984     if (bridge_length++ >= 11) {
    00985       /* Max 11 tile long bridges */
    00986       return false;
    00987     }
    00988     bridge_tile += delta;
    00989   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
    00990
    00991   /* no water tiles in between? */
    00992   if (bridge_length == 1) return false;
    00993
    00994   for (uint8 times = 0; times <= 22; times++) {
    00995     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
    00996
    00997     /* Can we actually build the bridge? */
    00998     if (CmdSucceeded(DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
    00999       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
    01000       _grow_town_result = GROWTH_SUCCEED;
    01001       return true;
    01002     }
    01003   }
    01004   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
    01005   return false;
    01006 }
    01007
    01025 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
    01026 {
    01027   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
    01028   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
    01029
    01030   assert(tile < MapSize());
    01031
    01032   if (cur_rb == ROAD_NONE) {
    01033     /* Tile has no road. First reset the status counter
    01034      * to say that this is the last iteration. */
    01035     _grow_town_result = GROWTH_SEARCH_STOPPED;
    01036
    01037     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
    01038
    01039     /* Remove hills etc */
    01040     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
    01041
    01042     /* Is a road allowed here? */
    01043     switch (t1->layout) {
    01044       default: NOT_REACHED();
    01045
    01046       case TL_3X3_GRID:
    01047       case TL_2X2_GRID:
    01048         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
    01049         if (rcmd == ROAD_NONE) return;
    01050         break;
    01051
    01052       case TL_BETTER_ROADS:
    01053       case TL_ORIGINAL:
    01054         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
    01055
    01056         DiagDirection source_dir = ReverseDiagDir(target_dir);
    01057
    01058         if (Chance16(1, 4)) {
    01059           /* Randomize a new target dir */
    01060           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
    01061         }
    01062
    01063         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
    01064           /* A road is not allowed to continue the randomized road,
    01065            *  return if the road we're trying to build is curved. */
    01066           if (target_dir != ReverseDiagDir(source_dir)) return;
    01067
    01068           /* Return if neither side of the new road is a house */
    01069           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
    01070               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
    01071             return;
    01072           }
    01073
    01074           /* That means that the road is only allowed if there is a house
    01075            *  at any side of the new road. */
    01076         }
    01077
    01078         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
    01079         break;
    01080     }
    01081
    01082   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
    01083     /* Continue building on a partial road.
    01084      * Should be allways OK, so we only generate
    01085      * the fitting RoadBits */
    01086     _grow_town_result = GROWTH_SEARCH_STOPPED;
    01087
    01088     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
    01089
    01090     switch (t1->layout) {
    01091       default: NOT_REACHED();
    01092
    01093       case TL_3X3_GRID:
    01094       case TL_2X2_GRID:
    01095         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
    01096         break;
    01097
    01098       case TL_BETTER_ROADS:
    01099       case TL_ORIGINAL:
    01100         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
    01101         break;
    01102     }
    01103   } else {
    01104     bool allow_house = true; // Value which decides if we want to construct a house
    01105
    01106     /* Reached a tunnel/bridge? Then continue at the other side of it. */
    01107     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
    01108       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
    01109         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
    01110       }
    01111       return;
    01112     }
    01113
    01114     /* Possibly extend the road in a direction.
    01115      * Randomize a direction and if it has a road, bail out. */
    01116     target_dir = RandomDiagDir();
    01117     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
    01118
    01119     /* This is the tile we will reach if we extend to this direction. */
    01120     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
    01121
    01122     /* Don't walk into water. */
    01123     if (IsWaterTile(house_tile)) return;
    01124
    01125     if (!IsValidTile(house_tile) || !IsValidTile(house_tile + TileOffsByDiagDir(target_dir))) return;
    01126
    01127     if (_settings_game.economy.allow_town_roads || _generating_world) {
    01128       switch (t1->layout) {
    01129         default: NOT_REACHED();
    01130
    01131         case TL_3X3_GRID: // Use 2x2 grid afterwards!
    01132           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
    01133           /* FALL THROUGH */
    01134
    01135         case TL_2X2_GRID:
    01136           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
    01137           allow_house = (rcmd == ROAD_NONE);
    01138           break;
    01139
    01140         case TL_BETTER_ROADS: // Use original afterwards!
    01141           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
    01142           /* FALL THROUGH */
    01143
    01144         case TL_ORIGINAL:
    01145           /* Allow a house at the edge. 60% chance or
    01146            * always ok if no road allowed. */
    01147           rcmd = DiagDirToRoadBits(target_dir);
    01148           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
    01149           break;
    01150       }
    01151     }
    01152
    01153     if (allow_house) {
    01154       /* Build a house, but not if there already is a house there. */
    01155       if (!IsTileType(house_tile, MP_HOUSE)) {
    01156         /* Level the land if possible */
    01157         if (Chance16(1, 6)) LevelTownLand(house_tile);
    01158
    01159         /* And build a house.
    01160          * Set result to -1 if we managed to build it. */
    01161         if (BuildTownHouse(t1, house_tile)) {
    01162           _grow_town_result = GROWTH_SUCCEED;
    01163         }
    01164       }
    01165       return;
    01166     }
    01167
    01168     _grow_town_result = GROWTH_SEARCH_STOPPED;
    01169   }
    01170
    01171   /* Return if a water tile */
    01172   if (IsWaterTile(tile)) return;
    01173
    01174   /* Make the roads look nicer */
    01175   rcmd = CleanUpRoadBits(tile, rcmd);
    01176   if (rcmd == ROAD_NONE) return;
    01177
    01178   /* Only use the target direction for bridges to ensure they're connected.
    01179    * The target_dir is as computed previously according to town layout, so
    01180    * it will match it perfectly. */
    01181   if (GrowTownWithBridge(t1, tile, target_dir)) return;
    01182
    01183   GrowTownWithRoad(t1, tile, rcmd);
    01184 }
    01185
    01191 static int GrowTownAtRoad(Town *t, TileIndex tile)
    01192 {
    01193   /* Special case.
    01194    * @see GrowTownInTile Check the else if
    01195    */
    01196   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
    01197
    01198   assert(tile < MapSize());
    01199
    01200   /* Number of times to search.
    01201    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
    01202    * them a little handicap. */
    01203   switch (t->layout) {
    01204     case TL_BETTER_ROADS:
    01205       _grow_town_result = 10 + t->num_houses * 2 / 9;
    01206       break;
    01207
    01208     case TL_3X3_GRID:
    01209     case TL_2X2_GRID:
    01210       _grow_town_result = 10 + t->num_houses * 1 / 9;
    01211       break;
    01212
    01213     default:
    01214       _grow_town_result = 10 + t->num_houses * 4 / 9;
    01215       break;
    01216   }
    01217
    01218   do {
    01219     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
    01220
    01221     /* Try to grow the town from this point */
    01222     GrowTownInTile(&tile, cur_rb, target_dir, t);
    01223
    01224     /* Exclude the source position from the bitmask
    01225      * and return if no more road blocks available */
    01226     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
    01227     if (cur_rb == ROAD_NONE)
    01228       return _grow_town_result;
    01229
    01230     /* Select a random bit from the blockmask, walk a step
    01231      * and continue the search from there. */
    01232     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
    01233     tile = TileAddByDiagDir(tile, target_dir);
    01234
    01235     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
    01236       /* Don't allow building over roads of other cities */
    01237       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && GetTownByTile(tile) != t) {
    01238         _grow_town_result = GROWTH_SUCCEED;
    01239       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
    01240         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
    01241          * owner :) (happy happy happy road now) */
    01242         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
    01243         SetTownIndex(tile, t->index);
    01244       }
    01245     }
    01246
    01247     /* Max number of times is checked. */
    01248   } while (--_grow_town_result >= 0);
    01249
    01250   return (_grow_town_result == -2);
    01251 }
    01252
    01260 static RoadBits GenRandomRoadBits()
    01261 {
    01262   uint32 r = Random();
    01263   uint a = GB(r, 0, 2);
    01264   uint b = GB(r, 8, 2);
    01265   if (a == b) b ^= 2;
    01266   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
    01267 }
    01268
    01273 static bool GrowTown(Town *t)
    01274 {
    01275   static const TileIndexDiffC _town_coord_mod[] = {
    01276     {-1,  0},
    01277     { 1,  1},
    01278     { 1, -1},
    01279     {-1, -1},
    01280     {-1,  0},
    01281     { 0,  2},
    01282     { 2,  0},
    01283     { 0, -2},
    01284     {-1, -1},
    01285     {-2,  2},
    01286     { 2,  2},
    01287     { 2, -2},
    01288     { 0,  0}
    01289   };
    01290
    01291   /* Current "company" is a town */
    01292   CompanyID old_company = _current_company;
    01293   _current_company = OWNER_TOWN;
    01294
    01295   TileIndex tile = t->xy; // The tile we are working with ATM
    01296
    01297   /* Find a road that we can base the construction on. */
    01298   const TileIndexDiffC *ptr;
    01299   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
    01300     if (GetTownRoadBits(tile) != ROAD_NONE) {
    01301       int r = GrowTownAtRoad(t, tile);
    01302       _current_company = old_company;
    01303       return r != 0;
    01304     }
    01305     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
    01306   }
    01307
    01308   /* No road available, try to build a random road block by
    01309    * clearing some land and then building a road there. */
    01310   tile = t->xy;
    01311   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
    01312     /* Only work with plain land that not already has a house */
    01313     if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
    01314       if (CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR))) {
    01315         DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
    01316         _current_company = old_company;
    01317         return true;
    01318       }
    01319     }
    01320     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
    01321   }
    01322
    01323   _current_company = old_company;
    01324   return false;
    01325 }
    01326
    01327 void UpdateTownRadius(Town *t)
    01328 {
    01329   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
    01330     {  4,  0,  0,  0,  0}, // 0
    01331     { 16,  0,  0,  0,  0},
    01332     { 25,  0,  0,  0,  0},
    01333     { 36,  0,  0,  0,  0},
    01334     { 49,  0,  4,  0,  0},
    01335     { 64,  0,  4,  0,  0}, // 20
    01336     { 64,  0,  9,  0,  1},
    01337     { 64,  0,  9,  0,  4},
    01338     { 64,  0, 16,  0,  4},
    01339     { 81,  0, 16,  0,  4},
    01340     { 81,  0, 16,  0,  4}, // 40
    01341     { 81,  0, 25,  0,  9},
    01342     { 81, 36, 25,  0,  9},
    01343     { 81, 36, 25, 16,  9},
    01344     { 81, 49,  0, 25,  9},
    01345     { 81, 64,  0, 25,  9}, // 60
    01346     { 81, 64,  0, 36,  9},
    01347     { 81, 64,  0, 36, 16},
    01348     {100, 81,  0, 49, 16},
    01349     {100, 81,  0, 49, 25},
    01350     {121, 81,  0, 49, 25}, // 80
    01351     {121, 81,  0, 49, 25},
    01352     {121, 81,  0, 49, 36}, // 88
    01353   };
    01354
    01355   if (t->num_houses < 92) {
    01356     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
    01357   } else {
    01358     int mass = t->num_houses / 8;
    01359     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
    01360      * The offsets are to make sure the radii do not decrease in size when going from the table
    01361      * to the calculated value.*/
    01362     t->squared_town_zone_radius[0] = mass * 15 - 40;
    01363     t->squared_town_zone_radius[1] = mass * 9 - 15;
    01364     t->squared_town_zone_radius[2] = 0;
    01365     t->squared_town_zone_radius[3] = mass * 5 - 5;
    01366     t->squared_town_zone_radius[4] = mass * 3 + 5;
    01367   }
    01368 }
    01369
    01370 extern int _nb_orig_names;
    01371
    01376 struct TownNameParams {
    01377   uint32 grfid;
    01378   uint16 townnametype;
    01379   bool grf;
    01380
    01381   TownNameParams(byte town_name)
    01382   {
    01383     this->grf = town_name >= _nb_orig_names;
    01384     this->grfid = this->grf ? GetGRFTownNameId(town_name - _nb_orig_names) : 0;
    01385     this->townnametype = this->grf ? GetGRFTownNameType(town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + town_name;
    01386   }
    01387 };
    01388
    01395 static bool VerifyTownName(uint32 r, const TownNameParams *par)
    01396 {
    01397   /* reserve space for extra unicode character and terminating '\0' */
    01398   char buf1[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
    01399   char buf2[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
    01400
    01401   SetDParam(0, r);
    01402   if (par->grf && par->grfid != 0) {
    01403     GRFTownNameGenerate(buf1, par->grfid, par->townnametype, r, lastof(buf1));
    01404   } else {
    01405     GetString(buf1, par->townnametype, lastof(buf1));
    01406   }
    01407
    01408   /* Check size and width */
    01409   if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES) return false;
    01410
    01411   const Town *t;
    01412   FOR_ALL_TOWNS(t) {
    01413     /* We can't just compare the numbers since
    01414      * several numbers may map to a single name. */
    01415     SetDParam(0, t->index);
    01416     GetString(buf2, STR_TOWN, lastof(buf2));
    01417     if (strcmp(buf1, buf2) == 0) return false;
    01418   }
    01419
    01420   return true;
    01421 }
    01422
    01428 bool GenerateTownName(uint32 *townnameparts)
    01429 {
    01430   /* Do not set too low tries, since when we run out of names, we loop
    01431    * for #tries only one time anyway - then we stop generating more
    01432    * towns. Do not show it too high neither, since looping through all
    01433    * the other towns may take considerable amount of time (10000 is
    01434    * too much). */
    01435   int tries = 1000;
    01436   TownNameParams par(_settings_game.game_creation.town_name);
    01437
    01438   assert(townnameparts != NULL);
    01439
    01440   for (;;) {
    01441     uint32 r = InteractiveRandom();
    01442
    01443     if (!VerifyTownName(r, &par)) {
    01444       if (tries-- < 0) return false;
    01445       continue;
    01446     }
    01447
    01448     *townnameparts = r;
    01449     return true;
    01450   }
    01451 }
    01452
    01453 void UpdateTownMaxPass(Town *t)
    01454 {
    01455   t->max_pass = t->population >> 3;
    01456   t->max_mail = t->population >> 4;
    01457 }
    01458
    01468 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
    01469 {
    01470   t->xy = tile;
    01471   t->num_houses = 0;
    01472   t->time_until_rebuild = 10;
    01473   UpdateTownRadius(t);
    01474   t->flags12 = 0;
    01475   t->population = 0;
    01476   t->grow_counter = 0;
    01477   t->growth_rate = 250;
    01478   t->new_max_pass = 0;
    01479   t->new_max_mail = 0;
    01480   t->new_act_pass = 0;
    01481   t->new_act_mail = 0;
    01482   t->max_pass = 0;
    01483   t->max_mail = 0;
    01484   t->act_pass = 0;
    01485   t->act_mail = 0;
    01486
    01487   t->pct_pass_transported = 0;
    01488   t->pct_mail_transported = 0;
    01489   t->fund_buildings_months = 0;
    01490   t->new_act_food = 0;
    01491   t->new_act_water = 0;
    01492   t->act_food = 0;
    01493   t->act_water = 0;
    01494
    01495   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
    01496
    01497   t->have_ratings = 0;
    01498   t->exclusivity = INVALID_COMPANY;
    01499   t->exclusive_counter = 0;
    01500   t->statues = 0;
    01501
    01502   if (_settings_game.game_creation.town_name < _nb_orig_names) {
    01503     /* Original town name */
    01504     t->townnamegrfid = 0;
    01505     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
    01506   } else {
    01507     /* Newgrf town name */
    01508     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
    01509     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
    01510   }
    01511   t->townnameparts = townnameparts;
    01512
    01513   UpdateTownVirtCoord(t);
    01514   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
    01515
    01516   t->InitializeLayout(layout);
    01517
    01518   t->larger_town = city;
    01519
    01520   int x = (int)size * 16 + 3;
    01521   if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
    01522   if (city) x *= _settings_game.economy.initial_city_size;
    01523
    01524   t->num_houses += x;
    01525   UpdateTownRadius(t);
    01526
    01527   int i = x * 4;
    01528   do {
    01529     GrowTown(t);
    01530   } while (--i);
    01531
    01532   t->num_houses -= x;
    01533   UpdateTownRadius(t);
    01534   UpdateTownMaxPass(t);
    01535   UpdateAirportsNoise();
    01536 }
    01537
    01548 CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01549 {
    01550   /* Only in the scenario editor */
    01551   if (_game_mode != GM_EDITOR) return CMD_ERROR;
    01552
    01553   TownSize size = (TownSize)GB(p1, 0, 2);
    01554   bool city = HasBit(p1, 2);
    01555   TownLayout layout = (TownLayout)GB(p1, 3, 3);
    01556   TownNameParams par(_settings_game.game_creation.town_name);
    01557   uint32 townnameparts = p2;
    01558
    01559   if (size > TS_RANDOM) return CMD_ERROR;
    01560   if (layout > TL_RANDOM) return CMD_ERROR;
    01561   if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
    01562
    01563   /* Check if too close to the edge of map */
    01564   if (DistanceFromEdge(tile) < 12) {
    01565     return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
    01566   }
    01567
    01568   /* Check distance to all other towns. */
    01569   if (IsCloseToTown(tile, 20)) {
    01570     return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
    01571   }
    01572
    01573   /* Can only build on clear flat areas, possibly with trees. */
    01574   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
    01575     return_cmd_error(STR_0239_SITE_UNSUITABLE);
    01576   }
    01577
    01578   /* Allocate town struct */
    01579   if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
    01580
    01581   /* Create the town */
    01582   if (flags & DC_EXEC) {
    01583     Town *t = new Town(tile);
    01584     _generating_world = true;
    01585     UpdateNearestTownForRoadTiles(true);
    01586     DoCreateTown(t, tile, townnameparts, size, city, layout);
    01587     UpdateNearestTownForRoadTiles(false);
    01588     _generating_world = false;
    01589   }
    01590   return CommandCost();
    01591 }
    01592
    01593 Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
    01594 {
    01595   if (!Town::CanAllocateItem()) return NULL;
    01596
    01597   do {
    01598     /* Generate a tile index not too close from the edge */
    01599     TileIndex tile = RandomTile();
    01600     switch (layout) {
    01601       case TL_2X2_GRID:
    01602         tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
    01603         break;
    01604       case TL_3X3_GRID:
    01605         tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
    01606         break;
    01607       default: break;
    01608     }
    01609     if (DistanceFromEdge(tile) < 20) continue;
    01610
    01611     /* Make sure the tile is plain */
    01612     if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
    01613
    01614     /* Check not too close to a town */
    01615     if (IsCloseToTown(tile, 20)) continue;
    01616
    01617     uint32 townnameparts;
    01618
    01619     /* Get a unique name for the town. */
    01620     if (!GenerateTownName(&townnameparts)) break;
    01621
    01622     /* Allocate a town struct */
    01623     Town *t = new Town(tile);
    01624
    01625     DoCreateTown(t, tile, townnameparts, size, city, layout);
    01626     return t;
    01627   } while (--attempts != 0);
    01628
    01629   return NULL;
    01630 }
    01631
    01632 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
    01633
    01634 bool GenerateTowns(TownLayout layout)
    01635 {
    01636   uint num = 0;
    01637   uint difficulty = _settings_game.difficulty.number_towns;
    01638   uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
    01639   uint num_cities = _settings_game.economy.larger_towns == 0 ? 0 : n / _settings_game.economy.larger_towns;
    01640
    01641   SetGeneratingWorldProgress(GWP_TOWN, n);
    01642
    01643   do {
    01644     IncreaseGeneratingWorldProgress(GWP_TOWN);
    01645     /* try 20 times to create a random-sized town for the first loop. */
    01646     if (CreateRandomTown(20, TS_RANDOM, num_cities > 0, layout) != NULL) num++;
    01647     if (num_cities > 0) num_cities--;
    01648   } while (--n);
    01649
    01650   /* give it a last try, but now more aggressive */
    01651   if (num == 0 && CreateRandomTown(10000, TS_RANDOM, false, layout) == NULL) {
    01652     if (GetNumTowns() == 0) {
    01653       if (_game_mode != GM_EDITOR) {
    01654         extern StringID _switch_mode_errorstr;
    01655         _switch_mode_errorstr = STR_COULD_NOT_CREATE_TOWN;
    01656       }
    01657
    01658       return false;
    01659     }
    01660   }
    01661
    01662   return true;
    01663 }
    01664
    01665
    01671 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
    01672 {
    01673   uint dist = DistanceSquare(tile, t->xy);
    01674
    01675   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
    01676
    01677   HouseZonesBits smallest = HZB_TOWN_EDGE;
    01678   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
    01679     if (dist < t->squared_town_zone_radius[i]) smallest = i;
    01680   }
    01681
    01682   return smallest;
    01683 }
    01684
    01695 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
    01696 {
    01697   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
    01698
    01699   assert(CmdSucceeded(cc));
    01700
    01701   IncreaseBuildingCount(t, type);
    01702   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
    01703   if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
    01704
    01705   MarkTileDirtyByTile(tile);
    01706 }
    01707
    01708
    01719 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
    01720 {
    01721   BuildingFlags size = GetHouseSpecs(type)->building_flags;
    01722
    01723   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
    01724   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
    01725   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
    01726   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
    01727 }
    01728
    01729
    01738 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
    01739 {
    01740   /* cannot build on these slopes... */
    01741   Slope slope = GetTileSlope(tile, NULL);
    01742   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
    01743
    01744   /* building under a bridge? */
    01745   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
    01746
    01747   /* do not try to build over house owned by another town */
    01748   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
    01749
    01750   /* can we clear the land? */
    01751   return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
    01752 }
    01753
    01754
    01764 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
    01765 {
    01766   if (!CanBuildHouseHere(tile, town, noslope)) return false;
    01767
    01768   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
    01769   if (GetTileMaxZ(tile) != z) return false;
    01770
    01771   return true;
    01772 }
    01773
    01774
    01784 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
    01785 {
    01786   /* we need to check this tile too because we can be at different tile now */
    01787   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
    01788
    01789   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
    01790     tile += TileOffsByDiagDir(d);
    01791     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
    01792   }
    01793
    01794   return true;
    01795 }
    01796
    01797
    01805 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
    01806 {
    01807   /* Allow towns everywhere when we don't build roads */
    01808   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
    01809
    01810   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
    01811
    01812   switch (t->layout) {
    01813     case TL_2X2_GRID:
    01814       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
    01815       break;
    01816
    01817     case TL_3X3_GRID:
    01818       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
    01819       break;
    01820
    01821     default:
    01822       break;
    01823   }
    01824
    01825   return true;
    01826 }
    01827
    01828
    01836 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
    01837 {
    01838   /* Allow towns everywhere when we don't build roads */
    01839   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
    01840
    01841   /* MapSize() is sure dividable by both MapSizeX() and MapSizeY(),
    01842    * so to do only one memory access, use MapSize() */
    01843   uint dx = MapSize() + TileX(t->xy) - TileX(tile);
    01844   uint dy = MapSize() + TileY(t->xy) - TileY(tile);
    01845
    01846   switch (t->layout) {
    01847     case TL_2X2_GRID:
    01848       if ((dx % 3) != 0 || (dy % 3) != 0) return false;
    01849       break;
    01850
    01851     case TL_3X3_GRID:
    01852       if ((dx % 4) < 2 || (dy % 4) < 2) return false;
    01853       break;
    01854
    01855     default:
    01856       break;
    01857   }
    01858
    01859   return true;
    01860 }
    01861
    01862
    01872 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
    01873 {
    01874   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
    01875
    01876   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
    01877   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
    01878
    01879   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
    01880   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
    01881     *tile = tile2;
    01882     return true;
    01883   }
    01884
    01885   return false;
    01886 }
    01887
    01888
    01897 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
    01898 {
    01899   TileIndex tile2 = *tile;
    01900
    01901   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
    01902     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
    01903       *tile = tile2;
    01904       return true;
    01905     }
    01906     if (d == DIAGDIR_END) break;
    01907     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
    01908   }
    01909
    01910   return false;
    01911 }
    01912
    01913
    01920 static bool BuildTownHouse(Town *t, TileIndex tile)
    01921 {
    01922   /* forbidden building here by town layout */
    01923   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
    01924
    01925   /* no house allowed at all, bail out */
    01926   if (!CanBuildHouseHere(tile, t->index, false)) return false;
    01927
    01928   uint z;
    01929   Slope slope = GetTileSlope(tile, &z);
    01930
    01931   /* Get the town zone type of the current tile, as well as the climate.
    01932    * This will allow to easily compare with the specs of the new house to build */
    01933   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
    01934
    01935   /* Above snow? */
    01936   int land = _settings_game.game_creation.landscape;
    01937   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
    01938
    01939   uint bitmask = (1 << rad) + (1 << (land + 12));
    01940
    01941   /* bits 0-4 are used
    01942    * bits 11-15 are used
    01943    * bits 5-10 are not used. */
    01944   HouseID houses[HOUSE_MAX];
    01945   uint num = 0;
    01946   uint probs[HOUSE_MAX];
    01947   uint probability_max = 0;
    01948
    01949   /* Generate a list of all possible houses that can be built. */
    01950   for (uint i = 0; i < HOUSE_MAX; i++) {
    01951     const HouseSpec *hs = GetHouseSpecs(i);
    01952     /* Verify that the candidate house spec matches the current tile status */
    01953     if ((~hs->building_availability & bitmask) == 0 && hs->enabled) {
    01954       /* Without NewHouses, all houses have probability '1' */
    01955       uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
    01956       probability_max += cur_prob;
    01957       probs[num] = cur_prob;
    01958       houses[num++] = (HouseID)i;
    01959     }
    01960   }
    01961
    01962   uint maxz = GetTileMaxZ(tile);
    01963
    01964   while (probability_max > 0) {
    01965     uint r = RandomRange(probability_max);
    01966     uint i;
    01967     for (i = 0; i < num; i++) {
    01968       if (probs[i] > r) break;
    01969       r -= probs[i];
    01970     }
    01971
    01972     HouseID house = houses[i];
    01973     probability_max -= probs[i];
    01974
    01975     /* remove tested house from the set */
    01976     num--;
    01977     houses[i] = houses[num];
    01978     probs[i] = probs[num];
    01979
    01980     const HouseSpec *hs = GetHouseSpecs(house);
    01981
    01982     if (_loaded_newgrf_features.has_newhouses) {
    01983       if (hs->override != 0) {
    01984         house = hs->override;
    01985         hs = GetHouseSpecs(house);
    01986       }
    01987
    01988       if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world && _game_mode != GM_EDITOR) continue;
    01989     }
    01990
    01991     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
    01992
    01993     /* Special houses that there can be only one of. */
    01994     uint oneof = 0;
    01995
    01996     if (hs->building_flags & BUILDING_IS_CHURCH) {
    01997       SetBit(oneof, TOWN_HAS_CHURCH);
    01998     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
    01999       SetBit(oneof, TOWN_HAS_STADIUM);
    02000     }
    02001
    02002     if (HASBITS(t->flags12, oneof)) continue;
    02003
    02004     /* Make sure there is no slope? */
    02005     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
    02006     if (noslope && slope != SLOPE_FLAT) continue;
    02007
    02008     if (hs->building_flags & TILE_SIZE_2x2) {
    02009       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
    02010     } else if (hs->building_flags & TILE_SIZE_2x1) {
    02011       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
    02012     } else if (hs->building_flags & TILE_SIZE_1x2) {
    02013       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
    02014     } else {
    02015       /* 1x1 house checks are already done */
    02016     }
    02017
    02018     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
    02019       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
    02020       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
    02021     }
    02022
    02023     /* build the house */
    02024     t->num_houses++;
    02025
    02026     /* Special houses that there can be only one of. */
    02027     t->flags12 |= oneof;
    02028
    02029     byte construction_counter = 0;
    02030     byte construction_stage = 0;
    02031
    02032     if (_generating_world || _game_mode == GM_EDITOR) {
    02033       uint32 r = Random();
    02034
    02035       construction_stage = TOWN_HOUSE_COMPLETED;
    02036       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
    02037
    02038       if (construction_stage == TOWN_HOUSE_COMPLETED) {
    02039         ChangePopulation(t, hs->population);
    02040       } else {
    02041         construction_counter = GB(r, 2, 2);
    02042       }
    02043     }
    02044
    02045     MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
    02046
    02047     return true;
    02048   }
    02049
    02050   return false;
    02051 }
    02052
    02059 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
    02060 {
    02061   assert(IsTileType(tile, MP_HOUSE));
    02062   DecreaseBuildingCount(t, house);
    02063   DoClearSquare(tile);
    02064   DeleteAnimatedTile(tile);
    02065 }
    02066
    02074 TileIndexDiff GetHouseNorthPart(HouseID &house)
    02075 {
    02076   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
    02077     if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
    02078       house--;
    02079       return TileDiffXY(-1, 0);
    02080     } else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
    02081       house--;
    02082       return TileDiffXY(0, -1);
    02083     } else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
    02084       house -= 2;
    02085       return TileDiffXY(-1, 0);
    02086     } else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
    02087       house -= 3;
    02088       return TileDiffXY(-1, -1);
    02089     }
    02090   }
    02091   return 0;
    02092 }
    02093
    02094 void ClearTownHouse(Town *t, TileIndex tile)
    02095 {
    02096   assert(IsTileType(tile, MP_HOUSE));
    02097
    02098   HouseID house = GetHouseType(tile);
    02099
    02100   /* need to align the tile to point to the upper left corner of the house */
    02101   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
    02102
    02103   const HouseSpec *hs = GetHouseSpecs(house);
    02104
    02105   /* Remove population from the town if the house is finished. */
    02106   if (IsHouseCompleted(tile)) {
    02107     ChangePopulation(t, -hs->population);
    02108   }
    02109
    02110   t->num_houses--;
    02111
    02112   /* Clear flags for houses that only may exist once/town. */
    02113   if (hs->building_flags & BUILDING_IS_CHURCH) {
    02114     ClrBit(t->flags12, TOWN_HAS_CHURCH);
    02115   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
    02116     ClrBit(t->flags12, TOWN_HAS_STADIUM);
    02117   }
    02118
    02119   /* Do the actual clearing of tiles */
    02120   uint eflags = hs->building_flags;
    02121   DoClearTownHouseHelper(tile, t, house);
    02122   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
    02123   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
    02124   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
    02125 }
    02126
    02127 static bool IsUniqueTownName(const char *name)
    02128 {
    02129   const Town *t;
    02130
    02131   FOR_ALL_TOWNS(t) {
    02132     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
    02133   }
    02134
    02135   return true;
    02136 }
    02137
    02144 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02145 {
    02146   if (!IsValidTownID(p1)) return CMD_ERROR;
    02147
    02148   bool reset = StrEmpty(text);
    02149
    02150   if (!reset) {
    02151     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
    02152     if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
    02153   }
    02154
    02155   if (flags & DC_EXEC) {
    02156     Town *t = GetTown(p1);
    02157
    02158     free(t->name);
    02159     t->name = reset ? NULL : strdup(text);
    02160
    02161     UpdateTownVirtCoord(t);
    02162     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
    02163     UpdateAllStationVirtCoord();
    02164     UpdateAllWaypointSigns();
    02165     MarkWholeScreenDirty();
    02166   }
    02167   return CommandCost();
    02168 }
    02169
    02171 void ExpandTown(Town *t)
    02172 {
    02173   /* Warn the users if towns are not allowed to build roads,
    02174    * but do this only onces per openttd run. */
    02175   static bool warned_no_roads = false;
    02176   if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
    02177     ShowErrorMessage(INVALID_STRING_ID, STR_TOWN_EXPAND_WARN_NO_ROADS, 0, 0);
    02178     warned_no_roads = true;
    02179   }
    02180
    02181   /* The more houses, the faster we grow */
    02182   uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
    02183   t->num_houses += amount;
    02184   UpdateTownRadius(t);
    02185
    02186   uint n = amount * 10;
    02187   do GrowTown(t); while (--n);
    02188
    02189   t->num_houses -= amount;
    02190   UpdateTownRadius(t);
    02191
    02192   UpdateTownMaxPass(t);
    02193 }
    02194
    02195 extern const byte _town_action_costs[8] = {
    02196   2, 4, 9, 35, 48, 53, 117, 175
    02197 };
    02198
    02199 static void TownActionAdvertiseSmall(Town *t)
    02200 {
    02201   ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
    02202 }
    02203
    02204 static void TownActionAdvertiseMedium(Town *t)
    02205 {
    02206   ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
    02207 }
    02208
    02209 static void TownActionAdvertiseLarge(Town *t)
    02210 {
    02211   ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
    02212 }
    02213
    02214 static void TownActionRoadRebuild(Town *t)
    02215 {
    02216   t->road_build_months = 6;
    02217
    02218   char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
    02219   SetDParam(0, _current_company);
    02220   GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
    02221
    02222   char *cn = strdup(company_name);
    02223   SetDParam(0, t->index);
    02224   SetDParamStr(1, cn);
    02225
    02226   AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING, NS_GENERAL, t->xy, 0, cn);
    02227 }
    02228
    02229 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
    02230 {
    02231   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
    02232   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
    02233   /* Don't build statues under bridges. */
    02234   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
    02235
    02236   if (!IsTileType(tile, MP_HOUSE) &&
    02237       !IsTileType(tile, MP_CLEAR) &&
    02238       !IsTileType(tile, MP_TREES)) {
    02239     return false;
    02240   }
    02241
    02242   CompanyID old = _current_company;
    02243   _current_company = OWNER_NONE;
    02244   CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
    02245   _current_company = old;
    02246
    02247   if (CmdFailed(r)) return false;
    02248
    02249   MakeStatue(tile, _current_company, town_id);
    02250   MarkTileDirtyByTile(tile);
    02251
    02252   return true;
    02253 }
    02254
    02261 static bool SearchTileForStatue(TileIndex tile, void *user_data)
    02262 {
    02263   TownID *town_id = (TownID *)user_data;
    02264   return DoBuildStatueOfCompany(tile, *town_id);
    02265 }
    02266
    02272 static void TownActionBuildStatue(Town *t)
    02273 {
    02274   TileIndex tile = t->xy;
    02275
    02276   if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
    02277     SetBit(t->statues, _current_company); // Once found and built, "inform" the Town
    02278   }
    02279 }
    02280
    02281 static void TownActionFundBuildings(Town *t)
    02282 {
    02283   /* Build next tick */
    02284   t->grow_counter = 1;
    02285   /* If we were not already growing */
    02286   SetBit(t->flags12, TOWN_IS_FUNDED);
    02287   /* And grow for 3 months */
    02288   t->fund_buildings_months = 3;
    02289 }
    02290
    02291 static void TownActionBuyRights(Town *t)
    02292 {
    02293   /* Check if it's allowed to by the rights */
    02294   if (!_settings_game.economy.exclusive_rights) return;
    02295
    02296   t->exclusive_counter = 12;
    02297   t->exclusivity = _current_company;
    02298
    02299   ModifyStationRatingAround(t->xy, _current_company, 130, 17);
    02300 }
    02301
    02302 static void TownActionBribe(Town *t)
    02303 {
    02304   if (Chance16(1, 14)) {
    02305     /* set as unwanted for 6 months */
    02306     t->unwanted[_current_company] = 6;
    02307
    02308     /* set all close by station ratings to 0 */
    02309     Station *st;
    02310     FOR_ALL_STATIONS(st) {
    02311       if (st->town == t && st->owner == _current_company) {
    02312         for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
    02313       }
    02314     }
    02315
    02316     /* only show errormessage to the executing player. All errors are handled command.c
    02317      * but this is special, because it can only 'fail' on a DC_EXEC */
    02318     if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
    02319
    02320     /* decrease by a lot!
    02321      * ChangeTownRating is only for stuff in demolishing. Bribe failure should
    02322      * be independent of any cheat settings
    02323      */
    02324     if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
    02325       t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
    02326       InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
    02327     }
    02328   } else {
    02329     ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
    02330   }
    02331 }
    02332
    02333 typedef void TownActionProc(Town *t);
    02334 static TownActionProc * const _town_action_proc[] = {
    02335   TownActionAdvertiseSmall,
    02336   TownActionAdvertiseMedium,
    02337   TownActionAdvertiseLarge,
    02338   TownActionRoadRebuild,
    02339   TownActionBuildStatue,
    02340   TownActionFundBuildings,
    02341   TownActionBuyRights,
    02342   TownActionBribe
    02343 };
    02344
    02345 enum TownActions {
    02346   TACT_NONE             = 0x00,
    02347
    02348   TACT_ADVERTISE_SMALL  = 0x01,
    02349   TACT_ADVERTISE_MEDIUM = 0x02,
    02350   TACT_ADVERTISE_LARGE  = 0x04,
    02351   TACT_ROAD_REBUILD     = 0x08,
    02352   TACT_BUILD_STATUE     = 0x10,
    02353   TACT_FOUND_BUILDINGS  = 0x20,
    02354   TACT_BUY_RIGHTS       = 0x40,
    02355   TACT_BRIBE            = 0x80,
    02356
    02357   TACT_ADVERTISE        = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
    02358   TACT_CONSTRUCTION     = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
    02359   TACT_FUNDS            = TACT_BUY_RIGHTS | TACT_BRIBE,
    02360   TACT_ALL              = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
    02361 };
    02362
    02363 DECLARE_ENUM_AS_BIT_SET(TownActions);
    02364
    02371 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
    02372 {
    02373   int num = 0;
    02374   TownActions buttons = TACT_NONE;
    02375
    02376   /* Spectators and unwanted have no options */
    02377   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
    02378
    02379     /* Things worth more than this are not shown */
    02380     Money avail = GetCompany(cid)->money + _price.station_value * 200;
    02381     Money ref = _price.build_industry >> 8;
    02382
    02383     /* Check the action bits for validity and
    02384      * if they are valid add them */
    02385     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
    02386       const TownActions cur = (TownActions)(1 << i);
    02387
    02388       /* Is the company not able to bribe ? */
    02389       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
    02390         continue;
    02391
    02392       /* Is the company not able to buy exclusive rights ? */
    02393       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
    02394         continue;
    02395
    02396       /* Is the company not able to build a statue ? */
    02397       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
    02398         continue;
    02399
    02400       if (avail >= _town_action_costs[i] * ref) {
    02401         buttons |= cur;
    02402         num++;
    02403       }
    02404     }
    02405   }
    02406
    02407   if (nump != NULL) *nump = num;
    02408   return buttons;
    02409 }
    02410
    02419 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    02420 {
    02421   if (!IsValidTownID(p1) || p2 > lengthof(_town_action_proc)) return CMD_ERROR;
    02422
    02423   Town *t = GetTown(p1);
    02424
    02425   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
    02426
    02427   CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
    02428
    02429   if (flags & DC_EXEC) {
    02430     _town_action_proc[p2](t);
    02431     InvalidateWindow(WC_TOWN_AUTHORITY, p1);
    02432   }
    02433
    02434   return cost;
    02435 }
    02436
    02437 static void UpdateTownGrowRate(Town *t)
    02438 {
    02439   /* Increase company ratings if they're low */
    02440   const Company *c;
    02441   FOR_ALL_COMPANIES(c) {
    02442     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
    02443       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
    02444     }
    02445   }
    02446
    02447   int n = 0;
    02448
    02449   const Station *st;
    02450   FOR_ALL_STATIONS(st) {
    02451     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
    02452       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
    02453         n++;
    02454         if (IsValidCompanyID(st->owner)) {
    02455           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
    02456           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
    02457         }
    02458       } else {
    02459         if (IsValidCompanyID(st->owner)) {
    02460           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
    02461           t->ratings[st->owner] = max(new_rating, INT16_MIN);
    02462         }
    02463       }
    02464     }
    02465   }
    02466
    02467   /* clamp all ratings to valid values */
    02468   for (uint i = 0; i < MAX_COMPANIES; i++) {
    02469     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
    02470   }
    02471
    02472   InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
    02473
    02474   ClrBit(t->flags12, TOWN_IS_FUNDED);
    02475   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
    02476
    02479   static const uint16 _grow_count_values[2][6] = {
    02480     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
    02481     { 320, 420, 300, 220, 160, 100 }  // Normal values
    02482   };
    02483
    02484   uint16 m;
    02485
    02486   if (t->fund_buildings_months != 0) {
    02487     m = _grow_count_values[0][min(n, 5)];
    02488     t->fund_buildings_months--;
    02489   } else {
    02490     m = _grow_count_values[1][min(n, 5)];
    02491     if (n == 0 && !Chance16(1, 12)) return;
    02492   }
    02493
    02494   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
    02495     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
    02496       return;
    02497   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
    02498     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
    02499       return;
    02500   }
    02501
    02502   /* Use the normal growth rate values if new buildings have been funded in
    02503    * this town and the growth rate is set to none. */
    02504   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
    02505
    02506   m >>= growth_multiplier;
    02507   if (t->larger_town) m /= 2;
    02508
    02509   t->growth_rate = m / (t->num_houses / 50 + 1);
    02510   if (m <= t->grow_counter)
    02511     t->grow_counter = m;
    02512
    02513   SetBit(t->flags12, TOWN_IS_FUNDED);
    02514 }
    02515
    02516 static void UpdateTownAmounts(Town *t)
    02517 {
    02518   /* Using +1 here to prevent overflow and division by zero */
    02519   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
    02520
    02521   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
    02522   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
    02523   t->act_food = t->new_act_food; t->new_act_food = 0;
    02524   t->act_water = t->new_act_water; t->new_act_water = 0;
    02525
    02526   /* Using +1 here to prevent overflow and division by zero */
    02527   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
    02528   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
    02529   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
    02530
    02531   InvalidateWindow(WC_TOWN_VIEW, t->index);
    02532 }
    02533
    02534 static void UpdateTownUnwanted(Town *t)
    02535 {
    02536   const Company *c;
    02537
    02538   FOR_ALL_COMPANIES(c) {
    02539     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
    02540   }
    02541 }
    02542
    02548 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
    02549 {
    02550   if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
    02551
    02552   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
    02553   if (t == NULL) return true;
    02554
    02555   if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
    02556
    02557   _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
    02558   SetDParam(0, t->index);
    02559
    02560   return false;
    02561 }
    02562
    02563
    02564 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
    02565 {
    02566   Town *t;
    02567   uint best = threshold;
    02568   Town *best_town = NULL;
    02569
    02570   FOR_ALL_TOWNS(t) {
    02571     uint dist = DistanceManhattan(tile, t->xy);
    02572     if (dist < best) {
    02573       best = dist;
    02574       best_town = t;
    02575     }
    02576   }
    02577
    02578   return best_town;
    02579 }
    02580
    02581
    02582 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
    02583 {
    02584   switch (GetTileType(tile)) {
    02585     case MP_ROAD:
    02586       if (!HasTownOwnedRoad(tile)) {
    02587         TownID tid = GetTownIndex(tile);
    02588         if (tid == (TownID)INVALID_TOWN) {
    02589           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
    02590           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
    02591           assert(GetNumTowns() == 0);
    02592           return NULL;
    02593         }
    02594
    02595         Town *town = GetTown(tid);
    02596         assert(town->IsValid());
    02597         assert(town == CalcClosestTownFromTile(tile));
    02598
    02599         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
    02600
    02601         return town;
    02602       }
    02603       /* FALL THROUGH */
    02604
    02605     case MP_HOUSE:
    02606       return GetTownByTile(tile);
    02607
    02608     default:
    02609       return CalcClosestTownFromTile(tile, threshold);
    02610   }
    02611 }
    02612
    02613 static bool _town_rating_test = false;
    02614 SmallMap<const Town *, int, 4> _town_test_ratings;
    02615
    02616 void SetTownRatingTestMode(bool mode)
    02617 {
    02618   static int ref_count = 0;
    02619   if (mode) {
    02620     if (ref_count == 0) {
    02621       _town_test_ratings.Clear();
    02622     }
    02623     ref_count++;
    02624   } else {
    02625     assert(ref_count > 0);
    02626     ref_count--;
    02627   }
    02628   _town_rating_test = !(ref_count == 0);
    02629 }
    02630
    02631 static int GetRating(const Town *t)
    02632 {
    02633   if (_town_rating_test) {
    02634     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
    02635     if (it != _town_test_ratings.End()) {
    02636       return it->second;
    02637     }
    02638   }
    02639   return t->ratings[_current_company];
    02640 }
    02641
    02649 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
    02650 {
    02651   /* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
    02652   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
    02653       !IsValidCompanyID(_current_company) ||
    02654       (_cheats.magic_bulldozer.value && add < 0)) {
    02655     return;
    02656   }
    02657
    02658   int rating = GetRating(t);
    02659   if (add < 0) {
    02660     if (rating > max) {
    02661       rating += add;
    02662       if (rating < max) rating = max;
    02663     }
    02664   } else {
    02665     if (rating < max) {
    02666       rating += add;
    02667       if (rating > max) rating = max;
    02668     }
    02669   }
    02670   if (_town_rating_test) {
    02671     _town_test_ratings[t] = rating;
    02672   } else {
    02673     SetBit(t->have_ratings, _current_company);
    02674     t->ratings[_current_company] = rating;
    02675     InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
    02676   }
    02677 }
    02678
    02679 /* penalty for removing town-owned stuff */
    02680 static const int _default_rating_settings [3][3] = {
    02681   /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE */
    02682   {  0, 128, 384}, // Permissive
    02683   { 48, 192, 480}, // Neutral
    02684   { 96, 384, 768}, // Hostile
    02685 };
    02686
    02687 bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
    02688 {
    02689   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
    02690   if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
    02691     return true;
    02692
    02693   /* check if you're allowed to remove the street/bridge/tunnel/industry
    02694    * owned by a town no removal if rating is lower than ... depends now on
    02695    * difficulty setting. Minimum town rating selected by difficulty level
    02696    */
    02697   int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
    02698
    02699   if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
    02700     SetDParam(0, t->index);
    02701     _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
    02702     return false;
    02703   }
    02704
    02705   return true;
    02706 }
    02707
    02708 void TownsMonthlyLoop()
    02709 {
    02710   Town *t;
    02711
    02712   FOR_ALL_TOWNS(t) {
    02713     if (t->road_build_months != 0) t->road_build_months--;
    02714
    02715     if (t->exclusive_counter != 0)
    02716       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
    02717
    02718     UpdateTownGrowRate(t);
    02719     UpdateTownAmounts(t);
    02720     UpdateTownUnwanted(t);
    02721   }
    02722 }
    02723
    02724 void TownsYearlyLoop()
    02725 {
    02726   /* Increment house ages */
    02727   for (TileIndex t = 0; t < MapSize(); t++) {
    02728     if (!IsTileType(t, MP_HOUSE)) continue;
    02729     IncrementHouseAge(t);
    02730   }
    02731 }
    02732
    02733 void InitializeTowns()
    02734 {
    02735   /* Clean the town pool and create 1 block in it */
    02736   _Town_pool.CleanPool();
    02737   _Town_pool.AddBlockToPool();
    02738
    02739   memset(_subsidies, 0, sizeof(_subsidies));
    02740   for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
    02741     s->cargo_type = CT_INVALID;
    02742   }
    02743
    02744   _cur_town_ctr = 0;
    02745   _cur_town_iter = 0;
    02746   _total_towns = 0;
    02747 }
    02748
    02749 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
    02750 {
    02751   if (AutoslopeEnabled()) {
    02752     HouseID house = GetHouseType(tile);
    02753     GetHouseNorthPart(house); // modifies house to the ID of the north tile
    02754     const HouseSpec *hs = GetHouseSpecs(house);
    02755
    02756     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
    02757     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
    02758       (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
    02759   }
    02760
    02761   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    02762 }
    02763
    02765 extern const TileTypeProcs _tile_type_town_procs = {
    02766   DrawTile_Town,           // draw_tile_proc
    02767   GetSlopeZ_Town,          // get_slope_z_proc
    02768   ClearTile_Town,          // clear_tile_proc
    02769   GetAcceptedCargo_Town,   // get_accepted_cargo_proc
    02770   GetTileDesc_Town,        // get_tile_desc_proc
    02771   GetTileTrackStatus_Town, // get_tile_track_status_proc
    02772   ClickTile_Town,          // click_tile_proc
    02773   AnimateTile_Town,        // animate_tile_proc
    02774   TileLoop_Town,           // tile_loop_clear
    02775   ChangeTileOwner_Town,    // change_tile_owner_clear
    02776   GetProducedCargo_Town,   // get_produced_cargo_proc
    02777   NULL,                    // vehicle_enter_tile_proc
    02778   GetFoundation_Town,      // get_foundation_proc
    02779   TerraformTile_Town,      // terraform_tile_proc
    02780 };
    02781
    02782 void ResetHouses()
    02783 {
    02784   memset(&_house_specs, 0, sizeof(_house_specs));
    02785   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
    02786
    02787   /* Reset any overrides that have been set. */
    02788   _house_mngr.ResetOverride();
    02789 }