00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013 #include "road_internal.h"
00014 #include "road_cmd.h"
00015 #include "landscape.h"
00016 #include "viewport_func.h"
00017 #include "command_func.h"
00018 #include "industry.h"
00019 #include "station_base.h"
00020 #include "company_base.h"
00021 #include "news_func.h"
00022 #include "gui.h"
00023 #include "unmovable_map.h"
00024 #include "variables.h"
00025 #include "genworld.h"
00026 #include "newgrf.h"
00027 #include "newgrf_house.h"
00028 #include "newgrf_commons.h"
00029 #include "newgrf_text.h"
00030 #include "autoslope.h"
00031 #include "tunnelbridge_map.h"
00032 #include "strings_func.h"
00033 #include "window_func.h"
00034 #include "string_func.h"
00035 #include "newgrf_cargo.h"
00036 #include "cheat_type.h"
00037 #include "functions.h"
00038 #include "animated_tile_func.h"
00039 #include "date_func.h"
00040 #include "subsidy_func.h"
00041 #include "core/smallmap_type.hpp"
00042 #include "core/pool_func.hpp"
00043 #include "town.h"
00044 #include "townname_func.h"
00045 #include "townname_type.h"
00046 #include "core/random_func.hpp"
00047
00048 #include "table/strings.h"
00049 #include "table/town_land.h"
00050
00051 static Town *_cleared_town;
00052 static int _cleared_town_rating;
00053 TownID _new_town_id;
00054
00055
00056 TownPool _town_pool("Town");
00057 INSTANTIATE_POOL_METHODS(Town)
00058
00059 Town::~Town()
00060 {
00061 free(this->name);
00062
00063 if (CleaningPool()) return;
00064
00065 Industry *i;
00066
00067
00068
00069 DeleteWindowById(WC_TOWN_VIEW, this->index);
00070
00071
00072 FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
00073
00074
00075 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00076 switch (GetTileType(tile)) {
00077 case MP_HOUSE:
00078 if (Town::GetByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00079 break;
00080
00081 case MP_ROAD:
00082
00083 if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
00084 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00085 }
00086 break;
00087
00088 case MP_TUNNELBRIDGE:
00089 if (IsTileOwner(tile, OWNER_TOWN) &&
00090 ClosestTownFromTile(tile, UINT_MAX) == this)
00091 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
00092 break;
00093
00094 default:
00095 break;
00096 }
00097 }
00098
00099 DeleteSubsidyWith(ST_TOWN, this->index);
00100 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00101 MarkWholeScreenDirty();
00102 }
00103
00104
00110 void Town::PostDestructor(size_t index)
00111 {
00112 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00113 UpdateNearestTownForRoadTiles(false);
00114 }
00115
00119 void Town::InitializeLayout(TownLayout layout)
00120 {
00121 if (layout != TL_RANDOM) {
00122 this->layout = layout;
00123 return;
00124 }
00125
00126 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00127 }
00128
00133 Town *Town::GetRandom()
00134 {
00135 if (Town::GetNumItems() == 0) return NULL;
00136 int num = RandomRange((uint16)Town::GetNumItems());
00137 size_t index = MAX_UVALUE(size_t);
00138
00139 while (num >= 0) {
00140 num--;
00141 index++;
00142
00143
00144 while (!Town::IsValidID(index)) {
00145 index++;
00146 assert(index < Town::GetPoolSize());
00147 }
00148 }
00149
00150 return Town::Get(index);
00151 }
00152
00153 Money HouseSpec::GetRemovalCost() const
00154 {
00155 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00156 }
00157
00158
00159 static int _grow_town_result;
00160
00161
00162 enum TownGrowthResult {
00163 GROWTH_SUCCEED = -1,
00164 GROWTH_SEARCH_STOPPED = 0
00165
00166 };
00167
00168 static bool BuildTownHouse(Town *t, TileIndex tile);
00169 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00170
00171 static void TownDrawHouseLift(const TileInfo *ti)
00172 {
00173 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00174 }
00175
00176 typedef void TownDrawTileProc(const TileInfo *ti);
00177 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00178 TownDrawHouseLift
00179 };
00180
00186 static inline DiagDirection RandomDiagDir()
00187 {
00188 return (DiagDirection)(3 & Random());
00189 }
00190
00196 static void DrawTile_Town(TileInfo *ti)
00197 {
00198 HouseID house_id = GetHouseType(ti->tile);
00199
00200 if (house_id >= NEW_HOUSE_OFFSET) {
00201
00202
00203
00204 if (HouseSpec::Get(house_id)->spritegroup != NULL) {
00205 DrawNewHouseTile(ti, house_id);
00206 return;
00207 } else {
00208 house_id = HouseSpec::Get(house_id)->substitute_id;
00209 }
00210 }
00211
00212
00213 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00214
00215 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00216
00217 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00218
00219
00220 if (IsInvisibilitySet(TO_HOUSES)) return;
00221
00222
00223 SpriteID image = dcts->building.sprite;
00224 if (image != 0) {
00225 AddSortableSpriteToDraw(image, dcts->building.pal,
00226 ti->x + dcts->subtile_x,
00227 ti->y + dcts->subtile_y,
00228 dcts->width,
00229 dcts->height,
00230 dcts->dz,
00231 ti->z,
00232 IsTransparencySet(TO_HOUSES)
00233 );
00234
00235 if (IsTransparencySet(TO_HOUSES)) return;
00236 }
00237
00238 {
00239 int proc = dcts->draw_proc - 1;
00240
00241 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00242 }
00243 }
00244
00245 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00246 {
00247 return GetTileMaxZ(tile);
00248 }
00249
00251 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00252 {
00253 HouseID hid = GetHouseType(tile);
00254
00255
00256
00257
00258
00259 if (hid >= NEW_HOUSE_OFFSET) {
00260 const HouseSpec *hs = HouseSpec::Get(hid);
00261 if (hs->spritegroup != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00262 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00263 if (callback_res == 0) return FOUNDATION_NONE;
00264 }
00265 }
00266 return FlatteningFoundation(tileh);
00267 }
00268
00275 static void AnimateTile_Town(TileIndex tile)
00276 {
00277 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00278 AnimateNewHouseTile(tile);
00279 return;
00280 }
00281
00282 if (_tick_counter & 3) return;
00283
00284
00285
00286
00287
00288 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00289 DeleteAnimatedTile(tile);
00290 return;
00291 }
00292
00293 if (!LiftHasDestination(tile)) {
00294 uint i;
00295
00296
00297
00298
00299
00300 do {
00301 i = RandomRange(7);
00302 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00303
00304 SetLiftDestination(tile, i);
00305 }
00306
00307 int pos = GetLiftPosition(tile);
00308 int dest = GetLiftDestination(tile) * 6;
00309 pos += (pos < dest) ? 1 : -1;
00310 SetLiftPosition(tile, pos);
00311
00312 if (pos == dest) {
00313 HaltLift(tile);
00314 DeleteAnimatedTile(tile);
00315 }
00316
00317 MarkTileDirtyByTile(tile);
00318 }
00319
00326 static bool IsCloseToTown(TileIndex tile, uint dist)
00327 {
00328 const Town *t;
00329
00330 FOR_ALL_TOWNS(t) {
00331 if (DistanceManhattan(tile, t->xy) < dist) return true;
00332 }
00333 return false;
00334 }
00335
00340 void Town::UpdateVirtCoord()
00341 {
00342 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00343 SetDParam(0, this->index);
00344 SetDParam(1, this->population);
00345 this->sign.UpdatePosition(pt.x, pt.y - 24,
00346 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00347
00348 SetWindowDirty(WC_TOWN_VIEW, this->index);
00349 }
00350
00352 void UpdateAllTownVirtCoords()
00353 {
00354 Town *t;
00355
00356 FOR_ALL_TOWNS(t) {
00357 t->UpdateVirtCoord();
00358 }
00359 }
00360
00366 static void ChangePopulation(Town *t, int mod)
00367 {
00368 t->population += mod;
00369 SetWindowDirty(WC_TOWN_VIEW, t->index);
00370 t->UpdateVirtCoord();
00371
00372 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00373 }
00374
00380 uint32 GetWorldPopulation()
00381 {
00382 uint32 pop = 0;
00383 const Town *t;
00384
00385 FOR_ALL_TOWNS(t) pop += t->population;
00386 return pop;
00387 }
00388
00393 static void MakeSingleHouseBigger(TileIndex tile)
00394 {
00395 assert(IsTileType(tile, MP_HOUSE));
00396
00397
00398 if (LiftHasDestination(tile)) return;
00399
00400
00401 IncHouseConstructionTick(tile);
00402 if (GetHouseConstructionTick(tile) != 0) return;
00403
00404 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00405
00406
00407 if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
00408 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00409 if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
00410 }
00411
00412 if (IsHouseCompleted(tile)) {
00413
00414
00415 ChangePopulation(Town::GetByTile(tile), hs->population);
00416 ResetHouseAge(tile);
00417 }
00418 MarkTileDirtyByTile(tile);
00419 }
00420
00424 static void MakeTownHouseBigger(TileIndex tile)
00425 {
00426 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00427 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00428 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00429 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00430 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00431 }
00432
00439 static void TileLoop_Town(TileIndex tile)
00440 {
00441 HouseID house_id = GetHouseType(tile);
00442
00443
00444
00445 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00446
00447 if (!IsHouseCompleted(tile)) {
00448
00449 MakeTownHouseBigger(tile);
00450 return;
00451 }
00452
00453 const HouseSpec *hs = HouseSpec::Get(house_id);
00454
00455
00456 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00457 house_id < NEW_HOUSE_OFFSET &&
00458 !LiftHasDestination(tile) &&
00459 Chance16(1, 2)) {
00460 AddAnimatedTile(tile);
00461 }
00462
00463 Town *t = Town::GetByTile(tile);
00464 uint32 r = Random();
00465
00466 StationFinder stations(TileArea(tile, 1, 1));
00467
00468 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00469 for (uint i = 0; i < 256; i++) {
00470 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00471
00472 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00473
00474 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00475 if (cargo == CT_INVALID) continue;
00476
00477 uint amt = GB(callback, 0, 8);
00478 if (amt == 0) continue;
00479
00480 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00481
00482 const CargoSpec *cs = CargoSpec::Get(cargo);
00483 switch (cs->town_effect) {
00484 case TE_PASSENGERS:
00485 t->new_max_pass += amt;
00486 t->new_act_pass += moved;
00487 break;
00488
00489 case TE_MAIL:
00490 t->new_max_mail += amt;
00491 t->new_act_mail += moved;
00492 break;
00493
00494 default:
00495 break;
00496 }
00497 }
00498 } else {
00499 if (GB(r, 0, 8) < hs->population) {
00500 uint amt = GB(r, 0, 8) / 8 + 1;
00501
00502 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00503 t->new_max_pass += amt;
00504 t->new_act_pass += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00505 }
00506
00507 if (GB(r, 8, 8) < hs->mail_generation) {
00508 uint amt = GB(r, 8, 8) / 8 + 1;
00509
00510 if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
00511 t->new_max_mail += amt;
00512 t->new_act_mail += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00513 }
00514 }
00515
00516 _current_company = OWNER_TOWN;
00517
00518 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00519 HasBit(t->flags, TOWN_IS_FUNDED) &&
00520 CanDeleteHouse(tile) &&
00521 GetHouseAge(tile) >= hs->minimum_life &&
00522 --t->time_until_rebuild == 0) {
00523 t->time_until_rebuild = GB(r, 16, 8) + 192;
00524
00525 ClearTownHouse(t, tile);
00526
00527
00528 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00529 }
00530
00531 _current_company = OWNER_NONE;
00532 }
00533
00534 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00535 {
00536 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00537 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00538
00539 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00540
00541 CommandCost cost(EXPENSES_CONSTRUCTION);
00542 cost.AddCost(hs->GetRemovalCost());
00543
00544 int rating = hs->remove_rating_decrease;
00545 _cleared_town_rating += rating;
00546 Town *t = _cleared_town = Town::GetByTile(tile);
00547
00548 if (Company::IsValidID(_current_company)) {
00549 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00550 SetDParam(0, t->index);
00551 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00552 }
00553 }
00554
00555 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00556 if (flags & DC_EXEC) {
00557 ClearTownHouse(t, tile);
00558 }
00559
00560 return cost;
00561 }
00562
00563 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00564 {
00565 HouseID house_id = GetHouseType(tile);
00566 const HouseSpec *hs = HouseSpec::Get(house_id);
00567 Town *t = Town::GetByTile(tile);
00568
00569 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00570 for (uint i = 0; i < 256; i++) {
00571 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00572
00573 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00574
00575 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
00576
00577 if (cargo == CT_INVALID) continue;
00578 produced[cargo]++;
00579 }
00580 } else {
00581 if (hs->population > 0) {
00582 produced[CT_PASSENGERS]++;
00583 }
00584 if (hs->mail_generation > 0) {
00585 produced[CT_MAIL]++;
00586 }
00587 }
00588 }
00589
00590 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00591 {
00592 if (cargo == CT_INVALID || amount == 0) return;
00593 acceptance[cargo] += amount;
00594 SetBit(*always_accepted, cargo);
00595 }
00596
00597 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00598 {
00599 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00600 CargoID accepts[3];
00601
00602
00603 for (uint8 i = 0; i < lengthof(accepts); i++) {
00604 accepts[i] = hs->accepts_cargo[i];
00605 }
00606
00607
00608 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00609 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00610 if (callback != CALLBACK_FAILED) {
00611
00612 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grffile);
00613 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grffile);
00614 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
00615 }
00616 }
00617
00618
00619 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00620 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00621 if (callback != CALLBACK_FAILED) {
00622 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00623 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00624 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00625
00626 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00627 } else {
00628 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00629 }
00630 return;
00631 }
00632 }
00633
00634
00635 for (uint8 i = 0; i < lengthof(accepts); i++) {
00636 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00637 }
00638 }
00639
00640 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00641 {
00642 const HouseID house = GetHouseType(tile);
00643 const HouseSpec *hs = HouseSpec::Get(house);
00644 bool house_completed = IsHouseCompleted(tile);
00645
00646 td->str = hs->building_name;
00647
00648 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00649 if (callback_res != CALLBACK_FAILED) {
00650 StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
00651 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00652 td->str = new_name;
00653 }
00654 }
00655
00656 if (!house_completed) {
00657 SetDParamX(td->dparam, 0, td->str);
00658 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00659 }
00660
00661 if (hs->grffile != NULL) {
00662 const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
00663 td->grf = gc->name;
00664 }
00665
00666 td->owner[0] = OWNER_TOWN;
00667 }
00668
00669 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00670 {
00671
00672 return 0;
00673 }
00674
00675 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00676 {
00677
00678 }
00679
00680 static bool GrowTown(Town *t);
00681
00682 static void TownTickHandler(Town *t)
00683 {
00684 if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00685 int i = t->grow_counter - 1;
00686 if (i < 0) {
00687 if (GrowTown(t)) {
00688 i = t->growth_rate;
00689 } else {
00690 i = 0;
00691 }
00692 }
00693 t->grow_counter = i;
00694 }
00695
00696 UpdateTownRadius(t);
00697 }
00698
00699 void OnTick_Town()
00700 {
00701 if (_game_mode == GM_EDITOR) return;
00702
00703 Town *t;
00704 FOR_ALL_TOWNS(t) {
00705
00706 if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00707 TownTickHandler(t);
00708 }
00709 }
00710 }
00711
00720 static RoadBits GetTownRoadBits(TileIndex tile)
00721 {
00722 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00723
00724 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00725 }
00726
00737 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00738 {
00739 if (!IsValidTile(tile)) return false;
00740
00741
00742 const TileIndexDiff tid_lt[3] = {
00743 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00744 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00745 TileOffsByDiagDir(ReverseDiagDir(dir)),
00746 };
00747
00748 dist_multi = (dist_multi + 1) * 4;
00749 for (uint pos = 4; pos < dist_multi; pos++) {
00750
00751 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00752
00753
00754 if (pos & 2) cur += tid_lt[2];
00755
00756
00757 if (IsValidTile(tile + cur) &&
00758 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00759 }
00760 return false;
00761 }
00762
00771 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00772 {
00773 if (DistanceFromEdge(tile) == 0) return false;
00774
00775 Slope cur_slope, desired_slope;
00776
00777 for (;;) {
00778
00779 if (GetTownRoadBits(tile) == ROAD_NONE) {
00780
00781
00782
00783 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00784 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00785 return false;
00786 }
00787
00788 cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00789 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00790 if (cur_slope == SLOPE_FLAT) return ret;
00791
00792
00793
00794 desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00795 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00796 if (Chance16(1, 8)) {
00797 CommandCost res = CMD_ERROR;
00798 if (!_generating_world && Chance16(1, 10)) {
00799
00800 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00801 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00802 }
00803 if (res.Failed() && Chance16(1, 3)) {
00804
00805 return ret;
00806 }
00807 }
00808 return false;
00809 }
00810 return ret;
00811 }
00812 }
00813
00814 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00815 {
00816 assert(tile < MapSize());
00817
00818 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00819 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00820 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00821 return true;
00822 }
00823
00824 static void LevelTownLand(TileIndex tile)
00825 {
00826 assert(tile < MapSize());
00827
00828
00829 if (IsTileType(tile, MP_HOUSE)) return;
00830 Slope tileh = GetTileSlope(tile, NULL);
00831 if (tileh == SLOPE_FLAT) return;
00832
00833
00834 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00835 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00836 }
00837 }
00838
00848 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00849 {
00850
00851 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00852 RoadBits rcmd = ROAD_NONE;
00853
00854 switch (t->layout) {
00855 default: NOT_REACHED();
00856
00857 case TL_2X2_GRID:
00858 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00859 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00860 break;
00861
00862 case TL_3X3_GRID:
00863 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00864 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00865 break;
00866 }
00867
00868
00869 if (rcmd != ROAD_ALL) return rcmd;
00870
00871 RoadBits rb_template;
00872
00873 switch (GetTileSlope(tile, NULL)) {
00874 default: rb_template = ROAD_ALL; break;
00875 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00876 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00877 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00878 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00879 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00880 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00881 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00882 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00883 case SLOPE_STEEP_W:
00884 case SLOPE_STEEP_S:
00885 case SLOPE_STEEP_E:
00886 case SLOPE_STEEP_N:
00887 rb_template = ROAD_NONE;
00888 break;
00889 }
00890
00891
00892 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00893
00894 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00895 }
00896
00907 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00908 {
00909
00910 if (DistanceFromEdge(tile) == 0) return false;
00911
00912 uint counter = 0;
00913
00914
00915 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00916
00917
00918
00919 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00920 case MP_HOUSE:
00921 case MP_VOID:
00922 counter++;
00923 break;
00924
00925 default:
00926 break;
00927 }
00928
00929
00930 if (counter >= 3) {
00931 if (BuildTownHouse(t, tile)) {
00932 _grow_town_result = GROWTH_SUCCEED;
00933 return true;
00934 }
00935 return false;
00936 }
00937 }
00938 return false;
00939 }
00940
00949 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00950 {
00951 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
00952 _grow_town_result = GROWTH_SUCCEED;
00953 return true;
00954 }
00955 return false;
00956 }
00957
00968 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00969 {
00970 assert(bridge_dir < DIAGDIR_END);
00971
00972 const Slope slope = GetTileSlope(tile, NULL);
00973 if (slope == SLOPE_FLAT) return false;
00974
00975
00976
00977
00978 if (slope & InclinedSlope(bridge_dir)) return false;
00979
00980
00981 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00982
00983
00984 uint8 bridge_length = 0;
00985 TileIndex bridge_tile = tile;
00986
00987 const int delta = TileOffsByDiagDir(bridge_dir);
00988 do {
00989 if (bridge_length++ >= 11) {
00990
00991 return false;
00992 }
00993 bridge_tile += delta;
00994 } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00995
00996
00997 if (bridge_length == 1) return false;
00998
00999 for (uint8 times = 0; times <= 22; times++) {
01000 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01001
01002
01003 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE).Succeeded()) {
01004 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
01005 _grow_town_result = GROWTH_SUCCEED;
01006 return true;
01007 }
01008 }
01009
01010 return false;
01011 }
01012
01030 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01031 {
01032 RoadBits rcmd = ROAD_NONE;
01033 TileIndex tile = *tile_ptr;
01034
01035 assert(tile < MapSize());
01036
01037 if (cur_rb == ROAD_NONE) {
01038
01039
01040 _grow_town_result = GROWTH_SEARCH_STOPPED;
01041
01042 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01043
01044
01045 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01046
01047
01048 switch (t1->layout) {
01049 default: NOT_REACHED();
01050
01051 case TL_3X3_GRID:
01052 case TL_2X2_GRID:
01053 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01054 if (rcmd == ROAD_NONE) return;
01055 break;
01056
01057 case TL_BETTER_ROADS:
01058 case TL_ORIGINAL:
01059 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01060
01061 DiagDirection source_dir = ReverseDiagDir(target_dir);
01062
01063 if (Chance16(1, 4)) {
01064
01065 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01066 }
01067
01068 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01069
01070
01071 if (target_dir != ReverseDiagDir(source_dir)) return;
01072
01073
01074 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01075 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01076 return;
01077 }
01078
01079
01080
01081 }
01082
01083 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01084 break;
01085 }
01086
01087 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01088
01089
01090
01091 _grow_town_result = GROWTH_SEARCH_STOPPED;
01092
01093 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01094
01095 switch (t1->layout) {
01096 default: NOT_REACHED();
01097
01098 case TL_3X3_GRID:
01099 case TL_2X2_GRID:
01100 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01101 break;
01102
01103 case TL_BETTER_ROADS:
01104 case TL_ORIGINAL:
01105 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01106 break;
01107 }
01108 } else {
01109 bool allow_house = true;
01110
01111
01112 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01113 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01114 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01115 }
01116 return;
01117 }
01118
01119
01120
01121 target_dir = RandomDiagDir();
01122 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01123
01124
01125 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01126
01127
01128 if (IsWaterTile(house_tile)) return;
01129
01130 if (!IsValidTile(house_tile)) return;
01131
01132 if (_settings_game.economy.allow_town_roads || _generating_world) {
01133 switch (t1->layout) {
01134 default: NOT_REACHED();
01135
01136 case TL_3X3_GRID:
01137 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01138
01139
01140 case TL_2X2_GRID:
01141 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01142 allow_house = (rcmd == ROAD_NONE);
01143 break;
01144
01145 case TL_BETTER_ROADS:
01146 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01147
01148
01149 case TL_ORIGINAL:
01150
01151
01152 rcmd = DiagDirToRoadBits(target_dir);
01153 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01154 break;
01155 }
01156 }
01157
01158 if (allow_house) {
01159
01160 if (!IsTileType(house_tile, MP_HOUSE)) {
01161
01162 if (Chance16(1, 6)) LevelTownLand(house_tile);
01163
01164
01165
01166 if (BuildTownHouse(t1, house_tile)) {
01167 _grow_town_result = GROWTH_SUCCEED;
01168 }
01169 }
01170 return;
01171 }
01172
01173 _grow_town_result = GROWTH_SEARCH_STOPPED;
01174 }
01175
01176
01177 if (IsWaterTile(tile)) return;
01178
01179
01180 rcmd = CleanUpRoadBits(tile, rcmd);
01181 if (rcmd == ROAD_NONE) return;
01182
01183
01184
01185
01186 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01187
01188 GrowTownWithRoad(t1, tile, rcmd);
01189 }
01190
01196 static int GrowTownAtRoad(Town *t, TileIndex tile)
01197 {
01198
01199
01200
01201 DiagDirection target_dir = DIAGDIR_END;
01202
01203 assert(tile < MapSize());
01204
01205
01206
01207
01208 switch (t->layout) {
01209 case TL_BETTER_ROADS:
01210 _grow_town_result = 10 + t->num_houses * 2 / 9;
01211 break;
01212
01213 case TL_3X3_GRID:
01214 case TL_2X2_GRID:
01215 _grow_town_result = 10 + t->num_houses * 1 / 9;
01216 break;
01217
01218 default:
01219 _grow_town_result = 10 + t->num_houses * 4 / 9;
01220 break;
01221 }
01222
01223 do {
01224 RoadBits cur_rb = GetTownRoadBits(tile);
01225
01226
01227 GrowTownInTile(&tile, cur_rb, target_dir, t);
01228
01229
01230
01231 cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01232 if (cur_rb == ROAD_NONE)
01233 return _grow_town_result;
01234
01235
01236
01237 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01238 tile = TileAddByDiagDir(tile, target_dir);
01239
01240 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01241
01242 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01243 _grow_town_result = GROWTH_SUCCEED;
01244 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01245
01246
01247 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01248 SetTownIndex(tile, t->index);
01249 }
01250 }
01251
01252
01253 } while (--_grow_town_result >= 0);
01254
01255 return (_grow_town_result == -2);
01256 }
01257
01265 static RoadBits GenRandomRoadBits()
01266 {
01267 uint32 r = Random();
01268 uint a = GB(r, 0, 2);
01269 uint b = GB(r, 8, 2);
01270 if (a == b) b ^= 2;
01271 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01272 }
01273
01278 static bool GrowTown(Town *t)
01279 {
01280 static const TileIndexDiffC _town_coord_mod[] = {
01281 {-1, 0},
01282 { 1, 1},
01283 { 1, -1},
01284 {-1, -1},
01285 {-1, 0},
01286 { 0, 2},
01287 { 2, 0},
01288 { 0, -2},
01289 {-1, -1},
01290 {-2, 2},
01291 { 2, 2},
01292 { 2, -2},
01293 { 0, 0}
01294 };
01295
01296
01297 CompanyID old_company = _current_company;
01298 _current_company = OWNER_TOWN;
01299
01300 TileIndex tile = t->xy;
01301
01302
01303 const TileIndexDiffC *ptr;
01304 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01305 if (GetTownRoadBits(tile) != ROAD_NONE) {
01306 int r = GrowTownAtRoad(t, tile);
01307 _current_company = old_company;
01308 return r != 0;
01309 }
01310 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01311 }
01312
01313
01314
01315 if (_settings_game.economy.allow_town_roads || _generating_world) {
01316 tile = t->xy;
01317 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01318
01319 if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01320 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01321 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01322 _current_company = old_company;
01323 return true;
01324 }
01325 }
01326 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01327 }
01328 }
01329
01330 _current_company = old_company;
01331 return false;
01332 }
01333
01334 void UpdateTownRadius(Town *t)
01335 {
01336 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01337 { 4, 0, 0, 0, 0},
01338 { 16, 0, 0, 0, 0},
01339 { 25, 0, 0, 0, 0},
01340 { 36, 0, 0, 0, 0},
01341 { 49, 0, 4, 0, 0},
01342 { 64, 0, 4, 0, 0},
01343 { 64, 0, 9, 0, 1},
01344 { 64, 0, 9, 0, 4},
01345 { 64, 0, 16, 0, 4},
01346 { 81, 0, 16, 0, 4},
01347 { 81, 0, 16, 0, 4},
01348 { 81, 0, 25, 0, 9},
01349 { 81, 36, 25, 0, 9},
01350 { 81, 36, 25, 16, 9},
01351 { 81, 49, 0, 25, 9},
01352 { 81, 64, 0, 25, 9},
01353 { 81, 64, 0, 36, 9},
01354 { 81, 64, 0, 36, 16},
01355 {100, 81, 0, 49, 16},
01356 {100, 81, 0, 49, 25},
01357 {121, 81, 0, 49, 25},
01358 {121, 81, 0, 49, 25},
01359 {121, 81, 0, 49, 36},
01360 };
01361
01362 if (t->num_houses < 92) {
01363 memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01364 } else {
01365 int mass = t->num_houses / 8;
01366
01367
01368
01369 t->squared_town_zone_radius[0] = mass * 15 - 40;
01370 t->squared_town_zone_radius[1] = mass * 9 - 15;
01371 t->squared_town_zone_radius[2] = 0;
01372 t->squared_town_zone_radius[3] = mass * 5 - 5;
01373 t->squared_town_zone_radius[4] = mass * 3 + 5;
01374 }
01375 }
01376
01377 void UpdateTownMaxPass(Town *t)
01378 {
01379 t->max_pass = t->population >> 3;
01380 t->max_mail = t->population >> 4;
01381 }
01382
01394 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01395 {
01396 t->xy = tile;
01397 t->num_houses = 0;
01398 t->time_until_rebuild = 10;
01399 UpdateTownRadius(t);
01400 t->flags = 0;
01401 t->population = 0;
01402 t->grow_counter = 0;
01403 t->growth_rate = 250;
01404 t->new_max_pass = 0;
01405 t->new_max_mail = 0;
01406 t->new_act_pass = 0;
01407 t->new_act_mail = 0;
01408 t->max_pass = 0;
01409 t->max_mail = 0;
01410 t->act_pass = 0;
01411 t->act_mail = 0;
01412
01413 t->pct_pass_transported = 0;
01414 t->pct_mail_transported = 0;
01415 t->fund_buildings_months = 0;
01416 t->new_act_food = 0;
01417 t->new_act_water = 0;
01418 t->act_food = 0;
01419 t->act_water = 0;
01420
01421 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01422
01423 t->have_ratings = 0;
01424 t->exclusivity = INVALID_COMPANY;
01425 t->exclusive_counter = 0;
01426 t->statues = 0;
01427
01428 extern int _nb_orig_names;
01429 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01430
01431 t->townnamegrfid = 0;
01432 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01433 } else {
01434
01435 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01436 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01437 }
01438 t->townnameparts = townnameparts;
01439
01440 t->UpdateVirtCoord();
01441 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01442
01443 t->InitializeLayout(layout);
01444
01445 t->larger_town = city;
01446
01447 int x = (int)size * 16 + 3;
01448 if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
01449
01450 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01451
01452 t->num_houses += x;
01453 UpdateTownRadius(t);
01454
01455 int i = x * 4;
01456 do {
01457 GrowTown(t);
01458 } while (--i);
01459
01460 t->num_houses -= x;
01461 UpdateTownRadius(t);
01462 UpdateTownMaxPass(t);
01463 UpdateAirportsNoise();
01464 }
01465
01471 static CommandCost TownCanBePlacedHere(TileIndex tile)
01472 {
01473
01474 if (DistanceFromEdge(tile) < 12) {
01475 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01476 }
01477
01478
01479 if (IsCloseToTown(tile, 20)) {
01480 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01481 }
01482
01483
01484 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01485 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01486 }
01487
01488 return CommandCost(EXPENSES_OTHER);
01489 }
01490
01496 static bool IsUniqueTownName(const char *name)
01497 {
01498 const Town *t;
01499
01500 FOR_ALL_TOWNS(t) {
01501 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01502 }
01503
01504 return true;
01505 }
01506
01519 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01520 {
01521 TownSize size = (TownSize)GB(p1, 0, 2);
01522 bool city = HasBit(p1, 2);
01523 TownLayout layout = (TownLayout)GB(p1, 3, 3);
01524 TownNameParams par(_settings_game.game_creation.town_name);
01525 bool random = HasBit(p1, 6);
01526 uint32 townnameparts = p2;
01527
01528 if (size > TS_RANDOM) return CMD_ERROR;
01529 if (layout > TL_RANDOM) return CMD_ERROR;
01530
01531
01532 if (_game_mode != GM_EDITOR) {
01533 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01534 if (size == TS_LARGE) return CMD_ERROR;
01535 if (random) return CMD_ERROR;
01536 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01537 return CMD_ERROR;
01538 }
01539 }
01540
01541 if (StrEmpty(text)) {
01542
01543 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01544 } else {
01545
01546 if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
01547 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01548 }
01549
01550
01551 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01552
01553 if (!random) {
01554 CommandCost ret = TownCanBePlacedHere(tile);
01555 if (ret.Failed()) return ret;
01556 }
01557
01558 static const byte price_mult[][TS_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01559
01560 assert_compile(lengthof(price_mult[0]) == 4);
01561
01562 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01563 byte mult = price_mult[city][size];
01564
01565 cost.MultiplyCost(mult);
01566
01567
01568 if (flags & DC_EXEC) {
01569 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01570 _additional_cash_required = cost.GetCost();
01571 return CommandCost(EXPENSES_OTHER);
01572 }
01573
01574 _generating_world = true;
01575 UpdateNearestTownForRoadTiles(true);
01576 Town *t;
01577 if (random) {
01578 t = CreateRandomTown(20, townnameparts, size, city, layout);
01579 if (t == NULL) {
01580 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01581 } else {
01582 _new_town_id = t->index;
01583 }
01584 } else {
01585 t = new Town(tile);
01586 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01587 }
01588 UpdateNearestTownForRoadTiles(false);
01589 _generating_world = false;
01590
01591 if (t != NULL && !StrEmpty(text)) {
01592 t->name = strdup(text);
01593 t->UpdateVirtCoord();
01594 }
01595
01596 if (_game_mode != GM_EDITOR) {
01597
01598 assert(!random);
01599 char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
01600 SetDParam(0, _current_company);
01601 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01602
01603 char *cn = strdup(company_name);
01604 SetDParamStr(0, cn);
01605 SetDParam(1, t->index);
01606
01607 AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01608 }
01609 }
01610 return cost;
01611 }
01612
01622 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01623 {
01624 switch (layout) {
01625 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01626 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01627 default: return tile;
01628 }
01629 }
01630
01640 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01641 {
01642 switch (layout) {
01643 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01644 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01645 default: return true;
01646 }
01647 }
01648
01652 struct SpotData {
01653 TileIndex tile;
01654 uint max_dist;
01655 TownLayout layout;
01656 };
01657
01674 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01675 {
01676 SpotData *sp = (SpotData*)user_data;
01677 uint dist = GetClosestWaterDistance(tile, true);
01678
01679 if (IsTileType(tile, MP_CLEAR) &&
01680 GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01681 IsTileAlignedToGrid(tile, sp->layout) &&
01682 dist > sp->max_dist) {
01683 sp->tile = tile;
01684 sp->max_dist = dist;
01685 }
01686
01687 return false;
01688 }
01689
01696 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01697 {
01698 return IsTileType(tile, MP_CLEAR);
01699 }
01700
01713 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01714 {
01715 SpotData sp = { INVALID_TILE, 0, layout };
01716
01717 TileIndex coast = tile;
01718 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01719 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01720 return sp.tile;
01721 }
01722
01723
01724 return INVALID_TILE;
01725 }
01726
01727 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01728 {
01729 if (!Town::CanAllocateItem()) return NULL;
01730
01731 do {
01732
01733 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01734
01735
01736
01737 if (IsTileType(tile, MP_WATER)) {
01738 tile = FindNearestGoodCoastalTownSpot(tile, layout);
01739 if (tile == INVALID_TILE) continue;
01740 }
01741
01742
01743 if (TownCanBePlacedHere(tile).Failed()) continue;
01744
01745
01746 Town *t = new Town(tile);
01747
01748 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01749
01750
01751
01752 if (t->population > 0) return t;
01753 delete t;
01754 } while (--attempts != 0);
01755
01756 return NULL;
01757 }
01758
01759 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01760
01767 bool GenerateTowns(TownLayout layout)
01768 {
01769 uint num = 0;
01770 uint difficulty = _settings_game.difficulty.number_towns;
01771 uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01772 uint32 townnameparts;
01773
01774 SetGeneratingWorldProgress(GWP_TOWN, n);
01775
01776
01777
01778
01779 do {
01780 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01781 IncreaseGeneratingWorldProgress(GWP_TOWN);
01782
01783 if (!GenerateTownName(&townnameparts)) continue;
01784
01785 if (CreateRandomTown(20, townnameparts, TS_RANDOM, city, layout) != NULL) num++;
01786 } while (--n);
01787
01788 if (num != 0) return true;
01789
01790
01791
01792 if (GenerateTownName(&townnameparts) &&
01793 CreateRandomTown(10000, townnameparts, TS_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01794 return true;
01795 }
01796
01797
01798 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01799 extern StringID _switch_mode_errorstr;
01800 _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01801 }
01802
01803 return false;
01804 }
01805
01806
01812 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01813 {
01814 uint dist = DistanceSquare(tile, t->xy);
01815
01816 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01817
01818 HouseZonesBits smallest = HZB_TOWN_EDGE;
01819 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01820 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01821 }
01822
01823 return smallest;
01824 }
01825
01836 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01837 {
01838 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01839
01840 assert(cc.Succeeded());
01841
01842 IncreaseBuildingCount(t, type);
01843 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01844 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01845
01846 MarkTileDirtyByTile(tile);
01847 }
01848
01849
01860 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01861 {
01862 BuildingFlags size = HouseSpec::Get(type)->building_flags;
01863
01864 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01865 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01866 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01867 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01868 }
01869
01870
01879 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01880 {
01881
01882 Slope slope = GetTileSlope(tile, NULL);
01883 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01884
01885
01886 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01887
01888
01889 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01890
01891
01892 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01893 }
01894
01895
01905 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01906 {
01907 if (!CanBuildHouseHere(tile, town, noslope)) return false;
01908
01909
01910 if (GetTileMaxZ(tile) != z) return false;
01911
01912 return true;
01913 }
01914
01915
01925 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01926 {
01927
01928 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01929
01930 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01931 tile += TileOffsByDiagDir(d);
01932 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01933 }
01934
01935 return true;
01936 }
01937
01938
01946 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01947 {
01948
01949 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01950
01951 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01952
01953 switch (t->layout) {
01954 case TL_2X2_GRID:
01955 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01956 break;
01957
01958 case TL_3X3_GRID:
01959 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01960 break;
01961
01962 default:
01963 break;
01964 }
01965
01966 return true;
01967 }
01968
01969
01977 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01978 {
01979
01980 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01981
01982
01983
01984 uint dx = MapSize() + TileX(t->xy) - TileX(tile);
01985 uint dy = MapSize() + TileY(t->xy) - TileY(tile);
01986
01987 switch (t->layout) {
01988 case TL_2X2_GRID:
01989 if ((dx % 3) != 0 || (dy % 3) != 0) return false;
01990 break;
01991
01992 case TL_3X3_GRID:
01993 if ((dx % 4) < 2 || (dy % 4) < 2) return false;
01994 break;
01995
01996 default:
01997 break;
01998 }
01999
02000 return true;
02001 }
02002
02003
02013 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02014 {
02015
02016
02017 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02018 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02019
02020 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02021 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02022 *tile = tile2;
02023 return true;
02024 }
02025
02026 return false;
02027 }
02028
02029
02038 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02039 {
02040 TileIndex tile2 = *tile;
02041
02042 for (DiagDirection d = DIAGDIR_SE;;d++) {
02043 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02044 *tile = tile2;
02045 return true;
02046 }
02047 if (d == DIAGDIR_END) break;
02048 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
02049 }
02050
02051 return false;
02052 }
02053
02054
02061 static bool BuildTownHouse(Town *t, TileIndex tile)
02062 {
02063
02064 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02065
02066
02067 if (!CanBuildHouseHere(tile, t->index, false)) return false;
02068
02069 uint z;
02070 Slope slope = GetTileSlope(tile, &z);
02071
02072
02073
02074 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02075
02076
02077 int land = _settings_game.game_creation.landscape;
02078 if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02079
02080 uint bitmask = (1 << rad) + (1 << (land + 12));
02081
02082
02083
02084
02085 HouseID houses[HOUSE_MAX];
02086 uint num = 0;
02087 uint probs[HOUSE_MAX];
02088 uint probability_max = 0;
02089
02090
02091 for (uint i = 0; i < HOUSE_MAX; i++) {
02092 const HouseSpec *hs = HouseSpec::Get(i);
02093
02094
02095 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->override != INVALID_HOUSE_ID) continue;
02096
02097
02098 if (hs->class_id != HOUSE_NO_CLASS) {
02099
02100 if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02101 } else {
02102
02103 if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02104 }
02105
02106
02107 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02108 probability_max += cur_prob;
02109 probs[num] = cur_prob;
02110 houses[num++] = (HouseID)i;
02111 }
02112
02113 uint maxz = GetTileMaxZ(tile);
02114
02115 while (probability_max > 0) {
02116 uint r = RandomRange(probability_max);
02117 uint i;
02118 for (i = 0; i < num; i++) {
02119 if (probs[i] > r) break;
02120 r -= probs[i];
02121 }
02122
02123 HouseID house = houses[i];
02124 probability_max -= probs[i];
02125
02126
02127 num--;
02128 houses[i] = houses[num];
02129 probs[i] = probs[num];
02130
02131 const HouseSpec *hs = HouseSpec::Get(house);
02132
02133 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02134 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02135 continue;
02136 }
02137
02138 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02139
02140
02141 uint oneof = 0;
02142
02143 if (hs->building_flags & BUILDING_IS_CHURCH) {
02144 SetBit(oneof, TOWN_HAS_CHURCH);
02145 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02146 SetBit(oneof, TOWN_HAS_STADIUM);
02147 }
02148
02149 if (t->flags & oneof) continue;
02150
02151
02152 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02153 if (noslope && slope != SLOPE_FLAT) continue;
02154
02155 if (hs->building_flags & TILE_SIZE_2x2) {
02156 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02157 } else if (hs->building_flags & TILE_SIZE_2x1) {
02158 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02159 } else if (hs->building_flags & TILE_SIZE_1x2) {
02160 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02161 } else {
02162
02163 }
02164
02165 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02166 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
02167 if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02168 }
02169
02170
02171 t->num_houses++;
02172
02173
02174 t->flags |= oneof;
02175
02176 byte construction_counter = 0;
02177 byte construction_stage = 0;
02178
02179 if (_generating_world || _game_mode == GM_EDITOR) {
02180 uint32 r = Random();
02181
02182 construction_stage = TOWN_HOUSE_COMPLETED;
02183 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02184
02185 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02186 ChangePopulation(t, hs->population);
02187 } else {
02188 construction_counter = GB(r, 2, 2);
02189 }
02190 }
02191
02192 MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
02193
02194 return true;
02195 }
02196
02197 return false;
02198 }
02199
02206 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02207 {
02208 assert(IsTileType(tile, MP_HOUSE));
02209 DecreaseBuildingCount(t, house);
02210 DoClearSquare(tile);
02211 DeleteAnimatedTile(tile);
02212 }
02213
02221 TileIndexDiff GetHouseNorthPart(HouseID &house)
02222 {
02223 if (house >= 3) {
02224 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02225 house--;
02226 return TileDiffXY(-1, 0);
02227 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02228 house--;
02229 return TileDiffXY(0, -1);
02230 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02231 house -= 2;
02232 return TileDiffXY(-1, 0);
02233 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02234 house -= 3;
02235 return TileDiffXY(-1, -1);
02236 }
02237 }
02238 return 0;
02239 }
02240
02241 void ClearTownHouse(Town *t, TileIndex tile)
02242 {
02243 assert(IsTileType(tile, MP_HOUSE));
02244
02245 HouseID house = GetHouseType(tile);
02246
02247
02248 tile += GetHouseNorthPart(house);
02249
02250 const HouseSpec *hs = HouseSpec::Get(house);
02251
02252
02253 if (IsHouseCompleted(tile)) {
02254 ChangePopulation(t, -hs->population);
02255 }
02256
02257 t->num_houses--;
02258
02259
02260 if (hs->building_flags & BUILDING_IS_CHURCH) {
02261 ClrBit(t->flags, TOWN_HAS_CHURCH);
02262 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02263 ClrBit(t->flags, TOWN_HAS_STADIUM);
02264 }
02265
02266
02267 uint eflags = hs->building_flags;
02268 DoClearTownHouseHelper(tile, t, house);
02269 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02270 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02271 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02272 }
02273
02282 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02283 {
02284 Town *t = Town::GetIfValid(p1);
02285 if (t == NULL) return CMD_ERROR;
02286
02287 bool reset = StrEmpty(text);
02288
02289 if (!reset) {
02290 if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
02291 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02292 }
02293
02294 if (flags & DC_EXEC) {
02295 free(t->name);
02296 t->name = reset ? NULL : strdup(text);
02297
02298 t->UpdateVirtCoord();
02299 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02300 UpdateAllStationVirtCoords();
02301 }
02302 return CommandCost();
02303 }
02304
02306 void ExpandTown(Town *t)
02307 {
02308
02309
02310 static bool warned_no_roads = false;
02311 if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
02312 ShowErrorMessage(STR_ERROR_TOWN_EXPAND_WARN_NO_ROADS, INVALID_STRING_ID, 0, 0);
02313 warned_no_roads = true;
02314 }
02315
02316
02317 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02318 t->num_houses += amount;
02319 UpdateTownRadius(t);
02320
02321 uint n = amount * 10;
02322 do GrowTown(t); while (--n);
02323
02324 t->num_houses -= amount;
02325 UpdateTownRadius(t);
02326
02327 UpdateTownMaxPass(t);
02328 }
02329
02333 const byte _town_action_costs[TACT_COUNT] = {
02334 2, 4, 9, 35, 48, 53, 117, 175
02335 };
02336
02337 static void TownActionAdvertiseSmall(Town *t)
02338 {
02339 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02340 }
02341
02342 static void TownActionAdvertiseMedium(Town *t)
02343 {
02344 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02345 }
02346
02347 static void TownActionAdvertiseLarge(Town *t)
02348 {
02349 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02350 }
02351
02352 static void TownActionRoadRebuild(Town *t)
02353 {
02354 t->road_build_months = 6;
02355
02356 char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
02357 SetDParam(0, _current_company);
02358 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02359
02360 char *cn = strdup(company_name);
02361 SetDParam(0, t->index);
02362 SetDParamStr(1, cn);
02363
02364 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02365 }
02366
02367 static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
02368 {
02369
02370 if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02371
02372 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02373
02374 if (!IsTileType(tile, MP_HOUSE) &&
02375 !IsTileType(tile, MP_CLEAR) &&
02376 !IsTileType(tile, MP_TREES)) {
02377 return false;
02378 }
02379
02380 CompanyID old = _current_company;
02381 _current_company = OWNER_NONE;
02382 CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02383 _current_company = old;
02384
02385 if (r.Failed()) return false;
02386
02387 MakeStatue(tile, _current_company, town_id);
02388 MarkTileDirtyByTile(tile);
02389
02390 return true;
02391 }
02392
02399 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02400 {
02401 TownID *town_id = (TownID *)user_data;
02402 return DoBuildStatueOfCompany(tile, *town_id);
02403 }
02404
02410 static void TownActionBuildStatue(Town *t)
02411 {
02412 TileIndex tile = t->xy;
02413
02414 if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
02415 SetBit(t->statues, _current_company);
02416 }
02417 }
02418
02419 static void TownActionFundBuildings(Town *t)
02420 {
02421
02422 t->grow_counter = 1;
02423
02424 SetBit(t->flags, TOWN_IS_FUNDED);
02425
02426 t->fund_buildings_months = 3;
02427 }
02428
02429 static void TownActionBuyRights(Town *t)
02430 {
02431
02432 if (!_settings_game.economy.exclusive_rights) return;
02433
02434 t->exclusive_counter = 12;
02435 t->exclusivity = _current_company;
02436
02437 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02438 }
02439
02440 static void TownActionBribe(Town *t)
02441 {
02442 if (Chance16(1, 14)) {
02443
02444 t->unwanted[_current_company] = 6;
02445
02446
02447 Station *st;
02448 FOR_ALL_STATIONS(st) {
02449 if (st->town == t && st->owner == _current_company) {
02450 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02451 }
02452 }
02453
02454
02455
02456 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, 0, 0);
02457
02458
02459
02460
02461
02462 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02463 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02464 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02465 }
02466 } else {
02467 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02468 }
02469 }
02470
02471 typedef void TownActionProc(Town *t);
02472 static TownActionProc * const _town_action_proc[] = {
02473 TownActionAdvertiseSmall,
02474 TownActionAdvertiseMedium,
02475 TownActionAdvertiseLarge,
02476 TownActionRoadRebuild,
02477 TownActionBuildStatue,
02478 TownActionFundBuildings,
02479 TownActionBuyRights,
02480 TownActionBribe
02481 };
02482
02489 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02490 {
02491 int num = 0;
02492 TownActions buttons = TACT_NONE;
02493
02494
02495 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02496
02497
02498 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02499
02500
02501
02502 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02503 const TownActions cur = (TownActions)(1 << i);
02504
02505
02506 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
02507 continue;
02508
02509
02510 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
02511 continue;
02512
02513
02514 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
02515 continue;
02516
02517 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02518 buttons |= cur;
02519 num++;
02520 }
02521 }
02522 }
02523
02524 if (nump != NULL) *nump = num;
02525 return buttons;
02526 }
02527
02538 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02539 {
02540 Town *t = Town::GetIfValid(p1);
02541 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02542
02543 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02544
02545 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02546
02547 if (flags & DC_EXEC) {
02548 _town_action_proc[p2](t);
02549 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02550 }
02551
02552 return cost;
02553 }
02554
02555 static void UpdateTownGrowRate(Town *t)
02556 {
02557
02558 const Company *c;
02559 FOR_ALL_COMPANIES(c) {
02560 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02561 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02562 }
02563 }
02564
02565 int n = 0;
02566
02567 const Station *st;
02568 FOR_ALL_STATIONS(st) {
02569 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02570 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02571 n++;
02572 if (Company::IsValidID(st->owner)) {
02573 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02574 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02575 }
02576 } else {
02577 if (Company::IsValidID(st->owner)) {
02578 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02579 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02580 }
02581 }
02582 }
02583 }
02584
02585
02586 for (uint i = 0; i < MAX_COMPANIES; i++) {
02587 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02588 }
02589
02590 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02591
02592 ClrBit(t->flags, TOWN_IS_FUNDED);
02593 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02594
02597 static const uint16 _grow_count_values[2][6] = {
02598 { 120, 120, 120, 100, 80, 60 },
02599 { 320, 420, 300, 220, 160, 100 }
02600 };
02601
02602 uint16 m;
02603
02604 if (t->fund_buildings_months != 0) {
02605 m = _grow_count_values[0][min(n, 5)];
02606 t->fund_buildings_months--;
02607 } else {
02608 m = _grow_count_values[1][min(n, 5)];
02609 if (n == 0 && !Chance16(1, 12)) return;
02610 }
02611
02612 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02613 if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
02614 return;
02615 } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02616 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
02617 return;
02618 }
02619
02620
02621
02622 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02623
02624 m >>= growth_multiplier;
02625 if (t->larger_town) m /= 2;
02626
02627 t->growth_rate = m / (t->num_houses / 50 + 1);
02628 if (m <= t->grow_counter)
02629 t->grow_counter = m;
02630
02631 SetBit(t->flags, TOWN_IS_FUNDED);
02632 }
02633
02634 static void UpdateTownAmounts(Town *t)
02635 {
02636
02637 t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02638
02639 t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02640 t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02641 t->act_food = t->new_act_food; t->new_act_food = 0;
02642 t->act_water = t->new_act_water; t->new_act_water = 0;
02643
02644
02645 t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02646 t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02647 t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02648
02649 SetWindowDirty(WC_TOWN_VIEW, t->index);
02650 }
02651
02652 static void UpdateTownUnwanted(Town *t)
02653 {
02654 const Company *c;
02655
02656 FOR_ALL_COMPANIES(c) {
02657 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02658 }
02659 }
02660
02666 bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02667 {
02668 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
02669
02670 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02671 if (t == NULL) return true;
02672
02673 if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
02674
02675 _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02676 SetDParam(0, t->index);
02677
02678 return false;
02679 }
02680
02681
02682 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02683 {
02684 Town *t;
02685 uint best = threshold;
02686 Town *best_town = NULL;
02687
02688 FOR_ALL_TOWNS(t) {
02689 uint dist = DistanceManhattan(tile, t->xy);
02690 if (dist < best) {
02691 best = dist;
02692 best_town = t;
02693 }
02694 }
02695
02696 return best_town;
02697 }
02698
02699
02700 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02701 {
02702 switch (GetTileType(tile)) {
02703 case MP_ROAD:
02704 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02705
02706 if (!HasTownOwnedRoad(tile)) {
02707 TownID tid = GetTownIndex(tile);
02708
02709 if (tid == (TownID)INVALID_TOWN) {
02710
02711 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02712 assert(Town::GetNumItems() == 0);
02713 return NULL;
02714 }
02715
02716 assert(Town::IsValidID(tid));
02717 Town *town = Town::Get(tid);
02718
02719 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02720
02721 return town;
02722 }
02723
02724
02725 case MP_HOUSE:
02726 return Town::GetByTile(tile);
02727
02728 default:
02729 return CalcClosestTownFromTile(tile, threshold);
02730 }
02731 }
02732
02733 static bool _town_rating_test = false;
02734 static SmallMap<const Town *, int, 4> _town_test_ratings;
02735
02736 void SetTownRatingTestMode(bool mode)
02737 {
02738 static int ref_count = 0;
02739 if (mode) {
02740 if (ref_count == 0) {
02741 _town_test_ratings.Clear();
02742 }
02743 ref_count++;
02744 } else {
02745 assert(ref_count > 0);
02746 ref_count--;
02747 }
02748 _town_rating_test = !(ref_count == 0);
02749 }
02750
02751 static int GetRating(const Town *t)
02752 {
02753 if (_town_rating_test) {
02754 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02755 if (it != _town_test_ratings.End()) {
02756 return it->second;
02757 }
02758 }
02759 return t->ratings[_current_company];
02760 }
02761
02769 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02770 {
02771
02772 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02773 !Company::IsValidID(_current_company) ||
02774 (_cheats.magic_bulldozer.value && add < 0)) {
02775 return;
02776 }
02777
02778 int rating = GetRating(t);
02779 if (add < 0) {
02780 if (rating > max) {
02781 rating += add;
02782 if (rating < max) rating = max;
02783 }
02784 } else {
02785 if (rating < max) {
02786 rating += add;
02787 if (rating > max) rating = max;
02788 }
02789 }
02790 if (_town_rating_test) {
02791 _town_test_ratings[t] = rating;
02792 } else {
02793 SetBit(t->have_ratings, _current_company);
02794 t->ratings[_current_company] = rating;
02795 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02796 }
02797 }
02798
02799 bool CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
02800 {
02801
02802 if (t == NULL || !Company::IsValidID(_current_company) ||
02803 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
02804 return true;
02805 }
02806
02807
02808 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
02809
02810 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE},
02811 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL},
02812 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE},
02813 };
02814
02815
02816
02817
02818
02819 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
02820
02821 if (GetRating(t) < needed) {
02822 SetDParam(0, t->index);
02823 _error_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS;
02824 return false;
02825 }
02826
02827 return true;
02828 }
02829
02830 void TownsMonthlyLoop()
02831 {
02832 Town *t;
02833
02834 FOR_ALL_TOWNS(t) {
02835 if (t->road_build_months != 0) t->road_build_months--;
02836
02837 if (t->exclusive_counter != 0)
02838 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
02839
02840 UpdateTownGrowRate(t);
02841 UpdateTownAmounts(t);
02842 UpdateTownUnwanted(t);
02843 }
02844 }
02845
02846 void TownsYearlyLoop()
02847 {
02848
02849 for (TileIndex t = 0; t < MapSize(); t++) {
02850 if (!IsTileType(t, MP_HOUSE)) continue;
02851 IncrementHouseAge(t);
02852 }
02853 }
02854
02855 void InitializeTowns()
02856 {
02857 _town_pool.CleanPool();
02858 }
02859
02860 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
02861 {
02862 if (AutoslopeEnabled()) {
02863 HouseID house = GetHouseType(tile);
02864 GetHouseNorthPart(house);
02865 const HouseSpec *hs = HouseSpec::Get(house);
02866
02867
02868 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
02869 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
02870 bool allow_terraform = true;
02871
02872
02873 house = GetHouseType(tile);
02874 hs = HouseSpec::Get(house);
02875 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
02876
02877 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
02878 if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
02879 }
02880
02881 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
02882 }
02883 }
02884
02885 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02886 }
02887
02889 extern const TileTypeProcs _tile_type_town_procs = {
02890 DrawTile_Town,
02891 GetSlopeZ_Town,
02892 ClearTile_Town,
02893 AddAcceptedCargo_Town,
02894 GetTileDesc_Town,
02895 GetTileTrackStatus_Town,
02896 NULL,
02897 AnimateTile_Town,
02898 TileLoop_Town,
02899 ChangeTileOwner_Town,
02900 AddProducedCargo_Town,
02901 NULL,
02902 GetFoundation_Town,
02903 TerraformTile_Town,
02904 };
02905
02906
02907 HouseSpec _house_specs[HOUSE_MAX];
02908
02909 void ResetHouses()
02910 {
02911 memset(&_house_specs, 0, sizeof(_house_specs));
02912 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
02913
02914
02915 _house_mngr.ResetOverride();
02916 }