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
00164 Money HouseSpec::GetRemovalCost() const
00165 {
00166 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00167 }
00168
00169
00170 static int _grow_town_result;
00171
00172
00173 enum TownGrowthResult {
00174 GROWTH_SUCCEED = -1,
00175 GROWTH_SEARCH_STOPPED = 0
00176
00177 };
00178
00179 static bool BuildTownHouse(Town *t, TileIndex tile);
00180 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00181
00182 static void TownDrawHouseLift(const TileInfo *ti)
00183 {
00184 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00185 }
00186
00187 typedef void TownDrawTileProc(const TileInfo *ti);
00188 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00189 TownDrawHouseLift
00190 };
00191
00197 static inline DiagDirection RandomDiagDir()
00198 {
00199 return (DiagDirection)(3 & Random());
00200 }
00201
00207 static void DrawTile_Town(TileInfo *ti)
00208 {
00209 HouseID house_id = GetHouseType(ti->tile);
00210
00211 if (house_id >= NEW_HOUSE_OFFSET) {
00212
00213
00214
00215 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00216 DrawNewHouseTile(ti, house_id);
00217 return;
00218 } else {
00219 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00220 }
00221 }
00222
00223
00224 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00225
00226 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00227
00228 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00229
00230
00231 if (IsInvisibilitySet(TO_HOUSES)) return;
00232
00233
00234 SpriteID image = dcts->building.sprite;
00235 if (image != 0) {
00236 AddSortableSpriteToDraw(image, dcts->building.pal,
00237 ti->x + dcts->subtile_x,
00238 ti->y + dcts->subtile_y,
00239 dcts->width,
00240 dcts->height,
00241 dcts->dz,
00242 ti->z,
00243 IsTransparencySet(TO_HOUSES)
00244 );
00245
00246 if (IsTransparencySet(TO_HOUSES)) return;
00247 }
00248
00249 {
00250 int proc = dcts->draw_proc - 1;
00251
00252 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00253 }
00254 }
00255
00256 static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
00257 {
00258 return GetTileMaxZ(tile);
00259 }
00260
00262 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00263 {
00264 HouseID hid = GetHouseType(tile);
00265
00266
00267
00268
00269
00270 if (hid >= NEW_HOUSE_OFFSET) {
00271 const HouseSpec *hs = HouseSpec::Get(hid);
00272 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00273 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00274 if (callback_res == 0) return FOUNDATION_NONE;
00275 }
00276 }
00277 return FlatteningFoundation(tileh);
00278 }
00279
00286 static void AnimateTile_Town(TileIndex tile)
00287 {
00288 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00289 AnimateNewHouseTile(tile);
00290 return;
00291 }
00292
00293 if (_tick_counter & 3) return;
00294
00295
00296
00297
00298
00299 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00300 DeleteAnimatedTile(tile);
00301 return;
00302 }
00303
00304 if (!LiftHasDestination(tile)) {
00305 uint i;
00306
00307
00308
00309
00310
00311 do {
00312 i = RandomRange(7);
00313 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00314
00315 SetLiftDestination(tile, i);
00316 }
00317
00318 int pos = GetLiftPosition(tile);
00319 int dest = GetLiftDestination(tile) * 6;
00320 pos += (pos < dest) ? 1 : -1;
00321 SetLiftPosition(tile, pos);
00322
00323 if (pos == dest) {
00324 HaltLift(tile);
00325 DeleteAnimatedTile(tile);
00326 }
00327
00328 MarkTileDirtyByTile(tile);
00329 }
00330
00337 static bool IsCloseToTown(TileIndex tile, uint dist)
00338 {
00339 const Town *t;
00340
00341 FOR_ALL_TOWNS(t) {
00342 if (DistanceManhattan(tile, t->xy) < dist) return true;
00343 }
00344 return false;
00345 }
00346
00351 void Town::UpdateVirtCoord()
00352 {
00353 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00354 SetDParam(0, this->index);
00355 SetDParam(1, this->population);
00356 this->sign.UpdatePosition(pt.x, pt.y - 24,
00357 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00358
00359 SetWindowDirty(WC_TOWN_VIEW, this->index);
00360 }
00361
00363 void UpdateAllTownVirtCoords()
00364 {
00365 Town *t;
00366
00367 FOR_ALL_TOWNS(t) {
00368 t->UpdateVirtCoord();
00369 }
00370 }
00371
00377 static void ChangePopulation(Town *t, int mod)
00378 {
00379 t->population += mod;
00380 SetWindowDirty(WC_TOWN_VIEW, t->index);
00381 t->UpdateVirtCoord();
00382
00383 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00384 }
00385
00391 uint32 GetWorldPopulation()
00392 {
00393 uint32 pop = 0;
00394 const Town *t;
00395
00396 FOR_ALL_TOWNS(t) pop += t->population;
00397 return pop;
00398 }
00399
00404 static void MakeSingleHouseBigger(TileIndex tile)
00405 {
00406 assert(IsTileType(tile, MP_HOUSE));
00407
00408
00409 IncHouseConstructionTick(tile);
00410 if (GetHouseConstructionTick(tile) != 0) return;
00411
00412 AnimateNewHouseConstruction(tile);
00413
00414 if (IsHouseCompleted(tile)) {
00415
00416
00417 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00418 ResetHouseAge(tile);
00419 }
00420 MarkTileDirtyByTile(tile);
00421 }
00422
00427 static void MakeTownHouseBigger(TileIndex tile)
00428 {
00429 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00430 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00431 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00432 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00433 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00434 }
00435
00442 static void TileLoop_Town(TileIndex tile)
00443 {
00444 HouseID house_id = GetHouseType(tile);
00445
00446
00447
00448 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00449
00450 if (!IsHouseCompleted(tile)) {
00451
00452 MakeTownHouseBigger(tile);
00453 return;
00454 }
00455
00456 const HouseSpec *hs = HouseSpec::Get(house_id);
00457
00458
00459 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00460 house_id < NEW_HOUSE_OFFSET &&
00461 !LiftHasDestination(tile) &&
00462 Chance16(1, 2)) {
00463 AddAnimatedTile(tile);
00464 }
00465
00466 Town *t = Town::GetByTile(tile);
00467 uint32 r = Random();
00468
00469 StationFinder stations(TileArea(tile, 1, 1));
00470
00471 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00472 for (uint i = 0; i < 256; i++) {
00473 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00474
00475 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00476
00477 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00478 if (cargo == CT_INVALID) continue;
00479
00480 uint amt = GB(callback, 0, 8);
00481 if (amt == 0) continue;
00482
00483 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00484
00485 const CargoSpec *cs = CargoSpec::Get(cargo);
00486 switch (cs->town_effect) {
00487 case TE_PASSENGERS:
00488 t->new_max_pass += amt;
00489 t->new_act_pass += moved;
00490 break;
00491
00492 case TE_MAIL:
00493 t->new_max_mail += amt;
00494 t->new_act_mail += moved;
00495 break;
00496
00497 default:
00498 break;
00499 }
00500 }
00501 } else {
00502 if (GB(r, 0, 8) < hs->population) {
00503 uint amt = GB(r, 0, 8) / 8 + 1;
00504
00505 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00506 t->new_max_pass += amt;
00507 t->new_act_pass += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00508 }
00509
00510 if (GB(r, 8, 8) < hs->mail_generation) {
00511 uint amt = GB(r, 8, 8) / 8 + 1;
00512
00513 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00514 t->new_max_mail += amt;
00515 t->new_act_mail += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00516 }
00517 }
00518
00519 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00520
00521 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00522 HasBit(t->flags, TOWN_IS_FUNDED) &&
00523 CanDeleteHouse(tile) &&
00524 GetHouseAge(tile) >= hs->minimum_life &&
00525 --t->time_until_rebuild == 0) {
00526 t->time_until_rebuild = GB(r, 16, 8) + 192;
00527
00528 ClearTownHouse(t, tile);
00529
00530
00531 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00532 }
00533
00534 cur_company.Restore();
00535 }
00536
00537 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00538 {
00539 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00540 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00541
00542 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00543
00544 CommandCost cost(EXPENSES_CONSTRUCTION);
00545 cost.AddCost(hs->GetRemovalCost());
00546
00547 int rating = hs->remove_rating_decrease;
00548 Town *t = Town::GetByTile(tile);
00549
00550 if (Company::IsValidID(_current_company)) {
00551 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00552 SetDParam(0, t->index);
00553 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00554 }
00555 }
00556
00557 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00558 if (flags & DC_EXEC) {
00559 ClearTownHouse(t, tile);
00560 }
00561
00562 return cost;
00563 }
00564
00565 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00566 {
00567 HouseID house_id = GetHouseType(tile);
00568 const HouseSpec *hs = HouseSpec::Get(house_id);
00569 Town *t = Town::GetByTile(tile);
00570
00571 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00572 for (uint i = 0; i < 256; i++) {
00573 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00574
00575 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00576
00577 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00578
00579 if (cargo == CT_INVALID) continue;
00580 produced[cargo]++;
00581 }
00582 } else {
00583 if (hs->population > 0) {
00584 produced[CT_PASSENGERS]++;
00585 }
00586 if (hs->mail_generation > 0) {
00587 produced[CT_MAIL]++;
00588 }
00589 }
00590 }
00591
00592 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00593 {
00594 if (cargo == CT_INVALID || amount == 0) return;
00595 acceptance[cargo] += amount;
00596 SetBit(*always_accepted, cargo);
00597 }
00598
00599 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00600 {
00601 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00602 CargoID accepts[3];
00603
00604
00605 for (uint8 i = 0; i < lengthof(accepts); i++) {
00606 accepts[i] = hs->accepts_cargo[i];
00607 }
00608
00609
00610 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00611 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00612 if (callback != CALLBACK_FAILED) {
00613
00614 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
00615 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
00616 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00617 }
00618 }
00619
00620
00621 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00622 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00623 if (callback != CALLBACK_FAILED) {
00624 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00625 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00626 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00627
00628 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00629 } else {
00630 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00631 }
00632 return;
00633 }
00634 }
00635
00636
00637 for (uint8 i = 0; i < lengthof(accepts); i++) {
00638 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00639 }
00640 }
00641
00642 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00643 {
00644 const HouseID house = GetHouseType(tile);
00645 const HouseSpec *hs = HouseSpec::Get(house);
00646 bool house_completed = IsHouseCompleted(tile);
00647
00648 td->str = hs->building_name;
00649
00650 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00651 if (callback_res != CALLBACK_FAILED) {
00652 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00653 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00654 td->str = new_name;
00655 }
00656 }
00657
00658 if (!house_completed) {
00659 SetDParamX(td->dparam, 0, td->str);
00660 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
00661 }
00662
00663 if (hs->grf_prop.grffile != NULL) {
00664 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
00665 td->grf = gc->GetName();
00666 }
00667
00668 td->owner[0] = OWNER_TOWN;
00669 }
00670
00671 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00672 {
00673
00674 return 0;
00675 }
00676
00677 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
00678 {
00679
00680 }
00681
00682 static bool GrowTown(Town *t);
00683
00684 static void TownTickHandler(Town *t)
00685 {
00686 if (HasBit(t->flags, TOWN_IS_FUNDED)) {
00687 int i = t->grow_counter - 1;
00688 if (i < 0) {
00689 if (GrowTown(t)) {
00690 i = t->growth_rate;
00691 } else {
00692 i = 0;
00693 }
00694 }
00695 t->grow_counter = i;
00696 }
00697
00698 UpdateTownRadius(t);
00699 }
00700
00701 void OnTick_Town()
00702 {
00703 if (_game_mode == GM_EDITOR) return;
00704
00705 Town *t;
00706 FOR_ALL_TOWNS(t) {
00707
00708 if ((_tick_counter + t->index) % TOWN_GROWTH_FREQUENCY == 0) {
00709 TownTickHandler(t);
00710 }
00711 }
00712 }
00713
00722 static RoadBits GetTownRoadBits(TileIndex tile)
00723 {
00724 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00725
00726 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00727 }
00728
00739 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00740 {
00741 if (!IsValidTile(tile)) return false;
00742
00743
00744 const TileIndexDiff tid_lt[3] = {
00745 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00746 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00747 TileOffsByDiagDir(ReverseDiagDir(dir)),
00748 };
00749
00750 dist_multi = (dist_multi + 1) * 4;
00751 for (uint pos = 4; pos < dist_multi; pos++) {
00752
00753 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00754
00755
00756 if (pos & 2) cur += tid_lt[2];
00757
00758
00759 if (IsValidTile(tile + cur) &&
00760 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00761 }
00762 return false;
00763 }
00764
00773 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00774 {
00775 if (DistanceFromEdge(tile) == 0) return false;
00776
00777 Slope cur_slope, desired_slope;
00778
00779 for (;;) {
00780
00781 if (GetTownRoadBits(tile) == ROAD_NONE) {
00782
00783
00784
00785 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00786 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed())
00787 return false;
00788 }
00789
00790 cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
00791 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00792 if (cur_slope == SLOPE_FLAT) return ret;
00793
00794
00795
00796 desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00797 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00798 if (Chance16(1, 8)) {
00799 CommandCost res = CMD_ERROR;
00800 if (!_generating_world && Chance16(1, 10)) {
00801
00802 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00803 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00804 }
00805 if (res.Failed() && Chance16(1, 3)) {
00806
00807 return ret;
00808 }
00809 }
00810 return false;
00811 }
00812 return ret;
00813 }
00814 }
00815
00816 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00817 {
00818 assert(tile < MapSize());
00819
00820 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00821 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00822 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00823 return true;
00824 }
00825
00826 static void LevelTownLand(TileIndex tile)
00827 {
00828 assert(tile < MapSize());
00829
00830
00831 if (IsTileType(tile, MP_HOUSE)) return;
00832 Slope tileh = GetTileSlope(tile, NULL);
00833 if (tileh == SLOPE_FLAT) return;
00834
00835
00836 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00837 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00838 }
00839 }
00840
00850 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00851 {
00852
00853 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00854 RoadBits rcmd = ROAD_NONE;
00855
00856 switch (t->layout) {
00857 default: NOT_REACHED();
00858
00859 case TL_2X2_GRID:
00860 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00861 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00862 break;
00863
00864 case TL_3X3_GRID:
00865 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00866 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00867 break;
00868 }
00869
00870
00871 if (rcmd != ROAD_ALL) return rcmd;
00872
00873 RoadBits rb_template;
00874
00875 switch (GetTileSlope(tile, NULL)) {
00876 default: rb_template = ROAD_ALL; break;
00877 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00878 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00879 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00880 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00881 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00882 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00883 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00884 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00885 case SLOPE_STEEP_W:
00886 case SLOPE_STEEP_S:
00887 case SLOPE_STEEP_E:
00888 case SLOPE_STEEP_N:
00889 rb_template = ROAD_NONE;
00890 break;
00891 }
00892
00893
00894 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00895
00896 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00897 }
00898
00909 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00910 {
00911
00912 if (DistanceFromEdge(tile) == 0) return false;
00913
00914 uint counter = 0;
00915
00916
00917 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00918
00919
00920
00921 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00922 case MP_HOUSE:
00923 case MP_VOID:
00924 counter++;
00925 break;
00926
00927 default:
00928 break;
00929 }
00930
00931
00932 if (counter >= 3) {
00933 if (BuildTownHouse(t, tile)) {
00934 _grow_town_result = GROWTH_SUCCEED;
00935 return true;
00936 }
00937 return false;
00938 }
00939 }
00940 return false;
00941 }
00942
00951 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
00952 {
00953 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
00954 _grow_town_result = GROWTH_SUCCEED;
00955 return true;
00956 }
00957 return false;
00958 }
00959
00970 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
00971 {
00972 assert(bridge_dir < DIAGDIR_END);
00973
00974 const Slope slope = GetTileSlope(tile, NULL);
00975 if (slope == SLOPE_FLAT) return false;
00976
00977
00978
00979
00980 if (slope & InclinedSlope(bridge_dir)) return false;
00981
00982
00983 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
00984
00985
00986 uint8 bridge_length = 0;
00987 TileIndex bridge_tile = tile;
00988
00989 const int delta = TileOffsByDiagDir(bridge_dir);
00990 do {
00991 if (bridge_length++ >= 11) {
00992
00993 return false;
00994 }
00995 bridge_tile += delta;
00996 } while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
00997
00998
00999 if (bridge_length == 1) return false;
01000
01001 for (uint8 times = 0; times <= 22; times++) {
01002 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01003
01004
01005 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01006 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01007 _grow_town_result = GROWTH_SUCCEED;
01008 return true;
01009 }
01010 }
01011
01012 return false;
01013 }
01014
01032 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01033 {
01034 RoadBits rcmd = ROAD_NONE;
01035 TileIndex tile = *tile_ptr;
01036
01037 assert(tile < MapSize());
01038
01039 if (cur_rb == ROAD_NONE) {
01040
01041
01042 _grow_town_result = GROWTH_SEARCH_STOPPED;
01043
01044 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01045 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01046
01047
01048 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01049
01050
01051 switch (t1->layout) {
01052 default: NOT_REACHED();
01053
01054 case TL_3X3_GRID:
01055 case TL_2X2_GRID:
01056 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01057 if (rcmd == ROAD_NONE) return;
01058 break;
01059
01060 case TL_BETTER_ROADS:
01061 case TL_ORIGINAL:
01062 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01063
01064 DiagDirection source_dir = ReverseDiagDir(target_dir);
01065
01066 if (Chance16(1, 4)) {
01067
01068 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01069 }
01070
01071 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01072
01073
01074 if (target_dir != ReverseDiagDir(source_dir)) return;
01075
01076
01077 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01078 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01079 return;
01080 }
01081
01082
01083
01084 }
01085
01086 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01087 break;
01088 }
01089
01090 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01091
01092
01093
01094 _grow_town_result = GROWTH_SEARCH_STOPPED;
01095
01096 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01097
01098 switch (t1->layout) {
01099 default: NOT_REACHED();
01100
01101 case TL_3X3_GRID:
01102 case TL_2X2_GRID:
01103 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01104 break;
01105
01106 case TL_BETTER_ROADS:
01107 case TL_ORIGINAL:
01108 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01109 break;
01110 }
01111 } else {
01112 bool allow_house = true;
01113
01114
01115 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01116 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
01117 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01118 }
01119 return;
01120 }
01121
01122
01123
01124 target_dir = RandomDiagDir();
01125 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01126
01127
01128 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01129
01130
01131 if (HasTileWaterGround(house_tile)) return;
01132
01133 if (!IsValidTile(house_tile)) return;
01134
01135 if (_settings_game.economy.allow_town_roads || _generating_world) {
01136 switch (t1->layout) {
01137 default: NOT_REACHED();
01138
01139 case TL_3X3_GRID:
01140 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01141
01142
01143 case TL_2X2_GRID:
01144 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01145 allow_house = (rcmd == ROAD_NONE);
01146 break;
01147
01148 case TL_BETTER_ROADS:
01149 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01150
01151
01152 case TL_ORIGINAL:
01153
01154
01155 rcmd = DiagDirToRoadBits(target_dir);
01156 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01157 break;
01158 }
01159 }
01160
01161 if (allow_house) {
01162
01163 if (!IsTileType(house_tile, MP_HOUSE)) {
01164
01165 if (Chance16(1, 6)) LevelTownLand(house_tile);
01166
01167
01168
01169 if (BuildTownHouse(t1, house_tile)) {
01170 _grow_town_result = GROWTH_SUCCEED;
01171 }
01172 }
01173 return;
01174 }
01175
01176 _grow_town_result = GROWTH_SEARCH_STOPPED;
01177 }
01178
01179
01180 if (HasTileWaterGround(tile)) return;
01181
01182
01183 rcmd = CleanUpRoadBits(tile, rcmd);
01184 if (rcmd == ROAD_NONE) return;
01185
01186
01187
01188
01189 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01190
01191 GrowTownWithRoad(t1, tile, rcmd);
01192 }
01193
01200 static int GrowTownAtRoad(Town *t, TileIndex tile)
01201 {
01202
01203
01204
01205 DiagDirection target_dir = DIAGDIR_END;
01206
01207 assert(tile < MapSize());
01208
01209
01210
01211
01212 switch (t->layout) {
01213 case TL_BETTER_ROADS:
01214 _grow_town_result = 10 + t->num_houses * 2 / 9;
01215 break;
01216
01217 case TL_3X3_GRID:
01218 case TL_2X2_GRID:
01219 _grow_town_result = 10 + t->num_houses * 1 / 9;
01220 break;
01221
01222 default:
01223 _grow_town_result = 10 + t->num_houses * 4 / 9;
01224 break;
01225 }
01226
01227 do {
01228 RoadBits cur_rb = GetTownRoadBits(tile);
01229
01230
01231 GrowTownInTile(&tile, cur_rb, target_dir, t);
01232
01233
01234
01235 cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01236 if (cur_rb == ROAD_NONE) {
01237 return _grow_town_result;
01238 }
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
01284 static bool GrowTown(Town *t)
01285 {
01286 static const TileIndexDiffC _town_coord_mod[] = {
01287 {-1, 0},
01288 { 1, 1},
01289 { 1, -1},
01290 {-1, -1},
01291 {-1, 0},
01292 { 0, 2},
01293 { 2, 0},
01294 { 0, -2},
01295 {-1, -1},
01296 {-2, 2},
01297 { 2, 2},
01298 { 2, -2},
01299 { 0, 0}
01300 };
01301
01302
01303 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
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 cur_company.Restore();
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 cur_company.Restore();
01328 return true;
01329 }
01330 }
01331 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01332 }
01333 }
01334
01335 cur_company.Restore();
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_END) return CMD_ERROR;
01534 if (layout >= NUM_TLS) 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 (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) 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_CHARS * MAX_CHAR_LENGTH];
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 AI::BroadcastNewEvent(new AIEventTownFounded(t->index));
01614 }
01615 }
01616 return cost;
01617 }
01618
01628 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01629 {
01630 switch (layout) {
01631 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01632 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01633 default: return tile;
01634 }
01635 }
01636
01646 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01647 {
01648 switch (layout) {
01649 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01650 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01651 default: return true;
01652 }
01653 }
01654
01658 struct SpotData {
01659 TileIndex tile;
01660 uint max_dist;
01661 TownLayout layout;
01662 };
01663
01680 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01681 {
01682 SpotData *sp = (SpotData*)user_data;
01683 uint dist = GetClosestWaterDistance(tile, true);
01684
01685 if (IsTileType(tile, MP_CLEAR) &&
01686 GetTileSlope(tile, NULL) == SLOPE_FLAT &&
01687 IsTileAlignedToGrid(tile, sp->layout) &&
01688 dist > sp->max_dist) {
01689 sp->tile = tile;
01690 sp->max_dist = dist;
01691 }
01692
01693 return false;
01694 }
01695
01702 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01703 {
01704 return IsTileType(tile, MP_CLEAR);
01705 }
01706
01719 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01720 {
01721 SpotData sp = { INVALID_TILE, 0, layout };
01722
01723 TileIndex coast = tile;
01724 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01725 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01726 return sp.tile;
01727 }
01728
01729
01730 return INVALID_TILE;
01731 }
01732
01733 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01734 {
01735 if (!Town::CanAllocateItem()) return NULL;
01736
01737 do {
01738
01739 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01740
01741
01742
01743 if (IsTileType(tile, MP_WATER)) {
01744 tile = FindNearestGoodCoastalTownSpot(tile, layout);
01745 if (tile == INVALID_TILE) continue;
01746 }
01747
01748
01749 if (TownCanBePlacedHere(tile).Failed()) continue;
01750
01751
01752 Town *t = new Town(tile);
01753
01754 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01755
01756
01757
01758 if (t->population > 0) return t;
01759 DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01760 } while (--attempts != 0);
01761
01762 return NULL;
01763 }
01764
01765 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01766
01774 bool GenerateTowns(TownLayout layout)
01775 {
01776 uint current_number = 0;
01777 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01778 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01779 uint32 townnameparts;
01780
01781 SetGeneratingWorldProgress(GWP_TOWN, total);
01782
01783
01784
01785
01786 do {
01787 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01788 IncreaseGeneratingWorldProgress(GWP_TOWN);
01789
01790 if (!GenerateTownName(&townnameparts)) continue;
01791
01792 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++;
01793 } while (--total);
01794
01795 if (current_number != 0) return true;
01796
01797
01798
01799 if (GenerateTownName(&townnameparts) &&
01800 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01801 return true;
01802 }
01803
01804
01805 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01806 extern StringID _switch_mode_errorstr;
01807 _switch_mode_errorstr = STR_ERROR_COULD_NOT_CREATE_TOWN;
01808 }
01809
01810 return false;
01811 }
01812
01813
01820 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01821 {
01822 uint dist = DistanceSquare(tile, t->xy);
01823
01824 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01825
01826 HouseZonesBits smallest = HZB_TOWN_EDGE;
01827 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01828 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01829 }
01830
01831 return smallest;
01832 }
01833
01844 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01845 {
01846 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01847
01848 assert(cc.Succeeded());
01849
01850 IncreaseBuildingCount(t, type);
01851 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01852 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01853
01854 MarkTileDirtyByTile(tile);
01855 }
01856
01857
01868 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01869 {
01870 BuildingFlags size = HouseSpec::Get(type)->building_flags;
01871
01872 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01873 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01874 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01875 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01876 }
01877
01878
01887 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01888 {
01889
01890 Slope slope = GetTileSlope(tile, NULL);
01891 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01892
01893
01894 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01895
01896
01897 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01898
01899
01900 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01901 }
01902
01903
01913 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
01914 {
01915 if (!CanBuildHouseHere(tile, town, noslope)) return false;
01916
01917
01918 if (GetTileMaxZ(tile) != z) return false;
01919
01920 return true;
01921 }
01922
01923
01933 static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
01934 {
01935
01936 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01937
01938 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
01939 tile += TileOffsByDiagDir(d);
01940 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
01941 }
01942
01943 return true;
01944 }
01945
01946
01954 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
01955 {
01956
01957 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01958
01959 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01960
01961 switch (t->layout) {
01962 case TL_2X2_GRID:
01963 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
01964 break;
01965
01966 case TL_3X3_GRID:
01967 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
01968 break;
01969
01970 default:
01971 break;
01972 }
01973
01974 return true;
01975 }
01976
01977
01985 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
01986 {
01987
01988 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
01989
01990
01991 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
01992
01993 switch (t->layout) {
01994 case TL_2X2_GRID:
01995 grid_pos.x %= 3;
01996 grid_pos.y %= 3;
01997 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
01998 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
01999 break;
02000
02001 case TL_3X3_GRID:
02002 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02003 break;
02004
02005 default:
02006 break;
02007 }
02008
02009 return true;
02010 }
02011
02012
02022 static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
02023 {
02024
02025
02026 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02027 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02028
02029 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02030 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02031 *tile = tile2;
02032 return true;
02033 }
02034
02035 return false;
02036 }
02037
02038
02047 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
02048 {
02049 TileIndex tile2 = *tile;
02050
02051 for (DiagDirection d = DIAGDIR_SE;;d++) {
02052 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02053 *tile = tile2;
02054 return true;
02055 }
02056 if (d == DIAGDIR_END) break;
02057 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
02058 }
02059
02060 return false;
02061 }
02062
02063
02070 static bool BuildTownHouse(Town *t, TileIndex tile)
02071 {
02072
02073 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02074
02075
02076 if (!CanBuildHouseHere(tile, t->index, false)) return false;
02077
02078 uint z;
02079 Slope slope = GetTileSlope(tile, &z);
02080
02081
02082
02083 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02084
02085
02086 int land = _settings_game.game_creation.landscape;
02087 if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
02088
02089 uint bitmask = (1 << rad) + (1 << (land + 12));
02090
02091
02092
02093
02094 HouseID houses[HOUSE_MAX];
02095 uint num = 0;
02096 uint probs[HOUSE_MAX];
02097 uint probability_max = 0;
02098
02099
02100 for (uint i = 0; i < HOUSE_MAX; i++) {
02101 const HouseSpec *hs = HouseSpec::Get(i);
02102
02103
02104 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02105
02106
02107 if (hs->class_id != HOUSE_NO_CLASS) {
02108
02109 if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02110 } else {
02111
02112 if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02113 }
02114
02115
02116 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02117 probability_max += cur_prob;
02118 probs[num] = cur_prob;
02119 houses[num++] = (HouseID)i;
02120 }
02121
02122 uint maxz = GetTileMaxZ(tile);
02123
02124 while (probability_max > 0) {
02125 uint r = RandomRange(probability_max);
02126 uint i;
02127 for (i = 0; i < num; i++) {
02128 if (probs[i] > r) break;
02129 r -= probs[i];
02130 }
02131
02132 HouseID house = houses[i];
02133 probability_max -= probs[i];
02134
02135
02136 num--;
02137 houses[i] = houses[num];
02138 probs[i] = probs[num];
02139
02140 const HouseSpec *hs = HouseSpec::Get(house);
02141
02142 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02143 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02144 continue;
02145 }
02146
02147 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02148
02149
02150 uint oneof = 0;
02151
02152 if (hs->building_flags & BUILDING_IS_CHURCH) {
02153 SetBit(oneof, TOWN_HAS_CHURCH);
02154 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02155 SetBit(oneof, TOWN_HAS_STADIUM);
02156 }
02157
02158 if (t->flags & oneof) continue;
02159
02160
02161 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02162 if (noslope && slope != SLOPE_FLAT) continue;
02163
02164 if (hs->building_flags & TILE_SIZE_2x2) {
02165 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02166 } else if (hs->building_flags & TILE_SIZE_2x1) {
02167 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02168 } else if (hs->building_flags & TILE_SIZE_1x2) {
02169 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02170 } else {
02171
02172 }
02173
02174 byte random_bits = Random();
02175
02176 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02177 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02178 if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
02179 }
02180
02181
02182 t->num_houses++;
02183
02184
02185 t->flags |= oneof;
02186
02187 byte construction_counter = 0;
02188 byte construction_stage = 0;
02189
02190 if (_generating_world || _game_mode == GM_EDITOR) {
02191 uint32 r = Random();
02192
02193 construction_stage = TOWN_HOUSE_COMPLETED;
02194 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02195
02196 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02197 ChangePopulation(t, hs->population);
02198 } else {
02199 construction_counter = GB(r, 2, 2);
02200 }
02201 }
02202
02203 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02204
02205 return true;
02206 }
02207
02208 return false;
02209 }
02210
02217 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02218 {
02219 assert(IsTileType(tile, MP_HOUSE));
02220 DecreaseBuildingCount(t, house);
02221 DoClearSquare(tile);
02222 DeleteAnimatedTile(tile);
02223
02224 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02225 }
02226
02234 TileIndexDiff GetHouseNorthPart(HouseID &house)
02235 {
02236 if (house >= 3) {
02237 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02238 house--;
02239 return TileDiffXY(-1, 0);
02240 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02241 house--;
02242 return TileDiffXY(0, -1);
02243 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02244 house -= 2;
02245 return TileDiffXY(-1, 0);
02246 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02247 house -= 3;
02248 return TileDiffXY(-1, -1);
02249 }
02250 }
02251 return 0;
02252 }
02253
02254 void ClearTownHouse(Town *t, TileIndex tile)
02255 {
02256 assert(IsTileType(tile, MP_HOUSE));
02257
02258 HouseID house = GetHouseType(tile);
02259
02260
02261 tile += GetHouseNorthPart(house);
02262
02263 const HouseSpec *hs = HouseSpec::Get(house);
02264
02265
02266 if (IsHouseCompleted(tile)) {
02267 ChangePopulation(t, -hs->population);
02268 }
02269
02270 t->num_houses--;
02271
02272
02273 if (hs->building_flags & BUILDING_IS_CHURCH) {
02274 ClrBit(t->flags, TOWN_HAS_CHURCH);
02275 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02276 ClrBit(t->flags, TOWN_HAS_STADIUM);
02277 }
02278
02279
02280 uint eflags = hs->building_flags;
02281 DoClearTownHouseHelper(tile, t, house);
02282 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02283 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02284 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02285 }
02286
02296 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02297 {
02298 Town *t = Town::GetIfValid(p1);
02299 if (t == NULL) return CMD_ERROR;
02300
02301 bool reset = StrEmpty(text);
02302
02303 if (!reset) {
02304 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02305 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02306 }
02307
02308 if (flags & DC_EXEC) {
02309 free(t->name);
02310 t->name = reset ? NULL : strdup(text);
02311
02312 t->UpdateVirtCoord();
02313 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02314 UpdateAllStationVirtCoords();
02315 }
02316 return CommandCost();
02317 }
02318
02328 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02329 {
02330 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02331 Town *t = Town::GetIfValid(p1);
02332 if (t == NULL) return CMD_ERROR;
02333
02334 if (flags & DC_EXEC) {
02335
02336 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02337 t->num_houses += amount;
02338 UpdateTownRadius(t);
02339
02340 uint n = amount * 10;
02341 do GrowTown(t); while (--n);
02342
02343 t->num_houses -= amount;
02344 UpdateTownRadius(t);
02345
02346 UpdateTownMaxPass(t);
02347 }
02348
02349 return CommandCost();
02350 }
02351
02361 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02362 {
02363 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02364 Town *t = Town::GetIfValid(p1);
02365 if (t == NULL) return CMD_ERROR;
02366
02367
02368 const Station *st;
02369 FOR_ALL_STATIONS(st) {
02370 if (st->town == t) {
02371
02372 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02373
02374 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02375 if (ret.Failed()) return ret;
02376 }
02377 }
02378
02379
02380 const Depot *d;
02381 FOR_ALL_DEPOTS(d) {
02382 if (d->town == t) return CMD_ERROR;
02383 }
02384
02385
02386 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02387 bool try_clear = false;
02388 switch (GetTileType(tile)) {
02389 case MP_ROAD:
02390 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02391 break;
02392
02393 case MP_TUNNELBRIDGE:
02394 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02395 break;
02396
02397 case MP_HOUSE:
02398 try_clear = GetTownIndex(tile) == t->index;
02399 break;
02400
02401 case MP_INDUSTRY:
02402 try_clear = Industry::GetByTile(tile)->town == t;
02403 break;
02404
02405 case MP_OBJECT:
02406 if (Town::GetNumItems() == 1) {
02407
02408 try_clear = true;
02409 } else {
02410 Object *o = Object::GetByTile(tile);
02411 if (o->town == t) {
02412 if (GetObjectType(tile) == OBJECT_STATUE) {
02413
02414 try_clear = true;
02415 } else {
02416
02417 o->town = NULL;
02418 }
02419 }
02420 }
02421 break;
02422
02423 default:
02424 break;
02425 }
02426 if (try_clear) {
02427 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02428 if (ret.Failed()) return ret;
02429 }
02430 }
02431
02432
02433 if (flags & DC_EXEC) delete t;
02434
02435 return CommandCost();
02436 }
02437
02442 const byte _town_action_costs[TACT_COUNT] = {
02443 2, 4, 9, 35, 48, 53, 117, 175
02444 };
02445
02446 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02447 {
02448 if (flags & DC_EXEC) {
02449 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02450 }
02451 return CommandCost();
02452 }
02453
02454 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02455 {
02456 if (flags & DC_EXEC) {
02457 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02458 }
02459 return CommandCost();
02460 }
02461
02462 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02463 {
02464 if (flags & DC_EXEC) {
02465 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02466 }
02467 return CommandCost();
02468 }
02469
02470 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02471 {
02472 if (flags & DC_EXEC) {
02473 t->road_build_months = 6;
02474
02475 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02476 SetDParam(0, _current_company);
02477 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02478
02479 char *cn = strdup(company_name);
02480 SetDParam(0, t->index);
02481 SetDParamStr(1, cn);
02482
02483 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02484 }
02485 return CommandCost();
02486 }
02487
02494 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02495 {
02496
02497 if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
02498
02499 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02500
02501 if (!IsTileType(tile, MP_HOUSE) &&
02502 !IsTileType(tile, MP_CLEAR) &&
02503 !IsTileType(tile, MP_TREES)) {
02504 return false;
02505 }
02506
02507 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02508 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02509 cur_company.Restore();
02510
02511 if (r.Failed()) return false;
02512
02513 return true;
02514 }
02515
02523 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02524 {
02525 TileIndex tile = t->xy;
02526 if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02527 if (flags & DC_EXEC) {
02528 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02529 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02530 cur_company.Restore();
02531 BuildObject(OBJECT_STATUE, tile, _current_company, t);
02532 SetBit(t->statues, _current_company);
02533 MarkTileDirtyByTile(tile);
02534 }
02535 return CommandCost();
02536 }
02537 return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02538 }
02539
02540 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02541 {
02542 if (flags & DC_EXEC) {
02543
02544 t->grow_counter = 1;
02545
02546 SetBit(t->flags, TOWN_IS_FUNDED);
02547
02548 t->fund_buildings_months = 3;
02549 }
02550 return CommandCost();
02551 }
02552
02553 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02554 {
02555
02556 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02557
02558 if (flags & DC_EXEC) {
02559 t->exclusive_counter = 12;
02560 t->exclusivity = _current_company;
02561
02562 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02563 }
02564 return CommandCost();
02565 }
02566
02567 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02568 {
02569 if (flags & DC_EXEC) {
02570 if (Chance16(1, 14)) {
02571
02572 t->unwanted[_current_company] = 6;
02573
02574
02575 Station *st;
02576 FOR_ALL_STATIONS(st) {
02577 if (st->town == t && st->owner == _current_company) {
02578 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02579 }
02580 }
02581
02582
02583
02584 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, STR_ERROR_BRIBE_FAILED_2, WL_INFO);
02585
02586
02587
02588
02589
02590 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02591 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02592 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02593 }
02594 } else {
02595 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02596 }
02597 }
02598 return CommandCost();
02599 }
02600
02601 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02602 static TownActionProc * const _town_action_proc[] = {
02603 TownActionAdvertiseSmall,
02604 TownActionAdvertiseMedium,
02605 TownActionAdvertiseLarge,
02606 TownActionRoadRebuild,
02607 TownActionBuildStatue,
02608 TownActionFundBuildings,
02609 TownActionBuyRights,
02610 TownActionBribe
02611 };
02612
02620 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02621 {
02622 int num = 0;
02623 TownActions buttons = TACT_NONE;
02624
02625
02626 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02627
02628
02629 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02630
02631
02632
02633 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02634 const TownActions cur = (TownActions)(1 << i);
02635
02636
02637 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02638
02639
02640 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02641
02642
02643 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02644
02645 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02646 buttons |= cur;
02647 num++;
02648 }
02649 }
02650 }
02651
02652 if (nump != NULL) *nump = num;
02653 return buttons;
02654 }
02655
02667 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02668 {
02669 Town *t = Town::GetIfValid(p1);
02670 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02671
02672 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02673
02674 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02675
02676 CommandCost ret = _town_action_proc[p2](t, flags);
02677 if (ret.Failed()) return ret;
02678
02679 if (flags & DC_EXEC) {
02680 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02681 }
02682
02683 return cost;
02684 }
02685
02686 static void UpdateTownGrowRate(Town *t)
02687 {
02688
02689 const Company *c;
02690 FOR_ALL_COMPANIES(c) {
02691 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02692 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02693 }
02694 }
02695
02696 int n = 0;
02697
02698 const Station *st;
02699 FOR_ALL_STATIONS(st) {
02700 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02701 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02702 n++;
02703 if (Company::IsValidID(st->owner)) {
02704 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02705 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02706 }
02707 } else {
02708 if (Company::IsValidID(st->owner)) {
02709 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02710 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02711 }
02712 }
02713 }
02714 }
02715
02716
02717 for (uint i = 0; i < MAX_COMPANIES; i++) {
02718 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02719 }
02720
02721 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02722
02723 ClrBit(t->flags, TOWN_IS_FUNDED);
02724 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02725
02730 static const uint16 _grow_count_values[2][6] = {
02731 { 120, 120, 120, 100, 80, 60 },
02732 { 320, 420, 300, 220, 160, 100 }
02733 };
02734
02735 uint16 m;
02736
02737 if (t->fund_buildings_months != 0) {
02738 m = _grow_count_values[0][min(n, 5)];
02739 t->fund_buildings_months--;
02740 } else {
02741 m = _grow_count_values[1][min(n, 5)];
02742 if (n == 0 && !Chance16(1, 12)) return;
02743 }
02744
02745 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
02746 if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90) return;
02747
02748 } else if (_settings_game.game_creation.landscape == LT_TROPIC) {
02749 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60) return;
02750 }
02751
02752
02753
02754 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02755
02756 m >>= growth_multiplier;
02757 if (t->larger_town) m /= 2;
02758
02759 t->growth_rate = m / (t->num_houses / 50 + 1);
02760 if (m <= t->grow_counter) {
02761 t->grow_counter = m;
02762 }
02763
02764 SetBit(t->flags, TOWN_IS_FUNDED);
02765 }
02766
02767 static void UpdateTownAmounts(Town *t)
02768 {
02769
02770 t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
02771
02772 t->max_pass = t->new_max_pass; t->new_max_pass = 0;
02773 t->act_pass = t->new_act_pass; t->new_act_pass = 0;
02774 t->act_food = t->new_act_food; t->new_act_food = 0;
02775 t->act_water = t->new_act_water; t->new_act_water = 0;
02776
02777
02778 t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
02779 t->max_mail = t->new_max_mail; t->new_max_mail = 0;
02780 t->act_mail = t->new_act_mail; t->new_act_mail = 0;
02781
02782 SetWindowDirty(WC_TOWN_VIEW, t->index);
02783 }
02784
02785 static void UpdateTownUnwanted(Town *t)
02786 {
02787 const Company *c;
02788
02789 FOR_ALL_COMPANIES(c) {
02790 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02791 }
02792 }
02793
02800 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02801 {
02802 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
02803
02804 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02805 if (t == NULL) return CommandCost();
02806
02807 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
02808
02809 SetDParam(0, t->index);
02810 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
02811 }
02812
02821 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02822 {
02823 Town *t;
02824 uint best = threshold;
02825 Town *best_town = NULL;
02826
02827 FOR_ALL_TOWNS(t) {
02828 uint dist = DistanceManhattan(tile, t->xy);
02829 if (dist < best) {
02830 best = dist;
02831 best_town = t;
02832 }
02833 }
02834
02835 return best_town;
02836 }
02837
02846 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02847 {
02848 switch (GetTileType(tile)) {
02849 case MP_ROAD:
02850 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02851
02852 if (!HasTownOwnedRoad(tile)) {
02853 TownID tid = GetTownIndex(tile);
02854
02855 if (tid == (TownID)INVALID_TOWN) {
02856
02857 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
02858 assert(Town::GetNumItems() == 0);
02859 return NULL;
02860 }
02861
02862 assert(Town::IsValidID(tid));
02863 Town *town = Town::Get(tid);
02864
02865 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
02866
02867 return town;
02868 }
02869
02870
02871 case MP_HOUSE:
02872 return Town::GetByTile(tile);
02873
02874 default:
02875 return CalcClosestTownFromTile(tile, threshold);
02876 }
02877 }
02878
02879 static bool _town_rating_test = false;
02880 static SmallMap<const Town *, int, 4> _town_test_ratings;
02881
02887 void SetTownRatingTestMode(bool mode)
02888 {
02889 static int ref_count = 0;
02890 if (mode) {
02891 if (ref_count == 0) {
02892 _town_test_ratings.Clear();
02893 }
02894 ref_count++;
02895 } else {
02896 assert(ref_count > 0);
02897 ref_count--;
02898 }
02899 _town_rating_test = !(ref_count == 0);
02900 }
02901
02907 static int GetRating(const Town *t)
02908 {
02909 if (_town_rating_test) {
02910 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
02911 if (it != _town_test_ratings.End()) {
02912 return it->second;
02913 }
02914 }
02915 return t->ratings[_current_company];
02916 }
02917
02925 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
02926 {
02927
02928 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
02929 !Company::IsValidID(_current_company) ||
02930 (_cheats.magic_bulldozer.value && add < 0)) {
02931 return;
02932 }
02933
02934 int rating = GetRating(t);
02935 if (add < 0) {
02936 if (rating > max) {
02937 rating += add;
02938 if (rating < max) rating = max;
02939 }
02940 } else {
02941 if (rating < max) {
02942 rating += add;
02943 if (rating > max) rating = max;
02944 }
02945 }
02946 if (_town_rating_test) {
02947 _town_test_ratings[t] = rating;
02948 } else {
02949 SetBit(t->have_ratings, _current_company);
02950 t->ratings[_current_company] = rating;
02951 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02952 }
02953 }
02954
02962 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
02963 {
02964
02965 if (t == NULL || !Company::IsValidID(_current_company) ||
02966 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
02967 return CommandCost();
02968 }
02969
02970
02971 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
02972
02973 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE},
02974 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL},
02975 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE},
02976 };
02977
02978
02979
02980
02981
02982 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
02983
02984 if (GetRating(t) < needed) {
02985 SetDParam(0, t->index);
02986 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
02987 }
02988
02989 return CommandCost();
02990 }
02991
02992 void TownsMonthlyLoop()
02993 {
02994 Town *t;
02995
02996 FOR_ALL_TOWNS(t) {
02997 if (t->road_build_months != 0) t->road_build_months--;
02998
02999 if (t->exclusive_counter != 0) {
03000 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03001 }
03002
03003 UpdateTownGrowRate(t);
03004 UpdateTownAmounts(t);
03005 UpdateTownUnwanted(t);
03006 }
03007 }
03008
03009 void TownsYearlyLoop()
03010 {
03011
03012 for (TileIndex t = 0; t < MapSize(); t++) {
03013 if (!IsTileType(t, MP_HOUSE)) continue;
03014 IncrementHouseAge(t);
03015 }
03016 }
03017
03018 void InitializeTowns()
03019 {
03020 _town_pool.CleanPool();
03021 }
03022
03023 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
03024 {
03025 if (AutoslopeEnabled()) {
03026 HouseID house = GetHouseType(tile);
03027 GetHouseNorthPart(house);
03028 const HouseSpec *hs = HouseSpec::Get(house);
03029
03030
03031 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03032 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03033 bool allow_terraform = true;
03034
03035
03036 house = GetHouseType(tile);
03037 hs = HouseSpec::Get(house);
03038 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03039
03040 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03041 if ((res != 0) && (res != CALLBACK_FAILED)) allow_terraform = false;
03042 }
03043
03044 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03045 }
03046 }
03047
03048 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03049 }
03050
03052 extern const TileTypeProcs _tile_type_town_procs = {
03053 DrawTile_Town,
03054 GetSlopeZ_Town,
03055 ClearTile_Town,
03056 AddAcceptedCargo_Town,
03057 GetTileDesc_Town,
03058 GetTileTrackStatus_Town,
03059 NULL,
03060 AnimateTile_Town,
03061 TileLoop_Town,
03062 ChangeTileOwner_Town,
03063 AddProducedCargo_Town,
03064 NULL,
03065 GetFoundation_Town,
03066 TerraformTile_Town,
03067 };
03068
03069
03070 HouseSpec _house_specs[HOUSE_MAX];
03071
03072 void ResetHouses()
03073 {
03074 memset(&_house_specs, 0, sizeof(_house_specs));
03075 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03076
03077
03078 _house_mngr.ResetOverride();
03079 }