Fix: Stopped ships shouldn't block depots (#8578)
[openttd-github.git] / src / smallmap_gui.cpp
blobef1638d2f3e63b83c18022d4a018c3657af93222
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 smallmap_gui.cpp GUI that shows a small map of the world with metadata like owner or height. */
10 #include "stdafx.h"
11 #include "clear_map.h"
12 #include "industry.h"
13 #include "station_map.h"
14 #include "landscape.h"
15 #include "tree_map.h"
16 #include "viewport_func.h"
17 #include "town.h"
18 #include "tunnelbridge_map.h"
19 #include "core/endian_func.hpp"
20 #include "vehicle_base.h"
21 #include "sound_func.h"
22 #include "window_func.h"
23 #include "company_base.h"
24 #include "guitimer_func.h"
26 #include "smallmap_gui.h"
28 #include "table/strings.h"
30 #include <bitset>
32 #include "safeguards.h"
34 static int _smallmap_industry_count; ///< Number of used industries
35 static int _smallmap_company_count; ///< Number of entries in the owner legend.
36 static int _smallmap_cargo_count; ///< Number of cargos in the link stats legend.
38 /** Link stat colours shown in legenda. */
39 static uint8 _linkstat_colours_in_legenda[] = {0, 1, 3, 5, 7, 9, 11};
41 static const int NUM_NO_COMPANY_ENTRIES = 4; ///< Number of entries in the owner legend that are not companies.
43 /** Macro for ordinary entry of LegendAndColour */
44 #define MK(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}
46 /** Macro for a height legend entry with configurable colour. */
47 #define MC(col_break) {0, STR_TINY_BLACK_HEIGHT, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, col_break}
49 /** Macro for non-company owned property entry of LegendAndColour */
50 #define MO(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}
52 /** Macro used for forcing a rebuild of the owner legend the first time it is used. */
53 #define MOEND() {0, 0, INVALID_INDUSTRYTYPE, 0, OWNER_NONE, true, true, false}
55 /** Macro for end of list marker in arrays of LegendAndColour */
56 #define MKEND() {0, STR_NULL, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, true, false}
58 /**
59 * Macro for break marker in arrays of LegendAndColour.
60 * It will have valid data, though
62 #define MS(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, true}
64 /** Legend text giving the colours to look for on the minimap */
65 static LegendAndColour _legend_land_contours[] = {
66 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_ROADS),
67 MK(PC_GREY, STR_SMALLMAP_LEGENDA_RAILROADS),
68 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_STATIONS_AIRPORTS_DOCKS),
69 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
70 MK(PC_WHITE, STR_SMALLMAP_LEGENDA_VEHICLES),
72 /* Placeholders for the colours and heights of the legend.
73 * The following values are set at BuildLandLegend() based
74 * on each colour scheme and the maximum map height. */
75 MC(true),
76 MC(false),
77 MC(false),
78 MC(false),
79 MC(false),
80 MC(false),
81 MC(true),
82 MC(false),
83 MC(false),
84 MC(false),
85 MC(false),
86 MC(false),
87 MKEND()
90 static const LegendAndColour _legend_vehicles[] = {
91 MK(PC_RED, STR_SMALLMAP_LEGENDA_TRAINS),
92 MK(PC_YELLOW, STR_SMALLMAP_LEGENDA_ROAD_VEHICLES),
93 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_SHIPS),
94 MK(PC_WHITE, STR_SMALLMAP_LEGENDA_AIRCRAFT),
96 MS(PC_BLACK, STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
97 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
98 MKEND()
101 static const LegendAndColour _legend_routes[] = {
102 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_ROADS),
103 MK(PC_GREY, STR_SMALLMAP_LEGENDA_RAILROADS),
104 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
106 MS(PC_VERY_DARK_BROWN, STR_SMALLMAP_LEGENDA_RAILROAD_STATION),
107 MK(PC_ORANGE, STR_SMALLMAP_LEGENDA_TRUCK_LOADING_BAY),
108 MK(PC_YELLOW, STR_SMALLMAP_LEGENDA_BUS_STATION),
109 MK(PC_RED, STR_SMALLMAP_LEGENDA_AIRPORT_HELIPORT),
110 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_DOCK),
111 MKEND()
114 static const LegendAndColour _legend_vegetation[] = {
115 MK(PC_ROUGH_LAND, STR_SMALLMAP_LEGENDA_ROUGH_LAND),
116 MK(PC_GRASS_LAND, STR_SMALLMAP_LEGENDA_GRASS_LAND),
117 MK(PC_BARE_LAND, STR_SMALLMAP_LEGENDA_BARE_LAND),
118 MK(PC_RAINFOREST, STR_SMALLMAP_LEGENDA_RAINFOREST),
119 MK(PC_FIELDS, STR_SMALLMAP_LEGENDA_FIELDS),
120 MK(PC_TREES, STR_SMALLMAP_LEGENDA_TREES),
122 MS(PC_GREEN, STR_SMALLMAP_LEGENDA_FOREST),
123 MK(PC_GREY, STR_SMALLMAP_LEGENDA_ROCKS),
124 MK(PC_ORANGE, STR_SMALLMAP_LEGENDA_DESERT),
125 MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_SNOW),
126 MK(PC_BLACK, STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
127 MK(PC_DARK_RED, STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
128 MKEND()
131 static LegendAndColour _legend_land_owners[NUM_NO_COMPANY_ENTRIES + MAX_COMPANIES + 1] = {
132 MO(PC_WATER, STR_SMALLMAP_LEGENDA_WATER),
133 MO(0x00, STR_SMALLMAP_LEGENDA_NO_OWNER), // This colour will vary depending on settings.
134 MO(PC_DARK_RED, STR_SMALLMAP_LEGENDA_TOWNS),
135 MO(PC_DARK_GREY, STR_SMALLMAP_LEGENDA_INDUSTRIES),
136 /* The legend will be terminated the first time it is used. */
137 MOEND(),
140 #undef MK
141 #undef MC
142 #undef MS
143 #undef MO
144 #undef MOEND
145 #undef MKEND
147 /** Legend entries for the link stats view. */
148 static LegendAndColour _legend_linkstats[NUM_CARGO + lengthof(_linkstat_colours_in_legenda) + 1];
150 * Allow room for all industries, plus a terminator entry
151 * This is required in order to have the industry slots all filled up
153 static LegendAndColour _legend_from_industries[NUM_INDUSTRYTYPES + 1];
154 /** For connecting industry type to position in industries list(small map legend) */
155 static uint _industry_to_list_pos[NUM_INDUSTRYTYPES];
156 /** Show heightmap in industry and owner mode of smallmap window. */
157 static bool _smallmap_show_heightmap = false;
158 /** Highlight a specific industry type */
159 static IndustryType _smallmap_industry_highlight = INVALID_INDUSTRYTYPE;
160 /** State of highlight blinking */
161 static bool _smallmap_industry_highlight_state;
162 /** For connecting company ID to position in owner list (small map legend) */
163 static uint _company_to_list_pos[MAX_COMPANIES];
166 * Fills an array for the industries legends.
168 void BuildIndustriesLegend()
170 uint j = 0;
172 /* Add each name */
173 for (IndustryType ind : _sorted_industry_types) {
174 const IndustrySpec *indsp = GetIndustrySpec(ind);
175 if (indsp->enabled) {
176 _legend_from_industries[j].legend = indsp->name;
177 _legend_from_industries[j].colour = indsp->map_colour;
178 _legend_from_industries[j].type = ind;
179 _legend_from_industries[j].show_on_map = true;
180 _legend_from_industries[j].col_break = false;
181 _legend_from_industries[j].end = false;
183 /* Store widget number for this industry type. */
184 _industry_to_list_pos[ind] = j;
185 j++;
188 /* Terminate the list */
189 _legend_from_industries[j].end = true;
191 /* Store number of enabled industries */
192 _smallmap_industry_count = j;
196 * Populate legend table for the link stat view.
198 void BuildLinkStatsLegend()
200 /* Clear the legend */
201 memset(_legend_linkstats, 0, sizeof(_legend_linkstats));
203 uint i = 0;
204 for (; i < _sorted_cargo_specs.size(); ++i) {
205 const CargoSpec *cs = _sorted_cargo_specs[i];
207 _legend_linkstats[i].legend = cs->name;
208 _legend_linkstats[i].colour = cs->legend_colour;
209 _legend_linkstats[i].type = cs->Index();
210 _legend_linkstats[i].show_on_map = true;
213 _legend_linkstats[i].col_break = true;
214 _smallmap_cargo_count = i;
216 for (; i < _smallmap_cargo_count + lengthof(_linkstat_colours_in_legenda); ++i) {
217 _legend_linkstats[i].legend = STR_EMPTY;
218 _legend_linkstats[i].colour = LinkGraphOverlay::LINK_COLOURS[_linkstat_colours_in_legenda[i - _smallmap_cargo_count]];
219 _legend_linkstats[i].show_on_map = true;
222 _legend_linkstats[_smallmap_cargo_count].legend = STR_LINKGRAPH_LEGEND_UNUSED;
223 _legend_linkstats[i - 1].legend = STR_LINKGRAPH_LEGEND_OVERLOADED;
224 _legend_linkstats[(_smallmap_cargo_count + i - 1) / 2].legend = STR_LINKGRAPH_LEGEND_SATURATED;
225 _legend_linkstats[i].end = true;
228 static const LegendAndColour * const _legend_table[] = {
229 _legend_land_contours,
230 _legend_vehicles,
231 _legend_from_industries,
232 _legend_linkstats,
233 _legend_routes,
234 _legend_vegetation,
235 _legend_land_owners,
238 #define MKCOLOUR(x) TO_LE32X(x)
240 #define MKCOLOUR_XXXX(x) (MKCOLOUR(0x01010101) * (uint)(x))
241 #define MKCOLOUR_X0X0(x) (MKCOLOUR(0x01000100) * (uint)(x))
242 #define MKCOLOUR_0X0X(x) (MKCOLOUR(0x00010001) * (uint)(x))
243 #define MKCOLOUR_0XX0(x) (MKCOLOUR(0x00010100) * (uint)(x))
244 #define MKCOLOUR_X00X(x) (MKCOLOUR(0x01000001) * (uint)(x))
246 #define MKCOLOUR_XYXY(x, y) (MKCOLOUR_X0X0(x) | MKCOLOUR_0X0X(y))
247 #define MKCOLOUR_XYYX(x, y) (MKCOLOUR_X00X(x) | MKCOLOUR_0XX0(y))
249 #define MKCOLOUR_0000 MKCOLOUR_XXXX(0x00)
250 #define MKCOLOUR_0FF0 MKCOLOUR_0XX0(0xFF)
251 #define MKCOLOUR_F00F MKCOLOUR_X00X(0xFF)
252 #define MKCOLOUR_FFFF MKCOLOUR_XXXX(0xFF)
254 #include "table/heightmap_colours.h"
256 /** Colour scheme of the smallmap. */
257 struct SmallMapColourScheme {
258 uint32 *height_colours; ///< Cached colours for each level in a map.
259 const uint32 *height_colours_base; ///< Base table for determining the colours
260 size_t colour_count; ///< The number of colours.
261 uint32 default_colour; ///< Default colour of the land.
264 /** Available colour schemes for height maps. */
265 static SmallMapColourScheme _heightmap_schemes[] = {
266 {nullptr, _green_map_heights, lengthof(_green_map_heights), MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
267 {nullptr, _dark_green_map_heights, lengthof(_dark_green_map_heights), MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
268 {nullptr, _violet_map_heights, lengthof(_violet_map_heights), MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme.
272 * (Re)build the colour tables for the legends.
274 void BuildLandLegend()
276 /* The smallmap window has never been initialized, so no need to change the legend. */
277 if (_heightmap_schemes[0].height_colours == nullptr) return;
280 * The general idea of this function is to fill the legend with an appropriate evenly spaced
281 * selection of height levels. All entries with STR_TINY_BLACK_HEIGHT are reserved for this.
282 * At the moment there are twelve of these.
284 * The table below defines up to which height level a particular delta in the legend should be
285 * used. One could opt for just dividing the maximum height and use that as delta, but that
286 * creates many "ugly" legend labels, e.g. once every 950 meter. As a result, this table will
287 * reduce the number of deltas to 7: every 100m, 200m, 300m, 500m, 750m, 1000m and 1250m. The
288 * deltas are closer together at the lower numbers because going from 12 entries to just 4, as
289 * would happen when replacing 200m and 300m by 250m, would mean the legend would be short and
290 * that might not be considered appropriate.
292 * The current method yields at least 7 legend entries and at most 12. It can be increased to
293 * 8 by adding a 150m and 400m option, but especially 150m creates ugly heights.
295 * It tries to evenly space the legend items over the two columns that are there for the legend.
298 /* Table for delta; if max_height is less than the first column, use the second column as value. */
299 uint deltas[][2] = { { 24, 2 }, { 48, 4 }, { 72, 6 }, { 120, 10 }, { 180, 15 }, { 240, 20 }, { MAX_TILE_HEIGHT + 1, 25 }};
300 uint i = 0;
301 for (; _settings_game.construction.max_heightlevel >= deltas[i][0]; i++) {
302 /* Nothing to do here. */
304 uint delta = deltas[i][1];
306 int total_entries = (_settings_game.construction.max_heightlevel / delta) + 1;
307 int rows = CeilDiv(total_entries, 2);
308 int j = 0;
310 for (i = 0; i < lengthof(_legend_land_contours) - 1 && j < total_entries; i++) {
311 if (_legend_land_contours[i].legend != STR_TINY_BLACK_HEIGHT) continue;
313 _legend_land_contours[i].col_break = j % rows == 0;
314 _legend_land_contours[i].end = false;
315 _legend_land_contours[i].height = j * delta;
316 _legend_land_contours[i].colour = _heightmap_schemes[_settings_client.gui.smallmap_land_colour].height_colours[j * delta];
317 j++;
319 _legend_land_contours[i].end = true;
323 * Completes the array for the owned property legend.
325 void BuildOwnerLegend()
327 _legend_land_owners[1].colour = _heightmap_schemes[_settings_client.gui.smallmap_land_colour].default_colour;
329 int i = NUM_NO_COMPANY_ENTRIES;
330 for (const Company *c : Company::Iterate()) {
331 _legend_land_owners[i].colour = _colour_gradient[c->colour][5];
332 _legend_land_owners[i].company = c->index;
333 _legend_land_owners[i].show_on_map = true;
334 _legend_land_owners[i].col_break = false;
335 _legend_land_owners[i].end = false;
336 _company_to_list_pos[c->index] = i;
337 i++;
340 /* Terminate the list */
341 _legend_land_owners[i].end = true;
343 /* Store maximum amount of owner legend entries. */
344 _smallmap_company_count = i;
347 struct AndOr {
348 uint32 mor;
349 uint32 mand;
352 static inline uint32 ApplyMask(uint32 colour, const AndOr *mask)
354 return (colour & mask->mand) | mask->mor;
358 /** Colour masks for "Contour" and "Routes" modes. */
359 static const AndOr _smallmap_contours_andor[] = {
360 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_CLEAR
361 {MKCOLOUR_0XX0(PC_GREY ), MKCOLOUR_F00F}, // MP_RAILWAY
362 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_ROAD
363 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_HOUSE
364 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TREES
365 {MKCOLOUR_XXXX(PC_LIGHT_BLUE), MKCOLOUR_0000}, // MP_STATION
366 {MKCOLOUR_XXXX(PC_WATER ), MKCOLOUR_0000}, // MP_WATER
367 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_VOID
368 {MKCOLOUR_XXXX(PC_DARK_RED ), MKCOLOUR_0000}, // MP_INDUSTRY
369 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
370 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_OBJECT
371 {MKCOLOUR_0XX0(PC_GREY ), MKCOLOUR_F00F},
374 /** Colour masks for "Vehicles", "Industry", and "Vegetation" modes. */
375 static const AndOr _smallmap_vehicles_andor[] = {
376 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_CLEAR
377 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_RAILWAY
378 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_ROAD
379 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_HOUSE
380 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TREES
381 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F}, // MP_STATION
382 {MKCOLOUR_XXXX(PC_WATER ), MKCOLOUR_0000}, // MP_WATER
383 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_VOID
384 {MKCOLOUR_XXXX(PC_DARK_RED ), MKCOLOUR_0000}, // MP_INDUSTRY
385 {MKCOLOUR_0000 , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
386 {MKCOLOUR_0XX0(PC_DARK_RED ), MKCOLOUR_F00F}, // MP_OBJECT
387 {MKCOLOUR_0XX0(PC_BLACK ), MKCOLOUR_F00F},
390 /** Mapping of tile type to importance of the tile (higher number means more interesting to show). */
391 static const byte _tiletype_importance[] = {
392 2, // MP_CLEAR
393 8, // MP_RAILWAY
394 7, // MP_ROAD
395 5, // MP_HOUSE
396 2, // MP_TREES
397 9, // MP_STATION
398 2, // MP_WATER
399 1, // MP_VOID
400 6, // MP_INDUSTRY
401 8, // MP_TUNNELBRIDGE
402 2, // MP_OBJECT
408 * Return the colour a tile would be displayed with in the small map in mode "Contour".
409 * @param tile The tile of which we would like to get the colour.
410 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
411 * @return The colour of tile in the small map in mode "Contour"
413 static inline uint32 GetSmallMapContoursPixels(TileIndex tile, TileType t)
415 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
416 return ApplyMask(cs->height_colours[TileHeight(tile)], &_smallmap_contours_andor[t]);
420 * Return the colour a tile would be displayed with in the small map in mode "Vehicles".
422 * @param tile The tile of which we would like to get the colour.
423 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
424 * @return The colour of tile in the small map in mode "Vehicles"
426 static inline uint32 GetSmallMapVehiclesPixels(TileIndex tile, TileType t)
428 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
429 return ApplyMask(cs->default_colour, &_smallmap_vehicles_andor[t]);
433 * Return the colour a tile would be displayed with in the small map in mode "Industries".
435 * @param tile The tile of which we would like to get the colour.
436 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
437 * @return The colour of tile in the small map in mode "Industries"
439 static inline uint32 GetSmallMapIndustriesPixels(TileIndex tile, TileType t)
441 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
442 return ApplyMask(_smallmap_show_heightmap ? cs->height_colours[TileHeight(tile)] : cs->default_colour, &_smallmap_vehicles_andor[t]);
446 * Return the colour a tile would be displayed with in the small map in mode "Routes".
448 * @param tile The tile of which we would like to get the colour.
449 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
450 * @return The colour of tile in the small map in mode "Routes"
452 static inline uint32 GetSmallMapRoutesPixels(TileIndex tile, TileType t)
454 switch (t) {
455 case MP_STATION:
456 switch (GetStationType(tile)) {
457 case STATION_RAIL: return MKCOLOUR_XXXX(PC_VERY_DARK_BROWN);
458 case STATION_AIRPORT: return MKCOLOUR_XXXX(PC_RED);
459 case STATION_TRUCK: return MKCOLOUR_XXXX(PC_ORANGE);
460 case STATION_BUS: return MKCOLOUR_XXXX(PC_YELLOW);
461 case STATION_DOCK: return MKCOLOUR_XXXX(PC_LIGHT_BLUE);
462 default: return MKCOLOUR_FFFF;
465 case MP_RAILWAY: {
466 AndOr andor = {
467 MKCOLOUR_0XX0(GetRailTypeInfo(GetRailType(tile))->map_colour),
468 _smallmap_contours_andor[t].mand
471 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
472 return ApplyMask(cs->default_colour, &andor);
475 case MP_ROAD: {
476 const RoadTypeInfo *rti = nullptr;
477 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
478 rti = GetRoadTypeInfo(GetRoadTypeRoad(tile));
479 } else {
480 rti = GetRoadTypeInfo(GetRoadTypeTram(tile));
482 if (rti != nullptr) {
483 AndOr andor = {
484 MKCOLOUR_0XX0(rti->map_colour),
485 _smallmap_contours_andor[t].mand
488 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
489 return ApplyMask(cs->default_colour, &andor);
491 FALLTHROUGH;
494 default:
495 /* Ground colour */
496 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
497 return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
502 * Return the colour a tile would be displayed with in the small map in mode "link stats".
504 * @param tile The tile of which we would like to get the colour.
505 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
506 * @return The colour of tile in the small map in mode "link stats"
508 static inline uint32 GetSmallMapLinkStatsPixels(TileIndex tile, TileType t)
510 return _smallmap_show_heightmap ? GetSmallMapContoursPixels(tile, t) : GetSmallMapRoutesPixels(tile, t);
513 static const uint32 _vegetation_clear_bits[] = {
514 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< full grass
515 MKCOLOUR_XXXX(PC_ROUGH_LAND), ///< rough land
516 MKCOLOUR_XXXX(PC_GREY), ///< rocks
517 MKCOLOUR_XXXX(PC_FIELDS), ///< fields
518 MKCOLOUR_XXXX(PC_LIGHT_BLUE), ///< snow
519 MKCOLOUR_XXXX(PC_ORANGE), ///< desert
520 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
521 MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
525 * Return the colour a tile would be displayed with in the smallmap in mode "Vegetation".
527 * @param tile The tile of which we would like to get the colour.
528 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
529 * @return The colour of tile in the smallmap in mode "Vegetation"
531 static inline uint32 GetSmallMapVegetationPixels(TileIndex tile, TileType t)
533 switch (t) {
534 case MP_CLEAR:
535 if (IsClearGround(tile, CLEAR_GRASS)) {
536 if (GetClearDensity(tile) < 3) return MKCOLOUR_XXXX(PC_BARE_LAND);
537 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST) return MKCOLOUR_XXXX(PC_RAINFOREST);
539 return _vegetation_clear_bits[GetClearGround(tile)];
541 case MP_INDUSTRY:
542 return IsTileForestIndustry(tile) ? MKCOLOUR_XXXX(PC_GREEN) : MKCOLOUR_XXXX(PC_DARK_RED);
544 case MP_TREES:
545 if (GetTreeGround(tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(tile) == TREE_GROUND_ROUGH_SNOW) {
546 return (_settings_game.game_creation.landscape == LT_ARCTIC) ? MKCOLOUR_XYYX(PC_LIGHT_BLUE, PC_TREES) : MKCOLOUR_XYYX(PC_ORANGE, PC_TREES);
548 return (GetTropicZone(tile) == TROPICZONE_RAINFOREST) ? MKCOLOUR_XYYX(PC_RAINFOREST, PC_TREES) : MKCOLOUR_XYYX(PC_GRASS_LAND, PC_TREES);
550 default:
551 return ApplyMask(MKCOLOUR_XXXX(PC_GRASS_LAND), &_smallmap_vehicles_andor[t]);
556 * Return the colour a tile would be displayed with in the small map in mode "Owner".
558 * @param tile The tile of which we would like to get the colour.
559 * @param t Effective tile type of the tile (see #SmallMapWindow::GetTileColours).
560 * @return The colour of tile in the small map in mode "Owner"
562 static inline uint32 GetSmallMapOwnerPixels(TileIndex tile, TileType t)
564 Owner o;
566 switch (t) {
567 case MP_INDUSTRY: return MKCOLOUR_XXXX(PC_DARK_GREY);
568 case MP_HOUSE: return MKCOLOUR_XXXX(PC_DARK_RED);
569 default: o = GetTileOwner(tile); break;
570 /* FIXME: For MP_ROAD there are multiple owners.
571 * GetTileOwner returns the rail owner (level crossing) resp. the owner of ROADTYPE_ROAD (normal road),
572 * even if there are no ROADTYPE_ROAD bits on the tile.
576 if ((o < MAX_COMPANIES && !_legend_land_owners[_company_to_list_pos[o]].show_on_map) || o == OWNER_NONE || o == OWNER_WATER) {
577 if (t == MP_WATER) return MKCOLOUR_XXXX(PC_WATER);
578 const SmallMapColourScheme *cs = &_heightmap_schemes[_settings_client.gui.smallmap_land_colour];
579 return _smallmap_show_heightmap ? cs->height_colours[TileHeight(tile)] : cs->default_colour;
580 } else if (o == OWNER_TOWN) {
581 return MKCOLOUR_XXXX(PC_DARK_RED);
584 return MKCOLOUR_XXXX(_legend_land_owners[_company_to_list_pos[o]].colour);
587 /** Vehicle colours in #SMT_VEHICLES mode. Indexed by #VehicleType. */
588 static const byte _vehicle_type_colours[6] = {
589 PC_RED, PC_YELLOW, PC_LIGHT_BLUE, PC_WHITE, PC_BLACK, PC_RED
593 /** Notify the industry chain window to stop sending newly selected industries. */
594 /* static */ void SmallMapWindow::BreakIndustryChainLink()
596 InvalidateWindowClassesData(WC_INDUSTRY_CARGOES, NUM_INDUSTRYTYPES);
599 inline Point SmallMapWindow::SmallmapRemapCoords(int x, int y) const
601 Point pt;
602 pt.x = (y - x) * 2;
603 pt.y = y + x;
604 return pt;
608 * Remap tile to location on this smallmap.
609 * @param tile_x X coordinate of the tile.
610 * @param tile_y Y coordinate of the tile.
611 * @return Position to draw on.
613 inline Point SmallMapWindow::RemapTile(int tile_x, int tile_y) const
615 int x_offset = tile_x - this->scroll_x / (int)TILE_SIZE;
616 int y_offset = tile_y - this->scroll_y / (int)TILE_SIZE;
618 if (this->zoom == 1) return SmallmapRemapCoords(x_offset, y_offset);
620 /* For negative offsets, round towards -inf. */
621 if (x_offset < 0) x_offset -= this->zoom - 1;
622 if (y_offset < 0) y_offset -= this->zoom - 1;
624 return SmallmapRemapCoords(x_offset / this->zoom, y_offset / this->zoom);
628 * Determine the tile relative to the base tile of the smallmap, and the pixel position at
629 * that tile for a point in the smallmap.
630 * @param px Horizontal coordinate of the pixel.
631 * @param py Vertical coordinate of the pixel.
632 * @param[out] sub Pixel position at the tile (0..3).
633 * @param add_sub Add current #subscroll to the position.
634 * @return Tile being displayed at the given position relative to #scroll_x and #scroll_y.
635 * @note The #subscroll offset is already accounted for.
637 inline Point SmallMapWindow::PixelToTile(int px, int py, int *sub, bool add_sub) const
639 if (add_sub) px += this->subscroll; // Total horizontal offset.
641 /* For each two rows down, add a x and a y tile, and
642 * For each four pixels to the right, move a tile to the right. */
643 Point pt = {((py >> 1) - (px >> 2)) * this->zoom, ((py >> 1) + (px >> 2)) * this->zoom};
644 px &= 3;
646 if (py & 1) { // Odd number of rows, handle the 2 pixel shift.
647 if (px < 2) {
648 pt.x += this->zoom;
649 px += 2;
650 } else {
651 pt.y += this->zoom;
652 px -= 2;
656 *sub = px;
657 return pt;
661 * Compute base parameters of the smallmap such that tile (\a tx, \a ty) starts at pixel (\a x, \a y).
662 * @param tx Tile x coordinate.
663 * @param ty Tile y coordinate.
664 * @param x Non-negative horizontal position in the display where the tile starts.
665 * @param y Non-negative vertical position in the display where the tile starts.
666 * @param[out] sub Value of #subscroll needed.
667 * @return #scroll_x, #scroll_y values.
669 Point SmallMapWindow::ComputeScroll(int tx, int ty, int x, int y, int *sub)
671 assert(x >= 0 && y >= 0);
673 int new_sub;
674 Point tile_xy = PixelToTile(x, y, &new_sub, false);
675 tx -= tile_xy.x;
676 ty -= tile_xy.y;
678 Point scroll;
679 if (new_sub == 0) {
680 *sub = 0;
681 scroll.x = (tx + this->zoom) * TILE_SIZE;
682 scroll.y = (ty - this->zoom) * TILE_SIZE;
683 } else {
684 *sub = 4 - new_sub;
685 scroll.x = (tx + 2 * this->zoom) * TILE_SIZE;
686 scroll.y = (ty - 2 * this->zoom) * TILE_SIZE;
688 return scroll;
692 * Initialize or change the zoom level.
693 * @param change Way to change the zoom level.
694 * @param zoom_pt Position to keep fixed while zooming.
695 * @pre \c *zoom_pt should contain a point in the smallmap display when zooming in or out.
697 void SmallMapWindow::SetZoomLevel(ZoomLevelChange change, const Point *zoom_pt)
699 static const int zoomlevels[] = {1, 2, 4, 6, 8}; // Available zoom levels. Bigger number means more zoom-out (further away).
700 static const int MIN_ZOOM_INDEX = 0;
701 static const int MAX_ZOOM_INDEX = lengthof(zoomlevels) - 1;
703 int new_index, cur_index, sub;
704 Point tile;
705 switch (change) {
706 case ZLC_INITIALIZE:
707 cur_index = - 1; // Definitely different from new_index.
708 new_index = MIN_ZOOM_INDEX;
709 tile.x = tile.y = 0;
710 break;
712 case ZLC_ZOOM_IN:
713 case ZLC_ZOOM_OUT:
714 for (cur_index = MIN_ZOOM_INDEX; cur_index <= MAX_ZOOM_INDEX; cur_index++) {
715 if (this->zoom == zoomlevels[cur_index]) break;
717 assert(cur_index <= MAX_ZOOM_INDEX);
719 tile = this->PixelToTile(zoom_pt->x, zoom_pt->y, &sub);
720 new_index = Clamp(cur_index + ((change == ZLC_ZOOM_IN) ? -1 : 1), MIN_ZOOM_INDEX, MAX_ZOOM_INDEX);
721 break;
723 default: NOT_REACHED();
726 if (new_index != cur_index) {
727 this->zoom = zoomlevels[new_index];
728 if (cur_index >= 0) {
729 Point new_tile = this->PixelToTile(zoom_pt->x, zoom_pt->y, &sub);
730 this->SetNewScroll(this->scroll_x + (tile.x - new_tile.x) * TILE_SIZE,
731 this->scroll_y + (tile.y - new_tile.y) * TILE_SIZE, sub);
732 } else if (this->map_type == SMT_LINKSTATS) {
733 this->overlay->SetDirty();
735 this->SetWidgetDisabledState(WID_SM_ZOOM_IN, this->zoom == zoomlevels[MIN_ZOOM_INDEX]);
736 this->SetWidgetDisabledState(WID_SM_ZOOM_OUT, this->zoom == zoomlevels[MAX_ZOOM_INDEX]);
737 this->SetDirty();
742 * Decide which colours to show to the user for a group of tiles.
743 * @param ta Tile area to investigate.
744 * @return Colours to display.
746 inline uint32 SmallMapWindow::GetTileColours(const TileArea &ta) const
748 int importance = 0;
749 TileIndex tile = INVALID_TILE; // Position of the most important tile.
750 TileType et = MP_VOID; // Effective tile type at that position.
752 TILE_AREA_LOOP(ti, ta) {
753 TileType ttype = GetTileType(ti);
755 switch (ttype) {
756 case MP_TUNNELBRIDGE: {
757 TransportType tt = GetTunnelBridgeTransportType(ti);
759 switch (tt) {
760 case TRANSPORT_RAIL: ttype = MP_RAILWAY; break;
761 case TRANSPORT_ROAD: ttype = MP_ROAD; break;
762 default: ttype = MP_WATER; break;
764 break;
767 case MP_INDUSTRY:
768 /* Special handling of industries while in "Industries" smallmap view. */
769 if (this->map_type == SMT_INDUSTRY) {
770 /* If industry is allowed to be seen, use its colour on the map.
771 * This has the highest priority above any value in _tiletype_importance. */
772 IndustryType type = Industry::GetByTile(ti)->type;
773 if (_legend_from_industries[_industry_to_list_pos[type]].show_on_map) {
774 if (type == _smallmap_industry_highlight) {
775 if (_smallmap_industry_highlight_state) return MKCOLOUR_XXXX(PC_WHITE);
776 } else {
777 return GetIndustrySpec(type)->map_colour * 0x01010101;
780 /* Otherwise make it disappear */
781 ttype = IsTileOnWater(ti) ? MP_WATER : MP_CLEAR;
783 break;
785 default:
786 break;
789 if (_tiletype_importance[ttype] > importance) {
790 importance = _tiletype_importance[ttype];
791 tile = ti;
792 et = ttype;
796 switch (this->map_type) {
797 case SMT_CONTOUR:
798 return GetSmallMapContoursPixels(tile, et);
800 case SMT_VEHICLES:
801 return GetSmallMapVehiclesPixels(tile, et);
803 case SMT_INDUSTRY:
804 return GetSmallMapIndustriesPixels(tile, et);
806 case SMT_LINKSTATS:
807 return GetSmallMapLinkStatsPixels(tile, et);
809 case SMT_ROUTES:
810 return GetSmallMapRoutesPixels(tile, et);
812 case SMT_VEGETATION:
813 return GetSmallMapVegetationPixels(tile, et);
815 case SMT_OWNER:
816 return GetSmallMapOwnerPixels(tile, et);
818 default: NOT_REACHED();
823 * Draws one column of tiles of the small map in a certain mode onto the screen buffer, skipping the shifted rows in between.
825 * @param dst Pointer to a part of the screen buffer to write to.
826 * @param xc The X coordinate of the first tile in the column.
827 * @param yc The Y coordinate of the first tile in the column
828 * @param pitch Number of pixels to advance in the screen buffer each time a pixel is written.
829 * @param reps Number of lines to draw
830 * @param start_pos Position of first pixel to draw.
831 * @param end_pos Position of last pixel to draw (exclusive).
832 * @param blitter current blitter
833 * @note If pixel position is below \c 0, skip drawing.
835 void SmallMapWindow::DrawSmallMapColumn(void *dst, uint xc, uint yc, int pitch, int reps, int start_pos, int end_pos, Blitter *blitter) const
837 void *dst_ptr_abs_end = blitter->MoveTo(_screen.dst_ptr, 0, _screen.height);
838 uint min_xy = _settings_game.construction.freeform_edges ? 1 : 0;
840 do {
841 /* Check if the tile (xc,yc) is within the map range */
842 if (xc >= MapMaxX() || yc >= MapMaxY()) continue;
844 /* Check if the dst pointer points to a pixel inside the screen buffer */
845 if (dst < _screen.dst_ptr) continue;
846 if (dst >= dst_ptr_abs_end) continue;
848 /* Construct tilearea covered by (xc, yc, xc + this->zoom, yc + this->zoom) such that it is within min_xy limits. */
849 TileArea ta;
850 if (min_xy == 1 && (xc == 0 || yc == 0)) {
851 if (this->zoom == 1) continue; // The tile area is empty, don't draw anything.
853 ta = TileArea(TileXY(std::max(min_xy, xc), std::max(min_xy, yc)), this->zoom - (xc == 0), this->zoom - (yc == 0));
854 } else {
855 ta = TileArea(TileXY(xc, yc), this->zoom, this->zoom);
857 ta.ClampToMap(); // Clamp to map boundaries (may contain MP_VOID tiles!).
859 uint32 val = this->GetTileColours(ta);
860 uint8 *val8 = (uint8 *)&val;
861 int idx = std::max(0, -start_pos);
862 for (int pos = std::max(0, start_pos); pos < end_pos; pos++) {
863 blitter->SetPixel(dst, idx, 0, val8[idx]);
864 idx++;
866 /* Switch to next tile in the column */
867 } while (xc += this->zoom, yc += this->zoom, dst = blitter->MoveTo(dst, pitch, 0), --reps != 0);
871 * Adds vehicles to the smallmap.
872 * @param dpi the part of the smallmap to be drawn into
873 * @param blitter current blitter
875 void SmallMapWindow::DrawVehicles(const DrawPixelInfo *dpi, Blitter *blitter) const
877 for (const Vehicle *v : Vehicle::Iterate()) {
878 if (v->type == VEH_EFFECT) continue;
879 if (v->vehstatus & (VS_HIDDEN | VS_UNCLICKABLE)) continue;
881 /* Remap into flat coordinates. */
882 Point pt = this->RemapTile(v->x_pos / (int)TILE_SIZE, v->y_pos / (int)TILE_SIZE);
884 int y = pt.y - dpi->top;
885 if (!IsInsideMM(y, 0, dpi->height)) continue; // y is out of bounds.
887 bool skip = false; // Default is to draw both pixels.
888 int x = pt.x - this->subscroll - 3 - dpi->left; // Offset X coordinate.
889 if (x < 0) {
890 /* if x+1 is 0, that means we're on the very left edge,
891 * and should thus only draw a single pixel */
892 if (++x != 0) continue;
893 skip = true;
894 } else if (x >= dpi->width - 1) {
895 /* Check if we're at the very right edge, and if so draw only a single pixel */
896 if (x != dpi->width - 1) continue;
897 skip = true;
900 /* Calculate pointer to pixel and the colour */
901 byte colour = (this->map_type == SMT_VEHICLES) ? _vehicle_type_colours[v->type] : PC_WHITE;
903 /* And draw either one or two pixels depending on clipping */
904 blitter->SetPixel(dpi->dst_ptr, x, y, colour);
905 if (!skip) blitter->SetPixel(dpi->dst_ptr, x + 1, y, colour);
910 * Adds town names to the smallmap.
911 * @param dpi the part of the smallmap to be drawn into
913 void SmallMapWindow::DrawTowns(const DrawPixelInfo *dpi) const
915 for (const Town *t : Town::Iterate()) {
916 /* Remap the town coordinate */
917 Point pt = this->RemapTile(TileX(t->xy), TileY(t->xy));
918 int x = pt.x - this->subscroll - (t->cache.sign.width_small >> 1);
919 int y = pt.y;
921 /* Check if the town sign is within bounds */
922 if (x + t->cache.sign.width_small > dpi->left &&
923 x < dpi->left + dpi->width &&
924 y + FONT_HEIGHT_SMALL > dpi->top &&
925 y < dpi->top + dpi->height) {
926 /* And draw it. */
927 SetDParam(0, t->index);
928 DrawString(x, x + t->cache.sign.width_small, y, STR_SMALLMAP_TOWN);
934 * Adds map indicators to the smallmap.
936 void SmallMapWindow::DrawMapIndicators() const
938 /* Find main viewport. */
939 const Viewport *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
941 Point upper_left_smallmap_coord = InverseRemapCoords2(vp->virtual_left, vp->virtual_top);
942 Point lower_right_smallmap_coord = InverseRemapCoords2(vp->virtual_left + vp->virtual_width - 1, vp->virtual_top + vp->virtual_height - 1);
944 Point upper_left = this->RemapTile(upper_left_smallmap_coord.x / (int)TILE_SIZE, upper_left_smallmap_coord.y / (int)TILE_SIZE);
945 upper_left.x -= this->subscroll;
947 Point lower_right = this->RemapTile(lower_right_smallmap_coord.x / (int)TILE_SIZE, lower_right_smallmap_coord.y / (int)TILE_SIZE);
948 lower_right.x -= this->subscroll;
950 SmallMapWindow::DrawVertMapIndicator(upper_left.x, upper_left.y, lower_right.y);
951 SmallMapWindow::DrawVertMapIndicator(lower_right.x, upper_left.y, lower_right.y);
953 SmallMapWindow::DrawHorizMapIndicator(upper_left.x, lower_right.x, upper_left.y);
954 SmallMapWindow::DrawHorizMapIndicator(upper_left.x, lower_right.x, lower_right.y);
958 * Draws the small map.
960 * Basically, the small map is draw column of pixels by column of pixels. The pixels
961 * are drawn directly into the screen buffer. The final map is drawn in multiple passes.
962 * The passes are:
963 * <ol><li>The colours of tiles in the different modes.</li>
964 * <li>Town names (optional)</li></ol>
966 * @param dpi pointer to pixel to write onto
968 void SmallMapWindow::DrawSmallMap(DrawPixelInfo *dpi) const
970 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
971 DrawPixelInfo *old_dpi;
973 old_dpi = _cur_dpi;
974 _cur_dpi = dpi;
976 /* Clear it */
977 GfxFillRect(dpi->left, dpi->top, dpi->left + dpi->width - 1, dpi->top + dpi->height - 1, PC_BLACK);
979 /* Which tile is displayed at (dpi->left, dpi->top)? */
980 int dx;
981 Point tile = this->PixelToTile(dpi->left, dpi->top, &dx);
982 int tile_x = this->scroll_x / (int)TILE_SIZE + tile.x;
983 int tile_y = this->scroll_y / (int)TILE_SIZE + tile.y;
985 void *ptr = blitter->MoveTo(dpi->dst_ptr, -dx - 4, 0);
986 int x = - dx - 4;
987 int y = 0;
989 for (;;) {
990 /* Distance from left edge */
991 if (x >= -3) {
992 if (x >= dpi->width) break; // Exit the loop.
994 int end_pos = std::min(dpi->width, x + 4);
995 int reps = (dpi->height - y + 1) / 2; // Number of lines.
996 if (reps > 0) {
997 this->DrawSmallMapColumn(ptr, tile_x, tile_y, dpi->pitch * 2, reps, x, end_pos, blitter);
1001 if (y == 0) {
1002 tile_y += this->zoom;
1003 y++;
1004 ptr = blitter->MoveTo(ptr, 0, 1);
1005 } else {
1006 tile_x -= this->zoom;
1007 y--;
1008 ptr = blitter->MoveTo(ptr, 0, -1);
1010 ptr = blitter->MoveTo(ptr, 2, 0);
1011 x += 2;
1014 /* Draw vehicles */
1015 if (this->map_type == SMT_CONTOUR || this->map_type == SMT_VEHICLES) this->DrawVehicles(dpi, blitter);
1017 /* Draw link stat overlay */
1018 if (this->map_type == SMT_LINKSTATS) this->overlay->Draw(dpi);
1020 /* Draw town names */
1021 if (this->show_towns) this->DrawTowns(dpi);
1023 /* Draw map indicators */
1024 this->DrawMapIndicators();
1026 _cur_dpi = old_dpi;
1030 * Function to set up widgets depending on the information being shown on the smallmap.
1032 void SmallMapWindow::SetupWidgetData()
1034 StringID legend_tooltip;
1035 StringID enable_all_tooltip;
1036 StringID disable_all_tooltip;
1037 int plane;
1038 switch (this->map_type) {
1039 case SMT_INDUSTRY:
1040 legend_tooltip = STR_SMALLMAP_TOOLTIP_INDUSTRY_SELECTION;
1041 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_INDUSTRIES;
1042 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_INDUSTRIES;
1043 plane = 0;
1044 break;
1046 case SMT_OWNER:
1047 legend_tooltip = STR_SMALLMAP_TOOLTIP_COMPANY_SELECTION;
1048 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_COMPANIES;
1049 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_COMPANIES;
1050 plane = 0;
1051 break;
1053 case SMT_LINKSTATS:
1054 legend_tooltip = STR_SMALLMAP_TOOLTIP_CARGO_SELECTION;
1055 enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_CARGOS;
1056 disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_CARGOS;
1057 plane = 0;
1058 break;
1060 default:
1061 legend_tooltip = STR_NULL;
1062 enable_all_tooltip = STR_NULL;
1063 disable_all_tooltip = STR_NULL;
1064 plane = 1;
1065 break;
1068 this->GetWidget<NWidgetCore>(WID_SM_LEGEND)->SetDataTip(STR_NULL, legend_tooltip);
1069 this->GetWidget<NWidgetCore>(WID_SM_ENABLE_ALL)->SetDataTip(STR_SMALLMAP_ENABLE_ALL, enable_all_tooltip);
1070 this->GetWidget<NWidgetCore>(WID_SM_DISABLE_ALL)->SetDataTip(STR_SMALLMAP_DISABLE_ALL, disable_all_tooltip);
1071 this->GetWidget<NWidgetStacked>(WID_SM_SELECT_BUTTONS)->SetDisplayedPlane(plane);
1074 SmallMapWindow::SmallMapWindow(WindowDesc *desc, int window_number) : Window(desc), refresh(GUITimer(FORCE_REFRESH_PERIOD))
1076 _smallmap_industry_highlight = INVALID_INDUSTRYTYPE;
1077 this->overlay = new LinkGraphOverlay(this, WID_SM_MAP, 0, this->GetOverlayCompanyMask(), 1);
1078 this->InitNested(window_number);
1079 this->LowerWidget(this->map_type + WID_SM_CONTOUR);
1081 this->RebuildColourIndexIfNecessary();
1083 this->SetWidgetLoweredState(WID_SM_SHOW_HEIGHT, _smallmap_show_heightmap);
1085 this->SetWidgetLoweredState(WID_SM_TOGGLETOWNNAME, this->show_towns);
1087 this->SetupWidgetData();
1089 this->SetZoomLevel(ZLC_INITIALIZE, nullptr);
1090 this->SmallMapCenterOnCurrentPos();
1091 this->SetOverlayCargoMask();
1094 SmallMapWindow::~SmallMapWindow()
1096 delete this->overlay;
1097 this->BreakIndustryChainLink();
1101 * Rebuilds the colour indices used for fast access to the smallmap contour colours based on the heightlevel.
1103 void SmallMapWindow::RebuildColourIndexIfNecessary()
1105 /* Rebuild colour indices if necessary. */
1106 if (SmallMapWindow::max_heightlevel == _settings_game.construction.max_heightlevel) return;
1108 for (uint n = 0; n < lengthof(_heightmap_schemes); n++) {
1109 /* The heights go from 0 up to and including maximum. */
1110 int heights = _settings_game.construction.max_heightlevel + 1;
1111 _heightmap_schemes[n].height_colours = ReallocT<uint32>(_heightmap_schemes[n].height_colours, heights);
1113 for (int z = 0; z < heights; z++) {
1114 size_t access_index = (_heightmap_schemes[n].colour_count * z) / heights;
1116 /* Choose colour by mapping the range (0..max heightlevel) on the complete colour table. */
1117 _heightmap_schemes[n].height_colours[z] = _heightmap_schemes[n].height_colours_base[access_index];
1121 SmallMapWindow::max_heightlevel = _settings_game.construction.max_heightlevel;
1122 BuildLandLegend();
1125 /* virtual */ void SmallMapWindow::SetStringParameters(int widget) const
1127 switch (widget) {
1128 case WID_SM_CAPTION:
1129 SetDParam(0, STR_SMALLMAP_TYPE_CONTOURS + this->map_type);
1130 break;
1134 /* virtual */ void SmallMapWindow::OnInit()
1136 uint min_width = 0;
1137 this->min_number_of_columns = INDUSTRY_MIN_NUMBER_OF_COLUMNS;
1138 this->min_number_of_fixed_rows = lengthof(_linkstat_colours_in_legenda);
1139 for (uint i = 0; i < lengthof(_legend_table); i++) {
1140 uint height = 0;
1141 uint num_columns = 1;
1142 for (const LegendAndColour *tbl = _legend_table[i]; !tbl->end; ++tbl) {
1143 StringID str;
1144 if (i == SMT_INDUSTRY) {
1145 SetDParam(0, tbl->legend);
1146 SetDParam(1, IndustryPool::MAX_SIZE);
1147 str = STR_SMALLMAP_INDUSTRY;
1148 } else if (i == SMT_LINKSTATS) {
1149 SetDParam(0, tbl->legend);
1150 str = STR_SMALLMAP_LINKSTATS;
1151 } else if (i == SMT_OWNER) {
1152 if (tbl->company != INVALID_COMPANY) {
1153 if (!Company::IsValidID(tbl->company)) {
1154 /* Rebuild the owner legend. */
1155 BuildOwnerLegend();
1156 this->OnInit();
1157 return;
1159 /* Non-fixed legend entries for the owner view. */
1160 SetDParam(0, tbl->company);
1161 str = STR_SMALLMAP_COMPANY;
1162 } else {
1163 str = tbl->legend;
1165 } else {
1166 if (tbl->col_break) {
1167 this->min_number_of_fixed_rows = std::max(this->min_number_of_fixed_rows, height);
1168 height = 0;
1169 num_columns++;
1171 height++;
1172 str = tbl->legend;
1174 min_width = std::max(GetStringBoundingBox(str).width, min_width);
1176 this->min_number_of_fixed_rows = std::max(this->min_number_of_fixed_rows, height);
1177 this->min_number_of_columns = std::max(this->min_number_of_columns, num_columns);
1180 /* The width of a column is the minimum width of all texts + the size of the blob + some spacing */
1181 this->column_width = min_width + LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1184 /* virtual */ void SmallMapWindow::OnPaint()
1186 if (this->map_type == SMT_OWNER) {
1187 for (const LegendAndColour *tbl = _legend_table[this->map_type]; !tbl->end; ++tbl) {
1188 if (tbl->company != INVALID_COMPANY && !Company::IsValidID(tbl->company)) {
1189 /* Rebuild the owner legend. */
1190 BuildOwnerLegend();
1191 this->InvalidateData(1);
1192 break;
1197 this->DrawWidgets();
1200 /* virtual */ void SmallMapWindow::DrawWidget(const Rect &r, int widget) const
1202 switch (widget) {
1203 case WID_SM_MAP: {
1204 DrawPixelInfo new_dpi;
1205 if (!FillDrawPixelInfo(&new_dpi, r.left + 1, r.top + 1, r.right - r.left - 1, r.bottom - r.top - 1)) return;
1206 this->DrawSmallMap(&new_dpi);
1207 break;
1210 case WID_SM_LEGEND: {
1211 uint columns = this->GetNumberColumnsLegend(r.right - r.left + 1);
1212 uint number_of_rows = this->GetNumberRowsLegend(columns);
1213 bool rtl = _current_text_dir == TD_RTL;
1214 uint y_org = r.top + WD_FRAMERECT_TOP;
1215 uint x = rtl ? r.right - this->column_width - WD_FRAMERECT_RIGHT : r.left + WD_FRAMERECT_LEFT;
1216 uint y = y_org;
1217 uint i = 0; // Row counter for industry legend.
1218 uint row_height = FONT_HEIGHT_SMALL;
1220 uint text_left = rtl ? 0 : LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT;
1221 uint text_right = this->column_width - 1 - (rtl ? LEGEND_BLOB_WIDTH + WD_FRAMERECT_RIGHT : 0);
1222 uint blob_left = rtl ? this->column_width - 1 - LEGEND_BLOB_WIDTH : 0;
1223 uint blob_right = rtl ? this->column_width - 1 : LEGEND_BLOB_WIDTH;
1225 StringID string = STR_NULL;
1226 switch (this->map_type) {
1227 case SMT_INDUSTRY:
1228 string = STR_SMALLMAP_INDUSTRY;
1229 break;
1230 case SMT_LINKSTATS:
1231 string = STR_SMALLMAP_LINKSTATS;
1232 break;
1233 case SMT_OWNER:
1234 string = STR_SMALLMAP_COMPANY;
1235 break;
1236 default:
1237 break;
1240 for (const LegendAndColour *tbl = _legend_table[this->map_type]; !tbl->end; ++tbl) {
1241 if (tbl->col_break || ((this->map_type == SMT_INDUSTRY || this->map_type == SMT_OWNER || this->map_type == SMT_LINKSTATS) && i++ >= number_of_rows)) {
1242 /* Column break needed, continue at top, COLUMN_WIDTH pixels
1243 * (one "row") to the right. */
1244 x += rtl ? -(int)this->column_width : this->column_width;
1245 y = y_org;
1246 i = 1;
1249 uint8 legend_colour = tbl->colour;
1251 switch (this->map_type) {
1252 case SMT_INDUSTRY:
1253 /* Industry name must be formatted, since it's not in tiny font in the specs.
1254 * So, draw with a parameter and use the STR_SMALLMAP_INDUSTRY string, which is tiny font */
1255 SetDParam(0, tbl->legend);
1256 SetDParam(1, Industry::GetIndustryTypeCount(tbl->type));
1257 if (tbl->show_on_map && tbl->type == _smallmap_industry_highlight) {
1258 legend_colour = _smallmap_industry_highlight_state ? PC_WHITE : PC_BLACK;
1260 FALLTHROUGH;
1262 case SMT_LINKSTATS:
1263 SetDParam(0, tbl->legend);
1264 FALLTHROUGH;
1266 case SMT_OWNER:
1267 if (this->map_type != SMT_OWNER || tbl->company != INVALID_COMPANY) {
1268 if (this->map_type == SMT_OWNER) SetDParam(0, tbl->company);
1269 if (!tbl->show_on_map) {
1270 /* Simply draw the string, not the black border of the legend colour.
1271 * This will enforce the idea of the disabled item */
1272 DrawString(x + text_left, x + text_right, y, string, TC_GREY);
1273 } else {
1274 DrawString(x + text_left, x + text_right, y, string, TC_BLACK);
1275 GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK); // Outer border of the legend colour
1277 break;
1279 FALLTHROUGH;
1281 default:
1282 if (this->map_type == SMT_CONTOUR) SetDParam(0, tbl->height * TILE_HEIGHT_STEP);
1283 /* Anything that is not an industry or a company is using normal process */
1284 GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK);
1285 DrawString(x + text_left, x + text_right, y, tbl->legend);
1286 break;
1288 GfxFillRect(x + blob_left + 1, y + 2, x + blob_right - 1, y + row_height - 2, legend_colour); // Legend colour
1290 y += row_height;
1297 * Select a new map type.
1298 * @param map_type New map type.
1300 void SmallMapWindow::SwitchMapType(SmallMapType map_type)
1302 this->RaiseWidget(this->map_type + WID_SM_CONTOUR);
1303 this->map_type = map_type;
1304 this->LowerWidget(this->map_type + WID_SM_CONTOUR);
1306 this->SetupWidgetData();
1308 if (map_type == SMT_LINKSTATS) this->overlay->SetDirty();
1309 if (map_type != SMT_INDUSTRY) this->BreakIndustryChainLink();
1310 this->SetDirty();
1314 * Get the number of rows in the legend from the number of columns. Those
1315 * are at least min_number_of_fixed_rows and possibly more if there are so
1316 * many cargoes, industry types or companies that they won't fit in the
1317 * available space.
1318 * @param columns Number of columns in the legend.
1319 * @return Number of rows needed for everything to fit in.
1321 inline uint SmallMapWindow::GetNumberRowsLegend(uint columns) const
1323 /* Reserve one column for link colours */
1324 uint num_rows_linkstats = CeilDiv(_smallmap_cargo_count, columns - 1);
1325 uint num_rows_others = CeilDiv(std::max(_smallmap_industry_count, _smallmap_company_count), columns);
1326 return std::max({this->min_number_of_fixed_rows, num_rows_linkstats, num_rows_others});
1330 * Select and toggle a legend item. When CTRL is pressed, disable all other
1331 * items in the group defined by begin_legend_item and end_legend_item and
1332 * keep the clicked one enabled even if it was already enabled before. If
1333 * the other items in the group are all disabled already and CTRL is pressed
1334 * enable them instead.
1335 * @param click_pos the index of the item being selected
1336 * @param legend the legend from which we select
1337 * @param end_legend_item index one past the last item in the group to be inverted
1338 * @param begin_legend_item index of the first item in the group to be inverted
1340 void SmallMapWindow::SelectLegendItem(int click_pos, LegendAndColour *legend, int end_legend_item, int begin_legend_item)
1342 if (_ctrl_pressed) {
1343 /* Disable all, except the clicked one */
1344 bool changes = false;
1345 for (int i = begin_legend_item; i != end_legend_item; i++) {
1346 bool new_state = (i == click_pos);
1347 if (legend[i].show_on_map != new_state) {
1348 changes = true;
1349 legend[i].show_on_map = new_state;
1352 if (!changes) {
1353 /* Nothing changed? Then show all (again). */
1354 for (int i = begin_legend_item; i != end_legend_item; i++) {
1355 legend[i].show_on_map = true;
1358 } else {
1359 legend[click_pos].show_on_map = !legend[click_pos].show_on_map;
1362 if (this->map_type == SMT_INDUSTRY) this->BreakIndustryChainLink();
1366 * Set the link graph overlay cargo mask from the legend.
1368 void SmallMapWindow::SetOverlayCargoMask()
1370 CargoTypes cargo_mask = 0;
1371 for (int i = 0; i != _smallmap_cargo_count; ++i) {
1372 if (_legend_linkstats[i].show_on_map) SetBit(cargo_mask, _legend_linkstats[i].type);
1374 this->overlay->SetCargoMask(cargo_mask);
1378 * Determines the mouse position on the legend.
1379 * @param pt Mouse position.
1380 * @return Legend item under the mouse.
1382 int SmallMapWindow::GetPositionOnLegend(Point pt)
1384 const NWidgetBase *wi = this->GetWidget<NWidgetBase>(WID_SM_LEGEND);
1385 uint line = (pt.y - wi->pos_y - WD_FRAMERECT_TOP) / FONT_HEIGHT_SMALL;
1386 uint columns = this->GetNumberColumnsLegend(wi->current_x);
1387 uint number_of_rows = this->GetNumberRowsLegend(columns);
1388 if (line >= number_of_rows) return -1;
1390 bool rtl = _current_text_dir == TD_RTL;
1391 int x = pt.x - wi->pos_x;
1392 if (rtl) x = wi->current_x - x;
1393 uint column = (x - WD_FRAMERECT_LEFT) / this->column_width;
1395 return (column * number_of_rows) + line;
1398 /* virtual */ void SmallMapWindow::OnMouseOver(Point pt, int widget)
1400 IndustryType new_highlight = INVALID_INDUSTRYTYPE;
1401 if (widget == WID_SM_LEGEND && this->map_type == SMT_INDUSTRY) {
1402 int industry_pos = GetPositionOnLegend(pt);
1403 if (industry_pos >= 0 && industry_pos < _smallmap_industry_count) {
1404 new_highlight = _legend_from_industries[industry_pos].type;
1407 if (new_highlight != _smallmap_industry_highlight) {
1408 _smallmap_industry_highlight = new_highlight;
1409 this->refresh.SetInterval(_smallmap_industry_highlight != INVALID_INDUSTRYTYPE ? BLINK_PERIOD : FORCE_REFRESH_PERIOD);
1410 _smallmap_industry_highlight_state = true;
1411 this->SetDirty();
1415 /* virtual */ void SmallMapWindow::OnClick(Point pt, int widget, int click_count)
1417 switch (widget) {
1418 case WID_SM_MAP: { // Map window
1419 if (click_count > 0) this->mouse_capture_widget = widget;
1421 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1422 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
1423 int sub;
1424 pt = this->PixelToTile(pt.x - wid->pos_x, pt.y - wid->pos_y, &sub);
1425 ScrollWindowTo(this->scroll_x + pt.x * TILE_SIZE, this->scroll_y + pt.y * TILE_SIZE, -1, w);
1427 this->SetDirty();
1428 break;
1431 case WID_SM_ZOOM_IN:
1432 case WID_SM_ZOOM_OUT: {
1433 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1434 Point pt = { (int)wid->current_x / 2, (int)wid->current_y / 2};
1435 this->SetZoomLevel((widget == WID_SM_ZOOM_IN) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &pt);
1436 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1437 break;
1440 case WID_SM_CONTOUR: // Show land contours
1441 case WID_SM_VEHICLES: // Show vehicles
1442 case WID_SM_INDUSTRIES: // Show industries
1443 case WID_SM_LINKSTATS: // Show route map
1444 case WID_SM_ROUTES: // Show transport routes
1445 case WID_SM_VEGETATION: // Show vegetation
1446 case WID_SM_OWNERS: // Show land owners
1447 this->SwitchMapType((SmallMapType)(widget - WID_SM_CONTOUR));
1448 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1449 break;
1451 case WID_SM_CENTERMAP: // Center the smallmap again
1452 this->SmallMapCenterOnCurrentPos();
1453 this->HandleButtonClick(WID_SM_CENTERMAP);
1454 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1455 break;
1457 case WID_SM_TOGGLETOWNNAME: // Toggle town names
1458 this->show_towns = !this->show_towns;
1459 this->SetWidgetLoweredState(WID_SM_TOGGLETOWNNAME, this->show_towns);
1461 this->SetDirty();
1462 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
1463 break;
1465 case WID_SM_LEGEND: // Legend
1466 if (this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER) {
1467 int click_pos = this->GetPositionOnLegend(pt);
1468 if (click_pos < 0) break;
1470 /* If industry type small map*/
1471 if (this->map_type == SMT_INDUSTRY) {
1472 /* If click on industries label, find right industry type and enable/disable it. */
1473 if (click_pos < _smallmap_industry_count) {
1474 this->SelectLegendItem(click_pos, _legend_from_industries, _smallmap_industry_count);
1476 } else if (this->map_type == SMT_LINKSTATS) {
1477 if (click_pos < _smallmap_cargo_count) {
1478 this->SelectLegendItem(click_pos, _legend_linkstats, _smallmap_cargo_count);
1479 this->SetOverlayCargoMask();
1481 } else if (this->map_type == SMT_OWNER) {
1482 if (click_pos < _smallmap_company_count) {
1483 this->SelectLegendItem(click_pos, _legend_land_owners, _smallmap_company_count, NUM_NO_COMPANY_ENTRIES);
1486 this->SetDirty();
1488 break;
1490 case WID_SM_ENABLE_ALL:
1491 case WID_SM_DISABLE_ALL: {
1492 LegendAndColour *tbl = nullptr;
1493 switch (this->map_type) {
1494 case SMT_INDUSTRY:
1495 tbl = _legend_from_industries;
1496 this->BreakIndustryChainLink();
1497 break;
1498 case SMT_OWNER:
1499 tbl = &(_legend_land_owners[NUM_NO_COMPANY_ENTRIES]);
1500 break;
1501 case SMT_LINKSTATS:
1502 tbl = _legend_linkstats;
1503 break;
1504 default:
1505 NOT_REACHED();
1507 for (;!tbl->end && tbl->legend != STR_LINKGRAPH_LEGEND_UNUSED; ++tbl) {
1508 tbl->show_on_map = (widget == WID_SM_ENABLE_ALL);
1510 if (this->map_type == SMT_LINKSTATS) this->SetOverlayCargoMask();
1511 this->SetDirty();
1512 break;
1515 case WID_SM_SHOW_HEIGHT: // Enable/disable showing of heightmap.
1516 _smallmap_show_heightmap = !_smallmap_show_heightmap;
1517 this->SetWidgetLoweredState(WID_SM_SHOW_HEIGHT, _smallmap_show_heightmap);
1518 this->SetDirty();
1519 break;
1524 * Some data on this window has become invalid.
1525 * @param data Information about the changed data.
1526 * - data = 0: Displayed industries at the industry chain window have changed.
1527 * - data = 1: Companies have changed.
1528 * - data = 2: Cheat changing the maximum heightlevel has been used, rebuild our heightlevel-to-colour index
1529 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1531 /* virtual */ void SmallMapWindow::OnInvalidateData(int data, bool gui_scope)
1533 if (!gui_scope) return;
1535 switch (data) {
1536 case 1:
1537 /* The owner legend has already been rebuilt. */
1538 this->ReInit();
1539 break;
1541 case 0: {
1542 extern std::bitset<NUM_INDUSTRYTYPES> _displayed_industries;
1543 if (this->map_type != SMT_INDUSTRY) this->SwitchMapType(SMT_INDUSTRY);
1545 for (int i = 0; i != _smallmap_industry_count; i++) {
1546 _legend_from_industries[i].show_on_map = _displayed_industries.test(_legend_from_industries[i].type);
1548 break;
1551 case 2:
1552 this->RebuildColourIndexIfNecessary();
1553 break;
1555 default: NOT_REACHED();
1557 this->SetDirty();
1560 /* virtual */ bool SmallMapWindow::OnRightClick(Point pt, int widget)
1562 if (widget != WID_SM_MAP || _scrolling_viewport) return false;
1564 _scrolling_viewport = true;
1565 return true;
1568 /* virtual */ void SmallMapWindow::OnMouseWheel(int wheel)
1570 if (_settings_client.gui.scrollwheel_scrolling != 2) {
1571 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1572 int cursor_x = _cursor.pos.x - this->left - wid->pos_x;
1573 int cursor_y = _cursor.pos.y - this->top - wid->pos_y;
1574 if (IsInsideMM(cursor_x, 0, wid->current_x) && IsInsideMM(cursor_y, 0, wid->current_y)) {
1575 Point pt = {cursor_x, cursor_y};
1576 this->SetZoomLevel((wheel < 0) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &pt);
1581 /* virtual */ void SmallMapWindow::OnRealtimeTick(uint delta_ms)
1583 /* Update the window every now and then */
1584 if (!this->refresh.Elapsed(delta_ms)) return;
1586 if (this->map_type == SMT_LINKSTATS) {
1587 uint32 company_mask = this->GetOverlayCompanyMask();
1588 if (this->overlay->GetCompanyMask() != company_mask) {
1589 this->overlay->SetCompanyMask(company_mask);
1590 } else {
1591 this->overlay->SetDirty();
1594 _smallmap_industry_highlight_state = !_smallmap_industry_highlight_state;
1596 this->refresh.SetInterval(_smallmap_industry_highlight != INVALID_INDUSTRYTYPE ? BLINK_PERIOD : FORCE_REFRESH_PERIOD);
1597 this->SetDirty();
1601 * Set new #scroll_x, #scroll_y, and #subscroll values after limiting them such that the center
1602 * of the smallmap always contains a part of the map.
1603 * @param sx Proposed new #scroll_x
1604 * @param sy Proposed new #scroll_y
1605 * @param sub Proposed new #subscroll
1607 void SmallMapWindow::SetNewScroll(int sx, int sy, int sub)
1609 const NWidgetBase *wi = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1610 Point hv = InverseRemapCoords(wi->current_x * ZOOM_LVL_BASE * TILE_SIZE / 2, wi->current_y * ZOOM_LVL_BASE * TILE_SIZE / 2);
1611 hv.x *= this->zoom;
1612 hv.y *= this->zoom;
1614 if (sx < -hv.x) {
1615 sx = -hv.x;
1616 sub = 0;
1618 if (sx > (int)(MapMaxX() * TILE_SIZE) - hv.x) {
1619 sx = MapMaxX() * TILE_SIZE - hv.x;
1620 sub = 0;
1622 if (sy < -hv.y) {
1623 sy = -hv.y;
1624 sub = 0;
1626 if (sy > (int)(MapMaxY() * TILE_SIZE) - hv.y) {
1627 sy = MapMaxY() * TILE_SIZE - hv.y;
1628 sub = 0;
1631 this->scroll_x = sx;
1632 this->scroll_y = sy;
1633 this->subscroll = sub;
1634 if (this->map_type == SMT_LINKSTATS) this->overlay->SetDirty();
1637 /* virtual */ void SmallMapWindow::OnScroll(Point delta)
1639 if (_settings_client.gui.scroll_mode == VSM_VIEWPORT_RMB_FIXED || _settings_client.gui.scroll_mode == VSM_MAP_RMB_FIXED) _cursor.fix_at = true;
1641 /* While tile is at (delta.x, delta.y)? */
1642 int sub;
1643 Point pt = this->PixelToTile(delta.x, delta.y, &sub);
1644 this->SetNewScroll(this->scroll_x + pt.x * TILE_SIZE, this->scroll_y + pt.y * TILE_SIZE, sub);
1646 this->SetDirty();
1650 * Center the small map on the current center of the viewport.
1652 void SmallMapWindow::SmallMapCenterOnCurrentPos()
1654 const Viewport *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
1655 Point viewport_center = InverseRemapCoords2(vp->virtual_left + vp->virtual_width / 2, vp->virtual_top + vp->virtual_height / 2);
1657 int sub;
1658 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SM_MAP);
1659 Point sxy = this->ComputeScroll(viewport_center.x / (int)TILE_SIZE, viewport_center.y / (int)TILE_SIZE,
1660 std::max(0, (int)wid->current_x / 2 - 2), wid->current_y / 2, &sub);
1661 this->SetNewScroll(sxy.x, sxy.y, sub);
1662 this->SetDirty();
1666 * Get the center of the given station as point on the screen in the smallmap window.
1667 * @param st Station to find in the smallmap.
1668 * @return Point with coordinates of the station.
1670 Point SmallMapWindow::GetStationMiddle(const Station *st) const
1672 int x = (st->rect.right + st->rect.left + 1) / 2;
1673 int y = (st->rect.bottom + st->rect.top + 1) / 2;
1674 Point ret = this->RemapTile(x, y);
1676 /* Same magic 3 as in DrawVehicles; that's where I got it from.
1677 * No idea what it is, but without it the result looks bad.
1679 ret.x -= 3 + this->subscroll;
1680 return ret;
1683 SmallMapWindow::SmallMapType SmallMapWindow::map_type = SMT_CONTOUR;
1684 bool SmallMapWindow::show_towns = true;
1685 int SmallMapWindow::max_heightlevel = -1;
1688 * Custom container class for displaying smallmap with a vertically resizing legend panel.
1689 * The legend panel has a smallest height that depends on its width. Standard containers cannot handle this case.
1691 * @note The container assumes it has two children, the first is the display, the second is the bar with legends and selection image buttons.
1692 * Both children should be both horizontally and vertically resizable and horizontally fillable.
1693 * The bar should have a minimal size with a zero-size legends display. Child padding is not supported.
1695 class NWidgetSmallmapDisplay : public NWidgetContainer {
1696 const SmallMapWindow *smallmap_window; ///< Window manager instance.
1697 public:
1698 NWidgetSmallmapDisplay() : NWidgetContainer(NWID_VERTICAL)
1700 this->smallmap_window = nullptr;
1703 void SetupSmallestSize(Window *w, bool init_array) override
1705 NWidgetBase *display = this->head;
1706 NWidgetBase *bar = display->next;
1708 display->SetupSmallestSize(w, init_array);
1709 bar->SetupSmallestSize(w, init_array);
1711 this->smallmap_window = dynamic_cast<SmallMapWindow *>(w);
1712 assert(this->smallmap_window != nullptr);
1713 this->smallest_x = std::max(display->smallest_x, bar->smallest_x + smallmap_window->GetMinLegendWidth());
1714 this->smallest_y = display->smallest_y + std::max(bar->smallest_y, smallmap_window->GetLegendHeight(smallmap_window->min_number_of_columns));
1715 this->fill_x = std::max(display->fill_x, bar->fill_x);
1716 this->fill_y = (display->fill_y == 0 && bar->fill_y == 0) ? 0 : std::min(display->fill_y, bar->fill_y);
1717 this->resize_x = std::max(display->resize_x, bar->resize_x);
1718 this->resize_y = std::min(display->resize_y, bar->resize_y);
1721 void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl) override
1723 this->pos_x = x;
1724 this->pos_y = y;
1725 this->current_x = given_width;
1726 this->current_y = given_height;
1728 NWidgetBase *display = this->head;
1729 NWidgetBase *bar = display->next;
1731 if (sizing == ST_SMALLEST) {
1732 this->smallest_x = given_width;
1733 this->smallest_y = given_height;
1734 /* Make display and bar exactly equal to their minimal size. */
1735 display->AssignSizePosition(ST_SMALLEST, x, y, display->smallest_x, display->smallest_y, rtl);
1736 bar->AssignSizePosition(ST_SMALLEST, x, y + display->smallest_y, bar->smallest_x, bar->smallest_y, rtl);
1739 uint bar_height = std::max(bar->smallest_y, this->smallmap_window->GetLegendHeight(this->smallmap_window->GetNumberColumnsLegend(given_width - bar->smallest_x)));
1740 uint display_height = given_height - bar_height;
1741 display->AssignSizePosition(ST_RESIZE, x, y, given_width, display_height, rtl);
1742 bar->AssignSizePosition(ST_RESIZE, x, y + display_height, given_width, bar_height, rtl);
1745 NWidgetCore *GetWidgetFromPos(int x, int y) override
1747 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1748 for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1749 NWidgetCore *widget = child_wid->GetWidgetFromPos(x, y);
1750 if (widget != nullptr) return widget;
1752 return nullptr;
1755 void Draw(const Window *w) override
1757 for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) child_wid->Draw(w);
1761 /** Widget parts of the smallmap display. */
1762 static const NWidgetPart _nested_smallmap_display[] = {
1763 NWidget(WWT_PANEL, COLOUR_BROWN, WID_SM_MAP_BORDER),
1764 NWidget(WWT_INSET, COLOUR_BROWN, WID_SM_MAP), SetMinimalSize(346, 140), SetResize(1, 1), SetPadding(2, 2, 2, 2), EndContainer(),
1765 EndContainer(),
1768 /** Widget parts of the smallmap legend bar + image buttons. */
1769 static const NWidgetPart _nested_smallmap_bar[] = {
1770 NWidget(WWT_PANEL, COLOUR_BROWN),
1771 NWidget(NWID_HORIZONTAL),
1772 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SM_LEGEND), SetResize(1, 1),
1773 NWidget(NWID_VERTICAL),
1774 /* Top button row. */
1775 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1776 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_ZOOM_IN),
1777 SetDataTip(SPR_IMG_ZOOMIN, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_IN), SetFill(1, 1),
1778 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_CENTERMAP),
1779 SetDataTip(SPR_IMG_SMALLMAP, STR_SMALLMAP_CENTER), SetFill(1, 1),
1780 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_BLANK),
1781 SetDataTip(SPR_DOT_SMALL, STR_NULL), SetFill(1, 1),
1782 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_CONTOUR),
1783 SetDataTip(SPR_IMG_SHOW_COUNTOURS, STR_SMALLMAP_TOOLTIP_SHOW_LAND_CONTOURS_ON_MAP), SetFill(1, 1),
1784 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_VEHICLES),
1785 SetDataTip(SPR_IMG_SHOW_VEHICLES, STR_SMALLMAP_TOOLTIP_SHOW_VEHICLES_ON_MAP), SetFill(1, 1),
1786 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_INDUSTRIES),
1787 SetDataTip(SPR_IMG_INDUSTRY, STR_SMALLMAP_TOOLTIP_SHOW_INDUSTRIES_ON_MAP), SetFill(1, 1),
1788 EndContainer(),
1789 /* Bottom button row. */
1790 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1791 NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, WID_SM_ZOOM_OUT),
1792 SetDataTip(SPR_IMG_ZOOMOUT, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_OUT), SetFill(1, 1),
1793 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_TOGGLETOWNNAME),
1794 SetDataTip(SPR_IMG_TOWN, STR_SMALLMAP_TOOLTIP_TOGGLE_TOWN_NAMES_ON_OFF), SetFill(1, 1),
1795 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_LINKSTATS),
1796 SetDataTip(SPR_IMG_CARGOFLOW, STR_SMALLMAP_TOOLTIP_SHOW_LINK_STATS_ON_MAP), SetFill(1, 1),
1797 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_ROUTES),
1798 SetDataTip(SPR_IMG_SHOW_ROUTES, STR_SMALLMAP_TOOLTIP_SHOW_TRANSPORT_ROUTES_ON), SetFill(1, 1),
1799 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_VEGETATION),
1800 SetDataTip(SPR_IMG_PLANTTREES, STR_SMALLMAP_TOOLTIP_SHOW_VEGETATION_ON_MAP), SetFill(1, 1),
1801 NWidget(WWT_IMGBTN, COLOUR_BROWN, WID_SM_OWNERS),
1802 SetDataTip(SPR_IMG_COMPANY_GENERAL, STR_SMALLMAP_TOOLTIP_SHOW_LAND_OWNERS_ON_MAP), SetFill(1, 1),
1803 EndContainer(),
1804 NWidget(NWID_SPACER), SetResize(0, 1),
1805 EndContainer(),
1806 EndContainer(),
1807 EndContainer(),
1810 static NWidgetBase *SmallMapDisplay(int *biggest_index)
1812 NWidgetContainer *map_display = new NWidgetSmallmapDisplay;
1814 MakeNWidgets(_nested_smallmap_display, lengthof(_nested_smallmap_display), biggest_index, map_display);
1815 MakeNWidgets(_nested_smallmap_bar, lengthof(_nested_smallmap_bar), biggest_index, map_display);
1816 return map_display;
1820 static const NWidgetPart _nested_smallmap_widgets[] = {
1821 NWidget(NWID_HORIZONTAL),
1822 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1823 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_SM_CAPTION), SetDataTip(STR_SMALLMAP_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1824 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1825 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1826 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1827 EndContainer(),
1828 NWidgetFunction(SmallMapDisplay), // Smallmap display and legend bar + image buttons.
1829 /* Bottom button row and resize box. */
1830 NWidget(NWID_HORIZONTAL),
1831 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_SM_SELECT_BUTTONS),
1832 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1833 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_SM_ENABLE_ALL), SetDataTip(STR_SMALLMAP_ENABLE_ALL, STR_NULL),
1834 NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, WID_SM_DISABLE_ALL), SetDataTip(STR_SMALLMAP_DISABLE_ALL, STR_NULL),
1835 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_SM_SHOW_HEIGHT), SetDataTip(STR_SMALLMAP_SHOW_HEIGHT, STR_SMALLMAP_TOOLTIP_SHOW_HEIGHT),
1836 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(1, 0),
1837 EndContainer(),
1838 EndContainer(),
1839 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(1, 0),
1840 EndContainer(),
1841 EndContainer(),
1842 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1843 EndContainer(),
1846 static WindowDesc _smallmap_desc(
1847 WDP_AUTO, "smallmap", 484, 314,
1848 WC_SMALLMAP, WC_NONE,
1850 _nested_smallmap_widgets, lengthof(_nested_smallmap_widgets)
1854 * Show the smallmap window.
1856 void ShowSmallMap()
1858 AllocateWindowDescFront<SmallMapWindow>(&_smallmap_desc, 0);
1862 * Scrolls the main window to given coordinates.
1863 * @param x x coordinate
1864 * @param y y coordinate
1865 * @param z z coordinate; -1 to scroll to terrain height
1866 * @param instant scroll instantly (meaningful only when smooth_scrolling is active)
1867 * @return did the viewport position change?
1869 bool ScrollMainWindowTo(int x, int y, int z, bool instant)
1871 bool res = ScrollWindowTo(x, y, z, FindWindowById(WC_MAIN_WINDOW, 0), instant);
1873 /* If a user scrolls to a tile (via what way what so ever) and already is on
1874 * that tile (e.g.: pressed twice), move the smallmap to that location,
1875 * so you directly see where you are on the smallmap. */
1877 if (res) return res;
1879 SmallMapWindow *w = dynamic_cast<SmallMapWindow*>(FindWindowById(WC_SMALLMAP, 0));
1880 if (w != nullptr) w->SmallMapCenterOnCurrentPos();
1882 return res;