Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / map_func.h
blob14d65db690e2c1cbcdb35e8e852f800b37379f6a
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 map_func.h Functions related to maps. */
10 #ifndef MAP_FUNC_H
11 #define MAP_FUNC_H
13 #include "core/math_func.hpp"
14 #include "tile_type.h"
15 #include "map_type.h"
16 #include "direction_func.h"
18 /**
19 * Wrapper class to abstract away the way the tiles are stored. It is
20 * intended to be used to access the "map" data of a single tile.
22 * The wrapper is expected to be fully optimized away by the compiler, even
23 * with low optimization levels except when completely disabling it.
25 class Tile {
26 private:
27 friend struct Map;
28 /**
29 * Data that is stored per tile. Also used TileExtended for this.
30 * Look at docs/landscape.html for the exact meaning of the members.
32 struct TileBase {
33 byte type; ///< The type (bits 4..7), bridges (2..3), rainforest/desert (0..1)
34 byte height; ///< The height of the northern corner.
35 uint16_t m2; ///< Primarily used for indices to towns, industries and stations
36 byte m1; ///< Primarily used for ownership information
37 byte m3; ///< General purpose
38 byte m4; ///< General purpose
39 byte m5; ///< General purpose
42 static_assert(sizeof(TileBase) == 8);
44 /**
45 * Data that is stored per tile. Also used TileBase for this.
46 * Look at docs/landscape.html for the exact meaning of the members.
48 struct TileExtended {
49 byte m6; ///< General purpose
50 byte m7; ///< Primarily used for newgrf support
51 uint16_t m8; ///< General purpose
54 static TileBase *base_tiles; ///< Pointer to the tile-array.
55 static TileExtended *extended_tiles; ///< Pointer to the extended tile-array.
57 TileIndex tile; ///< The tile to access the map data for.
59 public:
60 /**
61 * Create the tile wrapper for the given tile.
62 * @param tile The tile to access the map for.
64 debug_inline Tile(TileIndex tile) : tile(tile) {}
66 /**
67 * Create the tile wrapper for the given tile.
68 * @param tile The tile to access the map for.
70 Tile(uint tile) : tile(tile) {}
72 /**
73 * Implicit conversion to the TileIndex.
75 debug_inline constexpr operator TileIndex() const { return tile; }
77 /**
78 * Implicit conversion to the uint for bounds checking.
80 debug_inline constexpr operator uint() const { return tile.base(); }
82 /**
83 * The type (bits 4..7), bridges (2..3), rainforest/desert (0..1)
85 * Look at docs/landscape.html for the exact meaning of the data.
86 * @param tile The tile to get the data for.
87 * @return reference to the byte holding the data.
89 debug_inline byte &type()
91 return base_tiles[tile.base()].type;
94 /**
95 * The height of the northern corner
97 * Look at docs/landscape.html for the exact meaning of the data.
98 * @param tile The tile to get the height for.
99 * @return reference to the byte holding the height.
101 debug_inline byte &height()
103 return base_tiles[tile.base()].height;
107 * Primarily used for ownership information
109 * Look at docs/landscape.html for the exact meaning of the data.
110 * @param tile The tile to get the data for.
111 * @return reference to the byte holding the data.
113 debug_inline byte &m1()
115 return base_tiles[tile.base()].m1;
119 * Primarily used for indices to towns, industries and stations
121 * Look at docs/landscape.html for the exact meaning of the data.
122 * @param tile The tile to get the data for.
123 * @return reference to the uint16_t holding the data.
125 debug_inline uint16_t &m2()
127 return base_tiles[tile.base()].m2;
131 * General purpose
133 * Look at docs/landscape.html for the exact meaning of the data.
134 * @param tile The tile to get the data for.
135 * @return reference to the byte holding the data.
137 debug_inline byte &m3()
139 return base_tiles[tile.base()].m3;
143 * General purpose
145 * Look at docs/landscape.html for the exact meaning of the data.
146 * @param tile The tile to get the data for.
147 * @return reference to the byte holding the data.
149 debug_inline byte &m4()
151 return base_tiles[tile.base()].m4;
155 * General purpose
157 * Look at docs/landscape.html for the exact meaning of the data.
158 * @param tile The tile to get the data for.
159 * @return reference to the byte holding the data.
161 debug_inline byte &m5()
163 return base_tiles[tile.base()].m5;
167 * General purpose
169 * Look at docs/landscape.html for the exact meaning of the data.
170 * @param tile The tile to get the data for.
171 * @return reference to the byte holding the data.
173 debug_inline byte &m6()
175 return extended_tiles[tile.base()].m6;
179 * Primarily used for newgrf support
181 * Look at docs/landscape.html for the exact meaning of the data.
182 * @param tile The tile to get the data for.
183 * @return reference to the byte holding the data.
185 debug_inline byte &m7()
187 return extended_tiles[tile.base()].m7;
191 * General purpose
193 * Look at docs/landscape.html for the exact meaning of the data.
194 * @param tile The tile to get the data for.
195 * @return reference to the uint16_t holding the data.
197 debug_inline uint16_t &m8()
199 return extended_tiles[tile.base()].m8;
204 * Size related data of the map.
206 struct Map {
207 private:
209 * Iterator to iterate all Tiles
211 struct Iterator {
212 typedef Tile value_type;
213 typedef Tile *pointer;
214 typedef Tile &reference;
215 typedef size_t difference_type;
216 typedef std::forward_iterator_tag iterator_category;
218 explicit Iterator(TileIndex index) : index(index) {}
219 bool operator==(const Iterator &other) const { return this->index == other.index; }
220 bool operator!=(const Iterator &other) const { return !(*this == other); }
221 Tile operator*() const { return this->index; }
222 Iterator & operator++() { this->index++; return *this; }
223 private:
224 TileIndex index;
228 * Iterable ensemble of all Tiles
230 struct IterateWrapper {
231 Iterator begin() { return Iterator(0); }
232 Iterator end() { return Iterator(Map::Size()); }
233 bool empty() { return false; }
236 static uint log_x; ///< 2^_map_log_x == _map_size_x
237 static uint log_y; ///< 2^_map_log_y == _map_size_y
238 static uint size_x; ///< Size of the map along the X
239 static uint size_y; ///< Size of the map along the Y
240 static uint size; ///< The number of tiles on the map
241 static uint tile_mask; ///< _map_size - 1 (to mask the mapsize)
243 public:
244 static void Allocate(uint size_x, uint size_y);
247 * Logarithm of the map size along the X side.
248 * @note try to avoid using this one
249 * @return 2^"return value" == Map::SizeX()
251 debug_inline static uint LogX()
253 return Map::log_x;
257 * Logarithm of the map size along the y side.
258 * @note try to avoid using this one
259 * @return 2^"return value" == Map::SizeY()
261 static inline uint LogY()
263 return Map::log_y;
267 * Get the size of the map along the X
268 * @return the number of tiles along the X of the map
270 debug_inline static uint SizeX()
272 return Map::size_x;
276 * Get the size of the map along the Y
277 * @return the number of tiles along the Y of the map
279 static inline uint SizeY()
281 return Map::size_y;
285 * Get the size of the map
286 * @return the number of tiles of the map
288 debug_inline static uint Size()
290 return Map::size;
294 * Gets the maximum X coordinate within the map, including MP_VOID
295 * @return the maximum X coordinate
297 debug_inline static uint MaxX()
299 return Map::SizeX() - 1;
303 * Gets the maximum Y coordinate within the map, including MP_VOID
304 * @return the maximum Y coordinate
306 static inline uint MaxY()
308 return Map::SizeY() - 1;
313 * 'Wraps' the given "tile" so it is within the map.
314 * It does this by masking the 'high' bits of.
315 * @param tile the tile to 'wrap'
317 static inline TileIndex WrapToMap(TileIndex tile)
319 return tile.base() & Map::tile_mask;
323 * Scales the given value by the map size, where the given value is
324 * for a 256 by 256 map.
325 * @param n the value to scale
326 * @return the scaled size
328 static inline uint ScaleBySize(uint n)
330 /* Subtract 12 from shift in order to prevent integer overflow
331 * for large values of n. It's safe since the min mapsize is 64x64. */
332 return CeilDiv(n << (Map::LogX() + Map::LogY() - 12), 1 << 4);
336 * Scales the given value by the maps circumference, where the given
337 * value is for a 256 by 256 map
338 * @param n the value to scale
339 * @return the scaled size
341 static inline uint ScaleBySize1D(uint n)
343 /* Normal circumference for the X+Y is 256+256 = 1<<9
344 * Note, not actually taking the full circumference into account,
345 * just half of it. */
346 return CeilDiv((n << Map::LogX()) + (n << Map::LogY()), 1 << 9);
350 * Check whether the map has been initialized, as to not try to save the map
351 * during crashlog when the map is not there yet.
352 * @return true when the map has been allocated/initialized.
354 static bool IsInitialized()
356 return Tile::base_tiles != nullptr;
360 * Returns an iterable ensemble of all Tiles
361 * @return an iterable ensemble of all Tiles
363 static IterateWrapper Iterate() { return IterateWrapper(); }
367 * An offset value between two tiles.
369 * This value is used for the difference between
370 * two tiles. It can be added to a TileIndex to get
371 * the resulting TileIndex of the start tile applied
372 * with this saved difference.
374 * @see TileDiffXY(int, int)
376 typedef int32_t TileIndexDiff;
379 * Returns the TileIndex of a coordinate.
381 * @param x The x coordinate of the tile
382 * @param y The y coordinate of the tile
383 * @return The TileIndex calculated by the coordinate
385 debug_inline static TileIndex TileXY(uint x, uint y)
387 return (y << Map::LogX()) + x;
391 * Calculates an offset for the given coordinate(-offset).
393 * This function calculate an offset value which can be added to a
394 * #TileIndex. The coordinates can be negative.
396 * @param x The offset in x direction
397 * @param y The offset in y direction
398 * @return The resulting offset value of the given coordinate
399 * @see ToTileIndexDiff(TileIndexDiffC)
401 inline TileIndexDiff TileDiffXY(int x, int y)
403 /* Multiplication gives much better optimization on MSVC than shifting.
404 * 0 << shift isn't optimized to 0 properly.
405 * Typically x and y are constants, and then this doesn't result
406 * in any actual multiplication in the assembly code.. */
407 return (y * Map::SizeX()) + x;
411 * Get a tile from the virtual XY-coordinate.
412 * @param x The virtual x coordinate of the tile.
413 * @param y The virtual y coordinate of the tile.
414 * @return The TileIndex calculated by the coordinate.
416 debug_inline static TileIndex TileVirtXY(uint x, uint y)
418 return (y >> 4 << Map::LogX()) + (x >> 4);
423 * Get the X component of a tile
424 * @param tile the tile to get the X component of
425 * @return the X component
427 debug_inline static uint TileX(TileIndex tile)
429 return tile.base() & Map::MaxX();
433 * Get the Y component of a tile
434 * @param tile the tile to get the Y component of
435 * @return the Y component
437 debug_inline static uint TileY(TileIndex tile)
439 return tile.base() >> Map::LogX();
443 * Return the offset between two tiles from a TileIndexDiffC struct.
445 * This function works like #TileDiffXY(int, int) and returns the
446 * difference between two tiles.
448 * @param tidc The coordinate of the offset as TileIndexDiffC
449 * @return The difference between two tiles.
450 * @see TileDiffXY(int, int)
452 inline TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
454 return (tidc.y << Map::LogX()) + tidc.x;
458 #ifndef _DEBUG
460 * Adds two tiles together.
462 * @param x One tile
463 * @param y Another tile to add
464 * @return The resulting tile(index)
466 # define TILE_ADD(x, y) ((x) + (y))
467 #else
468 extern TileIndex TileAdd(TileIndex tile, TileIndexDiff add,
469 const char *exp, const char *file, int line);
470 # define TILE_ADD(x, y) (TileAdd((x), (y), #x " + " #y, __FILE__, __LINE__))
471 #endif
474 * Adds a given offset to a tile.
476 * @param tile The tile to add an offset on it
477 * @param x The x offset to add to the tile
478 * @param y The y offset to add to the tile
480 #define TILE_ADDXY(tile, x, y) TILE_ADD(tile, TileDiffXY(x, y))
482 TileIndex TileAddWrap(TileIndex tile, int addx, int addy);
485 * Returns the TileIndexDiffC offset from a DiagDirection.
487 * @param dir The given direction
488 * @return The offset as TileIndexDiffC value
490 inline TileIndexDiffC TileIndexDiffCByDiagDir(DiagDirection dir)
492 extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
494 assert(IsValidDiagDirection(dir));
495 return _tileoffs_by_diagdir[dir];
499 * Returns the TileIndexDiffC offset from a Direction.
501 * @param dir The given direction
502 * @return The offset as TileIndexDiffC value
504 inline TileIndexDiffC TileIndexDiffCByDir(Direction dir)
506 extern const TileIndexDiffC _tileoffs_by_dir[DIR_END];
508 assert(IsValidDirection(dir));
509 return _tileoffs_by_dir[dir];
513 * Add a TileIndexDiffC to a TileIndex and returns the new one.
515 * Returns tile + the diff given in diff. If the result tile would end up
516 * outside of the map, INVALID_TILE is returned instead.
518 * @param tile The base tile to add the offset on
519 * @param diff The offset to add on the tile
520 * @return The resulting TileIndex
522 inline TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff)
524 int x = TileX(tile) + diff.x;
525 int y = TileY(tile) + diff.y;
526 /* Negative value will become big positive value after cast */
527 if ((uint)x >= Map::SizeX() || (uint)y >= Map::SizeY()) return INVALID_TILE;
528 return TileXY(x, y);
532 * Returns the diff between two tiles
534 * @param tile_a from tile
535 * @param tile_b to tile
536 * @return the difference between tila_a and tile_b
538 inline TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
540 TileIndexDiffC difference;
542 difference.x = TileX(tile_a) - TileX(tile_b);
543 difference.y = TileY(tile_a) - TileY(tile_b);
545 return difference;
548 /* Functions to calculate distances */
549 uint DistanceManhattan(TileIndex, TileIndex); ///< also known as L1-Norm. Is the shortest distance one could go over diagonal tracks (or roads)
550 uint DistanceSquare(TileIndex, TileIndex); ///< euclidian- or L2-Norm squared
551 uint DistanceMax(TileIndex, TileIndex); ///< also known as L-Infinity-Norm
552 uint DistanceMaxPlusManhattan(TileIndex, TileIndex); ///< Max + Manhattan
553 uint DistanceFromEdge(TileIndex); ///< shortest distance from any edge of the map
554 uint DistanceFromEdgeDir(TileIndex, DiagDirection); ///< distance from the map edge in given direction
557 * Convert a DiagDirection to a TileIndexDiff
559 * @param dir The DiagDirection
560 * @return The resulting TileIndexDiff
561 * @see TileIndexDiffCByDiagDir
563 inline TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
565 extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
567 assert(IsValidDiagDirection(dir));
568 return ToTileIndexDiff(_tileoffs_by_diagdir[dir]);
572 * Convert a Direction to a TileIndexDiff.
574 * @param dir The direction to convert from
575 * @return The resulting TileIndexDiff
577 inline TileIndexDiff TileOffsByDir(Direction dir)
579 extern const TileIndexDiffC _tileoffs_by_dir[DIR_END];
581 assert(IsValidDirection(dir));
582 return ToTileIndexDiff(_tileoffs_by_dir[dir]);
586 * Adds a Direction to a tile.
588 * @param tile The current tile
589 * @param dir The direction in which we want to step
590 * @return the moved tile
592 inline TileIndex TileAddByDir(TileIndex tile, Direction dir)
594 return TILE_ADD(tile, TileOffsByDir(dir));
598 * Adds a DiagDir to a tile.
600 * @param tile The current tile
601 * @param dir The direction in which we want to step
602 * @return the moved tile
604 inline TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
606 return TILE_ADD(tile, TileOffsByDiagDir(dir));
610 * Determines the DiagDirection to get from one tile to another.
611 * The tiles do not necessarily have to be adjacent.
612 * @param tile_from Origin tile
613 * @param tile_to Destination tile
614 * @return DiagDirection from tile_from towards tile_to, or INVALID_DIAGDIR if the tiles are not on an axis
616 inline DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
618 int dx = (int)TileX(tile_to) - (int)TileX(tile_from);
619 int dy = (int)TileY(tile_to) - (int)TileY(tile_from);
620 if (dx == 0) {
621 if (dy == 0) return INVALID_DIAGDIR;
622 return (dy < 0 ? DIAGDIR_NW : DIAGDIR_SE);
623 } else {
624 if (dy != 0) return INVALID_DIAGDIR;
625 return (dx < 0 ? DIAGDIR_NE : DIAGDIR_SW);
630 * A callback function type for searching tiles.
632 * @param tile The tile to test
633 * @param user_data additional data for the callback function to use
634 * @return A boolean value, depend on the definition of the function.
636 typedef bool TestTileOnSearchProc(TileIndex tile, void *user_data);
638 bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data);
639 bool CircularTileSearch(TileIndex *tile, uint radius, uint w, uint h, TestTileOnSearchProc proc, void *user_data);
642 * Get a random tile out of a given seed.
643 * @param r the random 'seed'
644 * @return a valid tile
646 inline TileIndex RandomTileSeed(uint32_t r)
648 return Map::WrapToMap(r);
652 * Get a valid random tile.
653 * @note a define so 'random' gets inserted in the place where it is actually
654 * called, thus making the random traces more explicit.
655 * @return a valid tile
657 #define RandomTile() RandomTileSeed(Random())
659 uint GetClosestWaterDistance(TileIndex tile, bool water);
661 #endif /* MAP_FUNC_H */