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 "error.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 "autoslope.h"
00030 #include "tunnelbridge_map.h"
00031 #include "strings_func.h"
00032 #include "window_func.h"
00033 #include "string_func.h"
00034 #include "newgrf_cargo.h"
00035 #include "cheat_type.h"
00036 #include "animated_tile_func.h"
00037 #include "date_func.h"
00038 #include "subsidy_func.h"
00039 #include "core/pool_func.hpp"
00040 #include "town.h"
00041 #include "townname_func.h"
00042 #include "core/random_func.hpp"
00043 #include "core/backup_type.hpp"
00044 #include "depot_base.h"
00045 #include "object_map.h"
00046 #include "object_base.h"
00047 #include "ai/ai.hpp"
00048 #include "game/game.hpp"
00049
00050 #include "table/strings.h"
00051 #include "table/town_land.h"
00052
00053 TownID _new_town_id;
00054 uint32 _town_cargoes_accepted;
00055
00056
00057 TownPool _town_pool("Town");
00058 INSTANTIATE_POOL_METHODS(Town)
00059
00060 Town::~Town()
00061 {
00062 free(this->name);
00063 free(this->text);
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
00100 this->psa_list.clear();
00101
00102 DeleteSubsidyWith(ST_TOWN, this->index);
00103 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
00104 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
00105 MarkWholeScreenDirty();
00106 }
00107
00108
00114 void Town::PostDestructor(size_t index)
00115 {
00116 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
00117 UpdateNearestTownForRoadTiles(false);
00118
00119
00120 Object *o;
00121 FOR_ALL_OBJECTS(o) {
00122 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
00123 }
00124 }
00125
00129 void Town::InitializeLayout(TownLayout layout)
00130 {
00131 if (layout != TL_RANDOM) {
00132 this->layout = layout;
00133 return;
00134 }
00135
00136 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
00137 }
00138
00143 Town *Town::GetRandom()
00144 {
00145 if (Town::GetNumItems() == 0) return NULL;
00146 int num = RandomRange((uint16)Town::GetNumItems());
00147 size_t index = MAX_UVALUE(size_t);
00148
00149 while (num >= 0) {
00150 num--;
00151 index++;
00152
00153
00154 while (!Town::IsValidID(index)) {
00155 index++;
00156 assert(index < Town::GetPoolSize());
00157 }
00158 }
00159
00160 return Town::Get(index);
00161 }
00162
00167 Money HouseSpec::GetRemovalCost() const
00168 {
00169 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
00170 }
00171
00172
00173 static int _grow_town_result;
00174
00175
00176 enum TownGrowthResult {
00177 GROWTH_SUCCEED = -1,
00178 GROWTH_SEARCH_STOPPED = 0
00179
00180 };
00181
00182 static bool BuildTownHouse(Town *t, TileIndex tile);
00183 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
00184
00185 static void TownDrawHouseLift(const TileInfo *ti)
00186 {
00187 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
00188 }
00189
00190 typedef void TownDrawTileProc(const TileInfo *ti);
00191 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
00192 TownDrawHouseLift
00193 };
00194
00200 static inline DiagDirection RandomDiagDir()
00201 {
00202 return (DiagDirection)(3 & Random());
00203 }
00204
00210 static void DrawTile_Town(TileInfo *ti)
00211 {
00212 HouseID house_id = GetHouseType(ti->tile);
00213
00214 if (house_id >= NEW_HOUSE_OFFSET) {
00215
00216
00217
00218 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
00219 DrawNewHouseTile(ti, house_id);
00220 return;
00221 } else {
00222 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
00223 }
00224 }
00225
00226
00227 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
00228
00229 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
00230
00231 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
00232
00233
00234 if (IsInvisibilitySet(TO_HOUSES)) return;
00235
00236
00237 SpriteID image = dcts->building.sprite;
00238 if (image != 0) {
00239 AddSortableSpriteToDraw(image, dcts->building.pal,
00240 ti->x + dcts->subtile_x,
00241 ti->y + dcts->subtile_y,
00242 dcts->width,
00243 dcts->height,
00244 dcts->dz,
00245 ti->z,
00246 IsTransparencySet(TO_HOUSES)
00247 );
00248
00249 if (IsTransparencySet(TO_HOUSES)) return;
00250 }
00251
00252 {
00253 int proc = dcts->draw_proc - 1;
00254
00255 if (proc >= 0) _town_draw_tile_procs[proc](ti);
00256 }
00257 }
00258
00259 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
00260 {
00261 return GetTileMaxPixelZ(tile);
00262 }
00263
00265 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
00266 {
00267 HouseID hid = GetHouseType(tile);
00268
00269
00270
00271
00272
00273 if (hid >= NEW_HOUSE_OFFSET) {
00274 const HouseSpec *hs = HouseSpec::Get(hid);
00275 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
00276 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
00277 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
00278 }
00279 }
00280 return FlatteningFoundation(tileh);
00281 }
00282
00289 static void AnimateTile_Town(TileIndex tile)
00290 {
00291 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
00292 AnimateNewHouseTile(tile);
00293 return;
00294 }
00295
00296 if (_tick_counter & 3) return;
00297
00298
00299
00300
00301
00302 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
00303 DeleteAnimatedTile(tile);
00304 return;
00305 }
00306
00307 if (!LiftHasDestination(tile)) {
00308 uint i;
00309
00310
00311
00312
00313
00314 do {
00315 i = RandomRange(7);
00316 } while (i == 1 || i * 6 == GetLiftPosition(tile));
00317
00318 SetLiftDestination(tile, i);
00319 }
00320
00321 int pos = GetLiftPosition(tile);
00322 int dest = GetLiftDestination(tile) * 6;
00323 pos += (pos < dest) ? 1 : -1;
00324 SetLiftPosition(tile, pos);
00325
00326 if (pos == dest) {
00327 HaltLift(tile);
00328 DeleteAnimatedTile(tile);
00329 }
00330
00331 MarkTileDirtyByTile(tile);
00332 }
00333
00340 static bool IsCloseToTown(TileIndex tile, uint dist)
00341 {
00342 const Town *t;
00343
00344 FOR_ALL_TOWNS(t) {
00345 if (DistanceManhattan(tile, t->xy) < dist) return true;
00346 }
00347 return false;
00348 }
00349
00354 void Town::UpdateVirtCoord()
00355 {
00356 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00357 SetDParam(0, this->index);
00358 SetDParam(1, this->cache.population);
00359 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
00360 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN);
00361
00362 SetWindowDirty(WC_TOWN_VIEW, this->index);
00363 }
00364
00366 void UpdateAllTownVirtCoords()
00367 {
00368 Town *t;
00369
00370 FOR_ALL_TOWNS(t) {
00371 t->UpdateVirtCoord();
00372 }
00373 }
00374
00380 static void ChangePopulation(Town *t, int mod)
00381 {
00382 t->cache.population += mod;
00383 InvalidateWindowData(WC_TOWN_VIEW, t->index);
00384 t->UpdateVirtCoord();
00385
00386 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
00387 }
00388
00394 uint32 GetWorldPopulation()
00395 {
00396 uint32 pop = 0;
00397 const Town *t;
00398
00399 FOR_ALL_TOWNS(t) pop += t->cache.population;
00400 return pop;
00401 }
00402
00407 static void MakeSingleHouseBigger(TileIndex tile)
00408 {
00409 assert(IsTileType(tile, MP_HOUSE));
00410
00411
00412 IncHouseConstructionTick(tile);
00413 if (GetHouseConstructionTick(tile) != 0) return;
00414
00415 AnimateNewHouseConstruction(tile);
00416
00417 if (IsHouseCompleted(tile)) {
00418
00419
00420 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
00421 ResetHouseAge(tile);
00422 }
00423 MarkTileDirtyByTile(tile);
00424 }
00425
00430 static void MakeTownHouseBigger(TileIndex tile)
00431 {
00432 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
00433 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
00434 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
00435 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
00436 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
00437 }
00438
00445 static void TileLoop_Town(TileIndex tile)
00446 {
00447 HouseID house_id = GetHouseType(tile);
00448
00449
00450
00451 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
00452
00453 if (!IsHouseCompleted(tile)) {
00454
00455 MakeTownHouseBigger(tile);
00456 return;
00457 }
00458
00459 const HouseSpec *hs = HouseSpec::Get(house_id);
00460
00461
00462 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
00463 house_id < NEW_HOUSE_OFFSET &&
00464 !LiftHasDestination(tile) &&
00465 Chance16(1, 2)) {
00466 AddAnimatedTile(tile);
00467 }
00468
00469 Town *t = Town::GetByTile(tile);
00470 uint32 r = Random();
00471
00472 StationFinder stations(TileArea(tile, 1, 1));
00473
00474 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00475 for (uint i = 0; i < 256; i++) {
00476 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
00477
00478 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00479
00480 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00481 if (cargo == CT_INVALID) continue;
00482
00483 uint amt = GB(callback, 0, 8);
00484 if (amt == 0) continue;
00485
00486 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
00487
00488 const CargoSpec *cs = CargoSpec::Get(cargo);
00489 t->supplied[cs->Index()].new_max += amt;
00490 t->supplied[cs->Index()].new_act += moved;
00491 }
00492 } else {
00493 if (GB(r, 0, 8) < hs->population) {
00494 uint amt = GB(r, 0, 8) / 8 + 1;
00495
00496 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00497 t->supplied[CT_PASSENGERS].new_max += amt;
00498 t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
00499 }
00500
00501 if (GB(r, 8, 8) < hs->mail_generation) {
00502 uint amt = GB(r, 8, 8) / 8 + 1;
00503
00504 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00505 t->supplied[CT_MAIL].new_max += amt;
00506 t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
00507 }
00508 }
00509
00510 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
00511
00512 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
00513 HasBit(t->flags, TOWN_IS_GROWING) &&
00514 CanDeleteHouse(tile) &&
00515 GetHouseAge(tile) >= hs->minimum_life &&
00516 --t->time_until_rebuild == 0) {
00517 t->time_until_rebuild = GB(r, 16, 8) + 192;
00518
00519 ClearTownHouse(t, tile);
00520
00521
00522 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
00523 }
00524
00525 cur_company.Restore();
00526 }
00527
00528 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
00529 {
00530 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
00531 if (!CanDeleteHouse(tile)) return CMD_ERROR;
00532
00533 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00534
00535 CommandCost cost(EXPENSES_CONSTRUCTION);
00536 cost.AddCost(hs->GetRemovalCost());
00537
00538 int rating = hs->remove_rating_decrease;
00539 Town *t = Town::GetByTile(tile);
00540
00541 if (Company::IsValidID(_current_company)) {
00542 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
00543 SetDParam(0, t->index);
00544 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00545 }
00546 }
00547
00548 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
00549 if (flags & DC_EXEC) {
00550 ClearTownHouse(t, tile);
00551 }
00552
00553 return cost;
00554 }
00555
00556 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
00557 {
00558 HouseID house_id = GetHouseType(tile);
00559 const HouseSpec *hs = HouseSpec::Get(house_id);
00560 Town *t = Town::GetByTile(tile);
00561
00562 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
00563 for (uint i = 0; i < 256; i++) {
00564 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
00565
00566 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
00567
00568 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
00569
00570 if (cargo == CT_INVALID) continue;
00571 produced[cargo]++;
00572 }
00573 } else {
00574 if (hs->population > 0) {
00575 produced[CT_PASSENGERS]++;
00576 }
00577 if (hs->mail_generation > 0) {
00578 produced[CT_MAIL]++;
00579 }
00580 }
00581 }
00582
00583 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
00584 {
00585 if (cargo == CT_INVALID || amount == 0) return;
00586 acceptance[cargo] += amount;
00587 SetBit(*always_accepted, cargo);
00588 }
00589
00590 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00591 {
00592 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
00593 CargoID accepts[3];
00594
00595
00596 for (uint8 i = 0; i < lengthof(accepts); i++) {
00597 accepts[i] = hs->accepts_cargo[i];
00598 }
00599
00600
00601 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
00602 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00603 if (callback != CALLBACK_FAILED) {
00604
00605 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
00606 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
00607 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
00608 }
00609 }
00610
00611
00612 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
00613 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
00614 if (callback != CALLBACK_FAILED) {
00615 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
00616 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
00617 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
00618
00619 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
00620 } else {
00621 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
00622 }
00623 return;
00624 }
00625 }
00626
00627
00628 for (uint8 i = 0; i < lengthof(accepts); i++) {
00629 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
00630 }
00631 }
00632
00633 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
00634 {
00635 const HouseID house = GetHouseType(tile);
00636 const HouseSpec *hs = HouseSpec::Get(house);
00637 bool house_completed = IsHouseCompleted(tile);
00638
00639 td->str = hs->building_name;
00640
00641 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
00642 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
00643 if (callback_res > 0x400) {
00644 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
00645 } else {
00646 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
00647 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
00648 td->str = new_name;
00649 }
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
00680 void UpdateTownCargoTotal(Town *t)
00681 {
00682 t->cargo_accepted_total = 0;
00683
00684 const TileArea &area = t->cargo_accepted.GetArea();
00685 TILE_AREA_LOOP(tile, area) {
00686 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00687 t->cargo_accepted_total |= t->cargo_accepted[tile];
00688 }
00689 }
00690 }
00691
00698 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
00699 {
00700 CargoArray accepted, produced;
00701 uint32 dummy;
00702
00703
00704
00705
00706 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
00707 TILE_AREA_LOOP(tile, area) {
00708 if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
00709
00710 AddAcceptedCargo_Town(tile, accepted, &dummy);
00711 AddProducedCargo_Town(tile, produced);
00712 }
00713
00714
00715 uint32 acc = 0;
00716 for (uint cid = 0; cid < NUM_CARGO; cid++) {
00717 if (accepted[cid] >= 8) SetBit(acc, cid);
00718 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
00719 }
00720 t->cargo_accepted[start] = acc;
00721
00722 if (update_total) UpdateTownCargoTotal(t);
00723 }
00724
00728 void UpdateTownCargoes(Town *t)
00729 {
00730 t->cargo_produced = 0;
00731
00732 const TileArea &area = t->cargo_accepted.GetArea();
00733 if (area.tile == INVALID_TILE) return;
00734
00735
00736 TILE_AREA_LOOP(tile, area) {
00737 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
00738 UpdateTownCargoes(t, tile, false);
00739 }
00740 }
00741
00742
00743 UpdateTownCargoTotal(t);
00744 }
00745
00747 void UpdateTownCargoBitmap()
00748 {
00749 Town *town;
00750 _town_cargoes_accepted = 0;
00751
00752 FOR_ALL_TOWNS(town) {
00753 _town_cargoes_accepted |= town->cargo_accepted_total;
00754 }
00755 }
00756
00757 static bool GrowTown(Town *t);
00758
00759 static void TownTickHandler(Town *t)
00760 {
00761 if (HasBit(t->flags, TOWN_IS_GROWING)) {
00762 int i = t->grow_counter - 1;
00763 if (i < 0) {
00764 if (GrowTown(t)) {
00765 i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
00766 } else {
00767 i = 0;
00768 }
00769 }
00770 t->grow_counter = i;
00771 }
00772 }
00773
00774 void OnTick_Town()
00775 {
00776 if (_game_mode == GM_EDITOR) return;
00777
00778 Town *t;
00779 FOR_ALL_TOWNS(t) {
00780
00781 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00782 TownTickHandler(t);
00783 }
00784 }
00785 }
00786
00795 static RoadBits GetTownRoadBits(TileIndex tile)
00796 {
00797 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00798
00799 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00800 }
00801
00812 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00813 {
00814 if (!IsValidTile(tile)) return false;
00815
00816
00817 const TileIndexDiff tid_lt[3] = {
00818 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00819 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00820 TileOffsByDiagDir(ReverseDiagDir(dir)),
00821 };
00822
00823 dist_multi = (dist_multi + 1) * 4;
00824 for (uint pos = 4; pos < dist_multi; pos++) {
00825
00826 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00827
00828
00829 if (pos & 2) cur += tid_lt[2];
00830
00831
00832 if (IsValidTile(tile + cur) &&
00833 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00834 }
00835 return false;
00836 }
00837
00846 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00847 {
00848 if (DistanceFromEdge(tile) == 0) return false;
00849
00850
00851 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
00852
00853
00854 if (GetTownRoadBits(tile) == ROAD_NONE) {
00855
00856
00857
00858 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00859 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
00860 return false;
00861 }
00862 }
00863
00864 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
00865 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00866 if (cur_slope == SLOPE_FLAT) return ret;
00867
00868
00869
00870 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00871 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00872 if (Chance16(1, 8)) {
00873 CommandCost res = CMD_ERROR;
00874 if (!_generating_world && Chance16(1, 10)) {
00875
00876 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00877 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00878 }
00879 if (res.Failed() && Chance16(1, 3)) {
00880
00881 return ret;
00882 }
00883 }
00884 return false;
00885 }
00886 return ret;
00887 }
00888
00889 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00890 {
00891 assert(tile < MapSize());
00892
00893 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00894 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00895 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00896 return true;
00897 }
00898
00899 static void LevelTownLand(TileIndex tile)
00900 {
00901 assert(tile < MapSize());
00902
00903
00904 if (IsTileType(tile, MP_HOUSE)) return;
00905 Slope tileh = GetTileSlope(tile);
00906 if (tileh == SLOPE_FLAT) return;
00907
00908
00909 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00910 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00911 }
00912 }
00913
00923 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00924 {
00925
00926 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00927 RoadBits rcmd = ROAD_NONE;
00928
00929 switch (t->layout) {
00930 default: NOT_REACHED();
00931
00932 case TL_2X2_GRID:
00933 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00934 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00935 break;
00936
00937 case TL_3X3_GRID:
00938 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00939 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00940 break;
00941 }
00942
00943
00944 if (rcmd != ROAD_ALL) return rcmd;
00945
00946 RoadBits rb_template;
00947
00948 switch (GetTileSlope(tile)) {
00949 default: rb_template = ROAD_ALL; break;
00950 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00951 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00952 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00953 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00954 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00955 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00956 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00957 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00958 case SLOPE_STEEP_W:
00959 case SLOPE_STEEP_S:
00960 case SLOPE_STEEP_E:
00961 case SLOPE_STEEP_N:
00962 rb_template = ROAD_NONE;
00963 break;
00964 }
00965
00966
00967 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00968
00969 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00970 }
00971
00982 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00983 {
00984
00985 if (DistanceFromEdge(tile) == 0) return false;
00986
00987 uint counter = 0;
00988
00989
00990 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00991
00992
00993
00994 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00995 case MP_HOUSE:
00996 case MP_VOID:
00997 counter++;
00998 break;
00999
01000 default:
01001 break;
01002 }
01003
01004
01005 if (counter >= 3) {
01006 if (BuildTownHouse(t, tile)) {
01007 _grow_town_result = GROWTH_SUCCEED;
01008 return true;
01009 }
01010 return false;
01011 }
01012 }
01013 return false;
01014 }
01015
01024 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01025 {
01026 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01027 _grow_town_result = GROWTH_SUCCEED;
01028 return true;
01029 }
01030 return false;
01031 }
01032
01043 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01044 {
01045 assert(bridge_dir < DIAGDIR_END);
01046
01047 const Slope slope = GetTileSlope(tile);
01048
01049
01050
01051
01052 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
01053
01054
01055 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01056
01057
01058 uint8 bridge_length = 0;
01059 TileIndex bridge_tile = tile;
01060
01061 const int delta = TileOffsByDiagDir(bridge_dir);
01062
01063 if (slope == SLOPE_FLAT) {
01064
01065 do {
01066 if (bridge_length++ >= 4) {
01067
01068 return false;
01069 }
01070 bridge_tile += delta;
01071 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
01072 } else {
01073 do {
01074 if (bridge_length++ >= 11) {
01075
01076 return false;
01077 }
01078 bridge_tile += delta;
01079 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
01080 }
01081
01082
01083 if (bridge_length == 1) return false;
01084
01085 for (uint8 times = 0; times <= 22; times++) {
01086 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01087
01088
01089 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01090 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01091 _grow_town_result = GROWTH_SUCCEED;
01092 return true;
01093 }
01094 }
01095
01096 return false;
01097 }
01098
01116 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01117 {
01118 RoadBits rcmd = ROAD_NONE;
01119 TileIndex tile = *tile_ptr;
01120
01121 assert(tile < MapSize());
01122
01123 if (cur_rb == ROAD_NONE) {
01124
01125
01126 _grow_town_result = GROWTH_SEARCH_STOPPED;
01127
01128 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01129 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01130
01131
01132 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01133
01134
01135 switch (t1->layout) {
01136 default: NOT_REACHED();
01137
01138 case TL_3X3_GRID:
01139 case TL_2X2_GRID:
01140 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01141 if (rcmd == ROAD_NONE) return;
01142 break;
01143
01144 case TL_BETTER_ROADS:
01145 case TL_ORIGINAL:
01146 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01147
01148 DiagDirection source_dir = ReverseDiagDir(target_dir);
01149
01150 if (Chance16(1, 4)) {
01151
01152 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01153 }
01154
01155 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01156
01157
01158 if (target_dir != ReverseDiagDir(source_dir)) return;
01159
01160
01161 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01162 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01163 return;
01164 }
01165
01166
01167
01168 }
01169
01170 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01171 break;
01172 }
01173
01174 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01175
01176
01177
01178 _grow_town_result = GROWTH_SEARCH_STOPPED;
01179
01180 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01181
01182 switch (t1->layout) {
01183 default: NOT_REACHED();
01184
01185 case TL_3X3_GRID:
01186 case TL_2X2_GRID:
01187 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01188 break;
01189
01190 case TL_BETTER_ROADS:
01191 case TL_ORIGINAL:
01192 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01193 break;
01194 }
01195 } else {
01196 bool allow_house = true;
01197
01198
01199
01200 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01201 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
01202 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01203 }
01204 return;
01205 }
01206
01207
01208
01209 target_dir = RandomDiagDir();
01210 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01211
01212
01213 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01214
01215
01216 if (HasTileWaterGround(house_tile)) return;
01217
01218 if (!IsValidTile(house_tile)) return;
01219
01220 if (_settings_game.economy.allow_town_roads || _generating_world) {
01221 switch (t1->layout) {
01222 default: NOT_REACHED();
01223
01224 case TL_3X3_GRID:
01225 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01226
01227
01228 case TL_2X2_GRID:
01229 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01230 allow_house = (rcmd == ROAD_NONE);
01231 break;
01232
01233 case TL_BETTER_ROADS:
01234 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01235
01236
01237 case TL_ORIGINAL:
01238
01239
01240 rcmd = DiagDirToRoadBits(target_dir);
01241 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01242 break;
01243 }
01244 }
01245
01246 if (allow_house) {
01247
01248 if (!IsTileType(house_tile, MP_HOUSE)) {
01249
01250 if (Chance16(1, 6)) LevelTownLand(house_tile);
01251
01252
01253
01254 if (BuildTownHouse(t1, house_tile)) {
01255 _grow_town_result = GROWTH_SUCCEED;
01256 }
01257 }
01258 return;
01259 }
01260
01261 _grow_town_result = GROWTH_SEARCH_STOPPED;
01262 }
01263
01264
01265 if (HasTileWaterGround(tile)) return;
01266
01267
01268 rcmd = CleanUpRoadBits(tile, rcmd);
01269 if (rcmd == ROAD_NONE) return;
01270
01271
01272
01273
01274 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01275
01276 GrowTownWithRoad(t1, tile, rcmd);
01277 }
01278
01285 static int GrowTownAtRoad(Town *t, TileIndex tile)
01286 {
01287
01288
01289
01290 DiagDirection target_dir = DIAGDIR_END;
01291
01292 assert(tile < MapSize());
01293
01294
01295
01296
01297 switch (t->layout) {
01298 case TL_BETTER_ROADS:
01299 _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
01300 break;
01301
01302 case TL_3X3_GRID:
01303 case TL_2X2_GRID:
01304 _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
01305 break;
01306
01307 default:
01308 _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
01309 break;
01310 }
01311
01312 do {
01313 RoadBits cur_rb = GetTownRoadBits(tile);
01314
01315
01316 GrowTownInTile(&tile, cur_rb, target_dir, t);
01317
01318
01319
01320 if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01321 if (cur_rb == ROAD_NONE) {
01322 return _grow_town_result;
01323 }
01324
01325 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01326
01327 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
01328 } else {
01329
01330
01331 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01332 }
01333 tile = TileAddByDiagDir(tile, target_dir);
01334
01335 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01336
01337 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01338 _grow_town_result = GROWTH_SUCCEED;
01339 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01340
01341
01342 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01343 SetTownIndex(tile, t->index);
01344 }
01345 }
01346
01347
01348 } while (--_grow_town_result >= 0);
01349
01350 return (_grow_town_result == -2);
01351 }
01352
01360 static RoadBits GenRandomRoadBits()
01361 {
01362 uint32 r = Random();
01363 uint a = GB(r, 0, 2);
01364 uint b = GB(r, 8, 2);
01365 if (a == b) b ^= 2;
01366 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01367 }
01368
01374 static bool GrowTown(Town *t)
01375 {
01376 static const TileIndexDiffC _town_coord_mod[] = {
01377 {-1, 0},
01378 { 1, 1},
01379 { 1, -1},
01380 {-1, -1},
01381 {-1, 0},
01382 { 0, 2},
01383 { 2, 0},
01384 { 0, -2},
01385 {-1, -1},
01386 {-2, 2},
01387 { 2, 2},
01388 { 2, -2},
01389 { 0, 0}
01390 };
01391
01392
01393 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01394
01395 TileIndex tile = t->xy;
01396
01397
01398 const TileIndexDiffC *ptr;
01399 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01400 if (GetTownRoadBits(tile) != ROAD_NONE) {
01401 int r = GrowTownAtRoad(t, tile);
01402 cur_company.Restore();
01403 return r != 0;
01404 }
01405 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01406 }
01407
01408
01409
01410 if (_settings_game.economy.allow_town_roads || _generating_world) {
01411 tile = t->xy;
01412 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01413
01414 if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
01415 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01416 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01417 cur_company.Restore();
01418 return true;
01419 }
01420 }
01421 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01422 }
01423 }
01424
01425 cur_company.Restore();
01426 return false;
01427 }
01428
01429 void UpdateTownRadius(Town *t)
01430 {
01431 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01432 { 4, 0, 0, 0, 0},
01433 { 16, 0, 0, 0, 0},
01434 { 25, 0, 0, 0, 0},
01435 { 36, 0, 0, 0, 0},
01436 { 49, 0, 4, 0, 0},
01437 { 64, 0, 4, 0, 0},
01438 { 64, 0, 9, 0, 1},
01439 { 64, 0, 9, 0, 4},
01440 { 64, 0, 16, 0, 4},
01441 { 81, 0, 16, 0, 4},
01442 { 81, 0, 16, 0, 4},
01443 { 81, 0, 25, 0, 9},
01444 { 81, 36, 25, 0, 9},
01445 { 81, 36, 25, 16, 9},
01446 { 81, 49, 0, 25, 9},
01447 { 81, 64, 0, 25, 9},
01448 { 81, 64, 0, 36, 9},
01449 { 81, 64, 0, 36, 16},
01450 {100, 81, 0, 49, 16},
01451 {100, 81, 0, 49, 25},
01452 {121, 81, 0, 49, 25},
01453 {121, 81, 0, 49, 25},
01454 {121, 81, 0, 49, 36},
01455 };
01456
01457 if (t->cache.num_houses < 92) {
01458 memcpy(t->cache.squared_town_zone_radius, _town_squared_town_zone_radius_data[t->cache.num_houses / 4], sizeof(t->cache.squared_town_zone_radius));
01459 } else {
01460 int mass = t->cache.num_houses / 8;
01461
01462
01463
01464 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
01465 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
01466 t->cache.squared_town_zone_radius[2] = 0;
01467 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
01468 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
01469 }
01470 }
01471
01472 void UpdateTownMaxPass(Town *t)
01473 {
01474 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
01475 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
01476 }
01477
01489 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01490 {
01491 t->xy = tile;
01492 t->cache.num_houses = 0;
01493 t->time_until_rebuild = 10;
01494 UpdateTownRadius(t);
01495 t->flags = 0;
01496 t->cache.population = 0;
01497 t->grow_counter = 0;
01498 t->growth_rate = 250;
01499
01500
01501 switch (_settings_game.game_creation.landscape) {
01502 case LT_ARCTIC:
01503 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
01504 break;
01505
01506 case LT_TROPIC:
01507 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
01508 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
01509 break;
01510 }
01511
01512 t->fund_buildings_months = 0;
01513
01514 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01515
01516 t->have_ratings = 0;
01517 t->exclusivity = INVALID_COMPANY;
01518 t->exclusive_counter = 0;
01519 t->statues = 0;
01520
01521 extern int _nb_orig_names;
01522 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01523
01524 t->townnamegrfid = 0;
01525 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01526 } else {
01527
01528 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01529 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01530 }
01531 t->townnameparts = townnameparts;
01532
01533 t->UpdateVirtCoord();
01534 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01535
01536 t->InitializeLayout(layout);
01537
01538 t->larger_town = city;
01539
01540 int x = (int)size * 16 + 3;
01541 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01542
01543 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01544
01545 t->cache.num_houses += x;
01546 UpdateTownRadius(t);
01547
01548 int i = x * 4;
01549 do {
01550 GrowTown(t);
01551 } while (--i);
01552
01553 t->cache.num_houses -= x;
01554 UpdateTownRadius(t);
01555 UpdateTownMaxPass(t);
01556 UpdateAirportsNoise();
01557 }
01558
01564 static CommandCost TownCanBePlacedHere(TileIndex tile)
01565 {
01566
01567 if (DistanceFromEdge(tile) < 12) {
01568 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01569 }
01570
01571
01572 if (IsCloseToTown(tile, 20)) {
01573 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01574 }
01575
01576
01577 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
01578 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01579 }
01580
01581 return CommandCost(EXPENSES_OTHER);
01582 }
01583
01589 static bool IsUniqueTownName(const char *name)
01590 {
01591 const Town *t;
01592
01593 FOR_ALL_TOWNS(t) {
01594 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01595 }
01596
01597 return true;
01598 }
01599
01612 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01613 {
01614 TownSize size = Extract<TownSize, 0, 2>(p1);
01615 bool city = HasBit(p1, 2);
01616 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01617 TownNameParams par(_settings_game.game_creation.town_name);
01618 bool random = HasBit(p1, 6);
01619 uint32 townnameparts = p2;
01620
01621 if (size >= TSZ_END) return CMD_ERROR;
01622 if (layout >= NUM_TLS) return CMD_ERROR;
01623
01624
01625 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
01626 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01627 if (size == TSZ_LARGE) return CMD_ERROR;
01628 if (random) return CMD_ERROR;
01629 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01630 return CMD_ERROR;
01631 }
01632 } else if (_current_company == OWNER_DEITY && random) {
01633
01634 return CMD_ERROR;
01635 }
01636
01637 if (StrEmpty(text)) {
01638
01639 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01640 } else {
01641
01642 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01643 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01644 }
01645
01646
01647 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01648
01649 if (!random) {
01650 CommandCost ret = TownCanBePlacedHere(tile);
01651 if (ret.Failed()) return ret;
01652 }
01653
01654 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01655
01656 assert_compile(lengthof(price_mult[0]) == 4);
01657
01658 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01659 byte mult = price_mult[city][size];
01660
01661 cost.MultiplyCost(mult);
01662
01663
01664 if (flags & DC_EXEC) {
01665 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01666 _additional_cash_required = cost.GetCost();
01667 return CommandCost(EXPENSES_OTHER);
01668 }
01669
01670 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
01671 UpdateNearestTownForRoadTiles(true);
01672 Town *t;
01673 if (random) {
01674 t = CreateRandomTown(20, townnameparts, size, city, layout);
01675 if (t == NULL) {
01676 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01677 } else {
01678 _new_town_id = t->index;
01679 }
01680 } else {
01681 t = new Town(tile);
01682 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01683 }
01684 UpdateNearestTownForRoadTiles(false);
01685 old_generating_world.Restore();
01686
01687 if (t != NULL && !StrEmpty(text)) {
01688 t->name = strdup(text);
01689 t->UpdateVirtCoord();
01690 }
01691
01692 if (_game_mode != GM_EDITOR) {
01693
01694 assert(!random);
01695 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01696 SetDParam(0, _current_company);
01697 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01698
01699 char *cn = strdup(company_name);
01700 SetDParamStr(0, cn);
01701 SetDParam(1, t->index);
01702
01703 AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
01704 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
01705 Game::NewEvent(new ScriptEventTownFounded(t->index));
01706 }
01707 }
01708 return cost;
01709 }
01710
01720 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01721 {
01722 switch (layout) {
01723 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01724 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01725 default: return tile;
01726 }
01727 }
01728
01738 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01739 {
01740 switch (layout) {
01741 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01742 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01743 default: return true;
01744 }
01745 }
01746
01750 struct SpotData {
01751 TileIndex tile;
01752 uint max_dist;
01753 TownLayout layout;
01754 };
01755
01772 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01773 {
01774 SpotData *sp = (SpotData*)user_data;
01775 uint dist = GetClosestWaterDistance(tile, true);
01776
01777 if (IsTileType(tile, MP_CLEAR) &&
01778 IsTileFlat(tile) &&
01779 IsTileAlignedToGrid(tile, sp->layout) &&
01780 dist > sp->max_dist) {
01781 sp->tile = tile;
01782 sp->max_dist = dist;
01783 }
01784
01785 return false;
01786 }
01787
01794 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01795 {
01796 return IsTileType(tile, MP_CLEAR);
01797 }
01798
01811 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01812 {
01813 SpotData sp = { INVALID_TILE, 0, layout };
01814
01815 TileIndex coast = tile;
01816 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01817 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01818 return sp.tile;
01819 }
01820
01821
01822 return INVALID_TILE;
01823 }
01824
01825 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01826 {
01827 assert(_game_mode == GM_EDITOR || _generating_world);
01828
01829 if (!Town::CanAllocateItem()) return NULL;
01830
01831 do {
01832
01833 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01834
01835
01836
01837 if (IsTileType(tile, MP_WATER)) {
01838 tile = FindNearestGoodCoastalTownSpot(tile, layout);
01839 if (tile == INVALID_TILE) continue;
01840 }
01841
01842
01843 if (TownCanBePlacedHere(tile).Failed()) continue;
01844
01845
01846 Town *t = new Town(tile);
01847
01848 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01849
01850
01851
01852 if (t->cache.population > 0) return t;
01853
01854 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01855 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01856 cur_company.Restore();
01857 assert(rc.Succeeded());
01858
01859
01860
01861
01862
01863 assert(Town::CanAllocateItem());
01864 } while (--attempts != 0);
01865
01866 return NULL;
01867 }
01868
01869 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01870
01878 bool GenerateTowns(TownLayout layout)
01879 {
01880 uint current_number = 0;
01881 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01882 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01883 uint32 townnameparts;
01884
01885 SetGeneratingWorldProgress(GWP_TOWN, total);
01886
01887
01888
01889
01890 do {
01891 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01892 IncreaseGeneratingWorldProgress(GWP_TOWN);
01893
01894 if (!GenerateTownName(&townnameparts)) continue;
01895
01896 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++;
01897 } while (--total);
01898
01899 if (current_number != 0) return true;
01900
01901
01902
01903 if (GenerateTownName(&townnameparts) &&
01904 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01905 return true;
01906 }
01907
01908
01909 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01910 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
01911 }
01912
01913 return false;
01914 }
01915
01916
01923 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01924 {
01925 uint dist = DistanceSquare(tile, t->xy);
01926
01927 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01928
01929 HouseZonesBits smallest = HZB_TOWN_EDGE;
01930 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01931 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
01932 }
01933
01934 return smallest;
01935 }
01936
01947 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01948 {
01949 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01950
01951 assert(cc.Succeeded());
01952
01953 IncreaseBuildingCount(t, type);
01954 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01955 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01956
01957 MarkTileDirtyByTile(tile);
01958 }
01959
01960
01971 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01972 {
01973 BuildingFlags size = HouseSpec::Get(type)->building_flags;
01974
01975 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01976 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01977 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01978 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01979 }
01980
01981
01990 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01991 {
01992
01993 Slope slope = GetTileSlope(tile);
01994 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01995
01996
01997 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01998
01999
02000 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
02001
02002
02003 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
02004 }
02005
02006
02016 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
02017 {
02018 if (!CanBuildHouseHere(tile, town, noslope)) return false;
02019
02020
02021 if (GetTileMaxZ(tile) != z) return false;
02022
02023 return true;
02024 }
02025
02026
02036 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
02037 {
02038
02039 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02040
02041 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02042 tile += TileOffsByDiagDir(d);
02043 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02044 }
02045
02046 return true;
02047 }
02048
02049
02057 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02058 {
02059
02060 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02061
02062 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02063
02064 switch (t->layout) {
02065 case TL_2X2_GRID:
02066 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02067 break;
02068
02069 case TL_3X3_GRID:
02070 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02071 break;
02072
02073 default:
02074 break;
02075 }
02076
02077 return true;
02078 }
02079
02080
02088 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02089 {
02090
02091 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02092
02093
02094 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02095
02096 switch (t->layout) {
02097 case TL_2X2_GRID:
02098 grid_pos.x %= 3;
02099 grid_pos.y %= 3;
02100 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02101 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02102 break;
02103
02104 case TL_3X3_GRID:
02105 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02106 break;
02107
02108 default:
02109 break;
02110 }
02111
02112 return true;
02113 }
02114
02115
02125 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
02126 {
02127
02128
02129 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02130 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02131
02132 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02133 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02134 *tile = tile2;
02135 return true;
02136 }
02137
02138 return false;
02139 }
02140
02141
02150 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
02151 {
02152 TileIndex tile2 = *tile;
02153
02154 for (DiagDirection d = DIAGDIR_SE;; d++) {
02155 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02156 *tile = tile2;
02157 return true;
02158 }
02159 if (d == DIAGDIR_END) break;
02160 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
02161 }
02162
02163 return false;
02164 }
02165
02166
02173 static bool BuildTownHouse(Town *t, TileIndex tile)
02174 {
02175
02176 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02177
02178
02179 if (!CanBuildHouseHere(tile, t->index, false)) return false;
02180
02181 Slope slope = GetTileSlope(tile);
02182 int maxz = GetTileMaxZ(tile);
02183
02184
02185
02186 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02187
02188
02189 int land = _settings_game.game_creation.landscape;
02190 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
02191
02192 uint bitmask = (1 << rad) + (1 << (land + 12));
02193
02194
02195
02196
02197 HouseID houses[NUM_HOUSES];
02198 uint num = 0;
02199 uint probs[NUM_HOUSES];
02200 uint probability_max = 0;
02201
02202
02203 for (uint i = 0; i < NUM_HOUSES; i++) {
02204 const HouseSpec *hs = HouseSpec::Get(i);
02205
02206
02207 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02208
02209
02210 if (hs->class_id != HOUSE_NO_CLASS) {
02211
02212 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02213 } else {
02214
02215 if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
02216 }
02217
02218
02219 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02220 probability_max += cur_prob;
02221 probs[num] = cur_prob;
02222 houses[num++] = (HouseID)i;
02223 }
02224
02225 TileIndex baseTile = tile;
02226
02227 while (probability_max > 0) {
02228
02229
02230
02231
02232
02233 tile = baseTile;
02234
02235 uint r = RandomRange(probability_max);
02236 uint i;
02237 for (i = 0; i < num; i++) {
02238 if (probs[i] > r) break;
02239 r -= probs[i];
02240 }
02241
02242 HouseID house = houses[i];
02243 probability_max -= probs[i];
02244
02245
02246 num--;
02247 houses[i] = houses[num];
02248 probs[i] = probs[num];
02249
02250 const HouseSpec *hs = HouseSpec::Get(house);
02251
02252 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02253 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02254 continue;
02255 }
02256
02257 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02258
02259
02260 uint oneof = 0;
02261
02262 if (hs->building_flags & BUILDING_IS_CHURCH) {
02263 SetBit(oneof, TOWN_HAS_CHURCH);
02264 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02265 SetBit(oneof, TOWN_HAS_STADIUM);
02266 }
02267
02268 if (t->flags & oneof) continue;
02269
02270
02271 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02272 if (noslope && slope != SLOPE_FLAT) continue;
02273
02274 if (hs->building_flags & TILE_SIZE_2x2) {
02275 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02276 } else if (hs->building_flags & TILE_SIZE_2x1) {
02277 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02278 } else if (hs->building_flags & TILE_SIZE_1x2) {
02279 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02280 } else {
02281
02282 }
02283
02284 byte random_bits = Random();
02285
02286 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02287 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02288 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
02289 }
02290
02291
02292 t->cache.num_houses++;
02293
02294
02295 t->flags |= oneof;
02296
02297 byte construction_counter = 0;
02298 byte construction_stage = 0;
02299
02300 if (_generating_world || _game_mode == GM_EDITOR) {
02301 uint32 r = Random();
02302
02303 construction_stage = TOWN_HOUSE_COMPLETED;
02304 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02305
02306 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02307 ChangePopulation(t, hs->population);
02308 } else {
02309 construction_counter = GB(r, 2, 2);
02310 }
02311 }
02312
02313 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02314 UpdateTownRadius(t);
02315 UpdateTownCargoes(t, tile);
02316
02317 return true;
02318 }
02319
02320 return false;
02321 }
02322
02329 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02330 {
02331 assert(IsTileType(tile, MP_HOUSE));
02332 DecreaseBuildingCount(t, house);
02333 DoClearSquare(tile);
02334 DeleteAnimatedTile(tile);
02335
02336 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02337 }
02338
02346 TileIndexDiff GetHouseNorthPart(HouseID &house)
02347 {
02348 if (house >= 3) {
02349 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02350 house--;
02351 return TileDiffXY(-1, 0);
02352 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02353 house--;
02354 return TileDiffXY(0, -1);
02355 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02356 house -= 2;
02357 return TileDiffXY(-1, 0);
02358 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02359 house -= 3;
02360 return TileDiffXY(-1, -1);
02361 }
02362 }
02363 return 0;
02364 }
02365
02366 void ClearTownHouse(Town *t, TileIndex tile)
02367 {
02368 assert(IsTileType(tile, MP_HOUSE));
02369
02370 HouseID house = GetHouseType(tile);
02371
02372
02373 tile += GetHouseNorthPart(house);
02374
02375 const HouseSpec *hs = HouseSpec::Get(house);
02376
02377
02378 if (IsHouseCompleted(tile)) {
02379 ChangePopulation(t, -hs->population);
02380 }
02381
02382 t->cache.num_houses--;
02383
02384
02385 if (hs->building_flags & BUILDING_IS_CHURCH) {
02386 ClrBit(t->flags, TOWN_HAS_CHURCH);
02387 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02388 ClrBit(t->flags, TOWN_HAS_STADIUM);
02389 }
02390
02391
02392 uint eflags = hs->building_flags;
02393 DoClearTownHouseHelper(tile, t, house);
02394 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02395 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02396 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02397
02398 UpdateTownRadius(t);
02399
02400
02401 UpdateTownCargoes(t, tile);
02402 }
02403
02413 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02414 {
02415 Town *t = Town::GetIfValid(p1);
02416 if (t == NULL) return CMD_ERROR;
02417
02418 bool reset = StrEmpty(text);
02419
02420 if (!reset) {
02421 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02422 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02423 }
02424
02425 if (flags & DC_EXEC) {
02426 free(t->name);
02427 t->name = reset ? NULL : strdup(text);
02428
02429 t->UpdateVirtCoord();
02430 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02431 UpdateAllStationVirtCoords();
02432 }
02433 return CommandCost();
02434 }
02435
02441 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
02442 {
02443 const CargoSpec *cs;
02444 FOR_ALL_CARGOSPECS(cs) {
02445 if (cs->town_effect == effect) return cs;
02446 }
02447 return NULL;
02448 }
02449
02450 static void UpdateTownGrowRate(Town *t);
02451
02463 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02464 {
02465 if (_current_company != OWNER_DEITY) return CMD_ERROR;
02466
02467 TownEffect te = (TownEffect)GB(p1, 16, 8);
02468 if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
02469
02470 uint16 index = GB(p1, 0, 16);
02471 Town *t = Town::GetIfValid(index);
02472 if (t == NULL) return CMD_ERROR;
02473
02474
02475 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
02476 if (cargo == NULL) return CMD_ERROR;
02477
02478 if (flags & DC_EXEC) {
02479 t->goal[te] = p2;
02480 UpdateTownGrowRate(t);
02481 InvalidateWindowData(WC_TOWN_VIEW, index);
02482 }
02483
02484 return CommandCost();
02485 }
02486
02496 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02497 {
02498 if (_current_company != OWNER_DEITY) return CMD_ERROR;
02499 Town *t = Town::GetIfValid(p1);
02500 if (t == NULL) return CMD_ERROR;
02501
02502 if (flags & DC_EXEC) {
02503 free(t->text);
02504 t->text = StrEmpty(text) ? NULL : strdup(text);
02505 InvalidateWindowData(WC_TOWN_VIEW, p1);
02506 }
02507
02508 return CommandCost();
02509 }
02510
02520 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02521 {
02522 if (_current_company != OWNER_DEITY) return CMD_ERROR;
02523 if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
02524 if (GB(p2, 16, 16) != 0) return CMD_ERROR;
02525
02526 Town *t = Town::GetIfValid(p1);
02527 if (t == NULL) return CMD_ERROR;
02528
02529 if (flags & DC_EXEC) {
02530 if (p2 == 0) {
02531
02532 t->growth_rate = 0;
02533 } else {
02534 uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
02535 if (t->grow_counter >= old_rate) {
02536
02537 t->grow_counter = p2;
02538 } else {
02539
02540 t->grow_counter = t->grow_counter * p2 / old_rate;
02541 }
02542 t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
02543 }
02544 UpdateTownGrowRate(t);
02545 InvalidateWindowData(WC_TOWN_VIEW, p1);
02546 }
02547
02548 return CommandCost();
02549 }
02550
02560 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02561 {
02562 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
02563 Town *t = Town::GetIfValid(p1);
02564 if (t == NULL) return CMD_ERROR;
02565
02566 if (flags & DC_EXEC) {
02567
02568 if (p2 == 0) {
02569 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
02570 t->cache.num_houses += amount;
02571 UpdateTownRadius(t);
02572
02573 uint n = amount * 10;
02574 do GrowTown(t); while (--n);
02575
02576 t->cache.num_houses -= amount;
02577 } else {
02578 for (; p2 > 0; p2--) {
02579
02580 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
02581 }
02582 }
02583 UpdateTownRadius(t);
02584
02585 UpdateTownMaxPass(t);
02586 }
02587
02588 return CommandCost();
02589 }
02590
02600 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02601 {
02602 if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
02603 Town *t = Town::GetIfValid(p1);
02604 if (t == NULL) return CMD_ERROR;
02605
02606
02607 const Station *st;
02608 FOR_ALL_STATIONS(st) {
02609 if (st->town == t) {
02610
02611 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02612
02613 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02614 if (ret.Failed()) return ret;
02615 }
02616 }
02617
02618
02619 const Depot *d;
02620 FOR_ALL_DEPOTS(d) {
02621 if (d->town == t) return CMD_ERROR;
02622 }
02623
02624
02625 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02626 bool try_clear = false;
02627 switch (GetTileType(tile)) {
02628 case MP_ROAD:
02629 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02630 break;
02631
02632 case MP_TUNNELBRIDGE:
02633 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02634 break;
02635
02636 case MP_HOUSE:
02637 try_clear = GetTownIndex(tile) == t->index;
02638 break;
02639
02640 case MP_INDUSTRY:
02641 try_clear = Industry::GetByTile(tile)->town == t;
02642 break;
02643
02644 case MP_OBJECT:
02645 if (Town::GetNumItems() == 1) {
02646
02647 try_clear = true;
02648 } else {
02649 Object *o = Object::GetByTile(tile);
02650 if (o->town == t) {
02651 if (o->type == OBJECT_STATUE) {
02652
02653 try_clear = true;
02654 } else {
02655
02656 if (flags & DC_EXEC) o->town = NULL;
02657 }
02658 }
02659 }
02660 break;
02661
02662 default:
02663 break;
02664 }
02665 if (try_clear) {
02666 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02667 if (ret.Failed()) return ret;
02668 }
02669 }
02670
02671
02672 if (flags & DC_EXEC) delete t;
02673
02674 return CommandCost();
02675 }
02676
02681 const byte _town_action_costs[TACT_COUNT] = {
02682 2, 4, 9, 35, 48, 53, 117, 175
02683 };
02684
02685 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02686 {
02687 if (flags & DC_EXEC) {
02688 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02689 }
02690 return CommandCost();
02691 }
02692
02693 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02694 {
02695 if (flags & DC_EXEC) {
02696 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02697 }
02698 return CommandCost();
02699 }
02700
02701 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02702 {
02703 if (flags & DC_EXEC) {
02704 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02705 }
02706 return CommandCost();
02707 }
02708
02709 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02710 {
02711
02712 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02713
02714 if (flags & DC_EXEC) {
02715 t->road_build_months = 6;
02716
02717 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02718 SetDParam(0, _current_company);
02719 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02720
02721 char *cn = strdup(company_name);
02722 SetDParam(0, t->index);
02723 SetDParamStr(1, cn);
02724
02725 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02726 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02727 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02728 }
02729 return CommandCost();
02730 }
02731
02737 static bool TryClearTile(TileIndex tile)
02738 {
02739 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02740 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02741 cur_company.Restore();
02742 return r.Succeeded();
02743 }
02744
02746 struct StatueBuildSearchData {
02747 TileIndex best_position;
02748 int tile_count;
02749
02750 StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
02751 };
02752
02759 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02760 {
02761 static const int STATUE_NUMBER_INNER_TILES = 25;
02762
02763 StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
02764 statue_data->tile_count++;
02765
02766
02767 if (IsSteepSlope(GetTileSlope(tile))) return false;
02768
02769 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02770
02771
02772 if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
02773 statue_data->best_position = tile;
02774 return true;
02775 }
02776
02777 bool house = IsTileType(tile, MP_HOUSE);
02778
02779
02780 if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
02781
02782 if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
02783 statue_data->best_position = tile;
02784 }
02785
02786
02787 return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
02788 }
02789
02790
02791 statue_data->best_position = tile;
02792 return house && TryClearTile(tile);
02793 }
02794
02802 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02803 {
02804 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02805
02806 TileIndex tile = t->xy;
02807 StatueBuildSearchData statue_data(INVALID_TILE, 0);
02808 if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02809
02810 if (flags & DC_EXEC) {
02811 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02812 DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02813 cur_company.Restore();
02814 BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
02815 SetBit(t->statues, _current_company);
02816 MarkTileDirtyByTile(statue_data.best_position);
02817 }
02818 return CommandCost();
02819 }
02820
02821 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02822 {
02823
02824 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
02825
02826 if (flags & DC_EXEC) {
02827
02828 t->grow_counter = 1;
02829
02830 t->fund_buildings_months = 3;
02831
02832
02833 UpdateTownGrowRate(t);
02834
02835 SetWindowDirty(WC_TOWN_VIEW, t->index);
02836 }
02837 return CommandCost();
02838 }
02839
02840 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02841 {
02842
02843 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02844
02845 if (flags & DC_EXEC) {
02846 t->exclusive_counter = 12;
02847 t->exclusivity = _current_company;
02848
02849 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02850
02851 SetWindowClassesDirty(WC_STATION_VIEW);
02852
02853
02854 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
02855 cni->FillData(Company::Get(_current_company));
02856 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
02857 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
02858 SetDParam(2, t->index);
02859 SetDParamStr(3, cni->company_name);
02860 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
02861 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02862 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
02863 }
02864 return CommandCost();
02865 }
02866
02867 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02868 {
02869 if (flags & DC_EXEC) {
02870 if (Chance16(1, 14)) {
02871
02872 t->unwanted[_current_company] = 6;
02873
02874
02875 Station *st;
02876 FOR_ALL_STATIONS(st) {
02877 if (st->town == t && st->owner == _current_company) {
02878 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02879 }
02880 }
02881
02882
02883
02884 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
02885
02886
02887
02888
02889
02890 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02891 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02892 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02893 }
02894 } else {
02895 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02896 }
02897 }
02898 return CommandCost();
02899 }
02900
02901 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02902 static TownActionProc * const _town_action_proc[] = {
02903 TownActionAdvertiseSmall,
02904 TownActionAdvertiseMedium,
02905 TownActionAdvertiseLarge,
02906 TownActionRoadRebuild,
02907 TownActionBuildStatue,
02908 TownActionFundBuildings,
02909 TownActionBuyRights,
02910 TownActionBribe
02911 };
02912
02920 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02921 {
02922 int num = 0;
02923 TownActions buttons = TACT_NONE;
02924
02925
02926 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02927
02928
02929 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02930
02931
02932
02933 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02934 const TownActions cur = (TownActions)(1 << i);
02935
02936
02937 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02938
02939
02940 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02941
02942
02943 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
02944
02945
02946 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02947
02948
02949 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02950
02951 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02952 buttons |= cur;
02953 num++;
02954 }
02955 }
02956 }
02957
02958 if (nump != NULL) *nump = num;
02959 return buttons;
02960 }
02961
02973 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02974 {
02975 Town *t = Town::GetIfValid(p1);
02976 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02977
02978 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02979
02980 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02981
02982 CommandCost ret = _town_action_proc[p2](t, flags);
02983 if (ret.Failed()) return ret;
02984
02985 if (flags & DC_EXEC) {
02986 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02987 }
02988
02989 return cost;
02990 }
02991
02992 static void UpdateTownRating(Town *t)
02993 {
02994
02995 const Company *c;
02996 FOR_ALL_COMPANIES(c) {
02997 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02998 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02999 }
03000 }
03001
03002 const Station *st;
03003 FOR_ALL_STATIONS(st) {
03004 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
03005 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
03006 if (Company::IsValidID(st->owner)) {
03007 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
03008 t->ratings[st->owner] = min(new_rating, INT16_MAX);
03009 }
03010 } else {
03011 if (Company::IsValidID(st->owner)) {
03012 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
03013 t->ratings[st->owner] = max(new_rating, INT16_MIN);
03014 }
03015 }
03016 }
03017 }
03018
03019
03020 for (uint i = 0; i < MAX_COMPANIES; i++) {
03021 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
03022 }
03023
03024 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03025 }
03026
03027 static void UpdateTownGrowRate(Town *t)
03028 {
03029 ClrBit(t->flags, TOWN_IS_GROWING);
03030 SetWindowDirty(WC_TOWN_VIEW, t->index);
03031
03032 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
03033
03034 if (t->fund_buildings_months == 0) {
03035
03036 for (int i = TE_BEGIN; i < TE_END; i++) {
03037 switch (t->goal[i]) {
03038 case TOWN_GROWTH_WINTER:
03039 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
03040 break;
03041 case TOWN_GROWTH_DESERT:
03042 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
03043 break;
03044 default:
03045 if (t->goal[i] > t->received[i].old_act) return;
03046 break;
03047 }
03048 }
03049 }
03050
03051 if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
03052 if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
03053 SetWindowDirty(WC_TOWN_VIEW, t->index);
03054 return;
03055 }
03056
03061 static const uint16 _grow_count_values[2][6] = {
03062 { 120, 120, 120, 100, 80, 60 },
03063 { 320, 420, 300, 220, 160, 100 }
03064 };
03065
03066 int n = 0;
03067
03068 const Station *st;
03069 FOR_ALL_STATIONS(st) {
03070 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
03071 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
03072 n++;
03073 }
03074 }
03075 }
03076
03077 uint16 m;
03078
03079 if (t->fund_buildings_months != 0) {
03080 m = _grow_count_values[0][min(n, 5)];
03081 } else {
03082 m = _grow_count_values[1][min(n, 5)];
03083 if (n == 0 && !Chance16(1, 12)) return;
03084 }
03085
03086
03087
03088 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
03089
03090 m >>= growth_multiplier;
03091 if (t->larger_town) m /= 2;
03092
03093 t->growth_rate = m / (t->cache.num_houses / 50 + 1);
03094 if (m <= t->grow_counter) {
03095 t->grow_counter = m;
03096 }
03097
03098 SetBit(t->flags, TOWN_IS_GROWING);
03099 SetWindowDirty(WC_TOWN_VIEW, t->index);
03100 }
03101
03102 static void UpdateTownAmounts(Town *t)
03103 {
03104 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
03105 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
03106 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
03107
03108 SetWindowDirty(WC_TOWN_VIEW, t->index);
03109 }
03110
03111 static void UpdateTownUnwanted(Town *t)
03112 {
03113 const Company *c;
03114
03115 FOR_ALL_COMPANIES(c) {
03116 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
03117 }
03118 }
03119
03126 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
03127 {
03128 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
03129
03130 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
03131 if (t == NULL) return CommandCost();
03132
03133 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
03134
03135 SetDParam(0, t->index);
03136 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03137 }
03138
03147 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
03148 {
03149 Town *t;
03150 uint best = threshold;
03151 Town *best_town = NULL;
03152
03153 FOR_ALL_TOWNS(t) {
03154 uint dist = DistanceManhattan(tile, t->xy);
03155 if (dist < best) {
03156 best = dist;
03157 best_town = t;
03158 }
03159 }
03160
03161 return best_town;
03162 }
03163
03172 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
03173 {
03174 switch (GetTileType(tile)) {
03175 case MP_ROAD:
03176 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
03177
03178 if (!HasTownOwnedRoad(tile)) {
03179 TownID tid = GetTownIndex(tile);
03180
03181 if (tid == (TownID)INVALID_TOWN) {
03182
03183 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03184 assert(Town::GetNumItems() == 0);
03185 return NULL;
03186 }
03187
03188 assert(Town::IsValidID(tid));
03189 Town *town = Town::Get(tid);
03190
03191 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03192
03193 return town;
03194 }
03195
03196
03197 case MP_HOUSE:
03198 return Town::GetByTile(tile);
03199
03200 default:
03201 return CalcClosestTownFromTile(tile, threshold);
03202 }
03203 }
03204
03205 static bool _town_rating_test = false;
03206 static SmallMap<const Town *, int, 4> _town_test_ratings;
03207
03213 void SetTownRatingTestMode(bool mode)
03214 {
03215 static int ref_count = 0;
03216 if (mode) {
03217 if (ref_count == 0) {
03218 _town_test_ratings.Clear();
03219 }
03220 ref_count++;
03221 } else {
03222 assert(ref_count > 0);
03223 ref_count--;
03224 }
03225 _town_rating_test = !(ref_count == 0);
03226 }
03227
03233 static int GetRating(const Town *t)
03234 {
03235 if (_town_rating_test) {
03236 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03237 if (it != _town_test_ratings.End()) {
03238 return it->second;
03239 }
03240 }
03241 return t->ratings[_current_company];
03242 }
03243
03251 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03252 {
03253
03254 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03255 !Company::IsValidID(_current_company) ||
03256 (_cheats.magic_bulldozer.value && add < 0)) {
03257 return;
03258 }
03259
03260 int rating = GetRating(t);
03261 if (add < 0) {
03262 if (rating > max) {
03263 rating += add;
03264 if (rating < max) rating = max;
03265 }
03266 } else {
03267 if (rating < max) {
03268 rating += add;
03269 if (rating > max) rating = max;
03270 }
03271 }
03272 if (_town_rating_test) {
03273 _town_test_ratings[t] = rating;
03274 } else {
03275 SetBit(t->have_ratings, _current_company);
03276 t->ratings[_current_company] = rating;
03277 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03278 }
03279 }
03280
03288 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03289 {
03290
03291 if (t == NULL || !Company::IsValidID(_current_company) ||
03292 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03293 return CommandCost();
03294 }
03295
03296
03297 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03298
03299 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE},
03300 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL},
03301 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE},
03302 };
03303
03304
03305
03306
03307
03308 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03309
03310 if (GetRating(t) < needed) {
03311 SetDParam(0, t->index);
03312 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03313 }
03314
03315 return CommandCost();
03316 }
03317
03318 void TownsMonthlyLoop()
03319 {
03320 Town *t;
03321
03322 FOR_ALL_TOWNS(t) {
03323 if (t->road_build_months != 0) t->road_build_months--;
03324
03325 if (t->exclusive_counter != 0) {
03326 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03327 }
03328
03329 UpdateTownAmounts(t);
03330 UpdateTownRating(t);
03331 UpdateTownGrowRate(t);
03332 UpdateTownUnwanted(t);
03333 UpdateTownCargoes(t);
03334 }
03335
03336 UpdateTownCargoBitmap();
03337 }
03338
03339 void TownsYearlyLoop()
03340 {
03341
03342 for (TileIndex t = 0; t < MapSize(); t++) {
03343 if (!IsTileType(t, MP_HOUSE)) continue;
03344 IncrementHouseAge(t);
03345 }
03346 }
03347
03348 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03349 {
03350 if (AutoslopeEnabled()) {
03351 HouseID house = GetHouseType(tile);
03352 GetHouseNorthPart(house);
03353 const HouseSpec *hs = HouseSpec::Get(house);
03354
03355
03356 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03357 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03358 bool allow_terraform = true;
03359
03360
03361 house = GetHouseType(tile);
03362 hs = HouseSpec::Get(house);
03363 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03364
03365 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03366 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
03367 }
03368
03369 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03370 }
03371 }
03372
03373 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03374 }
03375
03377 extern const TileTypeProcs _tile_type_town_procs = {
03378 DrawTile_Town,
03379 GetSlopePixelZ_Town,
03380 ClearTile_Town,
03381 AddAcceptedCargo_Town,
03382 GetTileDesc_Town,
03383 GetTileTrackStatus_Town,
03384 NULL,
03385 AnimateTile_Town,
03386 TileLoop_Town,
03387 ChangeTileOwner_Town,
03388 AddProducedCargo_Town,
03389 NULL,
03390 GetFoundation_Town,
03391 TerraformTile_Town,
03392 };
03393
03394
03395 HouseSpec _house_specs[NUM_HOUSES];
03396
03397 void ResetHouses()
03398 {
03399 memset(&_house_specs, 0, sizeof(_house_specs));
03400 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03401
03402
03403 _house_mngr.ResetOverride();
03404 }