OpenTTD

town_cmd.cpp
Go to the documentation of this file.
1 /* $Id: town_cmd.cpp 27893 2017-08-13 18:38:42Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "road_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
49
50 #include "table/strings.h"
51 #include "table/town_land.h"
52
53 #include "safeguards.h"
54
55 TownID _new_town_id;
56 uint32 _town_cargoes_accepted;
57
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
60 INSTANTIATE_POOL_METHODS(Town)
61
62 Town::~Town()
63 {
64 free(this->name);
65 free(this->text);
66
67 if (CleaningPool()) return;
68
69 /* Delete town authority window
70 * and remove from list of sorted towns */
71 DeleteWindowById(WC_TOWN_VIEW, this->index);
72
73 /* Check no industry is related to us. */
74 const Industry *i;
75 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
76
77 /* ... and no object is related to us. */
78 const Object *o;
79 FOR_ALL_OBJECTS(o) assert(o->town != this);
80
81 /* Check no tile is related to us. */
82 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83 switch (GetTileType(tile)) {
84 case MP_HOUSE:
85 assert(GetTownIndex(tile) != this->index);
86 break;
87
88 case MP_ROAD:
89 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90 break;
91
92 case MP_TUNNELBRIDGE:
93 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94 break;
95
96 default:
97 break;
98 }
99 }
100
101 /* Clear the persistent storage list. */
102 this->psa_list.clear();
103
104 DeleteSubsidyWith(ST_TOWN, this->index);
105 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
106 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
107 MarkWholeScreenDirty();
108 }
109
110
116 void Town::PostDestructor(size_t index)
117 {
118 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
119 UpdateNearestTownForRoadTiles(false);
120
121 /* Give objects a new home! */
122 Object *o;
123 FOR_ALL_OBJECTS(o) {
124 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
125 }
126 }
127
131 void Town::InitializeLayout(TownLayout layout)
132 {
133 if (layout != TL_RANDOM) {
134 this->layout = layout;
135 return;
136 }
137
138 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
139 }
140
145 /* static */ Town *Town::GetRandom()
146 {
147 if (Town::GetNumItems() == 0) return NULL;
148 int num = RandomRange((uint16)Town::GetNumItems());
149 size_t index = MAX_UVALUE(size_t);
150
151 while (num >= 0) {
152 num--;
153 index++;
154
155 /* Make sure we have a valid town */
156 while (!Town::IsValidID(index)) {
157 index++;
158 assert(index < Town::GetPoolSize());
159 }
160 }
161
162 return Town::Get(index);
163 }
164
169 Money HouseSpec::GetRemovalCost() const
170 {
171 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
172 }
173
174 /* Local */
175 static int _grow_town_result;
176
177 /* Describe the possible states */
178 enum TownGrowthResult {
179 GROWTH_SUCCEED = -1,
180 GROWTH_SEARCH_STOPPED = 0
181 // GROWTH_SEARCH_RUNNING >= 1
182 };
183
184 static bool BuildTownHouse(Town *t, TileIndex tile);
185 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
186
187 static void TownDrawHouseLift(const TileInfo *ti)
188 {
189 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
190 }
191
192 typedef void TownDrawTileProc(const TileInfo *ti);
193 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
194 TownDrawHouseLift
195 };
196
202 static inline DiagDirection RandomDiagDir()
203 {
204 return (DiagDirection)(3 & Random());
205 }
206
212 static void DrawTile_Town(TileInfo *ti)
213 {
214 HouseID house_id = GetHouseType(ti->tile);
215
216 if (house_id >= NEW_HOUSE_OFFSET) {
217 /* Houses don't necessarily need new graphics. If they don't have a
218 * spritegroup associated with them, then the sprite for the substitute
219 * house id is drawn instead. */
220 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
221 DrawNewHouseTile(ti, house_id);
222 return;
223 } else {
224 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
225 }
226 }
227
228 /* Retrieve pointer to the draw town tile struct */
229 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
230
231 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
232
233 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
234
235 /* If houses are invisible, do not draw the upper part */
236 if (IsInvisibilitySet(TO_HOUSES)) return;
237
238 /* Add a house on top of the ground? */
239 SpriteID image = dcts->building.sprite;
240 if (image != 0) {
241 AddSortableSpriteToDraw(image, dcts->building.pal,
242 ti->x + dcts->subtile_x,
243 ti->y + dcts->subtile_y,
244 dcts->width,
245 dcts->height,
246 dcts->dz,
247 ti->z,
248 IsTransparencySet(TO_HOUSES)
249 );
250
251 if (IsTransparencySet(TO_HOUSES)) return;
252 }
253
254 {
255 int proc = dcts->draw_proc - 1;
256
257 if (proc >= 0) _town_draw_tile_procs[proc](ti);
258 }
259 }
260
261 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
262 {
263 return GetTileMaxPixelZ(tile);
264 }
265
267 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
268 {
269 HouseID hid = GetHouseType(tile);
270
271 /* For NewGRF house tiles we might not be drawing a foundation. We need to
272 * account for this, as other structures should
273 * draw the wall of the foundation in this case.
274 */
275 if (hid >= NEW_HOUSE_OFFSET) {
276 const HouseSpec *hs = HouseSpec::Get(hid);
277 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
278 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
279 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
280 }
281 }
282 return FlatteningFoundation(tileh);
283 }
284
291 static void AnimateTile_Town(TileIndex tile)
292 {
293 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
294 AnimateNewHouseTile(tile);
295 return;
296 }
297
298 if (_tick_counter & 3) return;
299
300 /* If the house is not one with a lift anymore, then stop this animating.
301 * Not exactly sure when this happens, but probably when a house changes.
302 * Before this was just a return...so it'd leak animated tiles..
303 * That bug seems to have been here since day 1?? */
304 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
305 DeleteAnimatedTile(tile);
306 return;
307 }
308
309 if (!LiftHasDestination(tile)) {
310 uint i;
311
312 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
313 * This is due to the fact that the first floor is, in the graphics,
314 * the height of 2 'normal' floors.
315 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
316 do {
317 i = RandomRange(7);
318 } while (i == 1 || i * 6 == GetLiftPosition(tile));
319
320 SetLiftDestination(tile, i);
321 }
322
323 int pos = GetLiftPosition(tile);
324 int dest = GetLiftDestination(tile) * 6;
325 pos += (pos < dest) ? 1 : -1;
326 SetLiftPosition(tile, pos);
327
328 if (pos == dest) {
329 HaltLift(tile);
330 DeleteAnimatedTile(tile);
331 }
332
333 MarkTileDirtyByTile(tile);
334 }
335
342 static bool IsCloseToTown(TileIndex tile, uint dist)
343 {
344 /* On a large map with many towns, it may be faster to check the surroundings of the tile.
345 * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
346 if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
347 const int tx = TileX(tile);
348 const int ty = TileY(tile);
349 TileArea tile_area = TileArea(
350 TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
351 TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
352 );
353 TILE_AREA_LOOP(atile, tile_area) {
354 if (GetTileType(atile) == MP_HOUSE) {
355 Town *t = Town::GetByTile(atile);
356 if (DistanceManhattan(tile, t->xy) < dist) return true;
357 }
358 }
359 return false;
360 }
361
362 const Town *t;
363
364 FOR_ALL_TOWNS(t) {
365 if (DistanceManhattan(tile, t->xy) < dist) return true;
366 }
367 return false;
368 }
369
374 void Town::UpdateVirtCoord()
375 {
376 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
377 SetDParam(0, this->index);
378 SetDParam(1, this->cache.population);
379 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
380 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
381 STR_VIEWPORT_TOWN);
382
383 SetWindowDirty(WC_TOWN_VIEW, this->index);
384 }
385
387 void UpdateAllTownVirtCoords()
388 {
389 Town *t;
390
391 FOR_ALL_TOWNS(t) {
392 t->UpdateVirtCoord();
393 }
394 }
395
401 static void ChangePopulation(Town *t, int mod)
402 {
403 t->cache.population += mod;
404 InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
405 t->UpdateVirtCoord();
406
407 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
408 }
409
415 uint32 GetWorldPopulation()
416 {
417 uint32 pop = 0;
418 const Town *t;
419
420 FOR_ALL_TOWNS(t) pop += t->cache.population;
421 return pop;
422 }
423
428 static void MakeSingleHouseBigger(TileIndex tile)
429 {
430 assert(IsTileType(tile, MP_HOUSE));
431
432 /* progress in construction stages */
433 IncHouseConstructionTick(tile);
434 if (GetHouseConstructionTick(tile) != 0) return;
435
436 AnimateNewHouseConstruction(tile);
437
438 if (IsHouseCompleted(tile)) {
439 /* Now that construction is complete, we can add the population of the
440 * building to the town. */
441 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
442 ResetHouseAge(tile);
443 }
444 MarkTileDirtyByTile(tile);
445 }
446
451 static void MakeTownHouseBigger(TileIndex tile)
452 {
453 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
454 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
455 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
456 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
457 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
458 }
459
466 static void TileLoop_Town(TileIndex tile)
467 {
468 HouseID house_id = GetHouseType(tile);
469
470 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
471 * doesn't exist any more, so don't continue here. */
472 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
473
474 if (!IsHouseCompleted(tile)) {
475 /* Construction is not completed. See if we can go further in construction*/
476 MakeTownHouseBigger(tile);
477 return;
478 }
479
480 const HouseSpec *hs = HouseSpec::Get(house_id);
481
482 /* If the lift has a destination, it is already an animated tile. */
483 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
484 house_id < NEW_HOUSE_OFFSET &&
485 !LiftHasDestination(tile) &&
486 Chance16(1, 2)) {
487 AddAnimatedTile(tile);
488 }
489
490 Town *t = Town::GetByTile(tile);
491 uint32 r = Random();
492
493 StationFinder stations(TileArea(tile, 1, 1));
494
495 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
496 for (uint i = 0; i < 256; i++) {
497 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
498
499 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
500
501 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
502 if (cargo == CT_INVALID) continue;
503
504 uint amt = GB(callback, 0, 8);
505 if (amt == 0) continue;
506
507 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
508
509 const CargoSpec *cs = CargoSpec::Get(cargo);
510 t->supplied[cs->Index()].new_max += amt;
511 t->supplied[cs->Index()].new_act += moved;
512 }
513 } else {
514 if (GB(r, 0, 8) < hs->population) {
515 uint amt = GB(r, 0, 8) / 8 + 1;
516
517 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
518 t->supplied[CT_PASSENGERS].new_max += amt;
519 t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
520 }
521
522 if (GB(r, 8, 8) < hs->mail_generation) {
523 uint amt = GB(r, 8, 8) / 8 + 1;
524
525 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
526 t->supplied[CT_MAIL].new_max += amt;
527 t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
528 }
529 }
530
531 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
532
533 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
534 HasBit(t->flags, TOWN_IS_GROWING) &&
535 CanDeleteHouse(tile) &&
536 GetHouseAge(tile) >= hs->minimum_life &&
537 --t->time_until_rebuild == 0) {
538 t->time_until_rebuild = GB(r, 16, 8) + 192;
539
540 ClearTownHouse(t, tile);
541
542 /* Rebuild with another house? */
543 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
544 }
545
546 cur_company.Restore();
547 }
548
549 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
550 {
551 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
552 if (!CanDeleteHouse(tile)) return CMD_ERROR;
553
554 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
555
556 CommandCost cost(EXPENSES_CONSTRUCTION);
557 cost.AddCost(hs->GetRemovalCost());
558
559 int rating = hs->remove_rating_decrease;
560 Town *t = Town::GetByTile(tile);
561
562 if (Company::IsValidID(_current_company)) {
563 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
564 SetDParam(0, t->index);
565 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
566 }
567 }
568
569 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
570 if (flags & DC_EXEC) {
571 ClearTownHouse(t, tile);
572 }
573
574 return cost;
575 }
576
577 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
578 {
579 HouseID house_id = GetHouseType(tile);
580 const HouseSpec *hs = HouseSpec::Get(house_id);
581 Town *t = Town::GetByTile(tile);
582
583 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
584 for (uint i = 0; i < 256; i++) {
585 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
586
587 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
588
589 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
590
591 if (cargo == CT_INVALID) continue;
592 produced[cargo]++;
593 }
594 } else {
595 if (hs->population > 0) {
596 produced[CT_PASSENGERS]++;
597 }
598 if (hs->mail_generation > 0) {
599 produced[CT_MAIL]++;
600 }
601 }
602 }
603
604 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
605 {
606 if (cargo == CT_INVALID || amount == 0) return;
607 acceptance[cargo] += amount;
608 SetBit(*always_accepted, cargo);
609 }
610
611 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
612 {
613 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
614 CargoID accepts[3];
615
616 /* Set the initial accepted cargo types */
617 for (uint8 i = 0; i < lengthof(accepts); i++) {
618 accepts[i] = hs->accepts_cargo[i];
619 }
620
621 /* Check for custom accepted cargo types */
622 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
623 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
624 if (callback != CALLBACK_FAILED) {
625 /* Replace accepted cargo types with translated values from callback */
626 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
627 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
628 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
629 }
630 }
631
632 /* Check for custom cargo acceptance */
633 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
634 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
635 if (callback != CALLBACK_FAILED) {
636 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
637 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
638 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
639 /* The 'S' bit indicates food instead of goods */
640 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
641 } else {
642 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
643 }
644 return;
645 }
646 }
647
648 /* No custom acceptance, so fill in with the default values */
649 for (uint8 i = 0; i < lengthof(accepts); i++) {
650 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
651 }
652 }
653
654 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
655 {
656 const HouseID house = GetHouseType(tile);
657 const HouseSpec *hs = HouseSpec::Get(house);
658 bool house_completed = IsHouseCompleted(tile);
659
660 td->str = hs->building_name;
661
662 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
663 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
664 if (callback_res > 0x400) {
665 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
666 } else {
667 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
668 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
669 td->str = new_name;
670 }
671 }
672 }
673
674 if (!house_completed) {
675 SetDParamX(td->dparam, 0, td->str);
676 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
677 }
678
679 if (hs->grf_prop.grffile != NULL) {
680 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
681 td->grf = gc->GetName();
682 }
683
684 td->owner[0] = OWNER_TOWN;
685 }
686
687 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
688 {
689 /* not used */
690 return 0;
691 }
692
693 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
694 {
695 /* not used */
696 }
697
701 void UpdateTownCargoTotal(Town *t)
702 {
703 t->cargo_accepted_total = 0;
704
705 const TileArea &area = t->cargo_accepted.GetArea();
706 TILE_AREA_LOOP(tile, area) {
707 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
708 t->cargo_accepted_total |= t->cargo_accepted[tile];
709 }
710 }
711 }
712
719 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
720 {
721 CargoArray accepted, produced;
722 uint32 dummy;
723
724 /* Gather acceptance for all houses in an area around the start tile.
725 * The area is composed of the square the tile is in, extended one square in all
726 * directions as the coverage area of a single station is bigger than just one square. */
727 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
728 TILE_AREA_LOOP(tile, area) {
729 if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
730
731 AddAcceptedCargo_Town(tile, accepted, &dummy);
732 AddProducedCargo_Town(tile, produced);
733 }
734
735 /* Create bitmap of produced and accepted cargoes. */
736 uint32 acc = 0;
737 for (uint cid = 0; cid < NUM_CARGO; cid++) {
738 if (accepted[cid] >= 8) SetBit(acc, cid);
739 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
740 }
741 t->cargo_accepted[start] = acc;
742
743 if (update_total) UpdateTownCargoTotal(t);
744 }
745
749 void UpdateTownCargoes(Town *t)
750 {
751 t->cargo_produced = 0;
752
753 const TileArea &area = t->cargo_accepted.GetArea();
754 if (area.tile == INVALID_TILE) return;
755
756 /* Update acceptance for each grid square. */
757 TILE_AREA_LOOP(tile, area) {
758 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
759 UpdateTownCargoes(t, tile, false);
760 }
761 }
762
763 /* Update the total acceptance. */
764 UpdateTownCargoTotal(t);
765 }
766
768 void UpdateTownCargoBitmap()
769 {
770 Town *town;
771 _town_cargoes_accepted = 0;
772
773 FOR_ALL_TOWNS(town) {
774 _town_cargoes_accepted |= town->cargo_accepted_total;
775 }
776 }
777
778 static bool GrowTown(Town *t);
779
780 static void TownTickHandler(Town *t)
781 {
782 if (HasBit(t->flags, TOWN_IS_GROWING)) {
783 int i = t->grow_counter - 1;
784 if (i < 0) {
785 if (GrowTown(t)) {
786 i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
787 } else {
788 i = 0;
789 }
790 }
791 t->grow_counter = i;
792 }
793 }
794
795 void OnTick_Town()
796 {
797 if (_game_mode == GM_EDITOR) return;
798
799 Town *t;
800 FOR_ALL_TOWNS(t) {
801 /* Run town tick at regular intervals, but not all at once. */
802 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
803 TownTickHandler(t);
804 }
805 }
806 }
807
816 static RoadBits GetTownRoadBits(TileIndex tile)
817 {
818 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
819
820 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
821 }
822
833 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
834 {
835 if (!IsValidTile(tile)) return false;
836
837 /* Lookup table for the used diff values */
838 const TileIndexDiff tid_lt[3] = {
839 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
840 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
841 TileOffsByDiagDir(ReverseDiagDir(dir)),
842 };
843
844 dist_multi = (dist_multi + 1) * 4;
845 for (uint pos = 4; pos < dist_multi; pos++) {
846 /* Go (pos / 4) tiles to the left or the right */
847 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
848
849 /* Use the current tile as origin, or go one tile backwards */
850 if (pos & 2) cur += tid_lt[2];
851
852 /* Test for roadbit parallel to dir and facing towards the middle axis */
853 if (IsValidTile(tile + cur) &&
854 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
855 }
856 return false;
857 }
858
867 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
868 {
869 if (DistanceFromEdge(tile) == 0) return false;
870
871 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
872 if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
873
874 /* Check if there already is a road at this point? */
875 if (GetTownRoadBits(tile) == ROAD_NONE) {
876 /* No, try if we are able to build a road piece there.
877 * If that fails clear the land, and if that fails exit.
878 * This is to make sure that we can build a road here later. */
879 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
880 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
881 return false;
882 }
883 }
884
885 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
886 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
887 if (cur_slope == SLOPE_FLAT) return ret;
888
889 /* If the tile is not a slope in the right direction, then
890 * maybe terraform some. */
891 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
892 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
893 if (Chance16(1, 8)) {
894 CommandCost res = CMD_ERROR;
895 if (!_generating_world && Chance16(1, 10)) {
896 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
897 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
898 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
899 }
900 if (res.Failed() && Chance16(1, 3)) {
901 /* We can consider building on the slope, though. */
902 return ret;
903 }
904 }
905 return false;
906 }
907 return ret;
908 }
909
910 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
911 {
912 assert(tile < MapSize());
913
914 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
915 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
916 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
917 return true;
918 }
919
920 static void LevelTownLand(TileIndex tile)
921 {
922 assert(tile < MapSize());
923
924 /* Don't terraform if land is plain or if there's a house there. */
925 if (IsTileType(tile, MP_HOUSE)) return;
926 Slope tileh = GetTileSlope(tile);
927 if (tileh == SLOPE_FLAT) return;
928
929 /* First try up, then down */
930 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
931 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
932 }
933 }
934
944 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
945 {
946 /* align the grid to the downtown */
947 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
948 RoadBits rcmd = ROAD_NONE;
949
950 switch (t->layout) {
951 default: NOT_REACHED();
952
953 case TL_2X2_GRID:
954 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
955 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
956 break;
957
958 case TL_3X3_GRID:
959 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
960 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
961 break;
962 }
963
964 /* Optimise only X-junctions */
965 if (rcmd != ROAD_ALL) return rcmd;
966
967 RoadBits rb_template;
968
969 switch (GetTileSlope(tile)) {
970 default: rb_template = ROAD_ALL; break;
971 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
972 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
973 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
974 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
975 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
976 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
977 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
978 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
979 case SLOPE_STEEP_W:
980 case SLOPE_STEEP_S:
981 case SLOPE_STEEP_E:
982 case SLOPE_STEEP_N:
983 rb_template = ROAD_NONE;
984 break;
985 }
986
987 /* Stop if the template is compatible to the growth dir */
988 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
989 /* If not generate a straight road in the direction of the growth */
990 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
991 }
992
1003 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
1004 {
1005 /* We can't look further than that. */
1006 if (DistanceFromEdge(tile) == 0) return false;
1007
1008 uint counter = 0; // counts the house neighbor tiles
1009
1010 /* Check the tiles E,N,W and S of the current tile for houses */
1011 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1012 /* Count both void and house tiles for checking whether there
1013 * are enough houses in the area. This to make it likely that
1014 * houses get build up to the edge of the map. */
1015 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1016 case MP_HOUSE:
1017 case MP_VOID:
1018 counter++;
1019 break;
1020
1021 default:
1022 break;
1023 }
1024
1025 /* If there are enough neighbors stop here */
1026 if (counter >= 3) {
1027 if (BuildTownHouse(t, tile)) {
1028 _grow_town_result = GROWTH_SUCCEED;
1029 return true;
1030 }
1031 return false;
1032 }
1033 }
1034 return false;
1035 }
1036
1045 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1046 {
1047 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1048 _grow_town_result = GROWTH_SUCCEED;
1049 return true;
1050 }
1051 return false;
1052 }
1053
1064 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1065 {
1066 assert(bridge_dir < DIAGDIR_END);
1067
1068 const Slope slope = GetTileSlope(tile);
1069
1070 /* Make sure the direction is compatible with the slope.
1071 * Well we check if the slope has an up bit set in the
1072 * reverse direction. */
1073 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1074
1075 /* Assure that the bridge is connectable to the start side */
1076 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1077
1078 /* We are in the right direction */
1079 uint8 bridge_length = 0; // This value stores the length of the possible bridge
1080 TileIndex bridge_tile = tile; // Used to store the other waterside
1081
1082 const int delta = TileOffsByDiagDir(bridge_dir);
1083
1084 if (slope == SLOPE_FLAT) {
1085 /* Bridges starting on flat tiles are only allowed when crossing rivers. */
1086 do {
1087 if (bridge_length++ >= 4) {
1088 /* Allow to cross rivers, not big lakes. */
1089 return false;
1090 }
1091 bridge_tile += delta;
1092 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile) && !IsSea(bridge_tile));
1093 } else {
1094 do {
1095 if (bridge_length++ >= 11) {
1096 /* Max 11 tile long bridges */
1097 return false;
1098 }
1099 bridge_tile += delta;
1100 } while (IsValidTile(bridge_tile) && IsWaterTile(bridge_tile));
1101 }
1102
1103 /* no water tiles in between? */
1104 if (bridge_length == 1) return false;
1105
1106 for (uint8 times = 0; times <= 22; times++) {
1107 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1108
1109 /* Can we actually build the bridge? */
1110 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1111 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1112 _grow_town_result = GROWTH_SUCCEED;
1113 return true;
1114 }
1115 }
1116 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1117 return false;
1118 }
1119
1137 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1138 {
1139 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1140 TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1141
1142 assert(tile < MapSize());
1143
1144 if (cur_rb == ROAD_NONE) {
1145 /* Tile has no road. First reset the status counter
1146 * to say that this is the last iteration. */
1147 _grow_town_result = GROWTH_SEARCH_STOPPED;
1148
1149 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1150 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
1151
1152 /* Remove hills etc */
1153 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1154
1155 /* Is a road allowed here? */
1156 switch (t1->layout) {
1157 default: NOT_REACHED();
1158
1159 case TL_3X3_GRID:
1160 case TL_2X2_GRID:
1161 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1162 if (rcmd == ROAD_NONE) return;
1163 break;
1164
1165 case TL_BETTER_ROADS:
1166 case TL_ORIGINAL:
1167 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1168
1169 DiagDirection source_dir = ReverseDiagDir(target_dir);
1170
1171 if (Chance16(1, 4)) {
1172 /* Randomize a new target dir */
1173 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1174 }
1175
1176 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1177 /* A road is not allowed to continue the randomized road,
1178 * return if the road we're trying to build is curved. */
1179 if (target_dir != ReverseDiagDir(source_dir)) return;
1180
1181 /* Return if neither side of the new road is a house */
1182 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
1183 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
1184 return;
1185 }
1186
1187 /* That means that the road is only allowed if there is a house
1188 * at any side of the new road. */
1189 }
1190
1191 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1192 break;
1193 }
1194
1195 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1196 /* Continue building on a partial road.
1197 * Should be always OK, so we only generate
1198 * the fitting RoadBits */
1199 _grow_town_result = GROWTH_SEARCH_STOPPED;
1200
1201 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1202
1203 switch (t1->layout) {
1204 default: NOT_REACHED();
1205
1206 case TL_3X3_GRID:
1207 case TL_2X2_GRID:
1208 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1209 break;
1210
1211 case TL_BETTER_ROADS:
1212 case TL_ORIGINAL:
1213 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1214 break;
1215 }
1216 } else {
1217 bool allow_house = true; // Value which decides if we want to construct a house
1218
1219 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1220 * it is the starting tile. Half the time, we stay on this side then.*/
1221 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1222 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1223 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1224 }
1225 return;
1226 }
1227
1228 /* Possibly extend the road in a direction.
1229 * Randomize a direction and if it has a road, bail out. */
1230 target_dir = RandomDiagDir();
1231 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
1232
1233 /* This is the tile we will reach if we extend to this direction. */
1234 TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1235
1236 /* Don't walk into water. */
1237 if (HasTileWaterGround(house_tile)) return;
1238
1239 if (!IsValidTile(house_tile)) return;
1240
1241 if (_settings_game.economy.allow_town_roads || _generating_world) {
1242 switch (t1->layout) {
1243 default: NOT_REACHED();
1244
1245 case TL_3X3_GRID: // Use 2x2 grid afterwards!
1246 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1247 FALLTHROUGH;
1248
1249 case TL_2X2_GRID:
1250 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1251 allow_house = (rcmd & DiagDirToRoadBits(target_dir)) == ROAD_NONE;
1252 break;
1253
1254 case TL_BETTER_ROADS: // Use original afterwards!
1255 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1256 FALLTHROUGH;
1257
1258 case TL_ORIGINAL:
1259 /* Allow a house at the edge. 60% chance or
1260 * always ok if no road allowed. */
1261 rcmd = DiagDirToRoadBits(target_dir);
1262 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1263 break;
1264 }
1265 }
1266
1267 if (allow_house) {
1268 /* Build a house, but not if there already is a house there. */
1269 if (!IsTileType(house_tile, MP_HOUSE)) {
1270 /* Level the land if possible */
1271 if (Chance16(1, 6)) LevelTownLand(house_tile);
1272
1273 /* And build a house.
1274 * Set result to -1 if we managed to build it. */
1275 if (BuildTownHouse(t1, house_tile)) {
1276 _grow_town_result = GROWTH_SUCCEED;
1277 }
1278 }
1279 return;
1280 }
1281
1282 _grow_town_result = GROWTH_SEARCH_STOPPED;
1283 }
1284
1285 /* Return if a water tile */
1286 if (HasTileWaterGround(tile)) return;
1287
1288 /* Make the roads look nicer */
1289 rcmd = CleanUpRoadBits(tile, rcmd);
1290 if (rcmd == ROAD_NONE) return;
1291
1292 /* Only use the target direction for bridges to ensure they're connected.
1293 * The target_dir is as computed previously according to town layout, so
1294 * it will match it perfectly. */
1295 if (GrowTownWithBridge(t1, tile, target_dir)) return;
1296
1297 GrowTownWithRoad(t1, tile, rcmd);
1298 }
1299
1307 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1308 {
1309 TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1310 if (!IsValidTile(target_tile)) return false;
1311 if (HasTileWaterGround(target_tile)) return false;
1312
1313 RoadBits target_rb = GetTownRoadBits(target_tile);
1314 if (_settings_game.economy.allow_town_roads || _generating_world) {
1315 /* Check whether a road connection exists or can be build. */
1316 switch (GetTileType(target_tile)) {
1317 case MP_ROAD:
1318 return target_rb != ROAD_NONE;
1319
1320 case MP_STATION:
1321 return IsDriveThroughStopTile(target_tile);
1322
1323 case MP_TUNNELBRIDGE:
1324 return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1325
1326 case MP_HOUSE:
1327 case MP_INDUSTRY:
1328 case MP_OBJECT:
1329 return false;
1330
1331 default:
1332 /* Checked for void and water earlier */
1333 return true;
1334 }
1335 } else {
1336 /* Check whether a road connection already exists,
1337 * and it leads somewhere else. */
1338 RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1339 return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1340 }
1341 }
1342
1349 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1350 {
1351 /* Special case.
1352 * @see GrowTownInTile Check the else if
1353 */
1354 DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1355
1356 assert(tile < MapSize());
1357
1358 /* Number of times to search.
1359 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1360 * them a little handicap. */
1361 switch (t->layout) {
1362 case TL_BETTER_ROADS:
1363 _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1364 break;
1365
1366 case TL_3X3_GRID:
1367 case TL_2X2_GRID:
1368 _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1369 break;
1370
1371 default:
1372 _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1373 break;
1374 }
1375
1376 do {
1377 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1378
1379 /* Try to grow the town from this point */
1380 GrowTownInTile(&tile, cur_rb, target_dir, t);
1381 if (_grow_town_result == GROWTH_SUCCEED) return true;
1382
1383 /* Exclude the source position from the bitmask
1384 * and return if no more road blocks available */
1385 if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1386 if (cur_rb == ROAD_NONE) return false;
1387
1388 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1389 /* Only build in the direction away from the tunnel or bridge. */
1390 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1391 } else {
1392 /* Select a random bit from the blockmask, walk a step
1393 * and continue the search from there. */
1394 do {
1395 if (cur_rb == ROAD_NONE) return false;
1396 RoadBits target_bits;
1397 do {
1398 target_dir = RandomDiagDir();
1399 target_bits = DiagDirToRoadBits(target_dir);
1400 } while (!(cur_rb & target_bits));
1401 cur_rb &= ~target_bits;
1402 } while (!CanFollowRoad(tile, target_dir));
1403 }
1404 tile = TileAddByDiagDir(tile, target_dir);
1405
1406 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1407 /* Don't allow building over roads of other cities */
1408 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1409 return false;
1410 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1411 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1412 * owner :) (happy happy happy road now) */
1413 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
1414 SetTownIndex(tile, t->index);
1415 }
1416 }
1417
1418 /* Max number of times is checked. */
1419 } while (--_grow_town_result >= 0);
1420
1421 return false;
1422 }
1423
1431 static RoadBits GenRandomRoadBits()
1432 {
1433 uint32 r = Random();
1434 uint a = GB(r, 0, 2);
1435 uint b = GB(r, 8, 2);
1436 if (a == b) b ^= 2;
1437 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1438 }
1439
1445 static bool GrowTown(Town *t)
1446 {
1447 static const TileIndexDiffC _town_coord_mod[] = {
1448 {-1, 0},
1449 { 1, 1},
1450 { 1, -1},
1451 {-1, -1},
1452 {-1, 0},
1453 { 0, 2},
1454 { 2, 0},
1455 { 0, -2},
1456 {-1, -1},
1457 {-2, 2},
1458 { 2, 2},
1459 { 2, -2},
1460 { 0, 0}
1461 };
1462
1463 /* Current "company" is a town */
1464 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1465
1466 TileIndex tile = t->xy; // The tile we are working with ATM
1467
1468 /* Find a road that we can base the construction on. */
1469 const TileIndexDiffC *ptr;
1470 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1471 if (GetTownRoadBits(tile) != ROAD_NONE) {
1472 bool success = GrowTownAtRoad(t, tile);
1473 cur_company.Restore();
1474 return success;
1475 }
1476 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1477 }
1478
1479 /* No road available, try to build a random road block by
1480 * clearing some land and then building a road there. */
1481 if (_settings_game.economy.allow_town_roads || _generating_world) {
1482 tile = t->xy;
1483 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1484 /* Only work with plain land that not already has a house */
1485 if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1486 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1487 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1488 cur_company.Restore();
1489 return true;
1490 }
1491 }
1492 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1493 }
1494 }
1495
1496 cur_company.Restore();
1497 return false;
1498 }
1499
1500 void UpdateTownRadius(Town *t)
1501 {
1502 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1503 { 4, 0, 0, 0, 0}, // 0
1504 { 16, 0, 0, 0, 0},
1505 { 25, 0, 0, 0, 0},
1506 { 36, 0, 0, 0, 0},
1507 { 49, 0, 4, 0, 0},
1508 { 64, 0, 4, 0, 0}, // 20
1509 { 64, 0, 9, 0, 1},
1510 { 64, 0, 9, 0, 4},
1511 { 64, 0, 16, 0, 4},
1512 { 81, 0, 16, 0, 4},
1513 { 81, 0, 16, 0, 4}, // 40
1514 { 81, 0, 25, 0, 9},
1515 { 81, 36, 25, 0, 9},
1516 { 81, 36, 25, 16, 9},
1517 { 81, 49, 0, 25, 9},
1518 { 81, 64, 0, 25, 9}, // 60
1519 { 81, 64, 0, 36, 9},
1520 { 81, 64, 0, 36, 16},
1521 {100, 81, 0, 49, 16},
1522 {100, 81, 0, 49, 25},
1523 {121, 81, 0, 49, 25}, // 80
1524 {121, 81, 0, 49, 25},
1525 {121, 81, 0, 49, 36}, // 88
1526 };
1527
1528 if (t->cache.num_houses < 92) {
1529 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));
1530 } else {
1531 int mass = t->cache.num_houses / 8;
1532 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1533 * The offsets are to make sure the radii do not decrease in size when going from the table
1534 * to the calculated value.*/
1535 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1536 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1537 t->cache.squared_town_zone_radius[2] = 0;
1538 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1539 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1540 }
1541 }
1542
1543 void UpdateTownMaxPass(Town *t)
1544 {
1545 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1546 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1547 }
1548
1560 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1561 {
1562 t->xy = tile;
1563 t->cache.num_houses = 0;
1564 t->time_until_rebuild = 10;
1565 UpdateTownRadius(t);
1566 t->flags = 0;
1567 t->cache.population = 0;
1568 t->grow_counter = 0;
1569 t->growth_rate = 250;
1570
1571 /* Set the default cargo requirement for town growth */
1572 switch (_settings_game.game_creation.landscape) {
1573 case LT_ARCTIC:
1574 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
1575 break;
1576
1577 case LT_TROPIC:
1578 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
1579 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
1580 break;
1581 }
1582
1583 t->fund_buildings_months = 0;
1584
1585 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1586
1587 t->have_ratings = 0;
1588 t->exclusivity = INVALID_COMPANY;
1589 t->exclusive_counter = 0;
1590 t->statues = 0;
1591
1592 extern int _nb_orig_names;
1593 if (_settings_game.game_creation.town_name < _nb_orig_names) {
1594 /* Original town name */
1595 t->townnamegrfid = 0;
1596 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1597 } else {
1598 /* Newgrf town name */
1599 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1600 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1601 }
1602 t->townnameparts = townnameparts;
1603
1604 t->UpdateVirtCoord();
1605 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
1606
1607 t->InitializeLayout(layout);
1608
1609 t->larger_town = city;
1610
1611 int x = (int)size * 16 + 3;
1612 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1613 /* Don't create huge cities when founding town in-game */
1614 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1615
1616 t->cache.num_houses += x;
1617 UpdateTownRadius(t);
1618
1619 int i = x * 4;
1620 do {
1621 GrowTown(t);
1622 } while (--i);
1623
1624 t->cache.num_houses -= x;
1625 UpdateTownRadius(t);
1626 UpdateTownMaxPass(t);
1627 UpdateAirportsNoise();
1628 }
1629
1635 static CommandCost TownCanBePlacedHere(TileIndex tile)
1636 {
1637 /* Check if too close to the edge of map */
1638 if (DistanceFromEdge(tile) < 12) {
1639 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1640 }
1641
1642 /* Check distance to all other towns. */
1643 if (IsCloseToTown(tile, 20)) {
1644 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1645 }
1646
1647 /* Can only build on clear flat areas, possibly with trees. */
1648 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1649 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1650 }
1651
1652 return CommandCost(EXPENSES_OTHER);
1653 }
1654
1660 static bool IsUniqueTownName(const char *name)
1661 {
1662 const Town *t;
1663
1664 FOR_ALL_TOWNS(t) {
1665 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1666 }
1667
1668 return true;
1669 }
1670
1683 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1684 {
1685 TownSize size = Extract<TownSize, 0, 2>(p1);
1686 bool city = HasBit(p1, 2);
1687 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1688 TownNameParams par(_settings_game.game_creation.town_name);
1689 bool random = HasBit(p1, 6);
1690 uint32 townnameparts = p2;
1691
1692 if (size >= TSZ_END) return CMD_ERROR;
1693 if (layout >= NUM_TLS) return CMD_ERROR;
1694
1695 /* Some things are allowed only in the scenario editor and for game scripts. */
1696 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1697 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
1698 if (size == TSZ_LARGE) return CMD_ERROR;
1699 if (random) return CMD_ERROR;
1700 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
1701 return CMD_ERROR;
1702 }
1703 } else if (_current_company == OWNER_DEITY && random) {
1704 /* Random parameter is not allowed for Game Scripts. */
1705 return CMD_ERROR;
1706 }
1707
1708 if (StrEmpty(text)) {
1709 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1710 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1711 } else {
1712 /* If name is not empty, it has to be unique custom name */
1713 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
1714 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1715 }
1716
1717 /* Allocate town struct */
1718 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1719
1720 if (!random) {
1721 CommandCost ret = TownCanBePlacedHere(tile);
1722 if (ret.Failed()) return ret;
1723 }
1724
1725 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1726 /* multidimensional arrays have to have defined length of non-first dimension */
1727 assert_compile(lengthof(price_mult[0]) == 4);
1728
1729 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1730 byte mult = price_mult[city][size];
1731
1732 cost.MultiplyCost(mult);
1733
1734 /* Create the town */
1735 if (flags & DC_EXEC) {
1736 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1737 _additional_cash_required = cost.GetCost();
1738 return CommandCost(EXPENSES_OTHER);
1739 }
1740
1741 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1742 UpdateNearestTownForRoadTiles(true);
1743 Town *t;
1744 if (random) {
1745 t = CreateRandomTown(20, townnameparts, size, city, layout);
1746 if (t == NULL) {
1747 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1748 } else {
1749 _new_town_id = t->index;
1750 }
1751 } else {
1752 t = new Town(tile);
1753 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1754 }
1755 UpdateNearestTownForRoadTiles(false);
1756 old_generating_world.Restore();
1757
1758 if (t != NULL && !StrEmpty(text)) {
1759 t->name = stredup(text);
1760 t->UpdateVirtCoord();
1761 }
1762
1763 if (_game_mode != GM_EDITOR) {
1764 /* 't' can't be NULL since 'random' is false outside scenedit */
1765 assert(!random);
1766 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1767 SetDParam(0, _current_company);
1768 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1769
1770 char *cn = stredup(company_name);
1771 SetDParamStr(0, cn);
1772 SetDParam(1, t->index);
1773
1774 AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1775 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1776 Game::NewEvent(new ScriptEventTownFounded(t->index));
1777 }
1778 }
1779 return cost;
1780 }
1781
1791 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
1792 {
1793 switch (layout) {
1794 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1795 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1796 default: return tile;
1797 }
1798 }
1799
1809 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1810 {
1811 switch (layout) {
1812 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1813 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1814 default: return true;
1815 }
1816 }
1817
1821 struct SpotData {
1822 TileIndex tile;
1823 uint max_dist;
1824 TownLayout layout;
1825 };
1826
1843 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1844 {
1845 SpotData *sp = (SpotData*)user_data;
1846 uint dist = GetClosestWaterDistance(tile, true);
1847
1848 if (IsTileType(tile, MP_CLEAR) &&
1849 IsTileFlat(tile) &&
1850 IsTileAlignedToGrid(tile, sp->layout) &&
1851 dist > sp->max_dist) {
1852 sp->tile = tile;
1853 sp->max_dist = dist;
1854 }
1855
1856 return false;
1857 }
1858
1865 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1866 {
1867 return IsTileType(tile, MP_CLEAR);
1868 }
1869
1882 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
1883 {
1884 SpotData sp = { INVALID_TILE, 0, layout };
1885
1886 TileIndex coast = tile;
1887 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
1888 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1889 return sp.tile;
1890 }
1891
1892 /* if we get here just give up */
1893 return INVALID_TILE;
1894 }
1895
1896 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1897 {
1898 assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1899
1900 if (!Town::CanAllocateItem()) return NULL;
1901
1902 do {
1903 /* Generate a tile index not too close from the edge */
1904 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1905
1906 /* if we tried to place the town on water, slide it over onto
1907 * the nearest likely-looking spot */
1908 if (IsTileType(tile, MP_WATER)) {
1909 tile = FindNearestGoodCoastalTownSpot(tile, layout);
1910 if (tile == INVALID_TILE) continue;
1911 }
1912
1913 /* Make sure town can be placed here */
1914 if (TownCanBePlacedHere(tile).Failed()) continue;
1915
1916 /* Allocate a town struct */
1917 Town *t = new Town(tile);
1918
1919 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
1920
1921 /* if the population is still 0 at the point, then the
1922 * placement is so bad it couldn't grow at all */
1923 if (t->cache.population > 0) return t;
1924
1925 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1926 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
1927 cur_company.Restore();
1928 assert(rc.Succeeded());
1929
1930 /* We already know that we can allocate a single town when
1931 * entering this function. However, we create and delete
1932 * a town which "resets" the allocation checks. As such we
1933 * need to check again when assertions are enabled. */
1934 assert(Town::CanAllocateItem());
1935 } while (--attempts != 0);
1936
1937 return NULL;
1938 }
1939
1940 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
1941
1949 bool GenerateTowns(TownLayout layout)
1950 {
1951 uint current_number = 0;
1952 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
1953 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
1954 total = min(TownPool::MAX_SIZE, total);
1955 uint32 townnameparts;
1956 TownNames town_names;
1957
1958 SetGeneratingWorldProgress(GWP_TOWN, total);
1959
1960 /* First attempt will be made at creating the suggested number of towns.
1961 * Note that this is really a suggested value, not a required one.
1962 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
1963 do {
1964 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
1965 IncreaseGeneratingWorldProgress(GWP_TOWN);
1966 /* Get a unique name for the town. */
1967 if (!GenerateTownName(&townnameparts, &town_names)) continue;
1968 /* try 20 times to create a random-sized town for the first loop. */
1969 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
1970 } while (--total);
1971
1972 town_names.clear();
1973
1974 if (current_number != 0) return true;
1975
1976 /* If current_number is still zero at this point, it means that not a single town has been created.
1977 * So give it a last try, but now more aggressive */
1978 if (GenerateTownName(&townnameparts) &&
1979 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
1980 return true;
1981 }
1982
1983 /* If there are no towns at all and we are generating new game, bail out */
1984 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
1985 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
1986 }
1987
1988 return false; // we are still without a town? we failed, simply
1989 }
1990
1991
1998 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
1999 {
2000 uint dist = DistanceSquare(tile, t->xy);
2001
2002 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2003
2004 HouseZonesBits smallest = HZB_TOWN_EDGE;
2005 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2006 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2007 }
2008
2009 return smallest;
2010 }
2011
2022 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2023 {
2024 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
2025
2026 assert(cc.Succeeded());
2027
2028 IncreaseBuildingCount(t, type);
2029 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2030 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2031
2032 MarkTileDirtyByTile(tile);
2033 }
2034
2035
2046 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2047 {
2048 BuildingFlags size = HouseSpec::Get(type)->building_flags;
2049
2050 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2051 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2052 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2053 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2054 }
2055
2056
2064 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2065 {
2066 /* cannot build on these slopes... */
2067 Slope slope = GetTileSlope(tile);
2068 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2069
2070 /* building under a bridge? */
2071 if (IsBridgeAbove(tile)) return false;
2072
2073 /* can we clear the land? */
2074 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2075 }
2076
2077
2086 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2087 {
2088 if (!CanBuildHouseHere(tile, noslope)) return false;
2089
2090 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2091 if (GetTileMaxZ(tile) != z) return false;
2092
2093 return true;
2094 }
2095
2096
2105 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2106 {
2107 /* we need to check this tile too because we can be at different tile now */
2108 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2109
2110 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2111 tile += TileOffsByDiagDir(d);
2112 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2113 }
2114
2115 return true;
2116 }
2117
2118
2126 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2127 {
2128 /* Allow towns everywhere when we don't build roads */
2129 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2130
2131 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2132
2133 switch (t->layout) {
2134 case TL_2X2_GRID:
2135 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2136 break;
2137
2138 case TL_3X3_GRID:
2139 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2140 break;
2141
2142 default:
2143 break;
2144 }
2145
2146 return true;
2147 }
2148
2149
2157 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2158 {
2159 /* Allow towns everywhere when we don't build roads */
2160 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2161
2162 /* Compute relative position of tile. (Positive offsets are towards north) */
2163 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2164
2165 switch (t->layout) {
2166 case TL_2X2_GRID:
2167 grid_pos.x %= 3;
2168 grid_pos.y %= 3;
2169 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2170 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2171 break;
2172
2173 case TL_3X3_GRID:
2174 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2175 break;
2176
2177 default:
2178 break;
2179 }
2180
2181 return true;
2182 }
2183
2184
2194 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2195 {
2196 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2197
2198 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2199 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2200
2201 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2202 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2203 *tile = tile2;
2204 return true;
2205 }
2206
2207 return false;
2208 }
2209
2210
2219 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2220 {
2221 TileIndex tile2 = *tile;
2222
2223 for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2224 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2225 *tile = tile2;
2226 return true;
2227 }
2228 if (d == DIAGDIR_END) break;
2229 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2230 }
2231
2232 return false;
2233 }
2234
2235
2242 static bool BuildTownHouse(Town *t, TileIndex tile)
2243 {
2244 /* forbidden building here by town layout */
2245 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2246
2247 /* no house allowed at all, bail out */
2248 if (!CanBuildHouseHere(tile, false)) return false;
2249
2250 Slope slope = GetTileSlope(tile);
2251 int maxz = GetTileMaxZ(tile);
2252
2253 /* Get the town zone type of the current tile, as well as the climate.
2254 * This will allow to easily compare with the specs of the new house to build */
2255 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2256
2257 /* Above snow? */
2258 int land = _settings_game.game_creation.landscape;
2259 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2260
2261 uint bitmask = (1 << rad) + (1 << (land + 12));
2262
2263 /* bits 0-4 are used
2264 * bits 11-15 are used
2265 * bits 5-10 are not used. */
2266 HouseID houses[NUM_HOUSES];
2267 uint num = 0;
2268 uint probs[NUM_HOUSES];
2269 uint probability_max = 0;
2270
2271 /* Generate a list of all possible houses that can be built. */
2272 for (uint i = 0; i < NUM_HOUSES; i++) {
2273 const HouseSpec *hs = HouseSpec::Get(i);
2274
2275 /* Verify that the candidate house spec matches the current tile status */
2276 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2277
2278 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2279 if (hs->class_id != HOUSE_NO_CLASS) {
2280 /* id_count is always <= class_count, so it doesn't need to be checked */
2281 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2282 } else {
2283 /* If the house has no class, check id_count instead */
2284 if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2285 }
2286
2287 /* Without NewHouses, all houses have probability '1' */
2288 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2289 probability_max += cur_prob;
2290 probs[num] = cur_prob;
2291 houses[num++] = (HouseID)i;
2292 }
2293
2294 TileIndex baseTile = tile;
2295
2296 while (probability_max > 0) {
2297 /* Building a multitile building can change the location of tile.
2298 * The building would still be built partially on that tile, but
2299 * its northern tile would be elsewhere. However, if the callback
2300 * fails we would be basing further work from the changed tile.
2301 * So a next 1x1 tile building could be built on the wrong tile. */
2302 tile = baseTile;
2303
2304 uint r = RandomRange(probability_max);
2305 uint i;
2306 for (i = 0; i < num; i++) {
2307 if (probs[i] > r) break;
2308 r -= probs[i];
2309 }
2310
2311 HouseID house = houses[i];
2312 probability_max -= probs[i];
2313
2314 /* remove tested house from the set */
2315 num--;
2316 houses[i] = houses[num];
2317 probs[i] = probs[num];
2318
2319 const HouseSpec *hs = HouseSpec::Get(house);
2320
2321 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
2322 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2323 continue;
2324 }
2325
2326 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2327
2328 /* Special houses that there can be only one of. */
2329 uint oneof = 0;
2330
2331 if (hs->building_flags & BUILDING_IS_CHURCH) {
2332 SetBit(oneof, TOWN_HAS_CHURCH);
2333 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2334 SetBit(oneof, TOWN_HAS_STADIUM);
2335 }
2336
2337 if (t->flags & oneof) continue;
2338
2339 /* Make sure there is no slope? */
2340 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2341 if (noslope && slope != SLOPE_FLAT) continue;
2342
2343 if (hs->building_flags & TILE_SIZE_2x2) {
2344 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2345 } else if (hs->building_flags & TILE_SIZE_2x1) {
2346 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2347 } else if (hs->building_flags & TILE_SIZE_1x2) {
2348 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2349 } else {
2350 /* 1x1 house checks are already done */
2351 }
2352
2353 byte random_bits = Random();
2354
2355 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
2356 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2357 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2358 }
2359
2360 /* build the house */
2361 t->cache.num_houses++;
2362
2363 /* Special houses that there can be only one of. */
2364 t->flags |= oneof;
2365
2366 byte construction_counter = 0;
2367 byte construction_stage = 0;
2368
2369 if (_generating_world || _game_mode == GM_EDITOR) {
2370 uint32 r = Random();
2371
2372 construction_stage = TOWN_HOUSE_COMPLETED;
2373 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2374
2375 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2376 ChangePopulation(t, hs->population);
2377 } else {
2378 construction_counter = GB(r, 2, 2);
2379 }
2380 }
2381
2382 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2383 UpdateTownRadius(t);
2384 UpdateTownCargoes(t, tile);
2385
2386 return true;
2387 }
2388
2389 return false;
2390 }
2391
2398 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2399 {
2400 assert(IsTileType(tile, MP_HOUSE));
2401 DecreaseBuildingCount(t, house);
2402 DoClearSquare(tile);
2403 DeleteAnimatedTile(tile);
2404
2405 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2406 }
2407
2415 TileIndexDiff GetHouseNorthPart(HouseID &house)
2416 {
2417 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2418 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2419 house--;
2420 return TileDiffXY(-1, 0);
2421 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2422 house--;
2423 return TileDiffXY(0, -1);
2424 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2425 house -= 2;
2426 return TileDiffXY(-1, 0);
2427 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2428 house -= 3;
2429 return TileDiffXY(-1, -1);
2430 }
2431 }
2432 return 0;
2433 }
2434
2435 void ClearTownHouse(Town *t, TileIndex tile)
2436 {
2437 assert(IsTileType(tile, MP_HOUSE));
2438
2439 HouseID house = GetHouseType(tile);
2440
2441 /* need to align the tile to point to the upper left corner of the house */
2442 tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2443
2444 const HouseSpec *hs = HouseSpec::Get(house);
2445
2446 /* Remove population from the town if the house is finished. */
2447 if (IsHouseCompleted(tile)) {
2448 ChangePopulation(t, -hs->population);
2449 }
2450
2451 t->cache.num_houses--;
2452
2453 /* Clear flags for houses that only may exist once/town. */
2454 if (hs->building_flags & BUILDING_IS_CHURCH) {
2455 ClrBit(t->flags, TOWN_HAS_CHURCH);
2456 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2457 ClrBit(t->flags, TOWN_HAS_STADIUM);
2458 }
2459
2460 /* Do the actual clearing of tiles */
2461 uint eflags = hs->building_flags;
2462 DoClearTownHouseHelper(tile, t, house);
2463 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2464 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2465 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2466
2467 UpdateTownRadius(t);
2468
2469 /* Update cargo acceptance. */
2470 UpdateTownCargoes(t, tile);
2471 }
2472
2482 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2483 {
2484 Town *t = Town::GetIfValid(p1);
2485 if (t == NULL) return CMD_ERROR;
2486
2487 bool reset = StrEmpty(text);
2488
2489 if (!reset) {
2490 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
2491 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2492 }
2493
2494 if (flags & DC_EXEC) {
2495 free(t->name);
2496 t->name = reset ? NULL : stredup(text);
2497
2498 t->UpdateVirtCoord();
2499 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
2500 UpdateAllStationVirtCoords();
2501 }
2502 return CommandCost();
2503 }
2504
2510 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
2511 {
2512 const CargoSpec *cs;
2513 FOR_ALL_CARGOSPECS(cs) {
2514 if (cs->town_effect == effect) return cs;
2515 }
2516 return NULL;
2517 }
2518
2519 static void UpdateTownGrowRate(Town *t);
2520
2532 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2533 {
2534 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2535
2536 TownEffect te = (TownEffect)GB(p1, 16, 8);
2537 if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2538
2539 uint16 index = GB(p1, 0, 16);
2540 Town *t = Town::GetIfValid(index);
2541 if (t == NULL) return CMD_ERROR;
2542
2543 /* Validate if there is a cargo which is the requested TownEffect */
2544 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2545 if (cargo == NULL) return CMD_ERROR;
2546
2547 if (flags & DC_EXEC) {
2548 t->goal[te] = p2;
2549 UpdateTownGrowRate(t);
2550 InvalidateWindowData(WC_TOWN_VIEW, index);
2551 }
2552
2553 return CommandCost();
2554 }
2555
2565 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2566 {
2567 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2568 Town *t = Town::GetIfValid(p1);
2569 if (t == NULL) return CMD_ERROR;
2570
2571 if (flags & DC_EXEC) {
2572 free(t->text);
2573 t->text = StrEmpty(text) ? NULL : stredup(text);
2574 InvalidateWindowData(WC_TOWN_VIEW, p1);
2575 }
2576
2577 return CommandCost();
2578 }
2579
2589 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2590 {
2591 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2592 if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
2593 if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2594
2595 Town *t = Town::GetIfValid(p1);
2596 if (t == NULL) return CMD_ERROR;
2597
2598 if (flags & DC_EXEC) {
2599 if (p2 == 0) {
2600 /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2601 t->growth_rate = 0;
2602 } else {
2603 uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
2604 if (t->grow_counter >= old_rate) {
2605 /* This also catches old_rate == 0 */
2606 t->grow_counter = p2;
2607 } else {
2608 /* Scale grow_counter, so half finished houses stay half finished */
2609 t->grow_counter = t->grow_counter * p2 / old_rate;
2610 }
2611 t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
2612 }
2613 UpdateTownGrowRate(t);
2614 InvalidateWindowData(WC_TOWN_VIEW, p1);
2615 }
2616
2617 return CommandCost();
2618 }
2619
2629 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2630 {
2631 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2632 Town *t = Town::GetIfValid(p1);
2633 if (t == NULL) return CMD_ERROR;
2634
2635 if (flags & DC_EXEC) {
2636 /* The more houses, the faster we grow */
2637 if (p2 == 0) {
2638 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2639 t->cache.num_houses += amount;
2640 UpdateTownRadius(t);
2641
2642 uint n = amount * 10;
2643 do GrowTown(t); while (--n);
2644
2645 t->cache.num_houses -= amount;
2646 } else {
2647 for (; p2 > 0; p2--) {
2648 /* Try several times to grow, as we are really suppose to grow */
2649 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2650 }
2651 }
2652 UpdateTownRadius(t);
2653
2654 UpdateTownMaxPass(t);
2655 }
2656
2657 return CommandCost();
2658 }
2659
2669 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2670 {
2671 if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2672 Town *t = Town::GetIfValid(p1);
2673 if (t == NULL) return CMD_ERROR;
2674
2675 /* Stations refer to towns. */
2676 const Station *st;
2677 FOR_ALL_STATIONS(st) {
2678 if (st->town == t) {
2679 /* Non-oil rig stations are always a problem. */
2680 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2681 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2682 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2683 if (ret.Failed()) return ret;
2684 }
2685 }
2686
2687 /* Depots refer to towns. */
2688 const Depot *d;
2689 FOR_ALL_DEPOTS(d) {
2690 if (d->town == t) return CMD_ERROR;
2691 }
2692
2693 /* Check all tiles for town ownership. */
2694 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2695 bool try_clear = false;
2696 switch (GetTileType(tile)) {
2697 case MP_ROAD:
2698 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2699 break;
2700
2701 case MP_TUNNELBRIDGE:
2702 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2703 break;
2704
2705 case MP_HOUSE:
2706 try_clear = GetTownIndex(tile) == t->index;
2707 break;
2708
2709 case MP_INDUSTRY:
2710 try_clear = Industry::GetByTile(tile)->town == t;
2711 break;
2712
2713 case MP_OBJECT:
2714 if (Town::GetNumItems() == 1) {
2715 /* No towns will be left, remove it! */
2716 try_clear = true;
2717 } else {
2718 Object *o = Object::GetByTile(tile);
2719 if (o->town == t) {
2720 if (o->type == OBJECT_STATUE) {
2721 /* Statue... always remove. */
2722 try_clear = true;
2723 } else {
2724 /* Tell to find a new town. */
2725 if (flags & DC_EXEC) o->town = NULL;
2726 }
2727 }
2728 }
2729 break;
2730
2731 default:
2732 break;
2733 }
2734 if (try_clear) {
2735 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2736 if (ret.Failed()) return ret;
2737 }
2738 }
2739
2740 /* The town destructor will delete the other things related to the town. */
2741 if (flags & DC_EXEC) delete t;
2742
2743 return CommandCost();
2744 }
2745
2750 const byte _town_action_costs[TACT_COUNT] = {
2751 2, 4, 9, 35, 48, 53, 117, 175
2752 };
2753
2754 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2755 {
2756 if (flags & DC_EXEC) {
2757 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2758 }
2759 return CommandCost();
2760 }
2761
2762 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2763 {
2764 if (flags & DC_EXEC) {
2765 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2766 }
2767 return CommandCost();
2768 }
2769
2770 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2771 {
2772 if (flags & DC_EXEC) {
2773 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2774 }
2775 return CommandCost();
2776 }
2777
2778 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2779 {
2780 /* Check if the company is allowed to fund new roads. */
2781 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
2782
2783 if (flags & DC_EXEC) {
2784 t->road_build_months = 6;
2785
2786 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2787 SetDParam(0, _current_company);
2788 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2789
2790 char *cn = stredup(company_name);
2791 SetDParam(0, t->index);
2792 SetDParamStr(1, cn);
2793
2794 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2795 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2796 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2797 }
2798 return CommandCost();
2799 }
2800
2806 static bool TryClearTile(TileIndex tile)
2807 {
2808 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2809 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
2810 cur_company.Restore();
2811 return r.Succeeded();
2812 }
2813
2815 struct StatueBuildSearchData {
2816 TileIndex best_position;
2817 int tile_count;
2818
2819 StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2820 };
2821
2828 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2829 {
2830 static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2831
2832 StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2833 statue_data->tile_count++;
2834
2835 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2836 if (IsSteepSlope(GetTileSlope(tile))) return false;
2837 /* Don't build statues under bridges. */
2838 if (IsBridgeAbove(tile)) return false;
2839
2840 /* A clear-able open space is always preferred. */
2841 if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2842 statue_data->best_position = tile;
2843 return true;
2844 }
2845
2846 bool house = IsTileType(tile, MP_HOUSE);
2847
2848 /* Searching inside the inner circle. */
2849 if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2850 /* Save first house in inner circle. */
2851 if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2852 statue_data->best_position = tile;
2853 }
2854
2855 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2856 return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2857 }
2858
2859 /* Searching outside the circle, just pick the first possible spot. */
2860 statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2861 return house && TryClearTile(tile);
2862 }
2863
2871 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
2872 {
2873 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2874
2875 TileIndex tile = t->xy;
2876 StatueBuildSearchData statue_data(INVALID_TILE, 0);
2877 if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2878
2879 if (flags & DC_EXEC) {
2880 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2881 DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2882 cur_company.Restore();
2883 BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
2884 SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2885 MarkTileDirtyByTile(statue_data.best_position);
2886 }
2887 return CommandCost();
2888 }
2889
2890 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2891 {
2892 /* Check if it's allowed to buy the rights */
2893 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
2894
2895 if (flags & DC_EXEC) {
2896 /* Build next tick */
2897 t->grow_counter = 1;
2898 /* And grow for 3 months */
2899 t->fund_buildings_months = 3;
2900
2901 /* Enable growth (also checking GameScript's opinion) */
2902 UpdateTownGrowRate(t);
2903
2904 SetWindowDirty(WC_TOWN_VIEW, t->index);
2905 }
2906 return CommandCost();
2907 }
2908
2909 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2910 {
2911 /* Check if it's allowed to buy the rights */
2912 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
2913
2914 if (flags & DC_EXEC) {
2915 t->exclusive_counter = 12;
2916 t->exclusivity = _current_company;
2917
2918 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
2919
2920 SetWindowClassesDirty(WC_STATION_VIEW);
2921
2922 /* Spawn news message */
2923 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2924 cni->FillData(Company::Get(_current_company));
2925 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
2926 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
2927 SetDParam(2, t->index);
2928 SetDParamStr(3, cni->company_name);
2929 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
2930 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2931 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2932 }
2933 return CommandCost();
2934 }
2935
2936 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
2937 {
2938 if (flags & DC_EXEC) {
2939 if (Chance16(1, 14)) {
2940 /* set as unwanted for 6 months */
2941 t->unwanted[_current_company] = 6;
2942
2943 /* set all close by station ratings to 0 */
2944 Station *st;
2945 FOR_ALL_STATIONS(st) {
2946 if (st->town == t && st->owner == _current_company) {
2947 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
2948 }
2949 }
2950
2951 /* only show error message to the executing player. All errors are handled command.c
2952 * but this is special, because it can only 'fail' on a DC_EXEC */
2953 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
2954
2955 /* decrease by a lot!
2956 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
2957 * be independent of any cheat settings
2958 */
2959 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
2960 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
2961 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
2962 }
2963 } else {
2964 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
2965 }
2966 }
2967 return CommandCost();
2968 }
2969
2970 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
2971 static TownActionProc * const _town_action_proc[] = {
2972 TownActionAdvertiseSmall,
2973 TownActionAdvertiseMedium,
2974 TownActionAdvertiseLarge,
2975 TownActionRoadRebuild,
2976 TownActionBuildStatue,
2977 TownActionFundBuildings,
2978 TownActionBuyRights,
2979 TownActionBribe
2980 };
2981
2989 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
2990 {
2991 int num = 0;
2992 TownActions buttons = TACT_NONE;
2993
2994 /* Spectators and unwanted have no options */
2995 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
2996
2997 /* Things worth more than this are not shown */
2998 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
2999
3000 /* Check the action bits for validity and
3001 * if they are valid add them */
3002 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3003 const TownActions cur = (TownActions)(1 << i);
3004
3005 /* Is the company not able to bribe ? */
3006 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3007
3008 /* Is the company not able to buy exclusive rights ? */
3009 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3010
3011 /* Is the company not able to fund buildings ? */
3012 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3013
3014 /* Is the company not able to fund local road reconstruction? */
3015 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3016
3017 /* Is the company not able to build a statue ? */
3018 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3019
3020 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3021 buttons |= cur;
3022 num++;
3023 }
3024 }
3025 }
3026
3027 if (nump != NULL) *nump = num;
3028 return buttons;
3029 }
3030
3042 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3043 {
3044 Town *t = Town::GetIfValid(p1);
3045 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3046
3047 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3048
3049 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3050
3051 CommandCost ret = _town_action_proc[p2](t, flags);
3052 if (ret.Failed()) return ret;
3053
3054 if (flags & DC_EXEC) {
3055 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
3056 }
3057
3058 return cost;
3059 }
3060
3061 static void UpdateTownRating(Town *t)
3062 {
3063 /* Increase company ratings if they're low */
3064 const Company *c;
3065 FOR_ALL_COMPANIES(c) {
3066 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3067 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3068 }
3069 }
3070
3071 const Station *st;
3072 FOR_ALL_STATIONS(st) {
3073 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3074 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3075 if (Company::IsValidID(st->owner)) {
3076 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3077 t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3078 }
3079 } else {
3080 if (Company::IsValidID(st->owner)) {
3081 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3082 t->ratings[st->owner] = max(new_rating, INT16_MIN);
3083 }
3084 }
3085 }
3086 }
3087
3088 /* clamp all ratings to valid values */
3089 for (uint i = 0; i < MAX_COMPANIES; i++) {
3090 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3091 }
3092
3093 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3094 }
3095
3096 static void UpdateTownGrowRate(Town *t)
3097 {
3098 ClrBit(t->flags, TOWN_IS_GROWING);
3099 SetWindowDirty(WC_TOWN_VIEW, t->index);
3100
3101 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3102
3103 if (t->fund_buildings_months == 0) {
3104 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3105 for (int i = TE_BEGIN; i < TE_END; i++) {
3106 switch (t->goal[i]) {
3107 case TOWN_GROWTH_WINTER:
3108 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3109 break;
3110 case TOWN_GROWTH_DESERT:
3111 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3112 break;
3113 default:
3114 if (t->goal[i] > t->received[i].old_act) return;
3115 break;
3116 }
3117 }
3118 }
3119
3120 if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
3121 if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
3122 SetWindowDirty(WC_TOWN_VIEW, t->index);
3123 return;
3124 }
3125
3130 static const uint16 _grow_count_values[2][6] = {
3131 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3132 { 320, 420, 300, 220, 160, 100 } // Normal values
3133 };
3134
3135 int n = 0;
3136
3137 const Station *st;
3138 FOR_ALL_STATIONS(st) {
3139 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3140 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3141 n++;
3142 }
3143 }
3144 }
3145
3146 uint16 m;
3147
3148 if (t->fund_buildings_months != 0) {
3149 m = _grow_count_values[0][min(n, 5)];
3150 } else {
3151 m = _grow_count_values[1][min(n, 5)];
3152 if (n == 0 && !Chance16(1, 12)) return;
3153 }
3154
3155 /* Use the normal growth rate values if new buildings have been funded in
3156 * this town and the growth rate is set to none. */
3157 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3158
3159 m >>= growth_multiplier;
3160 if (t->larger_town) m /= 2;
3161
3162 t->growth_rate = m / (t->cache.num_houses / 50 + 1);
3163 t->grow_counter = min(t->growth_rate, t->grow_counter);
3164
3165 SetBit(t->flags, TOWN_IS_GROWING);
3166 SetWindowDirty(WC_TOWN_VIEW, t->index);
3167 }
3168
3169 static void UpdateTownAmounts(Town *t)
3170 {
3171 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3172 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3173 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3174
3175 SetWindowDirty(WC_TOWN_VIEW, t->index);
3176 }
3177
3178 static void UpdateTownUnwanted(Town *t)
3179 {
3180 const Company *c;
3181
3182 FOR_ALL_COMPANIES(c) {
3183 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3184 }
3185 }
3186
3193 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
3194 {
3195 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
3196
3197 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
3198 if (t == NULL) return CommandCost();
3199
3200 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3201
3202 SetDParam(0, t->index);
3203 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3204 }
3205
3214 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
3215 {
3216 Town *t;
3217 uint best = threshold;
3218 Town *best_town = NULL;
3219
3220 FOR_ALL_TOWNS(t) {
3221 uint dist = DistanceManhattan(tile, t->xy);
3222 if (dist < best) {
3223 best = dist;
3224 best_town = t;
3225 }
3226 }
3227
3228 return best_town;
3229 }
3230
3239 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3240 {
3241 switch (GetTileType(tile)) {
3242 case MP_ROAD:
3243 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3244
3245 if (!HasTownOwnedRoad(tile)) {
3246 TownID tid = GetTownIndex(tile);
3247
3248 if (tid == (TownID)INVALID_TOWN) {
3249 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3250 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3251 assert(Town::GetNumItems() == 0);
3252 return NULL;
3253 }
3254
3255 assert(Town::IsValidID(tid));
3256 Town *town = Town::Get(tid);
3257
3258 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3259
3260 return town;
3261 }
3262 FALLTHROUGH;
3263
3264 case MP_HOUSE:
3265 return Town::GetByTile(tile);
3266
3267 default:
3268 return CalcClosestTownFromTile(tile, threshold);
3269 }
3270 }
3271
3272 static bool _town_rating_test = false;
3273 static SmallMap<const Town *, int, 4> _town_test_ratings;
3274
3280 void SetTownRatingTestMode(bool mode)
3281 {
3282 static int ref_count = 0; // Number of times test-mode is switched on.
3283 if (mode) {
3284 if (ref_count == 0) {
3285 _town_test_ratings.Clear();
3286 }
3287 ref_count++;
3288 } else {
3289 assert(ref_count > 0);
3290 ref_count--;
3291 }
3292 _town_rating_test = !(ref_count == 0);
3293 }
3294
3300 static int GetRating(const Town *t)
3301 {
3302 if (_town_rating_test) {
3303 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3304 if (it != _town_test_ratings.End()) {
3305 return it->second;
3306 }
3307 }
3308 return t->ratings[_current_company];
3309 }
3310
3318 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3319 {
3320 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3321 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3322 !Company::IsValidID(_current_company) ||
3323 (_cheats.magic_bulldozer.value && add < 0)) {
3324 return;
3325 }
3326
3327 int rating = GetRating(t);
3328 if (add < 0) {
3329 if (rating > max) {
3330 rating += add;
3331 if (rating < max) rating = max;
3332 }
3333 } else {
3334 if (rating < max) {
3335 rating += add;
3336 if (rating > max) rating = max;
3337 }
3338 }
3339 if (_town_rating_test) {
3340 _town_test_ratings[t] = rating;
3341 } else {
3342 SetBit(t->have_ratings, _current_company);
3343 t->ratings[_current_company] = rating;
3344 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3345 }
3346 }
3347
3355 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
3356 {
3357 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3358 if (t == NULL || !Company::IsValidID(_current_company) ||
3359 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
3360 return CommandCost();
3361 }
3362
3363 /* minimum rating needed to be allowed to remove stuff */
3364 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3365 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3366 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
3367 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
3368 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
3369 };
3370
3371 /* check if you're allowed to remove the road/bridge/tunnel
3372 * owned by a town no removal if rating is lower than ... depends now on
3373 * difficulty setting. Minimum town rating selected by difficulty level
3374 */
3375 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3376
3377 if (GetRating(t) < needed) {
3378 SetDParam(0, t->index);
3379 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3380 }
3381
3382 return CommandCost();
3383 }
3384
3385 void TownsMonthlyLoop()
3386 {
3387 Town *t;
3388
3389 FOR_ALL_TOWNS(t) {
3390 if (t->road_build_months != 0) t->road_build_months--;
3391
3392 if (t->exclusive_counter != 0) {
3393 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3394 }
3395
3396 UpdateTownAmounts(t);
3397 UpdateTownRating(t);
3398 UpdateTownGrowRate(t);
3399 UpdateTownUnwanted(t);
3400 UpdateTownCargoes(t);
3401 }
3402
3403 UpdateTownCargoBitmap();
3404 }
3405
3406 void TownsYearlyLoop()
3407 {
3408 /* Increment house ages */
3409 for (TileIndex t = 0; t < MapSize(); t++) {
3410 if (!IsTileType(t, MP_HOUSE)) continue;
3411 IncrementHouseAge(t);
3412 }
3413 }
3414
3415 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3416 {
3417 if (AutoslopeEnabled()) {
3418 HouseID house = GetHouseType(tile);
3419 GetHouseNorthPart(house); // modifies house to the ID of the north tile
3420 const HouseSpec *hs = HouseSpec::Get(house);
3421
3422 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3423 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3424 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3425 bool allow_terraform = true;
3426
3427 /* Call the autosloping callback per tile, not for the whole building at once. */
3428 house = GetHouseType(tile);
3429 hs = HouseSpec::Get(house);
3430 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
3431 /* If the callback fails, allow autoslope. */
3432 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3433 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3434 }
3435
3436 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3437 }
3438 }
3439
3440 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3441 }
3442
3444 extern const TileTypeProcs _tile_type_town_procs = {
3445 DrawTile_Town, // draw_tile_proc
3446 GetSlopePixelZ_Town, // get_slope_z_proc
3447 ClearTile_Town, // clear_tile_proc
3448 AddAcceptedCargo_Town, // add_accepted_cargo_proc
3449 GetTileDesc_Town, // get_tile_desc_proc
3450 GetTileTrackStatus_Town, // get_tile_track_status_proc
3451 NULL, // click_tile_proc
3452 AnimateTile_Town, // animate_tile_proc
3453 TileLoop_Town, // tile_loop_proc
3454 ChangeTileOwner_Town, // change_tile_owner_proc
3455 AddProducedCargo_Town, // add_produced_cargo_proc
3456 NULL, // vehicle_enter_tile_proc
3457 GetFoundation_Town, // get_foundation_proc
3458 TerraformTile_Town, // terraform_tile_proc
3459 };
3460
3461
3462 HouseSpec _house_specs[NUM_HOUSES];
3463
3464 void ResetHouses()
3465 {
3466 memset(&_house_specs, 0, sizeof(_house_specs));
3467 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3468
3469 /* Reset any overrides that have been set. */
3470 _house_mngr.ResetOverride();
3471 }
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:111
NUM_TLS
Number of town layouts.
Definition: town_type.h:91
strings_func.h
Functions related to OTTD&#39;s strings.
GetTileType
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:89
TOWN_GROWTH_WINTER
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:36
DC_AUTO
don&#39;t allow building on structures
Definition: command_type.h:343
newgrf_debug.h
Functions/types related to NewGRF debugging.
Town::cargo_accepted
AcceptanceMatrix cargo_accepted
Bitmap of cargoes accepted by houses for each 4*4 map square of the town.
Definition: town.h:89
Airport::type
byte type
Type of this airport,.
Definition: station_base.h:309
SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:55
DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:352
GameCreationSettings::custom_town_number
uint16 custom_town_number
manually entered number of towns
Definition: settings_type.h:290
RandomTile
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:425
IsLocalCompany
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
TOWN_GROWTH_TICKS
static const int TOWN_GROWTH_TICKS
cycle duration for towns trying to grow. (this originates from the size of the town array in TTD ...
Definition: date_type.h:39
TownRatingCheckType
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:151
TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition: town.h:167
ST_TOWN
Source/destination is a town.
Definition: cargo_type.h:141
GetHouseAge
static Year GetHouseAge(TileIndex t)
Get the age of the house.
Definition: town_map.h:251
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:117
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:134
UpdateTownCargoes
static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total=true)
Update accepted town cargoes around a specific tile.
Definition: town_cmd.cpp:719
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
Pool::PoolItem<&_town_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:257
ChangePopulation
static void ChangePopulation(Town *t, int mod)
Change the towns population.
Definition: town_cmd.cpp:401
UpdateNearestTownForRoadTiles
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1439
GrowTownWithExtraHouse
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1003
CompanyNewsInformation::FillData
void FillData(const struct Company *c, const struct Company *other=NULL)
Fill the CompanyNewsInformation struct with the required data.
Definition: company_cmd.cpp:749
GrowTownInTile
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1137
GetTropicZone
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:231
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:406
GetTunnelBridgeTransportType
static TransportType GetTunnelBridgeTransportType(TileIndex t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
Definition: tunnelbridge_map.h:41
GetTownRoadBits
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile.
Definition: town_cmd.cpp:816
Town::received
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:80
TileMatrix< uint32, 4 >::GetAreaForTile
static TileArea GetAreaForTile(TileIndex tile, uint extend=0)
Get the area of the matrix square that contains a specific tile.
Definition: tilematrix_type.hpp:94
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:44
EconomySettings::bribe
bool bribe
enable bribing the local authority
Definition: settings_type.h:471
TOWN_HOUSE_COMPLETED
static const byte TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:25
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:70
SLOPE_SE
south and east corner are raised
Definition: slope_type.h:59
GrowTownWithBridge
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1064
VerifyTownName
bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:84
Town::InitializeLayout
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:131
GenerateTowns
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:1949
SLOPE_W
the west corner of the tile is raised
Definition: slope_type.h:52
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3120
GameCreationSettings::landscape
byte landscape
the landscape we&#39;re currently in
Definition: settings_type.h:288
AddAnimatedTile
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet)...
Definition: animated_tile.cpp:51
TL_3X3_GRID
Geometric 3x3 grid algorithm.
Definition: town_type.h:87
CBM_HOUSE_ACCEPT_CARGO
decides accepted types
Definition: newgrf_callbacks.h:324
TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:73
town_land.h
Sprites to use and how to display them for town tiles.
ClearMakeHouseTile
static void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
Clears tile and builds a house or house part.
Definition: town_cmd.cpp:2022
SpotData::layout
TownLayout layout
tells us what kind of town we&#39;re building
Definition: town_cmd.cpp:1824
EconomySettings::found_town
TownFoundingByte found_town
town founding,
Definition: settings_type.h:487
MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:51
SmallMap::Find
const Pair * Find(const T &key) const
Finds given key in this map.
Definition: smallmap_type.hpp:57
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:553
TownCache::squared_town_zone_radius
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:50
RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:63
TileIndexDiff
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:156
IsRoadOwner
static bool IsRoadOwner(TileIndex t, RoadType rt, Owner o)
Check if a specific road type is owned by an owner.
Definition: road_map.h:237
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
GetAvailableMoneyForCommand
Money GetAvailableMoneyForCommand()
Definition: command.cpp:514
TownLayoutAllows2x2HouseHere
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if current town layout allows 2x2 building here.
Definition: town_cmd.cpp:2157
date_func.h
Functions related to dates.
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Object::town
Town * town
Town the object is built in.
Definition: object_base.h:27
Town::fund_buildings_months
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:97
RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:62
Town::exclusivity
CompanyByte exclusivity
which company has exclusivity
Definition: town.h:75
ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:24
CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
Definition: newgrf_callbacks.h:232
TownLayoutAllowsHouseHere
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if current town layout allows building here.
Definition: town_cmd.cpp:2126
Industry::town
Town * town
Nearest town.
Definition: industry.h:41
StatueBuildSearchData::best_position
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:2816
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:123
UpdateAllTownVirtCoords
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:387
Town::flags
byte flags
See TownFlags.
Definition: town.h:66
CMD_TERRAFORM_LAND
terraform a tile
Definition: command_type.h:188
Town::unwanted
uint8 unwanted[MAX_COMPANIES]
how many months companies aren&#39;t wanted by towns (bribe)
Definition: town.h:74
GetCargoTranslation
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:78
_town_rating_test
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3272
MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:45
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:25
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:47
OBJECT_STATUE
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:20
ScaleByMapSize
static uint ScaleByMapSize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map...
Definition: map_func.h:124
ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:61
road_internal.h
Functions used internally by the roads.
DC_NONE
no flag is set
Definition: command_type.h:341
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:56
IsCloseToTown
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:342
GUISettings::population_in_label
bool population_in_label
show the population of a town in his label?
Definition: settings_type.h:110
SmallMap
Implementation of simple mapping class.
Definition: smallmap_type.hpp:42
GenerateTownName
bool GenerateTownName(uint32 *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:122
HasTileWaterGround
static bool HasTileWaterGround(TileIndex t)
Checks whether the tile has water at the ground.
Definition: water_map.h:344
TACT_BUILD_STATUE
Build a statue.
Definition: town.h:206
MakeHouseTile
static void MakeHouseTile(TileIndex t, TownID tid, byte counter, byte stage, HouseID type, byte random_bits)
Make the tile a house.
Definition: town_map.h:354
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:207
ROAD_SW
South-west part.
Definition: road_type.h:58
Town::Town
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:109
TileAddByDiagDir
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:372
HouseSpec::cargo_acceptance
byte cargo_acceptance[3]
acceptance level for the cargo slots
Definition: house.h:107
GetSlopeMaxZ
static int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height) ...
Definition: slope_func.h:162
depot_base.h
Base for all depots (except hangars)
SmallVector< SmallPair< T, U >, S >::Clear
void Clear()
Remove all items from the list.
Definition: smallvec_type.hpp:98
EconomySettings::town_layout
TownLayoutByte town_layout
select town layout,
Definition: settings_type.h:485
HasTileRoadType
static bool HasTileRoadType(TileIndex t, RoadType rt)
Check if a tile has a specific road type.
Definition: road_map.h:188
_town_draw_tile_data
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:29
NT_INDUSTRY_OPEN
Opening of industries.
Definition: news_type.h:41
Industry
Defines the internal data of a functional industry.
Definition: industry.h:39
CMD_LANDSCAPE_CLEAR
demolish a tile
Definition: command_type.h:182
TileDesc
Tile description for the &#39;land area information&#39; tool.
Definition: tile_cmd.h:53
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:543
AI::BroadcastNewEvent
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:258
Pool::PoolItem<&_town_pool >::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
CheckFree2x2Area
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
Definition: town_cmd.cpp:2105
SLOPE_E
the east corner of the tile is raised
Definition: slope_type.h:54
IsSteepSlope
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:38
Town::time_until_rebuild
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:92
CmdDoTownAction
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Do a town action.
Definition: town_cmd.cpp:3042
cmd_helper.h
Helper functions to extract data from command parameters.
TE_WATER
Cargo behaves water-like.
Definition: cargotype.h:31
CMD_BUILD_ROAD
build a "half" road
Definition: command_type.h:203
SpotData
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:1821
TransportedCargoStat::NewMonth
void NewMonth()
Update stats for a new month.
Definition: town_type.h:121
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:37
Town::UpdateVirtCoord
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else) ...
Definition: town_cmd.cpp:374
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:702
Town::cargo_produced
uint32 cargo_produced
Bitmap of all cargoes produced by houses in this town.
Definition: town.h:88
CompanyNewsInformation
Data that needs to be stored for company news messages.
Definition: news_type.h:163
MP_RAILWAY
A railway.
Definition: tile_type.h:44
CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
Definition: newgrf_callbacks.h:116
EconomySettings::dist_local_authority
byte dist_local_authority
distance for town local authority, default 20
Definition: settings_type.h:475
genworld.h
Functions related to world/map generation.
RATING_INITIAL
initial rating
Definition: town_type.h:46
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:84
MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:53
Town::cargo_accepted_total
uint32 cargo_accepted_total
NOSAVE: Bitmap of all cargoes accepted by houses in this town.
Definition: town.h:90
BuildTownHouse
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2242
SLOPE_SW
south and west corner are raised
Definition: slope_type.h:58
CommandCost
Common return value for all commands.
Definition: command_type.h:25
LiftHasDestination
static bool LiftHasDestination(TileIndex t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:84
IsStandardRoadStopTile
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:224
DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:81
ViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport.cpp:1314
HouseSpec::callback_mask
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
GetCommandFlags
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:379
max
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
IsDriveThroughStopTile
static bool IsDriveThroughStopTile(TileIndex t)
Is tile t a drive through road stop station?
Definition: station_map.h:234
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:486
WC_TOWN_DIRECTORY
Town directory; Window numbers:
Definition: window_type.h:249
BaseStation::town
Town * town
The town this station is associated with.
Definition: base_station_base.h:62
HouseID
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:15
CargoPacket::InvalidateAllFrom
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Definition: cargopacket.cpp:129
TownCache::population
uint32 population
Current population of people.
Definition: town.h:47
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
CommandCost::MultiplyCost
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:75
GenRandomRoadBits
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1431
TransportedCargoStat::new_act
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:159
CBM_HOUSE_CARGO_ACCEPTANCE
decides amount of cargo acceptance
Definition: newgrf_callbacks.h:321
FindNearestGoodCoastalTownSpot
static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
Given a spot on the map (presumed to be a water tile), find a good coastal spot to build a city...
Definition: town_cmd.cpp:1882
SmallVector< SmallPair< T, U >, S >::End
const SmallPair< T, U > * End() const
Get the pointer behind the last valid item (const)
Definition: smallvec_type.hpp:292
DeleteSubsidyWith
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:153
SLOPE_FLAT
a flat tile
Definition: slope_type.h:51
_town_test_ratings
static SmallMap< const Town *, int, 4 > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3273
TileInfo::z
int z
Height.
Definition: tile_cmd.h:49
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:472
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
GetLiftDestination
static byte GetLiftDestination(TileIndex t)
Get the current destination for this lift.
Definition: town_map.h:106
RandomRange
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:83
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:31
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:390
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:64
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
IsNeighborRoadTile
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:833
TACT_ROAD_REBUILD
Rebuild the roads.
Definition: town.h:205
BUILDING_IS_HISTORICAL
this house will only appear during town generation in random games, thus the historical ...
Definition: house.h:90
SLOPE_NE
north and east corner are raised
Definition: slope_type.h:60
DoClearTownHouseHelper
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2398
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:110
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
Definition: newgrf_callbacks.h:229
viewport_func.h
Functions related to (drawing on) viewports.
random_func.hpp
Pseudo random number generator.
CompanyNewsInformation::company_name
char company_name[64]
The name of the company.
Definition: news_type.h:164
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:29
GetHouseBuildingStage
static byte GetHouseBuildingStage(TileIndex t)
House Construction Scheme.
Definition: town_map.h:185
Town::goal
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:81
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile.
Definition: town_cmd.cpp:3193
IsHouseCompleted
static bool IsHouseCompleted(TileIndex t)
Get the completion of this house.
Definition: town_map.h:147
TileIndexDiffC::y
int16 y
The y value of the coordinate.
Definition: map_type.h:60
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:115
CmdExpandTown
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:2629
AnimateTile_Town
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town Only certain houses can be animated The newhouses animation supersedes regu...
Definition: town_cmd.cpp:291
Pool::MAX_SIZE
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:87
IsValidTile
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:154
EconomySettings::exclusive_rights
bool exclusive_rights
allow buying exclusive rights
Definition: settings_type.h:476
IsBridgeAbove
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TownActions
TownActions
Town actions of a company.
Definition: town.h:199
GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:88
WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
RATING_ROAD_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:70
TO_HOUSES
town buildings
Definition: transparency.h:27
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
Definition: error_gui.cpp:378
IsTileOwner
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:207
DrawTile_Town
static void DrawTile_Town(TileInfo *ti)
House Tile drawing handler.
Definition: town_cmd.cpp:212
TileHash2Bit
static uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:332
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition: station_cmd.cpp:2159
SpotData::max_dist
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:1823
object_base.h
Base for all objects.
GrowTownWithRoad
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1045
newgrf_text.h
Header of Action 04 "universal holder" structure and functions.
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:279
DIAGDIRDIFF_90RIGHT
90 degrees right
Definition: direction_type.h:110
GetHouseConstructionTick
static byte GetHouseConstructionTick(TileIndex t)
Gets the construction stage of a house.
Definition: town_map.h:197
animated_tile_func.h
Tile animation!
ComplementSlope
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:78
TownEffect
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:25
string_func.h
Functions related to low-level strings.
pool_func.hpp
Some methods of Pool are placed here in order to reduce compilation time and binary size...
MAX_CHAR_LENGTH
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:20
DiagDirToRoadBits
static RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:144
TileInfo::x
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:45
GoodsEntry::rating
byte rating
Station rating for this cargo.
Definition: station_base.h:235
ROAD_ALL
Full 4-way crossing.
Definition: road_type.h:69
TileOffsByDiagDir
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:343
CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
Definition: newgrf_callbacks.h:226
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:96
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:95
cheat_type.h
Types related to cheating.
Town::xy
TileIndex xy
town center tile
Definition: town.h:56
DoCreateTown
static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Does the actual town creation.
Definition: town_cmd.cpp:1560
HouseSpec::mail_generation
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a give tiletype.
Definition: tile_map.h:143
TownCache::sign
ViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:48
TownCanBePlacedHere
static CommandCost TownCanBePlacedHere(TileIndex tile)
Checks if it&#39;s possible to place a town at given tile.
Definition: town_cmd.cpp:1635
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:48
error.h
Functions related to errors.
CheckTownBuild2x2House
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if 2x2 building is allowed here, also takes into account current town layout Also...
Definition: town_cmd.cpp:2219
DoCommand
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:436
CheckBuildHouseSameZ
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Checks if a house can be built at this tile, must have the same max z as parameter.
Definition: town_cmd.cpp:2086
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold...
Definition: town_cmd.cpp:3239
FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:97
CheckTownBuild2House
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout Also...
Definition: town_cmd.cpp:2194
RandomDiagDir
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:202
TownSize
TownSize
Supported initial town sizes.
Definition: town_type.h:21
Pool::PoolItem<&_town_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:267
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:119
ChangeTownRating
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3318
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:153
TL_2X2_GRID
Geometric 2x2 grid algorithm.
Definition: town_type.h:86
SmallPair
Simple pair of data.
Definition: smallmap_type.hpp:24
IsUniqueTownName
static bool IsUniqueTownName(const char *name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:1660
SetRoadOwner
static void SetRoadOwner(TileIndex t, RoadType rt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:220
Town::ratings
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:77
GWP_TOWN
Generate towns.
Definition: genworld.h:73
TACT_FUND_BUILDINGS
Fund new buildings.
Definition: town.h:207
HasTownOwnedRoad
static bool HasTownOwnedRoad(TileIndex t)
Checks if given tile has town owned road.
Definition: road_map.h:249
GetTownIndex
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:24
StationFinder::GetStations
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition: station_cmd.cpp:3826
newgrf_house.h
Functions related to NewGRF houses.
ConvertBooleanCallback
bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:552
ReverseDiagDir
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:120
CBM_HOUSE_PRODUCE_CARGO
custom cargo production
Definition: newgrf_callbacks.h:325
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:340
TOWN_GROW_RATE_CUSTOM
static const uint16 TOWN_GROW_RATE_CUSTOM
If this mask is applied to Town::growth_rate, the grow_counter will not be calculated by the system (...
Definition: town.h:38
DIAGDIR_SE
Southeast.
Definition: direction_type.h:83
DIAGDIR_SW
Southwest.
Definition: direction_type.h:84
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:152
RATING_ROAD_NEEDED_PERMISSIVE
rating needed, "Permissive" difficulty settings
Definition: town_type.h:68
NT_GENERAL
General news (from towns)
Definition: news_type.h:51
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:30
TILE_AREA_LOOP
#define TILE_AREA_LOOP(var, ta)
A loop which iterates over the tiles of a TileArea.
Definition: tilearea_type.h:232
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:54
Town::PostDestructor
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool...
Definition: town_cmd.cpp:116
MAX_LENGTH_COMPANY_NAME_CHARS
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including &#39;\0&#39;.
Definition: company_type.h:42
object_map.h
Map accessors for object tiles.
TILE_ADDXY
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:260
safeguards.h
A number of safeguards to prevent using unsafe methods.
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:20
TileIndexDiffC::x
int16 x
The x value of the coordinate.
Definition: map_type.h:59
TSZ_END
Number of available town sizes.
Definition: town_type.h:27
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:260
Town::GetRandom
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:145
MP_WATER
Water tile.
Definition: tile_type.h:49
TileInfo::y
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:46
GetLiftPosition
static byte GetLiftPosition(TileIndex t)
Get the position of the lift on this animated house.
Definition: town_map.h:127
IsRoadDepotTile
static bool IsRoadDepotTile(TileIndex t)
Return whether a tile is a road depot tile.
Definition: road_map.h:99
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:55
TownCache::building_counts
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:51
Object
An object, such as transmitter, on the map.
Definition: object_base.h:25
HouseSpec::accepts_cargo
CargoID accepts_cargo[3]
3 input cargo slots
Definition: house.h:108
DIAGDIR_END
Used for iterations.
Definition: direction_type.h:86
RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
rating needed, "Permissive" difficulty settings
Definition: town_type.h:61
NR_NONE
Empty reference.
Definition: news_type.h:65
IsValidDiagDirection
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:23
ROAD_NONE
No road-part is build.
Definition: road_type.h:56
UpdateTownCargoBitmap
void UpdateTownCargoBitmap()
Updates the bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:768
EconomySettings::fund_roads
bool fund_roads
allow funding local road reconstruction
Definition: settings_type.h:478
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:126
CMD_DELETE_TOWN
delete a town
Definition: command_type.h:268
TACT_COUNT
Number of available town actions.
Definition: town.h:211
CmdTownGrowthRate
CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the growth rate of the town.
Definition: town_cmd.cpp:2589
NF_NORMAL
Normal news item. (Newspaper with text only)
Definition: news_type.h:93
CBM_HOUSE_AUTOSLOPE
decides allowance of autosloping
Definition: newgrf_callbacks.h:328
ChangeDiagDir
static DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Definition: direction_func.h:151
DC_NO_WATER
don&#39;t allow building on water
Definition: command_type.h:345
TL_RANDOM
Random town layout.
Definition: town_type.h:89
RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
Definition: town_type.h:55
FindFurthestFromWater
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:1843
ROAD_NE
North-east part.
Definition: road_type.h:60
IncHouseConstructionTick
static void IncHouseConstructionTick(TileIndex t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits...
Definition: town_map.h:210
GetWorldPopulation
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:415
TransportedCargoStat::new_max
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:114
RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:69
DrawBuildingsTileStruct
This structure is the same for both Industries and Houses.
Definition: sprite.h:69
HouseSpec::GetRemovalCost
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:169
OWNER_NONE
The tile has no ownership.
Definition: company_type.h:27
DIAGDIR_NW
Northwest.
Definition: direction_type.h:85
GrowTown
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1445
CommandFlagsToDCFlags
static DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:62
GetHouseNorthPart
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2415
StatueBuildSearchData
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:2815
WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:340
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
TileMatrix::GetArea
const TileArea & GetArea() const
Get the total covered area.
Definition: tilematrix_type.hpp:83
BaseStation::facilities
StationFacilityByte facilities
The facilities that this station has.
Definition: base_station_base.h:64
CmdDeleteTown
CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Delete a town (scenario editor or worldgen only).
Definition: town_cmd.cpp:2669
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:80
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
SLOPE_ELEVATED
bit mask containing all &#39;simple&#39; slopes
Definition: slope_type.h:63
CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:70
TileHash
static uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:314
IsWaterTile
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:184
min
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
MAX_UVALUE
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:515
FlatteningFoundation
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:371
EconomyIsInRecession
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
GetAnyRoadBits
RoadBits GetAnyRoadBits(TileIndex tile, RoadType rt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:35
SetLiftDestination
static void SetLiftDestination(TileIndex t, byte dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit...
Definition: town_map.h:95
CleanUpRoadBits
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planed tile.
Definition: road.cpp:46
autoslope.h
Functions related to autoslope.
HouseSpec::max_year
Year max_year
last year it can be built
Definition: house.h:101
GetTunnelBridgeDirection
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
Definition: tunnelbridge_map.h:28
DifficultySettings::number_towns
byte number_towns
the amount of towns
Definition: settings_type.h:57
Convert8bitBooleanCallback
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:571
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:18
AutoslopeEnabled
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:46
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:219
GrowTownAtRoad
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Returns "growth" if a house was built, or no if the build failed.
Definition: town_cmd.cpp:1349
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:301
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:161
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:1998
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:25
SLOPE_STEEP_W
a steep slope falling to east (from west)
Definition: slope_type.h:68
GetBridgeAxis
static Axis GetBridgeAxis(TileIndex t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:688
EconomySettings::town_growth_rate
uint8 town_growth_rate
town growth rate
Definition: settings_type.h:482
GRFLoadedFeatures::has_newhouses
bool has_newhouses
Set if there are any newhouses loaded.
Definition: newgrf.h:164
TACT_NONE
Empty action set.
Definition: town.h:200
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:35
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3214
TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition: town.h:154
Pool
Base class for all pools.
Definition: pool_type.hpp:83
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
ROAD_NW
North-west part.
Definition: road_type.h:57
IsSea
static bool IsSea(TileIndex t)
Is it a sea water tile?
Definition: water_map.h:152
NF_COMPANY
Company news item. (Newspaper with face)
Definition: news_type.h:95
road_cmd.h
Road related functions.
IsRoadAllowedHere
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:867
CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
Definition: newgrf_callbacks.h:56
Chance16
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
Definition: random_func.hpp:133
ROAD_SE
South-east part.
Definition: road_type.h:59
StatueBuildSearchData::tile_count
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:2817
GRFFileProps::override
uint16 override
id of the entity been replaced by
Definition: newgrf_commons.h:333
NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
BaseStation::owner
OwnerByte owner
The owner of this station.
Definition: base_station_base.h:63
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:1904
_tick_counter
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
Company
Definition: company_base.h:110
TileDesc::dparam
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:64
GetClosestWaterDistance
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:342
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:58
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition: station_cmd.cpp:429
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:224
DeleteWindowById
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1137
EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:151
MakeTownHouse
static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
Write house information into the map.
Definition: town_cmd.cpp:2046
DiagDirToAxis
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:216
MakeTownHouseBigger
static void MakeTownHouseBigger(TileIndex tile)
Make the house advance in its construction stages until completion.
Definition: town_cmd.cpp:451
ToTileIndexDiff
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Definition: map_func.h:232
GetOtherTunnelBridgeEnd
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
Definition: tunnelbridge_map.h:80
Town::text
char * text
General text with additional information.
Definition: town.h:83
CUSTOM_TOWN_NUMBER_DIFFICULTY
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:31
DC_EXEC
execute the given command
Definition: command_type.h:342
GetFoundationSlope
Slope GetFoundationSlope(TileIndex tile, int *z)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation, the function returns the same as GetTileSlope.
Definition: landscape.cpp:342
HouseSpec
Definition: house.h:98
MakeSingleHouseBigger
static void MakeSingleHouseBigger(TileIndex tile)
Helper function for house completion stages progression.
Definition: town_cmd.cpp:428
CmdTownCargoGoal
CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2532
TOWN_GROWTH_DESERT
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:37
InclinedSlope
static Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:258
Town::growth_rate
uint16 growth_rate
town growth rate
Definition: town.h:95
TownActionBuildStatue
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
Definition: town_cmd.cpp:2871
HaltLift
static void HaltLift(TileIndex t)
Stop the lift of this animated house from moving.
Definition: town_map.h:117
MP_TREES
Tile got trees.
Definition: tile_type.h:47
CanFollowRoad
static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile...
Definition: town_cmd.cpp:1307
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:889
TransportedCargoStat::old_max
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
MapSize
static uint MapSize()
Get the size of the map.
Definition: map_func.h:94
CargoSpec::town_effect
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:67
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:518
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:74
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:61
TileLoop_Town
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:466
DecreaseBuildingCount
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
Definition: newgrf_house.cpp:121
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:153
TOWN_HAS_CHURCH
There can be only one church by town.
Definition: town.h:166
WC_TOWN_AUTHORITY
Town authority; Window numbers:
Definition: window_type.h:189
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:561
MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:52
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:118
MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:50
NR_TOWN
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:70
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:19
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:215
SetLiftPosition
static void SetLiftPosition(TileIndex t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:137
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:300
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
_current_company
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:144
AT_OILRIG
Oilrig airport.
Definition: airport.h:40
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
object.h
Functions related to objects.
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:159
newgrf_cargo.h
Cargo support for NewGRFs.
GetRating
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3300
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:276
OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:26
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=NULL)
Add a new newsitem to be shown.
Definition: news_gui.cpp:645
FindNearestEmptyLand
static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the nearest land tile.
Definition: town_cmd.cpp:1865
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:122
TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition: town.h:208
HouseSpec::remove_rating_decrease
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:105
GetHouseType
static HouseID GetHouseType(TileIndex t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:61
SLOPE_NW
north and west corner are raised
Definition: slope_type.h:57
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:217
TSZ_RANDOM
Random size, bigger than small, smaller than large.
Definition: town_type.h:25
TOWN_GROW_RATE_CUSTOM_NONE
static const uint16 TOWN_GROW_RATE_CUSTOM_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:39
Cheats::magic_bulldozer
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:29
DifficultySettings::town_council_tolerance
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:71
FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:96
CheckforTownRating
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3355
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:55
Object::location
TileArea location
Location of the object.
Definition: object_base.h:28
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:36
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:21
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:34
TownLayout
TownLayout
Town Layouts.
Definition: town_type.h:82
EconomySettings::initial_city_size
uint8 initial_city_size
multiplier for the initial size of the cities compared to towns
Definition: settings_type.h:484
Object::type
ObjectType type
Type of the object.
Definition: object_base.h:26
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:50
CanBuildHouseHere
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Checks if a house can be built here.
Definition: town_cmd.cpp:2064
WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:328
MP_STATION
A tile of a station.
Definition: tile_type.h:48
TF_FORBIDDEN
Forbidden.
Definition: town_type.h:100
_town_action_costs
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:2750
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:58
EconomySettings::larger_towns
uint8 larger_towns
the number of cities to build. These start off larger and grow twice as fast
Definition: settings_type.h:483
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:30
MapMaxY
static uint MapMaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:113
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:427
Town
Town data structure.
Definition: town.h:55
GetTownRoadGridElement
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:944
Town::exclusive_counter
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:76
Pool::PoolItem<&_town_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
TRANSPORT_ROAD
Transport by road vehicle.
Definition: transport_type.h:30
BuildObject
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=NULL, uint8 view=0)
Actually build the object.
Definition: object_cmd.cpp:85
landscape.h
Functions related to OTTD&#39;s landscape.
ResetHouseAge
static void ResetHouseAge(TileIndex t)
Sets the age of the house to zero.
Definition: town_map.h:228
GameCreationSettings::town_name
byte town_name
the town name generator used for town names
Definition: settings_type.h:287
TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:85
game.hpp
Base functions for all Games.
TE_END
End of town effects.
Definition: cargotype.h:33
TF_CUSTOM_LAYOUT
Allowed, with custom town layout.
Definition: town_type.h:102
command_func.h
Functions related to commands.
Town::larger_town
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:100
Town::name
char * name
Custom town name. If NULL, the town was not renamed and uses the generated name.
Definition: town.h:64
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:28
SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition: slope_type.h:71
TSZ_LARGE
Large town.
Definition: town_type.h:24
TownNameParams
Struct holding a parameters used to generate town name.
Definition: townname_type.h:29
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:604
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:564
Pool::PoolItem<&_town_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
Definition: pool_type.hpp:235
TileHeight
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:31
CBM_HOUSE_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
Definition: newgrf_callbacks.h:327
Object::GetByTile
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:52
TL_ORIGINAL
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:84
CMD_BUILD_BRIDGE
build a bridge
Definition: command_type.h:183
TE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:32
MAX_LENGTH_TOWN_NAME_CHARS
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including &#39;\0&#39;.
Definition: town_type.h:108
Town::layout
TownLayoutByte layout
town specific road layout
Definition: town.h:101
TryClearTile
static bool TryClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:2806
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:545
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:19
tunnelbridge_map.h
Functions that have tunnels and bridges in common.
TileDiffXY
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:181
_original_house_specs
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1818
industry.h
Base of all industries.
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:126
AddChildSpriteScreen
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:843
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
HouseSpec::grf_prop
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:114
Station::airport
Airport airport
Tile area the airport covers.
Definition: station_base.h:460
RATING_STATION_UP_STEP
when a town grows, company gains reputation for all well serviced stations ...
Definition: town_type.h:56
OverrideManagerBase::ResetOverride
void ResetOverride()
Resets the override, which is used while initializing game.
Definition: newgrf_commons.cpp:90
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:54
WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:23
_town_cargoes_accepted
uint32 _town_cargoes_accepted
Bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:56
GetMaskOfTownActions
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:2989
GetFoundation_Town
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback routine.
Definition: town_cmd.cpp:267
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:105
townname_func.h
Town name generator stuff.
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:114
ai.hpp
Base functions for all AIs.
TACT_BRIBE
Try to bribe the council.
Definition: town.h:209
AlignTileToGrid
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:1791
INVALID_TILE
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:85
town.h
Base of the town class.
SpotData::tile
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:1822
Town::supplied
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:79
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:544
MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:43
_nb_orig_names
int _nb_orig_names
Number of original town names.
Definition: settings_gui.cpp:67
MP_HOUSE
A house by a town.
Definition: tile_type.h:46
ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:62
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
MapMaxX
static uint MapMaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:104
EconomySettings::fund_buildings
bool fund_buildings
allow funding new buildings
Definition: settings_type.h:477
DistanceSquare
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the &#39;Square&#39; distance between the two given tiles.
Definition: map.cpp:176
IsInvisibilitySet
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:61
EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:163
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:94
IncreaseBuildingCount
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town...
Definition: newgrf_house.cpp:100
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:20
window_func.h
Window functions not directly related to making/drawing windows.
CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
Definition: newgrf_callbacks.h:131
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition: genworld_gui.cpp:1340
TownCache::num_houses
uint32 num_houses
Amount of houses.
Definition: town.h:46
SLOPE_STEEP_E
a steep slope falling to west (from east)
Definition: slope_type.h:70
_loaded_newgrf_features
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:77
UpdateTownCargoTotal
void UpdateTownCargoTotal(Town *t)
Update the total cargo acceptance of the whole town.
Definition: town_cmd.cpp:701
TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:165
DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:347
CBM_HOUSE_ALLOW_CONSTRUCTION
decide whether the house can be built on a given tile
Definition: newgrf_callbacks.h:316
TILE_ADD
#define TILE_ADD(x, y)
Adds to tiles together.
Definition: map_func.h:246
PalSpriteID::sprite
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:25
CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
Definition: newgrf_callbacks.h:80
SearchTileForStatue
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:2828
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3148
SetDParamX
static void SetDParamX(uint64 *s, uint n, uint64 v)
Set a string parameter v at index n in a given array s.
Definition: strings_func.h:191
CALLBACK_HOUSEPRODCARGO_END
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
Definition: newgrf_callbacks.h:407
news_func.h
Functions related to news.
StationFinder
Structure contains cached list of stations nearby.
Definition: station_type.h:104
CmdTownSetText
CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Set a custom text in the Town window.
Definition: town_cmd.cpp:2565
Town::road_build_months
byte road_build_months
fund road reconstruction in action?
Definition: town.h:98
CmdRenameTown
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename a town (server-only).
Definition: town_cmd.cpp:2482
station_base.h
Base classes/functions for stations.
SetTownIndex
static void SetTownIndex(TileIndex t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:36
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition: genworld_gui.cpp:1354
DIAGDIRDIFF_90LEFT
90 degrees left
Definition: direction_type.h:112
INVALID_COMPANY
An invalid company.
Definition: company_type.h:32
RemapCoords2
static Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap...
Definition: landscape.h:99
EconomySettings::allow_town_level_crossings
bool allow_town_level_crossings
towns are allowed to build level crossings
Definition: settings_type.h:490
SLOPE_S
the south corner of the tile is raised
Definition: slope_type.h:53
Town::grow_counter
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:94
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:734
RATING_STATION_DOWN_STEP
... but loses for bad serviced stations
Definition: town_type.h:57
backup_type.hpp
Class for backupping variables and making sure they are restored later.
ClampToU16
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:215
ROADTYPES_ROAD
Road.
Definition: road_type.h:38
Station
Station data structure.
Definition: station_base.h:446
IsTransparencySet
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:50
IsRoadDepot
static bool IsRoadDepot(TileIndex t)
Return whether a tile is a road depot.
Definition: road_map.h:89
subsidy_func.h
Functions related to subsidies.
CmdFoundTown
CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Create a new town.
Definition: town_cmd.cpp:1683
IsTileAlignedToGrid
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:1809
FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:58
OverflowSafeInt< int64, INT64_MAX, INT64_MIN >
TileXY
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:165
TileIndexToTileIndexDiffC
static TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:318
IncrementHouseAge
static void IncrementHouseAge(TileIndex t)
Increments the age of the house.
Definition: town_map.h:239
FindFirstCargoWithTownEffect
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2510
Depot
Definition: depot_base.h:21
SLOPE_STEEP_S
a steep slope falling to north (from south)
Definition: slope_type.h:69
_tile_type_town_procs
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3220
TransportedCargoStat::old_act
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
Town::have_ratings
CompanyMask have_ratings
which companies have a rating
Definition: town.h:73
HighestSnowLine
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:578
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1461
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:18
UpdateTownGrowRate
static void UpdateTownGrowRate(Town *t)
Definition: town_cmd.cpp:3096
GetTileMaxPixelZ
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:299
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:201
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:26
SetTownRatingTestMode
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Definition: town_cmd.cpp:3280