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