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/>.
9 * @file viewport.cpp Handling of all viewports.
12 * The in-game coordinate system looks like this *
28 * @defgroup vp_column_row Rows and columns in the viewport
30 * Columns are vertical sections of the viewport that are half a tile wide.
31 * The origin, i.e. column 0, is through the northern and southern most tile.
32 * This means that the column of e.g. Tile(0, 0) and Tile(100, 100) are in
33 * column number 0. The negative columns are towards the left of the screen,
34 * or towards the west, whereas the positive ones are towards respectively
36 * With half a tile wide is meant that the next column of tiles directly west
37 * or east of the centre line are respectively column -1 and 1. Their tile
38 * centers are only half a tile from the center of their adjoining tile when
39 * looking only at the X-coordinate.
58 * Rows are horizontal sections of the viewport, also half a tile wide.
59 * This time the northern most tile on the map defines 0 and
60 * everything south of that has a positive number.
64 #include "core/backup_type.hpp"
65 #include "landscape.h"
66 #include "viewport_func.h"
67 #include "station_base.h"
68 #include "waypoint_base.h"
70 #include "signs_base.h"
71 #include "signs_func.h"
72 #include "vehicle_base.h"
73 #include "vehicle_gui.h"
74 #include "blitter/factory.hpp"
75 #include "strings_func.h"
76 #include "zoom_func.h"
77 #include "vehicle_func.h"
78 #include "company_func.h"
79 #include "waypoint_func.h"
80 #include "window_func.h"
81 #include "tilehighlight_func.h"
82 #include "window_gui.h"
83 #include "linkgraph/linkgraph_gui.h"
84 #include "viewport_kdtree.h"
85 #include "town_kdtree.h"
86 #include "viewport_sprite_sorter.h"
87 #include "bridge_map.h"
88 #include "company_base.h"
89 #include "command_func.h"
90 #include "network/network_func.h"
91 #include "framerate_type.h"
92 #include "viewport_cmd.h"
94 #include <forward_list>
97 #include "table/strings.h"
98 #include "table/string_colours.h"
100 #include "safeguards.h"
102 Point _tile_fract_coords
;
105 ViewportSignKdtree
_viewport_sign_kdtree(&Kdtree_ViewportSignXYFunc
);
106 static int _viewport_sign_maxwidth
= 0;
109 static const int MAX_TILE_EXTENT_LEFT
= ZOOM_LVL_BASE
* TILE_PIXELS
; ///< Maximum left extent of tile relative to north corner.
110 static const int MAX_TILE_EXTENT_RIGHT
= ZOOM_LVL_BASE
* TILE_PIXELS
; ///< Maximum right extent of tile relative to north corner.
111 static const int MAX_TILE_EXTENT_TOP
= ZOOM_LVL_BASE
* MAX_BUILDING_PIXELS
; ///< Maximum top extent of tile relative to north corner (not considering bridges).
112 static const int MAX_TILE_EXTENT_BOTTOM
= ZOOM_LVL_BASE
* (TILE_PIXELS
+ 2 * TILE_HEIGHT
); ///< Maximum bottom extent of tile relative to north corner (worst case: #SLOPE_STEEP_N).
114 struct StringSpriteToDraw
{
123 struct TileSpriteToDraw
{
126 const SubSprite
*sub
; ///< only draw a rectangular part of the sprite
127 int32_t x
; ///< screen X coordinate of sprite
128 int32_t y
; ///< screen Y coordinate of sprite
131 struct ChildScreenSpriteToDraw
{
134 const SubSprite
*sub
; ///< only draw a rectangular part of the sprite
138 int next
; ///< next child to draw (-1 at the end)
141 /** Enumeration of multi-part foundations */
142 enum FoundationPart
{
143 FOUNDATION_PART_NONE
= 0xFF, ///< Neither foundation nor groundsprite drawn yet.
144 FOUNDATION_PART_NORMAL
= 0, ///< First part (normal foundation or no foundation)
145 FOUNDATION_PART_HALFTILE
= 1, ///< Second part (halftile foundation)
150 * Mode of "sprite combining"
151 * @see StartSpriteCombine
153 enum SpriteCombineMode
{
154 SPRITE_COMBINE_NONE
, ///< Every #AddSortableSpriteToDraw start its own bounding box
155 SPRITE_COMBINE_PENDING
, ///< %Sprite combining will start with the next unclipped sprite.
156 SPRITE_COMBINE_ACTIVE
, ///< %Sprite combining is active. #AddSortableSpriteToDraw outputs child sprites.
159 typedef std::vector
<TileSpriteToDraw
> TileSpriteToDrawVector
;
160 typedef std::vector
<StringSpriteToDraw
> StringSpriteToDrawVector
;
161 typedef std::vector
<ParentSpriteToDraw
> ParentSpriteToDrawVector
;
162 typedef std::vector
<ChildScreenSpriteToDraw
> ChildScreenSpriteToDrawVector
;
164 /** Data structure storing rendering information */
165 struct ViewportDrawer
{
168 StringSpriteToDrawVector string_sprites_to_draw
;
169 TileSpriteToDrawVector tile_sprites_to_draw
;
170 ParentSpriteToDrawVector parent_sprites_to_draw
;
171 ParentSpriteToSortVector parent_sprites_to_sort
; ///< Parent sprite pointer array used for sorting
172 ChildScreenSpriteToDrawVector child_screen_sprites_to_draw
;
176 SpriteCombineMode combine_sprites
; ///< Current mode of "sprite combining". @see StartSpriteCombine
178 int foundation
[FOUNDATION_PART_END
]; ///< Foundation sprites (index into parent_sprites_to_draw).
179 FoundationPart foundation_part
; ///< Currently active foundation for ground sprite drawing.
180 int *last_foundation_child
[FOUNDATION_PART_END
]; ///< Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw)
181 Point foundation_offset
[FOUNDATION_PART_END
]; ///< Pixel offset for ground sprites on the foundations.
184 static bool MarkViewportDirty(const Viewport
*vp
, int left
, int top
, int right
, int bottom
);
186 static ViewportDrawer _vd
;
188 TileHighlightData _thd
;
189 static TileInfo _cur_ti
;
190 bool _draw_bounding_boxes
= false;
191 bool _draw_dirty_blocks
= false;
192 uint _dirty_block_colour
= 0;
193 static VpSpriteSorter _vp_sprite_sorter
= nullptr;
195 static Point
MapXYZToViewport(const Viewport
*vp
, int x
, int y
, int z
)
197 Point p
= RemapCoords(x
, y
, z
);
198 p
.x
-= vp
->virtual_width
/ 2;
199 p
.y
-= vp
->virtual_height
/ 2;
203 void DeleteWindowViewport(Window
*w
)
206 w
->viewport
= nullptr;
210 * Initialize viewport of the window for use.
211 * @param w Window to use/display the viewport in
212 * @param x Offset of left edge of viewport with respect to left edge window \a w
213 * @param y Offset of top edge of viewport with respect to top edge window \a w
214 * @param width Width of the viewport
215 * @param height Height of the viewport
216 * @param focus Either the tile index or vehicle ID to focus.
217 * @param zoom Zoomlevel to display
219 void InitializeWindowViewport(Window
*w
, int x
, int y
,
220 int width
, int height
, std::variant
<TileIndex
, VehicleID
> focus
, ZoomLevel zoom
)
222 assert(w
->viewport
== nullptr);
224 ViewportData
*vp
= new ViewportData();
226 vp
->left
= x
+ w
->left
;
227 vp
->top
= y
+ w
->top
;
231 vp
->zoom
= static_cast<ZoomLevel
>(Clamp(zoom
, _settings_client
.gui
.zoom_min
, _settings_client
.gui
.zoom_max
));
233 vp
->virtual_width
= ScaleByZoom(width
, zoom
);
234 vp
->virtual_height
= ScaleByZoom(height
, zoom
);
238 if (std::holds_alternative
<VehicleID
>(focus
)) {
241 vp
->follow_vehicle
= std::get
<VehicleID
>(focus
);
242 veh
= Vehicle::Get(vp
->follow_vehicle
);
243 pt
= MapXYZToViewport(vp
, veh
->x_pos
, veh
->y_pos
, veh
->z_pos
);
245 TileIndex tile
= std::get
<TileIndex
>(focus
);
246 if (tile
== INVALID_TILE
) {
247 /* No tile? Use center of main viewport. */
248 const Window
*mw
= GetMainWindow();
250 /* center on same place as main window (zoom is maximum, no adjustment needed) */
251 pt
.x
= mw
->viewport
->scrollpos_x
+ mw
->viewport
->virtual_width
/ 2;
252 pt
.x
-= vp
->virtual_width
/ 2;
253 pt
.y
= mw
->viewport
->scrollpos_y
+ mw
->viewport
->virtual_height
/ 2;
254 pt
.y
-= vp
->virtual_height
/ 2;
256 x
= TileX(tile
) * TILE_SIZE
;
257 y
= TileY(tile
) * TILE_SIZE
;
258 pt
= MapXYZToViewport(vp
, x
, y
, GetSlopePixelZ(x
, y
));
260 vp
->follow_vehicle
= INVALID_VEHICLE
;
263 vp
->scrollpos_x
= pt
.x
;
264 vp
->scrollpos_y
= pt
.y
;
265 vp
->dest_scrollpos_x
= pt
.x
;
266 vp
->dest_scrollpos_y
= pt
.y
;
268 vp
->overlay
= nullptr;
271 vp
->virtual_left
= 0;
275 static Point _vp_move_offs
;
277 static void DoSetViewportPosition(Window::IteratorToFront it
, int left
, int top
, int width
, int height
)
279 for (; !it
.IsEnd(); ++it
) {
280 const Window
*w
= *it
;
281 if (left
+ width
> w
->left
&&
282 w
->left
+ w
->width
> left
&&
283 top
+ height
> w
->top
&&
284 w
->top
+ w
->height
> top
) {
286 if (left
< w
->left
) {
287 DoSetViewportPosition(it
, left
, top
, w
->left
- left
, height
);
288 DoSetViewportPosition(it
, left
+ (w
->left
- left
), top
, width
- (w
->left
- left
), height
);
292 if (left
+ width
> w
->left
+ w
->width
) {
293 DoSetViewportPosition(it
, left
, top
, (w
->left
+ w
->width
- left
), height
);
294 DoSetViewportPosition(it
, left
+ (w
->left
+ w
->width
- left
), top
, width
- (w
->left
+ w
->width
- left
), height
);
299 DoSetViewportPosition(it
, left
, top
, width
, (w
->top
- top
));
300 DoSetViewportPosition(it
, left
, top
+ (w
->top
- top
), width
, height
- (w
->top
- top
));
304 if (top
+ height
> w
->top
+ w
->height
) {
305 DoSetViewportPosition(it
, left
, top
, width
, (w
->top
+ w
->height
- top
));
306 DoSetViewportPosition(it
, left
, top
+ (w
->top
+ w
->height
- top
), width
, height
- (w
->top
+ w
->height
- top
));
315 int xo
= _vp_move_offs
.x
;
316 int yo
= _vp_move_offs
.y
;
318 if (abs(xo
) >= width
|| abs(yo
) >= height
) {
320 RedrawScreenRect(left
, top
, left
+ width
, top
+ height
);
324 GfxScroll(left
, top
, width
, height
, xo
, yo
);
327 RedrawScreenRect(left
, top
, xo
+ left
, top
+ height
);
331 RedrawScreenRect(left
+ width
+ xo
, top
, left
+ width
, top
+ height
);
336 RedrawScreenRect(left
, top
, width
+ left
, top
+ yo
);
338 RedrawScreenRect(left
, top
+ height
+ yo
, width
+ left
, top
+ height
);
343 static void SetViewportPosition(Window
*w
, int x
, int y
)
345 Viewport
*vp
= w
->viewport
;
346 int old_left
= vp
->virtual_left
;
347 int old_top
= vp
->virtual_top
;
349 int left
, top
, width
, height
;
351 vp
->virtual_left
= x
;
354 /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
355 * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
357 old_left
= UnScaleByZoomLower(old_left
, vp
->zoom
);
358 old_top
= UnScaleByZoomLower(old_top
, vp
->zoom
);
359 x
= UnScaleByZoomLower(x
, vp
->zoom
);
360 y
= UnScaleByZoomLower(y
, vp
->zoom
);
365 if (old_top
== 0 && old_left
== 0) return;
367 _vp_move_offs
.x
= old_left
;
368 _vp_move_offs
.y
= old_top
;
380 i
= left
+ width
- _screen
.width
;
381 if (i
>= 0) width
-= i
;
389 i
= top
+ height
- _screen
.height
;
390 if (i
>= 0) height
-= i
;
393 Window::IteratorToFront
it(w
);
395 DoSetViewportPosition(it
, left
, top
, width
, height
);
401 * Is a xy position inside the viewport of the window?
402 * @param w Window to examine its viewport
403 * @param x X coordinate of the xy position
404 * @param y Y coordinate of the xy position
405 * @return Pointer to the viewport if the xy position is in the viewport of the window,
406 * otherwise \c nullptr is returned.
408 Viewport
*IsPtInWindowViewport(const Window
*w
, int x
, int y
)
410 Viewport
*vp
= w
->viewport
;
413 IsInsideMM(x
, vp
->left
, vp
->left
+ vp
->width
) &&
414 IsInsideMM(y
, vp
->top
, vp
->top
+ vp
->height
))
421 * Translate screen coordinate in a viewport to underlying tile coordinate.
423 * Returns exact point of the map that is visible in the given place
424 * of the viewport (3D perspective), height of tiles and foundations matter.
426 * @param vp Viewport that contains the (\a x, \a y) screen coordinate
427 * @param x Screen x coordinate, distance in pixels from the left edge of viewport frame
428 * @param y Screen y coordinate, distance in pixels from the top edge of viewport frame
429 * @param clamp_to_map Clamp the coordinate outside of the map to the closest, non-void tile within the map
430 * @return Tile coordinate or (-1, -1) if given x or y is not within viewport frame
432 Point
TranslateXYToTileCoord(const Viewport
*vp
, int x
, int y
, bool clamp_to_map
)
434 if (!IsInsideBS(x
, vp
->left
, vp
->width
) || !IsInsideBS(y
, vp
->top
, vp
->height
)) {
435 Point pt
= { -1, -1 };
439 return InverseRemapCoords2(
440 ScaleByZoom(x
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
441 ScaleByZoom(y
- vp
->top
, vp
->zoom
) + vp
->virtual_top
, clamp_to_map
);
444 /* When used for zooming, check area below current coordinates (x,y)
445 * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
446 * when you just want the tile, make x = zoom_x and y = zoom_y */
447 static Point
GetTileFromScreenXY(int x
, int y
, int zoom_x
, int zoom_y
)
453 if ( (w
= FindWindowFromPt(x
, y
)) != nullptr &&
454 (vp
= IsPtInWindowViewport(w
, x
, y
)) != nullptr)
455 return TranslateXYToTileCoord(vp
, zoom_x
, zoom_y
);
461 Point
GetTileBelowCursor()
463 return GetTileFromScreenXY(_cursor
.pos
.x
, _cursor
.pos
.y
, _cursor
.pos
.x
, _cursor
.pos
.y
);
467 Point
GetTileZoomCenterWindow(bool in
, Window
* w
)
470 Viewport
*vp
= w
->viewport
;
473 x
= ((_cursor
.pos
.x
- vp
->left
) >> 1) + (vp
->width
>> 2);
474 y
= ((_cursor
.pos
.y
- vp
->top
) >> 1) + (vp
->height
>> 2);
476 x
= vp
->width
- (_cursor
.pos
.x
- vp
->left
);
477 y
= vp
->height
- (_cursor
.pos
.y
- vp
->top
);
479 /* Get the tile below the cursor and center on the zoomed-out center */
480 return GetTileFromScreenXY(_cursor
.pos
.x
, _cursor
.pos
.y
, x
+ vp
->left
, y
+ vp
->top
);
484 * Update the status of the zoom-buttons according to the zoom-level
485 * of the viewport. This will update their status and invalidate accordingly
486 * @param w Window pointer to the window that has the zoom buttons
487 * @param vp pointer to the viewport whose zoom-level the buttons represent
488 * @param widget_zoom_in widget index for window with zoom-in button
489 * @param widget_zoom_out widget index for window with zoom-out button
491 void HandleZoomMessage(Window
*w
, const Viewport
*vp
, WidgetID widget_zoom_in
, WidgetID widget_zoom_out
)
493 w
->SetWidgetDisabledState(widget_zoom_in
, vp
->zoom
<= _settings_client
.gui
.zoom_min
);
494 w
->SetWidgetDirty(widget_zoom_in
);
496 w
->SetWidgetDisabledState(widget_zoom_out
, vp
->zoom
>= _settings_client
.gui
.zoom_max
);
497 w
->SetWidgetDirty(widget_zoom_out
);
501 * Schedules a tile sprite for drawing.
503 * @param image the image to draw.
504 * @param pal the provided palette.
505 * @param x position x (world coordinates) of the sprite.
506 * @param y position y (world coordinates) of the sprite.
507 * @param z position z (world coordinates) of the sprite.
508 * @param sub Only draw a part of the sprite.
509 * @param extra_offs_x Pixel X offset for the sprite position.
510 * @param extra_offs_y Pixel Y offset for the sprite position.
512 static void AddTileSpriteToDraw(SpriteID image
, PaletteID pal
, int32_t x
, int32_t y
, int z
, const SubSprite
*sub
= nullptr, int extra_offs_x
= 0, int extra_offs_y
= 0)
514 assert((image
& SPRITE_MASK
) < MAX_SPRITES
);
516 TileSpriteToDraw
&ts
= _vd
.tile_sprites_to_draw
.emplace_back();
520 Point pt
= RemapCoords(x
, y
, z
);
521 ts
.x
= pt
.x
+ extra_offs_x
;
522 ts
.y
= pt
.y
+ extra_offs_y
;
526 * Adds a child sprite to the active foundation.
528 * The pixel offset of the sprite relative to the ParentSprite is the sum of the offset passed to OffsetGroundSprite() and extra_offs_?.
530 * @param image the image to draw.
531 * @param pal the provided palette.
532 * @param sub Only draw a part of the sprite.
533 * @param foundation_part Foundation part.
534 * @param extra_offs_x Pixel X offset for the sprite position.
535 * @param extra_offs_y Pixel Y offset for the sprite position.
537 static void AddChildSpriteToFoundation(SpriteID image
, PaletteID pal
, const SubSprite
*sub
, FoundationPart foundation_part
, int extra_offs_x
, int extra_offs_y
)
539 assert(IsInsideMM(foundation_part
, 0, FOUNDATION_PART_END
));
540 assert(_vd
.foundation
[foundation_part
] != -1);
541 Point offs
= _vd
.foundation_offset
[foundation_part
];
543 /* Change the active ChildSprite list to the one of the foundation */
544 int *old_child
= _vd
.last_child
;
545 _vd
.last_child
= _vd
.last_foundation_child
[foundation_part
];
547 AddChildSpriteScreen(image
, pal
, offs
.x
+ extra_offs_x
, offs
.y
+ extra_offs_y
, false, sub
, false, false);
549 /* Switch back to last ChildSprite list */
550 _vd
.last_child
= old_child
;
554 * Draws a ground sprite at a specific world-coordinate relative to the current tile.
555 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
557 * @param image the image to draw.
558 * @param pal the provided palette.
559 * @param x position x (world coordinates) of the sprite relative to current tile.
560 * @param y position y (world coordinates) of the sprite relative to current tile.
561 * @param z position z (world coordinates) of the sprite relative to current tile.
562 * @param sub Only draw a part of the sprite.
563 * @param extra_offs_x Pixel X offset for the sprite position.
564 * @param extra_offs_y Pixel Y offset for the sprite position.
566 void DrawGroundSpriteAt(SpriteID image
, PaletteID pal
, int32_t x
, int32_t y
, int z
, const SubSprite
*sub
, int extra_offs_x
, int extra_offs_y
)
568 /* Switch to first foundation part, if no foundation was drawn */
569 if (_vd
.foundation_part
== FOUNDATION_PART_NONE
) _vd
.foundation_part
= FOUNDATION_PART_NORMAL
;
571 if (_vd
.foundation
[_vd
.foundation_part
] != -1) {
572 Point pt
= RemapCoords(x
, y
, z
);
573 AddChildSpriteToFoundation(image
, pal
, sub
, _vd
.foundation_part
, pt
.x
+ extra_offs_x
* ZOOM_LVL_BASE
, pt
.y
+ extra_offs_y
* ZOOM_LVL_BASE
);
575 AddTileSpriteToDraw(image
, pal
, _cur_ti
.x
+ x
, _cur_ti
.y
+ y
, _cur_ti
.z
+ z
, sub
, extra_offs_x
* ZOOM_LVL_BASE
, extra_offs_y
* ZOOM_LVL_BASE
);
580 * Draws a ground sprite for the current tile.
581 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
583 * @param image the image to draw.
584 * @param pal the provided palette.
585 * @param sub Only draw a part of the sprite.
586 * @param extra_offs_x Pixel X offset for the sprite position.
587 * @param extra_offs_y Pixel Y offset for the sprite position.
589 void DrawGroundSprite(SpriteID image
, PaletteID pal
, const SubSprite
*sub
, int extra_offs_x
, int extra_offs_y
)
591 DrawGroundSpriteAt(image
, pal
, 0, 0, 0, sub
, extra_offs_x
, extra_offs_y
);
595 * Called when a foundation has been drawn for the current tile.
596 * Successive ground sprites for the current tile will be drawn as child sprites of the "foundation"-ParentSprite, not as TileSprites.
598 * @param x sprite x-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
599 * @param y sprite y-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
601 void OffsetGroundSprite(int x
, int y
)
603 /* Switch to next foundation part */
604 switch (_vd
.foundation_part
) {
605 case FOUNDATION_PART_NONE
:
606 _vd
.foundation_part
= FOUNDATION_PART_NORMAL
;
608 case FOUNDATION_PART_NORMAL
:
609 _vd
.foundation_part
= FOUNDATION_PART_HALFTILE
;
611 default: NOT_REACHED();
614 /* _vd.last_child == nullptr if foundation sprite was clipped by the viewport bounds */
615 if (_vd
.last_child
!= nullptr) _vd
.foundation
[_vd
.foundation_part
] = (uint
)_vd
.parent_sprites_to_draw
.size() - 1;
617 _vd
.foundation_offset
[_vd
.foundation_part
].x
= x
* ZOOM_LVL_BASE
;
618 _vd
.foundation_offset
[_vd
.foundation_part
].y
= y
* ZOOM_LVL_BASE
;
619 _vd
.last_foundation_child
[_vd
.foundation_part
] = _vd
.last_child
;
623 * Adds a child sprite to a parent sprite.
624 * In contrast to "AddChildSpriteScreen()" the sprite position is in world coordinates
626 * @param image the image to draw.
627 * @param pal the provided palette.
628 * @param x position x of the sprite.
629 * @param y position y of the sprite.
630 * @param z position z of the sprite.
631 * @param sub Only draw a part of the sprite.
633 static void AddCombinedSprite(SpriteID image
, PaletteID pal
, int x
, int y
, int z
, const SubSprite
*sub
)
635 Point pt
= RemapCoords(x
, y
, z
);
636 const Sprite
*spr
= GetSprite(image
& SPRITE_MASK
, SpriteType::Normal
);
638 if (pt
.x
+ spr
->x_offs
>= _vd
.dpi
.left
+ _vd
.dpi
.width
||
639 pt
.x
+ spr
->x_offs
+ spr
->width
<= _vd
.dpi
.left
||
640 pt
.y
+ spr
->y_offs
>= _vd
.dpi
.top
+ _vd
.dpi
.height
||
641 pt
.y
+ spr
->y_offs
+ spr
->height
<= _vd
.dpi
.top
)
644 const ParentSpriteToDraw
&pstd
= _vd
.parent_sprites_to_draw
.back();
645 AddChildSpriteScreen(image
, pal
, pt
.x
- pstd
.left
, pt
.y
- pstd
.top
, false, sub
, false);
649 * Draw a (transparent) sprite at given coordinates with a given bounding box.
650 * The bounding box extends from (x + bb_offset_x, y + bb_offset_y, z + bb_offset_z) to (x + w - 1, y + h - 1, z + dz - 1), both corners included.
651 * Bounding boxes with bb_offset_x == w or bb_offset_y == h or bb_offset_z == dz are allowed and produce thin slices.
653 * @note Bounding boxes are normally specified with bb_offset_x = bb_offset_y = bb_offset_z = 0. The extent of the bounding box in negative direction is
654 * defined by the sprite offset in the grf file.
655 * However if modifying the sprite offsets is not suitable (e.g. when using existing graphics), the bounding box can be tuned by bb_offset.
657 * @pre w >= bb_offset_x, h >= bb_offset_y, dz >= bb_offset_z. Else w, h or dz are ignored.
659 * @param image the image to combine and draw,
660 * @param pal the provided palette,
661 * @param x position X (world) of the sprite,
662 * @param y position Y (world) of the sprite,
663 * @param w bounding box extent towards positive X (world),
664 * @param h bounding box extent towards positive Y (world),
665 * @param dz bounding box extent towards positive Z (world),
666 * @param z position Z (world) of the sprite,
667 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
668 * @param bb_offset_x bounding box extent towards negative X (world),
669 * @param bb_offset_y bounding box extent towards negative Y (world),
670 * @param bb_offset_z bounding box extent towards negative Z (world)
671 * @param sub Only draw a part of the sprite.
673 void AddSortableSpriteToDraw(SpriteID image
, PaletteID pal
, int x
, int y
, int w
, int h
, int dz
, int z
, bool transparent
, int bb_offset_x
, int bb_offset_y
, int bb_offset_z
, const SubSprite
*sub
)
675 int32_t left
, right
, top
, bottom
;
677 assert((image
& SPRITE_MASK
) < MAX_SPRITES
);
679 /* make the sprites transparent with the right palette */
681 SetBit(image
, PALETTE_MODIFIER_TRANSPARENT
);
682 pal
= PALETTE_TO_TRANSPARENT
;
685 if (_vd
.combine_sprites
== SPRITE_COMBINE_ACTIVE
) {
686 AddCombinedSprite(image
, pal
, x
, y
, z
, sub
);
690 _vd
.last_child
= nullptr;
692 Point pt
= RemapCoords(x
, y
, z
);
693 int tmp_left
, tmp_top
, tmp_x
= pt
.x
, tmp_y
= pt
.y
;
695 /* Compute screen extents of sprite */
696 if (image
== SPR_EMPTY_BOUNDING_BOX
) {
697 left
= tmp_left
= RemapCoords(x
+ w
, y
+ bb_offset_y
, z
+ bb_offset_z
).x
;
698 right
= RemapCoords(x
+ bb_offset_x
, y
+ h
, z
+ bb_offset_z
).x
+ 1;
699 top
= tmp_top
= RemapCoords(x
+ bb_offset_x
, y
+ bb_offset_y
, z
+ dz
).y
;
700 bottom
= RemapCoords(x
+ w
, y
+ h
, z
+ bb_offset_z
).y
+ 1;
702 const Sprite
*spr
= GetSprite(image
& SPRITE_MASK
, SpriteType::Normal
);
703 left
= tmp_left
= (pt
.x
+= spr
->x_offs
);
704 right
= (pt
.x
+ spr
->width
);
705 top
= tmp_top
= (pt
.y
+= spr
->y_offs
);
706 bottom
= (pt
.y
+ spr
->height
);
709 if (_draw_bounding_boxes
&& (image
!= SPR_EMPTY_BOUNDING_BOX
)) {
710 /* Compute maximal extents of sprite and its bounding box */
711 left
= std::min(left
, RemapCoords(x
+ w
, y
+ bb_offset_y
, z
+ bb_offset_z
).x
);
712 right
= std::max(right
, RemapCoords(x
+ bb_offset_x
, y
+ h
, z
+ bb_offset_z
).x
+ 1);
713 top
= std::min(top
, RemapCoords(x
+ bb_offset_x
, y
+ bb_offset_y
, z
+ dz
).y
);
714 bottom
= std::max(bottom
, RemapCoords(x
+ w
, y
+ h
, z
+ bb_offset_z
).y
+ 1);
717 /* Do not add the sprite to the viewport, if it is outside */
718 if (left
>= _vd
.dpi
.left
+ _vd
.dpi
.width
||
719 right
<= _vd
.dpi
.left
||
720 top
>= _vd
.dpi
.top
+ _vd
.dpi
.height
||
721 bottom
<= _vd
.dpi
.top
) {
725 ParentSpriteToDraw
&ps
= _vd
.parent_sprites_to_draw
.emplace_back();
735 ps
.xmin
= x
+ bb_offset_x
;
736 ps
.xmax
= x
+ std::max(bb_offset_x
, w
) - 1;
738 ps
.ymin
= y
+ bb_offset_y
;
739 ps
.ymax
= y
+ std::max(bb_offset_y
, h
) - 1;
741 ps
.zmin
= z
+ bb_offset_z
;
742 ps
.zmax
= z
+ std::max(bb_offset_z
, dz
) - 1;
746 _vd
.last_child
= &ps
.first_child
;
748 if (_vd
.combine_sprites
== SPRITE_COMBINE_PENDING
) _vd
.combine_sprites
= SPRITE_COMBINE_ACTIVE
;
752 * Starts a block of sprites, which are "combined" into a single bounding box.
754 * Subsequent calls to #AddSortableSpriteToDraw will be drawn into the same bounding box.
755 * That is: The first sprite that is not clipped by the viewport defines the bounding box, and
756 * the following sprites will be child sprites to that one.
759 * - The drawing order is definite. No other sprites will be sorted between those of the block.
760 * - You have to provide a valid bounding box for all sprites,
761 * as you won't know which one is the first non-clipped one.
762 * Preferable you use the same bounding box for all.
763 * - You cannot use #AddChildSpriteScreen inside the block, as its result will be indefinite.
765 * The block is terminated by #EndSpriteCombine.
767 * You cannot nest "combined" blocks.
769 void StartSpriteCombine()
771 assert(_vd
.combine_sprites
== SPRITE_COMBINE_NONE
);
772 _vd
.combine_sprites
= SPRITE_COMBINE_PENDING
;
776 * Terminates a block of sprites started by #StartSpriteCombine.
777 * Take a look there for details.
779 void EndSpriteCombine()
781 assert(_vd
.combine_sprites
!= SPRITE_COMBINE_NONE
);
782 _vd
.combine_sprites
= SPRITE_COMBINE_NONE
;
786 * Check if the parameter "check" is inside the interval between
787 * begin and end, including both begin and end.
788 * @note Whether \c begin or \c end is the biggest does not matter.
789 * This method will account for that.
790 * @param begin The begin of the interval.
791 * @param end The end of the interval.
792 * @param check The value to check.
794 static bool IsInRangeInclusive(int begin
, int end
, int check
)
796 if (begin
> end
) Swap(begin
, end
);
797 return begin
<= check
&& check
<= end
;
801 * Checks whether a point is inside the selected a diagonal rectangle given by _thd.size and _thd.pos
802 * @param x The x coordinate of the point to be checked.
803 * @param y The y coordinate of the point to be checked.
804 * @return True if the point is inside the rectangle, else false.
806 bool IsInsideRotatedRectangle(int x
, int y
)
808 int dist_a
= (_thd
.size
.x
+ _thd
.size
.y
); // Rotated coordinate system for selected rectangle.
809 int dist_b
= (_thd
.size
.x
- _thd
.size
.y
); // We don't have to divide by 2. It's all relative!
810 int a
= ((x
- _thd
.pos
.x
) + (y
- _thd
.pos
.y
)); // Rotated coordinate system for the point under scrutiny.
811 int b
= ((x
- _thd
.pos
.x
) - (y
- _thd
.pos
.y
));
813 /* Check if a and b are between 0 and dist_a or dist_b respectively. */
814 return IsInRangeInclusive(dist_a
, 0, a
) && IsInRangeInclusive(dist_b
, 0, b
);
818 * Add a child sprite to a parent sprite.
820 * @param image the image to draw.
821 * @param pal the provided palette.
822 * @param x sprite x-offset (screen coordinates) relative to parent sprite.
823 * @param y sprite y-offset (screen coordinates) relative to parent sprite.
824 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
825 * @param sub Only draw a part of the sprite.
826 * @param scale if true, scale offsets to base zoom level.
827 * @param relative if true, draw sprite relative to parent sprite offsets.
829 void AddChildSpriteScreen(SpriteID image
, PaletteID pal
, int x
, int y
, bool transparent
, const SubSprite
*sub
, bool scale
, bool relative
)
831 assert((image
& SPRITE_MASK
) < MAX_SPRITES
);
833 /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
834 if (_vd
.last_child
== nullptr) return;
836 /* make the sprites transparent with the right palette */
838 SetBit(image
, PALETTE_MODIFIER_TRANSPARENT
);
839 pal
= PALETTE_TO_TRANSPARENT
;
842 *_vd
.last_child
= (uint
)_vd
.child_screen_sprites_to_draw
.size();
844 ChildScreenSpriteToDraw
&cs
= _vd
.child_screen_sprites_to_draw
.emplace_back();
848 cs
.x
= scale
? x
* ZOOM_LVL_BASE
: x
;
849 cs
.y
= scale
? y
* ZOOM_LVL_BASE
: y
;
850 cs
.relative
= relative
;
853 /* Append the sprite to the active ChildSprite list.
854 * If the active ParentSprite is a foundation, update last_foundation_child as well.
855 * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
856 if (_vd
.last_foundation_child
[0] == _vd
.last_child
) _vd
.last_foundation_child
[0] = &cs
.next
;
857 if (_vd
.last_foundation_child
[1] == _vd
.last_child
) _vd
.last_foundation_child
[1] = &cs
.next
;
858 _vd
.last_child
= &cs
.next
;
861 static void AddStringToDraw(int x
, int y
, StringID string
, Colours colour
, uint16_t width
)
864 StringSpriteToDraw
&ss
= _vd
.string_sprites_to_draw
.emplace_back();
865 ss
.string
= GetString(string
);
866 ss
.string_id
= string
;
875 * Draws sprites between ground sprite and everything above.
877 * The sprite is either drawn as TileSprite or as ChildSprite of the active foundation.
879 * @param image the image to draw.
880 * @param pal the provided palette.
881 * @param ti TileInfo Tile that is being drawn
882 * @param z_offset Z offset relative to the groundsprite. Only used for the sprite position, not for sprite sorting.
883 * @param foundation_part Foundation part the sprite belongs to.
884 * @param extra_offs_x Pixel X offset for the sprite position.
885 * @param extra_offs_y Pixel Y offset for the sprite position.
887 static void DrawSelectionSprite(SpriteID image
, PaletteID pal
, const TileInfo
*ti
, int z_offset
, FoundationPart foundation_part
, int extra_offs_x
= 0, int extra_offs_y
= 0)
889 /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
890 if (_vd
.foundation
[foundation_part
] == -1) {
891 /* draw on real ground */
892 AddTileSpriteToDraw(image
, pal
, ti
->x
, ti
->y
, ti
->z
+ z_offset
, nullptr, extra_offs_x
, extra_offs_y
);
894 /* draw on top of foundation */
895 AddChildSpriteToFoundation(image
, pal
, nullptr, foundation_part
, extra_offs_x
, extra_offs_y
- z_offset
* ZOOM_LVL_BASE
);
900 * Draws a selection rectangle on a tile.
902 * @param ti TileInfo Tile that is being drawn
903 * @param pal Palette to apply.
905 static void DrawTileSelectionRect(const TileInfo
*ti
, PaletteID pal
)
907 if (!IsValidTile(ti
->tile
)) return;
910 if (IsHalftileSlope(ti
->tileh
)) {
911 Corner halftile_corner
= GetHalftileSlopeCorner(ti
->tileh
);
912 SpriteID sel2
= SPR_HALFTILE_SELECTION_FLAT
+ halftile_corner
;
913 DrawSelectionSprite(sel2
, pal
, ti
, 7 + TILE_HEIGHT
, FOUNDATION_PART_HALFTILE
);
915 Corner opposite_corner
= OppositeCorner(halftile_corner
);
916 if (IsSteepSlope(ti
->tileh
)) {
917 sel
= SPR_HALFTILE_SELECTION_DOWN
;
919 sel
= ((ti
->tileh
& SlopeWithOneCornerRaised(opposite_corner
)) != 0 ? SPR_HALFTILE_SELECTION_UP
: SPR_HALFTILE_SELECTION_FLAT
);
921 sel
+= opposite_corner
;
923 sel
= SPR_SELECT_TILE
+ SlopeToSpriteOffset(ti
->tileh
);
925 DrawSelectionSprite(sel
, pal
, ti
, 7, FOUNDATION_PART_NORMAL
);
928 static bool IsPartOfAutoLine(int px
, int py
)
930 px
-= _thd
.selstart
.x
;
931 py
-= _thd
.selstart
.y
;
933 if ((_thd
.drawstyle
& HT_DRAG_MASK
) != HT_LINE
) return false;
935 switch (_thd
.drawstyle
& HT_DIR_MASK
) {
936 case HT_DIR_X
: return py
== 0; // x direction
937 case HT_DIR_Y
: return px
== 0; // y direction
938 case HT_DIR_HU
: return px
== -py
|| px
== -py
- 16; // horizontal upper
939 case HT_DIR_HL
: return px
== -py
|| px
== -py
+ 16; // horizontal lower
940 case HT_DIR_VL
: return px
== py
|| px
== py
+ 16; // vertical left
941 case HT_DIR_VR
: return px
== py
|| px
== py
- 16; // vertical right
947 /* [direction][side] */
948 static const HighLightStyle _autorail_type
[6][2] = {
949 { HT_DIR_X
, HT_DIR_X
},
950 { HT_DIR_Y
, HT_DIR_Y
},
951 { HT_DIR_HU
, HT_DIR_HL
},
952 { HT_DIR_HL
, HT_DIR_HU
},
953 { HT_DIR_VL
, HT_DIR_VR
},
954 { HT_DIR_VR
, HT_DIR_VL
}
957 #include "table/autorail.h"
960 * Draws autorail highlights.
962 * @param *ti TileInfo Tile that is being drawn
963 * @param autorail_type Offset into _AutorailTilehSprite[][]
965 static void DrawAutorailSelection(const TileInfo
*ti
, uint autorail_type
)
971 FoundationPart foundation_part
= FOUNDATION_PART_NORMAL
;
972 Slope autorail_tileh
= RemoveHalftileSlope(ti
->tileh
);
973 if (IsHalftileSlope(ti
->tileh
)) {
974 static const uint _lower_rail
[4] = { 5U, 2U, 4U, 3U };
975 Corner halftile_corner
= GetHalftileSlopeCorner(ti
->tileh
);
976 if (autorail_type
!= _lower_rail
[halftile_corner
]) {
977 foundation_part
= FOUNDATION_PART_HALFTILE
;
978 /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
979 autorail_tileh
= SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner
));
983 offset
= _AutorailTilehSprite
[autorail_tileh
][autorail_type
];
985 image
= SPR_AUTORAIL_BASE
+ offset
;
988 image
= SPR_AUTORAIL_BASE
- offset
;
989 pal
= PALETTE_SEL_TILE_RED
;
992 DrawSelectionSprite(image
, _thd
.make_square_red
? PALETTE_SEL_TILE_RED
: pal
, ti
, 7, foundation_part
);
995 enum TileHighlightType
{
1002 const Station
*_viewport_highlight_station
; ///< Currently selected station for coverage area highlight
1003 const Waypoint
*_viewport_highlight_waypoint
; ///< Currently selected waypoint for coverage area highlight
1004 const Town
*_viewport_highlight_town
; ///< Currently selected town for coverage area highlight
1007 * Get tile highlight type of coverage area for a given tile.
1008 * @param t Tile that is being drawn
1009 * @return Tile highlight type to draw
1011 static TileHighlightType
GetTileHighlightType(TileIndex t
)
1013 if (_viewport_highlight_station
!= nullptr) {
1014 if (IsTileType(t
, MP_STATION
) && GetStationIndex(t
) == _viewport_highlight_station
->index
) return THT_WHITE
;
1015 if (_viewport_highlight_station
->TileIsInCatchment(t
)) return THT_BLUE
;
1017 if (_viewport_highlight_waypoint
!= nullptr) {
1018 if (IsTileType(t
, MP_STATION
) && GetStationIndex(t
) == _viewport_highlight_waypoint
->index
) return THT_BLUE
;
1021 if (_viewport_highlight_town
!= nullptr) {
1022 if (IsTileType(t
, MP_HOUSE
)) {
1023 if (GetTownIndex(t
) == _viewport_highlight_town
->index
) {
1024 TileHighlightType type
= THT_RED
;
1025 for (const Station
*st
: _viewport_highlight_town
->stations_near
) {
1026 if (st
->owner
!= _current_company
) continue;
1027 if (st
->TileIsInCatchment(t
)) return THT_BLUE
;
1031 } else if (IsTileType(t
, MP_STATION
)) {
1032 for (const Station
*st
: _viewport_highlight_town
->stations_near
) {
1033 if (st
->owner
!= _current_company
) continue;
1034 if (GetStationIndex(t
) == st
->index
) return THT_WHITE
;
1043 * Draw tile highlight for coverage area highlight.
1044 * @param *ti TileInfo Tile that is being drawn
1045 * @param tht Highlight type to draw.
1047 static void DrawTileHighlightType(const TileInfo
*ti
, TileHighlightType tht
)
1051 case THT_NONE
: break;
1052 case THT_WHITE
: DrawTileSelectionRect(ti
, PAL_NONE
); break;
1053 case THT_BLUE
: DrawTileSelectionRect(ti
, PALETTE_SEL_TILE_BLUE
); break;
1054 case THT_RED
: DrawTileSelectionRect(ti
, PALETTE_SEL_TILE_RED
); break;
1059 * Highlights tiles insede local authority of selected towns.
1060 * @param *ti TileInfo Tile that is being drawn
1062 static void HighlightTownLocalAuthorityTiles(const TileInfo
*ti
)
1064 /* Going through cases in order of computational time. */
1066 if (_town_local_authority_kdtree
.Count() == 0) return;
1068 /* Tile belongs to town regardless of distance from town. */
1069 if (GetTileType(ti
->tile
) == MP_HOUSE
) {
1070 if (!Town::GetByTile(ti
->tile
)->show_zone
) return;
1072 DrawTileSelectionRect(ti
, PALETTE_CRASH
);
1076 /* If the closest town in the highlighted list is far, we can stop searching. */
1077 TownID tid
= _town_local_authority_kdtree
.FindNearest(TileX(ti
->tile
), TileY(ti
->tile
));
1078 Town
*closest_highlighted_town
= Town::Get(tid
);
1080 if (DistanceManhattan(ti
->tile
, closest_highlighted_town
->xy
) >= _settings_game
.economy
.dist_local_authority
) return;
1082 /* Tile is inside of the local autrhority distance of a highlighted town,
1083 but it is possible that a non-highlighted town is even closer. */
1084 Town
*closest_town
= ClosestTownFromTile(ti
->tile
, _settings_game
.economy
.dist_local_authority
);
1086 if (closest_town
->show_zone
) {
1087 DrawTileSelectionRect(ti
, PALETTE_CRASH
);
1093 * Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
1094 * @param *ti TileInfo Tile that is being drawn
1096 static void DrawTileSelection(const TileInfo
*ti
)
1098 /* Highlight tiles insede local authority of selected towns. */
1099 HighlightTownLocalAuthorityTiles(ti
);
1101 /* Draw a red error square? */
1102 bool is_redsq
= _thd
.redsq
== ti
->tile
;
1103 if (is_redsq
) DrawTileSelectionRect(ti
, PALETTE_TILE_RED_PULSATING
);
1105 TileHighlightType tht
= GetTileHighlightType(ti
->tile
);
1106 DrawTileHighlightType(ti
, tht
);
1108 /* No tile selection active? */
1109 if ((_thd
.drawstyle
& HT_DRAG_MASK
) == HT_NONE
) return;
1111 if (_thd
.diagonal
) { // We're drawing a 45 degrees rotated (diagonal) rectangle
1112 if (IsInsideRotatedRectangle((int)ti
->x
, (int)ti
->y
)) goto draw_inner
;
1116 /* Inside the inner area? */
1117 if (IsInsideBS(ti
->x
, _thd
.pos
.x
, _thd
.size
.x
) &&
1118 IsInsideBS(ti
->y
, _thd
.pos
.y
, _thd
.size
.y
)) {
1120 if (_thd
.drawstyle
& HT_RECT
) {
1121 if (!is_redsq
) DrawTileSelectionRect(ti
, _thd
.make_square_red
? PALETTE_SEL_TILE_RED
: PAL_NONE
);
1122 } else if (_thd
.drawstyle
& HT_POINT
) {
1123 /* Figure out the Z coordinate for the single dot. */
1125 FoundationPart foundation_part
= FOUNDATION_PART_NORMAL
;
1126 if (ti
->tileh
& SLOPE_N
) {
1128 if (RemoveHalftileSlope(ti
->tileh
) == SLOPE_STEEP_N
) z
+= TILE_HEIGHT
;
1130 if (IsHalftileSlope(ti
->tileh
)) {
1131 Corner halftile_corner
= GetHalftileSlopeCorner(ti
->tileh
);
1132 if ((halftile_corner
== CORNER_W
) || (halftile_corner
== CORNER_E
)) z
+= TILE_HEIGHT
;
1133 if (halftile_corner
!= CORNER_S
) {
1134 foundation_part
= FOUNDATION_PART_HALFTILE
;
1135 if (IsSteepSlope(ti
->tileh
)) z
-= TILE_HEIGHT
;
1138 DrawSelectionSprite(SPR_DOT
, PAL_NONE
, ti
, z
, foundation_part
);
1139 } else if (_thd
.drawstyle
& HT_RAIL
) {
1140 /* autorail highlight piece under cursor */
1141 HighLightStyle type
= _thd
.drawstyle
& HT_DIR_MASK
;
1142 assert(type
< HT_DIR_END
);
1143 DrawAutorailSelection(ti
, _autorail_type
[type
][0]);
1144 } else if (IsPartOfAutoLine(ti
->x
, ti
->y
)) {
1145 /* autorail highlighting long line */
1146 HighLightStyle dir
= _thd
.drawstyle
& HT_DIR_MASK
;
1149 if (dir
== HT_DIR_X
|| dir
== HT_DIR_Y
) {
1152 TileIndex start
= TileVirtXY(_thd
.selstart
.x
, _thd
.selstart
.y
);
1153 side
= Delta(Delta(TileX(start
), TileX(ti
->tile
)), Delta(TileY(start
), TileY(ti
->tile
)));
1156 DrawAutorailSelection(ti
, _autorail_type
[dir
][side
]);
1161 /* Check if it's inside the outer area? */
1162 if (!is_redsq
&& (tht
== THT_NONE
|| tht
== THT_RED
) && _thd
.outersize
.x
> 0 &&
1163 IsInsideBS(ti
->x
, _thd
.pos
.x
+ _thd
.offs
.x
, _thd
.size
.x
+ _thd
.outersize
.x
) &&
1164 IsInsideBS(ti
->y
, _thd
.pos
.y
+ _thd
.offs
.y
, _thd
.size
.y
+ _thd
.outersize
.y
)) {
1165 /* Draw a blue rect. */
1166 DrawTileSelectionRect(ti
, PALETTE_SEL_TILE_BLUE
);
1172 * Returns the y coordinate in the viewport coordinate system where the given
1174 * @param tile Any tile.
1175 * @return The viewport y coordinate where the tile is painted.
1177 static int GetViewportY(Point tile
)
1179 /* Each increment in X or Y direction moves down by half a tile, i.e. TILE_PIXELS / 2. */
1180 return (tile
.y
* (int)(TILE_PIXELS
/ 2) + tile
.x
* (int)(TILE_PIXELS
/ 2) - TilePixelHeightOutsideMap(tile
.x
, tile
.y
)) << ZOOM_LVL_SHIFT
;
1184 * Add the landscape to the viewport, i.e. all ground tiles and buildings.
1186 static void ViewportAddLandscape()
1188 assert(_vd
.dpi
.top
<= _vd
.dpi
.top
+ _vd
.dpi
.height
);
1189 assert(_vd
.dpi
.left
<= _vd
.dpi
.left
+ _vd
.dpi
.width
);
1191 Point upper_left
= InverseRemapCoords(_vd
.dpi
.left
, _vd
.dpi
.top
);
1192 Point upper_right
= InverseRemapCoords(_vd
.dpi
.left
+ _vd
.dpi
.width
, _vd
.dpi
.top
);
1194 /* Transformations between tile coordinates and viewport rows/columns: See vp_column_row
1197 * x = (row - column) / 2
1198 * y = (row + column) / 2
1199 * Note: (row, columns) pairs are only valid, if they are both even or both odd.
1202 /* Columns overlap with neighbouring columns by a half tile.
1203 * - Left column is column of upper_left (rounded down) and one column to the left.
1204 * - Right column is column of upper_right (rounded up) and one column to the right.
1205 * Note: Integer-division does not round down for negative numbers, so ensure rounding with another increment/decrement.
1207 int left_column
= (upper_left
.y
- upper_left
.x
) / (int)TILE_SIZE
- 2;
1208 int right_column
= (upper_right
.y
- upper_right
.x
) / (int)TILE_SIZE
+ 2;
1210 int potential_bridge_height
= ZOOM_LVL_BASE
* TILE_HEIGHT
* _settings_game
.construction
.max_bridge_height
;
1212 /* Rows overlap with neighbouring rows by a half tile.
1213 * The first row that could possibly be visible is the row above upper_left (if it is at height 0).
1214 * Due to integer-division not rounding down for negative numbers, we need another decrement.
1216 int row
= (upper_left
.x
+ upper_left
.y
) / (int)TILE_SIZE
- 2;
1217 bool last_row
= false;
1218 for (; !last_row
; row
++) {
1220 for (int column
= left_column
; column
<= right_column
; column
++) {
1221 /* Valid row/column? */
1222 if ((row
+ column
) % 2 != 0) continue;
1225 tilecoord
.x
= (row
- column
) / 2;
1226 tilecoord
.y
= (row
+ column
) / 2;
1227 assert(column
== tilecoord
.y
- tilecoord
.x
);
1228 assert(row
== tilecoord
.y
+ tilecoord
.x
);
1231 _cur_ti
.x
= tilecoord
.x
* TILE_SIZE
;
1232 _cur_ti
.y
= tilecoord
.y
* TILE_SIZE
;
1234 if (IsInsideBS(tilecoord
.x
, 0, Map::SizeX()) && IsInsideBS(tilecoord
.y
, 0, Map::SizeY())) {
1235 /* This includes the south border at Map::MaxX / Map::MaxY. When terraforming we still draw tile selections there. */
1236 _cur_ti
.tile
= TileXY(tilecoord
.x
, tilecoord
.y
);
1237 tile_type
= GetTileType(_cur_ti
.tile
);
1239 _cur_ti
.tile
= INVALID_TILE
;
1240 tile_type
= MP_VOID
;
1243 if (tile_type
!= MP_VOID
) {
1244 /* We are inside the map => paint landscape. */
1245 _cur_ti
.tileh
= GetTilePixelSlope(_cur_ti
.tile
, &_cur_ti
.z
);
1247 /* We are outside the map => paint black. */
1248 _cur_ti
.tileh
= GetTilePixelSlopeOutsideMap(tilecoord
.x
, tilecoord
.y
, &_cur_ti
.z
);
1251 int viewport_y
= GetViewportY(tilecoord
);
1253 if (viewport_y
+ MAX_TILE_EXTENT_BOTTOM
< _vd
.dpi
.top
) {
1254 /* The tile in this column is not visible yet.
1255 * Tiles in other columns may be visible, but we need more rows in any case. */
1260 int min_visible_height
= viewport_y
- (_vd
.dpi
.top
+ _vd
.dpi
.height
);
1261 bool tile_visible
= min_visible_height
<= 0;
1263 if (tile_type
!= MP_VOID
) {
1264 /* Is tile with buildings visible? */
1265 if (min_visible_height
< MAX_TILE_EXTENT_TOP
) tile_visible
= true;
1267 if (IsBridgeAbove(_cur_ti
.tile
)) {
1268 /* Is the bridge visible? */
1269 TileIndex bridge_tile
= GetNorthernBridgeEnd(_cur_ti
.tile
);
1270 int bridge_height
= ZOOM_LVL_BASE
* (GetBridgePixelHeight(bridge_tile
) - TilePixelHeight(_cur_ti
.tile
));
1271 if (min_visible_height
< bridge_height
+ MAX_TILE_EXTENT_TOP
) tile_visible
= true;
1274 /* Would a higher bridge on a more southern tile be visible?
1275 * If yes, we need to loop over more rows to possibly find one. */
1276 if (min_visible_height
< potential_bridge_height
+ MAX_TILE_EXTENT_TOP
) last_row
= false;
1278 /* Outside of map. If we are on the north border of the map, there may still be a bridge visible,
1279 * so we need to loop over more rows to possibly find one. */
1280 if ((tilecoord
.x
<= 0 || tilecoord
.y
<= 0) && min_visible_height
< potential_bridge_height
+ MAX_TILE_EXTENT_TOP
) last_row
= false;
1285 _vd
.foundation_part
= FOUNDATION_PART_NONE
;
1286 _vd
.foundation
[0] = -1;
1287 _vd
.foundation
[1] = -1;
1288 _vd
.last_foundation_child
[0] = nullptr;
1289 _vd
.last_foundation_child
[1] = nullptr;
1291 _tile_type_procs
[tile_type
]->draw_tile_proc(&_cur_ti
);
1292 if (_cur_ti
.tile
!= INVALID_TILE
) DrawTileSelection(&_cur_ti
);
1299 * Add a string to draw in the viewport
1300 * @param dpi current viewport area
1301 * @param small_from Zoomlevel from when the small font should be used
1302 * @param sign sign position and dimension
1303 * @param string_normal String for normal and 2x zoom level
1304 * @param string_small String for 4x and 8x zoom level
1305 * @param string_small_shadow Shadow string for 4x and 8x zoom level; or #STR_NULL if no shadow
1306 * @param colour colour of the sign background; or INVALID_COLOUR if transparent
1308 void ViewportAddString(const DrawPixelInfo
*dpi
, ZoomLevel small_from
, const ViewportSign
*sign
, StringID string_normal
, StringID string_small
, StringID string_small_shadow
, Colours colour
)
1310 bool small
= dpi
->zoom
>= small_from
;
1312 int left
= dpi
->left
;
1314 int right
= left
+ dpi
->width
;
1315 int bottom
= top
+ dpi
->height
;
1317 int sign_height
= ScaleByZoom(WidgetDimensions::scaled
.fullbevel
.top
+ GetCharacterHeight(FS_NORMAL
) + WidgetDimensions::scaled
.fullbevel
.bottom
, dpi
->zoom
);
1318 int sign_half_width
= ScaleByZoom((small
? sign
->width_small
: sign
->width_normal
) / 2, dpi
->zoom
);
1320 if (bottom
< sign
->top
||
1321 top
> sign
->top
+ sign_height
||
1322 right
< sign
->center
- sign_half_width
||
1323 left
> sign
->center
+ sign_half_width
) {
1328 AddStringToDraw(sign
->center
- sign_half_width
, sign
->top
, string_normal
, colour
, sign
->width_normal
);
1330 int shadow_offset
= 0;
1331 if (string_small_shadow
!= STR_NULL
) {
1333 AddStringToDraw(sign
->center
- sign_half_width
+ shadow_offset
, sign
->top
, string_small_shadow
, INVALID_COLOUR
, sign
->width_small
| 0x8000);
1335 AddStringToDraw(sign
->center
- sign_half_width
, sign
->top
- shadow_offset
, string_small
, colour
, sign
->width_small
| 0x8000);
1339 static Rect
ExpandRectWithViewportSignMargins(Rect r
, ZoomLevel zoom
)
1341 /* Pessimistically always use normal font, but also assume small font is never larger in either dimension */
1342 const int fh
= GetCharacterHeight(FS_NORMAL
);
1343 const int max_tw
= _viewport_sign_maxwidth
/ 2 + 1;
1344 const int expand_y
= ScaleByZoom(WidgetDimensions::scaled
.fullbevel
.top
+ fh
+ WidgetDimensions::scaled
.fullbevel
.bottom
, zoom
);
1345 const int expand_x
= ScaleByZoom(WidgetDimensions::scaled
.fullbevel
.left
+ max_tw
+ WidgetDimensions::scaled
.fullbevel
.right
, zoom
);
1348 r
.right
+= expand_x
;
1350 r
.bottom
+= expand_y
;
1355 static void ViewportAddKdtreeSigns(DrawPixelInfo
*dpi
)
1357 Rect search_rect
{ dpi
->left
, dpi
->top
, dpi
->left
+ dpi
->width
, dpi
->top
+ dpi
->height
};
1358 search_rect
= ExpandRectWithViewportSignMargins(search_rect
, dpi
->zoom
);
1360 bool show_stations
= HasBit(_display_opt
, DO_SHOW_STATION_NAMES
) && _game_mode
!= GM_MENU
;
1361 bool show_waypoints
= HasBit(_display_opt
, DO_SHOW_WAYPOINT_NAMES
) && _game_mode
!= GM_MENU
;
1362 bool show_towns
= HasBit(_display_opt
, DO_SHOW_TOWN_NAMES
) && _game_mode
!= GM_MENU
;
1363 bool show_signs
= HasBit(_display_opt
, DO_SHOW_SIGNS
) && !IsInvisibilitySet(TO_SIGNS
);
1364 bool show_competitors
= HasBit(_display_opt
, DO_SHOW_COMPETITOR_SIGNS
);
1366 /* Collect all the items first and draw afterwards, to ensure layering */
1367 std::vector
<const BaseStation
*> stations
;
1368 std::vector
<const Town
*> towns
;
1369 std::vector
<const Sign
*> signs
;
1371 _viewport_sign_kdtree
.FindContained(search_rect
.left
, search_rect
.top
, search_rect
.right
, search_rect
.bottom
, [&](const ViewportSignKdtreeItem
& item
) {
1372 switch (item
.type
) {
1373 case ViewportSignKdtreeItem::VKI_STATION
: {
1374 if (!show_stations
) break;
1375 const BaseStation
*st
= BaseStation::Get(item
.id
.station
);
1377 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1378 if (!show_competitors
&& _local_company
!= st
->owner
&& st
->owner
!= OWNER_NONE
) break;
1380 stations
.push_back(st
);
1384 case ViewportSignKdtreeItem::VKI_WAYPOINT
: {
1385 if (!show_waypoints
) break;
1386 const BaseStation
*st
= BaseStation::Get(item
.id
.station
);
1388 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1389 if (!show_competitors
&& _local_company
!= st
->owner
&& st
->owner
!= OWNER_NONE
) break;
1391 stations
.push_back(st
);
1395 case ViewportSignKdtreeItem::VKI_TOWN
:
1396 if (!show_towns
) break;
1397 towns
.push_back(Town::Get(item
.id
.town
));
1400 case ViewportSignKdtreeItem::VKI_SIGN
: {
1401 if (!show_signs
) break;
1402 const Sign
*si
= Sign::Get(item
.id
.sign
);
1404 /* Don't draw if sign is owned by another company and competitor signs should be hidden.
1405 * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
1406 * companies can leave OWNER_NONE signs after them. */
1407 if (!show_competitors
&& _local_company
!= si
->owner
&& si
->owner
!= OWNER_DEITY
) break;
1409 signs
.push_back(si
);
1418 /* Layering order (bottom to top): Town names, signs, stations */
1420 for (const auto *t
: towns
) {
1421 SetDParam(0, t
->index
);
1422 SetDParam(1, t
->cache
.population
);
1423 ViewportAddString(dpi
, ZOOM_LVL_OUT_16X
, &t
->cache
.sign
,
1424 _settings_client
.gui
.population_in_label
? STR_VIEWPORT_TOWN_POP
: STR_VIEWPORT_TOWN
,
1425 STR_VIEWPORT_TOWN_TINY_WHITE
, STR_VIEWPORT_TOWN_TINY_BLACK
);
1428 /* Do not draw signs nor station names if they are set invisible */
1429 if (IsInvisibilitySet(TO_SIGNS
)) return;
1431 for (const auto *si
: signs
) {
1432 SetDParam(0, si
->index
);
1433 ViewportAddString(dpi
, ZOOM_LVL_OUT_16X
, &si
->sign
,
1435 (IsTransparencySet(TO_SIGNS
) || si
->owner
== OWNER_DEITY
) ? STR_VIEWPORT_SIGN_SMALL_WHITE
: STR_VIEWPORT_SIGN_SMALL_BLACK
, STR_NULL
,
1436 (si
->owner
== OWNER_NONE
) ? COLOUR_GREY
: (si
->owner
== OWNER_DEITY
? INVALID_COLOUR
: _company_colours
[si
->owner
]));
1439 for (const auto *st
: stations
) {
1440 SetDParam(0, st
->index
);
1441 SetDParam(1, st
->facilities
);
1442 if (Station::IsExpected(st
)) {
1444 ViewportAddString(dpi
, ZOOM_LVL_OUT_16X
, &st
->sign
,
1445 STR_VIEWPORT_STATION
, STR_VIEWPORT_STATION_TINY
, STR_NULL
,
1446 (st
->owner
== OWNER_NONE
|| !st
->IsInUse()) ? COLOUR_GREY
: _company_colours
[st
->owner
]);
1449 ViewportAddString(dpi
, ZOOM_LVL_OUT_16X
, &st
->sign
,
1450 STR_VIEWPORT_WAYPOINT
, STR_VIEWPORT_WAYPOINT_TINY
, STR_NULL
,
1451 (st
->owner
== OWNER_NONE
|| !st
->IsInUse()) ? COLOUR_GREY
: _company_colours
[st
->owner
]);
1458 * Update the position of the viewport sign.
1459 * @param center the (preferred) center of the viewport sign
1460 * @param top the new top of the sign
1461 * @param str the string to show in the sign
1462 * @param str_small the string to show when zoomed out. STR_NULL means same as \a str
1464 void ViewportSign::UpdatePosition(int center
, int top
, StringID str
, StringID str_small
)
1466 if (this->width_normal
!= 0) this->MarkDirty();
1470 std::string name
= GetString(str
);
1471 this->width_normal
= WidgetDimensions::scaled
.fullbevel
.left
+ Align(GetStringBoundingBox(name
).width
, 2) + WidgetDimensions::scaled
.fullbevel
.right
;
1472 this->center
= center
;
1474 /* zoomed out version */
1475 if (str_small
!= STR_NULL
) {
1476 name
= GetString(str_small
);
1478 this->width_small
= WidgetDimensions::scaled
.fullbevel
.left
+ Align(GetStringBoundingBox(name
, FS_SMALL
).width
, 2) + WidgetDimensions::scaled
.fullbevel
.right
;
1484 * Mark the sign dirty in all viewports.
1485 * @param maxzoom Maximum %ZoomLevel at which the text is visible.
1489 void ViewportSign::MarkDirty(ZoomLevel maxzoom
) const
1491 Rect zoomlevels
[ZOOM_LVL_END
];
1493 for (ZoomLevel zoom
= ZOOM_LVL_BEGIN
; zoom
!= ZOOM_LVL_END
; zoom
++) {
1494 /* FIXME: This doesn't switch to width_small when appropriate. */
1495 zoomlevels
[zoom
].left
= this->center
- ScaleByZoom(this->width_normal
/ 2 + 1, zoom
);
1496 zoomlevels
[zoom
].top
= this->top
- ScaleByZoom(1, zoom
);
1497 zoomlevels
[zoom
].right
= this->center
+ ScaleByZoom(this->width_normal
/ 2 + 1, zoom
);
1498 zoomlevels
[zoom
].bottom
= this->top
+ ScaleByZoom(WidgetDimensions::scaled
.fullbevel
.top
+ GetCharacterHeight(FS_NORMAL
) + WidgetDimensions::scaled
.fullbevel
.bottom
+ 1, zoom
);
1501 for (const Window
*w
: Window::Iterate()) {
1502 Viewport
*vp
= w
->viewport
;
1503 if (vp
!= nullptr && vp
->zoom
<= maxzoom
) {
1504 assert(vp
->width
!= 0);
1505 Rect
&zl
= zoomlevels
[vp
->zoom
];
1506 MarkViewportDirty(vp
, zl
.left
, zl
.top
, zl
.right
, zl
.bottom
);
1511 static void ViewportDrawTileSprites(const TileSpriteToDrawVector
*tstdv
)
1513 for (const TileSpriteToDraw
&ts
: *tstdv
) {
1514 DrawSpriteViewport(ts
.image
, ts
.pal
, ts
.x
, ts
.y
, ts
.sub
);
1518 /** This fallback sprite checker always exists. */
1519 static bool ViewportSortParentSpritesChecker()
1524 /** Sort parent sprites pointer array replicating the way original sorter did it. */
1525 static void ViewportSortParentSprites(ParentSpriteToSortVector
*psdv
)
1527 if (psdv
->size() < 2) return;
1529 /* We rely on sprites being, for the most part, already ordered.
1530 * So we don't need to move many of them and can keep track of their
1531 * order efficiently by using stack. We always move sprites to the front
1532 * of the current position, i.e. to the top of the stack.
1533 * Also use special constants to indicate sorting state without
1534 * adding extra fields to ParentSpriteToDraw structure.
1536 const uint32_t ORDER_COMPARED
= UINT32_MAX
; // Sprite was compared but we still need to compare the ones preceding it
1537 const uint32_t ORDER_RETURNED
= UINT32_MAX
- 1; // Makr sorted sprite in case there are other occurrences of it in the stack
1538 std::stack
<ParentSpriteToDraw
*> sprite_order
;
1539 uint32_t next_order
= 0;
1541 std::forward_list
<std::pair
<int64_t, ParentSpriteToDraw
*>> sprite_list
; // We store sprites in a list sorted by xmin+ymin
1543 /* Initialize sprite list and order. */
1544 for (auto p
= psdv
->rbegin(); p
!= psdv
->rend(); p
++) {
1545 sprite_list
.push_front(std::make_pair((*p
)->xmin
+ (*p
)->ymin
, *p
));
1546 sprite_order
.push(*p
);
1547 (*p
)->order
= next_order
++;
1552 std::vector
<ParentSpriteToDraw
*> preceding
; // Temporarily stores sprites that precede current and their position in the list
1553 auto preceding_prev
= sprite_list
.begin(); // Store iterator in case we need to delete a single preciding sprite
1554 auto out
= psdv
->begin(); // Iterator to output sorted sprites
1556 while (!sprite_order
.empty()) {
1558 auto s
= sprite_order
.top();
1561 /* Sprite is already sorted, ignore it. */
1562 if (s
->order
== ORDER_RETURNED
) continue;
1564 /* Sprite was already compared, just need to output it. */
1565 if (s
->order
== ORDER_COMPARED
) {
1567 s
->order
= ORDER_RETURNED
;
1573 /* We only need sprites with xmin <= s->xmax && ymin <= s->ymax && zmin <= s->zmax
1574 * So by iterating sprites with xmin + ymin <= s->xmax + s->ymax
1575 * we get all we need and some more that we filter out later.
1576 * We don't include zmin into the sum as there are usually more neighbors on x and y than z
1577 * so including it will actually increase the amount of false positives.
1578 * Also min coordinates can be > max so using max(xmin, xmax) + max(ymin, ymax)
1579 * to ensure that we iterate the current sprite as we need to remove it from the list.
1581 auto ssum
= std::max(s
->xmax
, s
->xmin
) + std::max(s
->ymax
, s
->ymin
);
1582 auto prev
= sprite_list
.before_begin();
1583 auto x
= sprite_list
.begin();
1584 while (x
!= sprite_list
.end() && ((*x
).first
<= ssum
)) {
1585 auto p
= (*x
).second
;
1587 /* We found the current sprite, remove it and move on. */
1588 x
= sprite_list
.erase_after(prev
);
1595 if (s
->xmax
< p
->xmin
|| s
->ymax
< p
->ymin
|| s
->zmax
< p
->zmin
) continue;
1596 if (s
->xmin
<= p
->xmax
&& // overlap in X?
1597 s
->ymin
<= p
->ymax
&& // overlap in Y?
1598 s
->zmin
<= p
->zmax
) { // overlap in Z?
1599 if (s
->xmin
+ s
->xmax
+ s
->ymin
+ s
->ymax
+ s
->zmin
+ s
->zmax
<=
1600 p
->xmin
+ p
->xmax
+ p
->ymin
+ p
->ymax
+ p
->zmin
+ p
->zmax
) {
1604 preceding
.push_back(p
);
1605 preceding_prev
= p_prev
;
1608 if (preceding
.empty()) {
1609 /* No preceding sprites, add current one to the output */
1611 s
->order
= ORDER_RETURNED
;
1615 /* Optimization for the case when we only have 1 sprite to move. */
1616 if (preceding
.size() == 1) {
1617 auto p
= preceding
[0];
1618 /* We can only output the preceding sprite if there can't be any other sprites preceding it. */
1619 if (p
->xmax
<= s
->xmax
&& p
->ymax
<= s
->ymax
&& p
->zmax
<= s
->zmax
) {
1620 p
->order
= ORDER_RETURNED
;
1621 s
->order
= ORDER_RETURNED
;
1622 sprite_list
.erase_after(preceding_prev
);
1629 /* Sort all preceding sprites by order and assign new orders in reverse (as original sorter did). */
1630 std::sort(preceding
.begin(), preceding
.end(), [](const ParentSpriteToDraw
*a
, const ParentSpriteToDraw
*b
) {
1631 return a
->order
> b
->order
;
1634 s
->order
= ORDER_COMPARED
;
1635 sprite_order
.push(s
); // Still need to output so push it back for now
1637 for (auto p
: preceding
) {
1638 p
->order
= next_order
++;
1639 sprite_order
.push(p
);
1645 static void ViewportDrawParentSprites(const ParentSpriteToSortVector
*psd
, const ChildScreenSpriteToDrawVector
*csstdv
)
1647 for (const ParentSpriteToDraw
*ps
: *psd
) {
1648 if (ps
->image
!= SPR_EMPTY_BOUNDING_BOX
) DrawSpriteViewport(ps
->image
, ps
->pal
, ps
->x
, ps
->y
, ps
->sub
);
1650 int child_idx
= ps
->first_child
;
1651 while (child_idx
>= 0) {
1652 const ChildScreenSpriteToDraw
*cs
= csstdv
->data() + child_idx
;
1653 child_idx
= cs
->next
;
1655 DrawSpriteViewport(cs
->image
, cs
->pal
, ps
->left
+ cs
->x
, ps
->top
+ cs
->y
, cs
->sub
);
1657 DrawSpriteViewport(cs
->image
, cs
->pal
, ps
->x
+ cs
->x
, ps
->y
+ cs
->y
, cs
->sub
);
1664 * Draws the bounding boxes of all ParentSprites
1665 * @param psd Array of ParentSprites
1667 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector
*psd
)
1669 for (const ParentSpriteToDraw
*ps
: *psd
) {
1670 Point pt1
= RemapCoords(ps
->xmax
+ 1, ps
->ymax
+ 1, ps
->zmax
+ 1); // top front corner
1671 Point pt2
= RemapCoords(ps
->xmin
, ps
->ymax
+ 1, ps
->zmax
+ 1); // top left corner
1672 Point pt3
= RemapCoords(ps
->xmax
+ 1, ps
->ymin
, ps
->zmax
+ 1); // top right corner
1673 Point pt4
= RemapCoords(ps
->xmax
+ 1, ps
->ymax
+ 1, ps
->zmin
); // bottom front corner
1675 DrawBox( pt1
.x
, pt1
.y
,
1676 pt2
.x
- pt1
.x
, pt2
.y
- pt1
.y
,
1677 pt3
.x
- pt1
.x
, pt3
.y
- pt1
.y
,
1678 pt4
.x
- pt1
.x
, pt4
.y
- pt1
.y
);
1683 * Draw/colour the blocks that have been redrawn.
1685 static void ViewportDrawDirtyBlocks()
1687 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
1688 const DrawPixelInfo
*dpi
= _cur_dpi
;
1690 int right
= UnScaleByZoom(dpi
->width
, dpi
->zoom
);
1691 int bottom
= UnScaleByZoom(dpi
->height
, dpi
->zoom
);
1693 int colour
= _string_colourmap
[_dirty_block_colour
& 0xF];
1697 byte bo
= UnScaleByZoom(dpi
->left
+ dpi
->top
, dpi
->zoom
) & 1;
1699 for (int i
= (bo
^= 1); i
< right
; i
+= 2) blitter
->SetPixel(dst
, i
, 0, (uint8_t)colour
);
1700 dst
= blitter
->MoveTo(dst
, 0, 1);
1701 } while (--bottom
> 0);
1704 static void ViewportDrawStrings(ZoomLevel zoom
, const StringSpriteToDrawVector
*sstdv
)
1706 for (const StringSpriteToDraw
&ss
: *sstdv
) {
1707 TextColour colour
= TC_BLACK
;
1708 bool small
= HasBit(ss
.width
, 15);
1709 int w
= GB(ss
.width
, 0, 15);
1710 int x
= UnScaleByZoom(ss
.x
, zoom
);
1711 int y
= UnScaleByZoom(ss
.y
, zoom
);
1712 int h
= WidgetDimensions::scaled
.fullbevel
.top
+ (small
? GetCharacterHeight(FS_SMALL
) : GetCharacterHeight(FS_NORMAL
)) + WidgetDimensions::scaled
.fullbevel
.bottom
;
1714 if (ss
.colour
!= INVALID_COLOUR
) {
1715 if (IsTransparencySet(TO_SIGNS
) && ss
.string_id
!= STR_WHITE_SIGN
) {
1716 /* Don't draw the rectangle.
1717 * Real colours need the TC_IS_PALETTE_COLOUR flag.
1718 * Otherwise colours from _string_colourmap are assumed. */
1719 colour
= (TextColour
)_colour_gradient
[ss
.colour
][6] | TC_IS_PALETTE_COLOUR
;
1721 /* Draw the rectangle if 'transparent station signs' is off,
1722 * or if we are drawing a general text sign (STR_WHITE_SIGN). */
1724 x
, y
, x
+ w
- 1, y
+ h
- 1, ss
.colour
,
1725 IsTransparencySet(TO_SIGNS
) ? FR_TRANSPARENT
: FR_NONE
1730 DrawString(x
+ WidgetDimensions::scaled
.fullbevel
.left
, x
+ w
- 1 - WidgetDimensions::scaled
.fullbevel
.right
, y
+ WidgetDimensions::scaled
.fullbevel
.top
, ss
.string
, colour
, SA_HOR_CENTER
, false, small
? FS_SMALL
: FS_NORMAL
);
1734 void ViewportDoDraw(const Viewport
*vp
, int left
, int top
, int right
, int bottom
)
1736 _vd
.dpi
.zoom
= vp
->zoom
;
1737 int mask
= ScaleByZoom(-1, vp
->zoom
);
1739 _vd
.combine_sprites
= SPRITE_COMBINE_NONE
;
1741 _vd
.dpi
.width
= (right
- left
) & mask
;
1742 _vd
.dpi
.height
= (bottom
- top
) & mask
;
1743 _vd
.dpi
.left
= left
& mask
;
1744 _vd
.dpi
.top
= top
& mask
;
1745 _vd
.dpi
.pitch
= _cur_dpi
->pitch
;
1746 _vd
.last_child
= nullptr;
1748 int x
= UnScaleByZoom(_vd
.dpi
.left
- (vp
->virtual_left
& mask
), vp
->zoom
) + vp
->left
;
1749 int y
= UnScaleByZoom(_vd
.dpi
.top
- (vp
->virtual_top
& mask
), vp
->zoom
) + vp
->top
;
1751 _vd
.dpi
.dst_ptr
= BlitterFactory::GetCurrentBlitter()->MoveTo(_cur_dpi
->dst_ptr
, x
- _cur_dpi
->left
, y
- _cur_dpi
->top
);
1752 AutoRestoreBackup
dpi_backup(_cur_dpi
, &_vd
.dpi
);
1754 ViewportAddLandscape();
1755 ViewportAddVehicles(&_vd
.dpi
);
1757 ViewportAddKdtreeSigns(&_vd
.dpi
);
1759 DrawTextEffects(&_vd
.dpi
);
1761 if (!_vd
.tile_sprites_to_draw
.empty()) ViewportDrawTileSprites(&_vd
.tile_sprites_to_draw
);
1763 for (auto &psd
: _vd
.parent_sprites_to_draw
) {
1764 _vd
.parent_sprites_to_sort
.push_back(&psd
);
1767 _vp_sprite_sorter(&_vd
.parent_sprites_to_sort
);
1768 ViewportDrawParentSprites(&_vd
.parent_sprites_to_sort
, &_vd
.child_screen_sprites_to_draw
);
1770 if (_draw_bounding_boxes
) ViewportDrawBoundingBoxes(&_vd
.parent_sprites_to_sort
);
1771 if (_draw_dirty_blocks
) ViewportDrawDirtyBlocks();
1773 DrawPixelInfo dp
= _vd
.dpi
;
1774 ZoomLevel zoom
= _vd
.dpi
.zoom
;
1775 dp
.zoom
= ZOOM_LVL_NORMAL
;
1776 dp
.width
= UnScaleByZoom(dp
.width
, zoom
);
1777 dp
.height
= UnScaleByZoom(dp
.height
, zoom
);
1780 if (vp
->overlay
!= nullptr && vp
->overlay
->GetCargoMask() != 0 && vp
->overlay
->GetCompanyMask() != 0) {
1781 /* translate to window coordinates */
1784 vp
->overlay
->Draw(&dp
);
1787 if (!_vd
.string_sprites_to_draw
.empty()) {
1788 /* translate to world coordinates */
1789 dp
.left
= UnScaleByZoom(_vd
.dpi
.left
, zoom
);
1790 dp
.top
= UnScaleByZoom(_vd
.dpi
.top
, zoom
);
1791 ViewportDrawStrings(zoom
, &_vd
.string_sprites_to_draw
);
1794 _vd
.string_sprites_to_draw
.clear();
1795 _vd
.tile_sprites_to_draw
.clear();
1796 _vd
.parent_sprites_to_draw
.clear();
1797 _vd
.parent_sprites_to_sort
.clear();
1798 _vd
.child_screen_sprites_to_draw
.clear();
1801 static inline void ViewportDraw(const Viewport
*vp
, int left
, int top
, int right
, int bottom
)
1803 if (right
<= vp
->left
|| bottom
<= vp
->top
) return;
1805 if (left
>= vp
->left
+ vp
->width
) return;
1807 if (left
< vp
->left
) left
= vp
->left
;
1808 if (right
> vp
->left
+ vp
->width
) right
= vp
->left
+ vp
->width
;
1810 if (top
>= vp
->top
+ vp
->height
) return;
1812 if (top
< vp
->top
) top
= vp
->top
;
1813 if (bottom
> vp
->top
+ vp
->height
) bottom
= vp
->top
+ vp
->height
;
1816 ScaleByZoom(left
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
1817 ScaleByZoom(top
- vp
->top
, vp
->zoom
) + vp
->virtual_top
,
1818 ScaleByZoom(right
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
1819 ScaleByZoom(bottom
- vp
->top
, vp
->zoom
) + vp
->virtual_top
1824 * Draw the viewport of this window.
1826 void Window::DrawViewport() const
1828 PerformanceAccumulator
framerate(PFE_DRAWWORLD
);
1830 DrawPixelInfo
*dpi
= _cur_dpi
;
1832 dpi
->left
+= this->left
;
1833 dpi
->top
+= this->top
;
1835 ViewportDraw(this->viewport
, dpi
->left
, dpi
->top
, dpi
->left
+ dpi
->width
, dpi
->top
+ dpi
->height
);
1837 dpi
->left
-= this->left
;
1838 dpi
->top
-= this->top
;
1842 * Ensure that a given viewport has a valid scroll position.
1844 * There must be a visible piece of the map in the center of the viewport.
1845 * If there isn't, the viewport will be scrolled to nearest such location.
1847 * @param vp The viewport.
1848 * @param[in,out] scroll_x Viewport X scroll.
1849 * @param[in,out] scroll_y Viewport Y scroll.
1851 static inline void ClampViewportToMap(const Viewport
*vp
, int *scroll_x
, int *scroll_y
)
1853 /* Centre of the viewport is hot spot. */
1855 *scroll_x
+ vp
->virtual_width
/ 2,
1856 *scroll_y
+ vp
->virtual_height
/ 2
1859 /* Find nearest tile that is within borders of the map. */
1861 pt
= InverseRemapCoords2(pt
.x
, pt
.y
, true, &clamped
);
1864 /* Convert back to viewport coordinates and remove centering. */
1865 pt
= RemapCoords2(pt
.x
, pt
.y
);
1866 *scroll_x
= pt
.x
- vp
->virtual_width
/ 2;
1867 *scroll_y
= pt
.y
- vp
->virtual_height
/ 2;
1872 * Clamp the smooth scroll to a maxmimum speed and distance based on time elapsed.
1874 * Every 30ms, we move 1/4th of the distance, to give a smooth movement experience.
1875 * But we never go over the max_scroll speed.
1877 * @param delta_ms Time elapsed since last update.
1878 * @param delta_hi The distance to move in highest dimension (can't be zero).
1879 * @param delta_lo The distance to move in lowest dimension.
1880 * @param[out] delta_hi_clamped The clamped distance to move in highest dimension.
1881 * @param[out] delta_lo_clamped The clamped distance to move in lowest dimension.
1883 static void ClampSmoothScroll(uint32_t delta_ms
, int64_t delta_hi
, int64_t delta_lo
, int &delta_hi_clamped
, int &delta_lo_clamped
)
1885 /** A tile is 64 pixels in width at 1x zoom; viewport coordinates are in 4x zoom. */
1886 constexpr int PIXELS_PER_TILE
= TILE_PIXELS
* 2 * ZOOM_LVL_BASE
;
1888 assert(delta_hi
!= 0);
1890 /* Move at most 75% of the distance every 30ms, for a smooth experience */
1891 int64_t delta_left
= delta_hi
* std::pow(0.75, delta_ms
/ 30.0);
1892 /* Move never more than 16 tiles per 30ms. */
1893 int max_scroll
= Map::ScaleBySize1D(16 * PIXELS_PER_TILE
* delta_ms
/ 30);
1895 /* We never go over the max_scroll speed. */
1896 delta_hi_clamped
= Clamp(delta_hi
- delta_left
, -max_scroll
, max_scroll
);
1897 /* The lower delta is in ratio of the higher delta, so we keep going straight at the destination. */
1898 delta_lo_clamped
= delta_lo
* delta_hi_clamped
/ delta_hi
;
1900 /* Ensure we always move (delta_hi can't be zero). */
1901 if (delta_hi_clamped
== 0) {
1902 delta_hi_clamped
= delta_hi
> 0 ? 1 : -1;
1907 * Update the viewport position being displayed.
1908 * @param w %Window owning the viewport.
1910 void UpdateViewportPosition(Window
*w
, uint32_t delta_ms
)
1912 const Viewport
*vp
= w
->viewport
;
1914 if (w
->viewport
->follow_vehicle
!= INVALID_VEHICLE
) {
1915 const Vehicle
*veh
= Vehicle::Get(w
->viewport
->follow_vehicle
);
1916 Point pt
= MapXYZToViewport(vp
, veh
->x_pos
, veh
->y_pos
, veh
->z_pos
);
1918 w
->viewport
->scrollpos_x
= pt
.x
;
1919 w
->viewport
->scrollpos_y
= pt
.y
;
1920 SetViewportPosition(w
, pt
.x
, pt
.y
);
1922 /* Ensure the destination location is within the map */
1923 ClampViewportToMap(vp
, &w
->viewport
->dest_scrollpos_x
, &w
->viewport
->dest_scrollpos_y
);
1925 int delta_x
= w
->viewport
->dest_scrollpos_x
- w
->viewport
->scrollpos_x
;
1926 int delta_y
= w
->viewport
->dest_scrollpos_y
- w
->viewport
->scrollpos_y
;
1928 int current_x
= w
->viewport
->scrollpos_x
;
1929 int current_y
= w
->viewport
->scrollpos_y
;
1931 bool update_overlay
= false;
1932 if (delta_x
!= 0 || delta_y
!= 0) {
1933 if (_settings_client
.gui
.smooth_scroll
) {
1934 int delta_x_clamped
;
1935 int delta_y_clamped
;
1937 if (abs(delta_x
) > abs(delta_y
)) {
1938 ClampSmoothScroll(delta_ms
, delta_x
, delta_y
, delta_x_clamped
, delta_y_clamped
);
1940 ClampSmoothScroll(delta_ms
, delta_y
, delta_x
, delta_y_clamped
, delta_x_clamped
);
1943 w
->viewport
->scrollpos_x
+= delta_x_clamped
;
1944 w
->viewport
->scrollpos_y
+= delta_y_clamped
;
1946 w
->viewport
->scrollpos_x
= w
->viewport
->dest_scrollpos_x
;
1947 w
->viewport
->scrollpos_y
= w
->viewport
->dest_scrollpos_y
;
1949 update_overlay
= (w
->viewport
->scrollpos_x
== w
->viewport
->dest_scrollpos_x
&&
1950 w
->viewport
->scrollpos_y
== w
->viewport
->dest_scrollpos_y
);
1953 ClampViewportToMap(vp
, &w
->viewport
->scrollpos_x
, &w
->viewport
->scrollpos_y
);
1955 /* When moving small amounts around the border we can get stuck, and
1956 * not actually move. In those cases, teleport to the destination. */
1957 if ((delta_x
!= 0 || delta_y
!= 0) && current_x
== w
->viewport
->scrollpos_x
&& current_y
== w
->viewport
->scrollpos_y
) {
1958 w
->viewport
->scrollpos_x
= w
->viewport
->dest_scrollpos_x
;
1959 w
->viewport
->scrollpos_y
= w
->viewport
->dest_scrollpos_y
;
1962 SetViewportPosition(w
, w
->viewport
->scrollpos_x
, w
->viewport
->scrollpos_y
);
1963 if (update_overlay
) RebuildViewportOverlay(w
);
1968 * Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
1969 * @param vp The viewport to mark as dirty
1970 * @param left Left edge of area to repaint
1971 * @param top Top edge of area to repaint
1972 * @param right Right edge of area to repaint
1973 * @param bottom Bottom edge of area to repaint
1974 * @return true if the viewport contains a dirty block
1977 static bool MarkViewportDirty(const Viewport
*vp
, int left
, int top
, int right
, int bottom
)
1979 /* Rounding wrt. zoom-out level */
1980 right
+= (1 << vp
->zoom
) - 1;
1981 bottom
+= (1 << vp
->zoom
) - 1;
1983 right
-= vp
->virtual_left
;
1984 if (right
<= 0) return false;
1986 bottom
-= vp
->virtual_top
;
1987 if (bottom
<= 0) return false;
1989 left
= std::max(0, left
- vp
->virtual_left
);
1991 if (left
>= vp
->virtual_width
) return false;
1993 top
= std::max(0, top
- vp
->virtual_top
);
1995 if (top
>= vp
->virtual_height
) return false;
1998 UnScaleByZoomLower(left
, vp
->zoom
) + vp
->left
,
1999 UnScaleByZoomLower(top
, vp
->zoom
) + vp
->top
,
2000 UnScaleByZoom(right
, vp
->zoom
) + vp
->left
+ 1,
2001 UnScaleByZoom(bottom
, vp
->zoom
) + vp
->top
+ 1
2008 * Mark all viewports that display an area as dirty (in need of repaint).
2009 * @param left Left edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
2010 * @param top Top edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
2011 * @param right Right edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
2012 * @param bottom Bottom edge of area to repaint. (viewport coordinates, that is wrt. #ZOOM_LVL_NORMAL)
2013 * @return true if at least one viewport has a dirty block
2016 bool MarkAllViewportsDirty(int left
, int top
, int right
, int bottom
)
2020 for (const Window
*w
: Window::Iterate()) {
2021 Viewport
*vp
= w
->viewport
;
2022 if (vp
!= nullptr) {
2023 assert(vp
->width
!= 0);
2024 if (MarkViewportDirty(vp
, left
, top
, right
, bottom
)) dirty
= true;
2031 void ConstrainAllViewportsZoom()
2033 for (Window
*w
: Window::Iterate()) {
2034 if (w
->viewport
== nullptr) continue;
2036 ZoomLevel zoom
= static_cast<ZoomLevel
>(Clamp(w
->viewport
->zoom
, _settings_client
.gui
.zoom_min
, _settings_client
.gui
.zoom_max
));
2037 if (zoom
!= w
->viewport
->zoom
) {
2038 while (w
->viewport
->zoom
< zoom
) DoZoomInOutWindow(ZOOM_OUT
, w
);
2039 while (w
->viewport
->zoom
> zoom
) DoZoomInOutWindow(ZOOM_IN
, w
);
2045 * Mark a tile given by its index dirty for repaint.
2046 * @param tile The tile to mark dirty.
2047 * @param bridge_level_offset Height of bridge on tile to also mark dirty. (Height level relative to north corner.)
2048 * @param tile_height_override Height of the tile (#TileHeight).
2051 void MarkTileDirtyByTile(TileIndex tile
, int bridge_level_offset
, int tile_height_override
)
2053 Point pt
= RemapCoords(TileX(tile
) * TILE_SIZE
, TileY(tile
) * TILE_SIZE
, tile_height_override
* TILE_HEIGHT
);
2054 MarkAllViewportsDirty(
2055 pt
.x
- MAX_TILE_EXTENT_LEFT
,
2056 pt
.y
- MAX_TILE_EXTENT_TOP
- ZOOM_LVL_BASE
* TILE_HEIGHT
* bridge_level_offset
,
2057 pt
.x
+ MAX_TILE_EXTENT_RIGHT
,
2058 pt
.y
+ MAX_TILE_EXTENT_BOTTOM
);
2062 * Marks the selected tiles as dirty.
2064 * This function marks the selected tiles as dirty for repaint
2068 static void SetSelectionTilesDirty()
2070 int x_size
= _thd
.size
.x
;
2071 int y_size
= _thd
.size
.y
;
2073 if (!_thd
.diagonal
) { // Selecting in a straight rectangle (or a single square)
2074 int x_start
= _thd
.pos
.x
;
2075 int y_start
= _thd
.pos
.y
;
2077 if (_thd
.outersize
.x
!= 0) {
2078 x_size
+= _thd
.outersize
.x
;
2079 x_start
+= _thd
.offs
.x
;
2080 y_size
+= _thd
.outersize
.y
;
2081 y_start
+= _thd
.offs
.y
;
2084 x_size
-= TILE_SIZE
;
2085 y_size
-= TILE_SIZE
;
2087 assert(x_size
>= 0);
2088 assert(y_size
>= 0);
2090 int x_end
= Clamp(x_start
+ x_size
, 0, Map::SizeX() * TILE_SIZE
- TILE_SIZE
);
2091 int y_end
= Clamp(y_start
+ y_size
, 0, Map::SizeY() * TILE_SIZE
- TILE_SIZE
);
2093 x_start
= Clamp(x_start
, 0, Map::SizeX() * TILE_SIZE
- TILE_SIZE
);
2094 y_start
= Clamp(y_start
, 0, Map::SizeY() * TILE_SIZE
- TILE_SIZE
);
2096 /* make sure everything is multiple of TILE_SIZE */
2097 assert((x_end
| y_end
| x_start
| y_start
) % TILE_SIZE
== 0);
2100 * Suppose we have to mark dirty rectangle of 3x4 tiles:
2107 * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
2117 int top_x
= x_end
; // coordinates of top dirty tile
2118 int top_y
= y_start
;
2119 int bot_x
= top_x
; // coordinates of bottom dirty tile
2123 /* topmost dirty point */
2124 TileIndex top_tile
= TileVirtXY(top_x
, top_y
);
2125 Point top
= RemapCoords(top_x
, top_y
, GetTileMaxPixelZ(top_tile
));
2127 /* bottommost point */
2128 TileIndex bottom_tile
= TileVirtXY(bot_x
, bot_y
);
2129 Point bot
= RemapCoords(bot_x
+ TILE_SIZE
, bot_y
+ TILE_SIZE
, GetTilePixelZ(bottom_tile
)); // bottommost point
2131 /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
2132 * tile height/slope affects only the 'y' on-screen coordinate! */
2134 int l
= top
.x
- TILE_PIXELS
* ZOOM_LVL_BASE
; // 'x' coordinate of left side of the dirty rectangle
2135 int t
= top
.y
; // 'y' coordinate of top side of the dirty rectangle
2136 int r
= top
.x
+ TILE_PIXELS
* ZOOM_LVL_BASE
; // 'x' coordinate of right side of the dirty rectangle
2137 int b
= bot
.y
; // 'y' coordinate of bottom side of the dirty rectangle
2139 static const int OVERLAY_WIDTH
= 4 * ZOOM_LVL_BASE
; // part of selection sprites is drawn outside the selected area (in particular: terraforming)
2141 /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
2142 MarkAllViewportsDirty(l
- OVERLAY_WIDTH
, t
- OVERLAY_WIDTH
- TILE_HEIGHT
* ZOOM_LVL_BASE
, r
+ OVERLAY_WIDTH
, b
+ OVERLAY_WIDTH
);
2144 /* haven't we reached the topmost tile yet? */
2145 if (top_x
!= x_start
) {
2151 /* the way the bottom tile changes is different when we reach the bottommost tile */
2152 if (bot_y
!= y_end
) {
2157 } while (bot_x
>= top_x
);
2158 } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
2159 /* a_size, b_size describe a rectangle with rotated coordinates */
2160 int a_size
= x_size
+ y_size
, b_size
= x_size
- y_size
;
2162 int interval_a
= a_size
< 0 ? -(int)TILE_SIZE
: (int)TILE_SIZE
;
2163 int interval_b
= b_size
< 0 ? -(int)TILE_SIZE
: (int)TILE_SIZE
;
2165 for (int a
= -interval_a
; a
!= a_size
+ interval_a
; a
+= interval_a
) {
2166 for (int b
= -interval_b
; b
!= b_size
+ interval_b
; b
+= interval_b
) {
2167 uint x
= (_thd
.pos
.x
+ (a
+ b
) / 2) / TILE_SIZE
;
2168 uint y
= (_thd
.pos
.y
+ (a
- b
) / 2) / TILE_SIZE
;
2170 if (x
< Map::MaxX() && y
< Map::MaxY()) {
2171 MarkTileDirtyByTile(TileXY(x
, y
));
2179 void SetSelectionRed(bool b
)
2181 _thd
.make_square_red
= b
;
2182 SetSelectionTilesDirty();
2186 * Test whether a sign is below the mouse
2187 * @param vp the clicked viewport
2188 * @param x X position of click
2189 * @param y Y position of click
2190 * @param sign the sign to check
2191 * @return true if the sign was hit
2193 static bool CheckClickOnViewportSign(const Viewport
*vp
, int x
, int y
, const ViewportSign
*sign
)
2195 bool small
= (vp
->zoom
>= ZOOM_LVL_OUT_16X
);
2196 int sign_half_width
= ScaleByZoom((small
? sign
->width_small
: sign
->width_normal
) / 2, vp
->zoom
);
2197 int sign_height
= ScaleByZoom(WidgetDimensions::scaled
.fullbevel
.top
+ (small
? GetCharacterHeight(FS_SMALL
) : GetCharacterHeight(FS_NORMAL
)) + WidgetDimensions::scaled
.fullbevel
.bottom
, vp
->zoom
);
2199 return y
>= sign
->top
&& y
< sign
->top
+ sign_height
&&
2200 x
>= sign
->center
- sign_half_width
&& x
< sign
->center
+ sign_half_width
;
2205 * Check whether any viewport sign was clicked, and dispatch the click.
2206 * @param vp the clicked viewport
2207 * @param x X position of click
2208 * @param y Y position of click
2209 * @return true if the sign was hit
2211 static bool CheckClickOnViewportSign(const Viewport
*vp
, int x
, int y
)
2213 if (_game_mode
== GM_MENU
) return false;
2215 x
= ScaleByZoom(x
- vp
->left
, vp
->zoom
) + vp
->virtual_left
;
2216 y
= ScaleByZoom(y
- vp
->top
, vp
->zoom
) + vp
->virtual_top
;
2218 Rect search_rect
{ x
- 1, y
- 1, x
+ 1, y
+ 1 };
2219 search_rect
= ExpandRectWithViewportSignMargins(search_rect
, vp
->zoom
);
2221 bool show_stations
= HasBit(_display_opt
, DO_SHOW_STATION_NAMES
) && !IsInvisibilitySet(TO_SIGNS
);
2222 bool show_waypoints
= HasBit(_display_opt
, DO_SHOW_WAYPOINT_NAMES
) && !IsInvisibilitySet(TO_SIGNS
);
2223 bool show_towns
= HasBit(_display_opt
, DO_SHOW_TOWN_NAMES
);
2224 bool show_signs
= HasBit(_display_opt
, DO_SHOW_SIGNS
) && !IsInvisibilitySet(TO_SIGNS
);
2225 bool show_competitors
= HasBit(_display_opt
, DO_SHOW_COMPETITOR_SIGNS
);
2227 /* Topmost of each type that was hit */
2228 BaseStation
*st
= nullptr, *last_st
= nullptr;
2229 Town
*t
= nullptr, *last_t
= nullptr;
2230 Sign
*si
= nullptr, *last_si
= nullptr;
2232 /* See ViewportAddKdtreeSigns() for details on the search logic */
2233 _viewport_sign_kdtree
.FindContained(search_rect
.left
, search_rect
.top
, search_rect
.right
, search_rect
.bottom
, [&](const ViewportSignKdtreeItem
& item
) {
2234 switch (item
.type
) {
2235 case ViewportSignKdtreeItem::VKI_STATION
:
2236 if (!show_stations
) break;
2237 st
= BaseStation::Get(item
.id
.station
);
2238 if (!show_competitors
&& _local_company
!= st
->owner
&& st
->owner
!= OWNER_NONE
) break;
2239 if (CheckClickOnViewportSign(vp
, x
, y
, &st
->sign
)) last_st
= st
;
2242 case ViewportSignKdtreeItem::VKI_WAYPOINT
:
2243 if (!show_waypoints
) break;
2244 st
= BaseStation::Get(item
.id
.station
);
2245 if (!show_competitors
&& _local_company
!= st
->owner
&& st
->owner
!= OWNER_NONE
) break;
2246 if (CheckClickOnViewportSign(vp
, x
, y
, &st
->sign
)) last_st
= st
;
2249 case ViewportSignKdtreeItem::VKI_TOWN
:
2250 if (!show_towns
) break;
2251 t
= Town::Get(item
.id
.town
);
2252 if (CheckClickOnViewportSign(vp
, x
, y
, &t
->cache
.sign
)) last_t
= t
;
2255 case ViewportSignKdtreeItem::VKI_SIGN
:
2256 if (!show_signs
) break;
2257 si
= Sign::Get(item
.id
.sign
);
2258 if (!show_competitors
&& _local_company
!= si
->owner
&& si
->owner
!= OWNER_DEITY
) break;
2259 if (CheckClickOnViewportSign(vp
, x
, y
, &si
->sign
)) last_si
= si
;
2267 /* Select which hit to handle based on priority */
2268 if (last_st
!= nullptr) {
2269 if (Station::IsExpected(last_st
)) {
2270 ShowStationViewWindow(last_st
->index
);
2272 ShowWaypointWindow(Waypoint::From(last_st
));
2275 } else if (last_t
!= nullptr) {
2276 ShowTownViewWindow(last_t
->index
);
2278 } else if (last_si
!= nullptr) {
2279 HandleClickOnSign(last_si
);
2287 ViewportSignKdtreeItem
ViewportSignKdtreeItem::MakeStation(StationID id
)
2289 ViewportSignKdtreeItem item
;
2290 item
.type
= VKI_STATION
;
2291 item
.id
.station
= id
;
2293 const Station
*st
= Station::Get(id
);
2294 assert(st
->sign
.kdtree_valid
);
2295 item
.center
= st
->sign
.center
;
2296 item
.top
= st
->sign
.top
;
2298 /* Assume the sign can be a candidate for drawing, so measure its width */
2299 _viewport_sign_maxwidth
= std::max
<int>(_viewport_sign_maxwidth
, st
->sign
.width_normal
);
2304 ViewportSignKdtreeItem
ViewportSignKdtreeItem::MakeWaypoint(StationID id
)
2306 ViewportSignKdtreeItem item
;
2307 item
.type
= VKI_WAYPOINT
;
2308 item
.id
.station
= id
;
2310 const Waypoint
*st
= Waypoint::Get(id
);
2311 assert(st
->sign
.kdtree_valid
);
2312 item
.center
= st
->sign
.center
;
2313 item
.top
= st
->sign
.top
;
2315 /* Assume the sign can be a candidate for drawing, so measure its width */
2316 _viewport_sign_maxwidth
= std::max
<int>(_viewport_sign_maxwidth
, st
->sign
.width_normal
);
2321 ViewportSignKdtreeItem
ViewportSignKdtreeItem::MakeTown(TownID id
)
2323 ViewportSignKdtreeItem item
;
2324 item
.type
= VKI_TOWN
;
2327 const Town
*town
= Town::Get(id
);
2328 assert(town
->cache
.sign
.kdtree_valid
);
2329 item
.center
= town
->cache
.sign
.center
;
2330 item
.top
= town
->cache
.sign
.top
;
2332 /* Assume the sign can be a candidate for drawing, so measure its width */
2333 _viewport_sign_maxwidth
= std::max
<int>(_viewport_sign_maxwidth
, town
->cache
.sign
.width_normal
);
2338 ViewportSignKdtreeItem
ViewportSignKdtreeItem::MakeSign(SignID id
)
2340 ViewportSignKdtreeItem item
;
2341 item
.type
= VKI_SIGN
;
2344 const Sign
*sign
= Sign::Get(id
);
2345 assert(sign
->sign
.kdtree_valid
);
2346 item
.center
= sign
->sign
.center
;
2347 item
.top
= sign
->sign
.top
;
2349 /* Assume the sign can be a candidate for drawing, so measure its width */
2350 _viewport_sign_maxwidth
= std::max
<int>(_viewport_sign_maxwidth
, sign
->sign
.width_normal
);
2355 void RebuildViewportKdtree()
2357 /* Reset biggest size sign seen */
2358 _viewport_sign_maxwidth
= 0;
2360 std::vector
<ViewportSignKdtreeItem
> items
;
2361 items
.reserve(BaseStation::GetNumItems() + Town::GetNumItems() + Sign::GetNumItems());
2363 for (const Station
*st
: Station::Iterate()) {
2364 if (st
->sign
.kdtree_valid
) items
.push_back(ViewportSignKdtreeItem::MakeStation(st
->index
));
2367 for (const Waypoint
*wp
: Waypoint::Iterate()) {
2368 if (wp
->sign
.kdtree_valid
) items
.push_back(ViewportSignKdtreeItem::MakeWaypoint(wp
->index
));
2371 for (const Town
*town
: Town::Iterate()) {
2372 if (town
->cache
.sign
.kdtree_valid
) items
.push_back(ViewportSignKdtreeItem::MakeTown(town
->index
));
2375 for (const Sign
*sign
: Sign::Iterate()) {
2376 if (sign
->sign
.kdtree_valid
) items
.push_back(ViewportSignKdtreeItem::MakeSign(sign
->index
));
2379 _viewport_sign_kdtree
.Build(items
.begin(), items
.end());
2383 static bool CheckClickOnLandscape(const Viewport
*vp
, int x
, int y
)
2385 Point pt
= TranslateXYToTileCoord(vp
, x
, y
);
2387 if (pt
.x
!= -1) return ClickTile(TileVirtXY(pt
.x
, pt
.y
));
2391 static void PlaceObject()
2396 pt
= GetTileBelowCursor();
2397 if (pt
.x
== -1) return;
2399 if ((_thd
.place_mode
& HT_DRAG_MASK
) == HT_POINT
) {
2400 pt
.x
+= TILE_SIZE
/ 2;
2401 pt
.y
+= TILE_SIZE
/ 2;
2404 _tile_fract_coords
.x
= pt
.x
& TILE_UNIT_MASK
;
2405 _tile_fract_coords
.y
= pt
.y
& TILE_UNIT_MASK
;
2407 w
= _thd
.GetCallbackWnd();
2408 if (w
!= nullptr) w
->OnPlaceObject(pt
, TileVirtXY(pt
.x
, pt
.y
));
2412 bool HandleViewportClicked(const Viewport
*vp
, int x
, int y
)
2414 const Vehicle
*v
= CheckClickOnVehicle(vp
, x
, y
);
2416 if (_thd
.place_mode
& HT_VEHICLE
) {
2417 if (v
!= nullptr && VehicleClicked(v
)) return true;
2420 /* Vehicle placement mode already handled above. */
2421 if ((_thd
.place_mode
& HT_DRAG_MASK
) != HT_NONE
) {
2426 if (CheckClickOnViewportSign(vp
, x
, y
)) return true;
2427 bool result
= CheckClickOnLandscape(vp
, x
, y
);
2430 Debug(misc
, 2, "Vehicle {} (index {}) at {}", v
->unitnumber
, v
->index
, fmt::ptr(v
));
2431 if (IsCompanyBuildableVehicleType(v
)) {
2433 if (_ctrl_pressed
&& v
->owner
== _local_company
) {
2434 StartStopVehicle(v
, true);
2436 ShowVehicleViewWindow(v
);
2444 void RebuildViewportOverlay(Window
*w
)
2446 if (w
->viewport
->overlay
!= nullptr &&
2447 w
->viewport
->overlay
->GetCompanyMask() != 0 &&
2448 w
->viewport
->overlay
->GetCargoMask() != 0) {
2449 w
->viewport
->overlay
->SetDirty();
2455 * Scrolls the viewport in a window to a given location.
2456 * @param x Desired x location of the map to scroll to (world coordinate).
2457 * @param y Desired y location of the map to scroll to (world coordinate).
2458 * @param z Desired z location of the map to scroll to (world coordinate). Use \c -1 to scroll to the height of the map at the \a x, \a y location.
2459 * @param w %Window containing the viewport.
2460 * @param instant Jump to the location instead of slowly moving to it.
2461 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2463 bool ScrollWindowTo(int x
, int y
, int z
, Window
*w
, bool instant
)
2465 /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
2467 if ( x
>= 0 && x
<= (int)Map::SizeX() * (int)TILE_SIZE
- 1
2468 && y
>= 0 && y
<= (int)Map::SizeY() * (int)TILE_SIZE
- 1) {
2469 z
= GetSlopePixelZ(x
, y
);
2471 z
= TileHeightOutsideMap(x
/ (int)TILE_SIZE
, y
/ (int)TILE_SIZE
);
2475 Point pt
= MapXYZToViewport(w
->viewport
, x
, y
, z
);
2476 w
->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2478 if (w
->viewport
->dest_scrollpos_x
== pt
.x
&& w
->viewport
->dest_scrollpos_y
== pt
.y
) return false;
2481 w
->viewport
->scrollpos_x
= pt
.x
;
2482 w
->viewport
->scrollpos_y
= pt
.y
;
2483 RebuildViewportOverlay(w
);
2486 w
->viewport
->dest_scrollpos_x
= pt
.x
;
2487 w
->viewport
->dest_scrollpos_y
= pt
.y
;
2492 * Scrolls the viewport in a window to a given location.
2493 * @param tile Desired tile to center on.
2494 * @param w %Window containing the viewport.
2495 * @param instant Jump to the location instead of slowly moving to it.
2496 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2498 bool ScrollWindowToTile(TileIndex tile
, Window
*w
, bool instant
)
2500 return ScrollWindowTo(TileX(tile
) * TILE_SIZE
, TileY(tile
) * TILE_SIZE
, -1, w
, instant
);
2504 * Scrolls the viewport of the main window to a given location.
2505 * @param tile Desired tile to center on.
2506 * @param instant Jump to the location instead of slowly moving to it.
2507 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2509 bool ScrollMainWindowToTile(TileIndex tile
, bool instant
)
2511 return ScrollMainWindowTo(TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2, TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2, -1, instant
);
2515 * Set a tile to display a red error square.
2516 * @param tile Tile that should show the red error square.
2518 void SetRedErrorSquare(TileIndex tile
)
2526 if (tile
!= INVALID_TILE
) MarkTileDirtyByTile(tile
);
2527 if (old
!= INVALID_TILE
) MarkTileDirtyByTile(old
);
2532 * Highlight \a w by \a h tiles at the cursor.
2533 * @param w Width of the highlighted tiles rectangle.
2534 * @param h Height of the highlighted tiles rectangle.
2536 void SetTileSelectSize(int w
, int h
)
2538 _thd
.new_size
.x
= w
* TILE_SIZE
;
2539 _thd
.new_size
.y
= h
* TILE_SIZE
;
2540 _thd
.new_outersize
.x
= 0;
2541 _thd
.new_outersize
.y
= 0;
2544 void SetTileSelectBigSize(int ox
, int oy
, int sx
, int sy
)
2546 _thd
.offs
.x
= ox
* TILE_SIZE
;
2547 _thd
.offs
.y
= oy
* TILE_SIZE
;
2548 _thd
.new_outersize
.x
= sx
* TILE_SIZE
;
2549 _thd
.new_outersize
.y
= sy
* TILE_SIZE
;
2552 /** returns the best autorail highlight type from map coordinates */
2553 static HighLightStyle
GetAutorailHT(int x
, int y
)
2555 return HT_RAIL
| _autorail_piece
[x
& TILE_UNIT_MASK
][y
& TILE_UNIT_MASK
];
2559 * Reset tile highlighting.
2561 void TileHighlightData::Reset()
2565 this->new_pos
.x
= 0;
2566 this->new_pos
.y
= 0;
2570 * Is the user dragging a 'diagonal rectangle'?
2571 * @return User is dragging a rotated rectangle.
2573 bool TileHighlightData::IsDraggingDiagonal()
2575 return (this->place_mode
& HT_DIAGONAL
) != 0 && _ctrl_pressed
&& _left_button_down
;
2579 * Get the window that started the current highlighting.
2580 * @return The window that requested the current tile highlighting, or \c nullptr if not available.
2582 Window
*TileHighlightData::GetCallbackWnd()
2584 return FindWindowById(this->window_class
, this->window_number
);
2590 * Updates tile highlighting for all cases.
2591 * Uses _thd.selstart and _thd.selend and _thd.place_mode (set elsewhere) to determine _thd.pos and _thd.size
2592 * Also drawstyle is determined. Uses _thd.new.* as a buffer and calls SetSelectionTilesDirty() twice,
2593 * Once for the old and once for the new selection.
2594 * _thd is TileHighlightData, found in viewport.h
2596 void UpdateTileSelection()
2601 if (_thd
.freeze
) return;
2603 HighLightStyle new_drawstyle
= HT_NONE
;
2604 bool new_diagonal
= false;
2606 if ((_thd
.place_mode
& HT_DRAG_MASK
) == HT_SPECIAL
) {
2610 int x2
= _thd
.selstart
.x
& ~TILE_UNIT_MASK
;
2611 int y2
= _thd
.selstart
.y
& ~TILE_UNIT_MASK
;
2612 x1
&= ~TILE_UNIT_MASK
;
2613 y1
&= ~TILE_UNIT_MASK
;
2615 if (_thd
.IsDraggingDiagonal()) {
2616 new_diagonal
= true;
2618 if (x1
>= x2
) Swap(x1
, x2
);
2619 if (y1
>= y2
) Swap(y1
, y2
);
2621 _thd
.new_pos
.x
= x1
;
2622 _thd
.new_pos
.y
= y1
;
2623 _thd
.new_size
.x
= x2
- x1
;
2624 _thd
.new_size
.y
= y2
- y1
;
2625 if (!new_diagonal
) {
2626 _thd
.new_size
.x
+= TILE_SIZE
;
2627 _thd
.new_size
.y
+= TILE_SIZE
;
2629 new_drawstyle
= _thd
.next_drawstyle
;
2631 } else if ((_thd
.place_mode
& HT_DRAG_MASK
) != HT_NONE
) {
2632 Point pt
= GetTileBelowCursor();
2636 switch (_thd
.place_mode
& HT_DRAG_MASK
) {
2638 new_drawstyle
= HT_RECT
;
2641 new_drawstyle
= HT_POINT
;
2642 x1
+= TILE_SIZE
/ 2;
2643 y1
+= TILE_SIZE
/ 2;
2646 /* Draw one highlighted tile in any direction */
2647 new_drawstyle
= GetAutorailHT(pt
.x
, pt
.y
);
2650 switch (_thd
.place_mode
& HT_DIR_MASK
) {
2651 case HT_DIR_X
: new_drawstyle
= HT_LINE
| HT_DIR_X
; break;
2652 case HT_DIR_Y
: new_drawstyle
= HT_LINE
| HT_DIR_Y
; break;
2656 new_drawstyle
= (pt
.x
& TILE_UNIT_MASK
) + (pt
.y
& TILE_UNIT_MASK
) <= TILE_SIZE
? HT_LINE
| HT_DIR_HU
: HT_LINE
| HT_DIR_HL
;
2661 new_drawstyle
= (pt
.x
& TILE_UNIT_MASK
) > (pt
.y
& TILE_UNIT_MASK
) ? HT_LINE
| HT_DIR_VL
: HT_LINE
| HT_DIR_VR
;
2664 default: NOT_REACHED();
2666 _thd
.selstart
.x
= x1
& ~TILE_UNIT_MASK
;
2667 _thd
.selstart
.y
= y1
& ~TILE_UNIT_MASK
;
2672 _thd
.new_pos
.x
= x1
& ~TILE_UNIT_MASK
;
2673 _thd
.new_pos
.y
= y1
& ~TILE_UNIT_MASK
;
2677 /* redraw selection */
2678 if (_thd
.drawstyle
!= new_drawstyle
||
2679 _thd
.pos
.x
!= _thd
.new_pos
.x
|| _thd
.pos
.y
!= _thd
.new_pos
.y
||
2680 _thd
.size
.x
!= _thd
.new_size
.x
|| _thd
.size
.y
!= _thd
.new_size
.y
||
2681 _thd
.outersize
.x
!= _thd
.new_outersize
.x
||
2682 _thd
.outersize
.y
!= _thd
.new_outersize
.y
||
2683 _thd
.diagonal
!= new_diagonal
) {
2684 /* Clear the old tile selection? */
2685 if ((_thd
.drawstyle
& HT_DRAG_MASK
) != HT_NONE
) SetSelectionTilesDirty();
2687 _thd
.drawstyle
= new_drawstyle
;
2688 _thd
.pos
= _thd
.new_pos
;
2689 _thd
.size
= _thd
.new_size
;
2690 _thd
.outersize
= _thd
.new_outersize
;
2691 _thd
.diagonal
= new_diagonal
;
2694 /* Draw the new tile selection? */
2695 if ((new_drawstyle
& HT_DRAG_MASK
) != HT_NONE
) SetSelectionTilesDirty();
2700 * Displays the measurement tooltips when selecting multiple tiles
2701 * @param str String to be displayed
2702 * @param paramcount number of params to deal with
2704 static inline void ShowMeasurementTooltips(StringID str
, uint paramcount
)
2706 if (!_settings_client
.gui
.measure_tooltip
) return;
2707 GuiShowTooltips(_thd
.GetCallbackWnd(), str
, TCC_EXIT_VIEWPORT
, paramcount
);
2710 static void HideMeasurementTooltips()
2712 CloseWindowById(WC_TOOLTIPS
, 0);
2715 /** highlighting tiles while only going over them with the mouse */
2716 void VpStartPlaceSizing(TileIndex tile
, ViewportPlaceMethod method
, ViewportDragDropSelectionProcess process
)
2718 _thd
.select_method
= method
;
2719 _thd
.select_proc
= process
;
2720 _thd
.selend
.x
= TileX(tile
) * TILE_SIZE
;
2721 _thd
.selstart
.x
= TileX(tile
) * TILE_SIZE
;
2722 _thd
.selend
.y
= TileY(tile
) * TILE_SIZE
;
2723 _thd
.selstart
.y
= TileY(tile
) * TILE_SIZE
;
2725 /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
2726 * In effect, placement starts from the centre of a tile
2728 if (method
== VPM_X_OR_Y
|| method
== VPM_FIX_X
|| method
== VPM_FIX_Y
) {
2729 _thd
.selend
.x
+= TILE_SIZE
/ 2;
2730 _thd
.selend
.y
+= TILE_SIZE
/ 2;
2731 _thd
.selstart
.x
+= TILE_SIZE
/ 2;
2732 _thd
.selstart
.y
+= TILE_SIZE
/ 2;
2735 HighLightStyle others
= _thd
.place_mode
& ~(HT_DRAG_MASK
| HT_DIR_MASK
);
2736 if ((_thd
.place_mode
& HT_DRAG_MASK
) == HT_RECT
) {
2737 _thd
.place_mode
= HT_SPECIAL
| others
;
2738 _thd
.next_drawstyle
= HT_RECT
| others
;
2739 } else if (_thd
.place_mode
& (HT_RAIL
| HT_LINE
)) {
2740 _thd
.place_mode
= HT_SPECIAL
| others
;
2741 _thd
.next_drawstyle
= _thd
.drawstyle
| others
;
2743 _thd
.place_mode
= HT_SPECIAL
| others
;
2744 _thd
.next_drawstyle
= HT_POINT
| others
;
2746 _special_mouse_mode
= WSM_SIZING
;
2749 /** Drag over the map while holding the left mouse down. */
2750 void VpStartDragging(ViewportDragDropSelectionProcess process
)
2752 _thd
.select_method
= VPM_X_AND_Y
;
2753 _thd
.select_proc
= process
;
2754 _thd
.selstart
.x
= 0;
2755 _thd
.selstart
.y
= 0;
2756 _thd
.next_drawstyle
= HT_RECT
;
2758 _special_mouse_mode
= WSM_DRAGGING
;
2761 void VpSetPlaceSizingLimit(int limit
)
2763 _thd
.sizelimit
= limit
;
2767 * Highlights all tiles between a set of two tiles. Used in dock and tunnel placement
2768 * @param from TileIndex of the first tile to highlight
2769 * @param to TileIndex of the last tile to highlight
2771 void VpSetPresizeRange(TileIndex from
, TileIndex to
)
2773 uint64_t distance
= DistanceManhattan(from
, to
) + 1;
2775 _thd
.selend
.x
= TileX(to
) * TILE_SIZE
;
2776 _thd
.selend
.y
= TileY(to
) * TILE_SIZE
;
2777 _thd
.selstart
.x
= TileX(from
) * TILE_SIZE
;
2778 _thd
.selstart
.y
= TileY(from
) * TILE_SIZE
;
2779 _thd
.next_drawstyle
= HT_RECT
;
2781 /* show measurement only if there is any length to speak of */
2783 SetDParam(0, distance
);
2784 ShowMeasurementTooltips(STR_MEASURE_LENGTH
, 1);
2786 HideMeasurementTooltips();
2790 static void VpStartPreSizing()
2793 _special_mouse_mode
= WSM_PRESIZE
;
2797 * returns information about the 2x1 piece to be build.
2798 * The lower bits (0-3) are the track type.
2800 static HighLightStyle
Check2x1AutoRail(int mode
)
2802 int fxpy
= _tile_fract_coords
.x
+ _tile_fract_coords
.y
;
2803 int sxpy
= (_thd
.selend
.x
& TILE_UNIT_MASK
) + (_thd
.selend
.y
& TILE_UNIT_MASK
);
2804 int fxmy
= _tile_fract_coords
.x
- _tile_fract_coords
.y
;
2805 int sxmy
= (_thd
.selend
.x
& TILE_UNIT_MASK
) - (_thd
.selend
.y
& TILE_UNIT_MASK
);
2808 default: NOT_REACHED();
2809 case 0: // end piece is lower right
2810 if (fxpy
>= 20 && sxpy
<= 12) return HT_DIR_HL
;
2811 if (fxmy
< -3 && sxmy
> 3) return HT_DIR_VR
;
2815 if (fxmy
> 3 && sxmy
< -3) return HT_DIR_VL
;
2816 if (fxpy
<= 12 && sxpy
>= 20) return HT_DIR_HU
;
2820 if (fxmy
> 3 && sxmy
< -3) return HT_DIR_VL
;
2821 if (fxpy
>= 20 && sxpy
<= 12) return HT_DIR_HL
;
2825 if (fxmy
< -3 && sxmy
> 3) return HT_DIR_VR
;
2826 if (fxpy
<= 12 && sxpy
>= 20) return HT_DIR_HU
;
2832 * Check if the direction of start and end tile should be swapped based on
2833 * the dragging-style. Default directions are:
2834 * in the case of a line (HT_RAIL, HT_LINE): DIR_NE, DIR_NW, DIR_N, DIR_E
2835 * in the case of a rect (HT_RECT, HT_POINT): DIR_S, DIR_E
2836 * For example dragging a rectangle area from south to north should be swapped to
2837 * north-south (DIR_S) to obtain the same results with less code. This is what
2838 * the return value signifies.
2839 * @param style HighLightStyle dragging style
2840 * @param start_tile start tile of drag
2841 * @param end_tile end tile of drag
2842 * @return boolean value which when true means start/end should be swapped
2844 static bool SwapDirection(HighLightStyle style
, TileIndex start_tile
, TileIndex end_tile
)
2846 uint start_x
= TileX(start_tile
);
2847 uint start_y
= TileY(start_tile
);
2848 uint end_x
= TileX(end_tile
);
2849 uint end_y
= TileY(end_tile
);
2851 switch (style
& HT_DRAG_MASK
) {
2853 case HT_LINE
: return (end_x
> start_x
|| (end_x
== start_x
&& end_y
> start_y
));
2856 case HT_POINT
: return (end_x
!= start_x
&& end_y
< start_y
);
2857 default: NOT_REACHED();
2864 * Calculates height difference between one tile and another.
2865 * Multiplies the result to suit the standard given by #TILE_HEIGHT_STEP.
2867 * To correctly get the height difference we need the direction we are dragging
2868 * in, as well as with what kind of tool we are dragging. For example a horizontal
2869 * autorail tool that starts in bottom and ends at the top of a tile will need the
2870 * maximum of SW, S and SE, N corners respectively. This is handled by the lookup table below
2871 * See #_tileoffs_by_dir in map.cpp for the direction enums if you can't figure out the values yourself.
2872 * @param style Highlighting style of the drag. This includes direction and style (autorail, rect, etc.)
2873 * @param distance Number of tiles dragged, important for horizontal/vertical drags, ignored for others.
2874 * @param start_tile Start tile of the drag operation.
2875 * @param end_tile End tile of the drag operation.
2876 * @return Height difference between two tiles. The tile measurement tool utilizes this value in its tooltip.
2878 static int CalcHeightdiff(HighLightStyle style
, uint distance
, TileIndex start_tile
, TileIndex end_tile
)
2880 bool swap
= SwapDirection(style
, start_tile
, end_tile
);
2881 uint h0
, h1
; // Start height and end height.
2883 if (start_tile
== end_tile
) return 0;
2884 if (swap
) Swap(start_tile
, end_tile
);
2886 switch (style
& HT_DRAG_MASK
) {
2888 static const TileIndexDiffC heightdiff_area_by_dir
[] = {
2889 /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
2890 /* End */ {0, 1}, /* Dragging east */ {1, 1} // Dragging south
2893 /* In the case of an area we can determine whether we were dragging south or
2894 * east by checking the X-coordinates of the tiles */
2895 byte style_t
= (byte
)(TileX(end_tile
) > TileX(start_tile
));
2896 start_tile
= TILE_ADD(start_tile
, ToTileIndexDiff(heightdiff_area_by_dir
[style_t
]));
2897 end_tile
= TILE_ADD(end_tile
, ToTileIndexDiff(heightdiff_area_by_dir
[2 + style_t
]));
2902 h0
= TileHeight(start_tile
);
2903 h1
= TileHeight(end_tile
);
2905 default: { // All other types, this is mostly only line/autorail
2906 static const HighLightStyle flip_style_direction
[] = {
2907 HT_DIR_X
, HT_DIR_Y
, HT_DIR_HL
, HT_DIR_HU
, HT_DIR_VR
, HT_DIR_VL
2909 static const TileIndexDiffC heightdiff_line_by_dir
[] = {
2910 /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X */ {0, 1}, {1, 1}, // HT_DIR_Y
2911 /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
2912 /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
2914 /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X */ {1, 0}, {0, 0}, // HT_DIR_Y
2915 /* End */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
2916 /* End */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
2919 distance
%= 2; // we're only interested if the distance is even or uneven
2920 style
&= HT_DIR_MASK
;
2922 /* To handle autorail, we do some magic to be able to use a lookup table.
2923 * Firstly if we drag the other way around, we switch start&end, and if needed
2924 * also flip the drag-position. Eg if it was on the left, and the distance is even
2925 * that means the end, which is now the start is on the right */
2926 if (swap
&& distance
== 0) style
= flip_style_direction
[style
];
2928 /* Use lookup table for start-tile based on HighLightStyle direction */
2929 byte style_t
= style
* 2;
2930 assert(style_t
< lengthof(heightdiff_line_by_dir
) - 13);
2931 h0
= TileHeight(TILE_ADD(start_tile
, ToTileIndexDiff(heightdiff_line_by_dir
[style_t
])));
2932 uint ht
= TileHeight(TILE_ADD(start_tile
, ToTileIndexDiff(heightdiff_line_by_dir
[style_t
+ 1])));
2933 h0
= std::max(h0
, ht
);
2935 /* Use lookup table for end-tile based on HighLightStyle direction
2936 * flip around side (lower/upper, left/right) based on distance */
2937 if (distance
== 0) style_t
= flip_style_direction
[style
] * 2;
2938 assert(style_t
< lengthof(heightdiff_line_by_dir
) - 13);
2939 h1
= TileHeight(TILE_ADD(end_tile
, ToTileIndexDiff(heightdiff_line_by_dir
[12 + style_t
])));
2940 ht
= TileHeight(TILE_ADD(end_tile
, ToTileIndexDiff(heightdiff_line_by_dir
[12 + style_t
+ 1])));
2941 h1
= std::max(h1
, ht
);
2946 if (swap
) Swap(h0
, h1
);
2947 return (int)(h1
- h0
) * TILE_HEIGHT_STEP
;
2950 static const StringID measure_strings_length
[] = {STR_NULL
, STR_MEASURE_LENGTH
, STR_MEASURE_LENGTH_HEIGHTDIFF
};
2953 * Check for underflowing the map.
2954 * @param test the variable to test for underflowing
2955 * @param other the other variable to update to keep the line
2956 * @param mult the constant to multiply the difference by for \c other
2958 static void CheckUnderflow(int &test
, int &other
, int mult
)
2960 if (test
>= 0) return;
2962 other
+= mult
* test
;
2967 * Check for overflowing the map.
2968 * @param test the variable to test for overflowing
2969 * @param other the other variable to update to keep the line
2970 * @param max the maximum value for the \c test variable
2971 * @param mult the constant to multiply the difference by for \c other
2973 static void CheckOverflow(int &test
, int &other
, int max
, int mult
)
2975 if (test
<= max
) return;
2977 other
+= mult
* (test
- max
);
2981 /** while dragging */
2982 static void CalcRaildirsDrawstyle(int x
, int y
, int method
)
2986 int dx
= _thd
.selstart
.x
- (_thd
.selend
.x
& ~TILE_UNIT_MASK
);
2987 int dy
= _thd
.selstart
.y
- (_thd
.selend
.y
& ~TILE_UNIT_MASK
);
2988 uint w
= abs(dx
) + TILE_SIZE
;
2989 uint h
= abs(dy
) + TILE_SIZE
;
2991 if (method
& ~(VPM_RAILDIRS
| VPM_SIGNALDIRS
)) {
2992 /* We 'force' a selection direction; first four rail buttons. */
2993 method
&= ~(VPM_RAILDIRS
| VPM_SIGNALDIRS
);
2994 int raw_dx
= _thd
.selstart
.x
- _thd
.selend
.x
;
2995 int raw_dy
= _thd
.selstart
.y
- _thd
.selend
.y
;
2998 b
= HT_LINE
| HT_DIR_Y
;
2999 x
= _thd
.selstart
.x
;
3003 b
= HT_LINE
| HT_DIR_X
;
3004 y
= _thd
.selstart
.y
;
3007 case VPM_FIX_HORIZONTAL
:
3009 /* We are on a straight horizontal line. Determine the 'rail'
3010 * to build based the sub tile location. */
3011 b
= (x
& TILE_UNIT_MASK
) + (y
& TILE_UNIT_MASK
) >= TILE_SIZE
? HT_LINE
| HT_DIR_HL
: HT_LINE
| HT_DIR_HU
;
3013 /* We are not on a straight line. Determine the rail to build
3014 * based on whether we are above or below it. */
3015 b
= dx
+ dy
>= (int)TILE_SIZE
? HT_LINE
| HT_DIR_HU
: HT_LINE
| HT_DIR_HL
;
3017 /* Calculate where a horizontal line through the start point and
3018 * a vertical line from the selected end point intersect and
3019 * use that point as the end point. */
3020 int offset
= (raw_dx
- raw_dy
) / 2;
3021 x
= _thd
.selstart
.x
- (offset
& ~TILE_UNIT_MASK
);
3022 y
= _thd
.selstart
.y
+ (offset
& ~TILE_UNIT_MASK
);
3024 /* 'Build' the last half rail tile if needed */
3025 if ((offset
& TILE_UNIT_MASK
) > (TILE_SIZE
/ 2)) {
3026 if (dx
+ dy
>= (int)TILE_SIZE
) {
3027 x
+= (dx
+ dy
< 0) ? (int)TILE_SIZE
: -(int)TILE_SIZE
;
3029 y
+= (dx
+ dy
< 0) ? (int)TILE_SIZE
: -(int)TILE_SIZE
;
3033 /* Make sure we do not overflow the map! */
3034 CheckUnderflow(x
, y
, 1);
3035 CheckUnderflow(y
, x
, 1);
3036 CheckOverflow(x
, y
, (Map::MaxX() - 1) * TILE_SIZE
, 1);
3037 CheckOverflow(y
, x
, (Map::MaxY() - 1) * TILE_SIZE
, 1);
3038 assert(x
>= 0 && y
>= 0 && x
<= (int)(Map::MaxX() * TILE_SIZE
) && y
<= (int)(Map::MaxY() * TILE_SIZE
));
3042 case VPM_FIX_VERTICAL
:
3044 /* We are on a straight vertical line. Determine the 'rail'
3045 * to build based the sub tile location. */
3046 b
= (x
& TILE_UNIT_MASK
) > (y
& TILE_UNIT_MASK
) ? HT_LINE
| HT_DIR_VL
: HT_LINE
| HT_DIR_VR
;
3048 /* We are not on a straight line. Determine the rail to build
3049 * based on whether we are left or right from it. */
3050 b
= dx
< dy
? HT_LINE
| HT_DIR_VL
: HT_LINE
| HT_DIR_VR
;
3052 /* Calculate where a vertical line through the start point and
3053 * a horizontal line from the selected end point intersect and
3054 * use that point as the end point. */
3055 int offset
= (raw_dx
+ raw_dy
+ (int)TILE_SIZE
) / 2;
3056 x
= _thd
.selstart
.x
- (offset
& ~TILE_UNIT_MASK
);
3057 y
= _thd
.selstart
.y
- (offset
& ~TILE_UNIT_MASK
);
3059 /* 'Build' the last half rail tile if needed */
3060 if ((offset
& TILE_UNIT_MASK
) > (TILE_SIZE
/ 2)) {
3062 y
+= (dx
> dy
) ? (int)TILE_SIZE
: -(int)TILE_SIZE
;
3064 x
+= (dx
< dy
) ? (int)TILE_SIZE
: -(int)TILE_SIZE
;
3068 /* Make sure we do not overflow the map! */
3069 CheckUnderflow(x
, y
, -1);
3070 CheckUnderflow(y
, x
, -1);
3071 CheckOverflow(x
, y
, (Map::MaxX() - 1) * TILE_SIZE
, -1);
3072 CheckOverflow(y
, x
, (Map::MaxY() - 1) * TILE_SIZE
, -1);
3073 assert(x
>= 0 && y
>= 0 && x
<= (int)(Map::MaxX() * TILE_SIZE
) && y
<= (int)(Map::MaxY() * TILE_SIZE
));
3080 } else if (TileVirtXY(_thd
.selstart
.x
, _thd
.selstart
.y
) == TileVirtXY(x
, y
)) { // check if we're only within one tile
3081 if (method
& VPM_RAILDIRS
) {
3082 b
= GetAutorailHT(x
, y
);
3083 } else { // rect for autosignals on one tile
3086 } else if (h
== TILE_SIZE
) { // Is this in X direction?
3087 if (dx
== (int)TILE_SIZE
) { // 2x1 special handling
3088 b
= (Check2x1AutoRail(3)) | HT_LINE
;
3089 } else if (dx
== -(int)TILE_SIZE
) {
3090 b
= (Check2x1AutoRail(2)) | HT_LINE
;
3092 b
= HT_LINE
| HT_DIR_X
;
3094 y
= _thd
.selstart
.y
;
3095 } else if (w
== TILE_SIZE
) { // Or Y direction?
3096 if (dy
== (int)TILE_SIZE
) { // 2x1 special handling
3097 b
= (Check2x1AutoRail(1)) | HT_LINE
;
3098 } else if (dy
== -(int)TILE_SIZE
) { // 2x1 other direction
3099 b
= (Check2x1AutoRail(0)) | HT_LINE
;
3101 b
= HT_LINE
| HT_DIR_Y
;
3103 x
= _thd
.selstart
.x
;
3104 } else if (w
> h
* 2) { // still count as x dir?
3105 b
= HT_LINE
| HT_DIR_X
;
3106 y
= _thd
.selstart
.y
;
3107 } else if (h
> w
* 2) { // still count as y dir?
3108 b
= HT_LINE
| HT_DIR_Y
;
3109 x
= _thd
.selstart
.x
;
3110 } else { // complicated direction
3112 _thd
.selend
.x
= _thd
.selend
.x
& ~TILE_UNIT_MASK
;
3113 _thd
.selend
.y
= _thd
.selend
.y
& ~TILE_UNIT_MASK
;
3116 if (x
> _thd
.selstart
.x
) {
3117 if (y
> _thd
.selstart
.y
) {
3120 b
= (x
& TILE_UNIT_MASK
) > (y
& TILE_UNIT_MASK
) ? HT_LINE
| HT_DIR_VL
: HT_LINE
| HT_DIR_VR
;
3121 } else if (d
>= 0) {
3122 x
= _thd
.selstart
.x
+ h
;
3123 b
= HT_LINE
| HT_DIR_VL
;
3125 y
= _thd
.selstart
.y
+ w
;
3126 b
= HT_LINE
| HT_DIR_VR
;
3131 b
= (x
& TILE_UNIT_MASK
) + (y
& TILE_UNIT_MASK
) >= TILE_SIZE
? HT_LINE
| HT_DIR_HL
: HT_LINE
| HT_DIR_HU
;
3132 } else if (d
>= 0) {
3133 x
= _thd
.selstart
.x
+ h
;
3134 b
= HT_LINE
| HT_DIR_HL
;
3136 y
= _thd
.selstart
.y
- w
;
3137 b
= HT_LINE
| HT_DIR_HU
;
3141 if (y
> _thd
.selstart
.y
) {
3144 b
= (x
& TILE_UNIT_MASK
) + (y
& TILE_UNIT_MASK
) >= TILE_SIZE
? HT_LINE
| HT_DIR_HL
: HT_LINE
| HT_DIR_HU
;
3145 } else if (d
>= 0) {
3146 x
= _thd
.selstart
.x
- h
;
3147 b
= HT_LINE
| HT_DIR_HU
;
3149 y
= _thd
.selstart
.y
+ w
;
3150 b
= HT_LINE
| HT_DIR_HL
;
3155 b
= (x
& TILE_UNIT_MASK
) > (y
& TILE_UNIT_MASK
) ? HT_LINE
| HT_DIR_VL
: HT_LINE
| HT_DIR_VR
;
3156 } else if (d
>= 0) {
3157 x
= _thd
.selstart
.x
- h
;
3158 b
= HT_LINE
| HT_DIR_VR
;
3160 y
= _thd
.selstart
.y
- w
;
3161 b
= HT_LINE
| HT_DIR_VL
;
3167 if (_settings_client
.gui
.measure_tooltip
) {
3168 TileIndex t0
= TileVirtXY(_thd
.selstart
.x
, _thd
.selstart
.y
);
3169 TileIndex t1
= TileVirtXY(x
, y
);
3170 uint distance
= DistanceManhattan(t0
, t1
) + 1;
3173 if (distance
!= 1) {
3174 int heightdiff
= CalcHeightdiff(b
, distance
, t0
, t1
);
3175 /* If we are showing a tooltip for horizontal or vertical drags,
3176 * 2 tiles have a length of 1. To bias towards the ceiling we add
3177 * one before division. It feels more natural to count 3 lengths as 2 */
3178 if ((b
& HT_DIR_MASK
) != HT_DIR_X
&& (b
& HT_DIR_MASK
) != HT_DIR_Y
) {
3179 distance
= CeilDiv(distance
, 2);
3182 SetDParam(index
++, distance
);
3183 if (heightdiff
!= 0) SetDParam(index
++, heightdiff
);
3186 ShowMeasurementTooltips(measure_strings_length
[index
], index
);
3191 _thd
.next_drawstyle
= b
;
3195 * Selects tiles while dragging
3196 * @param x X coordinate of end of selection
3197 * @param y Y coordinate of end of selection
3198 * @param method modifies the way tiles are selected. Possible
3199 * methods are VPM_* in viewport.h
3201 void VpSelectTilesWithMethod(int x
, int y
, ViewportPlaceMethod method
)
3204 HighLightStyle style
;
3211 /* Special handling of drag in any (8-way) direction */
3212 if (method
& (VPM_RAILDIRS
| VPM_SIGNALDIRS
)) {
3215 CalcRaildirsDrawstyle(x
, y
, method
);
3219 /* Needed so level-land is placed correctly */
3220 if ((_thd
.next_drawstyle
& HT_DRAG_MASK
) == HT_POINT
) {
3225 sx
= _thd
.selstart
.x
;
3226 sy
= _thd
.selstart
.y
;
3231 case VPM_X_OR_Y
: // drag in X or Y direction
3232 if (abs(sy
- y
) < abs(sx
- x
)) {
3239 goto calc_heightdiff_single_direction
;
3241 case VPM_X_LIMITED
: // Drag in X direction (limited size).
3242 limit
= (_thd
.sizelimit
- 1) * TILE_SIZE
;
3245 case VPM_FIX_X
: // drag in Y direction
3248 goto calc_heightdiff_single_direction
;
3250 case VPM_Y_LIMITED
: // Drag in Y direction (limited size).
3251 limit
= (_thd
.sizelimit
- 1) * TILE_SIZE
;
3254 case VPM_FIX_Y
: // drag in X direction
3258 calc_heightdiff_single_direction
:;
3260 x
= sx
+ Clamp(x
- sx
, -limit
, limit
);
3261 y
= sy
+ Clamp(y
- sy
, -limit
, limit
);
3263 if (_settings_client
.gui
.measure_tooltip
) {
3264 TileIndex t0
= TileVirtXY(sx
, sy
);
3265 TileIndex t1
= TileVirtXY(x
, y
);
3266 uint distance
= DistanceManhattan(t0
, t1
) + 1;
3269 if (distance
!= 1) {
3270 /* With current code passing a HT_LINE style to calculate the height
3271 * difference is enough. However if/when a point-tool is created
3272 * with this method, function should be called with new_style (below)
3273 * instead of HT_LINE | style case HT_POINT is handled specially
3274 * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
3275 int heightdiff
= CalcHeightdiff(HT_LINE
| style
, 0, t0
, t1
);
3277 SetDParam(index
++, distance
);
3278 if (heightdiff
!= 0) SetDParam(index
++, heightdiff
);
3281 ShowMeasurementTooltips(measure_strings_length
[index
], index
);
3285 case VPM_X_AND_Y_LIMITED
: // Drag an X by Y constrained rect area.
3286 limit
= (_thd
.sizelimit
- 1) * TILE_SIZE
;
3287 x
= sx
+ Clamp(x
- sx
, -limit
, limit
);
3288 y
= sy
+ Clamp(y
- sy
, -limit
, limit
);
3291 case VPM_X_AND_Y
: // drag an X by Y area
3292 if (_settings_client
.gui
.measure_tooltip
) {
3293 static const StringID measure_strings_area
[] = {
3294 STR_NULL
, STR_NULL
, STR_MEASURE_AREA
, STR_MEASURE_AREA_HEIGHTDIFF
3297 TileIndex t0
= TileVirtXY(sx
, sy
);
3298 TileIndex t1
= TileVirtXY(x
, y
);
3299 uint dx
= Delta(TileX(t0
), TileX(t1
)) + 1;
3300 uint dy
= Delta(TileY(t0
), TileY(t1
)) + 1;
3303 /* If dragging an area (eg dynamite tool) and it is actually a single
3304 * row/column, change the type to 'line' to get proper calculation for height */
3305 style
= (HighLightStyle
)_thd
.next_drawstyle
;
3306 if (_thd
.IsDraggingDiagonal()) {
3307 /* Determine the "area" of the diagonal dragged selection.
3308 * We assume the area is the number of tiles along the X
3309 * edge and the number of tiles along the Y edge. However,
3310 * multiplying these two numbers does not give the exact
3311 * number of tiles; basically we are counting the black
3312 * squares on a chess board and ignore the white ones to
3313 * make the tile counts at the edges match up. There is no
3314 * other way to make a proper count though.
3316 * First convert to the rotated coordinate system. */
3317 int dist_x
= TileX(t0
) - TileX(t1
);
3318 int dist_y
= TileY(t0
) - TileY(t1
);
3319 int a_max
= dist_x
+ dist_y
;
3320 int b_max
= dist_y
- dist_x
;
3322 /* Now determine the size along the edge, but due to the
3323 * chess board principle this counts double. */
3324 a_max
= abs(a_max
+ (a_max
> 0 ? 2 : -2)) / 2;
3325 b_max
= abs(b_max
+ (b_max
> 0 ? 2 : -2)) / 2;
3327 /* We get a 1x1 on normal 2x1 rectangles, due to it being
3328 * a seen as two sides. As the result for actual building
3329 * will be the same as non-diagonal dragging revert to that
3330 * behaviour to give it a more normally looking size. */
3331 if (a_max
!= 1 || b_max
!= 1) {
3335 } else if (style
& HT_RECT
) {
3337 style
= HT_LINE
| HT_DIR_Y
;
3338 } else if (dy
== 1) {
3339 style
= HT_LINE
| HT_DIR_X
;
3343 if (dx
!= 1 || dy
!= 1) {
3344 int heightdiff
= CalcHeightdiff(style
, 0, t0
, t1
);
3346 SetDParam(index
++, dx
- (style
& HT_POINT
? 1 : 0));
3347 SetDParam(index
++, dy
- (style
& HT_POINT
? 1 : 0));
3348 if (heightdiff
!= 0) SetDParam(index
++, heightdiff
);
3351 ShowMeasurementTooltips(measure_strings_area
[index
], index
);
3355 default: NOT_REACHED();
3363 * Handle the mouse while dragging for placement/resizing.
3364 * @return State of handling the event.
3366 EventState
VpHandlePlaceSizingDrag()
3368 if (_special_mouse_mode
!= WSM_SIZING
&& _special_mouse_mode
!= WSM_DRAGGING
) return ES_NOT_HANDLED
;
3370 /* stop drag mode if the window has been closed */
3371 Window
*w
= _thd
.GetCallbackWnd();
3373 ResetObjectToPlace();
3377 /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
3378 if (_left_button_down
) {
3379 if (_special_mouse_mode
== WSM_DRAGGING
) {
3380 /* Only register a drag event when the mouse moved. */
3381 if (_thd
.new_pos
.x
== _thd
.selstart
.x
&& _thd
.new_pos
.y
== _thd
.selstart
.y
) return ES_HANDLED
;
3382 _thd
.selstart
.x
= _thd
.new_pos
.x
;
3383 _thd
.selstart
.y
= _thd
.new_pos
.y
;
3386 w
->OnPlaceDrag(_thd
.select_method
, _thd
.select_proc
, GetTileBelowCursor());
3390 /* Mouse button released. */
3391 _special_mouse_mode
= WSM_NONE
;
3392 if (_special_mouse_mode
== WSM_DRAGGING
) return ES_HANDLED
;
3394 /* Keep the selected tool, but reset it to the original mode. */
3395 HighLightStyle others
= _thd
.place_mode
& ~(HT_DRAG_MASK
| HT_DIR_MASK
);
3396 if ((_thd
.next_drawstyle
& HT_DRAG_MASK
) == HT_RECT
) {
3397 _thd
.place_mode
= HT_RECT
| others
;
3398 } else if (_thd
.select_method
& VPM_SIGNALDIRS
) {
3399 _thd
.place_mode
= HT_RECT
| others
;
3400 } else if (_thd
.select_method
& VPM_RAILDIRS
) {
3401 _thd
.place_mode
= (_thd
.select_method
& ~VPM_RAILDIRS
) ? _thd
.next_drawstyle
: (HT_RAIL
| others
);
3403 _thd
.place_mode
= HT_POINT
| others
;
3405 SetTileSelectSize(1, 1);
3407 HideMeasurementTooltips();
3408 w
->OnPlaceMouseUp(_thd
.select_method
, _thd
.select_proc
, _thd
.selend
, TileVirtXY(_thd
.selstart
.x
, _thd
.selstart
.y
), TileVirtXY(_thd
.selend
.x
, _thd
.selend
.y
));
3414 * Change the cursor and mouse click/drag handling to a mode for performing special operations like tile area selection, object placement, etc.
3415 * @param icon New shape of the mouse cursor.
3416 * @param pal Palette to use.
3417 * @param mode Mode to perform.
3418 * @param w %Window requesting the mode change.
3420 void SetObjectToPlaceWnd(CursorID icon
, PaletteID pal
, HighLightStyle mode
, Window
*w
)
3422 SetObjectToPlace(icon
, pal
, mode
, w
->window_class
, w
->window_number
);
3425 #include "table/animcursors.h"
3428 * Change the cursor and mouse click/drag handling to a mode for performing special operations like tile area selection, object placement, etc.
3429 * @param icon New shape of the mouse cursor.
3430 * @param pal Palette to use.
3431 * @param mode Mode to perform.
3432 * @param window_class %Window class of the window requesting the mode change.
3433 * @param window_num Number of the window in its class requesting the mode change.
3435 void SetObjectToPlace(CursorID icon
, PaletteID pal
, HighLightStyle mode
, WindowClass window_class
, WindowNumber window_num
)
3437 if (_thd
.window_class
!= WC_INVALID
) {
3438 /* Undo clicking on button and drag & drop */
3439 Window
*w
= _thd
.GetCallbackWnd();
3440 /* Call the abort function, but set the window class to something
3441 * that will never be used to avoid infinite loops. Setting it to
3442 * the 'next' window class must not be done because recursion into
3443 * this function might in some cases reset the newly set object to
3444 * place or not properly reset the original selection. */
3445 _thd
.window_class
= WC_INVALID
;
3447 w
->OnPlaceObjectAbort();
3448 HideMeasurementTooltips();
3452 /* Mark the old selection dirty, in case the selection shape or colour changes */
3453 if ((_thd
.drawstyle
& HT_DRAG_MASK
) != HT_NONE
) SetSelectionTilesDirty();
3455 SetTileSelectSize(1, 1);
3457 _thd
.make_square_red
= false;
3459 if (mode
== HT_DRAG
) { // HT_DRAG is for dragdropping trains in the depot window
3461 _special_mouse_mode
= WSM_DRAGDROP
;
3463 _special_mouse_mode
= WSM_NONE
;
3466 _thd
.place_mode
= mode
;
3467 _thd
.window_class
= window_class
;
3468 _thd
.window_number
= window_num
;
3470 if ((mode
& HT_DRAG_MASK
) == HT_SPECIAL
) { // special tools, like tunnels or docks start with presizing mode
3474 if ((icon
& ANIMCURSOR_FLAG
) != 0) {
3475 SetAnimatedMouseCursor(_animcursors
[icon
& ~ANIMCURSOR_FLAG
]);
3477 SetMouseCursor(icon
, pal
);
3482 /** Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows). */
3483 void ResetObjectToPlace()
3485 SetObjectToPlace(SPR_CURSOR_MOUSE
, PAL_NONE
, HT_NONE
, WC_MAIN_WINDOW
, 0);
3488 Point
GetViewportStationMiddle(const Viewport
*vp
, const Station
*st
)
3490 int x
= TileX(st
->xy
) * TILE_SIZE
;
3491 int y
= TileY(st
->xy
) * TILE_SIZE
;
3492 int z
= GetSlopePixelZ(Clamp(x
, 0, Map::SizeX() * TILE_SIZE
- 1), Clamp(y
, 0, Map::SizeY() * TILE_SIZE
- 1));
3494 Point p
= RemapCoords(x
, y
, z
);
3495 p
.x
= UnScaleByZoom(p
.x
- vp
->virtual_left
, vp
->zoom
) + vp
->left
;
3496 p
.y
= UnScaleByZoom(p
.y
- vp
->virtual_top
, vp
->zoom
) + vp
->top
;
3500 /** Helper class for getting the best sprite sorter. */
3501 struct ViewportSSCSS
{
3502 VpSorterChecker fct_checker
; ///< The check function.
3503 VpSpriteSorter fct_sorter
; ///< The sorting function.
3506 /** List of sorters ordered from best to worst. */
3507 static ViewportSSCSS _vp_sprite_sorters
[] = {
3509 { &ViewportSortParentSpritesSSE41Checker
, &ViewportSortParentSpritesSSE41
},
3511 { &ViewportSortParentSpritesChecker
, &ViewportSortParentSprites
}
3514 /** Choose the "best" sprite sorter and set _vp_sprite_sorter. */
3515 void InitializeSpriteSorter()
3517 for (uint i
= 0; i
< lengthof(_vp_sprite_sorters
); i
++) {
3518 if (_vp_sprite_sorters
[i
].fct_checker()) {
3519 _vp_sprite_sorter
= _vp_sprite_sorters
[i
].fct_sorter
;
3523 assert(_vp_sprite_sorter
!= nullptr);
3527 * Scroll players main viewport.
3528 * @param flags type of operation
3529 * @param tile tile to center viewport on
3530 * @param target ViewportScrollTarget of scroll target
3531 * @param ref company or client id depending on the target
3532 * @return the cost of this operation or an error
3534 CommandCost
CmdScrollViewport(DoCommandFlag flags
, TileIndex tile
, ViewportScrollTarget target
, uint32_t ref
)
3536 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
3541 if (_local_company
!= (CompanyID
)ref
) return CommandCost();
3544 if (_network_own_client_id
!= (ClientID
)ref
) return CommandCost();
3550 if (flags
& DC_EXEC
) {
3551 ResetObjectToPlace();
3552 ScrollMainWindowToTile(tile
);
3554 return CommandCost();
3557 void MarkCatchmentTilesDirty()
3559 if (_viewport_highlight_town
!= nullptr) {
3560 MarkWholeScreenDirty();
3563 if (_viewport_highlight_station
!= nullptr) {
3564 if (_viewport_highlight_station
->catchment_tiles
.tile
== INVALID_TILE
) {
3565 MarkWholeScreenDirty();
3566 _viewport_highlight_station
= nullptr;
3568 BitmapTileIterator
it(_viewport_highlight_station
->catchment_tiles
);
3569 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
3570 MarkTileDirtyByTile(tile
);
3574 if (_viewport_highlight_waypoint
!= nullptr) {
3575 if (!_viewport_highlight_waypoint
->IsInUse()) {
3576 _viewport_highlight_waypoint
= nullptr;
3578 MarkWholeScreenDirty();
3582 static void SetWindowDirtyForViewportCatchment()
3584 if (_viewport_highlight_station
!= nullptr) SetWindowDirty(WC_STATION_VIEW
, _viewport_highlight_station
->index
);
3585 if (_viewport_highlight_waypoint
!= nullptr) SetWindowDirty(WC_WAYPOINT_VIEW
, _viewport_highlight_waypoint
->index
);
3586 if (_viewport_highlight_town
!= nullptr) SetWindowDirty(WC_TOWN_VIEW
, _viewport_highlight_town
->index
);
3589 static void ClearViewportCatchment()
3591 MarkCatchmentTilesDirty();
3592 _viewport_highlight_station
= nullptr;
3593 _viewport_highlight_waypoint
= nullptr;
3594 _viewport_highlight_town
= nullptr;
3598 * Select or deselect station for coverage area highlight.
3599 * Selecting a station will deselect a town.
3600 * @param *st Station in question
3601 * @param sel Select or deselect given station
3603 void SetViewportCatchmentStation(const Station
*st
, bool sel
)
3605 SetWindowDirtyForViewportCatchment();
3606 if (sel
&& _viewport_highlight_station
!= st
) {
3607 ClearViewportCatchment();
3608 _viewport_highlight_station
= st
;
3609 MarkCatchmentTilesDirty();
3610 } else if (!sel
&& _viewport_highlight_station
== st
) {
3611 MarkCatchmentTilesDirty();
3612 _viewport_highlight_station
= nullptr;
3614 if (_viewport_highlight_station
!= nullptr) SetWindowDirty(WC_STATION_VIEW
, _viewport_highlight_station
->index
);
3618 * Select or deselect waypoint for coverage area highlight.
3619 * Selecting a waypoint will deselect a town.
3620 * @param *wp Waypoint in question
3621 * @param sel Select or deselect given waypoint
3623 void SetViewportCatchmentWaypoint(const Waypoint
*wp
, bool sel
)
3625 SetWindowDirtyForViewportCatchment();
3626 if (sel
&& _viewport_highlight_waypoint
!= wp
) {
3627 ClearViewportCatchment();
3628 _viewport_highlight_waypoint
= wp
;
3629 MarkCatchmentTilesDirty();
3630 } else if (!sel
&& _viewport_highlight_waypoint
== wp
) {
3631 MarkCatchmentTilesDirty();
3632 _viewport_highlight_waypoint
= nullptr;
3634 if (_viewport_highlight_waypoint
!= nullptr) SetWindowDirty(WC_WAYPOINT_VIEW
, _viewport_highlight_waypoint
->index
);
3638 * Select or deselect town for coverage area highlight.
3639 * Selecting a town will deselect a station.
3640 * @param *t Town in question
3641 * @param sel Select or deselect given town
3643 void SetViewportCatchmentTown(const Town
*t
, bool sel
)
3645 SetWindowDirtyForViewportCatchment();
3646 if (sel
&& _viewport_highlight_town
!= t
) {
3647 ClearViewportCatchment();
3648 _viewport_highlight_town
= t
;
3649 MarkWholeScreenDirty();
3650 } else if (!sel
&& _viewport_highlight_town
== t
) {
3651 _viewport_highlight_town
= nullptr;
3652 MarkWholeScreenDirty();
3654 if (_viewport_highlight_town
!= nullptr) SetWindowDirty(WC_TOWN_VIEW
, _viewport_highlight_town
->index
);