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