Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / landscape.cpp
blob43dacf8a358dd9eb5faf08837c40d91020fc21f7
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file landscape.cpp Functions related to the landscape (slopes etc.). */
10 /** @defgroup SnowLineGroup Snowline functions and data structures */
12 #include "stdafx.h"
13 #include "heightmap.h"
14 #include "clear_map.h"
15 #include "spritecache.h"
16 #include "viewport_func.h"
17 #include "command_func.h"
18 #include "landscape.h"
19 #include "void_map.h"
20 #include "tgp.h"
21 #include "genworld.h"
22 #include "fios.h"
23 #include "error_func.h"
24 #include "timer/timer_game_calendar.h"
25 #include "timer/timer_game_tick.h"
26 #include "water.h"
27 #include "effectvehicle_func.h"
28 #include "landscape_type.h"
29 #include "animated_tile_func.h"
30 #include "core/random_func.hpp"
31 #include "object_base.h"
32 #include "company_func.h"
33 #include "pathfinder/npf/aystar.h"
34 #include "saveload/saveload.h"
35 #include "framerate_type.h"
36 #include "landscape_cmd.h"
37 #include "terraform_cmd.h"
38 #include "station_func.h"
39 #include "pathfinder/water_regions.h"
41 #include "table/strings.h"
42 #include "table/sprites.h"
44 #include "safeguards.h"
46 extern const TileTypeProcs
47 _tile_type_clear_procs,
48 _tile_type_rail_procs,
49 _tile_type_road_procs,
50 _tile_type_town_procs,
51 _tile_type_trees_procs,
52 _tile_type_station_procs,
53 _tile_type_water_procs,
54 _tile_type_void_procs,
55 _tile_type_industry_procs,
56 _tile_type_tunnelbridge_procs,
57 _tile_type_object_procs;
59 /**
60 * Tile callback functions for each type of tile.
61 * @ingroup TileCallbackGroup
62 * @see TileType
64 const TileTypeProcs * const _tile_type_procs[16] = {
65 &_tile_type_clear_procs, ///< Callback functions for MP_CLEAR tiles
66 &_tile_type_rail_procs, ///< Callback functions for MP_RAILWAY tiles
67 &_tile_type_road_procs, ///< Callback functions for MP_ROAD tiles
68 &_tile_type_town_procs, ///< Callback functions for MP_HOUSE tiles
69 &_tile_type_trees_procs, ///< Callback functions for MP_TREES tiles
70 &_tile_type_station_procs, ///< Callback functions for MP_STATION tiles
71 &_tile_type_water_procs, ///< Callback functions for MP_WATER tiles
72 &_tile_type_void_procs, ///< Callback functions for MP_VOID tiles
73 &_tile_type_industry_procs, ///< Callback functions for MP_INDUSTRY tiles
74 &_tile_type_tunnelbridge_procs, ///< Callback functions for MP_TUNNELBRIDGE tiles
75 &_tile_type_object_procs, ///< Callback functions for MP_OBJECT tiles
78 /** landscape slope => sprite */
79 extern const byte _slope_to_sprite_offset[32] = {
80 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0,
81 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 17, 0, 15, 18, 0,
84 /**
85 * Description of the snow line throughout the year.
87 * If it is \c nullptr, a static snowline height is used, as set by \c _settings_game.game_creation.snow_line_height.
88 * Otherwise it points to a table loaded from a newGRF file that describes the variable snowline.
89 * @ingroup SnowLineGroup
90 * @see GetSnowLine() GameCreationSettings
92 static SnowLine *_snow_line = nullptr;
94 /**
95 * Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
96 * Function takes into account height of tiles and foundations.
98 * @param x X viewport 2D coordinate.
99 * @param y Y viewport 2D coordinate.
100 * @param clamp_to_map Clamp the coordinate outside of the map to the closest, non-void tile within the map.
101 * @param[out] clamped Whether coordinates were clamped.
102 * @return 3D world coordinate of point visible at the given screen coordinate (3D perspective).
104 * @note Inverse of #RemapCoords2 function. Smaller values may get rounded.
105 * @see InverseRemapCoords
107 Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
109 if (clamped != nullptr) *clamped = false; // Not clamping yet.
111 /* Initial x/y world coordinate is like if the landscape
112 * was completely flat on height 0. */
113 Point pt = InverseRemapCoords(x, y);
115 const uint min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
116 const uint max_x = Map::MaxX() * TILE_SIZE - 1;
117 const uint max_y = Map::MaxY() * TILE_SIZE - 1;
119 if (clamp_to_map) {
120 /* Bring the coordinates near to a valid range. At the top we allow a number
121 * of extra tiles. This is mostly due to the tiles on the north side of
122 * the map possibly being drawn higher due to the extra height levels. */
123 int extra_tiles = CeilDiv(_settings_game.construction.map_height_limit * TILE_HEIGHT, TILE_PIXELS);
124 Point old_pt = pt;
125 pt.x = Clamp(pt.x, -extra_tiles * TILE_SIZE, max_x);
126 pt.y = Clamp(pt.y, -extra_tiles * TILE_SIZE, max_y);
127 if (clamped != nullptr) *clamped = (pt.x != old_pt.x) || (pt.y != old_pt.y);
130 /* Now find the Z-world coordinate by fix point iteration.
131 * This is a bit tricky because the tile height is non-continuous at foundations.
132 * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
133 * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
134 * So give it a z-malus of 4 in the first iterations. */
135 int z = 0;
136 if (clamp_to_map) {
137 for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(pt.x + std::max(z, 4) - 4, min_coord, max_x), Clamp(pt.y + std::max(z, 4) - 4, min_coord, max_y)) / 2;
138 for (int m = 3; m > 0; m--) z = GetSlopePixelZ(Clamp(pt.x + std::max(z, m) - m, min_coord, max_x), Clamp(pt.y + std::max(z, m) - m, min_coord, max_y)) / 2;
139 for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(pt.x + z, min_coord, max_x), Clamp(pt.y + z, min_coord, max_y)) / 2;
140 } else {
141 for (int i = 0; i < 5; i++) z = GetSlopePixelZOutsideMap(pt.x + std::max(z, 4) - 4, pt.y + std::max(z, 4) - 4) / 2;
142 for (int m = 3; m > 0; m--) z = GetSlopePixelZOutsideMap(pt.x + std::max(z, m) - m, pt.y + std::max(z, m) - m) / 2;
143 for (int i = 0; i < 5; i++) z = GetSlopePixelZOutsideMap(pt.x + z, pt.y + z ) / 2;
146 pt.x += z;
147 pt.y += z;
148 if (clamp_to_map) {
149 Point old_pt = pt;
150 pt.x = Clamp(pt.x, min_coord, max_x);
151 pt.y = Clamp(pt.y, min_coord, max_y);
152 if (clamped != nullptr) *clamped = *clamped || (pt.x != old_pt.x) || (pt.y != old_pt.y);
155 return pt;
159 * Applies a foundation to a slope.
161 * @pre Foundation and slope must be valid combined.
162 * @param f The #Foundation.
163 * @param s The #Slope to modify.
164 * @return Increment to the tile Z coordinate.
166 uint ApplyFoundationToSlope(Foundation f, Slope *s)
168 if (!IsFoundation(f)) return 0;
170 if (IsLeveledFoundation(f)) {
171 uint dz = 1 + (IsSteepSlope(*s) ? 1 : 0);
172 *s = SLOPE_FLAT;
173 return dz;
176 if (f != FOUNDATION_STEEP_BOTH && IsNonContinuousFoundation(f)) {
177 *s = HalftileSlope(*s, GetHalftileFoundationCorner(f));
178 return 0;
181 if (IsSpecialRailFoundation(f)) {
182 *s = SlopeWithThreeCornersRaised(OppositeCorner(GetRailFoundationCorner(f)));
183 return 0;
186 uint dz = IsSteepSlope(*s) ? 1 : 0;
187 Corner highest_corner = GetHighestSlopeCorner(*s);
189 switch (f) {
190 case FOUNDATION_INCLINED_X:
191 *s = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ? SLOPE_SW : SLOPE_NE);
192 break;
194 case FOUNDATION_INCLINED_Y:
195 *s = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ? SLOPE_SE : SLOPE_NW);
196 break;
198 case FOUNDATION_STEEP_LOWER:
199 *s = SlopeWithOneCornerRaised(highest_corner);
200 break;
202 case FOUNDATION_STEEP_BOTH:
203 *s = HalftileSlope(SlopeWithOneCornerRaised(highest_corner), highest_corner);
204 break;
206 default: NOT_REACHED();
208 return dz;
213 * Determines height at given coordinate of a slope.
215 * At the northern corner (0, 0) the result is always a multiple of TILE_HEIGHT.
216 * When the height is a fractional Z, then the height is rounded down. For example,
217 * when at the height is 0 at x = 0 and the height is 8 at x = 16 (actually x = 0
218 * of the next tile), then height is 0 at x = 1, 1 at x = 2, and 7 at x = 15.
219 * @param x x coordinate (value from 0 to 15)
220 * @param y y coordinate (value from 0 to 15)
221 * @param corners slope to examine
222 * @return height of given point of given slope
224 uint GetPartialPixelZ(int x, int y, Slope corners)
226 if (IsHalftileSlope(corners)) {
227 /* A foundation is placed on half the tile at a specific corner. This means that,
228 * depending on the corner, that one half of the tile is at the maximum height. */
229 switch (GetHalftileSlopeCorner(corners)) {
230 case CORNER_W:
231 if (x > y) return GetSlopeMaxPixelZ(corners);
232 break;
234 case CORNER_S:
235 if (x + y >= (int)TILE_SIZE) return GetSlopeMaxPixelZ(corners);
236 break;
238 case CORNER_E:
239 if (x <= y) return GetSlopeMaxPixelZ(corners);
240 break;
242 case CORNER_N:
243 if (x + y < (int)TILE_SIZE) return GetSlopeMaxPixelZ(corners);
244 break;
246 default: NOT_REACHED();
250 switch (RemoveHalftileSlope(corners)) {
251 case SLOPE_FLAT: return 0;
253 /* One corner is up.*/
254 case SLOPE_N: return x + y <= (int)TILE_SIZE ? (TILE_SIZE - x - y) >> 1 : 0;
255 case SLOPE_E: return y >= x ? (1 + y - x) >> 1 : 0;
256 case SLOPE_S: return x + y >= (int)TILE_SIZE ? (1 + x + y - TILE_SIZE) >> 1 : 0;
257 case SLOPE_W: return x >= y ? (x - y) >> 1 : 0;
259 /* Two corners next to eachother are up. */
260 case SLOPE_NE: return (TILE_SIZE - x) >> 1;
261 case SLOPE_SE: return (y + 1) >> 1;
262 case SLOPE_SW: return (x + 1) >> 1;
263 case SLOPE_NW: return (TILE_SIZE - y) >> 1;
265 /* Three corners are up on the same level. */
266 case SLOPE_ENW: return x + y >= (int)TILE_SIZE ? TILE_HEIGHT - ((1 + x + y - TILE_SIZE) >> 1) : TILE_HEIGHT;
267 case SLOPE_SEN: return y < x ? TILE_HEIGHT - ((x - y) >> 1) : TILE_HEIGHT;
268 case SLOPE_WSE: return x + y <= (int)TILE_SIZE ? TILE_HEIGHT - ((TILE_SIZE - x - y) >> 1) : TILE_HEIGHT;
269 case SLOPE_NWS: return x < y ? TILE_HEIGHT - ((1 + y - x) >> 1) : TILE_HEIGHT;
271 /* Two corners at opposite sides are up. */
272 case SLOPE_NS: return x + y < (int)TILE_SIZE ? (TILE_SIZE - x - y) >> 1 : (1 + x + y - TILE_SIZE) >> 1;
273 case SLOPE_EW: return x >= y ? (x - y) >> 1 : (1 + y - x) >> 1;
275 /* Very special cases. */
276 case SLOPE_ELEVATED: return TILE_HEIGHT;
278 /* Steep slopes. The top is at 2 * TILE_HEIGHT. */
279 case SLOPE_STEEP_N: return (TILE_SIZE - x + TILE_SIZE - y) >> 1;
280 case SLOPE_STEEP_E: return (TILE_SIZE + 1 + y - x) >> 1;
281 case SLOPE_STEEP_S: return (1 + x + y) >> 1;
282 case SLOPE_STEEP_W: return (TILE_SIZE + x - y) >> 1;
284 default: NOT_REACHED();
289 * Return world \c Z coordinate of a given point of a tile. Normally this is the
290 * Z of the ground/foundation at the given location, but in some cases the
291 * ground/foundation can differ from the Z coordinate that the (ground) vehicle
292 * passing over it would take. For example when entering a tunnel or bridge.
294 * @param x World X coordinate in tile "units".
295 * @param y World Y coordinate in tile "units".
296 * @param ground_vehicle Whether to get the Z coordinate of the ground vehicle, or the ground.
297 * @return World Z coordinate at tile ground (vehicle) level, including slopes and foundations.
299 int GetSlopePixelZ(int x, int y, bool ground_vehicle)
301 TileIndex tile = TileVirtXY(x, y);
303 return _tile_type_procs[GetTileType(tile)]->get_slope_z_proc(tile, x, y, ground_vehicle);
307 * Return world \c z coordinate of a given point of a tile,
308 * also for tiles outside the map (virtual "black" tiles).
310 * @param x World X coordinate in tile "units", may be outside the map.
311 * @param y World Y coordinate in tile "units", may be outside the map.
312 * @return World Z coordinate at tile ground level, including slopes and foundations.
314 int GetSlopePixelZOutsideMap(int x, int y)
316 if (IsInsideBS(x, 0, Map::SizeX() * TILE_SIZE) && IsInsideBS(y, 0, Map::SizeY() * TILE_SIZE)) {
317 return GetSlopePixelZ(x, y, false);
318 } else {
319 return _tile_type_procs[MP_VOID]->get_slope_z_proc(INVALID_TILE, x, y, false);
324 * Determine the Z height of a corner relative to TileZ.
326 * @pre The slope must not be a halftile slope.
328 * @param tileh The slope.
329 * @param corner The corner.
330 * @return Z position of corner relative to TileZ.
332 int GetSlopeZInCorner(Slope tileh, Corner corner)
334 assert(!IsHalftileSlope(tileh));
335 return ((tileh & SlopeWithOneCornerRaised(corner)) != 0 ? 1 : 0) + (tileh == SteepSlope(corner) ? 1 : 0);
339 * Determine the Z height of the corners of a specific tile edge
341 * @note If a tile has a non-continuous halftile foundation, a corner can have different heights wrt. its edges.
343 * @pre z1 and z2 must be initialized (typ. with TileZ). The corner heights just get added.
345 * @param tileh The slope of the tile.
346 * @param edge The edge of interest.
347 * @param z1 Gets incremented by the height of the first corner of the edge. (near corner wrt. the camera)
348 * @param z2 Gets incremented by the height of the second corner of the edge. (far corner wrt. the camera)
350 void GetSlopePixelZOnEdge(Slope tileh, DiagDirection edge, int *z1, int *z2)
352 static const Slope corners[4][4] = {
353 /* corner | steep slope
354 * z1 z2 | z1 z2 */
355 {SLOPE_E, SLOPE_N, SLOPE_STEEP_E, SLOPE_STEEP_N}, // DIAGDIR_NE, z1 = E, z2 = N
356 {SLOPE_S, SLOPE_E, SLOPE_STEEP_S, SLOPE_STEEP_E}, // DIAGDIR_SE, z1 = S, z2 = E
357 {SLOPE_S, SLOPE_W, SLOPE_STEEP_S, SLOPE_STEEP_W}, // DIAGDIR_SW, z1 = S, z2 = W
358 {SLOPE_W, SLOPE_N, SLOPE_STEEP_W, SLOPE_STEEP_N}, // DIAGDIR_NW, z1 = W, z2 = N
361 int halftile_test = (IsHalftileSlope(tileh) ? SlopeWithOneCornerRaised(GetHalftileSlopeCorner(tileh)) : 0);
362 if (halftile_test == corners[edge][0]) *z2 += TILE_HEIGHT; // The slope is non-continuous in z2. z2 is on the upper side.
363 if (halftile_test == corners[edge][1]) *z1 += TILE_HEIGHT; // The slope is non-continuous in z1. z1 is on the upper side.
365 if ((tileh & corners[edge][0]) != 0) *z1 += TILE_HEIGHT; // z1 is raised
366 if ((tileh & corners[edge][1]) != 0) *z2 += TILE_HEIGHT; // z2 is raised
367 if (RemoveHalftileSlope(tileh) == corners[edge][2]) *z1 += TILE_HEIGHT; // z1 is highest corner of a steep slope
368 if (RemoveHalftileSlope(tileh) == corners[edge][3]) *z2 += TILE_HEIGHT; // z2 is highest corner of a steep slope
372 * Get slope of a tile on top of a (possible) foundation
373 * If a tile does not have a foundation, the function returns the same as GetTileSlope.
375 * @param tile The tile of interest.
376 * @param z returns the z of the foundation slope. (Can be nullptr, if not needed)
377 * @return The slope on top of the foundation.
379 Slope GetFoundationSlope(TileIndex tile, int *z)
381 Slope tileh = GetTileSlope(tile, z);
382 Foundation f = _tile_type_procs[GetTileType(tile)]->get_foundation_proc(tile, tileh);
383 uint z_inc = ApplyFoundationToSlope(f, &tileh);
384 if (z != nullptr) *z += z_inc;
385 return tileh;
389 bool HasFoundationNW(TileIndex tile, Slope slope_here, uint z_here)
391 int z;
393 int z_W_here = z_here;
394 int z_N_here = z_here;
395 GetSlopePixelZOnEdge(slope_here, DIAGDIR_NW, &z_W_here, &z_N_here);
397 Slope slope = GetFoundationPixelSlope(TILE_ADDXY(tile, 0, -1), &z);
398 int z_W = z;
399 int z_N = z;
400 GetSlopePixelZOnEdge(slope, DIAGDIR_SE, &z_W, &z_N);
402 return (z_N_here > z_N) || (z_W_here > z_W);
406 bool HasFoundationNE(TileIndex tile, Slope slope_here, uint z_here)
408 int z;
410 int z_E_here = z_here;
411 int z_N_here = z_here;
412 GetSlopePixelZOnEdge(slope_here, DIAGDIR_NE, &z_E_here, &z_N_here);
414 Slope slope = GetFoundationPixelSlope(TILE_ADDXY(tile, -1, 0), &z);
415 int z_E = z;
416 int z_N = z;
417 GetSlopePixelZOnEdge(slope, DIAGDIR_SW, &z_E, &z_N);
419 return (z_N_here > z_N) || (z_E_here > z_E);
423 * Draw foundation \a f at tile \a ti. Updates \a ti.
424 * @param ti Tile to draw foundation on
425 * @param f Foundation to draw
427 void DrawFoundation(TileInfo *ti, Foundation f)
429 if (!IsFoundation(f)) return;
431 /* Two part foundations must be drawn separately */
432 assert(f != FOUNDATION_STEEP_BOTH);
434 uint sprite_block = 0;
435 int z;
436 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
438 /* Select the needed block of foundations sprites
439 * Block 0: Walls at NW and NE edge
440 * Block 1: Wall at NE edge
441 * Block 2: Wall at NW edge
442 * Block 3: No walls at NW or NE edge
444 if (!HasFoundationNW(ti->tile, slope, z)) sprite_block += 1;
445 if (!HasFoundationNE(ti->tile, slope, z)) sprite_block += 2;
447 /* Use the original slope sprites if NW and NE borders should be visible */
448 SpriteID leveled_base = (sprite_block == 0 ? (int)SPR_FOUNDATION_BASE : (SPR_SLOPES_VIRTUAL_BASE + sprite_block * SPR_TRKFOUND_BLOCK_SIZE));
449 SpriteID inclined_base = SPR_SLOPES_VIRTUAL_BASE + SPR_SLOPES_INCLINED_OFFSET + sprite_block * SPR_TRKFOUND_BLOCK_SIZE;
450 SpriteID halftile_base = SPR_HALFTILE_FOUNDATION_BASE + sprite_block * SPR_HALFTILE_BLOCK_SIZE;
452 if (IsSteepSlope(ti->tileh)) {
453 if (!IsNonContinuousFoundation(f)) {
454 /* Lower part of foundation */
455 AddSortableSpriteToDraw(
456 leveled_base + (ti->tileh & ~SLOPE_STEEP), PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z
460 Corner highest_corner = GetHighestSlopeCorner(ti->tileh);
461 ti->z += ApplyPixelFoundationToSlope(f, &ti->tileh);
463 if (IsInclinedFoundation(f)) {
464 /* inclined foundation */
465 byte inclined = highest_corner * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
467 AddSortableSpriteToDraw(inclined_base + inclined, PAL_NONE, ti->x, ti->y,
468 f == FOUNDATION_INCLINED_X ? TILE_SIZE : 1,
469 f == FOUNDATION_INCLINED_Y ? TILE_SIZE : 1,
470 TILE_HEIGHT, ti->z
472 OffsetGroundSprite(0, 0);
473 } else if (IsLeveledFoundation(f)) {
474 AddSortableSpriteToDraw(leveled_base + SlopeWithOneCornerRaised(highest_corner), PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z - TILE_HEIGHT);
475 OffsetGroundSprite(0, -(int)TILE_HEIGHT);
476 } else if (f == FOUNDATION_STEEP_LOWER) {
477 /* one corner raised */
478 OffsetGroundSprite(0, -(int)TILE_HEIGHT);
479 } else {
480 /* halftile foundation */
481 int x_bb = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ? TILE_SIZE / 2 : 0);
482 int y_bb = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ? TILE_SIZE / 2 : 0);
484 AddSortableSpriteToDraw(halftile_base + highest_corner, PAL_NONE, ti->x + x_bb, ti->y + y_bb, TILE_SIZE / 2, TILE_SIZE / 2, TILE_HEIGHT - 1, ti->z + TILE_HEIGHT);
485 /* Reposition ground sprite back to original position after bounding box change above. This is similar to
486 * RemapCoords() but without zoom scaling. */
487 Point pt = {(y_bb - x_bb) * 2, y_bb + x_bb};
488 OffsetGroundSprite(-pt.x, -pt.y);
490 } else {
491 if (IsLeveledFoundation(f)) {
492 /* leveled foundation */
493 AddSortableSpriteToDraw(leveled_base + ti->tileh, PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z);
494 OffsetGroundSprite(0, -(int)TILE_HEIGHT);
495 } else if (IsNonContinuousFoundation(f)) {
496 /* halftile foundation */
497 Corner halftile_corner = GetHalftileFoundationCorner(f);
498 int x_bb = (((halftile_corner == CORNER_W) || (halftile_corner == CORNER_S)) ? TILE_SIZE / 2 : 0);
499 int y_bb = (((halftile_corner == CORNER_S) || (halftile_corner == CORNER_E)) ? TILE_SIZE / 2 : 0);
501 AddSortableSpriteToDraw(halftile_base + halftile_corner, PAL_NONE, ti->x + x_bb, ti->y + y_bb, TILE_SIZE / 2, TILE_SIZE / 2, TILE_HEIGHT - 1, ti->z);
502 /* Reposition ground sprite back to original position after bounding box change above. This is similar to
503 * RemapCoords() but without zoom scaling. */
504 Point pt = {(y_bb - x_bb) * 2, y_bb + x_bb};
505 OffsetGroundSprite(-pt.x, -pt.y);
506 } else if (IsSpecialRailFoundation(f)) {
507 /* anti-zig-zag foundation */
508 SpriteID spr;
509 if (ti->tileh == SLOPE_NS || ti->tileh == SLOPE_EW) {
510 /* half of leveled foundation under track corner */
511 spr = leveled_base + SlopeWithThreeCornersRaised(GetRailFoundationCorner(f));
512 } else {
513 /* tile-slope = sloped along X/Y, foundation-slope = three corners raised */
514 spr = inclined_base + 2 * GetRailFoundationCorner(f) + ((ti->tileh == SLOPE_SW || ti->tileh == SLOPE_NE) ? 1 : 0);
516 AddSortableSpriteToDraw(spr, PAL_NONE, ti->x, ti->y, TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1, ti->z);
517 OffsetGroundSprite(0, 0);
518 } else {
519 /* inclined foundation */
520 byte inclined = GetHighestSlopeCorner(ti->tileh) * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
522 AddSortableSpriteToDraw(inclined_base + inclined, PAL_NONE, ti->x, ti->y,
523 f == FOUNDATION_INCLINED_X ? TILE_SIZE : 1,
524 f == FOUNDATION_INCLINED_Y ? TILE_SIZE : 1,
525 TILE_HEIGHT, ti->z
527 OffsetGroundSprite(0, 0);
529 ti->z += ApplyPixelFoundationToSlope(f, &ti->tileh);
533 void DoClearSquare(TileIndex tile)
535 /* If the tile can have animation and we clear it, delete it from the animated tile list. */
536 if (_tile_type_procs[GetTileType(tile)]->animate_tile_proc != nullptr) DeleteAnimatedTile(tile);
538 bool remove = IsDockingTile(tile);
539 MakeClear(tile, CLEAR_GRASS, _generating_world ? 3 : 0);
540 MarkTileDirtyByTile(tile);
541 if (remove) RemoveDockingTile(tile);
543 InvalidateWaterRegion(tile);
547 * Returns information about trackdirs and signal states.
548 * If there is any trackbit at 'side', return all trackdirbits.
549 * For TRANSPORT_ROAD, return no trackbits if there is no roadbit (of given subtype) at given side.
550 * @param tile tile to get info about
551 * @param mode transport type
552 * @param sub_mode for TRANSPORT_ROAD, roadtypes to check
553 * @param side side we are entering from, INVALID_DIAGDIR to return all trackbits
554 * @return trackdirbits and other info depending on 'mode'
556 TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
558 return _tile_type_procs[GetTileType(tile)]->get_tile_track_status_proc(tile, mode, sub_mode, side);
562 * Change the owner of a tile
563 * @param tile Tile to change
564 * @param old_owner Current owner of the tile
565 * @param new_owner New owner of the tile
567 void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
569 _tile_type_procs[GetTileType(tile)]->change_tile_owner_proc(tile, old_owner, new_owner);
572 void GetTileDesc(TileIndex tile, TileDesc *td)
574 _tile_type_procs[GetTileType(tile)]->get_tile_desc_proc(tile, td);
578 * Has a snow line table already been loaded.
579 * @return true if the table has been loaded already.
580 * @ingroup SnowLineGroup
582 bool IsSnowLineSet()
584 return _snow_line != nullptr;
588 * Set a variable snow line, as loaded from a newgrf file.
589 * @param table the 12 * 32 byte table containing the snowline for each day
590 * @ingroup SnowLineGroup
592 void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
594 _snow_line = CallocT<SnowLine>(1);
595 _snow_line->lowest_value = 0xFF;
596 memcpy(_snow_line->table, table, sizeof(_snow_line->table));
598 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
599 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
600 _snow_line->highest_value = std::max(_snow_line->highest_value, table[i][j]);
601 _snow_line->lowest_value = std::min(_snow_line->lowest_value, table[i][j]);
607 * Get the current snow line, either variable or static.
608 * @return the snow line height.
609 * @ingroup SnowLineGroup
611 byte GetSnowLine()
613 if (_snow_line == nullptr) return _settings_game.game_creation.snow_line_height;
615 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
616 return _snow_line->table[ymd.month][ymd.day];
620 * Get the highest possible snow line height, either variable or static.
621 * @return the highest snow line height.
622 * @ingroup SnowLineGroup
624 byte HighestSnowLine()
626 return _snow_line == nullptr ? _settings_game.game_creation.snow_line_height : _snow_line->highest_value;
630 * Get the lowest possible snow line height, either variable or static.
631 * @return the lowest snow line height.
632 * @ingroup SnowLineGroup
634 byte LowestSnowLine()
636 return _snow_line == nullptr ? _settings_game.game_creation.snow_line_height : _snow_line->lowest_value;
640 * Clear the variable snow line table and free the memory.
641 * @ingroup SnowLineGroup
643 void ClearSnowLine()
645 free(_snow_line);
646 _snow_line = nullptr;
650 * Clear a piece of landscape
651 * @param flags of operation to conduct
652 * @param tile tile to clear
653 * @return the cost of this operation or an error
655 CommandCost CmdLandscapeClear(DoCommandFlag flags, TileIndex tile)
657 CommandCost cost(EXPENSES_CONSTRUCTION);
658 bool do_clear = false;
659 /* Test for stuff which results in water when cleared. Then add the cost to also clear the water. */
660 if ((flags & DC_FORCE_CLEAR_TILE) && HasTileWaterClass(tile) && IsTileOnWater(tile) && !IsWaterTile(tile) && !IsCoastTile(tile)) {
661 if ((flags & DC_AUTO) && GetWaterClass(tile) == WATER_CLASS_CANAL) return_cmd_error(STR_ERROR_MUST_DEMOLISH_CANAL_FIRST);
662 do_clear = true;
663 cost.AddCost(GetWaterClass(tile) == WATER_CLASS_CANAL ? _price[PR_CLEAR_CANAL] : _price[PR_CLEAR_WATER]);
666 Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? nullptr : Company::GetIfValid(_current_company);
667 if (c != nullptr && (int)GB(c->clear_limit, 16, 16) < 1) {
668 return_cmd_error(STR_ERROR_CLEARING_LIMIT_REACHED);
671 const ClearedObjectArea *coa = FindClearedObject(tile);
673 /* If this tile was the first tile which caused object destruction, always
674 * pass it on to the tile_type_proc. That way multiple test runs and the exec run stay consistent. */
675 if (coa != nullptr && coa->first_tile != tile) {
676 /* If this tile belongs to an object which was already cleared via another tile, pretend it has been
677 * already removed.
678 * However, we need to check stuff, which is not the same for all object tiles. (e.g. being on water or not) */
680 /* If a object is removed, it leaves either bare land or water. */
681 if ((flags & DC_NO_WATER) && HasTileWaterClass(tile) && IsTileOnWater(tile)) {
682 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
684 } else {
685 cost.AddCost(_tile_type_procs[GetTileType(tile)]->clear_tile_proc(tile, flags));
688 if (flags & DC_EXEC) {
689 if (c != nullptr) c->clear_limit -= 1 << 16;
690 if (do_clear) DoClearSquare(tile);
692 return cost;
696 * Clear a big piece of landscape
697 * @param flags of operation to conduct
698 * @param tile end tile of area dragging
699 * @param start_tile start tile of area dragging
700 * @param diagonal Whether to use the Orthogonal (false) or Diagonal (true) iterator.
701 * @return the cost of this operation or an error
703 std::tuple<CommandCost, Money> CmdClearArea(DoCommandFlag flags, TileIndex tile, TileIndex start_tile, bool diagonal)
705 if (start_tile >= Map::Size()) return { CMD_ERROR, 0 };
707 Money money = GetAvailableMoneyForCommand();
708 CommandCost cost(EXPENSES_CONSTRUCTION);
709 CommandCost last_error = CMD_ERROR;
710 bool had_success = false;
712 const Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? nullptr : Company::GetIfValid(_current_company);
713 int limit = (c == nullptr ? INT32_MAX : GB(c->clear_limit, 16, 16));
715 if (tile != start_tile) flags |= DC_FORCE_CLEAR_TILE;
717 std::unique_ptr<TileIterator> iter = TileIterator::Create(tile, start_tile, diagonal);
718 for (; *iter != INVALID_TILE; ++(*iter)) {
719 TileIndex t = *iter;
720 CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags & ~DC_EXEC, t);
721 if (ret.Failed()) {
722 last_error = ret;
724 /* We may not clear more tiles. */
725 if (c != nullptr && GB(c->clear_limit, 16, 16) < 1) break;
726 continue;
729 had_success = true;
730 if (flags & DC_EXEC) {
731 money -= ret.GetCost();
732 if (ret.GetCost() > 0 && money < 0) {
733 return { cost, ret.GetCost() };
735 Command<CMD_LANDSCAPE_CLEAR>::Do(flags, t);
737 /* draw explosion animation...
738 * Disable explosions when game is paused. Looks silly and blocks the view. */
739 if ((t == tile || t == start_tile) && _pause_mode == PM_UNPAUSED) {
740 /* big explosion in two corners, or small explosion for single tiles */
741 CreateEffectVehicleAbove(TileX(t) * TILE_SIZE + TILE_SIZE / 2, TileY(t) * TILE_SIZE + TILE_SIZE / 2, 2,
742 TileX(tile) == TileX(start_tile) && TileY(tile) == TileY(start_tile) ? EV_EXPLOSION_SMALL : EV_EXPLOSION_LARGE
745 } else {
746 /* When we're at the clearing limit we better bail (unneed) testing as well. */
747 if (ret.GetCost() != 0 && --limit <= 0) break;
749 cost.AddCost(ret);
752 return { had_success ? cost : last_error, 0 };
756 TileIndex _cur_tileloop_tile;
759 * Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks.
761 void RunTileLoop()
763 PerformanceAccumulator framerate(PFE_GL_LANDSCAPE);
765 /* The pseudorandom sequence of tiles is generated using a Galois linear feedback
766 * shift register (LFSR). This allows a deterministic pseudorandom ordering, but
767 * still with minimal state and fast iteration. */
769 /* Maximal length LFSR feedback terms, from 12-bit (for 64x64 maps) to 24-bit (for 4096x4096 maps).
770 * Extracted from http://www.ece.cmu.edu/~koopman/lfsr/ */
771 static const uint32_t feedbacks[] = {
772 0xD8F, 0x1296, 0x2496, 0x4357, 0x8679, 0x1030E, 0x206CD, 0x403FE, 0x807B8, 0x1004B2, 0x2006A8, 0x4004B2, 0x800B87
774 static_assert(lengthof(feedbacks) == 2 * MAX_MAP_SIZE_BITS - 2 * MIN_MAP_SIZE_BITS + 1);
775 const uint32_t feedback = feedbacks[Map::LogX() + Map::LogY() - 2 * MIN_MAP_SIZE_BITS];
777 /* We update every tile every 256 ticks, so divide the map size by 2^8 = 256 */
778 uint count = 1 << (Map::LogX() + Map::LogY() - 8);
780 TileIndex tile = _cur_tileloop_tile;
781 /* The LFSR cannot have a zeroed state. */
782 assert(tile != 0);
784 /* Manually update tile 0 every 256 ticks - the LFSR never iterates over it itself. */
785 if (TimerGameTick::counter % 256 == 0) {
786 _tile_type_procs[GetTileType(0)]->tile_loop_proc(0);
787 count--;
790 while (count--) {
791 _tile_type_procs[GetTileType(tile)]->tile_loop_proc(tile);
793 /* Get the next tile in sequence using a Galois LFSR. */
794 tile = (tile.base() >> 1) ^ (-(int32_t)(tile.base() & 1) & feedback);
797 _cur_tileloop_tile = tile;
800 void InitializeLandscape()
802 for (uint y = _settings_game.construction.freeform_edges ? 1 : 0; y < Map::MaxY(); y++) {
803 for (uint x = _settings_game.construction.freeform_edges ? 1 : 0; x < Map::MaxX(); x++) {
804 MakeClear(TileXY(x, y), CLEAR_GRASS, 3);
805 SetTileHeight(TileXY(x, y), 0);
806 SetTropicZone(TileXY(x, y), TROPICZONE_NORMAL);
807 ClearBridgeMiddle(TileXY(x, y));
811 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, Map::MaxY()));
812 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(Map::MaxX(), y));
815 static const byte _genterrain_tbl_1[5] = { 10, 22, 33, 37, 4 };
816 static const byte _genterrain_tbl_2[5] = { 0, 0, 0, 0, 33 };
818 static void GenerateTerrain(int type, uint flag)
820 uint32_t r = Random();
822 /* Choose one of the templates from the graphics file. */
823 const Sprite *templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + SPR_MAPGEN_BEGIN, SpriteType::MapGen);
824 if (templ == nullptr) UserError("Map generator sprites could not be loaded");
826 /* Chose a random location to apply the template to. */
827 uint x = r & Map::MaxX();
828 uint y = (r >> Map::LogX()) & Map::MaxY();
830 /* Make sure the template is not too close to the upper edges; bottom edges are checked later. */
831 uint edge_distance = 1 + (_settings_game.construction.freeform_edges ? 1 : 0);
832 if (x <= edge_distance || y <= edge_distance) return;
834 DiagDirection direction = (DiagDirection)GB(r, 22, 2);
835 uint w = templ->width;
836 uint h = templ->height;
838 if (DiagDirToAxis(direction) == AXIS_Y) Swap(w, h);
840 const byte *p = templ->data;
842 if ((flag & 4) != 0) {
843 /* This is only executed in secondary/tertiary loops to generate the terrain for arctic and tropic.
844 * It prevents the templates to be applied to certain parts of the map based on the flags, thus
845 * creating regions with different elevations/topography. */
846 uint xw = x * Map::SizeY();
847 uint yw = y * Map::SizeX();
848 uint bias = (Map::SizeX() + Map::SizeY()) * 16;
850 switch (flag & 3) {
851 default: NOT_REACHED();
852 case 0:
853 if (xw + yw > Map::Size() - bias) return;
854 break;
856 case 1:
857 if (yw < xw + bias) return;
858 break;
860 case 2:
861 if (xw + yw < Map::Size() + bias) return;
862 break;
864 case 3:
865 if (xw < yw + bias) return;
866 break;
870 /* Ensure the template does not overflow at the bottom edges of the map; upper edges were checked before. */
871 if (x + w >= Map::MaxX()) return;
872 if (y + h >= Map::MaxY()) return;
874 TileIndex tile = TileXY(x, y);
876 /* Get the template and overlay in a particular direction over the map's height from the given
877 * origin point (tile), and update the map's height everywhere where the height from the template
878 * is higher than the height of the map. In other words, this only raises the tile heights. */
879 switch (direction) {
880 default: NOT_REACHED();
881 case DIAGDIR_NE:
882 do {
883 TileIndex tile_cur = tile;
885 for (uint w_cur = w; w_cur != 0; --w_cur) {
886 if (GB(*p, 0, 4) >= TileHeight(tile_cur)) SetTileHeight(tile_cur, GB(*p, 0, 4));
887 p++;
888 tile_cur++;
890 tile += TileDiffXY(0, 1);
891 } while (--h != 0);
892 break;
894 case DIAGDIR_SE:
895 do {
896 TileIndex tile_cur = tile;
898 for (uint h_cur = h; h_cur != 0; --h_cur) {
899 if (GB(*p, 0, 4) >= TileHeight(tile_cur)) SetTileHeight(tile_cur, GB(*p, 0, 4));
900 p++;
901 tile_cur += TileDiffXY(0, 1);
903 tile += TileDiffXY(1, 0);
904 } while (--w != 0);
905 break;
907 case DIAGDIR_SW:
908 tile += TileDiffXY(w - 1, 0);
909 do {
910 TileIndex tile_cur = tile;
912 for (uint w_cur = w; w_cur != 0; --w_cur) {
913 if (GB(*p, 0, 4) >= TileHeight(tile_cur)) SetTileHeight(tile_cur, GB(*p, 0, 4));
914 p++;
915 tile_cur--;
917 tile += TileDiffXY(0, 1);
918 } while (--h != 0);
919 break;
921 case DIAGDIR_NW:
922 tile += TileDiffXY(0, h - 1);
923 do {
924 TileIndex tile_cur = tile;
926 for (uint h_cur = h; h_cur != 0; --h_cur) {
927 if (GB(*p, 0, 4) >= TileHeight(tile_cur)) SetTileHeight(tile_cur, GB(*p, 0, 4));
928 p++;
929 tile_cur -= TileDiffXY(0, 1);
931 tile += TileDiffXY(1, 0);
932 } while (--w != 0);
933 break;
938 #include "table/genland.h"
940 static void CreateDesertOrRainForest(uint desert_tropic_line)
942 uint update_freq = Map::Size() / 4;
943 const TileIndexDiffC *data;
945 for (TileIndex tile = 0; tile != Map::Size(); ++tile) {
946 if ((tile.base() % update_freq) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
948 if (!IsValidTile(tile)) continue;
950 for (data = _make_desert_or_rainforest_data;
951 data != endof(_make_desert_or_rainforest_data); ++data) {
952 TileIndex t = AddTileIndexDiffCWrap(tile, *data);
953 if (t != INVALID_TILE && (TileHeight(t) >= desert_tropic_line || IsTileType(t, MP_WATER))) break;
955 if (data == endof(_make_desert_or_rainforest_data)) {
956 SetTropicZone(tile, TROPICZONE_DESERT);
960 for (uint i = 0; i != 256; i++) {
961 if ((i % 64) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
963 RunTileLoop();
966 for (TileIndex tile = 0; tile != Map::Size(); ++tile) {
967 if ((tile.base() % update_freq) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
969 if (!IsValidTile(tile)) continue;
971 for (data = _make_desert_or_rainforest_data;
972 data != endof(_make_desert_or_rainforest_data); ++data) {
973 TileIndex t = AddTileIndexDiffCWrap(tile, *data);
974 if (t != INVALID_TILE && IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_DESERT)) break;
976 if (data == endof(_make_desert_or_rainforest_data)) {
977 SetTropicZone(tile, TROPICZONE_RAINFOREST);
983 * Find the spring of a river.
984 * @param tile The tile to consider for being the spring.
985 * @return True iff it is suitable as a spring.
987 static bool FindSpring(TileIndex tile, void *)
989 int referenceHeight;
990 if (!IsTileFlat(tile, &referenceHeight) || IsWaterTile(tile)) return false;
992 /* In the tropics rivers start in the rainforest. */
993 if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) != TROPICZONE_RAINFOREST) return false;
995 /* Are there enough higher tiles to warrant a 'spring'? */
996 uint num = 0;
997 for (int dx = -1; dx <= 1; dx++) {
998 for (int dy = -1; dy <= 1; dy++) {
999 TileIndex t = TileAddWrap(tile, dx, dy);
1000 if (t != INVALID_TILE && GetTileMaxZ(t) > referenceHeight) num++;
1004 if (num < 4) return false;
1006 /* Are we near the top of a hill? */
1007 for (int dx = -16; dx <= 16; dx++) {
1008 for (int dy = -16; dy <= 16; dy++) {
1009 TileIndex t = TileAddWrap(tile, dx, dy);
1010 if (t != INVALID_TILE && GetTileMaxZ(t) > referenceHeight + 2) return false;
1014 return true;
1018 * Make a connected lake; fill all tiles in the circular tile search that are connected.
1019 * @param tile The tile to consider for lake making.
1020 * @param user_data The height of the lake.
1021 * @return Always false, so it continues searching.
1023 static bool MakeLake(TileIndex tile, void *user_data)
1025 uint height = *(uint*)user_data;
1026 if (!IsValidTile(tile) || TileHeight(tile) != height || !IsTileFlat(tile)) return false;
1027 if (_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) == TROPICZONE_DESERT) return false;
1029 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
1030 TileIndex t2 = tile + TileOffsByDiagDir(d);
1031 if (IsWaterTile(t2)) {
1032 MakeRiverAndModifyDesertZoneAround(tile);
1033 return false;
1037 return false;
1041 * Widen a river by expanding into adjacent tiles via circular tile search.
1042 * @param tile The tile to try expanding the river into.
1043 * @param data The tile to try surrounding the river around.
1044 * @return Always false, so it continues searching.
1046 static bool RiverMakeWider(TileIndex tile, void *data)
1048 /* Don't expand into void tiles. */
1049 if (!IsValidTile(tile)) return false;
1051 /* If the tile is already sea or river, don't expand. */
1052 if (IsWaterTile(tile)) return false;
1054 /* If the tile is at height 0 after terraforming but the ocean hasn't flooded yet, don't build river. */
1055 if (GetTileMaxZ(tile) == 0) return false;
1057 TileIndex origin_tile = *(TileIndex *)data;
1058 Slope cur_slope = GetTileSlope(tile);
1059 Slope desired_slope = GetTileSlope(origin_tile); // Initialize matching the origin tile as a shortcut if no terraforming is needed.
1061 /* Never flow uphill. */
1062 if (GetTileMaxZ(tile) > GetTileMaxZ(origin_tile)) return false;
1064 /* If the new tile can't hold a river tile, try terraforming. */
1065 if (!IsTileFlat(tile) && !IsInclinedSlope(cur_slope)) {
1066 /* Don't try to terraform steep slopes. */
1067 if (IsSteepSlope(cur_slope)) return false;
1069 bool flat_river_found = false;
1070 bool sloped_river_found = false;
1072 /* There are two common possibilities:
1073 * 1. River flat, adjacent tile has one corner lowered.
1074 * 2. River descending, adjacent tile has either one or three corners raised.
1077 /* First, determine the desired slope based on adjacent river tiles. This doesn't necessarily match the origin tile for the CircularTileSearch. */
1078 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
1079 TileIndex other_tile = TileAddByDiagDir(tile, d);
1080 Slope other_slope = GetTileSlope(other_tile);
1082 /* Only consider river tiles. */
1083 if (IsWaterTile(other_tile) && IsRiver(other_tile)) {
1084 /* If the adjacent river tile flows downhill, we need to check where we are relative to the slope. */
1085 if (IsInclinedSlope(other_slope) && GetTileMaxZ(tile) == GetTileMaxZ(other_tile)) {
1086 /* Check for a parallel slope. If we don't find one, we're above or below the slope instead. */
1087 if (GetInclinedSlopeDirection(other_slope) == ChangeDiagDir(d, DIAGDIRDIFF_90RIGHT) ||
1088 GetInclinedSlopeDirection(other_slope) == ChangeDiagDir(d, DIAGDIRDIFF_90LEFT)) {
1089 desired_slope = other_slope;
1090 sloped_river_found = true;
1091 break;
1094 /* If we find an adjacent river tile, remember it. We'll terraform to match it later if we don't find a slope. */
1095 if (IsTileFlat(other_tile)) flat_river_found = true;
1098 /* We didn't find either an inclined or flat river, so we're climbing the wrong slope. Bail out. */
1099 if (!sloped_river_found && !flat_river_found) return false;
1101 /* We didn't find an inclined river, but there is a flat river. */
1102 if (!sloped_river_found && flat_river_found) desired_slope = SLOPE_FLAT;
1104 /* Now that we know the desired slope, it's time to terraform! */
1106 /* If the river is flat and the adjacent tile has one corner lowered, we want to raise it. */
1107 if (desired_slope == SLOPE_FLAT && IsSlopeWithThreeCornersRaised(cur_slope)) {
1108 /* Make sure we're not affecting an existing river slope tile. */
1109 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
1110 TileIndex other_tile = TileAddByDiagDir(tile, d);
1111 if (IsInclinedSlope(GetTileSlope(other_tile)) && IsWaterTile(other_tile)) return false;
1113 Command<CMD_TERRAFORM_LAND>::Do(DC_EXEC | DC_AUTO, tile, ComplementSlope(cur_slope), true);
1115 /* If the river is descending and the adjacent tile has either one or three corners raised, we want to make it match the slope. */
1116 } else if (IsInclinedSlope(desired_slope)) {
1117 /* Don't break existing flat river tiles by terraforming under them. */
1118 DiagDirection river_direction = ReverseDiagDir(GetInclinedSlopeDirection(desired_slope));
1120 for (DiagDirDiff d = DIAGDIRDIFF_BEGIN; d < DIAGDIRDIFF_END; d++) {
1121 /* We don't care about downstream or upstream tiles, just the riverbanks. */
1122 if (d == DIAGDIRDIFF_SAME || d == DIAGDIRDIFF_REVERSE) continue;
1124 TileIndex other_tile = (TileAddByDiagDir(tile, ChangeDiagDir(river_direction, d)));
1125 if (IsWaterTile(other_tile) && IsRiver(other_tile) && IsTileFlat(other_tile)) return false;
1128 /* Get the corners which are different between the current and desired slope. */
1129 Slope to_change = cur_slope ^ desired_slope;
1131 /* Lower unwanted corners first. If only one corner is raised, no corners need lowering. */
1132 if (!IsSlopeWithOneCornerRaised(cur_slope)) {
1133 to_change = to_change & ComplementSlope(desired_slope);
1134 Command<CMD_TERRAFORM_LAND>::Do(DC_EXEC | DC_AUTO, tile, to_change, false);
1137 /* Now check the match and raise any corners needed. */
1138 cur_slope = GetTileSlope(tile);
1139 if (cur_slope != desired_slope && IsSlopeWithOneCornerRaised(cur_slope)) {
1140 to_change = cur_slope ^ desired_slope;
1141 Command<CMD_TERRAFORM_LAND>::Do(DC_EXEC | DC_AUTO, tile, to_change, true);
1144 /* Update cur_slope after possibly terraforming. */
1145 cur_slope = GetTileSlope(tile);
1148 /* Sloped rivers need water both upstream and downstream. */
1149 if (IsInclinedSlope(cur_slope)) {
1150 DiagDirection slope_direction = GetInclinedSlopeDirection(cur_slope);
1152 TileIndex upstream_tile = TileAddByDiagDir(tile, slope_direction);
1153 TileIndex downstream_tile = TileAddByDiagDir(tile, ReverseDiagDir(slope_direction));
1155 /* Don't look outside the map. */
1156 if (!IsValidTile(upstream_tile) || !IsValidTile(downstream_tile)) return false;
1158 /* Downstream might be new ocean created by our terraforming, and it hasn't flooded yet. */
1159 bool downstream_is_ocean = GetTileZ(downstream_tile) == 0 && (GetTileSlope(downstream_tile) == SLOPE_FLAT || IsSlopeWithOneCornerRaised(GetTileSlope(downstream_tile)));
1161 /* If downstream is dry, flat, and not ocean, try making it a river tile. */
1162 if (!IsWaterTile(downstream_tile) && !downstream_is_ocean) {
1163 /* If the tile upstream isn't flat, don't bother. */
1164 if (GetTileSlope(downstream_tile) != SLOPE_FLAT) return false;
1166 MakeRiverAndModifyDesertZoneAround(downstream_tile);
1169 /* If upstream is dry and flat, try making it a river tile. */
1170 if (!IsWaterTile(upstream_tile)) {
1171 /* If the tile upstream isn't flat, don't bother. */
1172 if (GetTileSlope(upstream_tile) != SLOPE_FLAT) return false;
1174 MakeRiverAndModifyDesertZoneAround(upstream_tile);
1178 /* If the tile slope matches the desired slope, add a river tile. */
1179 if (cur_slope == desired_slope) {
1180 MakeRiverAndModifyDesertZoneAround(tile);
1183 /* Always return false to keep searching. */
1184 return false;
1188 * Check whether a river at begin could (logically) flow down to end.
1189 * @param begin The origin of the flow.
1190 * @param end The destination of the flow.
1191 * @return True iff the water can be flowing down.
1193 static bool FlowsDown(TileIndex begin, TileIndex end)
1195 assert(DistanceManhattan(begin, end) == 1);
1197 int heightBegin;
1198 int heightEnd;
1199 Slope slopeBegin = GetTileSlope(begin, &heightBegin);
1200 Slope slopeEnd = GetTileSlope(end, &heightEnd);
1202 return heightEnd <= heightBegin &&
1203 /* Slope either is inclined or flat; rivers don't support other slopes. */
1204 (slopeEnd == SLOPE_FLAT || IsInclinedSlope(slopeEnd)) &&
1205 /* Slope continues, then it must be lower... or either end must be flat. */
1206 ((slopeEnd == slopeBegin && heightEnd < heightBegin) || slopeEnd == SLOPE_FLAT || slopeBegin == SLOPE_FLAT);
1209 /** Parameters for river generation to pass as AyStar user data. */
1210 struct River_UserData {
1211 TileIndex spring; ///< The current spring during river generation.
1212 bool main_river; ///< Whether the current river is a big river that others flow into.
1215 /* AyStar callback for checking whether we reached our destination. */
1216 static int32_t River_EndNodeCheck(const AyStar *aystar, const OpenListNode *current)
1218 return current->path.node.tile == *(TileIndex*)aystar->user_target ? AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
1221 /* AyStar callback for getting the cost of the current node. */
1222 static int32_t River_CalculateG(AyStar *, AyStarNode *, OpenListNode *)
1224 return 1 + RandomRange(_settings_game.game_creation.river_route_random);
1227 /* AyStar callback for getting the estimated cost to the destination. */
1228 static int32_t River_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *)
1230 return DistanceManhattan(*(TileIndex*)aystar->user_target, current->tile);
1233 /* AyStar callback for getting the neighbouring nodes of the given node. */
1234 static void River_GetNeighbours(AyStar *aystar, OpenListNode *current)
1236 TileIndex tile = current->path.node.tile;
1238 aystar->num_neighbours = 0;
1239 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
1240 TileIndex t2 = tile + TileOffsByDiagDir(d);
1241 if (IsValidTile(t2) && FlowsDown(tile, t2)) {
1242 aystar->neighbours[aystar->num_neighbours].tile = t2;
1243 aystar->neighbours[aystar->num_neighbours].direction = INVALID_TRACKDIR;
1244 aystar->num_neighbours++;
1249 /* AyStar callback when an route has been found. */
1250 static void River_FoundEndNode(AyStar *aystar, OpenListNode *current)
1252 River_UserData *data = (River_UserData *)aystar->user_data;
1254 /* First, build the river without worrying about its width. */
1255 uint cur_pos = 0;
1256 for (PathNode *path = &current->path; path != nullptr; path = path->parent, cur_pos++) {
1257 TileIndex tile = path->node.tile;
1258 if (!IsWaterTile(tile)) {
1259 MakeRiverAndModifyDesertZoneAround(tile);
1263 /* If the river is a main river, go back along the path to widen it.
1264 * Don't make wide rivers if we're using the original landscape generator.
1266 if (_settings_game.game_creation.land_generator != LG_ORIGINAL && data->main_river) {
1267 const uint long_river_length = _settings_game.game_creation.min_river_length * 4;
1268 uint current_river_length;
1269 uint radius;
1271 cur_pos = 0;
1272 for (PathNode *path = &current->path; path != nullptr; path = path->parent, cur_pos++) {
1273 TileIndex tile = path->node.tile;
1275 /* Check if we should widen river depending on how far we are away from the source. */
1276 current_river_length = DistanceManhattan(data->spring, tile);
1277 radius = std::min(3u, (current_river_length / (long_river_length / 3u)) + 1u);
1279 if (radius > 1) CircularTileSearch(&tile, radius, RiverMakeWider, (void *)&path->node.tile);
1284 static const uint RIVER_HASH_SIZE = 8; ///< The number of bits the hash for river finding should have.
1287 * Simple hash function for river tiles to be used by AyStar.
1288 * @param tile The tile to hash.
1289 * @return The hash for the tile.
1291 static uint River_Hash(TileIndex tile, Trackdir)
1293 return GB(TileHash(TileX(tile), TileY(tile)), 0, RIVER_HASH_SIZE);
1297 * Actually build the river between the begin and end tiles using AyStar.
1298 * @param begin The begin of the river.
1299 * @param end The end of the river.
1300 * @param spring The springing point of the river.
1301 * @param main_river Whether the current river is a big river that others flow into.
1303 static void BuildRiver(TileIndex begin, TileIndex end, TileIndex spring, bool main_river)
1305 River_UserData user_data = { spring, main_river };
1307 AyStar finder = {};
1308 finder.CalculateG = River_CalculateG;
1309 finder.CalculateH = River_CalculateH;
1310 finder.GetNeighbours = River_GetNeighbours;
1311 finder.EndNodeCheck = River_EndNodeCheck;
1312 finder.FoundEndNode = River_FoundEndNode;
1313 finder.user_target = &end;
1314 finder.user_data = &user_data;
1316 finder.Init(River_Hash, 1 << RIVER_HASH_SIZE);
1318 AyStarNode start;
1319 start.tile = begin;
1320 start.direction = INVALID_TRACKDIR;
1321 finder.AddStartNode(&start, 0);
1322 finder.Main();
1323 finder.Free();
1327 * Try to flow the river down from a given begin.
1328 * @param spring The springing point of the river.
1329 * @param begin The begin point we are looking from; somewhere down hill from the spring.
1330 * @param min_river_length The minimum length for the river.
1331 * @return First element: True iff a river could/has been built, otherwise false; second element: River ends at sea.
1333 static std::tuple<bool, bool> FlowRiver(TileIndex spring, TileIndex begin, uint min_river_length)
1335 # define SET_MARK(x) marks.insert(x)
1336 # define IS_MARKED(x) (marks.find(x) != marks.end())
1338 uint height = TileHeight(begin);
1340 if (IsWaterTile(begin)) {
1341 return { DistanceManhattan(spring, begin) > min_river_length, GetTileZ(begin) == 0 };
1344 std::set<TileIndex> marks;
1345 SET_MARK(begin);
1347 /* Breadth first search for the closest tile we can flow down to. */
1348 std::list<TileIndex> queue;
1349 queue.push_back(begin);
1351 bool found = false;
1352 uint count = 0; // Number of tiles considered; to be used for lake location guessing.
1353 TileIndex end;
1354 do {
1355 end = queue.front();
1356 queue.pop_front();
1358 uint height2 = TileHeight(end);
1359 if (IsTileFlat(end) && (height2 < height || (height2 == height && IsWaterTile(end)))) {
1360 found = true;
1361 break;
1364 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
1365 TileIndex t2 = end + TileOffsByDiagDir(d);
1366 if (IsValidTile(t2) && !IS_MARKED(t2) && FlowsDown(end, t2)) {
1367 SET_MARK(t2);
1368 count++;
1369 queue.push_back(t2);
1372 } while (!queue.empty());
1374 bool main_river = false;
1375 if (found) {
1376 /* Flow further down hill. */
1377 std::tie(found, main_river) = FlowRiver(spring, end, min_river_length);
1378 } else if (count > 32) {
1379 /* Maybe we can make a lake. Find the Nth of the considered tiles. */
1380 std::set<TileIndex>::const_iterator cit = marks.cbegin();
1381 std::advance(cit, RandomRange(count - 1));
1382 TileIndex lakeCenter = *cit;
1384 if (IsValidTile(lakeCenter) &&
1385 /* A river, or lake, can only be built on flat slopes. */
1386 IsTileFlat(lakeCenter) &&
1387 /* We want the lake to be built at the height of the river. */
1388 TileHeight(begin) == TileHeight(lakeCenter) &&
1389 /* We don't want the lake at the entry of the valley. */
1390 lakeCenter != begin &&
1391 /* We don't want lakes in the desert. */
1392 (_settings_game.game_creation.landscape != LT_TROPIC || GetTropicZone(lakeCenter) != TROPICZONE_DESERT) &&
1393 /* We only want a lake if the river is long enough. */
1394 DistanceManhattan(spring, lakeCenter) > min_river_length) {
1395 end = lakeCenter;
1396 MakeRiverAndModifyDesertZoneAround(lakeCenter);
1397 uint range = RandomRange(8) + 3;
1398 CircularTileSearch(&lakeCenter, range, MakeLake, &height);
1399 /* Call the search a second time so artefacts from going circular in one direction get (mostly) hidden. */
1400 lakeCenter = end;
1401 CircularTileSearch(&lakeCenter, range, MakeLake, &height);
1402 found = true;
1406 marks.clear();
1407 if (found) BuildRiver(begin, end, spring, main_river);
1408 return { found, main_river };
1412 * Actually (try to) create some rivers.
1414 static void CreateRivers()
1416 int amount = _settings_game.game_creation.amount_of_rivers;
1417 if (amount == 0) return;
1419 uint wells = Map::ScaleBySize(4 << _settings_game.game_creation.amount_of_rivers);
1420 const uint num_short_rivers = wells - std::max(1u, wells / 10);
1421 SetGeneratingWorldProgress(GWP_RIVER, wells + 256 / 64); // Include the tile loop calls below.
1423 /* Try to create long rivers. */
1424 for (; wells > num_short_rivers; wells--) {
1425 IncreaseGeneratingWorldProgress(GWP_RIVER);
1426 for (int tries = 0; tries < 512; tries++) {
1427 TileIndex t = RandomTile();
1428 if (!CircularTileSearch(&t, 8, FindSpring, nullptr)) continue;
1429 if (std::get<0>(FlowRiver(t, t, _settings_game.game_creation.min_river_length * 4))) break;
1433 /* Try to create short rivers. */
1434 for (; wells != 0; wells--) {
1435 IncreaseGeneratingWorldProgress(GWP_RIVER);
1436 for (int tries = 0; tries < 128; tries++) {
1437 TileIndex t = RandomTile();
1438 if (!CircularTileSearch(&t, 8, FindSpring, nullptr)) continue;
1439 if (std::get<0>(FlowRiver(t, t, _settings_game.game_creation.min_river_length))) break;
1443 /* Widening rivers may have left some tiles requiring to be watered. */
1444 ConvertGroundTilesIntoWaterTiles();
1446 /* Run tile loop to update the ground density. */
1447 for (uint i = 0; i != 256; i++) {
1448 if (i % 64 == 0) IncreaseGeneratingWorldProgress(GWP_RIVER);
1449 RunTileLoop();
1454 * Calculate what height would be needed to cover N% of the landmass.
1456 * The function allows both snow and desert/tropic line to be calculated. It
1457 * tries to find the closests height which covers N% of the landmass; it can
1458 * be below or above it.
1460 * Tropic has a mechanism where water and tropic tiles in mountains grow
1461 * inside the desert. To better approximate the requested coverage, this is
1462 * taken into account via an edge histogram, which tells how many neighbouring
1463 * tiles are lower than the tiles of that height. The multiplier indicates how
1464 * severe this has to be taken into account.
1466 * @param coverage A value between 0 and 100 indicating a percentage of landmass that should be covered.
1467 * @param edge_multiplier How much effect neighbouring tiles that are of a lower height level have on the score.
1468 * @return The estimated best height to use to cover N% of the landmass.
1470 static uint CalculateCoverageLine(uint coverage, uint edge_multiplier)
1472 const DiagDirection neighbour_dir[] = {
1473 DIAGDIR_NE,
1474 DIAGDIR_SE,
1475 DIAGDIR_SW,
1476 DIAGDIR_NW,
1479 /* Histogram of how many tiles per height level exist. */
1480 std::array<int, MAX_TILE_HEIGHT + 1> histogram = {};
1481 /* Histogram of how many neighbour tiles are lower than the tiles of the height level. */
1482 std::array<int, MAX_TILE_HEIGHT + 1> edge_histogram = {};
1484 /* Build a histogram of the map height. */
1485 for (TileIndex tile = 0; tile < Map::Size(); tile++) {
1486 uint h = TileHeight(tile);
1487 histogram[h]++;
1489 if (edge_multiplier != 0) {
1490 /* Check if any of our neighbours is below us. */
1491 for (auto dir : neighbour_dir) {
1492 TileIndex neighbour_tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir));
1493 if (IsValidTile(neighbour_tile) && TileHeight(neighbour_tile) < h) {
1494 edge_histogram[h]++;
1500 /* The amount of land we have is the map size minus the first (sea) layer. */
1501 uint land_tiles = Map::Size() - histogram[0];
1502 int best_score = land_tiles;
1504 /* Our goal is the coverage amount of the land-mass. */
1505 int goal_tiles = land_tiles * coverage / 100;
1507 /* We scan from top to bottom. */
1508 uint h = MAX_TILE_HEIGHT;
1509 uint best_h = h;
1511 int current_tiles = 0;
1512 for (; h > 0; h--) {
1513 current_tiles += histogram[h];
1514 int current_score = goal_tiles - current_tiles;
1516 /* Tropic grows from water and mountains into the desert. This is a
1517 * great visual, but it also means we* need to take into account how
1518 * much less desert tiles are being created if we are on this
1519 * height-level. We estimate this based on how many neighbouring
1520 * tiles are below us for a given length, assuming that is where
1521 * tropic is growing from.
1523 if (edge_multiplier != 0 && h > 1) {
1524 /* From water tropic tiles grow for a few tiles land inward. */
1525 current_score -= edge_histogram[1] * edge_multiplier;
1526 /* Tropic tiles grow into the desert for a few tiles. */
1527 current_score -= edge_histogram[h] * edge_multiplier;
1530 if (std::abs(current_score) < std::abs(best_score)) {
1531 best_score = current_score;
1532 best_h = h;
1535 /* Always scan all height-levels, as h == 1 might give a better
1536 * score than any before. This is true for example with 0% desert
1537 * coverage. */
1540 return best_h;
1544 * Calculate the line from which snow begins.
1546 static void CalculateSnowLine()
1548 /* We do not have snow sprites on coastal tiles, so never allow "1" as height. */
1549 _settings_game.game_creation.snow_line_height = std::max(CalculateCoverageLine(_settings_game.game_creation.snow_coverage, 0), 2u);
1553 * Calculate the line (in height) between desert and tropic.
1554 * @return The height of the line between desert and tropic.
1556 static uint8_t CalculateDesertLine()
1558 /* CalculateCoverageLine() runs from top to bottom, so we need to invert the coverage. */
1559 return CalculateCoverageLine(100 - _settings_game.game_creation.desert_coverage, 4);
1562 bool GenerateLandscape(byte mode)
1564 /** Number of steps of landscape generation */
1565 enum GenLandscapeSteps {
1566 GLS_HEIGHTMAP = 3, ///< Loading a heightmap
1567 GLS_TERRAGENESIS = 5, ///< Terragenesis generator
1568 GLS_ORIGINAL = 2, ///< Original generator
1569 GLS_TROPIC = 12, ///< Extra steps needed for tropic landscape
1570 GLS_OTHER = 0, ///< Extra steps for other landscapes
1572 uint steps = (_settings_game.game_creation.landscape == LT_TROPIC) ? GLS_TROPIC : GLS_OTHER;
1574 if (mode == GWM_HEIGHTMAP) {
1575 SetGeneratingWorldProgress(GWP_LANDSCAPE, steps + GLS_HEIGHTMAP);
1576 if (!LoadHeightmap(_file_to_saveload.detail_ftype, _file_to_saveload.name.c_str())) {
1577 return false;
1579 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1580 } else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
1581 SetGeneratingWorldProgress(GWP_LANDSCAPE, steps + GLS_TERRAGENESIS);
1582 GenerateTerrainPerlin();
1583 } else {
1584 SetGeneratingWorldProgress(GWP_LANDSCAPE, steps + GLS_ORIGINAL);
1585 if (_settings_game.construction.freeform_edges) {
1586 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
1587 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
1589 switch (_settings_game.game_creation.landscape) {
1590 case LT_ARCTIC: {
1591 uint32_t r = Random();
1593 for (uint i = Map::ScaleBySize(GB(r, 0, 7) + 950); i != 0; --i) {
1594 GenerateTerrain(2, 0);
1597 uint flag = GB(r, 7, 2) | 4;
1598 for (uint i = Map::ScaleBySize(GB(r, 9, 7) + 450); i != 0; --i) {
1599 GenerateTerrain(4, flag);
1601 break;
1604 case LT_TROPIC: {
1605 uint32_t r = Random();
1607 for (uint i = Map::ScaleBySize(GB(r, 0, 7) + 170); i != 0; --i) {
1608 GenerateTerrain(0, 0);
1611 uint flag = GB(r, 7, 2) | 4;
1612 for (uint i = Map::ScaleBySize(GB(r, 9, 8) + 1700); i != 0; --i) {
1613 GenerateTerrain(0, flag);
1616 flag ^= 2;
1618 for (uint i = Map::ScaleBySize(GB(r, 17, 7) + 410); i != 0; --i) {
1619 GenerateTerrain(3, flag);
1621 break;
1624 default: {
1625 uint32_t r = Random();
1627 assert(_settings_game.difficulty.quantity_sea_lakes != CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY);
1628 uint i = Map::ScaleBySize(GB(r, 0, 7) + (3 - _settings_game.difficulty.quantity_sea_lakes) * 256 + 100);
1629 for (; i != 0; --i) {
1630 /* Make sure we do not overflow. */
1631 GenerateTerrain(Clamp(_settings_game.difficulty.terrain_type, 0, 3), 0);
1633 break;
1638 /* Do not call IncreaseGeneratingWorldProgress() before FixSlopes(),
1639 * it allows screen redraw. Drawing of broken slopes crashes the game */
1640 FixSlopes();
1641 MarkWholeScreenDirty();
1642 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1644 ConvertGroundTilesIntoWaterTiles();
1645 MarkWholeScreenDirty();
1646 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1648 switch (_settings_game.game_creation.landscape) {
1649 case LT_ARCTIC:
1650 CalculateSnowLine();
1651 break;
1653 case LT_TROPIC: {
1654 uint desert_tropic_line = CalculateDesertLine();
1655 CreateDesertOrRainForest(desert_tropic_line);
1656 break;
1659 default:
1660 break;
1663 CreateRivers();
1664 return true;
1667 void OnTick_Town();
1668 void OnTick_Trees();
1669 void OnTick_Station();
1670 void OnTick_Industry();
1672 void OnTick_Companies();
1673 void OnTick_LinkGraph();
1675 void CallLandscapeTick()
1678 PerformanceAccumulator framerate(PFE_GL_LANDSCAPE);
1680 OnTick_Town();
1681 OnTick_Trees();
1682 OnTick_Station();
1683 OnTick_Industry();
1686 OnTick_Companies();
1687 OnTick_LinkGraph();