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 "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 "animated_tile_func.h"
00038 #include "date_func.h"
00039 #include "subsidy_func.h"
00040 #include "core/pool_func.hpp"
00041 #include "town.h"
00042 #include "townname_func.h"
00043 #include "townname_type.h"
00044 #include "core/random_func.hpp"
00045 #include "core/backup_type.hpp"
00046 #include "depot_base.h"
00047 #include "object_map.h"
00048 #include "object_base.h"
00049 #include "ai/ai.hpp"
00050
00051 #include "table/strings.h"
00052 #include "table/town_land.h"
00053
00054 TownID _new_town_id;
00055 uint32 _town_cargos_accepted;
00056
00057
00058 TownPool _town_pool("Town");
00059 INSTANTIATE_POOL_METHODS(Town)
00060
00061 Town::~Town()
00062 {
00063 free(this->name);
00064
00065 if (CleaningPool()) return;
00066
00067
00068
00069 DeleteWindowById(WC_TOWN_VIEW, this->index);
00070
00071
00072 const Industry *i;
00073 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
00074
00075
00076 const Object *o;
00077 FOR_ALL_OBJECTS(o) assert(o->town != this);
00078
00079
00080 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
00081 switch (GetTileType(tile)) {
00082 case MP_HOUSE:
00083 assert(GetTownIndex(tile) != this->index);
00084 break;
00085
00086 case MP_ROAD:
00087 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
00088 break;
00089
00090 case MP_TUNNELBRIDGE:
00091 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
00092 break;
00093
00094 default:
00095 break;
00096 }
00097 }
00098
00099
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->population);
00359 this->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->population += mod;
00383 SetWindowDirty(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->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_FUNDED) &&
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 UpdateTownCargos(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 UpdateTownCargos(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 UpdateTownCargos(t, tile, false);
00739 }
00740 }
00741
00742
00743 UpdateTownCargoTotal(t);
00744 }
00745
00747 void UpdateTownCargoBitmap()
00748 {
00749 Town *town;
00750 _town_cargos_accepted = 0;
00751
00752 FOR_ALL_TOWNS(town) {
00753 _town_cargos_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_FUNDED)) {
00762 int i = t->grow_counter - 1;
00763 if (i < 0) {
00764 if (GrowTown(t)) {
00765 i = t->growth_rate;
00766 } else {
00767 i = 0;
00768 }
00769 }
00770 t->grow_counter = i;
00771 }
00772
00773 UpdateTownRadius(t);
00774 }
00775
00776 void OnTick_Town()
00777 {
00778 if (_game_mode == GM_EDITOR) return;
00779
00780 Town *t;
00781 FOR_ALL_TOWNS(t) {
00782
00783 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
00784 TownTickHandler(t);
00785 }
00786 }
00787 }
00788
00797 static RoadBits GetTownRoadBits(TileIndex tile)
00798 {
00799 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
00800
00801 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
00802 }
00803
00814 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
00815 {
00816 if (!IsValidTile(tile)) return false;
00817
00818
00819 const TileIndexDiff tid_lt[3] = {
00820 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
00821 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
00822 TileOffsByDiagDir(ReverseDiagDir(dir)),
00823 };
00824
00825 dist_multi = (dist_multi + 1) * 4;
00826 for (uint pos = 4; pos < dist_multi; pos++) {
00827
00828 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
00829
00830
00831 if (pos & 2) cur += tid_lt[2];
00832
00833
00834 if (IsValidTile(tile + cur) &&
00835 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
00836 }
00837 return false;
00838 }
00839
00848 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
00849 {
00850 if (DistanceFromEdge(tile) == 0) return false;
00851
00852
00853 if (GetTownRoadBits(tile) == ROAD_NONE) {
00854
00855
00856
00857 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
00858 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
00859 return false;
00860 }
00861 }
00862
00863 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
00864 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
00865 if (cur_slope == SLOPE_FLAT) return ret;
00866
00867
00868
00869 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
00870 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
00871 if (Chance16(1, 8)) {
00872 CommandCost res = CMD_ERROR;
00873 if (!_generating_world && Chance16(1, 10)) {
00874
00875 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
00876 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00877 }
00878 if (res.Failed() && Chance16(1, 3)) {
00879
00880 return ret;
00881 }
00882 }
00883 return false;
00884 }
00885 return ret;
00886 }
00887
00888 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
00889 {
00890 assert(tile < MapSize());
00891
00892 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
00893 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
00894 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
00895 return true;
00896 }
00897
00898 static void LevelTownLand(TileIndex tile)
00899 {
00900 assert(tile < MapSize());
00901
00902
00903 if (IsTileType(tile, MP_HOUSE)) return;
00904 Slope tileh = GetTileSlope(tile);
00905 if (tileh == SLOPE_FLAT) return;
00906
00907
00908 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
00909 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
00910 }
00911 }
00912
00922 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
00923 {
00924
00925 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
00926 RoadBits rcmd = ROAD_NONE;
00927
00928 switch (t->layout) {
00929 default: NOT_REACHED();
00930
00931 case TL_2X2_GRID:
00932 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
00933 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
00934 break;
00935
00936 case TL_3X3_GRID:
00937 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
00938 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
00939 break;
00940 }
00941
00942
00943 if (rcmd != ROAD_ALL) return rcmd;
00944
00945 RoadBits rb_template;
00946
00947 switch (GetTileSlope(tile)) {
00948 default: rb_template = ROAD_ALL; break;
00949 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
00950 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
00951 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
00952 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
00953 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
00954 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
00955 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
00956 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
00957 case SLOPE_STEEP_W:
00958 case SLOPE_STEEP_S:
00959 case SLOPE_STEEP_E:
00960 case SLOPE_STEEP_N:
00961 rb_template = ROAD_NONE;
00962 break;
00963 }
00964
00965
00966 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
00967
00968 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
00969 }
00970
00981 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
00982 {
00983
00984 if (DistanceFromEdge(tile) == 0) return false;
00985
00986 uint counter = 0;
00987
00988
00989 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00990
00991
00992
00993 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
00994 case MP_HOUSE:
00995 case MP_VOID:
00996 counter++;
00997 break;
00998
00999 default:
01000 break;
01001 }
01002
01003
01004 if (counter >= 3) {
01005 if (BuildTownHouse(t, tile)) {
01006 _grow_town_result = GROWTH_SUCCEED;
01007 return true;
01008 }
01009 return false;
01010 }
01011 }
01012 return false;
01013 }
01014
01023 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
01024 {
01025 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
01026 _grow_town_result = GROWTH_SUCCEED;
01027 return true;
01028 }
01029 return false;
01030 }
01031
01042 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
01043 {
01044 assert(bridge_dir < DIAGDIR_END);
01045
01046 const Slope slope = GetTileSlope(tile);
01047
01048
01049
01050
01051 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
01052
01053
01054 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
01055
01056
01057 uint8 bridge_length = 0;
01058 TileIndex bridge_tile = tile;
01059
01060 const int delta = TileOffsByDiagDir(bridge_dir);
01061
01062 if (slope == SLOPE_FLAT) {
01063
01064 do {
01065 if (bridge_length++ >= 4) {
01066
01067 return false;
01068 }
01069 bridge_tile += delta;
01070 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
01071 } else {
01072 do {
01073 if (bridge_length++ >= 11) {
01074
01075 return false;
01076 }
01077 bridge_tile += delta;
01078 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
01079 }
01080
01081
01082 if (bridge_length == 1) return false;
01083
01084 for (uint8 times = 0; times <= 22; times++) {
01085 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
01086
01087
01088 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
01089 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
01090 _grow_town_result = GROWTH_SUCCEED;
01091 return true;
01092 }
01093 }
01094
01095 return false;
01096 }
01097
01115 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
01116 {
01117 RoadBits rcmd = ROAD_NONE;
01118 TileIndex tile = *tile_ptr;
01119
01120 assert(tile < MapSize());
01121
01122 if (cur_rb == ROAD_NONE) {
01123
01124
01125 _grow_town_result = GROWTH_SEARCH_STOPPED;
01126
01127 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01128 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
01129
01130
01131 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
01132
01133
01134 switch (t1->layout) {
01135 default: NOT_REACHED();
01136
01137 case TL_3X3_GRID:
01138 case TL_2X2_GRID:
01139 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01140 if (rcmd == ROAD_NONE) return;
01141 break;
01142
01143 case TL_BETTER_ROADS:
01144 case TL_ORIGINAL:
01145 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
01146
01147 DiagDirection source_dir = ReverseDiagDir(target_dir);
01148
01149 if (Chance16(1, 4)) {
01150
01151 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
01152 }
01153
01154 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
01155
01156
01157 if (target_dir != ReverseDiagDir(source_dir)) return;
01158
01159
01160 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
01161 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
01162 return;
01163 }
01164
01165
01166
01167 }
01168
01169 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
01170 break;
01171 }
01172
01173 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
01174
01175
01176
01177 _grow_town_result = GROWTH_SEARCH_STOPPED;
01178
01179 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
01180
01181 switch (t1->layout) {
01182 default: NOT_REACHED();
01183
01184 case TL_3X3_GRID:
01185 case TL_2X2_GRID:
01186 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
01187 break;
01188
01189 case TL_BETTER_ROADS:
01190 case TL_ORIGINAL:
01191 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
01192 break;
01193 }
01194 } else {
01195 bool allow_house = true;
01196
01197
01198
01199 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01200 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
01201 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
01202 }
01203 return;
01204 }
01205
01206
01207
01208 target_dir = RandomDiagDir();
01209 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
01210
01211
01212 TileIndex house_tile = TileAddByDiagDir(tile, target_dir);
01213
01214
01215 if (HasTileWaterGround(house_tile)) return;
01216
01217 if (!IsValidTile(house_tile)) return;
01218
01219 if (_settings_game.economy.allow_town_roads || _generating_world) {
01220 switch (t1->layout) {
01221 default: NOT_REACHED();
01222
01223 case TL_3X3_GRID:
01224 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01225
01226
01227 case TL_2X2_GRID:
01228 rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
01229 allow_house = (rcmd == ROAD_NONE);
01230 break;
01231
01232 case TL_BETTER_ROADS:
01233 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
01234
01235
01236 case TL_ORIGINAL:
01237
01238
01239 rcmd = DiagDirToRoadBits(target_dir);
01240 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
01241 break;
01242 }
01243 }
01244
01245 if (allow_house) {
01246
01247 if (!IsTileType(house_tile, MP_HOUSE)) {
01248
01249 if (Chance16(1, 6)) LevelTownLand(house_tile);
01250
01251
01252
01253 if (BuildTownHouse(t1, house_tile)) {
01254 _grow_town_result = GROWTH_SUCCEED;
01255 }
01256 }
01257 return;
01258 }
01259
01260 _grow_town_result = GROWTH_SEARCH_STOPPED;
01261 }
01262
01263
01264 if (HasTileWaterGround(tile)) return;
01265
01266
01267 rcmd = CleanUpRoadBits(tile, rcmd);
01268 if (rcmd == ROAD_NONE) return;
01269
01270
01271
01272
01273 if (GrowTownWithBridge(t1, tile, target_dir)) return;
01274
01275 GrowTownWithRoad(t1, tile, rcmd);
01276 }
01277
01284 static int GrowTownAtRoad(Town *t, TileIndex tile)
01285 {
01286
01287
01288
01289 DiagDirection target_dir = DIAGDIR_END;
01290
01291 assert(tile < MapSize());
01292
01293
01294
01295
01296 switch (t->layout) {
01297 case TL_BETTER_ROADS:
01298 _grow_town_result = 10 + t->num_houses * 2 / 9;
01299 break;
01300
01301 case TL_3X3_GRID:
01302 case TL_2X2_GRID:
01303 _grow_town_result = 10 + t->num_houses * 1 / 9;
01304 break;
01305
01306 default:
01307 _grow_town_result = 10 + t->num_houses * 4 / 9;
01308 break;
01309 }
01310
01311 do {
01312 RoadBits cur_rb = GetTownRoadBits(tile);
01313
01314
01315 GrowTownInTile(&tile, cur_rb, target_dir, t);
01316
01317
01318
01319 cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
01320 if (cur_rb == ROAD_NONE) {
01321 return _grow_town_result;
01322 }
01323
01324 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
01325
01326 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
01327 } else {
01328
01329
01330 do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
01331 }
01332 tile = TileAddByDiagDir(tile, target_dir);
01333
01334 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
01335
01336 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
01337 _grow_town_result = GROWTH_SUCCEED;
01338 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
01339
01340
01341 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
01342 SetTownIndex(tile, t->index);
01343 }
01344 }
01345
01346
01347 } while (--_grow_town_result >= 0);
01348
01349 return (_grow_town_result == -2);
01350 }
01351
01359 static RoadBits GenRandomRoadBits()
01360 {
01361 uint32 r = Random();
01362 uint a = GB(r, 0, 2);
01363 uint b = GB(r, 8, 2);
01364 if (a == b) b ^= 2;
01365 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
01366 }
01367
01373 static bool GrowTown(Town *t)
01374 {
01375 static const TileIndexDiffC _town_coord_mod[] = {
01376 {-1, 0},
01377 { 1, 1},
01378 { 1, -1},
01379 {-1, -1},
01380 {-1, 0},
01381 { 0, 2},
01382 { 2, 0},
01383 { 0, -2},
01384 {-1, -1},
01385 {-2, 2},
01386 { 2, 2},
01387 { 2, -2},
01388 { 0, 0}
01389 };
01390
01391
01392 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
01393
01394 TileIndex tile = t->xy;
01395
01396
01397 const TileIndexDiffC *ptr;
01398 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01399 if (GetTownRoadBits(tile) != ROAD_NONE) {
01400 int r = GrowTownAtRoad(t, tile);
01401 cur_company.Restore();
01402 return r != 0;
01403 }
01404 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01405 }
01406
01407
01408
01409 if (_settings_game.economy.allow_town_roads || _generating_world) {
01410 tile = t->xy;
01411 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
01412
01413 if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile) == SLOPE_FLAT) {
01414 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
01415 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
01416 cur_company.Restore();
01417 return true;
01418 }
01419 }
01420 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
01421 }
01422 }
01423
01424 cur_company.Restore();
01425 return false;
01426 }
01427
01428 void UpdateTownRadius(Town *t)
01429 {
01430 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
01431 { 4, 0, 0, 0, 0},
01432 { 16, 0, 0, 0, 0},
01433 { 25, 0, 0, 0, 0},
01434 { 36, 0, 0, 0, 0},
01435 { 49, 0, 4, 0, 0},
01436 { 64, 0, 4, 0, 0},
01437 { 64, 0, 9, 0, 1},
01438 { 64, 0, 9, 0, 4},
01439 { 64, 0, 16, 0, 4},
01440 { 81, 0, 16, 0, 4},
01441 { 81, 0, 16, 0, 4},
01442 { 81, 0, 25, 0, 9},
01443 { 81, 36, 25, 0, 9},
01444 { 81, 36, 25, 16, 9},
01445 { 81, 49, 0, 25, 9},
01446 { 81, 64, 0, 25, 9},
01447 { 81, 64, 0, 36, 9},
01448 { 81, 64, 0, 36, 16},
01449 {100, 81, 0, 49, 16},
01450 {100, 81, 0, 49, 25},
01451 {121, 81, 0, 49, 25},
01452 {121, 81, 0, 49, 25},
01453 {121, 81, 0, 49, 36},
01454 };
01455
01456 if (t->num_houses < 92) {
01457 memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
01458 } else {
01459 int mass = t->num_houses / 8;
01460
01461
01462
01463 t->squared_town_zone_radius[0] = mass * 15 - 40;
01464 t->squared_town_zone_radius[1] = mass * 9 - 15;
01465 t->squared_town_zone_radius[2] = 0;
01466 t->squared_town_zone_radius[3] = mass * 5 - 5;
01467 t->squared_town_zone_radius[4] = mass * 3 + 5;
01468 }
01469 }
01470
01471 void UpdateTownMaxPass(Town *t)
01472 {
01473 t->supplied[CT_PASSENGERS].old_max = t->population >> 3;
01474 t->supplied[CT_MAIL].old_max = t->population >> 4;
01475 }
01476
01488 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
01489 {
01490 t->xy = tile;
01491 t->num_houses = 0;
01492 t->time_until_rebuild = 10;
01493 UpdateTownRadius(t);
01494 t->flags = 0;
01495 t->population = 0;
01496 t->grow_counter = 0;
01497 t->growth_rate = 250;
01498
01499
01500 switch (_settings_game.game_creation.landscape) {
01501 case LT_ARCTIC:
01502 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
01503 break;
01504
01505 case LT_TROPIC:
01506 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
01507 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
01508 break;
01509 }
01510
01511 t->fund_buildings_months = 0;
01512
01513 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01514
01515 t->have_ratings = 0;
01516 t->exclusivity = INVALID_COMPANY;
01517 t->exclusive_counter = 0;
01518 t->statues = 0;
01519
01520 extern int _nb_orig_names;
01521 if (_settings_game.game_creation.town_name < _nb_orig_names) {
01522
01523 t->townnamegrfid = 0;
01524 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
01525 } else {
01526
01527 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
01528 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
01529 }
01530 t->townnameparts = townnameparts;
01531
01532 t->UpdateVirtCoord();
01533 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
01534
01535 t->InitializeLayout(layout);
01536
01537 t->larger_town = city;
01538
01539 int x = (int)size * 16 + 3;
01540 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
01541
01542 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
01543
01544 t->num_houses += x;
01545 UpdateTownRadius(t);
01546
01547 int i = x * 4;
01548 do {
01549 GrowTown(t);
01550 } while (--i);
01551
01552 t->num_houses -= x;
01553 UpdateTownRadius(t);
01554 UpdateTownMaxPass(t);
01555 UpdateAirportsNoise();
01556 }
01557
01563 static CommandCost TownCanBePlacedHere(TileIndex tile)
01564 {
01565
01566 if (DistanceFromEdge(tile) < 12) {
01567 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
01568 }
01569
01570
01571 if (IsCloseToTown(tile, 20)) {
01572 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
01573 }
01574
01575
01576 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile) != SLOPE_FLAT) {
01577 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
01578 }
01579
01580 return CommandCost(EXPENSES_OTHER);
01581 }
01582
01588 static bool IsUniqueTownName(const char *name)
01589 {
01590 const Town *t;
01591
01592 FOR_ALL_TOWNS(t) {
01593 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
01594 }
01595
01596 return true;
01597 }
01598
01611 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01612 {
01613 TownSize size = Extract<TownSize, 0, 2>(p1);
01614 bool city = HasBit(p1, 2);
01615 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
01616 TownNameParams par(_settings_game.game_creation.town_name);
01617 bool random = HasBit(p1, 6);
01618 uint32 townnameparts = p2;
01619
01620 if (size >= TSZ_END) return CMD_ERROR;
01621 if (layout >= NUM_TLS) return CMD_ERROR;
01622
01623
01624 if (_game_mode != GM_EDITOR) {
01625 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
01626 if (size == TSZ_LARGE) return CMD_ERROR;
01627 if (random) return CMD_ERROR;
01628 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
01629 return CMD_ERROR;
01630 }
01631 }
01632
01633 if (StrEmpty(text)) {
01634
01635 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01636 } else {
01637
01638 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
01639 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01640 }
01641
01642
01643 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
01644
01645 if (!random) {
01646 CommandCost ret = TownCanBePlacedHere(tile);
01647 if (ret.Failed()) return ret;
01648 }
01649
01650 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
01651
01652 assert_compile(lengthof(price_mult[0]) == 4);
01653
01654 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
01655 byte mult = price_mult[city][size];
01656
01657 cost.MultiplyCost(mult);
01658
01659
01660 if (flags & DC_EXEC) {
01661 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
01662 _additional_cash_required = cost.GetCost();
01663 return CommandCost(EXPENSES_OTHER);
01664 }
01665
01666 _generating_world = true;
01667 UpdateNearestTownForRoadTiles(true);
01668 Town *t;
01669 if (random) {
01670 t = CreateRandomTown(20, townnameparts, size, city, layout);
01671 if (t == NULL) {
01672 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
01673 } else {
01674 _new_town_id = t->index;
01675 }
01676 } else {
01677 t = new Town(tile);
01678 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
01679 }
01680 UpdateNearestTownForRoadTiles(false);
01681 _generating_world = false;
01682
01683 if (t != NULL && !StrEmpty(text)) {
01684 t->name = strdup(text);
01685 t->UpdateVirtCoord();
01686 }
01687
01688 if (_game_mode != GM_EDITOR) {
01689
01690 assert(!random);
01691 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
01692 SetDParam(0, _current_company);
01693 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
01694
01695 char *cn = strdup(company_name);
01696 SetDParamStr(0, cn);
01697 SetDParam(1, t->index);
01698
01699 AddNewsItem(STR_NEWS_NEW_TOWN, NS_INDUSTRY_OPEN, NR_TILE, tile, NR_NONE, UINT32_MAX, cn);
01700 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
01701 }
01702 }
01703 return cost;
01704 }
01705
01715 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
01716 {
01717 switch (layout) {
01718 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
01719 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
01720 default: return tile;
01721 }
01722 }
01723
01733 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
01734 {
01735 switch (layout) {
01736 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
01737 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
01738 default: return true;
01739 }
01740 }
01741
01745 struct SpotData {
01746 TileIndex tile;
01747 uint max_dist;
01748 TownLayout layout;
01749 };
01750
01767 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
01768 {
01769 SpotData *sp = (SpotData*)user_data;
01770 uint dist = GetClosestWaterDistance(tile, true);
01771
01772 if (IsTileType(tile, MP_CLEAR) &&
01773 GetTileSlope(tile) == SLOPE_FLAT &&
01774 IsTileAlignedToGrid(tile, sp->layout) &&
01775 dist > sp->max_dist) {
01776 sp->tile = tile;
01777 sp->max_dist = dist;
01778 }
01779
01780 return false;
01781 }
01782
01789 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
01790 {
01791 return IsTileType(tile, MP_CLEAR);
01792 }
01793
01806 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
01807 {
01808 SpotData sp = { INVALID_TILE, 0, layout };
01809
01810 TileIndex coast = tile;
01811 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
01812 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
01813 return sp.tile;
01814 }
01815
01816
01817 return INVALID_TILE;
01818 }
01819
01820 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
01821 {
01822 if (!Town::CanAllocateItem()) return NULL;
01823
01824 do {
01825
01826 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
01827
01828
01829
01830 if (IsTileType(tile, MP_WATER)) {
01831 tile = FindNearestGoodCoastalTownSpot(tile, layout);
01832 if (tile == INVALID_TILE) continue;
01833 }
01834
01835
01836 if (TownCanBePlacedHere(tile).Failed()) continue;
01837
01838
01839 Town *t = new Town(tile);
01840
01841 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
01842
01843
01844
01845 if (t->population > 0) return t;
01846 DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
01847
01848
01849
01850
01851
01852 assert(Town::CanAllocateItem());
01853 } while (--attempts != 0);
01854
01855 return NULL;
01856 }
01857
01858 static const byte _num_initial_towns[4] = {5, 11, 23, 46};
01859
01867 bool GenerateTowns(TownLayout layout)
01868 {
01869 uint current_number = 0;
01870 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
01871 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
01872 uint32 townnameparts;
01873
01874 SetGeneratingWorldProgress(GWP_TOWN, total);
01875
01876
01877
01878
01879 do {
01880 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
01881 IncreaseGeneratingWorldProgress(GWP_TOWN);
01882
01883 if (!GenerateTownName(&townnameparts)) continue;
01884
01885 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++;
01886 } while (--total);
01887
01888 if (current_number != 0) return true;
01889
01890
01891
01892 if (GenerateTownName(&townnameparts) &&
01893 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
01894 return true;
01895 }
01896
01897
01898 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
01899 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
01900 }
01901
01902 return false;
01903 }
01904
01905
01912 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
01913 {
01914 uint dist = DistanceSquare(tile, t->xy);
01915
01916 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
01917
01918 HouseZonesBits smallest = HZB_TOWN_EDGE;
01919 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
01920 if (dist < t->squared_town_zone_radius[i]) smallest = i;
01921 }
01922
01923 return smallest;
01924 }
01925
01936 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
01937 {
01938 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
01939
01940 assert(cc.Succeeded());
01941
01942 IncreaseBuildingCount(t, type);
01943 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
01944 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
01945
01946 MarkTileDirtyByTile(tile);
01947 }
01948
01949
01960 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
01961 {
01962 BuildingFlags size = HouseSpec::Get(type)->building_flags;
01963
01964 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
01965 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
01966 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
01967 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
01968 }
01969
01970
01979 static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
01980 {
01981
01982 Slope slope = GetTileSlope(tile);
01983 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
01984
01985
01986 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
01987
01988
01989 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
01990
01991
01992 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
01993 }
01994
01995
02005 static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, int z, bool noslope)
02006 {
02007 if (!CanBuildHouseHere(tile, town, noslope)) return false;
02008
02009
02010 if (GetTileMaxZ(tile) != z) return false;
02011
02012 return true;
02013 }
02014
02015
02025 static bool CheckFree2x2Area(TileIndex tile, TownID town, int z, bool noslope)
02026 {
02027
02028 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02029
02030 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
02031 tile += TileOffsByDiagDir(d);
02032 if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
02033 }
02034
02035 return true;
02036 }
02037
02038
02046 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
02047 {
02048
02049 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02050
02051 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02052
02053 switch (t->layout) {
02054 case TL_2X2_GRID:
02055 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
02056 break;
02057
02058 case TL_3X3_GRID:
02059 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
02060 break;
02061
02062 default:
02063 break;
02064 }
02065
02066 return true;
02067 }
02068
02069
02077 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
02078 {
02079
02080 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
02081
02082
02083 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
02084
02085 switch (t->layout) {
02086 case TL_2X2_GRID:
02087 grid_pos.x %= 3;
02088 grid_pos.y %= 3;
02089 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
02090 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
02091 break;
02092
02093 case TL_3X3_GRID:
02094 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
02095 break;
02096
02097 default:
02098 break;
02099 }
02100
02101 return true;
02102 }
02103
02104
02114 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
02115 {
02116
02117
02118 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
02119 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
02120
02121 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
02122 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
02123 *tile = tile2;
02124 return true;
02125 }
02126
02127 return false;
02128 }
02129
02130
02139 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
02140 {
02141 TileIndex tile2 = *tile;
02142
02143 for (DiagDirection d = DIAGDIR_SE;; d++) {
02144 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
02145 *tile = tile2;
02146 return true;
02147 }
02148 if (d == DIAGDIR_END) break;
02149 tile2 += TileOffsByDiagDir(ReverseDiagDir(d));
02150 }
02151
02152 return false;
02153 }
02154
02155
02162 static bool BuildTownHouse(Town *t, TileIndex tile)
02163 {
02164
02165 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
02166
02167
02168 if (!CanBuildHouseHere(tile, t->index, false)) return false;
02169
02170 int z;
02171 Slope slope = GetTileSlope(tile, &z);
02172
02173
02174
02175 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
02176
02177
02178 int land = _settings_game.game_creation.landscape;
02179 if (land == LT_ARCTIC && z >= HighestSnowLine()) land = -1;
02180
02181 uint bitmask = (1 << rad) + (1 << (land + 12));
02182
02183
02184
02185
02186 HouseID houses[HOUSE_MAX];
02187 uint num = 0;
02188 uint probs[HOUSE_MAX];
02189 uint probability_max = 0;
02190
02191
02192 for (uint i = 0; i < HOUSE_MAX; i++) {
02193 const HouseSpec *hs = HouseSpec::Get(i);
02194
02195
02196 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
02197
02198
02199 if (hs->class_id != HOUSE_NO_CLASS) {
02200
02201 if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
02202 } else {
02203
02204 if (t->building_counts.id_count[i] == UINT16_MAX) continue;
02205 }
02206
02207
02208 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
02209 probability_max += cur_prob;
02210 probs[num] = cur_prob;
02211 houses[num++] = (HouseID)i;
02212 }
02213
02214 int maxz = GetTileMaxZ(tile);
02215 TileIndex baseTile = tile;
02216
02217 while (probability_max > 0) {
02218
02219
02220
02221
02222
02223 tile = baseTile;
02224
02225 uint r = RandomRange(probability_max);
02226 uint i;
02227 for (i = 0; i < num; i++) {
02228 if (probs[i] > r) break;
02229 r -= probs[i];
02230 }
02231
02232 HouseID house = houses[i];
02233 probability_max -= probs[i];
02234
02235
02236 num--;
02237 houses[i] = houses[num];
02238 probs[i] = probs[num];
02239
02240 const HouseSpec *hs = HouseSpec::Get(house);
02241
02242 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
02243 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
02244 continue;
02245 }
02246
02247 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
02248
02249
02250 uint oneof = 0;
02251
02252 if (hs->building_flags & BUILDING_IS_CHURCH) {
02253 SetBit(oneof, TOWN_HAS_CHURCH);
02254 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02255 SetBit(oneof, TOWN_HAS_STADIUM);
02256 }
02257
02258 if (t->flags & oneof) continue;
02259
02260
02261 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
02262 if (noslope && slope != SLOPE_FLAT) continue;
02263
02264 if (hs->building_flags & TILE_SIZE_2x2) {
02265 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
02266 } else if (hs->building_flags & TILE_SIZE_2x1) {
02267 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
02268 } else if (hs->building_flags & TILE_SIZE_1x2) {
02269 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
02270 } else {
02271
02272 }
02273
02274 byte random_bits = Random();
02275
02276 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
02277 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
02278 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
02279 }
02280
02281
02282 t->num_houses++;
02283
02284
02285 t->flags |= oneof;
02286
02287 byte construction_counter = 0;
02288 byte construction_stage = 0;
02289
02290 if (_generating_world || _game_mode == GM_EDITOR) {
02291 uint32 r = Random();
02292
02293 construction_stage = TOWN_HOUSE_COMPLETED;
02294 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
02295
02296 if (construction_stage == TOWN_HOUSE_COMPLETED) {
02297 ChangePopulation(t, hs->population);
02298 } else {
02299 construction_counter = GB(r, 2, 2);
02300 }
02301 }
02302
02303 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
02304 UpdateTownCargos(t, tile);
02305
02306 return true;
02307 }
02308
02309 return false;
02310 }
02311
02318 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
02319 {
02320 assert(IsTileType(tile, MP_HOUSE));
02321 DecreaseBuildingCount(t, house);
02322 DoClearSquare(tile);
02323 DeleteAnimatedTile(tile);
02324
02325 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
02326 }
02327
02335 TileIndexDiff GetHouseNorthPart(HouseID &house)
02336 {
02337 if (house >= 3) {
02338 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
02339 house--;
02340 return TileDiffXY(-1, 0);
02341 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
02342 house--;
02343 return TileDiffXY(0, -1);
02344 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
02345 house -= 2;
02346 return TileDiffXY(-1, 0);
02347 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
02348 house -= 3;
02349 return TileDiffXY(-1, -1);
02350 }
02351 }
02352 return 0;
02353 }
02354
02355 void ClearTownHouse(Town *t, TileIndex tile)
02356 {
02357 assert(IsTileType(tile, MP_HOUSE));
02358
02359 HouseID house = GetHouseType(tile);
02360
02361
02362 tile += GetHouseNorthPart(house);
02363
02364 const HouseSpec *hs = HouseSpec::Get(house);
02365
02366
02367 if (IsHouseCompleted(tile)) {
02368 ChangePopulation(t, -hs->population);
02369 }
02370
02371 t->num_houses--;
02372
02373
02374 if (hs->building_flags & BUILDING_IS_CHURCH) {
02375 ClrBit(t->flags, TOWN_HAS_CHURCH);
02376 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
02377 ClrBit(t->flags, TOWN_HAS_STADIUM);
02378 }
02379
02380
02381 uint eflags = hs->building_flags;
02382 DoClearTownHouseHelper(tile, t, house);
02383 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
02384 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
02385 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
02386
02387
02388 UpdateTownCargos(t, tile);
02389 }
02390
02400 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02401 {
02402 Town *t = Town::GetIfValid(p1);
02403 if (t == NULL) return CMD_ERROR;
02404
02405 bool reset = StrEmpty(text);
02406
02407 if (!reset) {
02408 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
02409 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
02410 }
02411
02412 if (flags & DC_EXEC) {
02413 free(t->name);
02414 t->name = reset ? NULL : strdup(text);
02415
02416 t->UpdateVirtCoord();
02417 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
02418 UpdateAllStationVirtCoords();
02419 }
02420 return CommandCost();
02421 }
02422
02428 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
02429 {
02430 const CargoSpec *cs;
02431 FOR_ALL_CARGOSPECS(cs) {
02432 if (cs->town_effect == effect) return cs;
02433 }
02434 return NULL;
02435 }
02436
02446 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02447 {
02448 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02449 Town *t = Town::GetIfValid(p1);
02450 if (t == NULL) return CMD_ERROR;
02451
02452 if (flags & DC_EXEC) {
02453
02454 uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
02455 t->num_houses += amount;
02456 UpdateTownRadius(t);
02457
02458 uint n = amount * 10;
02459 do GrowTown(t); while (--n);
02460
02461 t->num_houses -= amount;
02462 UpdateTownRadius(t);
02463
02464 UpdateTownMaxPass(t);
02465 }
02466
02467 return CommandCost();
02468 }
02469
02479 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02480 {
02481 if (_game_mode != GM_EDITOR) return CMD_ERROR;
02482 Town *t = Town::GetIfValid(p1);
02483 if (t == NULL) return CMD_ERROR;
02484
02485
02486 const Station *st;
02487 FOR_ALL_STATIONS(st) {
02488 if (st->town == t) {
02489
02490 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
02491
02492 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02493 if (ret.Failed()) return ret;
02494 }
02495 }
02496
02497
02498 const Depot *d;
02499 FOR_ALL_DEPOTS(d) {
02500 if (d->town == t) return CMD_ERROR;
02501 }
02502
02503
02504 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
02505 bool try_clear = false;
02506 switch (GetTileType(tile)) {
02507 case MP_ROAD:
02508 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
02509 break;
02510
02511 case MP_TUNNELBRIDGE:
02512 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
02513 break;
02514
02515 case MP_HOUSE:
02516 try_clear = GetTownIndex(tile) == t->index;
02517 break;
02518
02519 case MP_INDUSTRY:
02520 try_clear = Industry::GetByTile(tile)->town == t;
02521 break;
02522
02523 case MP_OBJECT:
02524 if (Town::GetNumItems() == 1) {
02525
02526 try_clear = true;
02527 } else {
02528 Object *o = Object::GetByTile(tile);
02529 if (o->town == t) {
02530 if (GetObjectType(tile) == OBJECT_STATUE) {
02531
02532 try_clear = true;
02533 } else {
02534
02535 if (flags & DC_EXEC) o->town = NULL;
02536 }
02537 }
02538 }
02539 break;
02540
02541 default:
02542 break;
02543 }
02544 if (try_clear) {
02545 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
02546 if (ret.Failed()) return ret;
02547 }
02548 }
02549
02550
02551 if (flags & DC_EXEC) delete t;
02552
02553 return CommandCost();
02554 }
02555
02560 const byte _town_action_costs[TACT_COUNT] = {
02561 2, 4, 9, 35, 48, 53, 117, 175
02562 };
02563
02564 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
02565 {
02566 if (flags & DC_EXEC) {
02567 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
02568 }
02569 return CommandCost();
02570 }
02571
02572 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
02573 {
02574 if (flags & DC_EXEC) {
02575 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
02576 }
02577 return CommandCost();
02578 }
02579
02580 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
02581 {
02582 if (flags & DC_EXEC) {
02583 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
02584 }
02585 return CommandCost();
02586 }
02587
02588 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
02589 {
02590
02591 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
02592
02593 if (flags & DC_EXEC) {
02594 t->road_build_months = 6;
02595
02596 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
02597 SetDParam(0, _current_company);
02598 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
02599
02600 char *cn = strdup(company_name);
02601 SetDParam(0, t->index);
02602 SetDParamStr(1, cn);
02603
02604 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NS_GENERAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
02605 }
02606 return CommandCost();
02607 }
02608
02615 static bool SearchTileForStatue(TileIndex tile, void *user_data)
02616 {
02617
02618 if (IsSteepSlope(GetTileSlope(tile))) return false;
02619
02620 if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
02621
02622 if (!IsTileType(tile, MP_HOUSE) &&
02623 !IsTileType(tile, MP_CLEAR) &&
02624 !IsTileType(tile, MP_TREES)) {
02625 return false;
02626 }
02627
02628 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02629 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
02630 cur_company.Restore();
02631
02632 if (r.Failed()) return false;
02633
02634 return true;
02635 }
02636
02644 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
02645 {
02646 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
02647
02648 TileIndex tile = t->xy;
02649 if (CircularTileSearch(&tile, 9, SearchTileForStatue, NULL)) {
02650 if (flags & DC_EXEC) {
02651 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
02652 DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
02653 cur_company.Restore();
02654 BuildObject(OBJECT_STATUE, tile, _current_company, t);
02655 SetBit(t->statues, _current_company);
02656 MarkTileDirtyByTile(tile);
02657 }
02658 return CommandCost();
02659 }
02660 return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
02661 }
02662
02663 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
02664 {
02665
02666 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
02667
02668 if (flags & DC_EXEC) {
02669
02670 t->grow_counter = 1;
02671
02672 SetBit(t->flags, TOWN_IS_FUNDED);
02673
02674 t->fund_buildings_months = 3;
02675
02676 SetWindowDirty(WC_TOWN_VIEW, t->index);
02677 }
02678 return CommandCost();
02679 }
02680
02681 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
02682 {
02683
02684 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
02685
02686 if (flags & DC_EXEC) {
02687 t->exclusive_counter = 12;
02688 t->exclusivity = _current_company;
02689
02690 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
02691 }
02692 return CommandCost();
02693 }
02694
02695 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
02696 {
02697 if (flags & DC_EXEC) {
02698 if (Chance16(1, 14)) {
02699
02700 t->unwanted[_current_company] = 6;
02701
02702
02703 Station *st;
02704 FOR_ALL_STATIONS(st) {
02705 if (st->town == t && st->owner == _current_company) {
02706 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
02707 }
02708 }
02709
02710
02711
02712 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
02713
02714
02715
02716
02717
02718 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
02719 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
02720 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02721 }
02722 } else {
02723 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
02724 }
02725 }
02726 return CommandCost();
02727 }
02728
02729 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
02730 static TownActionProc * const _town_action_proc[] = {
02731 TownActionAdvertiseSmall,
02732 TownActionAdvertiseMedium,
02733 TownActionAdvertiseLarge,
02734 TownActionRoadRebuild,
02735 TownActionBuildStatue,
02736 TownActionFundBuildings,
02737 TownActionBuyRights,
02738 TownActionBribe
02739 };
02740
02748 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
02749 {
02750 int num = 0;
02751 TownActions buttons = TACT_NONE;
02752
02753
02754 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
02755
02756
02757 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
02758
02759
02760
02761 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
02762 const TownActions cur = (TownActions)(1 << i);
02763
02764
02765 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
02766
02767
02768 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
02769
02770
02771 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
02772
02773
02774 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
02775
02776
02777 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
02778
02779 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
02780 buttons |= cur;
02781 num++;
02782 }
02783 }
02784 }
02785
02786 if (nump != NULL) *nump = num;
02787 return buttons;
02788 }
02789
02801 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
02802 {
02803 Town *t = Town::GetIfValid(p1);
02804 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
02805
02806 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
02807
02808 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
02809
02810 CommandCost ret = _town_action_proc[p2](t, flags);
02811 if (ret.Failed()) return ret;
02812
02813 if (flags & DC_EXEC) {
02814 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
02815 }
02816
02817 return cost;
02818 }
02819
02820 static void UpdateTownRating(Town *t)
02821 {
02822
02823 const Company *c;
02824 FOR_ALL_COMPANIES(c) {
02825 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
02826 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
02827 }
02828 }
02829
02830 const Station *st;
02831 FOR_ALL_STATIONS(st) {
02832 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02833 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02834 if (Company::IsValidID(st->owner)) {
02835 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
02836 t->ratings[st->owner] = min(new_rating, INT16_MAX);
02837 }
02838 } else {
02839 if (Company::IsValidID(st->owner)) {
02840 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
02841 t->ratings[st->owner] = max(new_rating, INT16_MIN);
02842 }
02843 }
02844 }
02845 }
02846
02847
02848 for (uint i = 0; i < MAX_COMPANIES; i++) {
02849 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
02850 }
02851
02852 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
02853 }
02854
02855 static void UpdateTownGrowRate(Town *t)
02856 {
02857 ClrBit(t->flags, TOWN_IS_FUNDED);
02858 SetWindowDirty(WC_TOWN_VIEW, t->index);
02859
02860 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
02861
02862 if (t->fund_buildings_months == 0) {
02863
02864 for (int i = TE_BEGIN; i < TE_END; i++) {
02865 switch (t->goal[i]) {
02866 case TOWN_GROWTH_WINTER:
02867 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->population > 90) return;
02868 break;
02869 case TOWN_GROWTH_DESERT:
02870 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->population > 60) return;
02871 break;
02872 default:
02873 if (t->goal[i] > t->received[i].old_act) return;
02874 break;
02875 }
02876 }
02877 }
02878
02883 static const uint16 _grow_count_values[2][6] = {
02884 { 120, 120, 120, 100, 80, 60 },
02885 { 320, 420, 300, 220, 160, 100 }
02886 };
02887
02888 int n = 0;
02889
02890 const Station *st;
02891 FOR_ALL_STATIONS(st) {
02892 if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
02893 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
02894 n++;
02895 }
02896 }
02897 }
02898
02899 uint16 m;
02900
02901 if (t->fund_buildings_months != 0) {
02902 m = _grow_count_values[0][min(n, 5)];
02903 t->fund_buildings_months--;
02904 } else {
02905 m = _grow_count_values[1][min(n, 5)];
02906 if (n == 0 && !Chance16(1, 12)) return;
02907 }
02908
02909
02910
02911 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
02912
02913 m >>= growth_multiplier;
02914 if (t->larger_town) m /= 2;
02915
02916 t->growth_rate = m / (t->num_houses / 50 + 1);
02917 if (m <= t->grow_counter) {
02918 t->grow_counter = m;
02919 }
02920
02921 SetBit(t->flags, TOWN_IS_FUNDED);
02922 SetWindowDirty(WC_TOWN_VIEW, t->index);
02923 }
02924
02925 static void UpdateTownAmounts(Town *t)
02926 {
02927 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
02928 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
02929
02930 SetWindowDirty(WC_TOWN_VIEW, t->index);
02931 }
02932
02933 static void UpdateTownUnwanted(Town *t)
02934 {
02935 const Company *c;
02936
02937 FOR_ALL_COMPANIES(c) {
02938 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
02939 }
02940 }
02941
02948 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
02949 {
02950 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
02951
02952 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
02953 if (t == NULL) return CommandCost();
02954
02955 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
02956
02957 SetDParam(0, t->index);
02958 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
02959 }
02960
02969 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
02970 {
02971 Town *t;
02972 uint best = threshold;
02973 Town *best_town = NULL;
02974
02975 FOR_ALL_TOWNS(t) {
02976 uint dist = DistanceManhattan(tile, t->xy);
02977 if (dist < best) {
02978 best = dist;
02979 best_town = t;
02980 }
02981 }
02982
02983 return best_town;
02984 }
02985
02994 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
02995 {
02996 switch (GetTileType(tile)) {
02997 case MP_ROAD:
02998 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
02999
03000 if (!HasTownOwnedRoad(tile)) {
03001 TownID tid = GetTownIndex(tile);
03002
03003 if (tid == (TownID)INVALID_TOWN) {
03004
03005 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
03006 assert(Town::GetNumItems() == 0);
03007 return NULL;
03008 }
03009
03010 assert(Town::IsValidID(tid));
03011 Town *town = Town::Get(tid);
03012
03013 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
03014
03015 return town;
03016 }
03017
03018
03019 case MP_HOUSE:
03020 return Town::GetByTile(tile);
03021
03022 default:
03023 return CalcClosestTownFromTile(tile, threshold);
03024 }
03025 }
03026
03027 static bool _town_rating_test = false;
03028 static SmallMap<const Town *, int, 4> _town_test_ratings;
03029
03035 void SetTownRatingTestMode(bool mode)
03036 {
03037 static int ref_count = 0;
03038 if (mode) {
03039 if (ref_count == 0) {
03040 _town_test_ratings.Clear();
03041 }
03042 ref_count++;
03043 } else {
03044 assert(ref_count > 0);
03045 ref_count--;
03046 }
03047 _town_rating_test = !(ref_count == 0);
03048 }
03049
03055 static int GetRating(const Town *t)
03056 {
03057 if (_town_rating_test) {
03058 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
03059 if (it != _town_test_ratings.End()) {
03060 return it->second;
03061 }
03062 }
03063 return t->ratings[_current_company];
03064 }
03065
03073 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
03074 {
03075
03076 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
03077 !Company::IsValidID(_current_company) ||
03078 (_cheats.magic_bulldozer.value && add < 0)) {
03079 return;
03080 }
03081
03082 int rating = GetRating(t);
03083 if (add < 0) {
03084 if (rating > max) {
03085 rating += add;
03086 if (rating < max) rating = max;
03087 }
03088 } else {
03089 if (rating < max) {
03090 rating += add;
03091 if (rating > max) rating = max;
03092 }
03093 }
03094 if (_town_rating_test) {
03095 _town_test_ratings[t] = rating;
03096 } else {
03097 SetBit(t->have_ratings, _current_company);
03098 t->ratings[_current_company] = rating;
03099 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
03100 }
03101 }
03102
03110 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
03111 {
03112
03113 if (t == NULL || !Company::IsValidID(_current_company) ||
03114 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
03115 return CommandCost();
03116 }
03117
03118
03119 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
03120
03121 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE},
03122 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL},
03123 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE},
03124 };
03125
03126
03127
03128
03129
03130 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
03131
03132 if (GetRating(t) < needed) {
03133 SetDParam(0, t->index);
03134 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
03135 }
03136
03137 return CommandCost();
03138 }
03139
03140 void TownsMonthlyLoop()
03141 {
03142 Town *t;
03143
03144 FOR_ALL_TOWNS(t) {
03145 if (t->road_build_months != 0) t->road_build_months--;
03146
03147 if (t->exclusive_counter != 0) {
03148 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
03149 }
03150
03151 UpdateTownAmounts(t);
03152 UpdateTownRating(t);
03153 UpdateTownGrowRate(t);
03154 UpdateTownUnwanted(t);
03155 UpdateTownCargos(t);
03156 }
03157
03158 UpdateTownCargoBitmap();
03159 }
03160
03161 void TownsYearlyLoop()
03162 {
03163
03164 for (TileIndex t = 0; t < MapSize(); t++) {
03165 if (!IsTileType(t, MP_HOUSE)) continue;
03166 IncrementHouseAge(t);
03167 }
03168 }
03169
03170 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
03171 {
03172 if (AutoslopeEnabled()) {
03173 HouseID house = GetHouseType(tile);
03174 GetHouseNorthPart(house);
03175 const HouseSpec *hs = HouseSpec::Get(house);
03176
03177
03178 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
03179 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
03180 bool allow_terraform = true;
03181
03182
03183 house = GetHouseType(tile);
03184 hs = HouseSpec::Get(house);
03185 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
03186
03187 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
03188 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
03189 }
03190
03191 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
03192 }
03193 }
03194
03195 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
03196 }
03197
03199 extern const TileTypeProcs _tile_type_town_procs = {
03200 DrawTile_Town,
03201 GetSlopePixelZ_Town,
03202 ClearTile_Town,
03203 AddAcceptedCargo_Town,
03204 GetTileDesc_Town,
03205 GetTileTrackStatus_Town,
03206 NULL,
03207 AnimateTile_Town,
03208 TileLoop_Town,
03209 ChangeTileOwner_Town,
03210 AddProducedCargo_Town,
03211 NULL,
03212 GetFoundation_Town,
03213 TerraformTile_Town,
03214 };
03215
03216
03217 HouseSpec _house_specs[HOUSE_MAX];
03218
03219 void ResetHouses()
03220 {
03221 memset(&_house_specs, 0, sizeof(_house_specs));
03222 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
03223
03224
03225 _house_mngr.ResetOverride();
03226 }