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