town_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: town_cmd.cpp 16273 2009-05-10 21:33:55Z 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       if (amt == 0) continue;
00459 
00460       uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
00461 
00462       const CargoSpec *cs = GetCargo(cargo);
00463       switch (cs->town_effect) {
00464         case TE_PASSENGERS:
00465           t->new_max_pass += amt;
00466           t->new_act_pass += moved;
00467           break;
00468 
00469         case TE_MAIL:
00470           t->new_max_mail += amt;
00471           t->new_act_mail += moved;
00472           break;
00473 
00474         default:
00475           break;
00476       }
00477     }
00478   } else {
00479     if (GB(r, 0, 8) < hs->population) {
00480       uint amt = GB(r, 0, 8) / 8 + 1;
00481 
00482       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00483       t->new_max_pass += amt;
00484       t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
00485     }
00486 
00487     if (GB(r, 8, 8) < hs->mail_generation) {
00488       uint amt = GB(r, 8, 8) / 8 + 1;
00489 
00490       if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00491       t->new_max_mail += amt;
00492       t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
00493     }
00494   }
00495 
00496   _current_company = OWNER_TOWN;
00497 
00498   if (hs->building_flags & BUILDING_HAS_1_TILE &&
00499       HasBit(t->flags12, TOWN_IS_FUNDED) &&
00500       CanDeleteHouse(tile) &&
00501       GetHouseAge(tile) >= hs->minimum_life &&
00502       --t->time_until_rebuild == 0) {
00503     t->time_until_rebuild = GB(r, 16, 8) + 192;
00504 
00505     ClearTownHouse(t, tile);
00506 
00507     /* Rebuild with another house? */
00508     if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00509   }
00510 
00511   _current_company = OWNER_NONE;
00512 }
00513 
00518 static bool ClickTile_Town(TileIndex tile)
00519 {
00520   /* not used */
00521   return false;
00522 }
00523 
00524 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00525 {
00526   if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
00527   if (!CanDeleteHouse(tile)) return CMD_ERROR;
00528 
00529   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00530 
00531   CommandCost cost(EXPENSES_CONSTRUCTION);
00532   cost.AddCost(hs->GetRemovalCost());
00533 
00534   int rating = hs->remove_rating_decrease;
00535   _cleared_town_rating += rating;
00536   Town *t = _cleared_town = GetTownByTile(tile);
00537 
00538   if (IsValidCompanyID(_current_company)) {
00539     if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00540       SetDParam(0, t->index);
00541       return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
00542     }
00543   }
00544 
00545   ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00546   if (flags & DC_EXEC) {
00547     ClearTownHouse(t, tile);
00548   }
00549 
00550   return cost;
00551 }
00552 
00553 static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
00554 {
00555   HouseID house_id = GetHouseType(tile);
00556   const HouseSpec *hs = GetHouseSpecs(house_id);
00557   Town *t = GetTownByTile(tile);
00558 
00559   if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00560     for (uint i = 0; i < 256; i++) {
00561       uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00562 
00563       if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00564 
00565       CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00566 
00567       if (cargo == CT_INVALID) continue;
00568       *(b++) = cargo;
00569     }
00570   } else {
00571     if (hs->population > 0) {
00572       *(b++) = CT_PASSENGERS;
00573     }
00574     if (hs->mail_generation > 0) {
00575       *(b++) = CT_MAIL;
00576     }
00577   }
00578 }
00579 
00580 static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
00581 {
00582   const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
00583   CargoID accepts[3];
00584 
00585   /* Set the initial accepted cargo types */
00586   for (uint8 i = 0; i < lengthof(accepts); i++) {
00587     accepts[i] = hs->accepts_cargo[i];
00588   }
00589 
00590   /* Check for custom accepted cargo types */
00591   if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00592     uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00593     if (callback != CALLBACK_FAILED) {
00594       /* Replace accepted cargo types with translated values from callback */
00595       accepts[0] = GetCargoTranslation(GB(callback,  0, 5), hs->grffile);
00596       accepts[1] = GetCargoTranslation(GB(callback,  5, 5), hs->grffile);
00597       accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00598     }
00599   }
00600 
00601   /* Check for custom cargo acceptance */
00602   if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00603     uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
00604     if (callback != CALLBACK_FAILED) {
00605       if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
00606       if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
00607       if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00608         /* The 'S' bit indicates food instead of goods */
00609         ac[CT_FOOD] = GB(callback, 8, 4);
00610       } else {
00611         if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
00612       }
00613       return;
00614     }
00615   }
00616 
00617   /* No custom acceptance, so fill in with the default values */
00618   for (uint8 i = 0; i < lengthof(accepts); i++) {
00619     if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
00620   }
00621 }
00622 
00623 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00624 {
00625   const HouseID house = GetHouseType(tile);
00626   const HouseSpec *hs = GetHouseSpecs(house);
00627   bool house_completed = IsHouseCompleted(tile);
00628 
00629   td->str = hs->building_name;
00630 
00631   uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
00632   if (callback_res != CALLBACK_FAILED) {
00633     StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00634     if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00635       td->str = new_name;
00636     }
00637   }
00638 
00639   if (!house_completed) {
00640     SetDParamX(td->dparam, 0, td->str);
00641     td->str = STR_2058_UNDER_CONSTRUCTION;
00642   }
00643 
00644   if (hs->grffile != NULL) {
00645     const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00646     td->grf = gc->name;
00647   }
00648 
00649   td->owner[0] = OWNER_TOWN;
00650 }
00651 
00652 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00653 {
00654   /* not used */
00655   return 0;
00656 }
00657 
00658 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00659 {
00660   /* not used */
00661 }
00662 
00663 static bool GrowTown(Town *t);
00664 
00665 static void TownTickHandler(Town *t)
00666 {
00667   if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
00668     int i = t->grow_counter - 1;
00669     if (i < 0) {
00670       if (GrowTown(t)) {
00671         i = t->growth_rate;
00672       } else {
00673         i = 0;
00674       }
00675     }
00676     t->grow_counter = i;
00677   }
00678 
00679   UpdateTownRadius(t);
00680 }
00681 
00682 void OnTick_Town()
00683 {
00684   if (_game_mode == GM_EDITOR) return;
00685 
00686   /* Make sure each town's tickhandler invocation frequency is about the
00687    * same - TOWN_GROWTH_FREQUENCY - independent on the number of towns. */
00688   for (_cur_town_iter += GetMaxTownIndex() + 1;
00689        _cur_town_iter >= TOWN_GROWTH_FREQUENCY;
00690        _cur_town_iter -= TOWN_GROWTH_FREQUENCY) {
00691     uint32 i = _cur_town_ctr;
00692 
00693     if (++_cur_town_ctr > GetMaxTownIndex())
00694       _cur_town_ctr = 0;
00695 
00696     if (IsValidTownID(i)) TownTickHandler(GetTown(i));
00697   }
00698 }
00699 
00708 static RoadBits GetTownRoadBits(TileIndex tile)
00709 {
00710   TrackBits b = GetAnyRoadTrackBits(tile, ROADTYPE_ROAD);
00711   RoadBits r = ROAD_NONE;
00712 
00713   if (b == TRACK_BIT_NONE) return r;
00714   if (b & TRACK_BIT_X)     r |= ROAD_X;
00715   if (b & TRACK_BIT_Y)     r |= ROAD_Y;
00716   if (b & TRACK_BIT_UPPER) r |= ROAD_NE | ROAD_NW;
00717   if (b & TRACK_BIT_LOWER) r |= ROAD_SE | ROAD_SW;
00718   if (b & TRACK_BIT_LEFT)  r |= ROAD_NW | ROAD_SW;
00719   if (b & TRACK_BIT_RIGHT) r |= ROAD_NE | ROAD_SE;
00720   return r;
00721 }
00722 
00733 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00734 {
00735   if (!IsValidTile(tile)) return false;
00736 
00737   /* Lookup table for the used diff values */
00738   const TileIndexDiff tid_lt[3] = {
00739     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00740     TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00741     TileOffsByDiagDir(ReverseDiagDir(dir)),
00742   };
00743 
00744   dist_multi = (dist_multi + 1) * 4;
00745   for (uint pos = 4; pos < dist_multi; pos++) {
00746     /* Go (pos / 4) tiles to the left or the right */
00747     TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00748 
00749     /* Use the current tile as origin, or go one tile backwards */
00750     if (pos & 2) cur += tid_lt[2];
00751 
00752     /* Test for roadbit parallel to dir and facing towards the middle axis */
00753     if (IsValidTile(tile + cur) &&
00754       GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00755   }
00756   return false;
00757 }
00758 
00767 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00768 {
00769   if (TileX(tile) < 2 || TileX(tile) >= MapMaxX() || TileY(tile) < 2 || TileY(tile) >= MapMaxY()) return false;
00770 
00771   Slope cur_slope, desired_slope;
00772 
00773   for (;;) {
00774     /* Check if there already is a road at this point? */
00775     if (GetTownRoadBits(tile) == ROAD_NONE) {
00776       /* No, try if we are able to build a road piece there.
00777        * If that fails clear the land, and if that fails exit.
00778        * This is to make sure that we can build a road here later. */
00779       if (CmdFailed(DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
00780           CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
00781         return false;
00782     }
00783 
00784     cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00785     if (cur_slope == SLOPE_FLAT) {
00786 no_slope:
00787       /* Tile has no slope */
00788       switch (t->layout) {
00789         default: NOT_REACHED();
00790 
00791         case TL_ORIGINAL: // Disallow the road if any neighboring tile has a road (distance: 1)
00792           return !IsNeighborRoadTile(tile, dir, 1);
00793 
00794         case TL_BETTER_ROADS: // Disallow the road if any neighboring tile has a road (distance: 1 and 2).
00795           return !IsNeighborRoadTile(tile, dir, 2);
00796       }
00797     }
00798 
00799     /* If the tile is not a slope in the right direction, then
00800      * maybe terraform some. */
00801     desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00802     if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00803       if (Chance16(1, 8)) {
00804         CommandCost res = CMD_ERROR;
00805         if (!_generating_world && Chance16(1, 10)) {
00806           /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
00807           res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00808               DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00809         }
00810         if (CmdFailed(res) && Chance16(1, 3)) {
00811           /* We can consider building on the slope, though. */
00812           goto no_slope;
00813         }
00814       }
00815       return false;
00816     }
00817     return true;
00818   }
00819 }
00820 
00821 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00822 {
00823   assert(tile < MapSize());
00824 
00825   CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00826   if (CmdFailed(r) || r.GetCost() >= (_price.terraform + 2) * 8) return false;
00827   DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00828   return true;
00829 }
00830 
00831 static void LevelTownLand(TileIndex tile)
00832 {
00833   assert(tile < MapSize());
00834 
00835   /* Don't terraform if land is plain or if there's a house there. */
00836   if (IsTileType(tile, MP_HOUSE)) return;
00837   Slope tileh = GetTileSlope(tile, NULL);
00838   if (tileh == SLOPE_FLAT) return;
00839 
00840   /* First try up, then down */
00841   if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00842     TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00843   }
00844 }
00845 
00855 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00856 {
00857   /* align the grid to the downtown */
00858   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
00859   RoadBits rcmd = ROAD_NONE;
00860 
00861   switch (t->layout) {
00862     default: NOT_REACHED();
00863 
00864     case TL_2X2_GRID:
00865       if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00866       if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00867       break;
00868 
00869     case TL_3X3_GRID:
00870       if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00871       if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00872       break;
00873   }
00874 
00875   /* Optimise only X-junctions */
00876   if (rcmd != ROAD_ALL) return rcmd;
00877 
00878   RoadBits rb_template;
00879 
00880   switch (GetTileSlope(tile, NULL)) {
00881     default:       rb_template = ROAD_ALL; break;
00882     case SLOPE_W:  rb_template = ROAD_NW | ROAD_SW; break;
00883     case SLOPE_SW: rb_template = ROAD_Y  | ROAD_SW; break;
00884     case SLOPE_S:  rb_template = ROAD_SW | ROAD_SE; break;
00885     case SLOPE_SE: rb_template = ROAD_X  | ROAD_SE; break;
00886     case SLOPE_E:  rb_template = ROAD_SE | ROAD_NE; break;
00887     case SLOPE_NE: rb_template = ROAD_Y  | ROAD_NE; break;
00888     case SLOPE_N:  rb_template = ROAD_NE | ROAD_NW; break;
00889     case SLOPE_NW: rb_template = ROAD_X  | ROAD_NW; break;
00890     case SLOPE_STEEP_W:
00891     case SLOPE_STEEP_S:
00892     case SLOPE_STEEP_E:
00893     case SLOPE_STEEP_N:
00894       rb_template = ROAD_NONE;
00895       break;
00896   }
00897 
00898   /* Stop if the template is compatible to the growth dir */
00899   if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00900   /* If not generate a straight road in the direction of the growth */
00901   return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00902 }
00903 
00914 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00915 {
00916   /* We can't look further than that. */
00917   if (TileX(tile) < 2 || TileY(tile) < 2 || MapMaxX() <= TileX(tile) || MapMaxY() <= TileY(tile)) return false;
00918 
00919   uint counter = 0; // counts the house neighbor tiles
00920 
00921   /* Check the tiles E,N,W and S of the current tile for houses */
00922   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00923 
00924     if (IsTileType(TileAddByDiagDir(tile, dir), MP_HOUSE)) counter++;
00925 
00926     /* If there are enough neighbors stop here */
00927     if (counter >= 3) {
00928       if (BuildTownHouse(t, tile)) {
00929         _grow_town_result = GROWTH_SUCCEED;
00930         return true;
00931       }
00932       return false;
00933     }
00934   }
00935   return false;
00936 }
00937 
00946 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00947 {
00948   if (CmdSucceeded(DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD))) {
00949     _grow_town_result = GROWTH_SUCCEED;
00950     return true;
00951   }
00952   return false;
00953 }
00954 
00965 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00966 {
00967   assert(bridge_dir < DIAGDIR_END);
00968 
00969   const Slope slope = GetTileSlope(tile, NULL);
00970   if (slope == SLOPE_FLAT) return false; // no slope, no bridge
00971 
00972   /* Make sure the direction is compatible with the slope.
00973    * Well we check if the slope has an up bit set in the
00974    * reverse direction. */
00975   if (HASBITS(slope, InclinedSlope(bridge_dir))) return false;
00976 
00977   /* Assure that the bridge is connectable to the start side */
00978   if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00979 
00980   /* We are in the right direction */
00981   uint8 bridge_length = 0;      // This value stores the length of the possible bridge
00982   TileIndex bridge_tile = tile; // Used to store the other waterside
00983 
00984   const int delta = TileOffsByDiagDir(bridge_dir);
00985   do {
00986     if (bridge_length++ >= 11) {
00987       /* Max 11 tile long bridges */
00988       return false;
00989     }
00990     bridge_tile += delta;
00991   } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00992 
00993   /* no water tiles in between? */
00994   if (bridge_length == 1) return false;
00995 
00996   for (uint8 times = 0; times <= 22; times++) {
00997     byte bridge_type = RandomRange(MAX_BRIDGES - 1);
00998 
00999     /* Can we actually build the bridge? */
01000     if (CmdSucceeded(DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
01001       DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
01002       _grow_town_result = GROWTH_SUCCEED;
01003       return true;
01004     }
01005   }
01006   /* Quit if it selecting an appropiate bridge type fails a large number of times. */
01007   return false;
01008 }
01009 
01027 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01028 {
01029   RoadBits rcmd = ROAD_NONE;  // RoadBits for the road construction command
01030   TileIndex tile = *tile_ptr; // The main tile on which we base our growth
01031 
01032   assert(tile < MapSize());
01033 
01034   if (cur_rb == ROAD_NONE) {
01035     /* Tile has no road. First reset the status counter
01036      * to say that this is the last iteration. */
01037     _grow_town_result = GROWTH_SEARCH_STOPPED;
01038 
01039     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01040 
01041     /* Remove hills etc */
01042     if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01043 
01044     /* Is a road allowed here? */
01045     switch (t1->layout) {
01046       default: NOT_REACHED();
01047 
01048       case TL_3X3_GRID:
01049       case TL_2X2_GRID:
01050         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01051         if (rcmd == ROAD_NONE) return;
01052         break;
01053 
01054       case TL_BETTER_ROADS:
01055       case TL_ORIGINAL:
01056         if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01057 
01058         DiagDirection source_dir = ReverseDiagDir(target_dir);
01059 
01060         if (Chance16(1, 4)) {
01061           /* Randomize a new target dir */
01062           do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01063         }
01064 
01065         if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01066           /* A road is not allowed to continue the randomized road,
01067            *  return if the road we're trying to build is curved. */
01068           if (target_dir != ReverseDiagDir(source_dir)) return;
01069 
01070           /* Return if neither side of the new road is a house */
01071           if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01072               !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01073             return;
01074           }
01075 
01076           /* That means that the road is only allowed if there is a house
01077            *  at any side of the new road. */
01078         }
01079 
01080         rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01081         break;
01082     }
01083 
01084   } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01085     /* Continue building on a partial road.
01086      * Should be allways OK, so we only generate
01087      * the fitting RoadBits */
01088     _grow_town_result = GROWTH_SEARCH_STOPPED;
01089 
01090     if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01091 
01092     switch (t1->layout) {
01093       default: NOT_REACHED();
01094 
01095       case TL_3X3_GRID:
01096       case TL_2X2_GRID:
01097         rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01098         break;
01099 
01100       case TL_BETTER_ROADS:
01101       case TL_ORIGINAL:
01102         rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01103         break;
01104     }
01105   } else {
01106     bool allow_house = true; // Value which decides if we want to construct a house
01107 
01108     /* Reached a tunnel/bridge? Then continue at the other side of it. */
01109     if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01110       if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01111         *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01112       }
01113       return;
01114     }
01115 
01116     /* Possibly extend the road in a direction.
01117      * Randomize a direction and if it has a road, bail out. */
01118     target_dir = RandomDiagDir();
01119     if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01120 
01121     /* This is the tile we will reach if we extend to this direction. */
01122     TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
01123 
01124     /* Don't walk into water. */
01125     if (IsWaterTile(house_tile)) return;
01126 
01127     if (!IsValidTile(house_tile) || !IsValidTile(house_tile + TileOffsByDiagDir(target_dir))) return;
01128 
01129     if (_settings_game.economy.allow_town_roads || _generating_world) {
01130       switch (t1->layout) {
01131         default: NOT_REACHED();
01132 
01133         case TL_3X3_GRID: // Use 2x2 grid afterwards!
01134           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01135           /* FALL THROUGH */
01136 
01137         case TL_2X2_GRID:
01138           rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01139           allow_house = (rcmd == ROAD_NONE);
01140           break;
01141 
01142         case TL_BETTER_ROADS: // Use original afterwards!
01143           GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01144           /* FALL THROUGH */
01145 
01146         case TL_ORIGINAL:
01147           /* Allow a house at the edge. 60% chance or
01148            * always ok if no road allowed. */
01149           rcmd = DiagDirToRoadBits(target_dir);
01150           allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01151           break;
01152       }
01153     }
01154 
01155     if (allow_house) {
01156       /* Build a house, but not if there already is a house there. */
01157       if (!IsTileType(house_tile, MP_HOUSE)) {
01158         /* Level the land if possible */
01159         if (Chance16(1, 6)) LevelTownLand(house_tile);
01160 
01161         /* And build a house.
01162          * Set result to -1 if we managed to build it. */
01163         if (BuildTownHouse(t1, house_tile)) {
01164           _grow_town_result = GROWTH_SUCCEED;
01165         }
01166       }
01167       return;
01168     }
01169 
01170     _grow_town_result = GROWTH_SEARCH_STOPPED;
01171   }
01172 
01173   /* Return if a water tile */
01174   if (IsWaterTile(tile)) return;
01175 
01176   /* Make the roads look nicer */
01177   rcmd = CleanUpRoadBits(tile, rcmd);
01178   if (rcmd == ROAD_NONE) return;
01179 
01180   /* Only use the target direction for bridges to ensure they're connected.
01181    * The target_dir is as computed previously according to town layout, so
01182    * it will match it perfectly. */
01183   if (GrowTownWithBridge(t1, tile, target_dir)) return;
01184 
01185   GrowTownWithRoad(t1, tile, rcmd);
01186 }
01187 
01193 static int GrowTownAtRoad(Town *t, TileIndex tile)
01194 {
01195   /* Special case.
01196    * @see GrowTownInTile Check the else if
01197    */
01198   DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
01199 
01200   assert(tile < MapSize());
01201 
01202   /* Number of times to search.
01203    * Better roads, 2X2 and 3X3 grid grow quite fast so we give
01204    * them a little handicap. */
01205   switch (t->layout) {
01206     case TL_BETTER_ROADS:
01207       _grow_town_result = 10 + t->num_houses * 2 / 9;
01208       break;
01209 
01210     case TL_3X3_GRID:
01211     case TL_2X2_GRID:
01212       _grow_town_result = 10 + t->num_houses * 1 / 9;
01213       break;
01214 
01215     default:
01216       _grow_town_result = 10 + t->num_houses * 4 / 9;
01217       break;
01218   }
01219 
01220   do {
01221     RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
01222 
01223     /* Try to grow the town from this point */
01224     GrowTownInTile(&tile, cur_rb, target_dir, t);
01225 
01226     /* Exclude the source position from the bitmask
01227      * and return if no more road blocks available */
01228     cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01229     if (cur_rb == ROAD_NONE)
01230       return _grow_town_result;
01231 
01232     /* Select a random bit from the blockmask, walk a step
01233      * and continue the search from there. */
01234     do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01235     tile = TileAddByDiagDir(tile, target_dir);
01236 
01237     if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01238       /* Don't allow building over roads of other cities */
01239       if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && GetTownByTile(tile) != t) {
01240         _grow_town_result = GROWTH_SUCCEED;
01241       } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01242         /* If we are in the SE, and this road-piece has no town owner yet, it just found an
01243          * owner :) (happy happy happy road now) */
01244         SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01245         SetTownIndex(tile, t->index);
01246       }
01247     }
01248 
01249     /* Max number of times is checked. */
01250   } while (--_grow_town_result >= 0);
01251 
01252   return (_grow_town_result == -2);
01253 }
01254 
01262 static RoadBits GenRandomRoadBits()
01263 {
01264   uint32 r = Random();
01265   uint a = GB(r, 0, 2);
01266   uint b = GB(r, 8, 2);
01267   if (a == b) b ^= 2;
01268   return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01269 }
01270 
01275 static bool GrowTown(Town *t)
01276 {
01277   static const TileIndexDiffC _town_coord_mod[] = {
01278     {-1,  0},
01279     { 1,  1},
01280     { 1, -1},
01281     {-1, -1},
01282     {-1,  0},
01283     { 0,  2},
01284     { 2,  0},
01285     { 0, -2},
01286     {-1, -1},
01287     {-2,  2},
01288     { 2,  2},
01289     { 2, -2},
01290     { 0,  0}
01291   };
01292 
01293   /* Current "company" is a town */
01294   CompanyID old_company = _current_company;
01295   _current_company = OWNER_TOWN;
01296 
01297   TileIndex tile = t->xy; // The tile we are working with ATM
01298 
01299   /* Find a road that we can base the construction on. */
01300   const TileIndexDiffC *ptr;
01301   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01302     if (GetTownRoadBits(tile) != ROAD_NONE) {
01303       int r = GrowTownAtRoad(t, tile);
01304       _current_company = old_company;
01305       return r != 0;
01306     }
01307     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01308   }
01309 
01310   /* No road available, try to build a random road block by
01311    * clearing some land and then building a road there. */
01312   tile = t->xy;
01313   for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01314     /* Only work with plain land that not already has a house */
01315     if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01316       if (CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR))) {
01317         DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01318         _current_company = old_company;
01319         return true;
01320       }
01321     }
01322     tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01323   }
01324 
01325   _current_company = old_company;
01326   return false;
01327 }
01328 
01329 void UpdateTownRadius(Town *t)
01330 {
01331   static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01332     {  4,  0,  0,  0,  0}, // 0
01333     { 16,  0,  0,  0,  0},
01334     { 25,  0,  0,  0,  0},
01335     { 36,  0,  0,  0,  0},
01336     { 49,  0,  4,  0,  0},
01337     { 64,  0,  4,  0,  0}, // 20
01338     { 64,  0,  9,  0,  1},
01339     { 64,  0,  9,  0,  4},
01340     { 64,  0, 16,  0,  4},
01341     { 81,  0, 16,  0,  4},
01342     { 81,  0, 16,  0,  4}, // 40
01343     { 81,  0, 25,  0,  9},
01344     { 81, 36, 25,  0,  9},
01345     { 81, 36, 25, 16,  9},
01346     { 81, 49,  0, 25,  9},
01347     { 81, 64,  0, 25,  9}, // 60
01348     { 81, 64,  0, 36,  9},
01349     { 81, 64,  0, 36, 16},
01350     {100, 81,  0, 49, 16},
01351     {100, 81,  0, 49, 25},
01352     {121, 81,  0, 49, 25}, // 80
01353     {121, 81,  0, 49, 25},
01354     {121, 81,  0, 49, 36}, // 88
01355   };
01356 
01357   if (t->num_houses < 92) {
01358     memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01359   } else {
01360     int mass = t->num_houses / 8;
01361     /* Actually we are proportional to sqrt() but that's right because we are covering an area.
01362      * The offsets are to make sure the radii do not decrease in size when going from the table
01363      * to the calculated value.*/
01364     t->squared_town_zone_radius[0] = mass * 15 - 40;
01365     t->squared_town_zone_radius[1] = mass * 9 - 15;
01366     t->squared_town_zone_radius[2] = 0;
01367     t->squared_town_zone_radius[3] = mass * 5 - 5;
01368     t->squared_town_zone_radius[4] = mass * 3 + 5;
01369   }
01370 }
01371 
01372 extern int _nb_orig_names;
01373 
01378 struct TownNameParams {
01379   uint32 grfid;        
01380   uint16 townnametype; 
01381   bool grf;            
01382 
01383   TownNameParams(byte town_name)
01384   {
01385     this->grf = town_name >= _nb_orig_names;
01386     this->grfid = this->grf ? GetGRFTownNameId(town_name - _nb_orig_names) : 0;
01387     this->townnametype = this->grf ? GetGRFTownNameType(town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + town_name;
01388   }
01389 };
01390 
01397 static bool VerifyTownName(uint32 r, const TownNameParams *par)
01398 {
01399   /* reserve space for extra unicode character and terminating '\0' */
01400   char buf1[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
01401   char buf2[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
01402 
01403   SetDParam(0, r);
01404   if (par->grf && par->grfid != 0) {
01405     GRFTownNameGenerate(buf1, par->grfid, par->townnametype, r, lastof(buf1));
01406   } else {
01407     GetString(buf1, par->townnametype, lastof(buf1));
01408   }
01409 
01410   /* Check size and width */
01411   if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES) return false;
01412 
01413   const Town *t;
01414   FOR_ALL_TOWNS(t) {
01415     /* We can't just compare the numbers since
01416      * several numbers may map to a single name. */
01417     SetDParam(0, t->index);
01418     GetString(buf2, STR_TOWN, lastof(buf2));
01419     if (strcmp(buf1, buf2) == 0) return false;
01420   }
01421 
01422   return true;
01423 }
01424 
01430 bool GenerateTownName(uint32 *townnameparts)
01431 {
01432   /* Do not set too low tries, since when we run out of names, we loop
01433    * for #tries only one time anyway - then we stop generating more
01434    * towns. Do not show it too high neither, since looping through all
01435    * the other towns may take considerable amount of time (10000 is
01436    * too much). */
01437   int tries = 1000;
01438   TownNameParams par(_settings_game.game_creation.town_name);
01439 
01440   assert(townnameparts != NULL);
01441 
01442   for (;;) {
01443     uint32 r = InteractiveRandom();
01444 
01445     if (!VerifyTownName(r, &par)) {
01446       if (tries-- < 0) return false;
01447       continue;
01448     }
01449 
01450     *townnameparts = r;
01451     return true;
01452   }
01453 }
01454 
01455 void UpdateTownMaxPass(Town *t)
01456 {
01457   t->max_pass = t->population >> 3;
01458   t->max_mail = t->population >> 4;
01459 }
01460 
01470 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01471 {
01472   t->xy = tile;
01473   t->num_houses = 0;
01474   t->time_until_rebuild = 10;
01475   UpdateTownRadius(t);
01476   t->flags12 = 0;
01477   t->population = 0;
01478   t->grow_counter = 0;
01479   t->growth_rate = 250;
01480   t->new_max_pass = 0;
01481   t->new_max_mail = 0;
01482   t->new_act_pass = 0;
01483   t->new_act_mail = 0;
01484   t->max_pass = 0;
01485   t->max_mail = 0;
01486   t->act_pass = 0;
01487   t->act_mail = 0;
01488 
01489   t->pct_pass_transported = 0;
01490   t->pct_mail_transported = 0;
01491   t->fund_buildings_months = 0;
01492   t->new_act_food = 0;
01493   t->new_act_water = 0;
01494   t->act_food = 0;
01495   t->act_water = 0;
01496 
01497   for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01498 
01499   t->have_ratings = 0;
01500   t->exclusivity = INVALID_COMPANY;
01501   t->exclusive_counter = 0;
01502   t->statues = 0;
01503 
01504   if (_settings_game.game_creation.town_name < _nb_orig_names) {
01505     /* Original town name */
01506     t->townnamegrfid = 0;
01507     t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01508   } else {
01509     /* Newgrf town name */
01510     t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name  - _nb_orig_names);
01511     t->townnametype  = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01512   }
01513   t->townnameparts = townnameparts;
01514 
01515   UpdateTownVirtCoord(t);
01516   InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01517 
01518   t->InitializeLayout(layout);
01519 
01520   t->larger_town = city;
01521 
01522   int x = (int)size * 16 + 3;
01523   if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
01524   if (city) x *= _settings_game.economy.initial_city_size;
01525 
01526   t->num_houses += x;
01527   UpdateTownRadius(t);
01528 
01529   int i = x * 4;
01530   do {
01531     GrowTown(t);
01532   } while (--i);
01533 
01534   t->num_houses -= x;
01535   UpdateTownRadius(t);
01536   UpdateTownMaxPass(t);
01537   UpdateAirportsNoise();
01538 }
01539 
01550 CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01551 {
01552   /* Only in the scenario editor */
01553   if (_game_mode != GM_EDITOR) return CMD_ERROR;
01554 
01555   TownSize size = (TownSize)GB(p1, 0, 2);
01556   bool city = HasBit(p1, 2);
01557   TownLayout layout = (TownLayout)GB(p1, 3, 3);
01558   TownNameParams par(_settings_game.game_creation.town_name);
01559   uint32 townnameparts = p2;
01560 
01561   if (size > TS_RANDOM) return CMD_ERROR;
01562   if (layout > TL_RANDOM) return CMD_ERROR;
01563   if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
01564 
01565   /* Check if too close to the edge of map */
01566   if (DistanceFromEdge(tile) < 12) {
01567     return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
01568   }
01569 
01570   /* Check distance to all other towns. */
01571   if (IsCloseToTown(tile, 20)) {
01572     return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
01573   }
01574 
01575   /* Can only build on clear flat areas, possibly with trees. */
01576   if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01577     return_cmd_error(STR_0239_SITE_UNSUITABLE);
01578   }
01579 
01580   /* Allocate town struct */
01581   if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
01582 
01583   /* Create the town */
01584   if (flags & DC_EXEC) {
01585     Town *t = new Town(tile);
01586     _generating_world = true;
01587     UpdateNearestTownForRoadTiles(true);
01588     DoCreateTown(t, tile, townnameparts, size, city, layout);
01589     UpdateNearestTownForRoadTiles(false);
01590     _generating_world = false;
01591   }
01592   return CommandCost();
01593 }
01594 
01595 Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
01596 {
01597   if (!Town::CanAllocateItem()) return NULL;
01598 
01599   do {
01600     /* Generate a tile index not too close from the edge */
01601     TileIndex tile = RandomTile();
01602     switch (layout) {
01603       case TL_2X2_GRID:
01604         tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01605         break;
01606       case TL_3X3_GRID:
01607         tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01608         break;
01609       default: break;
01610     }
01611     if (DistanceFromEdge(tile) < 20) continue;
01612 
01613     /* Make sure the tile is plain */
01614     if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
01615 
01616     /* Check not too close to a town */
01617     if (IsCloseToTown(tile, 20)) continue;
01618 
01619     uint32 townnameparts;
01620 
01621     /* Get a unique name for the town. */
01622     if (!GenerateTownName(&townnameparts)) break;
01623 
01624     /* Allocate a town struct */
01625     Town *t = new Town(tile);
01626 
01627     DoCreateTown(t, tile, townnameparts, size, city, layout);
01628     return t;
01629   } while (--attempts != 0);
01630 
01631   return NULL;
01632 }
01633 
01634 static const byte _num_initial_towns[4] = {5, 11, 23, 46};  // very low, low, normal, high
01635 
01636 bool GenerateTowns(TownLayout layout)
01637 {
01638   uint num = 0;
01639   uint difficulty = _settings_game.difficulty.number_towns;
01640   uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01641 
01642   SetGeneratingWorldProgress(GWP_TOWN, n);
01643 
01644   do {
01645     bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01646     IncreaseGeneratingWorldProgress(GWP_TOWN);
01647     /* try 20 times to create a random-sized town for the first loop. */
01648     if (CreateRandomTown(20, TS_RANDOM, city, layout) != NULL) num++;
01649   } while (--n);
01650 
01651   /* give it a last try, but now more aggressive */
01652   if (num == 0 && CreateRandomTown(10000, TS_RANDOM, _settings_game.economy.larger_towns != 0, layout) == NULL) {
01653     if (GetNumTowns() == 0) {
01654       if (_game_mode != GM_EDITOR) {
01655         extern StringID _switch_mode_errorstr;
01656         _switch_mode_errorstr = STR_COULD_NOT_CREATE_TOWN;
01657       }
01658 
01659       return false;
01660     }
01661   }
01662 
01663   return true;
01664 }
01665 
01666 
01672 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01673 {
01674   uint dist = DistanceSquare(tile, t->xy);
01675 
01676   if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01677 
01678   HouseZonesBits smallest = HZB_TOWN_EDGE;
01679   for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01680     if (dist < t->squared_town_zone_radius[i]) smallest = i;
01681   }
01682 
01683   return smallest;
01684 }
01685 
01696 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01697 {
01698   CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01699 
01700   assert(CmdSucceeded(cc));
01701 
01702   IncreaseBuildingCount(t, type);
01703   MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01704   if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01705 
01706   MarkTileDirtyByTile(tile);
01707 }
01708 
01709 
01720 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01721 {
01722   BuildingFlags size = GetHouseSpecs(type)->building_flags;
01723 
01724   ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01725   if (size & BUILDING_2_TILES_Y)   ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01726   if (size & BUILDING_2_TILES_X)   ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01727   if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01728 }
01729 
01730 
01739 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01740 {
01741   /* cannot build on these slopes... */
01742   Slope slope = GetTileSlope(tile, NULL);
01743   if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01744 
01745   /* building under a bridge? */
01746   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01747 
01748   /* do not try to build over house owned by another town */
01749   if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01750 
01751   /* can we clear the land? */
01752   return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
01753 }
01754 
01755 
01765 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01766 {
01767   if (!CanBuildHouseHere(tile, town, noslope)) return false;
01768 
01769   /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
01770   if (GetTileMaxZ(tile) != z) return false;
01771 
01772   return true;
01773 }
01774 
01775 
01785 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01786 {
01787   /* we need to check this tile too because we can be at different tile now */
01788   if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01789 
01790   for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01791     tile += TileOffsByDiagDir(d);
01792     if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01793   }
01794 
01795   return true;
01796 }
01797 
01798 
01806 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01807 {
01808   /* Allow towns everywhere when we don't build roads */
01809   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01810 
01811   TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01812 
01813   switch (t->layout) {
01814     case TL_2X2_GRID:
01815       if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01816       break;
01817 
01818     case TL_3X3_GRID:
01819       if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01820       break;
01821 
01822     default:
01823       break;
01824   }
01825 
01826   return true;
01827 }
01828 
01829 
01837 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01838 {
01839   /* Allow towns everywhere when we don't build roads */
01840   if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01841 
01842   /* MapSize() is sure dividable by both MapSizeX() and MapSizeY(),
01843    * so to do only one memory access, use MapSize() */
01844   uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01845   uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01846 
01847   switch (t->layout) {
01848     case TL_2X2_GRID:
01849       if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01850       break;
01851 
01852     case TL_3X3_GRID:
01853       if ((dx % 4) < 2 || (dy % 4) < 2) return false;
01854       break;
01855 
01856     default:
01857       break;
01858   }
01859 
01860   return true;
01861 }
01862 
01863 
01873 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
01874 {
01875   /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
01876 
01877   TileIndex tile2 = *tile + TileOffsByDiagDir(second);
01878   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
01879 
01880   tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
01881   if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
01882     *tile = tile2;
01883     return true;
01884   }
01885 
01886   return false;
01887 }
01888 
01889 
01898 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
01899 {
01900   TileIndex tile2 = *tile;
01901 
01902   for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
01903     if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
01904       *tile = tile2;
01905       return true;
01906     }
01907     if (d == DIAGDIR_END) break;
01908     tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
01909   }
01910 
01911   return false;
01912 }
01913 
01914 
01921 static bool BuildTownHouse(Town *t, TileIndex tile)
01922 {
01923   /* forbidden building here by town layout */
01924   if (!TownLayoutAllowsHouseHere(t, tile)) return false;
01925 
01926   /* no house allowed at all, bail out */
01927   if (!CanBuildHouseHere(tile, t->index, false)) return false;
01928 
01929   uint z;
01930   Slope slope = GetTileSlope(tile, &z);
01931 
01932   /* Get the town zone type of the current tile, as well as the climate.
01933    * This will allow to easily compare with the specs of the new house to build */
01934   HouseZonesBits rad = GetTownRadiusGroup(t, tile);
01935 
01936   /* Above snow? */
01937   int land = _settings_game.game_creation.landscape;
01938   if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
01939 
01940   uint bitmask = (1 << rad) + (1 << (land + 12));
01941 
01942   /* bits 0-4 are used
01943    * bits 11-15 are used
01944    * bits 5-10 are not used. */
01945   HouseID houses[HOUSE_MAX];
01946   uint num = 0;
01947   uint probs[HOUSE_MAX];
01948   uint probability_max = 0;
01949 
01950   /* Generate a list of all possible houses that can be built. */
01951   for (uint i = 0; i < HOUSE_MAX; i++) {
01952     const HouseSpec *hs = GetHouseSpecs(i);
01953 
01954     /* Verify that the candidate house spec matches the current tile status */
01955     if ((~hs->building_availability & bitmask) != 0 || !hs->enabled) continue;
01956 
01957     /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
01958     if (hs->class_id != HOUSE_NO_CLASS) {
01959       /* id_count is always <= class_count, so it doesn't need to be checked */
01960       if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
01961     } else {
01962       /* If the house has no class, check id_count instead */
01963       if (t->building_counts.id_count[i] == UINT16_MAX) continue;
01964     }
01965 
01966     /* Without NewHouses, all houses have probability '1' */
01967     uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
01968     probability_max += cur_prob;
01969     probs[num] = cur_prob;
01970     houses[num++] = (HouseID)i;
01971   }
01972 
01973   uint maxz = GetTileMaxZ(tile);
01974 
01975   while (probability_max > 0) {
01976     uint r = RandomRange(probability_max);
01977     uint i;
01978     for (i = 0; i < num; i++) {
01979       if (probs[i] > r) break;
01980       r -= probs[i];
01981     }
01982 
01983     HouseID house = houses[i];
01984     probability_max -= probs[i];
01985 
01986     /* remove tested house from the set */
01987     num--;
01988     houses[i] = houses[num];
01989     probs[i] = probs[num];
01990 
01991     const HouseSpec *hs = GetHouseSpecs(house);
01992 
01993     if (_loaded_newgrf_features.has_newhouses) {
01994       if (hs->override != 0) {
01995         house = hs->override;
01996         hs = GetHouseSpecs(house);
01997       }
01998 
01999       if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world && _game_mode != GM_EDITOR) continue;
02000     }
02001 
02002     if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02003 
02004     /* Special houses that there can be only one of. */
02005     uint oneof = 0;
02006 
02007     if (hs->building_flags & BUILDING_IS_CHURCH) {
02008       SetBit(oneof, TOWN_HAS_CHURCH);
02009     } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02010       SetBit(oneof, TOWN_HAS_STADIUM);
02011     }
02012 
02013     if (HASBITS(t->flags12, oneof)) continue;
02014 
02015     /* Make sure there is no slope? */
02016     bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02017     if (noslope && slope != SLOPE_FLAT) continue;
02018 
02019     if (hs->building_flags & TILE_SIZE_2x2) {
02020       if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02021     } else if (hs->building_flags & TILE_SIZE_2x1) {
02022       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02023     } else if (hs->building_flags & TILE_SIZE_1x2) {
02024       if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02025     } else {
02026       /* 1x1 house checks are already done */
02027     }
02028 
02029     if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02030       uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
02031       if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02032     }
02033 
02034     /* build the house */
02035     t->num_houses++;
02036 
02037     /* Special houses that there can be only one of. */
02038     t->flags12 |= oneof;
02039 
02040     byte construction_counter = 0;
02041     byte construction_stage = 0;
02042 
02043     if (_generating_world || _game_mode == GM_EDITOR) {
02044       uint32 r = Random();
02045 
02046       construction_stage = TOWN_HOUSE_COMPLETED;
02047       if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02048 
02049       if (construction_stage == TOWN_HOUSE_COMPLETED) {
02050         ChangePopulation(t, hs->population);
02051       } else {
02052         construction_counter = GB(r, 2, 2);
02053       }
02054     }
02055 
02056     MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02057 
02058     return true;
02059   }
02060 
02061   return false;
02062 }
02063 
02070 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02071 {
02072   assert(IsTileType(tile, MP_HOUSE));
02073   DecreaseBuildingCount(t, house);
02074   DoClearSquare(tile);
02075   DeleteAnimatedTile(tile);
02076 }
02077 
02085 TileIndexDiff GetHouseNorthPart(HouseID &house)
02086 {
02087   if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
02088     if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
02089       house--;
02090       return TileDiffXY(-1, 0);
02091     } else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02092       house--;
02093       return TileDiffXY(0, -1);
02094     } else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02095       house -= 2;
02096       return TileDiffXY(-1, 0);
02097     } else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02098       house -= 3;
02099       return TileDiffXY(-1, -1);
02100     }
02101   }
02102   return 0;
02103 }
02104 
02105 void ClearTownHouse(Town *t, TileIndex tile)
02106 {
02107   assert(IsTileType(tile, MP_HOUSE));
02108 
02109   HouseID house = GetHouseType(tile);
02110 
02111   /* need to align the tile to point to the upper left corner of the house */
02112   tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
02113 
02114   const HouseSpec *hs = GetHouseSpecs(house);
02115 
02116   /* Remove population from the town if the house is finished. */
02117   if (IsHouseCompleted(tile)) {
02118     ChangePopulation(t, -hs->population);
02119   }
02120 
02121   t->num_houses--;
02122 
02123   /* Clear flags for houses that only may exist once/town. */
02124   if (hs->building_flags & BUILDING_IS_CHURCH) {
02125     ClrBit(t->flags12, TOWN_HAS_CHURCH);
02126   } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02127     ClrBit(t->flags12, TOWN_HAS_STADIUM);
02128   }
02129 
02130   /* Do the actual clearing of tiles */
02131   uint eflags = hs->building_flags;
02132   DoClearTownHouseHelper(tile, t, house);
02133   if (eflags & BUILDING_2_TILES_Y)   DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02134   if (eflags & BUILDING_2_TILES_X)   DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02135   if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02136 }
02137 
02138 static bool IsUniqueTownName(const char *name)
02139 {
02140   const Town *t;
02141 
02142   FOR_ALL_TOWNS(t) {
02143     if (t->name != NULL && strcmp(t->name, name) == 0) return false;
02144   }
02145 
02146   return true;
02147 }
02148 
02155 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02156 {
02157   if (!IsValidTownID(p1)) return CMD_ERROR;
02158 
02159   bool reset = StrEmpty(text);
02160 
02161   if (!reset) {
02162     if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02163     if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
02164   }
02165 
02166   if (flags & DC_EXEC) {
02167     Town *t = GetTown(p1);
02168 
02169     free(t->name);
02170     t->name = reset ? NULL : strdup(text);
02171 
02172     UpdateTownVirtCoord(t);
02173     InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02174     UpdateAllStationVirtCoord();
02175     UpdateAllWaypointSigns();
02176     MarkWholeScreenDirty();
02177   }
02178   return CommandCost();
02179 }
02180 
02182 void ExpandTown(Town *t)
02183 {
02184   /* Warn the users if towns are not allowed to build roads,
02185    * but do this only onces per openttd run. */
02186   static bool warned_no_roads = false;
02187   if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02188     ShowErrorMessage(INVALID_STRING_ID, STR_TOWN_EXPAND_WARN_NO_ROADS, 0, 0);
02189     warned_no_roads = true;
02190   }
02191 
02192   /* The more houses, the faster we grow */
02193   uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02194   t->num_houses += amount;
02195   UpdateTownRadius(t);
02196 
02197   uint n = amount * 10;
02198   do GrowTown(t); while (--n);
02199 
02200   t->num_houses -= amount;
02201   UpdateTownRadius(t);
02202 
02203   UpdateTownMaxPass(t);
02204 }
02205 
02206 extern const byte _town_action_costs[8] = {
02207   2, 4, 9, 35, 48, 53, 117, 175
02208 };
02209 
02210 static void TownActionAdvertiseSmall(Town *t)
02211 {
02212   ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02213 }
02214 
02215 static void TownActionAdvertiseMedium(Town *t)
02216 {
02217   ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02218 }
02219 
02220 static void TownActionAdvertiseLarge(Town *t)
02221 {
02222   ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02223 }
02224 
02225 static void TownActionRoadRebuild(Town *t)
02226 {
02227   t->road_build_months = 6;
02228 
02229   char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02230   SetDParam(0, _current_company);
02231   GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02232 
02233   char *cn = strdup(company_name);
02234   SetDParam(0, t->index);
02235   SetDParamStr(1, cn);
02236 
02237   AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING, NS_GENERAL, t->xy, 0, cn);
02238 }
02239 
02240 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
02241 {
02242   /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
02243   if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02244   /* Don't build statues under bridges. */
02245   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02246 
02247   if (!IsTileType(tile, MP_HOUSE) &&
02248       !IsTileType(tile, MP_CLEAR) &&
02249       !IsTileType(tile, MP_TREES)) {
02250     return false;
02251   }
02252 
02253   CompanyID old = _current_company;
02254   _current_company = OWNER_NONE;
02255   CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02256   _current_company = old;
02257 
02258   if (CmdFailed(r)) return false;
02259 
02260   MakeStatue(tile, _current_company, town_id);
02261   MarkTileDirtyByTile(tile);
02262 
02263   return true;
02264 }
02265 
02272 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02273 {
02274   TownID *town_id = (TownID *)user_data;
02275   return DoBuildStatueOfCompany(tile, *town_id);
02276 }
02277 
02283 static void TownActionBuildStatue(Town *t)
02284 {
02285   TileIndex tile = t->xy;
02286 
02287   if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
02288     SetBit(t->statues, _current_company); // Once found and built, "inform" the Town
02289   }
02290 }
02291 
02292 static void TownActionFundBuildings(Town *t)
02293 {
02294   /* Build next tick */
02295   t->grow_counter = 1;
02296   /* If we were not already growing */
02297   SetBit(t->flags12, TOWN_IS_FUNDED);
02298   /* And grow for 3 months */
02299   t->fund_buildings_months = 3;
02300 }
02301 
02302 static void TownActionBuyRights(Town *t)
02303 {
02304   /* Check if it's allowed to by the rights */
02305   if (!_settings_game.economy.exclusive_rights) return;
02306 
02307   t->exclusive_counter = 12;
02308   t->exclusivity = _current_company;
02309 
02310   ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02311 }
02312 
02313 static void TownActionBribe(Town *t)
02314 {
02315   if (Chance16(1, 14)) {
02316     /* set as unwanted for 6 months */
02317     t->unwanted[_current_company] = 6;
02318 
02319     /* set all close by station ratings to 0 */
02320     Station *st;
02321     FOR_ALL_STATIONS(st) {
02322       if (st->town == t && st->owner == _current_company) {
02323         for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02324       }
02325     }
02326 
02327     /* only show errormessage to the executing player. All errors are handled command.c
02328      * but this is special, because it can only 'fail' on a DC_EXEC */
02329     if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
02330 
02331     /* decrease by a lot!
02332      * ChangeTownRating is only for stuff in demolishing. Bribe failure should
02333      * be independent of any cheat settings
02334      */
02335     if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02336       t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02337       InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02338     }
02339   } else {
02340     ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02341   }
02342 }
02343 
02344 typedef void TownActionProc(Town *t);
02345 static TownActionProc * const _town_action_proc[] = {
02346   TownActionAdvertiseSmall,
02347   TownActionAdvertiseMedium,
02348   TownActionAdvertiseLarge,
02349   TownActionRoadRebuild,
02350   TownActionBuildStatue,
02351   TownActionFundBuildings,
02352   TownActionBuyRights,
02353   TownActionBribe
02354 };
02355 
02356 enum TownActions {
02357   TACT_NONE             = 0x00,
02358 
02359   TACT_ADVERTISE_SMALL  = 0x01,
02360   TACT_ADVERTISE_MEDIUM = 0x02,
02361   TACT_ADVERTISE_LARGE  = 0x04,
02362   TACT_ROAD_REBUILD     = 0x08,
02363   TACT_BUILD_STATUE     = 0x10,
02364   TACT_FOUND_BUILDINGS  = 0x20,
02365   TACT_BUY_RIGHTS       = 0x40,
02366   TACT_BRIBE            = 0x80,
02367 
02368   TACT_ADVERTISE        = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
02369   TACT_CONSTRUCTION     = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
02370   TACT_FUNDS            = TACT_BUY_RIGHTS | TACT_BRIBE,
02371   TACT_ALL              = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
02372 };
02373 
02374 DECLARE_ENUM_AS_BIT_SET(TownActions);
02375 
02382 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02383 {
02384   int num = 0;
02385   TownActions buttons = TACT_NONE;
02386 
02387   /* Spectators and unwanted have no options */
02388   if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02389 
02390     /* Things worth more than this are not shown */
02391     Money avail = GetCompany(cid)->money + _price.station_value * 200;
02392     Money ref = _price.build_industry >> 8;
02393 
02394     /* Check the action bits for validity and
02395      * if they are valid add them */
02396     for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02397       const TownActions cur = (TownActions)(1 << i);
02398 
02399       /* Is the company not able to bribe ? */
02400       if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02401         continue;
02402 
02403       /* Is the company not able to buy exclusive rights ? */
02404       if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02405         continue;
02406 
02407       /* Is the company not able to build a statue ? */
02408       if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02409         continue;
02410 
02411       if (avail >= _town_action_costs[i] * ref) {
02412         buttons |= cur;
02413         num++;
02414       }
02415     }
02416   }
02417 
02418   if (nump != NULL) *nump = num;
02419   return buttons;
02420 }
02421 
02430 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02431 {
02432   if (!IsValidTownID(p1) || p2 > lengthof(_town_action_proc)) return CMD_ERROR;
02433 
02434   Town *t = GetTown(p1);
02435 
02436   if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02437 
02438   CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
02439 
02440   if (flags & DC_EXEC) {
02441     _town_action_proc[p2](t);
02442     InvalidateWindow(WC_TOWN_AUTHORITY, p1);
02443   }
02444 
02445   return cost;
02446 }
02447 
02448 static void UpdateTownGrowRate(Town *t)
02449 {
02450   /* Increase company ratings if they're low */
02451   const Company *c;
02452   FOR_ALL_COMPANIES(c) {
02453     if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02454       t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02455     }
02456   }
02457 
02458   int n = 0;
02459 
02460   const Station *st;
02461   FOR_ALL_STATIONS(st) {
02462     if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02463       if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02464         n++;
02465         if (IsValidCompanyID(st->owner)) {
02466           int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02467           t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
02468         }
02469       } else {
02470         if (IsValidCompanyID(st->owner)) {
02471           int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02472           t->ratings[st->owner] = max(new_rating, INT16_MIN);
02473         }
02474       }
02475     }
02476   }
02477 
02478   /* clamp all ratings to valid values */
02479   for (uint i = 0; i < MAX_COMPANIES; i++) {
02480     t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02481   }
02482 
02483   InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02484 
02485   ClrBit(t->flags12, TOWN_IS_FUNDED);
02486   if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02487 
02490   static const uint16 _grow_count_values[2][6] = {
02491     { 120, 120, 120, 100,  80,  60 }, // Fund new buildings has been activated
02492     { 320, 420, 300, 220, 160, 100 }  // Normal values
02493   };
02494 
02495   uint16 m;
02496 
02497   if (t->fund_buildings_months != 0) {
02498     m = _grow_count_values[0][min(n, 5)];
02499     t->fund_buildings_months--;
02500   } else {
02501     m = _grow_count_values[1][min(n, 5)];
02502     if (n == 0 && !Chance16(1, 12)) return;
02503   }
02504 
02505   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02506     if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02507       return;
02508   } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02509     if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02510       return;
02511   }
02512 
02513   /* Use the normal growth rate values if new buildings have been funded in
02514    * this town and the growth rate is set to none. */
02515   uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02516 
02517   m >>= growth_multiplier;
02518   if (t->larger_town) m /= 2;
02519 
02520   t->growth_rate = m / (t->num_houses / 50 + 1);
02521   if (m <= t->grow_counter)
02522     t->grow_counter = m;
02523 
02524   SetBit(t->flags12, TOWN_IS_FUNDED);
02525 }
02526 
02527 static void UpdateTownAmounts(Town *t)
02528 {
02529   /* Using +1 here to prevent overflow and division by zero */
02530   t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02531 
02532   t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02533   t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02534   t->act_food = t->new_act_food; t->new_act_food = 0;
02535   t->act_water = t->new_act_water; t->new_act_water = 0;
02536 
02537   /* Using +1 here to prevent overflow and division by zero */
02538   t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02539   t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02540   t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02541 
02542   InvalidateWindow(WC_TOWN_VIEW, t->index);
02543 }
02544 
02545 static void UpdateTownUnwanted(Town *t)
02546 {
02547   const Company *c;
02548 
02549   FOR_ALL_COMPANIES(c) {
02550     if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02551   }
02552 }
02553 
02559 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02560 {
02561   if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02562 
02563   Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02564   if (t == NULL) return true;
02565 
02566   if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02567 
02568   _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02569   SetDParam(0, t->index);
02570 
02571   return false;
02572 }
02573 
02574 
02575 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02576 {
02577   Town *t;
02578   uint best = threshold;
02579   Town *best_town = NULL;
02580 
02581   FOR_ALL_TOWNS(t) {
02582     uint dist = DistanceManhattan(tile, t->xy);
02583     if (dist < best) {
02584       best = dist;
02585       best_town = t;
02586     }
02587   }
02588 
02589   return best_town;
02590 }
02591 
02592 
02593 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02594 {
02595   switch (GetTileType(tile)) {
02596     case MP_ROAD:
02597       if (!HasTownOwnedRoad(tile)) {
02598         TownID tid = GetTownIndex(tile);
02599         if (tid == (TownID)INVALID_TOWN) {
02600           /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
02601           if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02602           assert(GetNumTowns() == 0);
02603           return NULL;
02604         }
02605 
02606         Town *town = GetTown(tid);
02607         assert(town->IsValid());
02608 
02609         if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02610 
02611         return town;
02612       }
02613       /* FALL THROUGH */
02614 
02615     case MP_HOUSE:
02616       return GetTownByTile(tile);
02617 
02618     default:
02619       return CalcClosestTownFromTile(tile, threshold);
02620   }
02621 }
02622 
02623 static bool _town_rating_test = false;
02624 SmallMap<const Town *, int, 4> _town_test_ratings;
02625 
02626 void SetTownRatingTestMode(bool mode)
02627 {
02628   static int ref_count = 0;
02629   if (mode) {
02630     if (ref_count == 0) {
02631       _town_test_ratings.Clear();
02632     }
02633     ref_count++;
02634   } else {
02635     assert(ref_count > 0);
02636     ref_count--;
02637   }
02638   _town_rating_test = !(ref_count == 0);
02639 }
02640 
02641 static int GetRating(const Town *t)
02642 {
02643   if (_town_rating_test) {
02644     SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02645     if (it != _town_test_ratings.End()) {
02646       return it->second;
02647     }
02648   }
02649   return t->ratings[_current_company];
02650 }
02651 
02659 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02660 {
02661   /* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
02662   if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02663       !IsValidCompanyID(_current_company) ||
02664       (_cheats.magic_bulldozer.value && add < 0)) {
02665     return;
02666   }
02667 
02668   int rating = GetRating(t);
02669   if (add < 0) {
02670     if (rating > max) {
02671       rating += add;
02672       if (rating < max) rating = max;
02673     }
02674   } else {
02675     if (rating < max) {
02676       rating += add;
02677       if (rating > max) rating = max;
02678     }
02679   }
02680   if (_town_rating_test) {
02681     _town_test_ratings[t] = rating;
02682   } else {
02683     SetBit(t->have_ratings, _current_company);
02684     t->ratings[_current_company] = rating;
02685     InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
02686   }
02687 }
02688 
02689 /* penalty for removing town-owned stuff */
02690 static const int _default_rating_settings [3][3] = {
02691   /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE */
02692   {  0, 128, 384}, // Permissive
02693   { 48, 192, 480}, // Neutral
02694   { 96, 384, 768}, // Hostile
02695 };
02696 
02697 bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
02698 {
02699   /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
02700   if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
02701     return true;
02702 
02703   /* check if you're allowed to remove the street/bridge/tunnel/industry
02704    * owned by a town no removal if rating is lower than ... depends now on
02705    * difficulty setting. Minimum town rating selected by difficulty level
02706    */
02707   int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
02708 
02709   if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
02710     SetDParam(0, t->index);
02711     _error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
02712     return false;
02713   }
02714 
02715   return true;
02716 }
02717 
02718 void TownsMonthlyLoop()
02719 {
02720   Town *t;
02721 
02722   FOR_ALL_TOWNS(t) {
02723     if (t->road_build_months != 0) t->road_build_months--;
02724 
02725     if (t->exclusive_counter != 0)
02726       if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02727 
02728     UpdateTownGrowRate(t);
02729     UpdateTownAmounts(t);
02730     UpdateTownUnwanted(t);
02731   }
02732 }
02733 
02734 void TownsYearlyLoop()
02735 {
02736   /* Increment house ages */
02737   for (TileIndex t = 0; t < MapSize(); t++) {
02738     if (!IsTileType(t, MP_HOUSE)) continue;
02739     IncrementHouseAge(t);
02740   }
02741 }
02742 
02743 void InitializeTowns()
02744 {
02745   /* Clean the town pool and create 1 block in it */
02746   _Town_pool.CleanPool();
02747   _Town_pool.AddBlockToPool();
02748 
02749   memset(_subsidies, 0, sizeof(_subsidies));
02750   for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
02751     s->cargo_type = CT_INVALID;
02752   }
02753 
02754   _cur_town_ctr = 0;
02755   _cur_town_iter = 0;
02756   _total_towns = 0;
02757 }
02758 
02759 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02760 {
02761   if (AutoslopeEnabled()) {
02762     HouseID house = GetHouseType(tile);
02763     GetHouseNorthPart(house); // modifies house to the ID of the north tile
02764     const HouseSpec *hs = GetHouseSpecs(house);
02765 
02766     /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
02767     if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02768       (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
02769   }
02770 
02771   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02772 }
02773 
02775 extern const TileTypeProcs _tile_type_town_procs = {
02776   DrawTile_Town,           // draw_tile_proc
02777   GetSlopeZ_Town,          // get_slope_z_proc
02778   ClearTile_Town,          // clear_tile_proc
02779   GetAcceptedCargo_Town,   // get_accepted_cargo_proc
02780   GetTileDesc_Town,        // get_tile_desc_proc
02781   GetTileTrackStatus_Town, // get_tile_track_status_proc
02782   ClickTile_Town,          // click_tile_proc
02783   AnimateTile_Town,        // animate_tile_proc
02784   TileLoop_Town,           // tile_loop_clear
02785   ChangeTileOwner_Town,    // change_tile_owner_clear
02786   GetProducedCargo_Town,   // get_produced_cargo_proc
02787   NULL,                    // vehicle_enter_tile_proc
02788   GetFoundation_Town,      // get_foundation_proc
02789   TerraformTile_Town,      // terraform_tile_proc
02790 };
02791 
02792 void ResetHouses()
02793 {
02794   memset(&_house_specs, 0, sizeof(_house_specs));
02795   memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02796 
02797   /* Reset any overrides that have been set. */
02798   _house_mngr.ResetOverride();
02799 }

Generated on Mon May 11 15:48:08 2009 for OpenTTD by  doxygen 1.5.6