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