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 "cmd_helper.h"
00018 #include "command_func.h"
00019 #include "industry.h"
00020 #include "station_base.h"
00021 #include "company_base.h"
00022 #include "news_func.h"
00023 #include "gui.h"
00024 #include "object.h"
00025 #include "genworld.h"
00026 #include "newgrf_debug.h"
00027 #include "newgrf_house.h"
00028 #include "newgrf_text.h"
00029 #include "newgrf_config.h"
00030 #include "autoslope.h"
00031 #include "tunnelbridge_map.h"
00032 #include "strings_func.h"
00033 #include "window_func.h"
00034 #include "string_func.h"
00035 #include "newgrf_cargo.h"
00036 #include "cheat_type.h"
00037 #include "animated_tile_func.h"
00038 #include "date_func.h"
00039 #include "subsidy_func.h"
00040 #include "core/pool_func.hpp"
00041 #include "town.h"
00042 #include "townname_func.h"
00043 #include "townname_type.h"
00044 #include "core/random_func.hpp"
00045 #include "core/backup_type.hpp"
00046 #include "depot_base.h"
00047 #include "object_map.h"
00048 #include "object_base.h"
00049 #include "ai/ai.hpp"
00050
00051 #include "table/strings.h"
00052 #include "table/town_land.h"
00053
00054 TownID _new_town_id;
00055
00056
00057 TownPool _town_pool("Town");
00058 INSTANTIATE_POOL_METHODS(Town)
00059
00060 Town::~Town()
00061 {
00062 free(this->name);
00063
00064 if (CleaningPool()) return;
00065
00066
00067
00068 DeleteWindowById(WC_TOWN_VIEW, this->index);
00069
00070
00071 const Industry *i;
00072 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00073
00074
00075 const Object *o;
00076 FOR_ALL_OBJECTS(o) assert(o->town != this);
00077
00078
00079 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00080 switch (GetTileType(tile)) {
00081 case MP_HOUSE:
00082 assert(GetTownIndex(tile) != this->index);
00083 break;
00084
00085 case MP_ROAD:
00086 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00087 break;
00088
00089 case MP_TUNNELBRIDGE:
00090 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00091 break;
00092
00093 default:
00094 break;
00095 }
00096 }
00097
00098 DeleteSubsidyWith(ST_TOWN, this->index);
00099 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
00100 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00101 MarkWholeScreenDirty();
00102 }
00103
00104
00110 void Town::PostDestructor(size_t index)
00111 {
00112 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00113 UpdateNearestTownForRoadTiles(false);
00114
00115
00116 Object *o;
00117 FOR_ALL_OBJECTS(o) {
00118 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00119 }
00120 }
00121
00125 void Town::InitializeLayout(TownLayout layout)
00126 {
00127 if (layout != TL_RANDOM) {
00128 this->layout = layout;
00129 return;
00130 }
00131
00132 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00133 }
00134
00139 Town *Town::GetRandom()
00140 {
00141 if (Town::GetNumItems() == 0) return NULL;
00142 int num = RandomRange((uint16)Town::GetNumItems());
00143 size_t index = MAX_UVALUE(size_t);
00144
00145 while (num >= 0) {
00146 num--;
00147 index++;
00148
00149
00150 while (!Town::IsValidID(index)) {
00151 index++;
00152 assert(index < Town::GetPoolSize());
00153 }
00154 }
00155
00156 return Town::Get(index);
00157 }
00158
00167 void Town::UpdateLabel()
00168 {
00169 if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
00170 int r = this->ratings[_local_company];
00171 (this->town_label = 0, r <= RATING_VERYPOOR) ||
00172 (this->town_label++, r <= RATING_MEDIOCRE) ||
00173 (this->town_label++, r <= RATING_GOOD) ||
00174 (this->town_label++, r <= RATING_VERYGOOD) ||
00175 (this->town_label++, true);
00176 }
00177 }
00178
00183 Money HouseSpec::GetRemovalCost() const
00184 {
00185 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00186 }
00187
00188
00189 static int _grow_town_result;
00190
00191
00192 enum TownGrowthResult {
00193 GROWTH_SUCCEED = -1,
00194 GROWTH_SEARCH_STOPPED = 0
00195
00196 };
00197
00198 static bool BuildTownHouse(Town *t, TileIndex tile);
00199 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00200
00201 static void TownDrawHouseLift(const TileInfo *ti)
00202 {
00203 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00204 }
00205
00206 typedef void TownDrawTileProc(const TileInfo *ti);
00207 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00208 TownDrawHouseLift
00209 };
00210
00216 static inline DiagDirection RandomDiagDir()
00217 {
00218 return (DiagDirection)(3 & Random());
00219 }
00220
00226 static void DrawTile_Town(TileInfo *ti)
00227 {
00228 HouseID house_id = GetHouseType(ti->tile);
00229
00230 if (house_id >= NEW_HOUSE_OFFSET) {
00231
00232
00233
00234 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00235 DrawNewHouseTile(ti, house_id);
00236 return;
00237 } else {
00238 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00239 }
00240 }
00241
00242
00243 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00244
00245 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00246
00247 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00248
00249
00250 if (IsInvisibilitySet(TO_HOUSES)) return;
00251
00252
00253 SpriteID image = dcts->building.sprite;
00254 if (image != 0) {
00255 AddSortableSpriteToDraw(image, dcts->building.pal,
00256 ti->x + dcts->subtile_x,
00257 ti->y + dcts->subtile_y,
00258 dcts->width,
00259 dcts->height,
00260 dcts->dz,
00261 ti->z,
00262 IsTransparencySet(TO_HOUSES)
00263 );
00264
00265 if (IsTransparencySet(TO_HOUSES)) return;
00266 }
00267
00268 {
00269 int proc = dcts->draw_proc - 1;
00270
00271 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00272 }
00273 }
00274
00275 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00276 {
00277 return GetTileMaxZ(tile);
00278 }
00279
00281 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00282 {
00283 HouseID hid = GetHouseType(tile);
00284
00285
00286
00287
00288
00289 if (hid >= NEW_HOUSE_OFFSET) {
00290 const HouseSpec *hs = HouseSpec::Get(hid);
00291 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00292 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00293 if (callback_res == 0) return FOUNDATION_NONE;
00294 }
00295 }
00296 return FlatteningFoundation(tileh);
00297 }
00298
00305 static void AnimateTile_Town(TileIndex tile)
00306 {
00307 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00308 AnimateNewHouseTile(tile);
00309 return;
00310 }
00311
00312 if (_tick_counter & 3) return;
00313
00314
00315
00316
00317
00318 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00319 DeleteAnimatedTile(tile);
00320 return;
00321 }
00322
00323 if (!LiftHasDestination(tile)) {
00324 uint i;
00325
00326
00327
00328
00329
00330 do {
00331 i = RandomRange(7);
00332 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00333
00334 SetLiftDestination(tile, i);
00335 }
00336
00337 int pos = GetLiftPosition(tile);
00338 int dest = GetLiftDestination(tile) * 6;
00339 pos += (pos < dest) ? 1 : -1;
00340 SetLiftPosition(tile, pos);
00341
00342 if (pos == dest) {
00343 HaltLift(tile);
00344 DeleteAnimatedTile(tile);
00345 }
00346
00347 MarkTileDirtyByTile(tile);
00348 }
00349
00356 static bool IsCloseToTown(TileIndex tile, uint dist)
00357 {
00358 const Town *t;
00359
00360 FOR_ALL_TOWNS(t) {
00361 if (DistanceManhattan(tile, t->xy) < dist) return true;
00362 }
00363 return false;
00364 }
00365
00370 void Town::UpdateVirtCoord()
00371 {
00372 this->UpdateLabel();
00373 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00374 SetDParam(0, this->index);
00375 SetDParam(1, this->population);
00376 this->sign.UpdatePosition(pt.x, pt.y - 24, this->Label());
00377
00378 SetWindowDirty(WC_TOWN_VIEW, this->index);
00379 }
00380
00382 void UpdateAllTownVirtCoords()
00383 {
00384 Town *t;
00385
00386 FOR_ALL_TOWNS(t) {
00387 t->UpdateVirtCoord();
00388 }
00389 }
00390
00396 static void ChangePopulation(Town *t, int mod)
00397 {
00398 t->population += mod;
00399 SetWindowDirty(WC_TOWN_VIEW, t->index);
00400 t->UpdateVirtCoord();
00401
00402 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00403 }
00404
00410 uint32 GetWorldPopulation()
00411 {
00412 uint32 pop = 0;
00413 const Town *t;
00414
00415 FOR_ALL_TOWNS(t) pop += t->population;
00416 return pop;
00417 }
00418
00423 static void MakeSingleHouseBigger(TileIndex tile)
00424 {
00425 assert(IsTileType(tile, MP_HOUSE));
00426
00427
00428 IncHouseConstructionTick(tile);
00429 if (GetHouseConstructionTick(tile) != 0) return;
00430
00431 AnimateNewHouseConstruction(tile);
00432
00433 if (IsHouseCompleted(tile)) {
00434
00435
00436 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00437 ResetHouseAge(tile);
00438 }
00439 MarkTileDirtyByTile(tile);
00440 }
00441
00446 static void MakeTownHouseBigger(TileIndex tile)
00447 {
00448 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00449 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00450 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00451 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00452 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00453 }
00454
00465 static void TownGenerateCargo (Town *t, CargoID ct, uint amount, StationFinder &stations)
00466 {
00467
00468 int cf = _settings_game.economy.town_cargo_factor;
00469
00470
00471 if (EconomyIsInRecession())
00472 amount = (amount + 1) >> 1;
00473
00474
00475 if (cf < 0) {
00476
00477
00478
00479 amount = (amount + ((1 << -cf) - 1)) >> -cf;
00480 } else if (cf > 0) {
00481
00482
00483 amount = amount << cf;
00484 }
00485
00486
00487 assert(amount > 0);
00488
00489
00490 uint moved = MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
00491
00492
00493 const CargoSpec *cs = CargoSpec::Get(ct);
00494 switch (cs->town_effect) {
00495 case TE_PASSENGERS:
00496 t->new_gen_max_pass += amount;
00497 t->new_gen_act_pass += moved;
00498 break;
00499
00500 case TE_MAIL:
00501 t->new_gen_max_mail += amount;
00502 t->new_gen_act_mail += moved;
00503 break;
00504
00505 default:
00506 break;
00507 }
00508 }
00509
00516 static void TileLoop_Town(TileIndex tile)
00517 {
00518 HouseID house_id = GetHouseType(tile);
00519
00520
00521
00522 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00523
00524 if (!IsHouseCompleted(tile)) {
00525
00526 MakeTownHouseBigger(tile);
00527 return;
00528 }
00529
00530 const HouseSpec *hs = HouseSpec::Get(house_id);
00531
00532
00533 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00534 house_id < NEW_HOUSE_OFFSET &&
00535 !LiftHasDestination(tile) &&
00536 Chance16(1, 2)) {
00537 AddAnimatedTile(tile);
00538 }
00539
00540 Town *t = Town::GetByTile(tile);
00541 uint32 r = Random();
00542
00543 StationFinder stations(TileArea(tile, 1, 1));
00544
00545 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00546 for (uint i = 0; i < 256; i++) {
00547 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00548
00549 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00550
00551 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00552 if (cargo == CT_INVALID) continue;
00553
00554 uint amt = GB(callback, 0, 8);
00555 if (amt == 0) continue;
00556
00557 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00558
00559 const CargoSpec *cs = CargoSpec::Get(cargo);
00560 switch (cs->town_effect) {
00561 case TE_PASSENGERS:
00562 TownGenerateCargo(t, cargo, amt, stations);
00563 t->new_max_pass += amt;
00564 t->new_act_pass += moved;
00565 break;
00566
00567 case TE_MAIL:
00568 TownGenerateCargo(t, cargo, amt, stations);
00569 t->new_max_mail += amt;
00570 t->new_act_mail += moved;
00571 break;
00572
00573 case TE_FOOD:
00574 t->new_max_food += amt;
00575 t->new_act_food += moved;
00576 break;
00577
00578 case TE_WATER:
00579 t->new_max_water += amt;
00580 t->new_act_water += moved;
00581 break;
00582
00583 case TE_GOODS:
00584 t->new_max_goods += amt;
00585 t->new_act_goods += moved;
00586 break;
00587
00588 default:
00589 break;
00590 }
00591 }
00592 } else {
00593 if (GB(r, 0, 8) < hs->population) {
00594 uint amt = GB(r, 0, 8) / 8 + 1;
00595
00596 TownGenerateCargo(t, CT_PASSENGERS, amt, stations);
00597 }
00598
00599 if (GB(r, 8, 8) < hs->mail_generation) {
00600 uint amt = GB(r, 8, 8) / 8 + 1;
00601
00602 TownGenerateCargo(t, CT_MAIL, amt, stations);
00603 }
00604
00605 UpdateTownDemands(t);
00606 }
00607
00608 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00609
00610 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00611 HasBit(t->flags, TOWN_IS_FUNDED) &&
00612 CanDeleteHouse(tile) &&
00613 GetHouseAge(tile) >= (hs->minimum_life * _date_daylength_factor) &&
00614 --t->time_until_rebuild == 0) {
00615 t->time_until_rebuild = GB(r, 16, 8) + 192;
00616
00617 ClearTownHouse(t, tile);
00618
00619
00620 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00621 }
00622
00623 cur_company.Restore();
00624 }
00625
00626 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00627 {
00628 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00629 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00630
00631 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00632
00633 CommandCost cost(EXPENSES_CONSTRUCTION);
00634 cost.AddCost(hs->GetRemovalCost());
00635
00636 int rating = hs->remove_rating_decrease;
00637 Town *t = Town::GetByTile(tile);
00638
00639 if (Company::IsValidID(_current_company)) {
00640 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00641 SetDParam(0, t->index);
00642 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00643 }
00644 }
00645
00646 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00647 if (flags & DC_EXEC) {
00648 ClearTownHouse(t, tile);
00649 }
00650
00651 return cost;
00652 }
00653
00654 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00655 {
00656 HouseID house_id = GetHouseType(tile);
00657 const HouseSpec *hs = HouseSpec::Get(house_id);
00658 Town *t = Town::GetByTile(tile);
00659
00660 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00661 for (uint i = 0; i < 256; i++) {
00662 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00663
00664 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00665
00666 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00667
00668 if (cargo == CT_INVALID) continue;
00669 produced[cargo]++;
00670 }
00671 } else {
00672 if (hs->population > 0) {
00673 produced[CT_PASSENGERS]++;
00674 }
00675 if (hs->mail_generation > 0) {
00676 produced[CT_MAIL]++;
00677 }
00678 }
00679 }
00680
00681 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00682 {
00683 if (cargo == CT_INVALID || amount == 0) return;
00684 acceptance[cargo] += amount;
00685 SetBit(*always_accepted, cargo);
00686 }
00687
00688 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00689 {
00690 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00691 CargoID accepts[3];
00692
00693
00694 for (uint8 i = 0; i < lengthof(accepts); i++) {
00695 accepts[i] = hs->accepts_cargo[i];
00696 }
00697
00698
00699 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00700 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00701 if (callback != CALLBACK_FAILED) {
00702
00703 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
00704 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
00705 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00706 }
00707 }
00708
00709
00710 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00711 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00712 if (callback != CALLBACK_FAILED) {
00713 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00714 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00715 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00716
00717 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00718 } else {
00719 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00720 }
00721 return;
00722 }
00723 }
00724
00725
00726 for (uint8 i = 0; i < lengthof(accepts); i++) {
00727 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00728 }
00729 }
00730
00731 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00732 {
00733 const HouseID house = GetHouseType(tile);
00734 const HouseSpec *hs = HouseSpec::Get(house);
00735 bool house_completed = IsHouseCompleted(tile);
00736
00737 td->str = hs->building_name;
00738
00739 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00740 if (callback_res != CALLBACK_FAILED) {
00741 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00742 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00743 td->str = new_name;
00744 }
00745 }
00746
00747 if (!house_completed) {
00748 SetDParamX(td->dparam, 0, td->str);
00749 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00750 }
00751
00752 if (hs->grf_prop.grffile != NULL) {
00753 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00754 td->grf = gc->GetName();
00755 }
00756
00757 td->owner[0] = OWNER_TOWN;
00758 }
00759
00760 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00761 {
00762
00763 return 0;
00764 }
00765
00766 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00767 {
00768
00769 }
00770
00771 static bool GrowTown(Town *t);
00772
00773 static void TownTickHandler(Town *t)
00774 {
00775 if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00776 int i = t->grow_counter - 1;
00777 if (i < 0) {
00778 if (GrowTown(t)) {
00779 i = t->growth_rate;
00780 } else {
00781 i = 0;
00782 }
00783 }
00784 t->grow_counter = i;
00785 }
00786
00787 UpdateTownRadius(t);
00788 }
00789
00790 void OnTick_Town()
00791 {
00792 if (_game_mode == GM_EDITOR) return;
00793
00794 Town *t;
00795 FOR_ALL_TOWNS(t) {
00796
00797 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00798 TownTickHandler(t);
00799 }
00800 }
00801 }
00802
00811 static RoadBits GetTownRoadBits(TileIndex tile)
00812 {
00813 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00814
00815 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00816 }
00817
00828 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00829 {
00830 if (!IsValidTile(tile)) return false;
00831
00832
00833 const TileIndexDiff tid_lt[3] = {
00834 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00835 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00836 TileOffsByDiagDir(ReverseDiagDir(dir)),
00837 };
00838
00839 dist_multi = (dist_multi + 1) * 4;
00840 for (uint pos = 4; pos < dist_multi; pos++) {
00841
00842 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00843
00844
00845 if (pos & 2) cur += tid_lt[2];
00846
00847
00848 if (IsValidTile(tile + cur) &&
00849 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00850 }
00851 return false;
00852 }
00853
00862 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00863 {
00864 if (DistanceFromEdge(tile) == 0) return false;
00865
00866 Slope cur_slope, desired_slope;
00867
00868 for (;;) {
00869
00870 if (GetTownRoadBits(tile) == ROAD_NONE) {
00871
00872
00873
00874 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00875 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00876 return false;
00877 }
00878
00879 cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00880 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00881 if (cur_slope == SLOPE_FLAT) return ret;
00882
00883
00884
00885 desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00886 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00887 if (Chance16(1, 8)) {
00888 CommandCost res = CMD_ERROR;
00889 if (!_generating_world && Chance16(1, 10)) {
00890
00891 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00892 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00893 }
00894 if (res.Failed() && Chance16(1, 3)) {
00895
00896 return ret;
00897 }
00898 }
00899 return false;
00900 }
00901 return ret;
00902 }
00903 }
00904
00905 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00906 {
00907 assert(tile < MapSize());
00908
00909 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00910 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00911 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00912 return true;
00913 }
00914
00915 static void LevelTownLand(TileIndex tile)
00916 {
00917 assert(tile < MapSize());
00918
00919
00920 if (IsTileType(tile, MP_HOUSE)) return;
00921 Slope tileh = GetTileSlope(tile, NULL);
00922 if (tileh == SLOPE_FLAT) return;
00923
00924
00925 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00926 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00927 }
00928 }
00929
00939 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00940 {
00941
00942 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00943 RoadBits rcmd = ROAD_NONE;
00944
00945 switch (t->layout) {
00946 default: NOT_REACHED();
00947
00948 case TL_2X2_GRID:
00949 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00950 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00951 break;
00952
00953 case TL_3X3_GRID:
00954 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00955 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00956 break;
00957 }
00958
00959
00960 if (rcmd != ROAD_ALL) return rcmd;
00961
00962 RoadBits rb_template;
00963
00964 switch (GetTileSlope(tile, NULL)) {
00965 default: rb_template = ROAD_ALL; break;
00966 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00967 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00968 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00969 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00970 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00971 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00972 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00973 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00974 case SLOPE_STEEP_W:
00975 case SLOPE_STEEP_S:
00976 case SLOPE_STEEP_E:
00977 case SLOPE_STEEP_N:
00978 rb_template = ROAD_NONE;
00979 break;
00980 }
00981
00982
00983 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00984
00985 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00986 }
00987
00998 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00999 {
01000
01001 if (DistanceFromEdge(tile) == 0) return false;
01002
01003 uint counter = 0;
01004
01005
01006 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
01007
01008
01009
01010 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
01011 case MP_HOUSE:
01012 case MP_VOID:
01013 counter++;
01014 break;
01015
01016 default:
01017 break;
01018 }
01019
01020
01021 if (counter >= 3) {
01022 if (BuildTownHouse(t, tile)) {
01023 _grow_town_result = GROWTH_SUCCEED;
01024 return true;
01025 }
01026 return false;
01027 }
01028 }
01029 return false;
01030 }
01031
01040 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01041 {
01042 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01043 _grow_town_result = GROWTH_SUCCEED;
01044 return true;
01045 }
01046 return false;
01047 }
01048
01059 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01060 {
01061 assert(bridge_dir < DIAGDIR_END);
01062
01063 const Slope slope = GetTileSlope(tile, NULL);
01064 if (slope == SLOPE_FLAT) return false;
01065
01066
01067
01068
01069 if (slope & InclinedSlope(bridge_dir)) return false;
01070
01071
01072 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01073
01074
01075 uint8 bridge_length = 0;
01076 TileIndex bridge_tile = tile;
01077
01078 const int delta = TileOffsByDiagDir(bridge_dir);
01079 do {
01080 if (bridge_length++ >= 11) {
01081
01082 return false;
01083 }
01084 bridge_tile += delta;
01085 } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
01086
01087
01088 if (bridge_length == 1) return false;
01089
01090 for (uint8 times = 0; times <= 22; times++) {
01091 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01092
01093
01094 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01095 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01096 _grow_town_result = GROWTH_SUCCEED;
01097 return true;
01098 }
01099 }
01100
01101 return false;
01102 }
01103
01121 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01122 {
01123 RoadBits rcmd = ROAD_NONE;
01124 TileIndex tile = *tile_ptr;
01125
01126 assert(tile < MapSize());
01127
01128 if (cur_rb == ROAD_NONE) {
01129
01130
01131 _grow_town_result = GROWTH_SEARCH_STOPPED;
01132
01133 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01134 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01135
01136
01137 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01138
01139
01140 switch (t1->layout) {
01141 default: NOT_REACHED();
01142
01143 case TL_3X3_GRID:
01144 case TL_2X2_GRID:
01145 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01146 if (rcmd == ROAD_NONE) return;
01147 break;
01148
01149 case TL_BETTER_ROADS:
01150 case TL_ORIGINAL:
01151 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01152
01153 DiagDirection source_dir = ReverseDiagDir(target_dir);
01154
01155 if (Chance16(1, 4)) {
01156
01157 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01158 }
01159
01160 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01161
01162
01163 if (target_dir != ReverseDiagDir(source_dir)) return;
01164
01165
01166 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01167 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01168 return;
01169 }
01170
01171
01172
01173 }
01174
01175 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01176 break;
01177 }
01178
01179 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01180
01181
01182
01183 _grow_town_result = GROWTH_SEARCH_STOPPED;
01184
01185 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01186
01187 switch (t1->layout) {
01188 default: NOT_REACHED();
01189
01190 case TL_3X3_GRID:
01191 case TL_2X2_GRID:
01192 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01193 break;
01194
01195 case TL_BETTER_ROADS:
01196 case TL_ORIGINAL:
01197 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01198 break;
01199 }
01200 } else {
01201 bool allow_house = true;
01202
01203
01204 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01205 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01206 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01207 }
01208 return;
01209 }
01210
01211
01212
01213 target_dir = RandomDiagDir();
01214 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01215
01216
01217 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01218
01219
01220 if (HasTileWaterGround(house_tile)) return;
01221
01222 if (!IsValidTile(house_tile)) return;
01223
01224 if (_settings_game.economy.allow_town_roads || _generating_world) {
01225 switch (t1->layout) {
01226 default: NOT_REACHED();
01227
01228 case TL_3X3_GRID:
01229 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01230
01231
01232 case TL_2X2_GRID:
01233 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01234 allow_house = (rcmd == ROAD_NONE);
01235 break;
01236
01237 case TL_BETTER_ROADS:
01238 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01239
01240
01241 case TL_ORIGINAL:
01242
01243
01244 rcmd = DiagDirToRoadBits(target_dir);
01245 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01246 break;
01247 }
01248 }
01249
01250 if (allow_house) {
01251
01252 if (!IsTileType(house_tile, MP_HOUSE)) {
01253
01254 if (Chance16(1, 6)) LevelTownLand(house_tile);
01255
01256
01257
01258 if (BuildTownHouse(t1, house_tile)) {
01259 _grow_town_result = GROWTH_SUCCEED;
01260 }
01261 }
01262 return;
01263 }
01264
01265 _grow_town_result = GROWTH_SEARCH_STOPPED;
01266 }
01267
01268
01269 if (HasTileWaterGround(tile)) return;
01270
01271
01272 rcmd = CleanUpRoadBits(tile, rcmd);
01273 if (rcmd == ROAD_NONE) return;
01274
01275
01276
01277
01278 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01279
01280 GrowTownWithRoad(t1, tile, rcmd);
01281 }
01282
01289 static int GrowTownAtRoad(Town *t, TileIndex tile)
01290 {
01291
01292
01293
01294 DiagDirection target_dir = DIAGDIR_END;
01295
01296 assert(tile < MapSize());
01297
01298
01299
01300
01301 switch (t->layout) {
01302 case TL_BETTER_ROADS:
01303 _grow_town_result = 10 + t->num_houses * 2 / 9;
01304 break;
01305
01306 case TL_3X3_GRID:
01307 case TL_2X2_GRID:
01308 _grow_town_result = 10 + t->num_houses * 1 / 9;
01309 break;
01310
01311 default:
01312 _grow_town_result = 10 + t->num_houses * 4 / 9;
01313 break;
01314 }
01315
01316 do {
01317 RoadBits cur_rb = GetTownRoadBits(tile);
01318
01319
01320 GrowTownInTile(&tile, cur_rb, target_dir, t);
01321
01322
01323
01324 cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01325 if (cur_rb == ROAD_NONE) {
01326 return _grow_town_result;
01327 }
01328
01329
01330
01331 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01332 tile = TileAddByDiagDir(tile, target_dir);
01333
01334 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01335
01336 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01337 _grow_town_result = GROWTH_SUCCEED;
01338 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01339
01340
01341 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01342 SetTownIndex(tile, t->index);
01343 }
01344 }
01345
01346
01347 } while (--_grow_town_result >= 0);
01348
01349 return (_grow_town_result == -2);
01350 }
01351
01359 static RoadBits GenRandomRoadBits()
01360 {
01361 uint32 r = Random();
01362 uint a = GB(r, 0, 2);
01363 uint b = GB(r, 8, 2);
01364 if (a == b) b ^= 2;
01365 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01366 }
01367
01373 static bool GrowTown(Town *t)
01374 {
01375 static const TileIndexDiffC _town_coord_mod[] = {
01376 {-1, 0},
01377 { 1, 1},
01378 { 1, -1},
01379 {-1, -1},
01380 {-1, 0},
01381 { 0, 2},
01382 { 2, 0},
01383 { 0, -2},
01384 {-1, -1},
01385 {-2, 2},
01386 { 2, 2},
01387 { 2, -2},
01388 { 0, 0}
01389 };
01390
01391
01392 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01393
01394 TileIndex tile = t->xy;
01395
01396
01397 const TileIndexDiffC *ptr;
01398 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01399 if (GetTownRoadBits(tile) != ROAD_NONE) {
01400 int r = GrowTownAtRoad(t, tile);
01401 cur_company.Restore();
01402 return r != 0;
01403 }
01404 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01405 }
01406
01407
01408
01409 if (_settings_game.economy.allow_town_roads || _generating_world) {
01410 tile = t->xy;
01411 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01412
01413 if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
01414 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01415 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01416 cur_company.Restore();
01417 return true;
01418 }
01419 }
01420 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01421 }
01422 }
01423
01424 cur_company.Restore();
01425 return false;
01426 }
01427
01428 void UpdateTownRadius(Town *t)
01429 {
01430 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01431 { 4, 0, 0, 0, 0},
01432 { 16, 0, 0, 0, 0},
01433 { 25, 0, 0, 0, 0},
01434 { 36, 0, 0, 0, 0},
01435 { 49, 0, 4, 0, 0},
01436 { 64, 0, 4, 0, 0},
01437 { 64, 0, 9, 0, 1},
01438 { 64, 0, 9, 0, 4},
01439 { 64, 0, 16, 0, 4},
01440 { 81, 0, 16, 0, 4},
01441 { 81, 0, 16, 0, 4},
01442 { 81, 0, 25, 0, 9},
01443 { 81, 36, 25, 0, 9},
01444 { 81, 36, 25, 16, 9},
01445 { 81, 49, 0, 25, 9},
01446 { 81, 64, 0, 25, 9},
01447 { 81, 64, 0, 36, 9},
01448 { 81, 64, 0, 36, 16},
01449 {100, 81, 0, 49, 16},
01450 {100, 81, 0, 49, 25},
01451 {121, 81, 0, 49, 25},
01452 {121, 81, 0, 49, 25},
01453 {121, 81, 0, 49, 36},
01454 };
01455
01456 if (t->num_houses < 92) {
01457 memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01458 } else {
01459 int mass = t->num_houses / 8;
01460
01461
01462
01463 t->squared_town_zone_radius[0] = mass * 15 - 40;
01464 t->squared_town_zone_radius[1] = mass * 9 - 15;
01465 t->squared_town_zone_radius[2] = 0;
01466 t->squared_town_zone_radius[3] = mass * 5 - 5;
01467 t->squared_town_zone_radius[4] = mass * 3 + 5;
01468 }
01469 }
01470
01475 void UpdateTownGenCargo(Town *t)
01476 {
01477 t->gen_max_pass = t->population >> 3;
01478 t->gen_max_mail = t->population >> 4;
01479 }
01480
01485 void UpdateTownDemands(Town *t)
01486 {
01487 byte dtg;
01488 if(!t->larger_town) {
01489 dtg = _difficulty_town_needed_for_growth[_settings_game.economy.town_growth_cargo];
01490 } else {
01491 dtg = _difficulty_town_needed_for_growth[_settings_game.economy.larger_town_growth_cargo];
01492 }
01493 int cf = _settings_game.economy.town_cargo_factor;
01494 uint popul = t->population;
01495 if (t->larger_town) popul *= 2;
01496
01497
01498 t->max_pass = ((popul >> 3) / 4 * dtg) * _date_daylength_factor;
01499 t->max_mail = ((popul >> 4) / 4 * dtg) * _date_daylength_factor;
01500
01501 if (cf < 0) {
01502
01503
01504
01505 t->max_pass = (t->max_pass + ((1 << -cf) - 1)) >> -cf;
01506 t->max_mail = (t->max_mail + ((1 << -cf) - 1)) >> -cf;
01507 } else if (cf > 0) {
01508
01509
01510 t->max_pass = t->max_pass << cf;
01511 t->max_mail = t->max_mail << cf;
01512 }
01513
01514 t->max_food = ((popul >> 2) / 7 / 4) * dtg;
01515 t->max_water = ((popul >> 4) * 5 / 9 / 4) * dtg;
01516 t->max_goods = ((popul >> 2) / 5 / 4) * dtg;
01517 }
01518
01530 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01531 {
01532 t->xy = tile;
01533 t->num_houses = 0;
01534 t->time_until_rebuild = 10 * _date_daylength_factor;
01535 UpdateTownRadius(t);
01536 t->flags = 0;
01537 t->population = 0;
01538 t->grow_counter = 0;
01539 t->growth_rate = 250;
01540
01541 t->gen_act_pass = 0;
01542 t->gen_act_mail = 0;
01543 t->gen_max_pass = 0;
01544 t->gen_max_mail = 0;
01545 t->new_gen_max_pass = 0;
01546 t->new_gen_max_mail = 0;
01547 t->new_gen_act_pass = 0;
01548 t->new_gen_act_mail = 0;
01549
01550 t->new_max_pass = 0;
01551 t->new_max_mail = 0;
01552 t->new_max_food = 0;
01553 t->new_max_water = 0;
01554 t->new_max_goods = 0;
01555 t->new_act_pass = 0;
01556 t->new_act_mail = 0;
01557 t->new_act_food = 0;
01558 t->new_act_water = 0;
01559 t->new_act_goods = 0;
01560 t->max_pass = 0;
01561 t->max_mail = 0;
01562 t->max_food = 0;
01563 t->max_water = 0;
01564 t->max_goods = 0;
01565 t->act_pass = 0;
01566 t->act_mail = 0;
01567 t->act_food = 0;
01568 t->act_water = 0;
01569 t->act_goods = 0;
01570
01571 t->pct_pass_transported = 0;
01572 t->pct_mail_transported = 0;
01573 t->pct_food_transported = 0;
01574 t->pct_water_transported = 0;
01575 t->pct_goods_transported = 0;
01576
01577 t->fund_buildings_months = 0;
01578
01579 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01580
01581 t->have_ratings = 0;
01582 t->exclusivity = INVALID_COMPANY;
01583 t->exclusive_counter = 0;
01584 t->statues = 0;
01585
01586 extern int _nb_orig_names;
01587 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01588
01589 t->townnamegrfid = 0;
01590 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01591 } else {
01592
01593 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01594 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01595 }
01596 t->townnameparts = townnameparts;
01597
01598 t->UpdateVirtCoord();
01599 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01600
01601 t->InitializeLayout(layout);
01602
01603 t->larger_town = city;
01604
01605 int x = (int)size * 16 + 3;
01606 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01607
01608 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01609
01610 t->num_houses += x;
01611 UpdateTownRadius(t);
01612
01613 int i = x * 4;
01614 do {
01615 GrowTown(t);
01616 } while (--i);
01617
01618 t->num_houses -= x;
01619 UpdateTownRadius(t);
01620 UpdateTownGenCargo(t);
01621 UpdateTownDemands(t);
01622 UpdateAirportsNoise();
01623 }
01624
01630 static CommandCost TownCanBePlacedHere(TileIndex tile)
01631 {
01632
01633 if (DistanceFromEdge(tile) < 12) {
01634 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01635 }
01636
01637
01638 if (IsCloseToTown(tile, 20)) {
01639 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01640 }
01641
01642
01643 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
01644 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01645 }
01646
01647 return CommandCost(EXPENSES_OTHER);
01648 }
01649
01655 static bool IsUniqueTownName(const char *name)
01656 {
01657 const Town *t;
01658
01659 FOR_ALL_TOWNS(t) {
01660 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01661 }
01662
01663 return true;
01664 }
01665
01678 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01679 {
01680 TownSize size = Extract<TownSize, 0, 2>(p1);
01681 bool city = HasBit(p1, 2);
01682 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01683 TownNameParams par(_settings_game.game_creation.town_name);
01684 bool random = HasBit(p1, 6);
01685 uint32 townnameparts = p2;
01686
01687 if (size >= TSZ_END) return CMD_ERROR;
01688 if (layout >= NUM_TLS) return CMD_ERROR;
01689
01690
01691 if (_game_mode != GM_EDITOR) {
01692 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01693 if (size == TSZ_LARGE) return CMD_ERROR;
01694 if (random) return CMD_ERROR;
01695 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01696 return CMD_ERROR;
01697 }
01698 }
01699
01700 if (StrEmpty(text)) {
01701
01702 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01703 } else {
01704
01705 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01706 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01707 }
01708
01709
01710 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01711
01712 if (!random) {
01713 CommandCost ret = TownCanBePlacedHere(tile);
01714 if (ret.Failed()) return ret;
01715 }
01716
01717 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01718
01719 assert_compile(lengthof(price_mult[0]) == 4);
01720
01721 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01722 byte mult = price_mult[city][size];
01723
01724 cost.MultiplyCost(mult);
01725
01726
01727 if (flags & DC_EXEC) {
01728 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01729 _additional_cash_required = cost.GetCost();
01730 return CommandCost(EXPENSES_OTHER);
01731 }
01732
01733 _generating_world = true;
01734 UpdateNearestTownForRoadTiles(true);
01735 Town *t;
01736 if (random) {
01737 t = CreateRandomTown(20, townnameparts, size, city, layout);
01738 if (t == NULL) {
01739 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01740 } else {
01741 _new_town_id = t->index;
01742 }
01743 } else {
01744 t = new Town(tile);
01745 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01746 }
01747 UpdateNearestTownForRoadTiles(false);
01748 _generating_world = false;
01749
01750 if (t != NULL && !StrEmpty(text)) {
01751 t->name = strdup(text);
01752 t->UpdateVirtCoord();
01753 }
01754
01755 if (_game_mode != GM_EDITOR) {
01756
01757 assert(!random);
01758 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01759 SetDParam(0, _current_company);
01760 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01761
01762 char *cn = strdup(company_name);
01763 SetDParamStr(0, cn);
01764 SetDParam(1, t->index);
01765
01766 AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01767 AI::BroadcastNewEvent(new AIEventTownFounded(t->index));
01768 }
01769 }
01770 return cost;
01771 }
01772
01782 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01783 {
01784 switch (layout) {
01785 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01786 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01787 default: return tile;
01788 }
01789 }
01790
01800 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01801 {
01802 switch (layout) {
01803 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01804 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01805 default: return true;
01806 }
01807 }
01808
01812 struct SpotData {
01813 TileIndex tile;
01814 uint max_dist;
01815 TownLayout layout;
01816 };
01817
01834 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01835 {
01836 SpotData *sp = (SpotData*)user_data;
01837 uint dist = GetClosestWaterDistance(tile, true);
01838
01839 if (IsTileType(tile, MP_CLEAR) &&
01840 GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01841 IsTileAlignedToGrid(tile, sp->layout) &&
01842 dist > sp->max_dist) {
01843 sp->tile = tile;
01844 sp->max_dist = dist;
01845 }
01846
01847 return false;
01848 }
01849
01856 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01857 {
01858 return IsTileType(tile, MP_CLEAR);
01859 }
01860
01873 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01874 {
01875 SpotData sp = { INVALID_TILE, 0, layout };
01876
01877 TileIndex coast = tile;
01878 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01879 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01880 return sp.tile;
01881 }
01882
01883
01884 return INVALID_TILE;
01885 }
01886
01887 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01888 {
01889 if (!Town::CanAllocateItem()) return NULL;
01890
01891 do {
01892
01893 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01894
01895
01896
01897 if (IsTileType(tile, MP_WATER)) {
01898 tile = FindNearestGoodCoastalTownSpot(tile, layout);
01899 if (tile == INVALID_TILE) continue;
01900 }
01901
01902
01903 if (TownCanBePlacedHere(tile).Failed()) continue;
01904
01905
01906 Town *t = new Town(tile);
01907
01908 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01909
01910
01911
01912 if (t->population > 0) return t;
01913 DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01914
01915
01916
01917
01918
01919 assert(Town::CanAllocateItem());
01920 } while (--attempts != 0);
01921
01922 return NULL;
01923 }
01924
01925 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01926
01934 bool GenerateTowns(TownLayout layout)
01935 {
01936 uint current_number = 0;
01937 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01938 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01939 uint32 townnameparts;
01940
01941 SetGeneratingWorldProgress(GWP_TOWN, total);
01942
01943
01944
01945
01946 do {
01947 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01948 IncreaseGeneratingWorldProgress(GWP_TOWN);
01949
01950 if (!GenerateTownName(&townnameparts)) continue;
01951
01952 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++;
01953 } while (--total);
01954
01955 if (current_number != 0) return true;
01956
01957
01958
01959 if (GenerateTownName(&townnameparts) &&
01960 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01961 return true;
01962 }
01963
01964
01965 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01966 extern StringID _switch_mode_errorstr;
01967 _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01968 }
01969
01970 return false;
01971 }
01972
01973
01980 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01981 {
01982 uint dist = DistanceSquare(tile, t->xy);
01983
01984 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01985
01986 HouseZonesBits smallest = HZB_TOWN_EDGE;
01987 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01988 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01989 }
01990
01991 return smallest;
01992 }
01993
02004 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
02005 {
02006 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
02007
02008 assert(cc.Succeeded());
02009
02010 IncreaseBuildingCount(t, type);
02011 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
02012 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
02013
02014 MarkTileDirtyByTile(tile);
02015 }
02016
02017
02028 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
02029 {
02030 BuildingFlags size = HouseSpec::Get(type)->building_flags;
02031
02032 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
02033 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
02034 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
02035 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
02036 }
02037
02038
02047 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
02048 {
02049
02050 Slope slope = GetTileSlope(tile, NULL);
02051 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
02052
02053
02054 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02055
02056
02057 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
02058
02059
02060 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
02061 }
02062
02063
02073 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
02074 {
02075 if (!CanBuildHouseHere(tile, town, noslope)) return false;
02076
02077
02078 if (GetTileMaxZ(tile) != z) return false;
02079
02080 return true;
02081 }
02082
02083
02093 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
02094 {
02095
02096 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02097
02098 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02099 tile += TileOffsByDiagDir(d);
02100 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02101 }
02102
02103 return true;
02104 }
02105
02106
02114 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02115 {
02116
02117 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02118
02119 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02120
02121 switch (t->layout) {
02122 case TL_2X2_GRID:
02123 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02124 break;
02125
02126 case TL_3X3_GRID:
02127 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02128 break;
02129
02130 default:
02131 break;
02132 }
02133
02134 return true;
02135 }
02136
02137
02145 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02146 {
02147
02148 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02149
02150
02151 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02152
02153 switch (t->layout) {
02154 case TL_2X2_GRID:
02155 grid_pos.x %= 3;
02156 grid_pos.y %= 3;
02157 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02158 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02159 break;
02160
02161 case TL_3X3_GRID:
02162 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02163 break;
02164
02165 default:
02166 break;
02167 }
02168
02169 return true;
02170 }
02171
02172
02182 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02183 {
02184
02185
02186 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02187 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02188
02189 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02190 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02191 *tile = tile2;
02192 return true;
02193 }
02194
02195 return false;
02196 }
02197
02198
02207 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02208 {
02209 TileIndex tile2 = *tile;
02210
02211 for (DiagDirection d = DIAGDIR_SE;; d++) {
02212 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02213 *tile = tile2;
02214 return true;
02215 }
02216 if (d == DIAGDIR_END) break;
02217 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
02218 }
02219
02220 return false;
02221 }
02222
02223
02230 static bool BuildTownHouse(Town *t, TileIndex tile)
02231 {
02232
02233 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02234
02235
02236 if (!CanBuildHouseHere(tile, t->index, false)) return false;
02237
02238 uint z;
02239 Slope slope = GetTileSlope(tile, &z);
02240
02241
02242
02243 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02244
02245
02246 int land = _settings_game.game_creation.landscape;
02247 if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02248
02249 uint bitmask = (1 << rad) + (1 << (land + 12));
02250
02251
02252
02253
02254 HouseID houses[HOUSE_MAX];
02255 uint num = 0;
02256 uint probs[HOUSE_MAX];
02257 uint probability_max = 0;
02258
02259
02260 for (uint i = 0; i < HOUSE_MAX; i++) {
02261 const HouseSpec *hs = HouseSpec::Get(i);
02262
02263
02264 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02265
02266
02267 if (hs->class_id != HOUSE_NO_CLASS) {
02268
02269 if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02270 } else {
02271
02272 if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02273 }
02274
02275
02276 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02277 probability_max += cur_prob;
02278 probs[num] = cur_prob;
02279 houses[num++] = (HouseID)i;
02280 }
02281
02282 uint maxz = GetTileMaxZ(tile);
02283
02284 while (probability_max > 0) {
02285 uint r = RandomRange(probability_max);
02286 uint i;
02287 for (i = 0; i < num; i++) {
02288 if (probs[i] > r) break;
02289 r -= probs[i];
02290 }
02291
02292 HouseID house = houses[i];
02293 probability_max -= probs[i];
02294
02295
02296 num--;
02297 houses[i] = houses[num];
02298 probs[i] = probs[num];
02299
02300 const HouseSpec *hs = HouseSpec::Get(house);
02301
02302 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02303 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02304 continue;
02305 }
02306
02307 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02308
02309
02310 uint oneof = 0;
02311
02312 if (hs->building_flags & BUILDING_IS_CHURCH) {
02313 SetBit(oneof, TOWN_HAS_CHURCH);
02314 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02315 SetBit(oneof, TOWN_HAS_STADIUM);
02316 }
02317
02318 if (t->flags & oneof) continue;
02319
02320
02321 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02322 if (noslope && slope != SLOPE_FLAT) continue;
02323
02324 if (hs->building_flags & TILE_SIZE_2x2) {
02325 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02326 } else if (hs->building_flags & TILE_SIZE_2x1) {
02327 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02328 } else if (hs->building_flags & TILE_SIZE_1x2) {
02329 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02330 } else {
02331
02332 }
02333
02334 byte random_bits = Random();
02335
02336 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02337 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02338 if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02339 }
02340
02341
02342 t->num_houses++;
02343
02344
02345 t->flags |= oneof;
02346
02347 byte construction_counter = 0;
02348 byte construction_stage = 0;
02349
02350 if (_generating_world || _game_mode == GM_EDITOR) {
02351 uint32 r = Random();
02352
02353 construction_stage = TOWN_HOUSE_COMPLETED;
02354 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02355
02356 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02357 ChangePopulation(t, hs->population);
02358 } else {
02359 construction_counter = GB(r, 2, 2);
02360 }
02361 }
02362
02363 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02364
02365 return true;
02366 }
02367
02368 return false;
02369 }
02370
02377 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02378 {
02379 assert(IsTileType(tile, MP_HOUSE));
02380
02381 DecreaseBuildingCount(t, house);
02382 DoClearSquare(tile);
02383 DeleteAnimatedTile(tile);
02384
02385 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02386 }
02387
02395 TileIndexDiff GetHouseNorthPart(HouseID &house)
02396 {
02397 if (house >= 3) {
02398 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02399 house--;
02400 return TileDiffXY(-1, 0);
02401 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02402 house--;
02403 return TileDiffXY(0, -1);
02404 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02405 house -= 2;
02406 return TileDiffXY(-1, 0);
02407 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02408 house -= 3;
02409 return TileDiffXY(-1, -1);
02410 }
02411 }
02412 return 0;
02413 }
02414
02415 void ClearTownHouse(Town *t, TileIndex tile)
02416 {
02417 assert(IsTileType(tile, MP_HOUSE));
02418
02419 HouseID house = GetHouseType(tile);
02420
02421
02422 tile += GetHouseNorthPart(house);
02423
02424 const HouseSpec *hs = HouseSpec::Get(house);
02425
02426
02427 if (IsHouseCompleted(tile)) {
02428 ChangePopulation(t, -hs->population);
02429 }
02430
02431 t->num_houses--;
02432
02433
02434 if (hs->building_flags & BUILDING_IS_CHURCH) {
02435 ClrBit(t->flags, TOWN_HAS_CHURCH);
02436 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02437 ClrBit(t->flags, TOWN_HAS_STADIUM);
02438 }
02439
02440
02441 uint eflags = hs->building_flags;
02442 DoClearTownHouseHelper(tile, t, house);
02443 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02444 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02445 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02446 }
02447
02457 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02458 {
02459 Town *t = Town::GetIfValid(p1);
02460 if (t == NULL) return CMD_ERROR;
02461
02462 bool reset = StrEmpty(text);
02463
02464 if (!reset) {
02465 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02466 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02467 }
02468
02469 if (flags & DC_EXEC) {
02470 free(t->name);
02471 t->name = reset ? NULL : strdup(text);
02472
02473 t->UpdateVirtCoord();
02474 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02475 UpdateAllStationVirtCoords();
02476 }
02477 return CommandCost();
02478 }
02479
02489 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02490 {
02491 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02492 Town *t = Town::GetIfValid(p1);
02493 if (t == NULL) return CMD_ERROR;
02494
02495 if (flags & DC_EXEC) {
02496
02497 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02498 t->num_houses += amount;
02499 UpdateTownRadius(t);
02500
02501 uint n = amount * 10;
02502 do GrowTown(t); while (--n);
02503
02504 t->num_houses -= amount;
02505 UpdateTownRadius(t);
02506
02507 UpdateTownGenCargo(t);
02508 UpdateTownDemands(t);
02509 }
02510
02511 return CommandCost();
02512 }
02513
02523 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02524 {
02525 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02526 Town *t = Town::GetIfValid(p1);
02527 if (t == NULL) return CMD_ERROR;
02528
02529
02530 const Station *st;
02531 FOR_ALL_STATIONS(st) {
02532 if (st->town == t) {
02533
02534 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02535
02536 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02537 if (ret.Failed()) return ret;
02538 }
02539 }
02540
02541
02542 const Depot *d;
02543 FOR_ALL_DEPOTS(d) {
02544 if (d->town == t) return CMD_ERROR;
02545 }
02546
02547
02548 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02549 bool try_clear = false;
02550 switch (GetTileType(tile)) {
02551 case MP_ROAD:
02552 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02553 break;
02554
02555 case MP_TUNNELBRIDGE:
02556 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02557 break;
02558
02559 case MP_HOUSE:
02560 try_clear = GetTownIndex(tile) == t->index;
02561 break;
02562
02563 case MP_INDUSTRY:
02564 try_clear = Industry::GetByTile(tile)->town == t;
02565 break;
02566
02567 case MP_OBJECT:
02568 if (Town::GetNumItems() == 1) {
02569
02570 try_clear = true;
02571 } else {
02572 Object *o = Object::GetByTile(tile);
02573 if (o->town == t) {
02574 if (GetObjectType(tile) == OBJECT_STATUE) {
02575
02576 try_clear = true;
02577 } else {
02578
02579 if (flags & DC_EXEC) o->town = NULL;
02580 }
02581 }
02582 }
02583 break;
02584
02585 default:
02586 break;
02587 }
02588 if (try_clear) {
02589 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02590 if (ret.Failed()) return ret;
02591 }
02592 }
02593
02594
02595 if (flags & DC_EXEC) delete t;
02596
02597 return CommandCost();
02598 }
02599
02604 const byte _town_action_costs[TACT_COUNT] = {
02605 2, 4, 9, 35, 48, 53, 117, 175
02606 };
02607
02608 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02609 {
02610 if (flags & DC_EXEC) {
02611 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02612 }
02613 return CommandCost();
02614 }
02615
02616 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02617 {
02618 if (flags & DC_EXEC) {
02619 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02620 }
02621 return CommandCost();
02622 }
02623
02624 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02625 {
02626 if (flags & DC_EXEC) {
02627 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02628 }
02629 return CommandCost();
02630 }
02631
02632 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02633 {
02634
02635 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02636
02637 if (flags & DC_EXEC) {
02638 t->road_build_months = 6;
02639
02640 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02641 SetDParam(0, _current_company);
02642 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02643
02644 char *cn = strdup(company_name);
02645 SetDParam(0, t->index);
02646 SetDParamStr(1, cn);
02647
02648 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02649 }
02650 return CommandCost();
02651 }
02652
02659 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02660 {
02661
02662 if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02663
02664 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02665
02666 if (!IsTileType(tile, MP_HOUSE) &&
02667 !IsTileType(tile, MP_CLEAR) &&
02668 !IsTileType(tile, MP_TREES)) {
02669 return false;
02670 }
02671
02672 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02673 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02674 cur_company.Restore();
02675
02676 if (r.Failed()) return false;
02677
02678 return true;
02679 }
02680
02688 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02689 {
02690 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02691
02692 TileIndex tile = t->xy;
02693 if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02694 if (flags & DC_EXEC) {
02695 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02696 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02697 cur_company.Restore();
02698 BuildObject(OBJECT_STATUE, tile, _current_company, t);
02699 SetBit(t->statues, _current_company);
02700 MarkTileDirtyByTile(tile);
02701 }
02702 return CommandCost();
02703 }
02704 return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02705 }
02706
02707 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02708 {
02709 if (flags & DC_EXEC) {
02710
02711 t->grow_counter = 1;
02712
02713 SetBit(t->flags, TOWN_IS_FUNDED);
02714
02715 t->fund_buildings_months = 3;
02716 }
02717 return CommandCost();
02718 }
02719
02720 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02721 {
02722
02723 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02724
02725 if (flags & DC_EXEC) {
02726 t->exclusive_counter = 12 * _date_daylength_factor;
02727 t->exclusivity = _current_company;
02728
02729 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02730 }
02731 return CommandCost();
02732 }
02733
02734 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02735 {
02736 if (flags & DC_EXEC) {
02737 if (Chance16(1, 14)) {
02738
02739 t->unwanted[_current_company] = 6;
02740
02741
02742 Station *st;
02743 FOR_ALL_STATIONS(st) {
02744 if (st->town == t && st->owner == _current_company) {
02745 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02746 }
02747 }
02748
02749
02750
02751 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, WL_INFO);
02752
02753
02754
02755
02756
02757 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02758 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02759 t->UpdateVirtCoord();
02760 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02761 }
02762 } else {
02763 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02764 }
02765 }
02766 return CommandCost();
02767 }
02768
02769 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02770 static TownActionProc * const _town_action_proc[] = {
02771 TownActionAdvertiseSmall,
02772 TownActionAdvertiseMedium,
02773 TownActionAdvertiseLarge,
02774 TownActionRoadRebuild,
02775 TownActionBuildStatue,
02776 TownActionFundBuildings,
02777 TownActionBuyRights,
02778 TownActionBribe
02779 };
02780
02788 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02789 {
02790 int num = 0;
02791 TownActions buttons = TACT_NONE;
02792
02793
02794 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02795
02796
02797 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02798
02799
02800
02801 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02802 const TownActions cur = (TownActions)(1 << i);
02803
02804
02805 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02806
02807
02808 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02809
02810
02811 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02812
02813
02814 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02815
02816 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02817 buttons |= cur;
02818 num++;
02819 }
02820 }
02821 }
02822
02823 if (nump != NULL) *nump = num;
02824 return buttons;
02825 }
02826
02838 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02839 {
02840 Town *t = Town::GetIfValid(p1);
02841 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02842
02843 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02844
02845 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02846
02847 CommandCost ret = _town_action_proc[p2](t, flags);
02848 if (ret.Failed()) return ret;
02849
02850 if (flags & DC_EXEC) {
02851 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02852 }
02853
02854 return cost;
02855 }
02856
02857 static void UpdateTownGrowRate(Town *t)
02858 {
02859
02860 const Company *c;
02861 FOR_ALL_COMPANIES(c) {
02862 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02863 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02864 }
02865 }
02866
02867 int n = 0;
02868
02869
02870 const Station *st;
02871 FOR_ALL_STATIONS(st) {
02872 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02873 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02874 n++;
02875 if (Company::IsValidID(st->owner)) {
02876 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02877 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02878 }
02879 } else {
02880 if (Company::IsValidID(st->owner)) {
02881 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02882 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02883 }
02884 }
02885 }
02886 }
02887
02888
02889 for (uint i = 0; i < MAX_COMPANIES; i++) {
02890 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02891 }
02892
02893 t->UpdateVirtCoord();
02894 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02895
02896 ClrBit(t->flags, TOWN_IS_FUNDED);
02897 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02898
02903 static const uint16 _grow_count_values[2][6] = {
02904 { 120, 120, 120, 100, 80, 60 },
02905 { 320, 420, 300, 220, 160, 100 }
02906 };
02907
02908 uint16 m;
02909
02910 if (t->fund_buildings_months != 0) {
02911 m = _grow_count_values[0][min(n, 5)];
02912 t->fund_buildings_months--;
02913 } else {
02914 m = _grow_count_values[1][min(n, 5)];
02915 if (n == 0 && !Chance16(1, 12)) return;
02916 }
02917
02918 uint32 ratio = 1;
02919
02920 if ((!t->larger_town && _settings_game.economy.town_growth_cargo) ||
02921 (t->larger_town && _settings_game.economy.larger_town_growth_cargo)) {
02922 ratio = 0;
02923 uint32 current_ratio = 0;
02924 byte previous_ratio = 100;
02925
02926
02927
02928
02929
02930 if ((!t->larger_town && t->population > _settings_game.economy.town_pop_need_goods) ||
02931 (t->larger_town && t->population > _settings_game.economy.larger_town_pop_need_goods)) {
02932
02933
02934 static const uint32 _populations[] = {
02935 5500, 9000, 12500, 17000, 21500, 27000, 31500, 37000, 42500, 48000, 54500, 61000, 67500, 77500, 88500, 99500, 105500,
02936 };
02937
02938 byte required_stations = 5;
02939
02940 for (const uint32 *p = _populations; p < endof(_populations); p++) {
02941 if (t->population < *p) break;
02942 required_stations++;
02943 }
02944
02945
02946 if (t->population >= 5500) {
02947 if (!t->larger_town) {
02948 required_stations += _settings_game.economy.town_growth_cargo;
02949 } else {
02950 required_stations += _settings_game.economy.larger_town_growth_cargo;
02951 }
02952 }
02953
02954
02955 current_ratio = n / required_stations * 100;
02956 if (current_ratio > 100) current_ratio = 100;
02957 if (current_ratio < 100 && current_ratio < previous_ratio) {
02958 previous_ratio = current_ratio;
02959 t->needed_for_growth = GROWTH_NEED_STATION;
02960 }
02961 ratio += current_ratio;
02962
02963
02964 current_ratio = t->act_pass / t->max_pass * 100;
02965 if (current_ratio > 100) current_ratio = 100;
02966 if (current_ratio < 100 && current_ratio < previous_ratio) {
02967 previous_ratio = current_ratio;
02968 t->needed_for_growth = GROWTH_NEED_MORE_PASS;
02969 }
02970 ratio += current_ratio;
02971
02972
02973 current_ratio = t->act_mail / t->max_mail * 100;
02974 if (current_ratio > 100) current_ratio = 100;
02975 if (current_ratio < 100 && current_ratio < previous_ratio) {
02976 previous_ratio = current_ratio;
02977 t->needed_for_growth = GROWTH_NEED_MORE_MAIL;
02978 }
02979 ratio += current_ratio;
02980
02981
02982
02983 if ((_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine()) ||
02984 (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) ||
02985 (_settings_game.game_creation.landscape == LT_TOYLAND)) {
02986 current_ratio = t->act_food / t->max_food * 100;
02987 if (ratio > 100) current_ratio = 100;
02988 if (ratio < 100 && current_ratio < previous_ratio) {
02989 previous_ratio = current_ratio;
02990 t->needed_for_growth = GROWTH_NEED_MORE_FOOD;
02991 }
02992 ratio += current_ratio;
02993 }
02994
02995
02996 if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) {
02997 current_ratio = t->act_water / t->max_water * 100;
02998 if (current_ratio > 100) current_ratio = 100;
02999 if (current_ratio < 100 && current_ratio < previous_ratio) {
03000 previous_ratio = current_ratio;
03001 t->needed_for_growth = GROWTH_NEED_MORE_WATER;
03002 }
03003 ratio += current_ratio;
03004 }
03005
03006
03007
03008 current_ratio = t->act_goods / t->max_goods * 100;
03009 if (current_ratio > 100) current_ratio = 100;
03010 if (current_ratio < 100 && current_ratio < previous_ratio) {
03011 previous_ratio = current_ratio;
03012 t->needed_for_growth = GROWTH_NEED_MORE_GOODS;
03013 }
03014 ratio += current_ratio;
03015
03016
03017
03018 byte number_of_required = 4;
03019 if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) number_of_required += 2;
03020 if (_settings_game.game_creation.landscape == LT_TOYLAND || (_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine())) number_of_required += 1;
03021 ratio /= number_of_required;
03022
03023
03024 t->transported_goods_percent = ratio;
03025 ratio /= 100;
03026
03027
03028 if (t->act_pass == 0) {
03029 t->needed_for_growth = GROWTH_NEED_PASS ;
03030 return;
03031 }
03032
03033 if (t->act_mail == 0) {
03034 t->needed_for_growth = GROWTH_NEED_MAIL ;
03035 return;
03036 }
03037
03038 if (((_settings_game.game_creation.landscape == LT_ARCTIC && TilePixelHeight(t->xy) >= GetSnowLine()) ||
03039 (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(t->xy) == TROPICZONE_DESERT) ||
03040 (_settings_game.game_creation.landscape == LT_TOYLAND)) &&
03041 t->act_food == 0) {
03042 t->needed_for_growth = GROWTH_NEED_FOOD;
03043 return;
03044 }
03045
03046 if (_settings_game.game_creation.landscape == LT_TROPIC &&
03047 GetTropicZone(t->xy) == TROPICZONE_DESERT &&
03048 t->act_water == 0) {
03049 t->needed_for_growth = GROWTH_NEED_WATER;
03050 return;
03051 }
03052
03053 if (t->act_goods == 0) {
03054 t->needed_for_growth = GROWTH_NEED_GOODS ;
03055 return;
03056 }
03057 }
03058 }
03059
03060
03061 if ((!t->larger_town && !_settings_game.economy.town_growth_cargo) ||
03062 (t->larger_town && !_settings_game.economy.larger_town_growth_cargo)) {
03063 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
03064 if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90) {
03065 t->needed_for_growth = GROWTH_NEED_FOOD;
03066 return;
03067 }
03068 } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
03069 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->act_food == 0 && t->population > 60) {
03070 t->needed_for_growth = GROWTH_NEED_FOOD;
03071 return;
03072 }
03073 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->act_water == 0 && t->population > 60) {
03074 t->needed_for_growth = GROWTH_NEED_WATER;
03075 return;
03076 }
03077 }
03078 }
03079
03080
03081
03082
03083
03084 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
03085
03086 m >>= growth_multiplier;
03087 if (t->larger_town) m /= 2;
03088
03089
03090 if ((!t->larger_town && !_settings_game.economy.town_growth_cargo) ||
03091 (t->larger_town && !_settings_game.economy.larger_town_growth_cargo) ||
03092 (!t->larger_town && t->population < _settings_game.economy.town_pop_need_goods) ||
03093 (t->larger_town && t->population < _settings_game.economy.larger_town_pop_need_goods)) {
03094 t->growth_rate = m / (t->num_houses / 50 + 1);
03095 } else {
03096 t->growth_rate = m / (t->num_houses / 50 + 1) * ratio;
03097 }
03098
03099 if (m <= t->grow_counter) {
03100 t->grow_counter = m;
03101 }
03102
03103 SetBit(t->flags, TOWN_IS_FUNDED);
03104 }
03105
03106 static void UpdateTownAmounts(Town *t)
03107 {
03108
03109 t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
03110 t->gen_max_pass = t->new_gen_max_pass; t->new_gen_max_pass = 0;
03111 t->gen_act_pass = t->new_gen_act_pass; t->new_gen_act_pass = 0;
03112 t->max_pass = t->new_max_pass; t->new_max_pass = 0;
03113 t->act_pass = t->new_act_pass; t->new_act_pass = 0;
03114
03115 t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
03116 t->gen_max_mail = t->new_gen_max_mail; t->new_gen_max_mail = 0;
03117 t->gen_act_mail = t->new_gen_act_mail; t->new_gen_act_mail = 0;
03118 t->max_mail = t->new_max_mail; t->new_max_mail = 0;
03119 t->act_mail = t->new_act_mail; t->new_act_mail = 0;
03120
03121 t->pct_food_transported = t->new_act_food * 256 / (t->new_max_food + 1);
03122 t->max_food = t->new_max_food; t->new_max_food = 0;
03123 t->act_food = t->new_act_food; t->new_act_food = 0;
03124
03125 t->pct_water_transported = t->new_act_water * 256 / (t->new_max_water + 1);
03126 t->max_water = t->new_max_water; t->new_max_water = 0;
03127 t->act_water = t->new_act_water; t->new_act_water = 0;
03128
03129 t->pct_goods_transported = t->new_act_goods * 256 / (t->new_max_goods + 1);
03130 t->max_goods = t->new_max_goods; t->new_max_goods = 0;
03131 t->act_goods = t->new_act_goods; t->new_act_goods = 0;
03132
03133 SetWindowDirty(WC_TOWN_VIEW, t->index);
03134 }
03135
03136 static void UpdateTownUnwanted(Town *t)
03137 {
03138 const Company *c;
03139
03140 FOR_ALL_COMPANIES(c) {
03141 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
03142 }
03143 }
03144
03151 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
03152 {
03153 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
03154
03155 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
03156 if (t == NULL) return CommandCost();
03157
03158 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
03159
03160 SetDParam(0, t->index);
03161 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03162 }
03163
03172 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
03173 {
03174 Town *t;
03175 uint best = threshold;
03176 Town *best_town = NULL;
03177
03178 FOR_ALL_TOWNS(t) {
03179 uint dist = DistanceManhattan(tile, t->xy);
03180 if (dist < best) {
03181 best = dist;
03182 best_town = t;
03183 }
03184 }
03185
03186 return best_town;
03187 }
03188
03197 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
03198 {
03199 switch (GetTileType(tile)) {
03200 case MP_ROAD:
03201 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
03202
03203 if (!HasTownOwnedRoad(tile)) {
03204 TownID tid = GetTownIndex(tile);
03205
03206 if (tid == (TownID)INVALID_TOWN) {
03207
03208 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03209 assert(Town::GetNumItems() == 0);
03210 return NULL;
03211 }
03212
03213 assert(Town::IsValidID(tid));
03214 Town *town = Town::Get(tid);
03215
03216 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03217
03218 return town;
03219 }
03220
03221
03222 case MP_HOUSE:
03223 return Town::GetByTile(tile);
03224
03225 default:
03226 return CalcClosestTownFromTile(tile, threshold);
03227 }
03228 }
03229
03230 static bool _town_rating_test = false;
03231 static SmallMap<const Town *, int, 4> _town_test_ratings;
03232
03238 void SetTownRatingTestMode(bool mode)
03239 {
03240 static int ref_count = 0;
03241 if (mode) {
03242 if (ref_count == 0) {
03243 _town_test_ratings.Clear();
03244 }
03245 ref_count++;
03246 } else {
03247 assert(ref_count > 0);
03248 ref_count--;
03249 }
03250 _town_rating_test = !(ref_count == 0);
03251 }
03252
03258 static int GetRating(const Town *t)
03259 {
03260 if (_town_rating_test) {
03261 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03262 if (it != _town_test_ratings.End()) {
03263 return it->second;
03264 }
03265 }
03266 return t->ratings[_current_company];
03267 }
03268
03276 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03277 {
03278
03279 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03280 !Company::IsValidID(_current_company) ||
03281 (_cheats.magic_bulldozer.value && add < 0)) {
03282 return;
03283 }
03284
03285 int rating = GetRating(t);
03286 if (add < 0) {
03287 if (rating > max) {
03288 rating += add;
03289 if (rating < max) rating = max;
03290 }
03291 } else {
03292 if (rating < max) {
03293 rating += add;
03294 if (rating > max) rating = max;
03295 }
03296 }
03297 if (_town_rating_test) {
03298 _town_test_ratings[t] = rating;
03299 } else {
03300 SetBit(t->have_ratings, _current_company);
03301 t->ratings[_current_company] = rating;
03302 t->UpdateVirtCoord();
03303 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03304 }
03305 }
03306
03314 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03315 {
03316
03317 if (t == NULL || !Company::IsValidID(_current_company) ||
03318 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03319 return CommandCost();
03320 }
03321
03322
03323 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03324
03325 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE},
03326 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL},
03327 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE},
03328 };
03329
03330
03331
03332
03333
03334 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03335
03336 if (GetRating(t) < needed) {
03337 SetDParam(0, t->index);
03338 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03339 }
03340
03341 return CommandCost();
03342 }
03343
03344 void TownsMonthlyLoop()
03345 {
03346 Town *t;
03347
03348 FOR_ALL_TOWNS(t) {
03349 if (t->road_build_months != 0) t->road_build_months--;
03350
03351 if (t->exclusive_counter != 0) {
03352 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03353 }
03354
03355 UpdateTownGrowRate(t);
03356 UpdateTownAmounts(t);
03357 UpdateTownUnwanted(t);
03358 }
03359 }
03360
03361 void TownsYearlyLoop()
03362 {
03363
03364 for (TileIndex t = 0; t < MapSize(); t++) {
03365 if (!IsTileType(t, MP_HOUSE)) continue;
03366 IncrementHouseAge(t);
03367 }
03368 }
03369
03370 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03371 {
03372 if (AutoslopeEnabled()) {
03373 HouseID house = GetHouseType(tile);
03374 GetHouseNorthPart(house);
03375 const HouseSpec *hs = HouseSpec::Get(house);
03376
03377
03378 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03379 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03380 bool allow_terraform = true;
03381
03382
03383 house = GetHouseType(tile);
03384 hs = HouseSpec::Get(house);
03385 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03386
03387 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03388 if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
03389 }
03390
03391 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03392 }
03393 }
03394
03395 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03396 }
03397
03399 extern const TileTypeProcs _tile_type_town_procs = {
03400 DrawTile_Town,
03401 GetSlopeZ_Town,
03402 ClearTile_Town,
03403 AddAcceptedCargo_Town,
03404 GetTileDesc_Town,
03405 GetTileTrackStatus_Town,
03406 NULL,
03407 AnimateTile_Town,
03408 TileLoop_Town,
03409 ChangeTileOwner_Town,
03410 AddProducedCargo_Town,
03411 NULL,
03412 GetFoundation_Town,
03413 TerraformTile_Town,
03414 };
03415
03416
03417 HouseSpec _house_specs[HOUSE_MAX];
03418
03419 void ResetHouses()
03420 {
03421 memset(&_house_specs, 0, sizeof(_house_specs));
03422 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03423
03424
03425 _house_mngr.ResetOverride();
03426 }