Add support for deleted functions
[openttd/fttd.git] / src / viewport.cpp
blobc84167e9bd9698b281fb4608a64a615166d680ea
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /**
11 * @file viewport.cpp Handling of all viewports.
13 * \verbatim
14 * The in-game coordinate system looks like this *
15 * *
16 * ^ Z *
17 * | *
18 * | *
19 * | *
20 * | *
21 * / \ *
22 * / \ *
23 * / \ *
24 * / \ *
25 * X < > Y *
26 * \endverbatim
29 #include "stdafx.h"
30 #include "map/zoneheight.h"
31 #include "map/slope.h"
32 #include "landscape.h"
33 #include "viewport_func.h"
34 #include "station_base.h"
35 #include "waypoint_base.h"
36 #include "town.h"
37 #include "signs_base.h"
38 #include "signs_func.h"
39 #include "vehicle_base.h"
40 #include "vehicle_gui.h"
41 #include "blitter/factory.hpp"
42 #include "strings_func.h"
43 #include "zoom_func.h"
44 #include "vehicle_func.h"
45 #include "company_func.h"
46 #include "waypoint_func.h"
47 #include "window_func.h"
48 #include "tilehighlight_func.h"
49 #include "window_gui.h"
50 #include "linkgraph/linkgraph_gui.h"
51 #include "clear_func.h"
52 #include "station_func.h"
53 #include "viewport_sprite_sorter.h"
55 #include "table/strings.h"
56 #include "table/palettes.h"
58 Point _tile_fract_coords;
60 struct StringSpriteToDraw {
61 StringID string;
62 Colours colour;
63 int32 x;
64 int32 y;
65 uint64 params[2];
66 uint16 width;
69 struct TileSpriteToDraw {
70 SpriteID image;
71 PaletteID pal;
72 const SubSprite *sub; ///< only draw a rectangular part of the sprite
73 int32 x; ///< screen X coordinate of sprite
74 int32 y; ///< screen Y coordinate of sprite
77 struct ChildScreenSpriteToDraw {
78 SpriteID image;
79 PaletteID pal;
80 const SubSprite *sub; ///< only draw a rectangular part of the sprite
81 int32 x;
82 int32 y;
83 int next; ///< next child to draw (-1 at the end)
86 /** Enumeration of multi-part foundations */
87 enum FoundationPart {
88 FOUNDATION_PART_NONE = 0xFF, ///< Neither foundation nor groundsprite drawn yet.
89 FOUNDATION_PART_NORMAL = 0, ///< First part (normal foundation or no foundation)
90 FOUNDATION_PART_HALFTILE = 1, ///< Second part (halftile foundation)
91 FOUNDATION_PART_END
94 /**
95 * Mode of "sprite combining"
96 * @see StartSpriteCombine
98 enum SpriteCombineMode {
99 SPRITE_COMBINE_NONE, ///< Every #AddSortableSpriteToDraw start its own bounding box
100 SPRITE_COMBINE_PENDING, ///< %Sprite combining will start with the next unclipped sprite.
101 SPRITE_COMBINE_ACTIVE, ///< %Sprite combining is active. #AddSortableSpriteToDraw outputs child sprites.
104 typedef SmallVector<TileSpriteToDraw, 64> TileSpriteToDrawVector;
105 typedef SmallVector<StringSpriteToDraw, 4> StringSpriteToDrawVector;
106 typedef SmallVector<ParentSpriteToDraw, 64> ParentSpriteToDrawVector;
107 typedef SmallVector<ChildScreenSpriteToDraw, 16> ChildScreenSpriteToDrawVector;
109 /** Data structure storing rendering information */
110 struct ViewportDrawer {
111 DrawPixelInfo dpi;
113 StringSpriteToDrawVector string_sprites_to_draw;
114 TileSpriteToDrawVector tile_sprites_to_draw;
115 ParentSpriteToDrawVector parent_sprites_to_draw;
116 ParentSpriteToSortVector parent_sprites_to_sort; ///< Parent sprite pointer array used for sorting
117 ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
119 int *last_child;
121 SpriteCombineMode combine_sprites; ///< Current mode of "sprite combining". @see StartSpriteCombine
123 int foundation[FOUNDATION_PART_END]; ///< Foundation sprites (index into parent_sprites_to_draw).
124 FoundationPart foundation_part; ///< Currently active foundation for ground sprite drawing.
125 int *last_foundation_child[FOUNDATION_PART_END]; ///< Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw)
126 Point foundation_offset[FOUNDATION_PART_END]; ///< Pixel offset for ground sprites on the foundations.
129 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom);
131 static ViewportDrawer _vd;
133 TileHighlightData _thd;
134 static TileInfo *_cur_ti;
135 bool _draw_bounding_boxes = false;
136 bool _draw_dirty_blocks = false;
137 uint _dirty_block_colour = 0;
138 static VpSpriteSorter _vp_sprite_sorter = NULL;
140 static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
142 Point p = RemapCoords(x, y, z);
143 p.x -= vp->virtual_width / 2;
144 p.y -= vp->virtual_height / 2;
145 return p;
148 void DeleteWindowViewport(Window *w)
150 if (w->viewport == NULL) return;
152 delete w->viewport->overlay;
153 free(w->viewport);
154 w->viewport = NULL;
158 * Initialize viewport of the window for use.
159 * @param w Window to use/display the viewport in
160 * @param x Offset of left edge of viewport with respect to left edge window \a w
161 * @param y Offset of top edge of viewport with respect to top edge window \a w
162 * @param width Width of the viewport
163 * @param height Height of the viewport
164 * @param follow_flags Flags controlling the viewport.
165 * - If bit 31 is set, the lower 20 bits are the vehicle that the viewport should follow.
166 * - If bit 31 is clear, it is a #TileIndex.
167 * @param zoom Zoomlevel to display
169 void InitializeWindowViewport(Window *w, int x, int y,
170 int width, int height, uint32 follow_flags, ZoomLevel zoom)
172 assert(w->viewport == NULL);
174 ViewportData *vp = CallocT<ViewportData>(1);
176 vp->left = x + w->left;
177 vp->top = y + w->top;
178 vp->width = width;
179 vp->height = height;
181 vp->zoom = static_cast<ZoomLevel>(Clamp(zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
183 vp->virtual_width = ScaleByZoom(width, zoom);
184 vp->virtual_height = ScaleByZoom(height, zoom);
186 Point pt;
188 if (follow_flags & 0x80000000) {
189 const Vehicle *veh;
191 vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
192 veh = Vehicle::Get(vp->follow_vehicle);
193 pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
194 } else {
195 uint x = TileX(follow_flags) * TILE_SIZE;
196 uint y = TileY(follow_flags) * TILE_SIZE;
198 vp->follow_vehicle = INVALID_VEHICLE;
199 pt = MapXYZToViewport(vp, x, y, GetSlopePixelZ(x, y));
202 vp->scrollpos_x = pt.x;
203 vp->scrollpos_y = pt.y;
204 vp->dest_scrollpos_x = pt.x;
205 vp->dest_scrollpos_y = pt.y;
207 vp->overlay = NULL;
209 w->viewport = vp;
210 vp->virtual_left = 0;//pt.x;
211 vp->virtual_top = 0;//pt.y;
214 static Point _vp_move_offs;
216 static void DoSetViewportPosition(const Window *w, int left, int top, int width, int height)
218 FOR_ALL_WINDOWS_FROM_BACK_FROM(w, w) {
219 if (left + width > w->left &&
220 w->left + w->width > left &&
221 top + height > w->top &&
222 w->top + w->height > top) {
224 if (left < w->left) {
225 DoSetViewportPosition(w, left, top, w->left - left, height);
226 DoSetViewportPosition(w, left + (w->left - left), top, width - (w->left - left), height);
227 return;
230 if (left + width > w->left + w->width) {
231 DoSetViewportPosition(w, left, top, (w->left + w->width - left), height);
232 DoSetViewportPosition(w, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
233 return;
236 if (top < w->top) {
237 DoSetViewportPosition(w, left, top, width, (w->top - top));
238 DoSetViewportPosition(w, left, top + (w->top - top), width, height - (w->top - top));
239 return;
242 if (top + height > w->top + w->height) {
243 DoSetViewportPosition(w, left, top, width, (w->top + w->height - top));
244 DoSetViewportPosition(w, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
245 return;
248 return;
253 int xo = _vp_move_offs.x;
254 int yo = _vp_move_offs.y;
256 if (abs(xo) >= width || abs(yo) >= height) {
257 /* fully_outside */
258 RedrawScreenRect(left, top, left + width, top + height);
259 return;
262 GfxScroll(left, top, width, height, xo, yo);
264 if (xo > 0) {
265 RedrawScreenRect(left, top, xo + left, top + height);
266 left += xo;
267 width -= xo;
268 } else if (xo < 0) {
269 RedrawScreenRect(left + width + xo, top, left + width, top + height);
270 width += xo;
273 if (yo > 0) {
274 RedrawScreenRect(left, top, width + left, top + yo);
275 } else if (yo < 0) {
276 RedrawScreenRect(left, top + height + yo, width + left, top + height);
281 static void SetViewportPosition(Window *w, int x, int y)
283 ViewPort *vp = w->viewport;
284 int old_left = vp->virtual_left;
285 int old_top = vp->virtual_top;
286 int i;
287 int left, top, width, height;
289 vp->virtual_left = x;
290 vp->virtual_top = y;
292 /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
293 * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
295 old_left = UnScaleByZoomLower(old_left, vp->zoom);
296 old_top = UnScaleByZoomLower(old_top, vp->zoom);
297 x = UnScaleByZoomLower(x, vp->zoom);
298 y = UnScaleByZoomLower(y, vp->zoom);
300 old_left -= x;
301 old_top -= y;
303 if (old_top == 0 && old_left == 0) return;
305 _vp_move_offs.x = old_left;
306 _vp_move_offs.y = old_top;
308 left = vp->left;
309 top = vp->top;
310 width = vp->width;
311 height = vp->height;
313 if (left < 0) {
314 width += left;
315 left = 0;
318 i = left + width - _screen.width;
319 if (i >= 0) width -= i;
321 if (width > 0) {
322 if (top < 0) {
323 height += top;
324 top = 0;
327 i = top + height - _screen.height;
328 if (i >= 0) height -= i;
330 if (height > 0) DoSetViewportPosition(w->z_front, left, top, width, height);
335 * Is a xy position inside the viewport of the window?
336 * @param w Window to examine its viewport
337 * @param x X coordinate of the xy position
338 * @param y Y coordinate of the xy position
339 * @return Pointer to the viewport if the xy position is in the viewport of the window,
340 * otherwise \c NULL is returned.
342 ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
344 ViewPort *vp = w->viewport;
346 if (vp != NULL &&
347 IsInsideMM(x, vp->left, vp->left + vp->width) &&
348 IsInsideMM(y, vp->top, vp->top + vp->height))
349 return vp;
351 return NULL;
355 * Translate screen coordinate in a viewport to a tile coordinate
356 * @param vp Viewport that contains the (\a x, \a y) screen coordinate
357 * @param x Screen x coordinate
358 * @param y Screen y coordinate
359 * @return Tile coordinate
361 static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
363 Point pt;
364 int a, b;
365 int z;
367 if ( (uint)(x -= vp->left) >= (uint)vp->width ||
368 (uint)(y -= vp->top) >= (uint)vp->height) {
369 Point pt = {-1, -1};
370 return pt;
373 x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> (2 + ZOOM_LVL_SHIFT);
374 y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> (1 + ZOOM_LVL_SHIFT);
376 a = y - x;
377 b = y + x;
379 /* we need to move variables in to the valid range, as the
380 * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
381 * when the user tries to zoom out along the sides of the map */
382 a = Clamp(a, -4 * (int)TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
383 b = Clamp(b, -4 * (int)TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
385 /* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
386 * Now find the Z-world coordinate by fix point iteration.
387 * This is a bit tricky because the tile height is non-continuous at foundations.
388 * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
389 * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
390 * So give it a z-malus of 4 in the first iterations.
392 z = 0;
394 int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
396 for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(a + max(z, 4) - 4, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + max(z, 4) - 4, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
397 for (int malus = 3; malus > 0; malus--) z = GetSlopePixelZ(Clamp(a + max(z, malus) - malus, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + max(z, malus) - malus, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
398 for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(a + z, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + z, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
400 pt.x = Clamp(a + z, min_coord, MapMaxX() * TILE_SIZE - 1);
401 pt.y = Clamp(b + z, min_coord, MapMaxY() * TILE_SIZE - 1);
403 return pt;
406 /* When used for zooming, check area below current coordinates (x,y)
407 * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
408 * when you just want the tile, make x = zoom_x and y = zoom_y */
409 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
411 Window *w;
412 ViewPort *vp;
413 Point pt;
415 if ( (w = FindWindowFromPt(x, y)) != NULL &&
416 (vp = IsPtInWindowViewport(w, x, y)) != NULL)
417 return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
419 pt.y = pt.x = -1;
420 return pt;
423 Point GetTileBelowCursor()
425 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
429 Point GetTileZoomCenterWindow(bool in, Window * w)
431 int x, y;
432 ViewPort *vp = w->viewport;
434 if (in) {
435 x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
436 y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
437 } else {
438 x = vp->width - (_cursor.pos.x - vp->left);
439 y = vp->height - (_cursor.pos.y - vp->top);
441 /* Get the tile below the cursor and center on the zoomed-out center */
442 return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
446 * Update the status of the zoom-buttons according to the zoom-level
447 * of the viewport. This will update their status and invalidate accordingly
448 * @param w Window pointer to the window that has the zoom buttons
449 * @param vp pointer to the viewport whose zoom-level the buttons represent
450 * @param widget_zoom_in widget index for window with zoom-in button
451 * @param widget_zoom_out widget index for window with zoom-out button
453 void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
455 w->SetWidgetDisabledState(widget_zoom_in, vp->zoom <= _settings_client.gui.zoom_min);
456 w->SetWidgetDirty(widget_zoom_in);
458 w->SetWidgetDisabledState(widget_zoom_out, vp->zoom >= _settings_client.gui.zoom_max);
459 w->SetWidgetDirty(widget_zoom_out);
463 * Schedules a tile sprite for drawing.
465 * @param image the image to draw.
466 * @param pal the provided palette.
467 * @param x position x (world coordinates) of the sprite.
468 * @param y position y (world coordinates) of the sprite.
469 * @param z position z (world coordinates) of the sprite.
470 * @param sub Only draw a part of the sprite.
471 * @param extra_offs_x Pixel X offset for the sprite position.
472 * @param extra_offs_y Pixel Y offset for the sprite position.
474 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0)
476 assert((image & SPRITE_MASK) < MAX_SPRITES);
478 TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
479 ts->image = image;
480 ts->pal = pal;
481 ts->sub = sub;
482 Point pt = RemapCoords(x, y, z);
483 ts->x = pt.x + extra_offs_x;
484 ts->y = pt.y + extra_offs_y;
488 * Adds a child sprite to the active foundation.
490 * The pixel offset of the sprite relative to the ParentSprite is the sum of the offset passed to OffsetGroundSprite() and extra_offs_?.
492 * @param image the image to draw.
493 * @param pal the provided palette.
494 * @param sub Only draw a part of the sprite.
495 * @param foundation_part Foundation part.
496 * @param extra_offs_x Pixel X offset for the sprite position.
497 * @param extra_offs_y Pixel Y offset for the sprite position.
499 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
501 assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
502 assert(_vd.foundation[foundation_part] != -1);
503 Point offs = _vd.foundation_offset[foundation_part];
505 /* Change the active ChildSprite list to the one of the foundation */
506 int *old_child = _vd.last_child;
507 _vd.last_child = _vd.last_foundation_child[foundation_part];
509 AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub, false);
511 /* Switch back to last ChildSprite list */
512 _vd.last_child = old_child;
516 * Draws a ground sprite at a specific world-coordinate relative to the current tile.
517 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
519 * @param image the image to draw.
520 * @param pal the provided palette.
521 * @param x position x (world coordinates) of the sprite relative to current tile.
522 * @param y position y (world coordinates) of the sprite relative to current tile.
523 * @param z position z (world coordinates) of the sprite relative to current tile.
524 * @param sub Only draw a part of the sprite.
525 * @param extra_offs_x Pixel X offset for the sprite position.
526 * @param extra_offs_y Pixel Y offset for the sprite position.
528 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
530 /* Switch to first foundation part, if no foundation was drawn */
531 if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
533 if (_vd.foundation[_vd.foundation_part] != -1) {
534 Point pt = RemapCoords(x, y, z);
535 AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x * ZOOM_LVL_BASE, pt.y + extra_offs_y * ZOOM_LVL_BASE);
536 } else {
537 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);
542 * Draws a ground sprite for the current tile.
543 * If the current tile is drawn on top of a foundation the sprite is added as child sprite to the "foundation"-ParentSprite.
545 * @param image the image to draw.
546 * @param pal the provided palette.
547 * @param sub Only draw a part of the sprite.
548 * @param extra_offs_x Pixel X offset for the sprite position.
549 * @param extra_offs_y Pixel Y offset for the sprite position.
551 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
553 DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
557 * Called when a foundation has been drawn for the current tile.
558 * Successive ground sprites for the current tile will be drawn as child sprites of the "foundation"-ParentSprite, not as TileSprites.
560 * @param x sprite x-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
561 * @param y sprite y-offset (screen coordinates) of ground sprites relative to the "foundation"-ParentSprite.
563 void OffsetGroundSprite(int x, int y)
565 /* Switch to next foundation part */
566 switch (_vd.foundation_part) {
567 case FOUNDATION_PART_NONE:
568 _vd.foundation_part = FOUNDATION_PART_NORMAL;
569 break;
570 case FOUNDATION_PART_NORMAL:
571 _vd.foundation_part = FOUNDATION_PART_HALFTILE;
572 break;
573 default: NOT_REACHED();
576 /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
577 if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
579 _vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_LVL_BASE;
580 _vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_LVL_BASE;
581 _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
585 * Adds a child sprite to a parent sprite.
586 * In contrast to "AddChildSpriteScreen()" the sprite position is in world coordinates
588 * @param image the image to draw.
589 * @param pal the provided palette.
590 * @param x position x of the sprite.
591 * @param y position y of the sprite.
592 * @param z position z of the sprite.
593 * @param sub Only draw a part of the sprite.
595 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
597 Point pt = RemapCoords(x, y, z);
598 const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
600 if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
601 pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
602 pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
603 pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
604 return;
606 const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
607 AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub, false);
611 * Draw a (transparent) sprite at given coordinates with a given bounding box.
612 * 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.
613 * Bounding boxes with bb_offset_x == w or bb_offset_y == h or bb_offset_z == dz are allowed and produce thin slices.
615 * @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
616 * defined by the sprite offset in the grf file.
617 * However if modifying the sprite offsets is not suitable (e.g. when using existing graphics), the bounding box can be tuned by bb_offset.
619 * @pre w >= bb_offset_x, h >= bb_offset_y, dz >= bb_offset_z. Else w, h or dz are ignored.
621 * @param image the image to combine and draw,
622 * @param pal the provided palette,
623 * @param x position X (world) of the sprite,
624 * @param y position Y (world) of the sprite,
625 * @param w bounding box extent towards positive X (world),
626 * @param h bounding box extent towards positive Y (world),
627 * @param dz bounding box extent towards positive Z (world),
628 * @param z position Z (world) of the sprite,
629 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
630 * @param bb_offset_x bounding box extent towards negative X (world),
631 * @param bb_offset_y bounding box extent towards negative Y (world),
632 * @param bb_offset_z bounding box extent towards negative Z (world)
633 * @param sub Only draw a part of the sprite.
635 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)
637 int32 left, right, top, bottom;
639 assert((image & SPRITE_MASK) < MAX_SPRITES);
641 /* make the sprites transparent with the right palette */
642 if (transparent) {
643 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
644 pal = PALETTE_TO_TRANSPARENT;
647 if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
648 AddCombinedSprite(image, pal, x, y, z, sub);
649 return;
652 _vd.last_child = NULL;
654 Point pt = RemapCoords(x, y, z);
655 int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
657 /* Compute screen extents of sprite */
658 if (image == SPR_EMPTY_BOUNDING_BOX) {
659 left = tmp_left = RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x;
660 right = RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1;
661 top = tmp_top = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y;
662 bottom = RemapCoords(x + w , y + h , z + bb_offset_z).y + 1;
663 } else {
664 const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
665 left = tmp_left = (pt.x += spr->x_offs);
666 right = (pt.x + spr->width );
667 top = tmp_top = (pt.y += spr->y_offs);
668 bottom = (pt.y + spr->height);
671 if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
672 /* Compute maximal extents of sprite and its bounding box */
673 left = min(left , RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x);
674 right = max(right , RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1);
675 top = min(top , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y);
676 bottom = max(bottom, RemapCoords(x + w , y + h , z + bb_offset_z).y + 1);
679 /* Do not add the sprite to the viewport, if it is outside */
680 if (left >= _vd.dpi.left + _vd.dpi.width ||
681 right <= _vd.dpi.left ||
682 top >= _vd.dpi.top + _vd.dpi.height ||
683 bottom <= _vd.dpi.top) {
684 return;
687 ParentSpriteToDraw *ps = _vd.parent_sprites_to_draw.Append();
688 ps->x = tmp_x;
689 ps->y = tmp_y;
691 ps->left = tmp_left;
692 ps->top = tmp_top;
694 ps->image = image;
695 ps->pal = pal;
696 ps->sub = sub;
697 ps->xmin = x + bb_offset_x;
698 ps->xmax = x + max(bb_offset_x, w) - 1;
700 ps->ymin = y + bb_offset_y;
701 ps->ymax = y + max(bb_offset_y, h) - 1;
703 ps->zmin = z + bb_offset_z;
704 ps->zmax = z + max(bb_offset_z, dz) - 1;
706 ps->comparison_done = false;
707 ps->first_child = -1;
709 _vd.last_child = &ps->first_child;
711 if (_vd.combine_sprites == SPRITE_COMBINE_PENDING) _vd.combine_sprites = SPRITE_COMBINE_ACTIVE;
715 * Starts a block of sprites, which are "combined" into a single bounding box.
717 * Subsequent calls to #AddSortableSpriteToDraw will be drawn into the same bounding box.
718 * That is: The first sprite that is not clipped by the viewport defines the bounding box, and
719 * the following sprites will be child sprites to that one.
721 * That implies:
722 * - The drawing order is definite. No other sprites will be sorted between those of the block.
723 * - You have to provide a valid bounding box for all sprites,
724 * as you won't know which one is the first non-clipped one.
725 * Preferable you use the same bounding box for all.
726 * - You cannot use #AddChildSpriteScreen inside the block, as its result will be indefinite.
728 * The block is terminated by #EndSpriteCombine.
730 * You cannot nest "combined" blocks.
732 void StartSpriteCombine()
734 assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
735 _vd.combine_sprites = SPRITE_COMBINE_PENDING;
739 * Terminates a block of sprites started by #StartSpriteCombine.
740 * Take a look there for details.
742 void EndSpriteCombine()
744 assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
745 _vd.combine_sprites = SPRITE_COMBINE_NONE;
749 * Check if the parameter "check" is inside the interval between
750 * begin and end, including both begin and end.
751 * @note Whether \c begin or \c end is the biggest does not matter.
752 * This method will account for that.
753 * @param begin The begin of the interval.
754 * @param end The end of the interval.
755 * @param check The value to check.
757 static bool IsInRangeInclusive(int begin, int end, int check)
759 if (begin > end) Swap(begin, end);
760 return begin <= check && check <= end;
764 * Checks whether a point is inside the selected a diagonal rectangle given by _thd.size and _thd.pos
765 * @param x The x coordinate of the point to be checked.
766 * @param y The y coordinate of the point to be checked.
767 * @return True if the point is inside the rectangle, else false.
769 bool IsInsideRotatedRectangle(int x, int y)
771 int dist_a = (_thd.size.x + _thd.size.y); // Rotated coordinate system for selected rectangle.
772 int dist_b = (_thd.size.x - _thd.size.y); // We don't have to divide by 2. It's all relative!
773 int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
774 int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
776 /* Check if a and b are between 0 and dist_a or dist_b respectively. */
777 return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
781 * Add a child sprite to a parent sprite.
783 * @param image the image to draw.
784 * @param pal the provided palette.
785 * @param x sprite x-offset (screen coordinates) relative to parent sprite.
786 * @param y sprite y-offset (screen coordinates) relative to parent sprite.
787 * @param transparent if true, switch the palette between the provided palette and the transparent palette,
788 * @param sub Only draw a part of the sprite.
790 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
792 assert((image & SPRITE_MASK) < MAX_SPRITES);
794 /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
795 if (_vd.last_child == NULL) return;
797 /* make the sprites transparent with the right palette */
798 if (transparent) {
799 SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
800 pal = PALETTE_TO_TRANSPARENT;
803 *_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
805 ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
806 cs->image = image;
807 cs->pal = pal;
808 cs->sub = sub;
809 cs->x = scale ? x * ZOOM_LVL_BASE : x;
810 cs->y = scale ? y * ZOOM_LVL_BASE : y;
811 cs->next = -1;
813 /* Append the sprite to the active ChildSprite list.
814 * If the active ParentSprite is a foundation, update last_foundation_child as well.
815 * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
816 if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
817 if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
818 _vd.last_child = &cs->next;
821 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
823 assert(width != 0);
824 StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
825 ss->string = string;
826 ss->x = x;
827 ss->y = y;
828 ss->params[0] = params_1;
829 ss->params[1] = params_2;
830 ss->width = width;
831 ss->colour = colour;
836 * Draws sprites between ground sprite and everything above.
838 * The sprite is either drawn as TileSprite or as ChildSprite of the active foundation.
840 * @param image the image to draw.
841 * @param pal the provided palette.
842 * @param ti TileInfo Tile that is being drawn
843 * @param z_offset Z offset relative to the groundsprite. Only used for the sprite position, not for sprite sorting.
844 * @param foundation_part Foundation part the sprite belongs to.
846 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
848 /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
849 if (_vd.foundation[foundation_part] == -1) {
850 /* draw on real ground */
851 AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
852 } else {
853 /* draw on top of foundation */
854 AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset * ZOOM_LVL_BASE);
859 * Draws a selection rectangle on a tile.
861 * @param ti TileInfo Tile that is being drawn
862 * @param pal Palette to apply.
864 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
866 if (!IsValidTile(ti->tile)) return;
868 SpriteID sel;
869 if (IsHalftileSlope(ti->tileh)) {
870 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
871 SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
872 DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
874 Corner opposite_corner = OppositeCorner(halftile_corner);
875 if (IsSteepSlope(ti->tileh)) {
876 sel = SPR_HALFTILE_SELECTION_DOWN;
877 } else {
878 sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
880 sel += opposite_corner;
881 } else {
882 sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
884 DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
887 static bool IsPartOfAutoLine(int px, int py)
889 px -= _thd.selstart.x;
890 py -= _thd.selstart.y;
892 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
894 switch (_thd.drawstyle & HT_DIR_MASK) {
895 case HT_DIR_X: return py == 0; // x direction
896 case HT_DIR_Y: return px == 0; // y direction
897 case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
898 case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
899 case HT_DIR_VL: return px == py || px == py + 16; // vertical left
900 case HT_DIR_VR: return px == py || px == py - 16; // vertical right
901 default:
902 NOT_REACHED();
906 /* [direction][side] */
907 static const HighLightStyle _autorail_type[6][2] = {
908 { HT_DIR_X, HT_DIR_X },
909 { HT_DIR_Y, HT_DIR_Y },
910 { HT_DIR_HU, HT_DIR_HL },
911 { HT_DIR_HL, HT_DIR_HU },
912 { HT_DIR_VL, HT_DIR_VR },
913 { HT_DIR_VR, HT_DIR_VL }
916 #include "table/autorail.h"
919 * Draws autorail highlights.
921 * @param *ti TileInfo Tile that is being drawn
922 * @param autorail_type Offset into _AutorailTilehSprite[][]
924 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
926 SpriteID image;
927 PaletteID pal;
928 int offset;
930 FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
931 Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
932 if (IsHalftileSlope(ti->tileh)) {
933 static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
934 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
935 if (autorail_type != _lower_rail[halftile_corner]) {
936 foundation_part = FOUNDATION_PART_HALFTILE;
937 /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
938 autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
942 offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
943 if (offset >= 0) {
944 image = SPR_AUTORAIL_BASE + offset;
945 pal = PAL_NONE;
946 } else {
947 image = SPR_AUTORAIL_BASE - offset;
948 pal = PALETTE_SEL_TILE_RED;
951 DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
955 * Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
956 * @param *ti TileInfo Tile that is being drawn
958 static void DrawTileSelection(const TileInfo *ti)
960 /* Draw a red error square? */
961 bool is_redsq = _thd.redsq == ti->tile;
962 if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
964 /* No tile selection active? */
965 if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
967 if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
968 if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
969 return;
972 /* Inside the inner area? */
973 if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
974 IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
975 draw_inner:
976 if (_thd.drawstyle & HT_RECT) {
977 if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
978 } else if (_thd.drawstyle & HT_POINT) {
979 /* Figure out the Z coordinate for the single dot. */
980 int z = 0;
981 FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
982 if (ti->tileh & SLOPE_N) {
983 z += TILE_HEIGHT;
984 if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
986 if (IsHalftileSlope(ti->tileh)) {
987 Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
988 if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
989 if (halftile_corner != CORNER_S) {
990 foundation_part = FOUNDATION_PART_HALFTILE;
991 if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
994 DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
995 } else if (_thd.drawstyle & HT_RAIL) {
996 /* autorail highlight piece under cursor */
997 HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
998 assert(type < HT_DIR_END);
999 DrawAutorailSelection(ti, _autorail_type[type][0]);
1000 } else if (IsPartOfAutoLine(ti->x, ti->y)) {
1001 /* autorail highlighting long line */
1002 HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
1003 uint side;
1005 if (dir == HT_DIR_X || dir == HT_DIR_Y) {
1006 side = 0;
1007 } else {
1008 TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
1009 side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
1012 DrawAutorailSelection(ti, _autorail_type[dir][side]);
1014 return;
1017 /* Check if it's inside the outer area? */
1018 if (!is_redsq && _thd.outersize.x > 0 &&
1019 IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
1020 IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
1021 /* Draw a blue rect. */
1022 DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
1023 return;
1027 static void ViewportAddLandscape()
1029 int x, y, width, height;
1030 TileInfo ti;
1031 bool direction;
1033 _cur_ti = &ti;
1035 /* Transform into tile coordinates and round to closest full tile */
1036 x = ((_vd.dpi.top >> (1 + ZOOM_LVL_SHIFT)) - (_vd.dpi.left >> (2 + ZOOM_LVL_SHIFT))) & ~TILE_UNIT_MASK;
1037 y = ((_vd.dpi.top >> (1 + ZOOM_LVL_SHIFT)) + (_vd.dpi.left >> (2 + ZOOM_LVL_SHIFT)) - TILE_SIZE) & ~TILE_UNIT_MASK;
1039 /* determine size of area */
1041 Point pt = RemapCoords(x, y, 241);
1042 width = (_vd.dpi.left + _vd.dpi.width - pt.x + 96 * ZOOM_LVL_BASE - 1) >> (6 + ZOOM_LVL_SHIFT);
1043 height = (_vd.dpi.top + _vd.dpi.height - pt.y) >> (5 + ZOOM_LVL_SHIFT) << 1;
1046 assert(width > 0);
1047 assert(height > 0);
1049 direction = false;
1051 do {
1052 int width_cur = width;
1053 uint x_cur = x;
1054 uint y_cur = y;
1056 do {
1057 DrawTileProc *dtp = DrawVoidTile;
1059 ti.x = x_cur;
1060 ti.y = y_cur;
1062 ti.z = 0;
1064 ti.tileh = SLOPE_FLAT;
1065 ti.tile = INVALID_TILE;
1067 if (x_cur < MapMaxX() * TILE_SIZE &&
1068 y_cur < MapMaxY() * TILE_SIZE) {
1069 TileIndex tile = TileVirtXY(x_cur, y_cur);
1071 if (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0)) {
1072 if (x_cur == ((int)MapMaxX() - 1) * TILE_SIZE || y_cur == ((int)MapMaxY() - 1) * TILE_SIZE) {
1073 uint maxh = max<uint>(TileHeight(tile), 1);
1074 for (uint h = 0; h < maxh; h++) {
1075 AddTileSpriteToDraw(SPR_SHADOW_CELL, PAL_NONE, ti.x, ti.y, h * TILE_HEIGHT);
1079 ti.tile = tile;
1080 ti.tileh = GetTilePixelSlope(tile, &ti.z);
1081 dtp = GetTileProcs(tile)->draw_tile_proc;
1085 _vd.foundation_part = FOUNDATION_PART_NONE;
1086 _vd.foundation[0] = -1;
1087 _vd.foundation[1] = -1;
1088 _vd.last_foundation_child[0] = NULL;
1089 _vd.last_foundation_child[1] = NULL;
1091 dtp(&ti);
1093 if ((x_cur == (int)MapMaxX() * TILE_SIZE && IsInsideMM(y_cur, 0, MapMaxY() * TILE_SIZE + 1)) ||
1094 (y_cur == (int)MapMaxY() * TILE_SIZE && IsInsideMM(x_cur, 0, MapMaxX() * TILE_SIZE + 1))) {
1095 TileIndex tile = TileVirtXY(x_cur, y_cur);
1096 ti.tile = tile;
1097 ti.tileh = GetTilePixelSlope(tile, &ti.z);
1098 dtp = GetTileProcs(tile)->draw_tile_proc;
1100 if (ti.tile != INVALID_TILE) DrawTileSelection(&ti);
1102 y_cur += 0x10;
1103 x_cur -= 0x10;
1104 } while (--width_cur);
1106 if ((direction ^= 1) != 0) {
1107 y += 0x10;
1108 } else {
1109 x += 0x10;
1111 } while (--height);
1115 * Add a string to draw in the viewport
1116 * @param dpi current viewport area
1117 * @param small_from Zoomlevel from when the small font should be used
1118 * @param sign sign position and dimension
1119 * @param string_normal String for normal and 2x zoom level
1120 * @param string_small String for 4x and 8x zoom level
1121 * @param string_small_shadow Shadow string for 4x and 8x zoom level; or #STR_NULL if no shadow
1122 * @param colour colour of the sign background; or INVALID_COLOUR if transparent
1124 void ViewportAddString(const DrawPixelInfo *dpi, ZoomLevel small_from, const ViewportSign *sign, StringID string_normal, StringID string_small, StringID string_small_shadow, uint64 params_1, uint64 params_2, Colours colour)
1126 bool small = dpi->zoom >= small_from;
1128 int left = dpi->left;
1129 int top = dpi->top;
1130 int right = left + dpi->width;
1131 int bottom = top + dpi->height;
1133 int sign_height = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
1134 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
1136 if (bottom < sign->top ||
1137 top > sign->top + sign_height ||
1138 right < sign->center - sign_half_width ||
1139 left > sign->center + sign_half_width) {
1140 return;
1143 if (!small) {
1144 AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
1145 } else {
1146 int shadow_offset = 0;
1147 if (string_small_shadow != STR_NULL) {
1148 shadow_offset = 4;
1149 AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
1151 AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
1152 colour, sign->width_small | 0x8000);
1156 static void ViewportAddTownNames(DrawPixelInfo *dpi)
1158 if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
1160 const Town *t;
1161 FOR_ALL_TOWNS(t) {
1162 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &t->cache.sign,
1163 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
1164 STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
1165 t->index, t->cache.population);
1170 static void ViewportAddStationNames(DrawPixelInfo *dpi)
1172 if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
1174 const BaseStation *st;
1175 FOR_ALL_BASE_STATIONS(st) {
1176 /* Check whether the base station is a station or a waypoint */
1177 bool is_station = Station::IsExpected(st);
1179 /* Don't draw if the display options are disabled */
1180 if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
1182 /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1183 if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != st->owner && st->owner != OWNER_NONE) continue;
1185 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &st->sign,
1186 is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT,
1187 (is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT) + 1, STR_NULL,
1188 st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
1193 static void ViewportAddSigns(DrawPixelInfo *dpi)
1195 /* Signs are turned off or are invisible */
1196 if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
1198 const Sign *si;
1199 FOR_ALL_SIGNS(si) {
1200 /* Don't draw if sign is owned by another company and competitor signs should be hidden.
1201 * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
1202 * companies can leave OWNER_NONE signs after them. */
1203 if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != si->owner && si->owner != OWNER_DEITY) continue;
1205 ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &si->sign,
1206 STR_WHITE_SIGN,
1207 (IsTransparencySet(TO_SIGNS) || si->owner == OWNER_DEITY) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
1208 si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : (si->owner == OWNER_DEITY ? INVALID_COLOUR : _company_colours[si->owner]));
1213 * Update the position of the viewport sign.
1214 * @param center the (preferred) center of the viewport sign
1215 * @param top the new top of the sign
1216 * @param str the string to show in the sign
1218 void ViewportSign::UpdatePosition(int center, int top, StringID str)
1220 if (this->width_normal != 0) this->MarkDirty();
1222 this->top = top;
1224 char buffer[DRAW_STRING_BUFFER];
1226 GetString(buffer, str, lastof(buffer));
1227 this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
1228 this->center = center;
1230 /* zoomed out version */
1231 this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer, FS_SMALL).width, 2) + VPSM_RIGHT;
1233 this->MarkDirty();
1237 * Mark the sign dirty in all viewports.
1238 * @param maxzoom Maximum %ZoomLevel at which the text is visible.
1240 * @ingroup dirty
1242 void ViewportSign::MarkDirty(ZoomLevel maxzoom) const
1244 Rect zoomlevels[ZOOM_LVL_COUNT];
1246 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
1247 /* FIXME: This doesn't switch to width_small when appropriate. */
1248 zoomlevels[zoom].left = this->center - ScaleByZoom(this->width_normal / 2 + 1, zoom);
1249 zoomlevels[zoom].top = this->top - ScaleByZoom(1, zoom);
1250 zoomlevels[zoom].right = this->center + ScaleByZoom(this->width_normal / 2 + 1, zoom);
1251 zoomlevels[zoom].bottom = this->top + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, zoom);
1254 Window *w;
1255 FOR_ALL_WINDOWS_FROM_BACK(w) {
1256 ViewPort *vp = w->viewport;
1257 if (vp != NULL && vp->zoom <= maxzoom) {
1258 assert(vp->width != 0);
1259 Rect &zl = zoomlevels[vp->zoom];
1260 MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
1265 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
1267 const TileSpriteToDraw *tsend = tstdv->End();
1268 for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
1269 DrawSpriteViewport(ts->image, ts->pal, ts->x, ts->y, ts->sub);
1273 /** This fallback sprite checker always exists. */
1274 static bool ViewportSortParentSpritesChecker()
1276 return true;
1279 /** Sort parent sprites pointer array */
1280 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
1282 ParentSpriteToDraw **psdvend = psdv->End();
1283 ParentSpriteToDraw **psd = psdv->Begin();
1284 while (psd != psdvend) {
1285 ParentSpriteToDraw *ps = *psd;
1287 if (ps->comparison_done) {
1288 psd++;
1289 continue;
1292 ps->comparison_done = true;
1294 for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
1295 ParentSpriteToDraw *ps2 = *psd2;
1297 if (ps2->comparison_done) continue;
1299 /* Decide which comparator to use, based on whether the bounding
1300 * boxes overlap
1302 if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
1303 ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
1304 ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
1305 /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
1306 * the screen and with higher Z elevation, are drawn in front.
1307 * Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
1308 * i.e. X=(left+right)/2, etc.
1309 * However, since we only care about order, don't actually divide / 2
1311 if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
1312 ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
1313 continue;
1315 } else {
1316 /* We only change the order, if it is definite.
1317 * I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
1318 * That is: If one partial order says ps behind ps2, do not change the order.
1320 if (ps->xmax < ps2->xmin ||
1321 ps->ymax < ps2->ymin ||
1322 ps->zmax < ps2->zmin) {
1323 continue;
1327 /* Move ps2 in front of ps */
1328 ParentSpriteToDraw *temp = ps2;
1329 for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
1330 *psd3 = *(psd3 - 1);
1332 *psd = temp;
1337 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
1339 const ParentSpriteToDraw * const *psd_end = psd->End();
1340 for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
1341 const ParentSpriteToDraw *ps = *it;
1342 if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
1344 int child_idx = ps->first_child;
1345 while (child_idx >= 0) {
1346 const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
1347 child_idx = cs->next;
1348 DrawSpriteViewport(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
1354 * Draws the bounding boxes of all ParentSprites
1355 * @param psd Array of ParentSprites
1357 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
1359 const ParentSpriteToDraw * const *psd_end = psd->End();
1360 for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
1361 const ParentSpriteToDraw *ps = *it;
1362 Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
1363 Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner
1364 Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner
1365 Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin ); // bottom front corner
1367 DrawBox( pt1.x, pt1.y,
1368 pt2.x - pt1.x, pt2.y - pt1.y,
1369 pt3.x - pt1.x, pt3.y - pt1.y,
1370 pt4.x - pt1.x, pt4.y - pt1.y);
1375 * Draw/colour the blocks that have been redrawn.
1377 static void ViewportDrawDirtyBlocks()
1379 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1380 const DrawPixelInfo *dpi = _cur_dpi;
1381 void *dst;
1382 int right = UnScaleByZoom(dpi->width, dpi->zoom);
1383 int bottom = UnScaleByZoom(dpi->height, dpi->zoom);
1385 int colour = _string_colourmap[_dirty_block_colour & 0xF];
1387 dst = dpi->dst_ptr;
1389 byte bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1;
1390 do {
1391 for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
1392 dst = blitter->MoveTo(dst, 0, 1);
1393 } while (--bottom > 0);
1396 static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
1398 const StringSpriteToDraw *ssend = sstdv->End();
1399 for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
1400 TextColour colour = TC_BLACK;
1401 bool small = HasBit(ss->width, 15);
1402 int w = GB(ss->width, 0, 15);
1403 int x = UnScaleByZoom(ss->x, zoom);
1404 int y = UnScaleByZoom(ss->y, zoom);
1405 int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
1407 SetDParam(0, ss->params[0]);
1408 SetDParam(1, ss->params[1]);
1410 if (ss->colour != INVALID_COLOUR) {
1411 /* Do not draw signs nor station names if they are set invisible */
1412 if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue;
1414 if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) {
1415 /* Don't draw the rectangle.
1416 * Real colours need the TC_IS_PALETTE_COLOUR flag.
1417 * Otherwise colours from _string_colourmap are assumed. */
1418 colour = (TextColour)_colour_gradient[ss->colour][6] | TC_IS_PALETTE_COLOUR;
1419 } else {
1420 /* Draw the rectangle if 'transparent station signs' is off,
1421 * or if we are drawing a general text sign (STR_WHITE_SIGN). */
1422 DrawFrameRect(
1423 x, y, x + w, y + h, ss->colour,
1424 IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
1429 DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_HOR_CENTER);
1433 void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
1435 DrawPixelInfo *old_dpi = _cur_dpi;
1436 _cur_dpi = &_vd.dpi;
1438 _vd.dpi.zoom = vp->zoom;
1439 int mask = ScaleByZoom(-1, vp->zoom);
1441 _vd.combine_sprites = SPRITE_COMBINE_NONE;
1443 _vd.dpi.width = (right - left) & mask;
1444 _vd.dpi.height = (bottom - top) & mask;
1445 _vd.dpi.left = left & mask;
1446 _vd.dpi.top = top & mask;
1447 _vd.dpi.pitch = old_dpi->pitch;
1448 _vd.last_child = NULL;
1450 int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
1451 int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
1453 _vd.dpi.dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
1455 ViewportAddLandscape();
1456 ViewportAddVehicles(&_vd.dpi);
1458 ViewportAddTownNames(&_vd.dpi);
1459 ViewportAddStationNames(&_vd.dpi);
1460 ViewportAddSigns(&_vd.dpi);
1462 DrawTextEffects(&_vd.dpi);
1464 if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
1466 ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
1467 for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
1468 *_vd.parent_sprites_to_sort.Append() = it;
1471 _vp_sprite_sorter(&_vd.parent_sprites_to_sort);
1472 ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
1474 if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
1475 if (_draw_dirty_blocks) ViewportDrawDirtyBlocks();
1477 DrawPixelInfo dp = _vd.dpi;
1478 ZoomLevel zoom = _vd.dpi.zoom;
1479 dp.zoom = ZOOM_LVL_NORMAL;
1480 dp.width = UnScaleByZoom(dp.width, zoom);
1481 dp.height = UnScaleByZoom(dp.height, zoom);
1482 _cur_dpi = &dp;
1484 if (vp->overlay != NULL && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
1485 /* translate to window coordinates */
1486 dp.left = x;
1487 dp.top = y;
1488 vp->overlay->Draw(&dp);
1491 if (_vd.string_sprites_to_draw.Length() != 0) {
1492 /* translate to world coordinates */
1493 dp.left = UnScaleByZoom(_vd.dpi.left, zoom);
1494 dp.top = UnScaleByZoom(_vd.dpi.top, zoom);
1495 ViewportDrawStrings(zoom, &_vd.string_sprites_to_draw);
1498 _cur_dpi = old_dpi;
1500 _vd.string_sprites_to_draw.Clear();
1501 _vd.tile_sprites_to_draw.Clear();
1502 _vd.parent_sprites_to_draw.Clear();
1503 _vd.parent_sprites_to_sort.Clear();
1504 _vd.child_screen_sprites_to_draw.Clear();
1508 * Make sure we don't draw a too big area at a time.
1509 * If we do, the sprite memory will overflow.
1511 static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
1513 if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom) > 180000 * ZOOM_LVL_BASE * ZOOM_LVL_BASE) {
1514 if ((bottom - top) > (right - left)) {
1515 int t = (top + bottom) >> 1;
1516 ViewportDrawChk(vp, left, top, right, t);
1517 ViewportDrawChk(vp, left, t, right, bottom);
1518 } else {
1519 int t = (left + right) >> 1;
1520 ViewportDrawChk(vp, left, top, t, bottom);
1521 ViewportDrawChk(vp, t, top, right, bottom);
1523 } else {
1524 ViewportDoDraw(vp,
1525 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
1526 ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
1527 ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
1528 ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
1533 static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
1535 if (right <= vp->left || bottom <= vp->top) return;
1537 if (left >= vp->left + vp->width) return;
1539 if (left < vp->left) left = vp->left;
1540 if (right > vp->left + vp->width) right = vp->left + vp->width;
1542 if (top >= vp->top + vp->height) return;
1544 if (top < vp->top) top = vp->top;
1545 if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
1547 ViewportDrawChk(vp, left, top, right, bottom);
1551 * Draw the viewport of this window.
1553 void Window::DrawViewport() const
1555 DrawPixelInfo *dpi = _cur_dpi;
1557 dpi->left += this->left;
1558 dpi->top += this->top;
1560 ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
1562 dpi->left -= this->left;
1563 dpi->top -= this->top;
1566 static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
1568 /* Centre of the viewport is hot spot */
1569 x += vp->virtual_width / 2;
1570 y += vp->virtual_height / 2;
1572 /* Convert viewport coordinates to map coordinates
1573 * Calculation is scaled by 4 to avoid rounding errors */
1574 int vx = -x + y * 2;
1575 int vy = x + y * 2;
1577 /* clamp to size of map */
1578 vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4 * ZOOM_LVL_BASE);
1579 vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4 * ZOOM_LVL_BASE);
1581 /* Convert map coordinates to viewport coordinates */
1582 x = (-vx + vy) / 2;
1583 y = ( vx + vy) / 4;
1585 /* Remove centering */
1586 x -= vp->virtual_width / 2;
1587 y -= vp->virtual_height / 2;
1591 * Update the viewport position being displayed.
1592 * @param w %Window owning the viewport.
1594 void UpdateViewportPosition(Window *w)
1596 const ViewPort *vp = w->viewport;
1598 if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
1599 const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
1600 Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
1602 w->viewport->scrollpos_x = pt.x;
1603 w->viewport->scrollpos_y = pt.y;
1604 SetViewportPosition(w, pt.x, pt.y);
1605 } else {
1606 /* Ensure the destination location is within the map */
1607 ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
1609 int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
1610 int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
1612 bool update_overlay = false;
1613 if (delta_x != 0 || delta_y != 0) {
1614 if (_settings_client.gui.smooth_scroll) {
1615 int max_scroll = ScaleByMapPerimeter(512 * ZOOM_LVL_BASE);
1616 /* Not at our desired position yet... */
1617 w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
1618 w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
1619 } else {
1620 w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
1621 w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
1623 update_overlay = (w->viewport->scrollpos_x == w->viewport->dest_scrollpos_x &&
1624 w->viewport->scrollpos_y == w->viewport->dest_scrollpos_y);
1627 ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
1629 SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
1630 if (update_overlay) RebuildViewportOverlay(w);
1635 * Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
1636 * @param vp The viewport to mark as dirty
1637 * @param left Left edge of area to repaint
1638 * @param top Top edge of area to repaint
1639 * @param right Right edge of area to repaint
1640 * @param bottom Bottom edge of area to repaint
1641 * @ingroup dirty
1643 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
1645 right -= vp->virtual_left;
1646 if (right <= 0) return;
1648 bottom -= vp->virtual_top;
1649 if (bottom <= 0) return;
1651 left = max(0, left - vp->virtual_left);
1653 if (left >= vp->virtual_width) return;
1655 top = max(0, top - vp->virtual_top);
1657 if (top >= vp->virtual_height) return;
1659 SetDirtyBlocks(
1660 UnScaleByZoomLower(left, vp->zoom) + vp->left,
1661 UnScaleByZoomLower(top, vp->zoom) + vp->top,
1662 UnScaleByZoom(right, vp->zoom) + vp->left + 1,
1663 UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
1668 * Mark all viewports that display an area as dirty (in need of repaint).
1669 * @param left Left edge of area to repaint
1670 * @param top Top edge of area to repaint
1671 * @param right Right edge of area to repaint
1672 * @param bottom Bottom edge of area to repaint
1673 * @ingroup dirty
1675 void MarkAllViewportsDirty(int left, int top, int right, int bottom)
1677 Window *w;
1678 FOR_ALL_WINDOWS_FROM_BACK(w) {
1679 ViewPort *vp = w->viewport;
1680 if (vp != NULL) {
1681 assert(vp->width != 0);
1682 MarkViewportDirty(vp, left, top, right, bottom);
1687 void ConstrainAllViewportsZoom()
1689 Window *w;
1690 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1691 if (w->viewport == NULL) continue;
1693 ZoomLevel zoom = static_cast<ZoomLevel>(Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
1694 if (zoom != w->viewport->zoom) {
1695 while (w->viewport->zoom < zoom) DoZoomInOutWindow(ZOOM_OUT, w);
1696 while (w->viewport->zoom > zoom) DoZoomInOutWindow(ZOOM_IN, w);
1702 * Mark a tile given by its index dirty for repaint.
1703 * @param tile The tile to mark dirty.
1704 * @ingroup dirty
1706 void MarkTileDirtyByTile(TileIndex tile)
1708 Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTilePixelZ(tile));
1709 MarkAllViewportsDirty(
1710 pt.x - 31 * ZOOM_LVL_BASE,
1711 pt.y - 122 * ZOOM_LVL_BASE,
1712 pt.x - 31 * ZOOM_LVL_BASE + 67 * ZOOM_LVL_BASE,
1713 pt.y - 122 * ZOOM_LVL_BASE + 154 * ZOOM_LVL_BASE
1718 * Marks the selected tiles as dirty.
1720 * This function marks the selected tiles as dirty for repaint
1722 * @ingroup dirty
1724 static void SetSelectionTilesDirty()
1726 int x_size = _thd.size.x;
1727 int y_size = _thd.size.y;
1729 if (!_thd.diagonal) { // Selecting in a straight rectangle (or a single square)
1730 int x_start = _thd.pos.x;
1731 int y_start = _thd.pos.y;
1733 if (_thd.outersize.x != 0) {
1734 x_size += _thd.outersize.x;
1735 x_start += _thd.offs.x;
1736 y_size += _thd.outersize.y;
1737 y_start += _thd.offs.y;
1740 x_size -= TILE_SIZE;
1741 y_size -= TILE_SIZE;
1743 assert(x_size >= 0);
1744 assert(y_size >= 0);
1746 int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
1747 int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
1749 x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
1750 y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
1752 /* make sure everything is multiple of TILE_SIZE */
1753 assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
1755 /* How it works:
1756 * Suppose we have to mark dirty rectangle of 3x4 tiles:
1758 * xxx
1759 * xxxxx
1760 * xxxxx
1761 * xxx
1763 * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
1764 * 1) x 2) x
1765 * xxx Oxx
1766 * Oxxxx xOxxx
1767 * xxxxx Oxxxx
1768 * xxx xxx
1769 * x x
1770 * And so forth...
1773 int top_x = x_end; // coordinates of top dirty tile
1774 int top_y = y_start;
1775 int bot_x = top_x; // coordinates of bottom dirty tile
1776 int bot_y = top_y;
1778 do {
1779 /* topmost dirty point */
1780 TileIndex top_tile = TileVirtXY(top_x, top_y);
1781 Point top = RemapCoords(top_x, top_y, GetTileMaxPixelZ(top_tile));
1783 /* bottommost point */
1784 TileIndex bottom_tile = TileVirtXY(bot_x, bot_y);
1785 Point bot = RemapCoords(bot_x + TILE_SIZE, bot_y + TILE_SIZE, GetTilePixelZ(bottom_tile)); // bottommost point
1787 /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
1788 * tile height/slope affects only the 'y' on-screen coordinate! */
1790 int l = top.x - (TILE_PIXELS - 2) * ZOOM_LVL_BASE; // 'x' coordinate of left side of dirty rectangle
1791 int t = top.y; // 'y' coordinate of top side -//-
1792 int r = top.x + (TILE_PIXELS - 2) * ZOOM_LVL_BASE; // right side of dirty rectangle
1793 int b = bot.y; // bottom -//-
1795 static const int OVERLAY_WIDTH = 4 * ZOOM_LVL_BASE; // part of selection sprites is drawn outside the selected area
1797 /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
1798 MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT * ZOOM_LVL_BASE, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH * ZOOM_LVL_BASE);
1800 /* haven't we reached the topmost tile yet? */
1801 if (top_x != x_start) {
1802 top_x -= TILE_SIZE;
1803 } else {
1804 top_y += TILE_SIZE;
1807 /* the way the bottom tile changes is different when we reach the bottommost tile */
1808 if (bot_y != y_end) {
1809 bot_y += TILE_SIZE;
1810 } else {
1811 bot_x -= TILE_SIZE;
1813 } while (bot_x >= top_x);
1814 } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
1815 /* a_size, b_size describe a rectangle with rotated coordinates */
1816 int a_size = x_size + y_size, b_size = x_size - y_size;
1818 int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
1819 int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
1821 for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
1822 for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
1823 uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
1824 uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
1826 if (x < MapMaxX() && y < MapMaxY()) {
1827 MarkTileDirtyByTile(TileXY(x, y));
1835 void SetSelectionRed(bool b)
1837 _thd.make_square_red = b;
1838 SetSelectionTilesDirty();
1842 * Test whether a sign is below the mouse
1843 * @param vp the clicked viewport
1844 * @param x X position of click
1845 * @param y Y position of click
1846 * @param sign the sign to check
1847 * @return true if the sign was hit
1849 static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y, const ViewportSign *sign)
1851 bool small = (vp->zoom >= ZOOM_LVL_OUT_16X);
1852 int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
1853 int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
1855 x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
1856 y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
1858 return y >= sign->top && y < sign->top + sign_height &&
1859 x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
1862 static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
1864 if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
1866 const Town *t;
1867 FOR_ALL_TOWNS(t) {
1868 if (CheckClickOnViewportSign(vp, x, y, &t->cache.sign)) {
1869 ShowTownViewWindow(t->index);
1870 return true;
1874 return false;
1877 static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
1879 if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || IsInvisibilitySet(TO_SIGNS)) return false;
1881 const BaseStation *st;
1882 FOR_ALL_BASE_STATIONS(st) {
1883 /* Check whether the base station is a station or a waypoint */
1884 bool is_station = Station::IsExpected(st);
1886 /* Don't check if the display options are disabled */
1887 if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
1889 /* Don't check if competitor signs are not shown and the sign isn't owned by the local company */
1890 if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != st->owner && st->owner != OWNER_NONE) continue;
1892 if (CheckClickOnViewportSign(vp, x, y, &st->sign)) {
1893 if (is_station) {
1894 ShowStationViewWindow(st->index);
1895 } else {
1896 ShowWaypointWindow(Waypoint::From(st));
1898 return true;
1902 return false;
1906 static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
1908 /* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
1909 if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _local_company == COMPANY_SPECTATOR) return false;
1911 const Sign *si;
1912 FOR_ALL_SIGNS(si) {
1913 /* If competitor signs are hidden, don't check signs that aren't owned by local company */
1914 if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != si->owner && si->owner != OWNER_DEITY) continue;
1915 if (si->owner == OWNER_DEITY && _game_mode != GM_EDITOR) continue;
1917 if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
1918 HandleClickOnSign(si);
1919 return true;
1923 return false;
1927 static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
1929 Point pt = TranslateXYToTileCoord(vp, x, y);
1931 if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
1932 return true;
1935 static void PlaceObject()
1937 Point pt;
1938 Window *w;
1940 pt = GetTileBelowCursor();
1941 if (pt.x == -1) return;
1943 if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
1944 pt.x += TILE_SIZE / 2;
1945 pt.y += TILE_SIZE / 2;
1948 _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
1949 _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
1951 w = _thd.GetCallbackWnd();
1952 if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
1956 bool HandleViewportClicked(const ViewPort *vp, int x, int y)
1958 const Vehicle *v = CheckClickOnVehicle(vp, x, y);
1960 if (_thd.place_mode & HT_VEHICLE) {
1961 if (v != NULL && VehicleClicked(v)) return true;
1964 /* Vehicle placement mode already handled above. */
1965 if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
1966 PlaceObject();
1967 return true;
1970 if (CheckClickOnTown(vp, x, y)) return true;
1971 if (CheckClickOnStation(vp, x, y)) return true;
1972 if (CheckClickOnSign(vp, x, y)) return true;
1973 bool result = CheckClickOnLandscape(vp, x, y);
1975 if (v != NULL) {
1976 DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
1977 if (IsCompanyBuildableVehicleType(v)) {
1978 v = v->First();
1979 if (_ctrl_pressed && v->owner == _local_company) {
1980 StartStopVehicle(v, true);
1981 } else {
1982 ShowVehicleViewWindow(v);
1985 return true;
1987 return result;
1990 void RebuildViewportOverlay(Window *w)
1992 if (w->viewport->overlay != NULL &&
1993 w->viewport->overlay->GetCompanyMask() != 0 &&
1994 w->viewport->overlay->GetCargoMask() != 0) {
1995 w->viewport->overlay->RebuildCache();
1996 w->SetDirty();
2001 * Scrolls the viewport in a window to a given location.
2002 * @param x Desired x location of the map to scroll to (world coordinate).
2003 * @param y Desired y location of the map to scroll to (world coordinate).
2004 * @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.
2005 * @param w %Window containing the viewport.
2006 * @param instant Jump to the location instead of slowly moving to it.
2007 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2009 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
2011 /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
2012 if (z == -1) z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
2014 Point pt = MapXYZToViewport(w->viewport, x, y, z);
2015 w->viewport->follow_vehicle = INVALID_VEHICLE;
2017 if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
2019 if (instant) {
2020 w->viewport->scrollpos_x = pt.x;
2021 w->viewport->scrollpos_y = pt.y;
2022 RebuildViewportOverlay(w);
2025 w->viewport->dest_scrollpos_x = pt.x;
2026 w->viewport->dest_scrollpos_y = pt.y;
2027 return true;
2031 * Scrolls the viewport in a window to a given location.
2032 * @param tile Desired tile to center on.
2033 * @param w %Window containing the viewport.
2034 * @param instant Jump to the location instead of slowly moving to it.
2035 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2037 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
2039 return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
2043 * Scrolls the viewport of the main window to a given location.
2044 * @param tile Desired tile to center on.
2045 * @param instant Jump to the location instead of slowly moving to it.
2046 * @return Destination of the viewport was changed (to activate other actions when the viewport is already at the desired position).
2048 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
2050 return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
2054 * Set a tile to display a red error square.
2055 * @param tile Tile that should show the red error square.
2057 void SetRedErrorSquare(TileIndex tile)
2059 TileIndex old;
2061 old = _thd.redsq;
2062 _thd.redsq = tile;
2064 if (tile != old) {
2065 if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
2066 if (old != INVALID_TILE) MarkTileDirtyByTile(old);
2071 * Highlight \a w by \a h tiles at the cursor.
2072 * @param w Width of the highlighted tiles rectangle.
2073 * @param h Height of the highlighted tiles rectangle.
2075 void SetTileSelectSize(int w, int h)
2077 _thd.new_size.x = w * TILE_SIZE;
2078 _thd.new_size.y = h * TILE_SIZE;
2079 _thd.new_outersize.x = 0;
2080 _thd.new_outersize.y = 0;
2083 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
2085 _thd.offs.x = ox * TILE_SIZE;
2086 _thd.offs.y = oy * TILE_SIZE;
2087 _thd.new_outersize.x = sx * TILE_SIZE;
2088 _thd.new_outersize.y = sy * TILE_SIZE;
2091 /** returns the best autorail highlight type from map coordinates */
2092 static HighLightStyle GetAutorailHT(int x, int y)
2094 return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
2098 * Reset tile highlighting.
2100 void TileHighlightData::Reset()
2102 this->pos.x = 0;
2103 this->pos.y = 0;
2104 this->new_pos.x = 0;
2105 this->new_pos.y = 0;
2109 * Is the user dragging a 'diagonal rectangle'?
2110 * @return User is dragging a rotated rectangle.
2112 bool TileHighlightData::IsDraggingDiagonal()
2114 return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
2118 * Get the window that started the current highlighting.
2119 * @return The window that requested the current tile highlighting, or \c NULL if not available.
2121 Window *TileHighlightData::GetCallbackWnd()
2123 return FindWindowById(this->window_class, this->window_number);
2129 * Updates tile highlighting for all cases.
2130 * Uses _thd.selstart and _thd.selend and _thd.place_mode (set elsewhere) to determine _thd.pos and _thd.size
2131 * Also drawstyle is determined. Uses _thd.new.* as a buffer and calls SetSelectionTilesDirty() twice,
2132 * Once for the old and once for the new selection.
2133 * _thd is TileHighlightData, found in viewport.h
2135 void UpdateTileSelection()
2137 int x1;
2138 int y1;
2140 HighLightStyle new_drawstyle = HT_NONE;
2141 bool new_diagonal = false;
2143 if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
2144 x1 = _thd.selend.x;
2145 y1 = _thd.selend.y;
2146 if (x1 != -1) {
2147 int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
2148 int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
2149 x1 &= ~TILE_UNIT_MASK;
2150 y1 &= ~TILE_UNIT_MASK;
2152 if (_thd.IsDraggingDiagonal()) {
2153 new_diagonal = true;
2154 } else {
2155 if (x1 >= x2) Swap(x1, x2);
2156 if (y1 >= y2) Swap(y1, y2);
2158 _thd.new_pos.x = x1;
2159 _thd.new_pos.y = y1;
2160 _thd.new_size.x = x2 - x1;
2161 _thd.new_size.y = y2 - y1;
2162 if (!new_diagonal) {
2163 _thd.new_size.x += TILE_SIZE;
2164 _thd.new_size.y += TILE_SIZE;
2166 new_drawstyle = _thd.next_drawstyle;
2168 } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2169 Point pt = GetTileBelowCursor();
2170 x1 = pt.x;
2171 y1 = pt.y;
2172 if (x1 != -1) {
2173 switch (_thd.place_mode & HT_DRAG_MASK) {
2174 case HT_RECT:
2175 new_drawstyle = HT_RECT;
2176 break;
2177 case HT_POINT:
2178 new_drawstyle = HT_POINT;
2179 x1 += TILE_SIZE / 2;
2180 y1 += TILE_SIZE / 2;
2181 break;
2182 case HT_RAIL:
2183 /* Draw one highlighted tile in any direction */
2184 new_drawstyle = GetAutorailHT(pt.x, pt.y);
2185 break;
2186 case HT_LINE:
2187 switch (_thd.place_mode & HT_DIR_MASK) {
2188 case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
2189 case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
2191 case HT_DIR_HU:
2192 case HT_DIR_HL:
2193 new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2194 break;
2196 case HT_DIR_VL:
2197 case HT_DIR_VR:
2198 new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2199 break;
2201 default: NOT_REACHED();
2203 _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
2204 _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
2205 break;
2206 default:
2207 NOT_REACHED();
2208 break;
2210 _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
2211 _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
2215 /* redraw selection */
2216 if (_thd.drawstyle != new_drawstyle ||
2217 _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
2218 _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
2219 _thd.outersize.x != _thd.new_outersize.x ||
2220 _thd.outersize.y != _thd.new_outersize.y ||
2221 _thd.diagonal != new_diagonal) {
2222 /* Clear the old tile selection? */
2223 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2225 _thd.drawstyle = new_drawstyle;
2226 _thd.pos = _thd.new_pos;
2227 _thd.size = _thd.new_size;
2228 _thd.outersize = _thd.new_outersize;
2229 _thd.diagonal = new_diagonal;
2230 _thd.dirty = 0xff;
2232 /* Draw the new tile selection? */
2233 if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2238 * Displays the measurement tooltips when selecting multiple tiles
2239 * @param str String to be displayed
2240 * @param paramcount number of params to deal with
2241 * @param params (optional) up to 5 pieces of additional information that may be added to a tooltip
2242 * @param close_cond Condition for closing this tooltip.
2244 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_LEFT_CLICK)
2246 if (!_settings_client.gui.measure_tooltip) return;
2247 GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
2250 /** highlighting tiles while only going over them with the mouse */
2251 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
2253 _thd.select_method = method;
2254 _thd.select_proc = process;
2255 _thd.selend.x = TileX(tile) * TILE_SIZE;
2256 _thd.selstart.x = TileX(tile) * TILE_SIZE;
2257 _thd.selend.y = TileY(tile) * TILE_SIZE;
2258 _thd.selstart.y = TileY(tile) * TILE_SIZE;
2260 /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
2261 * In effect, placement starts from the centre of a tile
2263 if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
2264 _thd.selend.x += TILE_SIZE / 2;
2265 _thd.selend.y += TILE_SIZE / 2;
2266 _thd.selstart.x += TILE_SIZE / 2;
2267 _thd.selstart.y += TILE_SIZE / 2;
2270 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
2271 if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
2272 _thd.place_mode = HT_SPECIAL | others;
2273 _thd.next_drawstyle = HT_RECT | others;
2274 } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
2275 _thd.place_mode = HT_SPECIAL | others;
2276 _thd.next_drawstyle = _thd.drawstyle | others;
2277 } else {
2278 _thd.place_mode = HT_SPECIAL | others;
2279 _thd.next_drawstyle = HT_POINT | others;
2281 _special_mouse_mode = WSM_SIZING;
2284 void VpSetPlaceSizingLimit(int limit)
2286 _thd.sizelimit = limit;
2290 * Highlights all tiles between a set of two tiles. Used in dock and tunnel placement
2291 * @param from TileIndex of the first tile to highlight
2292 * @param to TileIndex of the last tile to highlight
2294 void VpSetPresizeRange(TileIndex from, TileIndex to)
2296 uint64 distance = DistanceManhattan(from, to) + 1;
2298 _thd.selend.x = TileX(to) * TILE_SIZE;
2299 _thd.selend.y = TileY(to) * TILE_SIZE;
2300 _thd.selstart.x = TileX(from) * TILE_SIZE;
2301 _thd.selstart.y = TileY(from) * TILE_SIZE;
2302 _thd.next_drawstyle = HT_RECT;
2304 /* show measurement only if there is any length to speak of */
2305 if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance, TCC_HOVER);
2308 static void VpStartPreSizing()
2310 _thd.selend.x = -1;
2311 _special_mouse_mode = WSM_PRESIZE;
2315 * returns information about the 2x1 piece to be build.
2316 * The lower bits (0-3) are the track type.
2318 static HighLightStyle Check2x1AutoRail(int mode)
2320 int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
2321 int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
2322 int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
2323 int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
2325 switch (mode) {
2326 default: NOT_REACHED();
2327 case 0: // end piece is lower right
2328 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2329 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2330 return HT_DIR_Y;
2332 case 1:
2333 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2334 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2335 return HT_DIR_Y;
2337 case 2:
2338 if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2339 if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2340 return HT_DIR_X;
2342 case 3:
2343 if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2344 if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2345 return HT_DIR_X;
2350 * Check if the direction of start and end tile should be swapped based on
2351 * the dragging-style. Default directions are:
2352 * in the case of a line (HT_RAIL, HT_LINE): DIR_NE, DIR_NW, DIR_N, DIR_E
2353 * in the case of a rect (HT_RECT, HT_POINT): DIR_S, DIR_E
2354 * For example dragging a rectangle area from south to north should be swapped to
2355 * north-south (DIR_S) to obtain the same results with less code. This is what
2356 * the return value signifies.
2357 * @param style HighLightStyle dragging style
2358 * @param start_tile start tile of drag
2359 * @param end_tile end tile of drag
2360 * @return boolean value which when true means start/end should be swapped
2362 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
2364 uint start_x = TileX(start_tile);
2365 uint start_y = TileY(start_tile);
2366 uint end_x = TileX(end_tile);
2367 uint end_y = TileY(end_tile);
2369 switch (style & HT_DRAG_MASK) {
2370 case HT_RAIL:
2371 case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
2373 case HT_RECT:
2374 case HT_POINT: return (end_x != start_x && end_y < start_y);
2375 default: NOT_REACHED();
2378 return false;
2382 * Calculates height difference between one tile and another.
2383 * Multiplies the result to suit the standard given by #TILE_HEIGHT_STEP.
2385 * To correctly get the height difference we need the direction we are dragging
2386 * in, as well as with what kind of tool we are dragging. For example a horizontal
2387 * autorail tool that starts in bottom and ends at the top of a tile will need the
2388 * maximum of SW, S and SE, N corners respectively. This is handled by the lookup table below
2389 * See #_tileoffs_by_dir in map.cpp for the direction enums if you can't figure out the values yourself.
2390 * @param style Highlighting style of the drag. This includes direction and style (autorail, rect, etc.)
2391 * @param distance Number of tiles dragged, important for horizontal/vertical drags, ignored for others.
2392 * @param start_tile Start tile of the drag operation.
2393 * @param end_tile End tile of the drag operation.
2394 * @return Height difference between two tiles. The tile measurement tool utilizes this value in its tooltip.
2396 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
2398 bool swap = SwapDirection(style, start_tile, end_tile);
2399 uint h0, h1; // Start height and end height.
2401 if (start_tile == end_tile) return 0;
2402 if (swap) Swap(start_tile, end_tile);
2404 switch (style & HT_DRAG_MASK) {
2405 case HT_RECT:
2406 /* In the case of an area we can determine whether we were dragging south or
2407 * east by checking the X-coordinates of the tiles */
2408 if (TileX(end_tile) > TileX(start_tile)) {
2409 start_tile = TILE_ADD(start_tile, TileDiffXY(0, 0));
2410 end_tile = TILE_ADD(end_tile, TileDiffXY(1, 1));
2411 } else {
2412 start_tile = TILE_ADD(start_tile, TileDiffXY(1, 0));
2413 end_tile = TILE_ADD(end_tile, TileDiffXY(0, 1));
2415 /* FALL THROUGH */
2416 case HT_POINT:
2417 h0 = TileHeight(start_tile);
2418 h1 = TileHeight(end_tile);
2419 break;
2420 default: { // All other types, this is mostly only line/autorail
2421 static const HighLightStyle flip_style_direction[] = {
2422 HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
2424 static const CoordDiff heightdiff_line_by_dir_start[][2] = {
2425 /* Start */ { {1, 0}, {1, 1} }, /* HT_DIR_X */ { {0, 1}, {1, 1} }, // HT_DIR_Y
2426 /* Start */ { {1, 0}, {0, 0} }, /* HT_DIR_HU */ { {1, 0}, {1, 1} }, // HT_DIR_HL
2427 /* Start */ { {1, 0}, {1, 1} }, /* HT_DIR_VL */ { {0, 1}, {1, 1} }, // HT_DIR_VR
2429 static const CoordDiff heightdiff_line_by_dir_end[][2] = {
2430 /* End */ { {0, 1}, {0, 0} }, /* HT_DIR_X */ { {1, 0}, {0, 0} }, // HT_DIR_Y
2431 /* End */ { {0, 1}, {0, 0} }, /* HT_DIR_HU */ { {1, 1}, {0, 1} }, // HT_DIR_HL
2432 /* End */ { {1, 0}, {0, 0} }, /* HT_DIR_VL */ { {0, 0}, {0, 1} }, // HT_DIR_VR
2435 distance %= 2; // we're only interested if the distance is even or uneven
2436 style &= HT_DIR_MASK;
2438 /* To handle autorail, we do some magic to be able to use a lookup table.
2439 * Firstly if we drag the other way around, we switch start&end, and if needed
2440 * also flip the drag-position. Eg if it was on the left, and the distance is even
2441 * that means the end, which is now the start is on the right */
2442 if (swap && distance == 0) style = flip_style_direction[style];
2444 /* Use lookup table for start-tile based on HighLightStyle direction */
2445 assert(style < lengthof(heightdiff_line_by_dir_start));
2446 h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir_start[style][0])));
2447 uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir_start[style][1])));
2448 h0 = max(h0, ht);
2450 /* Use lookup table for end-tile based on HighLightStyle direction
2451 * flip around side (lower/upper, left/right) based on distance */
2452 if (distance == 0) style = flip_style_direction[style];
2453 assert(style < lengthof(heightdiff_line_by_dir_end));
2454 h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir_end[style][0])));
2455 ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir_end[style][1])));
2456 h1 = max(h1, ht);
2457 break;
2461 if (swap) Swap(h0, h1);
2462 return (int)(h1 - h0) * TILE_HEIGHT_STEP;
2465 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
2468 * Check for underflowing the map.
2469 * @param test the variable to test for underflowing
2470 * @param other the other variable to update to keep the line
2471 * @param mult the constant to multiply the difference by for \c other
2473 static void CheckUnderflow(int &test, int &other, int mult)
2475 if (test >= 0) return;
2477 other += mult * test;
2478 test = 0;
2482 * Check for overflowing the map.
2483 * @param test the variable to test for overflowing
2484 * @param other the other variable to update to keep the line
2485 * @param max the maximum value for the \c test variable
2486 * @param mult the constant to multiply the difference by for \c other
2488 static void CheckOverflow(int &test, int &other, int max, int mult)
2490 if (test <= max) return;
2492 other += mult * (test - max);
2493 test = max;
2496 /** while dragging */
2497 static void CalcRaildirsDrawstyle(int x, int y, int method)
2499 HighLightStyle b;
2501 int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
2502 int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
2503 uint w = abs(dx) + TILE_SIZE;
2504 uint h = abs(dy) + TILE_SIZE;
2506 if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
2507 /* We 'force' a selection direction; first four rail buttons. */
2508 method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
2509 int raw_dx = _thd.selstart.x - _thd.selend.x;
2510 int raw_dy = _thd.selstart.y - _thd.selend.y;
2511 switch (method) {
2512 case VPM_FIX_X:
2513 b = HT_LINE | HT_DIR_Y;
2514 x = _thd.selstart.x;
2515 break;
2517 case VPM_FIX_Y:
2518 b = HT_LINE | HT_DIR_X;
2519 y = _thd.selstart.y;
2520 break;
2522 case VPM_FIX_HORIZONTAL:
2523 if (dx == -dy) {
2524 /* We are on a straight horizontal line. Determine the 'rail'
2525 * to build based the sub tile location. */
2526 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
2527 } else {
2528 /* We are not on a straight line. Determine the rail to build
2529 * based on whether we are above or below it. */
2530 b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2532 /* Calculate where a horizontal line through the start point and
2533 * a vertical line from the selected end point intersect and
2534 * use that point as the end point. */
2535 int offset = (raw_dx - raw_dy) / 2;
2536 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
2537 y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
2539 /* 'Build' the last half rail tile if needed */
2540 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
2541 if (dx + dy >= (int)TILE_SIZE) {
2542 x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2543 } else {
2544 y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2548 /* Make sure we do not overflow the map! */
2549 CheckUnderflow(x, y, 1);
2550 CheckUnderflow(y, x, 1);
2551 CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
2552 CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
2553 assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
2555 break;
2557 case VPM_FIX_VERTICAL:
2558 if (dx == dy) {
2559 /* We are on a straight vertical line. Determine the 'rail'
2560 * to build based the sub tile location. */
2561 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2562 } else {
2563 /* We are not on a straight line. Determine the rail to build
2564 * based on whether we are left or right from it. */
2565 b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2567 /* Calculate where a vertical line through the start point and
2568 * a horizontal line from the selected end point intersect and
2569 * use that point as the end point. */
2570 int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
2571 x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
2572 y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
2574 /* 'Build' the last half rail tile if needed */
2575 if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
2576 if (dx - dy < 0) {
2577 y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2578 } else {
2579 x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2583 /* Make sure we do not overflow the map! */
2584 CheckUnderflow(x, y, -1);
2585 CheckUnderflow(y, x, -1);
2586 CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
2587 CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
2588 assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
2590 break;
2592 default:
2593 NOT_REACHED();
2595 } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
2596 if (method & VPM_RAILDIRS) {
2597 b = GetAutorailHT(x, y);
2598 } else { // rect for autosignals on one tile
2599 b = HT_RECT;
2601 } else if (h == TILE_SIZE) { // Is this in X direction?
2602 if (dx == (int)TILE_SIZE) { // 2x1 special handling
2603 b = (Check2x1AutoRail(3)) | HT_LINE;
2604 } else if (dx == -(int)TILE_SIZE) {
2605 b = (Check2x1AutoRail(2)) | HT_LINE;
2606 } else {
2607 b = HT_LINE | HT_DIR_X;
2609 y = _thd.selstart.y;
2610 } else if (w == TILE_SIZE) { // Or Y direction?
2611 if (dy == (int)TILE_SIZE) { // 2x1 special handling
2612 b = (Check2x1AutoRail(1)) | HT_LINE;
2613 } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
2614 b = (Check2x1AutoRail(0)) | HT_LINE;
2615 } else {
2616 b = HT_LINE | HT_DIR_Y;
2618 x = _thd.selstart.x;
2619 } else if (w > h * 2) { // still count as x dir?
2620 b = HT_LINE | HT_DIR_X;
2621 y = _thd.selstart.y;
2622 } else if (h > w * 2) { // still count as y dir?
2623 b = HT_LINE | HT_DIR_Y;
2624 x = _thd.selstart.x;
2625 } else { // complicated direction
2626 int d = w - h;
2627 _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
2628 _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
2630 /* four cases. */
2631 if (x > _thd.selstart.x) {
2632 if (y > _thd.selstart.y) {
2633 /* south */
2634 if (d == 0) {
2635 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2636 } else if (d >= 0) {
2637 x = _thd.selstart.x + h;
2638 b = HT_LINE | HT_DIR_VL;
2639 } else {
2640 y = _thd.selstart.y + w;
2641 b = HT_LINE | HT_DIR_VR;
2643 } else {
2644 /* west */
2645 if (d == 0) {
2646 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
2647 } else if (d >= 0) {
2648 x = _thd.selstart.x + h;
2649 b = HT_LINE | HT_DIR_HL;
2650 } else {
2651 y = _thd.selstart.y - w;
2652 b = HT_LINE | HT_DIR_HU;
2655 } else {
2656 if (y > _thd.selstart.y) {
2657 /* east */
2658 if (d == 0) {
2659 b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
2660 } else if (d >= 0) {
2661 x = _thd.selstart.x - h;
2662 b = HT_LINE | HT_DIR_HU;
2663 } else {
2664 y = _thd.selstart.y + w;
2665 b = HT_LINE | HT_DIR_HL;
2667 } else {
2668 /* north */
2669 if (d == 0) {
2670 b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2671 } else if (d >= 0) {
2672 x = _thd.selstart.x - h;
2673 b = HT_LINE | HT_DIR_VR;
2674 } else {
2675 y = _thd.selstart.y - w;
2676 b = HT_LINE | HT_DIR_VL;
2682 if (_settings_client.gui.measure_tooltip) {
2683 TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
2684 TileIndex t1 = TileVirtXY(x, y);
2685 uint distance = DistanceManhattan(t0, t1) + 1;
2686 byte index = 0;
2687 uint64 params[2];
2689 if (distance != 1) {
2690 int heightdiff = CalcHeightdiff(b, distance, t0, t1);
2691 /* If we are showing a tooltip for horizontal or vertical drags,
2692 * 2 tiles have a length of 1. To bias towards the ceiling we add
2693 * one before division. It feels more natural to count 3 lengths as 2 */
2694 if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
2695 distance = CeilDiv(distance, 2);
2698 params[index++] = distance;
2699 if (heightdiff != 0) params[index++] = heightdiff;
2702 ShowMeasurementTooltips(measure_strings_length[index], index, params);
2705 _thd.selend.x = x;
2706 _thd.selend.y = y;
2707 _thd.next_drawstyle = b;
2711 * Selects tiles while dragging
2712 * @param x X coordinate of end of selection
2713 * @param y Y coordinate of end of selection
2714 * @param method modifies the way tiles are selected. Possible
2715 * methods are VPM_* in viewport.h
2717 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
2719 int sx, sy;
2720 HighLightStyle style;
2722 if (x == -1) {
2723 _thd.selend.x = -1;
2724 return;
2727 /* Special handling of drag in any (8-way) direction */
2728 if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
2729 _thd.selend.x = x;
2730 _thd.selend.y = y;
2731 CalcRaildirsDrawstyle(x, y, method);
2732 return;
2735 /* Needed so level-land is placed correctly */
2736 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
2737 x += TILE_SIZE / 2;
2738 y += TILE_SIZE / 2;
2741 sx = _thd.selstart.x;
2742 sy = _thd.selstart.y;
2744 int limit = 0;
2746 switch (method) {
2747 case VPM_X_OR_Y: // drag in X or Y direction
2748 if (abs(sy - y) < abs(sx - x)) {
2749 y = sy;
2750 style = HT_DIR_X;
2751 } else {
2752 x = sx;
2753 style = HT_DIR_Y;
2755 goto calc_heightdiff_single_direction;
2757 case VPM_X_LIMITED: // Drag in X direction (limited size).
2758 limit = (_thd.sizelimit - 1) * TILE_SIZE;
2759 /* FALL THROUGH */
2761 case VPM_FIX_X: // drag in Y direction
2762 x = sx;
2763 style = HT_DIR_Y;
2764 goto calc_heightdiff_single_direction;
2766 case VPM_Y_LIMITED: // Drag in Y direction (limited size).
2767 limit = (_thd.sizelimit - 1) * TILE_SIZE;
2768 /* FALL THROUGH */
2770 case VPM_FIX_Y: // drag in X direction
2771 y = sy;
2772 style = HT_DIR_X;
2774 calc_heightdiff_single_direction:;
2775 if (limit > 0) {
2776 x = sx + Clamp(x - sx, -limit, limit);
2777 y = sy + Clamp(y - sy, -limit, limit);
2779 if (_settings_client.gui.measure_tooltip) {
2780 TileIndex t0 = TileVirtXY(sx, sy);
2781 TileIndex t1 = TileVirtXY(x, y);
2782 uint distance = DistanceManhattan(t0, t1) + 1;
2783 byte index = 0;
2784 uint64 params[2];
2786 if (distance != 1) {
2787 /* With current code passing a HT_LINE style to calculate the height
2788 * difference is enough. However if/when a point-tool is created
2789 * with this method, function should be called with new_style (below)
2790 * instead of HT_LINE | style case HT_POINT is handled specially
2791 * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
2792 int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
2794 params[index++] = distance;
2795 if (heightdiff != 0) params[index++] = heightdiff;
2798 ShowMeasurementTooltips(measure_strings_length[index], index, params);
2800 break;
2802 case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
2803 limit = (_thd.sizelimit - 1) * TILE_SIZE;
2804 x = sx + Clamp(x - sx, -limit, limit);
2805 y = sy + Clamp(y - sy, -limit, limit);
2806 /* FALL THROUGH */
2808 case VPM_X_AND_Y: // drag an X by Y area
2809 if (_settings_client.gui.measure_tooltip) {
2810 static const StringID measure_strings_area[] = {
2811 STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
2814 TileIndex t0 = TileVirtXY(sx, sy);
2815 TileIndex t1 = TileVirtXY(x, y);
2816 uint dx = Delta(TileX(t0), TileX(t1)) + 1;
2817 uint dy = Delta(TileY(t0), TileY(t1)) + 1;
2818 byte index = 0;
2819 uint64 params[3];
2821 /* If dragging an area (eg dynamite tool) and it is actually a single
2822 * row/column, change the type to 'line' to get proper calculation for height */
2823 style = (HighLightStyle)_thd.next_drawstyle;
2824 if (_thd.IsDraggingDiagonal()) {
2825 /* Determine the "area" of the diagonal dragged selection.
2826 * We assume the area is the number of tiles along the X
2827 * edge and the number of tiles along the Y edge. However,
2828 * multiplying these two numbers does not give the exact
2829 * number of tiles; basically we are counting the black
2830 * squares on a chess board and ignore the white ones to
2831 * make the tile counts at the edges match up. There is no
2832 * other way to make a proper count though.
2834 * First convert to the rotated coordinate system. */
2835 int dist_x = TileX(t0) - TileX(t1);
2836 int dist_y = TileY(t0) - TileY(t1);
2837 int a_max = dist_x + dist_y;
2838 int b_max = dist_y - dist_x;
2840 /* Now determine the size along the edge, but due to the
2841 * chess board principle this counts double. */
2842 a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
2843 b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
2845 /* We get a 1x1 on normal 2x1 rectangles, due to it being
2846 * a seen as two sides. As the result for actual building
2847 * will be the same as non-diagonal dragging revert to that
2848 * behaviour to give it a more normally looking size. */
2849 if (a_max != 1 || b_max != 1) {
2850 dx = a_max;
2851 dy = b_max;
2853 } else if (style & HT_RECT) {
2854 if (dx == 1) {
2855 style = HT_LINE | HT_DIR_Y;
2856 } else if (dy == 1) {
2857 style = HT_LINE | HT_DIR_X;
2861 if (dx != 1 || dy != 1) {
2862 int heightdiff = CalcHeightdiff(style, 0, t0, t1);
2864 params[index++] = dx - (style & HT_POINT ? 1 : 0);
2865 params[index++] = dy - (style & HT_POINT ? 1 : 0);
2866 if (heightdiff != 0) params[index++] = heightdiff;
2869 ShowMeasurementTooltips(measure_strings_area[index], index, params);
2871 break;
2873 default: NOT_REACHED();
2876 _thd.selend.x = x;
2877 _thd.selend.y = y;
2881 * Handle the mouse while dragging for placement/resizing.
2882 * @return State of handling the event.
2884 EventState VpHandlePlaceSizingDrag()
2886 if (_special_mouse_mode != WSM_SIZING) return ES_NOT_HANDLED;
2888 /* stop drag mode if the window has been closed */
2889 Window *w = _thd.GetCallbackWnd();
2890 if (w == NULL) {
2891 ResetObjectToPlace();
2892 return ES_HANDLED;
2895 /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
2896 if (_left_button_down) {
2897 w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
2898 return ES_HANDLED;
2901 /* mouse button released..
2902 * keep the selected tool, but reset it to the original mode. */
2903 _special_mouse_mode = WSM_NONE;
2904 HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
2905 if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
2906 _thd.place_mode = HT_RECT | others;
2907 } else if (_thd.select_method & VPM_SIGNALDIRS) {
2908 _thd.place_mode = HT_RECT | others;
2909 } else if (_thd.select_method & VPM_RAILDIRS) {
2910 _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
2911 } else {
2912 _thd.place_mode = HT_POINT | others;
2914 SetTileSelectSize(1, 1);
2916 w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
2918 return ES_HANDLED;
2921 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
2923 SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
2926 #include "table/animcursors.h"
2928 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
2930 if (_thd.window_class != WC_INVALID) {
2931 /* Undo clicking on button and drag & drop */
2932 Window *w = _thd.GetCallbackWnd();
2933 /* Call the abort function, but set the window class to something
2934 * that will never be used to avoid infinite loops. Setting it to
2935 * the 'next' window class must not be done because recursion into
2936 * this function might in some cases reset the newly set object to
2937 * place or not properly reset the original selection. */
2938 _thd.window_class = WC_INVALID;
2939 if (w != NULL) w->OnPlaceObjectAbort();
2942 /* Mark the old selection dirty, in case the selection shape or colour changes */
2943 if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2945 SetTileSelectSize(1, 1);
2947 _thd.make_square_red = false;
2949 if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
2950 mode = HT_NONE;
2951 _special_mouse_mode = WSM_DRAGDROP;
2952 } else {
2953 _special_mouse_mode = WSM_NONE;
2956 _thd.place_mode = mode;
2957 _thd.window_class = window_class;
2958 _thd.window_number = window_num;
2960 if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
2961 VpStartPreSizing();
2964 if ((icon & ANIMCURSOR_FLAG) != 0) {
2965 SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
2966 } else {
2967 SetMouseCursor(icon, pal);
2972 void ResetObjectToPlace()
2974 SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
2977 Point GetViewportStationMiddle(const ViewPort *vp, const Station *st)
2979 int x = TileX(st->xy) * TILE_SIZE;
2980 int y = TileY(st->xy) * TILE_SIZE;
2981 int z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
2983 Point p = RemapCoords(x, y, z);
2984 p.x = UnScaleByZoom(p.x - vp->virtual_left, vp->zoom) + vp->left;
2985 p.y = UnScaleByZoom(p.y - vp->virtual_top, vp->zoom) + vp->top;
2986 return p;
2989 /** Helper class for getting the best sprite sorter. */
2990 struct ViewportSSCSS {
2991 VpSorterChecker fct_checker; ///< The check function.
2992 VpSpriteSorter fct_sorter; ///< The sorting function.
2995 /** List of sorters ordered from best to worst. */
2996 static ViewportSSCSS _vp_sprite_sorters[] = {
2997 #ifdef WITH_SSE
2998 { &ViewportSortParentSpritesSSE41Checker, &ViewportSortParentSpritesSSE41 },
2999 #endif
3000 { &ViewportSortParentSpritesChecker, &ViewportSortParentSprites }
3003 /** Choose the "best" sprite sorter and set _vp_sprite_sorter. */
3004 void InitializeSpriteSorter()
3006 for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) {
3007 if (_vp_sprite_sorters[i].fct_checker()) {
3008 _vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter;
3009 break;
3012 assert(_vp_sprite_sorter != NULL);