OpenTTD Source  13.2.1
viewport.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
63 #include "stdafx.h"
64 #include "landscape.h"
65 #include "viewport_func.h"
66 #include "station_base.h"
67 #include "waypoint_base.h"
68 #include "town.h"
69 #include "signs_base.h"
70 #include "signs_func.h"
71 #include "vehicle_base.h"
72 #include "vehicle_gui.h"
73 #include "blitter/factory.hpp"
74 #include "strings_func.h"
75 #include "zoom_func.h"
76 #include "vehicle_func.h"
77 #include "company_func.h"
78 #include "waypoint_func.h"
79 #include "window_func.h"
80 #include "tilehighlight_func.h"
81 #include "window_gui.h"
83 #include "viewport_kdtree.h"
84 #include "town_kdtree.h"
85 #include "viewport_sprite_sorter.h"
86 #include "bridge_map.h"
87 #include "company_base.h"
88 #include "command_func.h"
89 #include "network/network_func.h"
90 #include "framerate_type.h"
91 #include "viewport_cmd.h"
92 
93 #include <forward_list>
94 #include <map>
95 #include <stack>
96 
97 #include "table/strings.h"
98 #include "table/string_colours.h"
99 
100 #include "safeguards.h"
101 
102 Point _tile_fract_coords;
103 
104 
105 ViewportSignKdtree _viewport_sign_kdtree(&Kdtree_ViewportSignXYFunc);
106 static int _viewport_sign_maxwidth = 0;
107 
108 
109 static const int MAX_TILE_EXTENT_LEFT = ZOOM_LVL_BASE * TILE_PIXELS;
110 static const int MAX_TILE_EXTENT_RIGHT = ZOOM_LVL_BASE * TILE_PIXELS;
111 static const int MAX_TILE_EXTENT_TOP = ZOOM_LVL_BASE * MAX_BUILDING_PIXELS;
112 static const int MAX_TILE_EXTENT_BOTTOM = ZOOM_LVL_BASE * (TILE_PIXELS + 2 * TILE_HEIGHT);
113 
115  StringID string;
116  Colours colour;
117  int32 x;
118  int32 y;
119  uint64 params[2];
120  uint16 width;
121 };
122 
124  SpriteID image;
125  PaletteID pal;
126  const SubSprite *sub;
127  int32 x;
128  int32 y;
129 };
130 
132  SpriteID image;
133  PaletteID pal;
134  const SubSprite *sub;
135  int32 x;
136  int32 y;
137  bool relative;
138  int next;
139 };
140 
146  FOUNDATION_PART_END
147 };
148 
157 };
158 
159 typedef std::vector<TileSpriteToDraw> TileSpriteToDrawVector;
160 typedef std::vector<StringSpriteToDraw> StringSpriteToDrawVector;
161 typedef std::vector<ParentSpriteToDraw> ParentSpriteToDrawVector;
162 typedef std::vector<ChildScreenSpriteToDraw> ChildScreenSpriteToDrawVector;
163 
166  DrawPixelInfo dpi;
167 
168  StringSpriteToDrawVector string_sprites_to_draw;
169  TileSpriteToDrawVector tile_sprites_to_draw;
170  ParentSpriteToDrawVector parent_sprites_to_draw;
171  ParentSpriteToSortVector parent_sprites_to_sort;
172  ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
173 
174  int *last_child;
175 
177 
178  int foundation[FOUNDATION_PART_END];
180  int *last_foundation_child[FOUNDATION_PART_END];
181  Point foundation_offset[FOUNDATION_PART_END];
182 };
183 
184 static bool MarkViewportDirty(const Viewport *vp, int left, int top, int right, int bottom);
185 
186 static ViewportDrawer _vd;
187 
188 TileHighlightData _thd;
189 static TileInfo *_cur_ti;
190 bool _draw_bounding_boxes = false;
191 bool _draw_dirty_blocks = false;
192 uint _dirty_block_colour = 0;
193 static VpSpriteSorter _vp_sprite_sorter = nullptr;
194 
195 static Point MapXYZToViewport(const Viewport *vp, int x, int y, int z)
196 {
197  Point p = RemapCoords(x, y, z);
198  p.x -= vp->virtual_width / 2;
199  p.y -= vp->virtual_height / 2;
200  return p;
201 }
202 
203 void DeleteWindowViewport(Window *w)
204 {
205  if (w->viewport == nullptr) return;
206 
207  delete w->viewport->overlay;
208  free(w->viewport);
209  w->viewport = nullptr;
210 }
211 
224 void InitializeWindowViewport(Window *w, int x, int y,
225  int width, int height, uint32 follow_flags, ZoomLevel zoom)
226 {
227  assert(w->viewport == nullptr);
228 
229  ViewportData *vp = CallocT<ViewportData>(1);
230 
231  vp->left = x + w->left;
232  vp->top = y + w->top;
233  vp->width = width;
234  vp->height = height;
235 
237 
238  vp->virtual_width = ScaleByZoom(width, zoom);
239  vp->virtual_height = ScaleByZoom(height, zoom);
240 
241  Point pt;
242 
243  if (follow_flags & 0x80000000) {
244  const Vehicle *veh;
245 
246  vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
247  veh = Vehicle::Get(vp->follow_vehicle);
248  pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
249  } else {
250  x = TileX(follow_flags) * TILE_SIZE;
251  y = TileY(follow_flags) * TILE_SIZE;
252 
254  pt = MapXYZToViewport(vp, x, y, GetSlopePixelZ(x, y));
255  }
256 
257  vp->scrollpos_x = pt.x;
258  vp->scrollpos_y = pt.y;
259  vp->dest_scrollpos_x = pt.x;
260  vp->dest_scrollpos_y = pt.y;
261 
262  vp->overlay = nullptr;
263 
264  w->viewport = vp;
265  vp->virtual_left = 0; // pt.x;
266  vp->virtual_top = 0; // pt.y;
267 }
268 
269 static Point _vp_move_offs;
270 
271 static void DoSetViewportPosition(Window::IteratorToFront it, int left, int top, int width, int height)
272 {
273  for (; !it.IsEnd(); ++it) {
274  const Window *w = *it;
275  if (left + width > w->left &&
276  w->left + w->width > left &&
277  top + height > w->top &&
278  w->top + w->height > top) {
279 
280  if (left < w->left) {
281  DoSetViewportPosition(it, left, top, w->left - left, height);
282  DoSetViewportPosition(it, left + (w->left - left), top, width - (w->left - left), height);
283  return;
284  }
285 
286  if (left + width > w->left + w->width) {
287  DoSetViewportPosition(it, left, top, (w->left + w->width - left), height);
288  DoSetViewportPosition(it, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
289  return;
290  }
291 
292  if (top < w->top) {
293  DoSetViewportPosition(it, left, top, width, (w->top - top));
294  DoSetViewportPosition(it, left, top + (w->top - top), width, height - (w->top - top));
295  return;
296  }
297 
298  if (top + height > w->top + w->height) {
299  DoSetViewportPosition(it, left, top, width, (w->top + w->height - top));
300  DoSetViewportPosition(it, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
301  return;
302  }
303 
304  return;
305  }
306  }
307 
308  {
309  int xo = _vp_move_offs.x;
310  int yo = _vp_move_offs.y;
311 
312  if (abs(xo) >= width || abs(yo) >= height) {
313  /* fully_outside */
314  RedrawScreenRect(left, top, left + width, top + height);
315  return;
316  }
317 
318  GfxScroll(left, top, width, height, xo, yo);
319 
320  if (xo > 0) {
321  RedrawScreenRect(left, top, xo + left, top + height);
322  left += xo;
323  width -= xo;
324  } else if (xo < 0) {
325  RedrawScreenRect(left + width + xo, top, left + width, top + height);
326  width += xo;
327  }
328 
329  if (yo > 0) {
330  RedrawScreenRect(left, top, width + left, top + yo);
331  } else if (yo < 0) {
332  RedrawScreenRect(left, top + height + yo, width + left, top + height);
333  }
334  }
335 }
336 
337 static void SetViewportPosition(Window *w, int x, int y)
338 {
339  Viewport *vp = w->viewport;
340  int old_left = vp->virtual_left;
341  int old_top = vp->virtual_top;
342  int i;
343  int left, top, width, height;
344 
345  vp->virtual_left = x;
346  vp->virtual_top = y;
347 
348  /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
349  * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
350  */
351  old_left = UnScaleByZoomLower(old_left, vp->zoom);
352  old_top = UnScaleByZoomLower(old_top, vp->zoom);
353  x = UnScaleByZoomLower(x, vp->zoom);
354  y = UnScaleByZoomLower(y, vp->zoom);
355 
356  old_left -= x;
357  old_top -= y;
358 
359  if (old_top == 0 && old_left == 0) return;
360 
361  _vp_move_offs.x = old_left;
362  _vp_move_offs.y = old_top;
363 
364  left = vp->left;
365  top = vp->top;
366  width = vp->width;
367  height = vp->height;
368 
369  if (left < 0) {
370  width += left;
371  left = 0;
372  }
373 
374  i = left + width - _screen.width;
375  if (i >= 0) width -= i;
376 
377  if (width > 0) {
378  if (top < 0) {
379  height += top;
380  top = 0;
381  }
382 
383  i = top + height - _screen.height;
384  if (i >= 0) height -= i;
385 
386  if (height > 0) {
388  ++it;
389  DoSetViewportPosition(it, left, top, width, height);
390  }
391  }
392 }
393 
402 Viewport *IsPtInWindowViewport(const Window *w, int x, int y)
403 {
404  Viewport *vp = w->viewport;
405 
406  if (vp != nullptr &&
407  IsInsideMM(x, vp->left, vp->left + vp->width) &&
408  IsInsideMM(y, vp->top, vp->top + vp->height))
409  return vp;
410 
411  return nullptr;
412 }
413 
426 Point TranslateXYToTileCoord(const Viewport *vp, int x, int y, bool clamp_to_map)
427 {
428  if (!IsInsideBS(x, vp->left, vp->width) || !IsInsideBS(y, vp->top, vp->height)) {
429  Point pt = { -1, -1 };
430  return pt;
431  }
432 
433  return InverseRemapCoords2(
434  ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left,
435  ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top, clamp_to_map);
436 }
437 
438 /* When used for zooming, check area below current coordinates (x,y)
439  * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
440  * when you just want the tile, make x = zoom_x and y = zoom_y */
441 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
442 {
443  Window *w;
444  Viewport *vp;
445  Point pt;
446 
447  if ( (w = FindWindowFromPt(x, y)) != nullptr &&
448  (vp = IsPtInWindowViewport(w, x, y)) != nullptr)
449  return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
450 
451  pt.y = pt.x = -1;
452  return pt;
453 }
454 
455 Point GetTileBelowCursor()
456 {
457  return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
458 }
459 
460 
461 Point GetTileZoomCenterWindow(bool in, Window * w)
462 {
463  int x, y;
464  Viewport *vp = w->viewport;
465 
466  if (in) {
467  x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
468  y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
469  } else {
470  x = vp->width - (_cursor.pos.x - vp->left);
471  y = vp->height - (_cursor.pos.y - vp->top);
472  }
473  /* Get the tile below the cursor and center on the zoomed-out center */
474  return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
475 }
476 
485 void HandleZoomMessage(Window *w, const Viewport *vp, byte widget_zoom_in, byte widget_zoom_out)
486 {
487  w->SetWidgetDisabledState(widget_zoom_in, vp->zoom <= _settings_client.gui.zoom_min);
488  w->SetWidgetDirty(widget_zoom_in);
489 
490  w->SetWidgetDisabledState(widget_zoom_out, vp->zoom >= _settings_client.gui.zoom_max);
491  w->SetWidgetDirty(widget_zoom_out);
492 }
493 
506 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0)
507 {
508  assert((image & SPRITE_MASK) < MAX_SPRITES);
509 
510  TileSpriteToDraw &ts = _vd.tile_sprites_to_draw.emplace_back();
511  ts.image = image;
512  ts.pal = pal;
513  ts.sub = sub;
514  Point pt = RemapCoords(x, y, z);
515  ts.x = pt.x + extra_offs_x;
516  ts.y = pt.y + extra_offs_y;
517 }
518 
531 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
532 {
533  assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
534  assert(_vd.foundation[foundation_part] != -1);
535  Point offs = _vd.foundation_offset[foundation_part];
536 
537  /* Change the active ChildSprite list to the one of the foundation */
538  int *old_child = _vd.last_child;
539  _vd.last_child = _vd.last_foundation_child[foundation_part];
540 
541  AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub, false, false);
542 
543  /* Switch back to last ChildSprite list */
544  _vd.last_child = old_child;
545 }
546 
560 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
561 {
562  /* Switch to first foundation part, if no foundation was drawn */
564 
565  if (_vd.foundation[_vd.foundation_part] != -1) {
566  Point pt = RemapCoords(x, y, z);
567  AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x * ZOOM_LVL_BASE, pt.y + extra_offs_y * ZOOM_LVL_BASE);
568  } else {
569  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);
570  }
571 }
572 
583 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
584 {
585  DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
586 }
587 
595 void OffsetGroundSprite(int x, int y)
596 {
597  /* Switch to next foundation part */
598  switch (_vd.foundation_part) {
601  break;
604  break;
605  default: NOT_REACHED();
606  }
607 
608  /* _vd.last_child == nullptr if foundation sprite was clipped by the viewport bounds */
609  if (_vd.last_child != nullptr) _vd.foundation[_vd.foundation_part] = (uint)_vd.parent_sprites_to_draw.size() - 1;
610 
611  _vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_LVL_BASE;
612  _vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_LVL_BASE;
613  _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
614 }
615 
627 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
628 {
629  Point pt = RemapCoords(x, y, z);
630  const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
631 
632  if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
633  pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
634  pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
635  pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
636  return;
637 
638  const ParentSpriteToDraw &pstd = _vd.parent_sprites_to_draw.back();
639  AddChildSpriteScreen(image, pal, pt.x - pstd.left, pt.y - pstd.top, false, sub, false);
640 }
641 
667 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)
668 {
669  int32 left, right, top, bottom;
670 
671  assert((image & SPRITE_MASK) < MAX_SPRITES);
672 
673  /* make the sprites transparent with the right palette */
674  if (transparent) {
677  }
678 
680  AddCombinedSprite(image, pal, x, y, z, sub);
681  return;
682  }
683 
684  _vd.last_child = nullptr;
685 
686  Point pt = RemapCoords(x, y, z);
687  int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
688 
689  /* Compute screen extents of sprite */
690  if (image == SPR_EMPTY_BOUNDING_BOX) {
691  left = tmp_left = RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x;
692  right = RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1;
693  top = tmp_top = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y;
694  bottom = RemapCoords(x + w , y + h , z + bb_offset_z).y + 1;
695  } else {
696  const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
697  left = tmp_left = (pt.x += spr->x_offs);
698  right = (pt.x + spr->width );
699  top = tmp_top = (pt.y += spr->y_offs);
700  bottom = (pt.y + spr->height);
701  }
702 
703  if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
704  /* Compute maximal extents of sprite and its bounding box */
705  left = std::min(left , RemapCoords(x + w , y + bb_offset_y, z + bb_offset_z).x);
706  right = std::max(right , RemapCoords(x + bb_offset_x, y + h , z + bb_offset_z).x + 1);
707  top = std::min(top , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz ).y);
708  bottom = std::max(bottom, RemapCoords(x + w , y + h , z + bb_offset_z).y + 1);
709  }
710 
711  /* Do not add the sprite to the viewport, if it is outside */
712  if (left >= _vd.dpi.left + _vd.dpi.width ||
713  right <= _vd.dpi.left ||
714  top >= _vd.dpi.top + _vd.dpi.height ||
715  bottom <= _vd.dpi.top) {
716  return;
717  }
718 
719  ParentSpriteToDraw &ps = _vd.parent_sprites_to_draw.emplace_back();
720  ps.x = tmp_x;
721  ps.y = tmp_y;
722 
723  ps.left = tmp_left;
724  ps.top = tmp_top;
725 
726  ps.image = image;
727  ps.pal = pal;
728  ps.sub = sub;
729  ps.xmin = x + bb_offset_x;
730  ps.xmax = x + std::max(bb_offset_x, w) - 1;
731 
732  ps.ymin = y + bb_offset_y;
733  ps.ymax = y + std::max(bb_offset_y, h) - 1;
734 
735  ps.zmin = z + bb_offset_z;
736  ps.zmax = z + std::max(bb_offset_z, dz) - 1;
737 
738  ps.first_child = -1;
739 
740  _vd.last_child = &ps.first_child;
741 
743 }
744 
764 {
765  assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
767 }
768 
774 {
775  assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
777 }
778 
788 static bool IsInRangeInclusive(int begin, int end, int check)
789 {
790  if (begin > end) Swap(begin, end);
791  return begin <= check && check <= end;
792 }
793 
800 bool IsInsideRotatedRectangle(int x, int y)
801 {
802  int dist_a = (_thd.size.x + _thd.size.y); // Rotated coordinate system for selected rectangle.
803  int dist_b = (_thd.size.x - _thd.size.y); // We don't have to divide by 2. It's all relative!
804  int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
805  int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
806 
807  /* Check if a and b are between 0 and dist_a or dist_b respectively. */
808  return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
809 }
810 
823 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
824 {
825  assert((image & SPRITE_MASK) < MAX_SPRITES);
826 
827  /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
828  if (_vd.last_child == nullptr) return;
829 
830  /* make the sprites transparent with the right palette */
831  if (transparent) {
834  }
835 
836  *_vd.last_child = (uint)_vd.child_screen_sprites_to_draw.size();
837 
838  ChildScreenSpriteToDraw &cs = _vd.child_screen_sprites_to_draw.emplace_back();
839  cs.image = image;
840  cs.pal = pal;
841  cs.sub = sub;
842  cs.x = scale ? x * ZOOM_LVL_BASE : x;
843  cs.y = scale ? y * ZOOM_LVL_BASE : y;
844  cs.relative = relative;
845  cs.next = -1;
846 
847  /* Append the sprite to the active ChildSprite list.
848  * If the active ParentSprite is a foundation, update last_foundation_child as well.
849  * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
850  if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs.next;
851  if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs.next;
852  _vd.last_child = &cs.next;
853 }
854 
855 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
856 {
857  assert(width != 0);
858  StringSpriteToDraw &ss = _vd.string_sprites_to_draw.emplace_back();
859  ss.string = string;
860  ss.x = x;
861  ss.y = y;
862  ss.params[0] = params_1;
863  ss.params[1] = params_2;
864  ss.width = width;
865  ss.colour = colour;
866 }
867 
868 
882 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part, int extra_offs_x = 0, int extra_offs_y = 0)
883 {
884  /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
885  if (_vd.foundation[foundation_part] == -1) {
886  /* draw on real ground */
887  AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset, nullptr, extra_offs_x, extra_offs_y);
888  } else {
889  /* draw on top of foundation */
890  AddChildSpriteToFoundation(image, pal, nullptr, foundation_part, extra_offs_x, extra_offs_y - z_offset * ZOOM_LVL_BASE);
891  }
892 }
893 
900 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
901 {
902  if (!IsValidTile(ti->tile)) return;
903 
904  SpriteID sel;
905  if (IsHalftileSlope(ti->tileh)) {
906  Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
907  SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
909 
910  Corner opposite_corner = OppositeCorner(halftile_corner);
911  if (IsSteepSlope(ti->tileh)) {
912  sel = SPR_HALFTILE_SELECTION_DOWN;
913  } else {
914  sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
915  }
916  sel += opposite_corner;
917  } else {
918  sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
919  }
921 }
922 
923 static bool IsPartOfAutoLine(int px, int py)
924 {
925  px -= _thd.selstart.x;
926  py -= _thd.selstart.y;
927 
928  if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
929 
930  switch (_thd.drawstyle & HT_DIR_MASK) {
931  case HT_DIR_X: return py == 0; // x direction
932  case HT_DIR_Y: return px == 0; // y direction
933  case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
934  case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
935  case HT_DIR_VL: return px == py || px == py + 16; // vertical left
936  case HT_DIR_VR: return px == py || px == py - 16; // vertical right
937  default:
938  NOT_REACHED();
939  }
940 }
941 
942 /* [direction][side] */
943 static const HighLightStyle _autorail_type[6][2] = {
944  { HT_DIR_X, HT_DIR_X },
945  { HT_DIR_Y, HT_DIR_Y },
946  { HT_DIR_HU, HT_DIR_HL },
947  { HT_DIR_HL, HT_DIR_HU },
948  { HT_DIR_VL, HT_DIR_VR },
949  { HT_DIR_VR, HT_DIR_VL }
950 };
951 
952 #include "table/autorail.h"
953 
960 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
961 {
962  SpriteID image;
963  PaletteID pal;
964  int offset;
965 
966  FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
967  Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
968  if (IsHalftileSlope(ti->tileh)) {
969  static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
970  Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
971  if (autorail_type != _lower_rail[halftile_corner]) {
972  foundation_part = FOUNDATION_PART_HALFTILE;
973  /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
974  autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
975  }
976  }
977 
978  offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
979  if (offset >= 0) {
980  image = SPR_AUTORAIL_BASE + offset;
981  pal = PAL_NONE;
982  } else {
983  image = SPR_AUTORAIL_BASE - offset;
984  pal = PALETTE_SEL_TILE_RED;
985  }
986 
987  DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
988 }
989 
990 enum TileHighlightType {
991  THT_NONE,
992  THT_WHITE,
993  THT_BLUE,
994  THT_RED,
995 };
996 
999 
1005 static TileHighlightType GetTileHighlightType(TileIndex t)
1006 {
1007  if (_viewport_highlight_station != nullptr) {
1008  if (IsTileType(t, MP_STATION) && GetStationIndex(t) == _viewport_highlight_station->index) return THT_WHITE;
1009  if (_viewport_highlight_station->TileIsInCatchment(t)) return THT_BLUE;
1010  }
1011 
1012  if (_viewport_highlight_town != nullptr) {
1013  if (IsTileType(t, MP_HOUSE)) {
1015  TileHighlightType type = THT_RED;
1016  for (const Station *st : _viewport_highlight_town->stations_near) {
1017  if (st->owner != _current_company) continue;
1018  if (st->TileIsInCatchment(t)) return THT_BLUE;
1019  }
1020  return type;
1021  }
1022  } else if (IsTileType(t, MP_STATION)) {
1023  for (const Station *st : _viewport_highlight_town->stations_near) {
1024  if (st->owner != _current_company) continue;
1025  if (GetStationIndex(t) == st->index) return THT_WHITE;
1026  }
1027  }
1028  }
1029 
1030  return THT_NONE;
1031 }
1032 
1038 static void DrawTileHighlightType(const TileInfo *ti, TileHighlightType tht)
1039 {
1040  switch (tht) {
1041  default:
1042  case THT_NONE: break;
1043  case THT_WHITE: DrawTileSelectionRect(ti, PAL_NONE); break;
1044  case THT_BLUE: DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE); break;
1045  case THT_RED: DrawTileSelectionRect(ti, PALETTE_SEL_TILE_RED); break;
1046  }
1047 }
1048 
1054 {
1055  /* Going through cases in order of computational time. */
1056 
1057  if (_town_local_authority_kdtree.Count() == 0) return;
1058 
1059  /* Tile belongs to town regardless of distance from town. */
1060  if (GetTileType(ti->tile) == MP_HOUSE) {
1061  if (!Town::GetByTile(ti->tile)->show_zone) return;
1062 
1064  return;
1065  }
1066 
1067  /* If the closest town in the highlighted list is far, we can stop searching. */
1068  TownID tid = _town_local_authority_kdtree.FindNearest(TileX(ti->tile), TileY(ti->tile));
1069  Town *closest_highlighted_town = Town::Get(tid);
1070 
1071  if (DistanceManhattan(ti->tile, closest_highlighted_town->xy) >= _settings_game.economy.dist_local_authority) return;
1072 
1073  /* Tile is inside of the local autrhority distance of a highlighted town,
1074  but it is possible that a non-highlighted town is even closer. */
1076 
1077  if (closest_town->show_zone) {
1079  }
1080 
1081 }
1082 
1087 static void DrawTileSelection(const TileInfo *ti)
1088 {
1089  /* Highlight tiles insede local authority of selected towns. */
1091 
1092  /* Draw a red error square? */
1093  bool is_redsq = _thd.redsq == ti->tile;
1095 
1096  TileHighlightType tht = GetTileHighlightType(ti->tile);
1097  DrawTileHighlightType(ti, tht);
1098 
1099  /* No tile selection active? */
1100  if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
1101 
1102  if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
1103  if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
1104  return;
1105  }
1106 
1107  /* Inside the inner area? */
1108  if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
1109  IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
1110 draw_inner:
1111  if (_thd.drawstyle & HT_RECT) {
1112  if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
1113  } else if (_thd.drawstyle & HT_POINT) {
1114  /* Figure out the Z coordinate for the single dot. */
1115  int z = 0;
1116  FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
1117  if (ti->tileh & SLOPE_N) {
1118  z += TILE_HEIGHT;
1120  }
1121  if (IsHalftileSlope(ti->tileh)) {
1122  Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
1123  if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
1124  if (halftile_corner != CORNER_S) {
1125  foundation_part = FOUNDATION_PART_HALFTILE;
1126  if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
1127  }
1128  }
1129  DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
1130  } else if (_thd.drawstyle & HT_RAIL) {
1131  /* autorail highlight piece under cursor */
1132  HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
1133  assert(type < HT_DIR_END);
1134  DrawAutorailSelection(ti, _autorail_type[type][0]);
1135  } else if (IsPartOfAutoLine(ti->x, ti->y)) {
1136  /* autorail highlighting long line */
1137  HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
1138  uint side;
1139 
1140  if (dir == HT_DIR_X || dir == HT_DIR_Y) {
1141  side = 0;
1142  } else {
1143  TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
1144  side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
1145  }
1146 
1147  DrawAutorailSelection(ti, _autorail_type[dir][side]);
1148  }
1149  return;
1150  }
1151 
1152  /* Check if it's inside the outer area? */
1153  if (!is_redsq && (tht == THT_NONE || tht == THT_RED) && _thd.outersize.x > 0 &&
1154  IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
1155  IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
1156  /* Draw a blue rect. */
1158  return;
1159  }
1160 }
1161 
1168 static int GetViewportY(Point tile)
1169 {
1170  /* Each increment in X or Y direction moves down by half a tile, i.e. TILE_PIXELS / 2. */
1171  return (tile.y * (int)(TILE_PIXELS / 2) + tile.x * (int)(TILE_PIXELS / 2) - TilePixelHeightOutsideMap(tile.x, tile.y)) << ZOOM_LVL_SHIFT;
1172 }
1173 
1178 {
1179  assert(_vd.dpi.top <= _vd.dpi.top + _vd.dpi.height);
1180  assert(_vd.dpi.left <= _vd.dpi.left + _vd.dpi.width);
1181 
1182  Point upper_left = InverseRemapCoords(_vd.dpi.left, _vd.dpi.top);
1183  Point upper_right = InverseRemapCoords(_vd.dpi.left + _vd.dpi.width, _vd.dpi.top);
1184 
1185  /* Transformations between tile coordinates and viewport rows/columns: See vp_column_row
1186  * column = y - x
1187  * row = x + y
1188  * x = (row - column) / 2
1189  * y = (row + column) / 2
1190  * Note: (row, columns) pairs are only valid, if they are both even or both odd.
1191  */
1192 
1193  /* Columns overlap with neighbouring columns by a half tile.
1194  * - Left column is column of upper_left (rounded down) and one column to the left.
1195  * - Right column is column of upper_right (rounded up) and one column to the right.
1196  * Note: Integer-division does not round down for negative numbers, so ensure rounding with another increment/decrement.
1197  */
1198  int left_column = (upper_left.y - upper_left.x) / (int)TILE_SIZE - 2;
1199  int right_column = (upper_right.y - upper_right.x) / (int)TILE_SIZE + 2;
1200 
1201  int potential_bridge_height = ZOOM_LVL_BASE * TILE_HEIGHT * _settings_game.construction.max_bridge_height;
1202 
1203  /* Rows overlap with neighbouring rows by a half tile.
1204  * The first row that could possibly be visible is the row above upper_left (if it is at height 0).
1205  * Due to integer-division not rounding down for negative numbers, we need another decrement.
1206  */
1207  int row = (upper_left.x + upper_left.y) / (int)TILE_SIZE - 2;
1208  bool last_row = false;
1209  for (; !last_row; row++) {
1210  last_row = true;
1211  for (int column = left_column; column <= right_column; column++) {
1212  /* Valid row/column? */
1213  if ((row + column) % 2 != 0) continue;
1214 
1215  Point tilecoord;
1216  tilecoord.x = (row - column) / 2;
1217  tilecoord.y = (row + column) / 2;
1218  assert(column == tilecoord.y - tilecoord.x);
1219  assert(row == tilecoord.y + tilecoord.x);
1220 
1221  TileType tile_type;
1222  TileInfo tile_info;
1223  _cur_ti = &tile_info;
1224  tile_info.x = tilecoord.x * TILE_SIZE; // FIXME tile_info should use signed integers
1225  tile_info.y = tilecoord.y * TILE_SIZE;
1226 
1227  if (IsInsideBS(tilecoord.x, 0, MapSizeX()) && IsInsideBS(tilecoord.y, 0, MapSizeY())) {
1228  /* This includes the south border at MapMaxX / MapMaxY. When terraforming we still draw tile selections there. */
1229  tile_info.tile = TileXY(tilecoord.x, tilecoord.y);
1230  tile_type = GetTileType(tile_info.tile);
1231  } else {
1232  tile_info.tile = INVALID_TILE;
1233  tile_type = MP_VOID;
1234  }
1235 
1236  if (tile_type != MP_VOID) {
1237  /* We are inside the map => paint landscape. */
1238  tile_info.tileh = GetTilePixelSlope(tile_info.tile, &tile_info.z);
1239  } else {
1240  /* We are outside the map => paint black. */
1241  tile_info.tileh = GetTilePixelSlopeOutsideMap(tilecoord.x, tilecoord.y, &tile_info.z);
1242  }
1243 
1244  int viewport_y = GetViewportY(tilecoord);
1245 
1246  if (viewport_y + MAX_TILE_EXTENT_BOTTOM < _vd.dpi.top) {
1247  /* The tile in this column is not visible yet.
1248  * Tiles in other columns may be visible, but we need more rows in any case. */
1249  last_row = false;
1250  continue;
1251  }
1252 
1253  int min_visible_height = viewport_y - (_vd.dpi.top + _vd.dpi.height);
1254  bool tile_visible = min_visible_height <= 0;
1255 
1256  if (tile_type != MP_VOID) {
1257  /* Is tile with buildings visible? */
1258  if (min_visible_height < MAX_TILE_EXTENT_TOP) tile_visible = true;
1259 
1260  if (IsBridgeAbove(tile_info.tile)) {
1261  /* Is the bridge visible? */
1262  TileIndex bridge_tile = GetNorthernBridgeEnd(tile_info.tile);
1263  int bridge_height = ZOOM_LVL_BASE * (GetBridgePixelHeight(bridge_tile) - TilePixelHeight(tile_info.tile));
1264  if (min_visible_height < bridge_height + MAX_TILE_EXTENT_TOP) tile_visible = true;
1265  }
1266 
1267  /* Would a higher bridge on a more southern tile be visible?
1268  * If yes, we need to loop over more rows to possibly find one. */
1269  if (min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1270  } else {
1271  /* Outside of map. If we are on the north border of the map, there may still be a bridge visible,
1272  * so we need to loop over more rows to possibly find one. */
1273  if ((tilecoord.x <= 0 || tilecoord.y <= 0) && min_visible_height < potential_bridge_height + MAX_TILE_EXTENT_TOP) last_row = false;
1274  }
1275 
1276  if (tile_visible) {
1277  last_row = false;
1279  _vd.foundation[0] = -1;
1280  _vd.foundation[1] = -1;
1281  _vd.last_foundation_child[0] = nullptr;
1282  _vd.last_foundation_child[1] = nullptr;
1283 
1284  _tile_type_procs[tile_type]->draw_tile_proc(&tile_info);
1285  if (tile_info.tile != INVALID_TILE) DrawTileSelection(&tile_info);
1286  }
1287  }
1288  }
1289 }
1290 
1301 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)
1302 {
1303  bool small = dpi->zoom >= small_from;
1304 
1305  int left = dpi->left;
1306  int top = dpi->top;
1307  int right = left + dpi->width;
1308  int bottom = top + dpi->height;
1309 
1310  int sign_height = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + FONT_HEIGHT_NORMAL + WidgetDimensions::scaled.fullbevel.bottom, dpi->zoom);
1311  int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
1312 
1313  if (bottom < sign->top ||
1314  top > sign->top + sign_height ||
1315  right < sign->center - sign_half_width ||
1316  left > sign->center + sign_half_width) {
1317  return;
1318  }
1319 
1320  if (!small) {
1321  AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
1322  } else {
1323  int shadow_offset = 0;
1324  if (string_small_shadow != STR_NULL) {
1325  shadow_offset = 4;
1326  AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small | 0x8000);
1327  }
1328  AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
1329  colour, sign->width_small | 0x8000);
1330  }
1331 }
1332 
1333 static Rect ExpandRectWithViewportSignMargins(Rect r, ZoomLevel zoom)
1334 {
1335  /* Pessimistically always use normal font, but also assume small font is never larger in either dimension */
1336  const int fh = FONT_HEIGHT_NORMAL;
1337  const int max_tw = _viewport_sign_maxwidth / 2 + 1;
1338  const int expand_y = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + fh + WidgetDimensions::scaled.fullbevel.bottom, zoom);
1339  const int expand_x = ScaleByZoom(WidgetDimensions::scaled.fullbevel.left + max_tw + WidgetDimensions::scaled.fullbevel.right, zoom);
1340 
1341  r.left -= expand_x;
1342  r.right += expand_x;
1343  r.top -= expand_y;
1344  r.bottom += expand_y;
1345 
1346  return r;
1347 }
1348 
1349 static void ViewportAddKdtreeSigns(DrawPixelInfo *dpi)
1350 {
1351  Rect search_rect{ dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height };
1352  search_rect = ExpandRectWithViewportSignMargins(search_rect, dpi->zoom);
1353 
1354  bool show_stations = HasBit(_display_opt, DO_SHOW_STATION_NAMES) && _game_mode != GM_MENU;
1355  bool show_waypoints = HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES) && _game_mode != GM_MENU;
1356  bool show_towns = HasBit(_display_opt, DO_SHOW_TOWN_NAMES) && _game_mode != GM_MENU;
1357  bool show_signs = HasBit(_display_opt, DO_SHOW_SIGNS) && !IsInvisibilitySet(TO_SIGNS);
1358  bool show_competitors = HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS);
1359 
1360  const BaseStation *st;
1361  const Sign *si;
1362 
1363  /* Collect all the items first and draw afterwards, to ensure layering */
1364  std::vector<const BaseStation *> stations;
1365  std::vector<const Town *> towns;
1366  std::vector<const Sign *> signs;
1367 
1368  _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
1369  switch (item.type) {
1370  case ViewportSignKdtreeItem::VKI_STATION:
1371  if (!show_stations) break;
1372  st = BaseStation::Get(item.id.station);
1373 
1374  /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1375  if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1376 
1377  stations.push_back(st);
1378  break;
1379 
1380  case ViewportSignKdtreeItem::VKI_WAYPOINT:
1381  if (!show_waypoints) break;
1382  st = BaseStation::Get(item.id.station);
1383 
1384  /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
1385  if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
1386 
1387  stations.push_back(st);
1388  break;
1389 
1390  case ViewportSignKdtreeItem::VKI_TOWN:
1391  if (!show_towns) break;
1392  towns.push_back(Town::Get(item.id.town));
1393  break;
1394 
1395  case ViewportSignKdtreeItem::VKI_SIGN:
1396  if (!show_signs) break;
1397  si = Sign::Get(item.id.sign);
1398 
1399  /* Don't draw if sign is owned by another company and competitor signs should be hidden.
1400  * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
1401  * companies can leave OWNER_NONE signs after them. */
1402  if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
1403 
1404  signs.push_back(si);
1405  break;
1406 
1407  default:
1408  NOT_REACHED();
1409  }
1410  });
1411 
1412  /* Layering order (bottom to top): Town names, signs, stations */
1413 
1414  for (const auto *t : towns) {
1415  ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &t->cache.sign,
1416  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
1417  STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
1418  t->index, t->cache.population);
1419  }
1420 
1421  for (const auto *si : signs) {
1422  ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &si->sign,
1423  STR_WHITE_SIGN,
1424  (IsTransparencySet(TO_SIGNS) || si->owner == OWNER_DEITY) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
1425  si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : (si->owner == OWNER_DEITY ? INVALID_COLOUR : _company_colours[si->owner]));
1426  }
1427 
1428  for (const auto *st : stations) {
1429  if (Station::IsExpected(st)) {
1430  /* Station */
1432  STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY, STR_NULL,
1433  st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
1434  } else {
1435  /* Waypoint */
1437  STR_VIEWPORT_WAYPOINT, STR_VIEWPORT_WAYPOINT_TINY, STR_NULL,
1438  st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
1439  }
1440  }
1441 }
1442 
1443 
1451 void ViewportSign::UpdatePosition(int center, int top, StringID str, StringID str_small)
1452 {
1453  if (this->width_normal != 0) this->MarkDirty();
1454 
1455  this->top = top;
1456 
1457  char buffer[DRAW_STRING_BUFFER];
1458 
1459  GetString(buffer, str, lastof(buffer));
1461  this->center = center;
1462 
1463  /* zoomed out version */
1464  if (str_small != STR_NULL) {
1465  GetString(buffer, str_small, lastof(buffer));
1466  }
1468 
1469  this->MarkDirty();
1470 }
1471 
1479 {
1480  Rect zoomlevels[ZOOM_LVL_COUNT];
1481 
1482  for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
1483  /* FIXME: This doesn't switch to width_small when appropriate. */
1484  zoomlevels[zoom].left = this->center - ScaleByZoom(this->width_normal / 2 + 1, zoom);
1485  zoomlevels[zoom].top = this->top - ScaleByZoom(1, zoom);
1486  zoomlevels[zoom].right = this->center + ScaleByZoom(this->width_normal / 2 + 1, zoom);
1487  zoomlevels[zoom].bottom = this->top + ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + FONT_HEIGHT_NORMAL + WidgetDimensions::scaled.fullbevel.bottom + 1, zoom);
1488  }
1489 
1490  for (const Window *w : Window::Iterate()) {
1491  Viewport *vp = w->viewport;
1492  if (vp != nullptr && vp->zoom <= maxzoom) {
1493  assert(vp->width != 0);
1494  Rect &zl = zoomlevels[vp->zoom];
1495  MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
1496  }
1497  }
1498 }
1499 
1500 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
1501 {
1502  for (const TileSpriteToDraw &ts : *tstdv) {
1503  DrawSpriteViewport(ts.image, ts.pal, ts.x, ts.y, ts.sub);
1504  }
1505 }
1506 
1509 {
1510  return true;
1511 }
1512 
1514 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
1515 {
1516  if (psdv->size() < 2) return;
1517 
1518  /* We rely on sprites being, for the most part, already ordered.
1519  * So we don't need to move many of them and can keep track of their
1520  * order efficiently by using stack. We always move sprites to the front
1521  * of the current position, i.e. to the top of the stack.
1522  * Also use special constants to indicate sorting state without
1523  * adding extra fields to ParentSpriteToDraw structure.
1524  */
1525  const uint32 ORDER_COMPARED = UINT32_MAX; // Sprite was compared but we still need to compare the ones preceding it
1526  const uint32 ORDER_RETURNED = UINT32_MAX - 1; // Makr sorted sprite in case there are other occurrences of it in the stack
1527  std::stack<ParentSpriteToDraw *> sprite_order;
1528  uint32 next_order = 0;
1529 
1530  std::forward_list<std::pair<int64, ParentSpriteToDraw *>> sprite_list; // We store sprites in a list sorted by xmin+ymin
1531 
1532  /* Initialize sprite list and order. */
1533  for (auto p = psdv->rbegin(); p != psdv->rend(); p++) {
1534  sprite_list.push_front(std::make_pair((*p)->xmin + (*p)->ymin, *p));
1535  sprite_order.push(*p);
1536  (*p)->order = next_order++;
1537  }
1538 
1539  sprite_list.sort();
1540 
1541  std::vector<ParentSpriteToDraw *> preceding; // Temporarily stores sprites that precede current and their position in the list
1542  auto preceding_prev = sprite_list.begin(); // Store iterator in case we need to delete a single preciding sprite
1543  auto out = psdv->begin(); // Iterator to output sorted sprites
1544 
1545  while (!sprite_order.empty()) {
1546 
1547  auto s = sprite_order.top();
1548  sprite_order.pop();
1549 
1550  /* Sprite is already sorted, ignore it. */
1551  if (s->order == ORDER_RETURNED) continue;
1552 
1553  /* Sprite was already compared, just need to output it. */
1554  if (s->order == ORDER_COMPARED) {
1555  *(out++) = s;
1556  s->order = ORDER_RETURNED;
1557  continue;
1558  }
1559 
1560  preceding.clear();
1561 
1562  /* We only need sprites with xmin <= s->xmax && ymin <= s->ymax && zmin <= s->zmax
1563  * So by iterating sprites with xmin + ymin <= s->xmax + s->ymax
1564  * we get all we need and some more that we filter out later.
1565  * We don't include zmin into the sum as there are usually more neighbors on x and y than z
1566  * so including it will actually increase the amount of false positives.
1567  * Also min coordinates can be > max so using max(xmin, xmax) + max(ymin, ymax)
1568  * to ensure that we iterate the current sprite as we need to remove it from the list.
1569  */
1570  auto ssum = std::max(s->xmax, s->xmin) + std::max(s->ymax, s->ymin);
1571  auto prev = sprite_list.before_begin();
1572  auto x = sprite_list.begin();
1573  while (x != sprite_list.end() && ((*x).first <= ssum)) {
1574  auto p = (*x).second;
1575  if (p == s) {
1576  /* We found the current sprite, remove it and move on. */
1577  x = sprite_list.erase_after(prev);
1578  continue;
1579  }
1580 
1581  auto p_prev = prev;
1582  prev = x++;
1583 
1584  if (s->xmax < p->xmin || s->ymax < p->ymin || s->zmax < p->zmin) continue;
1585  if (s->xmin <= p->xmax && // overlap in X?
1586  s->ymin <= p->ymax && // overlap in Y?
1587  s->zmin <= p->zmax) { // overlap in Z?
1588  if (s->xmin + s->xmax + s->ymin + s->ymax + s->zmin + s->zmax <=
1589  p->xmin + p->xmax + p->ymin + p->ymax + p->zmin + p->zmax) {
1590  continue;
1591  }
1592  }
1593  preceding.push_back(p);
1594  preceding_prev = p_prev;
1595  }
1596 
1597  if (preceding.empty()) {
1598  /* No preceding sprites, add current one to the output */
1599  *(out++) = s;
1600  s->order = ORDER_RETURNED;
1601  continue;
1602  }
1603 
1604  /* Optimization for the case when we only have 1 sprite to move. */
1605  if (preceding.size() == 1) {
1606  auto p = preceding[0];
1607  /* We can only output the preceding sprite if there can't be any other sprites preceding it. */
1608  if (p->xmax <= s->xmax && p->ymax <= s->ymax && p->zmax <= s->zmax) {
1609  p->order = ORDER_RETURNED;
1610  s->order = ORDER_RETURNED;
1611  sprite_list.erase_after(preceding_prev);
1612  *(out++) = p;
1613  *(out++) = s;
1614  continue;
1615  }
1616  }
1617 
1618  /* Sort all preceding sprites by order and assign new orders in reverse (as original sorter did). */
1619  std::sort(preceding.begin(), preceding.end(), [](const ParentSpriteToDraw *a, const ParentSpriteToDraw *b) {
1620  return a->order > b->order;
1621  });
1622 
1623  s->order = ORDER_COMPARED;
1624  sprite_order.push(s); // Still need to output so push it back for now
1625 
1626  for (auto p: preceding) {
1627  p->order = next_order++;
1628  sprite_order.push(p);
1629  }
1630  }
1631 }
1632 
1633 
1634 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
1635 {
1636  for (const ParentSpriteToDraw *ps : *psd) {
1637  if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
1638 
1639  int child_idx = ps->first_child;
1640  while (child_idx >= 0) {
1641  const ChildScreenSpriteToDraw *cs = csstdv->data() + child_idx;
1642  child_idx = cs->next;
1643  if (cs->relative) {
1644  DrawSpriteViewport(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
1645  } else {
1646  DrawSpriteViewport(cs->image, cs->pal, ps->x + cs->x, ps->y + cs->y, cs->sub);
1647  }
1648  }
1649  }
1650 }
1651 
1656 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
1657 {
1658  for (const ParentSpriteToDraw *ps : *psd) {
1659  Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
1660  Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner
1661  Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner
1662  Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin ); // bottom front corner
1663 
1664  DrawBox( pt1.x, pt1.y,
1665  pt2.x - pt1.x, pt2.y - pt1.y,
1666  pt3.x - pt1.x, pt3.y - pt1.y,
1667  pt4.x - pt1.x, pt4.y - pt1.y);
1668  }
1669 }
1670 
1675 {
1677  const DrawPixelInfo *dpi = _cur_dpi;
1678  void *dst;
1679  int right = UnScaleByZoom(dpi->width, dpi->zoom);
1680  int bottom = UnScaleByZoom(dpi->height, dpi->zoom);
1681 
1682  int colour = _string_colourmap[_dirty_block_colour & 0xF];
1683 
1684  dst = dpi->dst_ptr;
1685 
1686  byte bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1;
1687  do {
1688  for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
1689  dst = blitter->MoveTo(dst, 0, 1);
1690  } while (--bottom > 0);
1691 }
1692 
1693 static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
1694 {
1695  for (const StringSpriteToDraw &ss : *sstdv) {
1696  TextColour colour = TC_BLACK;
1697  bool small = HasBit(ss.width, 15);
1698  int w = GB(ss.width, 0, 15);
1699  int x = UnScaleByZoom(ss.x, zoom);
1700  int y = UnScaleByZoom(ss.y, zoom);
1702 
1703  SetDParam(0, ss.params[0]);
1704  SetDParam(1, ss.params[1]);
1705 
1706  if (ss.colour != INVALID_COLOUR) {
1707  /* Do not draw signs nor station names if they are set invisible */
1708  if (IsInvisibilitySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) continue;
1709 
1710  if (IsTransparencySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) {
1711  /* Don't draw the rectangle.
1712  * Real colours need the TC_IS_PALETTE_COLOUR flag.
1713  * Otherwise colours from _string_colourmap are assumed. */
1714  colour = (TextColour)_colour_gradient[ss.colour][6] | TC_IS_PALETTE_COLOUR;
1715  } else {
1716  /* Draw the rectangle if 'transparent station signs' is off,
1717  * or if we are drawing a general text sign (STR_WHITE_SIGN). */
1718  DrawFrameRect(
1719  x, y, x + w - 1, y + h - 1, ss.colour,
1721  );
1722  }
1723  }
1724 
1725  DrawString(x + WidgetDimensions::scaled.fullbevel.left, x + w - 1 - WidgetDimensions::scaled.fullbevel.right, y + WidgetDimensions::scaled.fullbevel.top, ss.string, colour, SA_HOR_CENTER, false, small ? FS_SMALL : FS_NORMAL);
1726  }
1727 }
1728 
1729 void ViewportDoDraw(const Viewport *vp, int left, int top, int right, int bottom)
1730 {
1731  DrawPixelInfo *old_dpi = _cur_dpi;
1732  _cur_dpi = &_vd.dpi;
1733 
1734  _vd.dpi.zoom = vp->zoom;
1735  int mask = ScaleByZoom(-1, vp->zoom);
1736 
1738 
1739  _vd.dpi.width = (right - left) & mask;
1740  _vd.dpi.height = (bottom - top) & mask;
1741  _vd.dpi.left = left & mask;
1742  _vd.dpi.top = top & mask;
1743  _vd.dpi.pitch = old_dpi->pitch;
1744  _vd.last_child = nullptr;
1745 
1746  int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
1747  int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
1748 
1749  _vd.dpi.dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
1750 
1752  ViewportAddVehicles(&_vd.dpi);
1753 
1754  ViewportAddKdtreeSigns(&_vd.dpi);
1755 
1756  DrawTextEffects(&_vd.dpi);
1757 
1758  if (_vd.tile_sprites_to_draw.size() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
1759 
1760  for (auto &psd : _vd.parent_sprites_to_draw) {
1761  _vd.parent_sprites_to_sort.push_back(&psd);
1762  }
1763 
1764  _vp_sprite_sorter(&_vd.parent_sprites_to_sort);
1765  ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
1766 
1767  if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
1768  if (_draw_dirty_blocks) ViewportDrawDirtyBlocks();
1769 
1770  DrawPixelInfo dp = _vd.dpi;
1771  ZoomLevel zoom = _vd.dpi.zoom;
1772  dp.zoom = ZOOM_LVL_NORMAL;
1773  dp.width = UnScaleByZoom(dp.width, zoom);
1774  dp.height = UnScaleByZoom(dp.height, zoom);
1775  _cur_dpi = &dp;
1776 
1777  if (vp->overlay != nullptr && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
1778  /* translate to window coordinates */
1779  dp.left = x;
1780  dp.top = y;
1781  vp->overlay->Draw(&dp);
1782  }
1783 
1784  if (_vd.string_sprites_to_draw.size() != 0) {
1785  /* translate to world coordinates */
1786  dp.left = UnScaleByZoom(_vd.dpi.left, zoom);
1787  dp.top = UnScaleByZoom(_vd.dpi.top, zoom);
1788  ViewportDrawStrings(zoom, &_vd.string_sprites_to_draw);
1789  }
1790 
1791  _cur_dpi = old_dpi;
1792 
1793  _vd.string_sprites_to_draw.clear();
1794  _vd.tile_sprites_to_draw.clear();
1795  _vd.parent_sprites_to_draw.clear();
1796  _vd.parent_sprites_to_sort.clear();
1797  _vd.child_screen_sprites_to_draw.clear();
1798 }
1799 
1800 static inline void ViewportDraw(const Viewport *vp, int left, int top, int right, int bottom)
1801 {
1802  if (right <= vp->left || bottom <= vp->top) return;
1803 
1804  if (left >= vp->left + vp->width) return;
1805 
1806  if (left < vp->left) left = vp->left;
1807  if (right > vp->left + vp->width) right = vp->left + vp->width;
1808 
1809  if (top >= vp->top + vp->height) return;
1810 
1811  if (top < vp->top) top = vp->top;
1812  if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
1813 
1814  ViewportDoDraw(vp,
1815  ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
1816  ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
1817  ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
1818  ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
1819  );
1820 }
1821 
1826 {
1828 
1829  DrawPixelInfo *dpi = _cur_dpi;
1830 
1831  dpi->left += this->left;
1832  dpi->top += this->top;
1833 
1834  ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
1835 
1836  dpi->left -= this->left;
1837  dpi->top -= this->top;
1838 }
1839 
1850 static inline void ClampViewportToMap(const Viewport *vp, int *scroll_x, int *scroll_y)
1851 {
1852  /* Centre of the viewport is hot spot. */
1853  Point pt = {
1854  *scroll_x + vp->virtual_width / 2,
1855  *scroll_y + vp->virtual_height / 2
1856  };
1857 
1858  /* Find nearest tile that is within borders of the map. */
1859  bool clamped;
1860  pt = InverseRemapCoords2(pt.x, pt.y, true, &clamped);
1861 
1862  if (clamped) {
1863  /* Convert back to viewport coordinates and remove centering. */
1864  pt = RemapCoords2(pt.x, pt.y);
1865  *scroll_x = pt.x - vp->virtual_width / 2;
1866  *scroll_y = pt.y - vp->virtual_height / 2;
1867  }
1868 }
1869 
1875 {
1876  const Viewport *vp = w->viewport;
1877 
1879  const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
1880  Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
1881 
1882  w->viewport->scrollpos_x = pt.x;
1883  w->viewport->scrollpos_y = pt.y;
1884  SetViewportPosition(w, pt.x, pt.y);
1885  } else {
1886  /* Ensure the destination location is within the map */
1888 
1889  int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
1890  int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
1891 
1892  bool update_overlay = false;
1893  if (delta_x != 0 || delta_y != 0) {
1895  int max_scroll = ScaleByMapSize1D(512 * ZOOM_LVL_BASE);
1896  /* Not at our desired position yet... */
1897  w->viewport->scrollpos_x += Clamp(DivAwayFromZero(delta_x, 4), -max_scroll, max_scroll);
1898  w->viewport->scrollpos_y += Clamp(DivAwayFromZero(delta_y, 4), -max_scroll, max_scroll);
1899  } else {
1902  }
1903  update_overlay = (w->viewport->scrollpos_x == w->viewport->dest_scrollpos_x &&
1905  }
1906 
1908 
1909  SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
1910  if (update_overlay) RebuildViewportOverlay(w);
1911  }
1912 }
1913 
1924 static bool MarkViewportDirty(const Viewport *vp, int left, int top, int right, int bottom)
1925 {
1926  /* Rounding wrt. zoom-out level */
1927  right += (1 << vp->zoom) - 1;
1928  bottom += (1 << vp->zoom) - 1;
1929 
1930  right -= vp->virtual_left;
1931  if (right <= 0) return false;
1932 
1933  bottom -= vp->virtual_top;
1934  if (bottom <= 0) return false;
1935 
1936  left = std::max(0, left - vp->virtual_left);
1937 
1938  if (left >= vp->virtual_width) return false;
1939 
1940  top = std::max(0, top - vp->virtual_top);
1941 
1942  if (top >= vp->virtual_height) return false;
1943 
1944  AddDirtyBlock(
1945  UnScaleByZoomLower(left, vp->zoom) + vp->left,
1946  UnScaleByZoomLower(top, vp->zoom) + vp->top,
1947  UnScaleByZoom(right, vp->zoom) + vp->left + 1,
1948  UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
1949  );
1950 
1951  return true;
1952 }
1953 
1963 bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
1964 {
1965  bool dirty = false;
1966 
1967  for (const Window *w : Window::Iterate()) {
1968  Viewport *vp = w->viewport;
1969  if (vp != nullptr) {
1970  assert(vp->width != 0);
1971  if (MarkViewportDirty(vp, left, top, right, bottom)) dirty = true;
1972  }
1973  }
1974 
1975  return dirty;
1976 }
1977 
1978 void ConstrainAllViewportsZoom()
1979 {
1980  for (Window *w : Window::Iterate()) {
1981  if (w->viewport == nullptr) continue;
1982 
1983  ZoomLevel zoom = static_cast<ZoomLevel>(Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
1984  if (zoom != w->viewport->zoom) {
1985  while (w->viewport->zoom < zoom) DoZoomInOutWindow(ZOOM_OUT, w);
1986  while (w->viewport->zoom > zoom) DoZoomInOutWindow(ZOOM_IN, w);
1987  }
1988  }
1989 }
1990 
1998 void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
1999 {
2000  Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, tile_height_override * TILE_HEIGHT);
2002  pt.x - MAX_TILE_EXTENT_LEFT,
2003  pt.y - MAX_TILE_EXTENT_TOP - ZOOM_LVL_BASE * TILE_HEIGHT * bridge_level_offset,
2004  pt.x + MAX_TILE_EXTENT_RIGHT,
2005  pt.y + MAX_TILE_EXTENT_BOTTOM);
2006 }
2007 
2016 {
2017  int x_size = _thd.size.x;
2018  int y_size = _thd.size.y;
2019 
2020  if (!_thd.diagonal) { // Selecting in a straight rectangle (or a single square)
2021  int x_start = _thd.pos.x;
2022  int y_start = _thd.pos.y;
2023 
2024  if (_thd.outersize.x != 0) {
2025  x_size += _thd.outersize.x;
2026  x_start += _thd.offs.x;
2027  y_size += _thd.outersize.y;
2028  y_start += _thd.offs.y;
2029  }
2030 
2031  x_size -= TILE_SIZE;
2032  y_size -= TILE_SIZE;
2033 
2034  assert(x_size >= 0);
2035  assert(y_size >= 0);
2036 
2037  int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
2038  int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
2039 
2040  x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
2041  y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
2042 
2043  /* make sure everything is multiple of TILE_SIZE */
2044  assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
2045 
2046  /* How it works:
2047  * Suppose we have to mark dirty rectangle of 3x4 tiles:
2048  * x
2049  * xxx
2050  * xxxxx
2051  * xxxxx
2052  * xxx
2053  * x
2054  * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
2055  * 1) x 2) x
2056  * xxx Oxx
2057  * Oxxxx xOxxx
2058  * xxxxx Oxxxx
2059  * xxx xxx
2060  * x x
2061  * And so forth...
2062  */
2063 
2064  int top_x = x_end; // coordinates of top dirty tile
2065  int top_y = y_start;
2066  int bot_x = top_x; // coordinates of bottom dirty tile
2067  int bot_y = top_y;
2068 
2069  do {
2070  /* topmost dirty point */
2071  TileIndex top_tile = TileVirtXY(top_x, top_y);
2072  Point top = RemapCoords(top_x, top_y, GetTileMaxPixelZ(top_tile));
2073 
2074  /* bottommost point */
2075  TileIndex bottom_tile = TileVirtXY(bot_x, bot_y);
2076  Point bot = RemapCoords(bot_x + TILE_SIZE, bot_y + TILE_SIZE, GetTilePixelZ(bottom_tile)); // bottommost point
2077 
2078  /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
2079  * tile height/slope affects only the 'y' on-screen coordinate! */
2080 
2081  int l = top.x - TILE_PIXELS * ZOOM_LVL_BASE; // 'x' coordinate of left side of the dirty rectangle
2082  int t = top.y; // 'y' coordinate of top side of the dirty rectangle
2083  int r = top.x + TILE_PIXELS * ZOOM_LVL_BASE; // 'x' coordinate of right side of the dirty rectangle
2084  int b = bot.y; // 'y' coordinate of bottom side of the dirty rectangle
2085 
2086  static const int OVERLAY_WIDTH = 4 * ZOOM_LVL_BASE; // part of selection sprites is drawn outside the selected area (in particular: terraforming)
2087 
2088  /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
2089  MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT * ZOOM_LVL_BASE, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
2090 
2091  /* haven't we reached the topmost tile yet? */
2092  if (top_x != x_start) {
2093  top_x -= TILE_SIZE;
2094  } else {
2095  top_y += TILE_SIZE;
2096  }
2097 
2098  /* the way the bottom tile changes is different when we reach the bottommost tile */
2099  if (bot_y != y_end) {
2100  bot_y += TILE_SIZE;
2101  } else {
2102  bot_x -= TILE_SIZE;
2103  }
2104  } while (bot_x >= top_x);
2105  } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
2106  /* a_size, b_size describe a rectangle with rotated coordinates */
2107  int a_size = x_size + y_size, b_size = x_size - y_size;
2108 
2109  int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2110  int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
2111 
2112  for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
2113  for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
2114  uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
2115  uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
2116 
2117  if (x < MapMaxX() && y < MapMaxY()) {
2118  MarkTileDirtyByTile(TileXY(x, y));
2119  }
2120  }
2121  }
2122  }
2123 }
2124 
2125 
2126 void SetSelectionRed(bool b)
2127 {
2128  _thd.make_square_red = b;
2130 }
2131 
2140 static bool CheckClickOnViewportSign(const Viewport *vp, int x, int y, const ViewportSign *sign)
2141 {
2142  bool small = (vp->zoom >= ZOOM_LVL_OUT_16X);
2143  int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
2144  int sign_height = ScaleByZoom(WidgetDimensions::scaled.fullbevel.top + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + WidgetDimensions::scaled.fullbevel.bottom, vp->zoom);
2145 
2146  return y >= sign->top && y < sign->top + sign_height &&
2147  x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
2148 }
2149 
2150 
2158 static bool CheckClickOnViewportSign(const Viewport *vp, int x, int y)
2159 {
2160  if (_game_mode == GM_MENU) return false;
2161 
2162  x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
2163  y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
2164 
2165  Rect search_rect{ x - 1, y - 1, x + 1, y + 1 };
2166  search_rect = ExpandRectWithViewportSignMargins(search_rect, vp->zoom);
2167 
2170  bool show_towns = HasBit(_display_opt, DO_SHOW_TOWN_NAMES);
2171  bool show_signs = HasBit(_display_opt, DO_SHOW_SIGNS) && !IsInvisibilitySet(TO_SIGNS);
2172  bool show_competitors = HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS);
2173 
2174  /* Topmost of each type that was hit */
2175  BaseStation *st = nullptr, *last_st = nullptr;
2176  Town *t = nullptr, *last_t = nullptr;
2177  Sign *si = nullptr, *last_si = nullptr;
2178 
2179  /* See ViewportAddKdtreeSigns() for details on the search logic */
2180  _viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
2181  switch (item.type) {
2182  case ViewportSignKdtreeItem::VKI_STATION:
2183  if (!show_stations) break;
2184  st = BaseStation::Get(item.id.station);
2185  if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2186  if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2187  break;
2188 
2189  case ViewportSignKdtreeItem::VKI_WAYPOINT:
2190  if (!show_waypoints) break;
2191  st = BaseStation::Get(item.id.station);
2192  if (!show_competitors && _local_company != st->owner && st->owner != OWNER_NONE) break;
2193  if (CheckClickOnViewportSign(vp, x, y, &st->sign)) last_st = st;
2194  break;
2195 
2196  case ViewportSignKdtreeItem::VKI_TOWN:
2197  if (!show_towns) break;
2198  t = Town::Get(item.id.town);
2199  if (CheckClickOnViewportSign(vp, x, y, &t->cache.sign)) last_t = t;
2200  break;
2201 
2202  case ViewportSignKdtreeItem::VKI_SIGN:
2203  if (!show_signs) break;
2204  si = Sign::Get(item.id.sign);
2205  if (!show_competitors && _local_company != si->owner && si->owner != OWNER_DEITY) break;
2206  if (CheckClickOnViewportSign(vp, x, y, &si->sign)) last_si = si;
2207  break;
2208 
2209  default:
2210  NOT_REACHED();
2211  }
2212  });
2213 
2214  /* Select which hit to handle based on priority */
2215  if (last_st != nullptr) {
2216  if (Station::IsExpected(last_st)) {
2217  ShowStationViewWindow(last_st->index);
2218  } else {
2220  }
2221  return true;
2222  } else if (last_t != nullptr) {
2223  ShowTownViewWindow(last_t->index);
2224  return true;
2225  } else if (last_si != nullptr) {
2226  HandleClickOnSign(last_si);
2227  return true;
2228  } else {
2229  return false;
2230  }
2231 }
2232 
2233 
2234 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeStation(StationID id)
2235 {
2237  item.type = VKI_STATION;
2238  item.id.station = id;
2239 
2240  const Station *st = Station::Get(id);
2241  assert(st->sign.kdtree_valid);
2242  item.center = st->sign.center;
2243  item.top = st->sign.top;
2244 
2245  /* Assume the sign can be a candidate for drawing, so measure its width */
2246  _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, st->sign.width_normal);
2247 
2248  return item;
2249 }
2250 
2251 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeWaypoint(StationID id)
2252 {
2254  item.type = VKI_WAYPOINT;
2255  item.id.station = id;
2256 
2257  const Waypoint *st = Waypoint::Get(id);
2258  assert(st->sign.kdtree_valid);
2259  item.center = st->sign.center;
2260  item.top = st->sign.top;
2261 
2262  /* Assume the sign can be a candidate for drawing, so measure its width */
2263  _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, st->sign.width_normal);
2264 
2265  return item;
2266 }
2267 
2268 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeTown(TownID id)
2269 {
2271  item.type = VKI_TOWN;
2272  item.id.town = id;
2273 
2274  const Town *town = Town::Get(id);
2275  assert(town->cache.sign.kdtree_valid);
2276  item.center = town->cache.sign.center;
2277  item.top = town->cache.sign.top;
2278 
2279  /* Assume the sign can be a candidate for drawing, so measure its width */
2280  _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, town->cache.sign.width_normal);
2281 
2282  return item;
2283 }
2284 
2285 ViewportSignKdtreeItem ViewportSignKdtreeItem::MakeSign(SignID id)
2286 {
2288  item.type = VKI_SIGN;
2289  item.id.sign = id;
2290 
2291  const Sign *sign = Sign::Get(id);
2292  assert(sign->sign.kdtree_valid);
2293  item.center = sign->sign.center;
2294  item.top = sign->sign.top;
2295 
2296  /* Assume the sign can be a candidate for drawing, so measure its width */
2297  _viewport_sign_maxwidth = std::max<int>(_viewport_sign_maxwidth, sign->sign.width_normal);
2298 
2299  return item;
2300 }
2301 
2302 void RebuildViewportKdtree()
2303 {
2304  /* Reset biggest size sign seen */
2305  _viewport_sign_maxwidth = 0;
2306 
2307  std::vector<ViewportSignKdtreeItem> items;
2309 
2310  for (const Station *st : Station::Iterate()) {
2311  if (st->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeStation(st->index));
2312  }
2313 
2314  for (const Waypoint *wp : Waypoint::Iterate()) {
2315  if (wp->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeWaypoint(wp->index));
2316  }
2317 
2318  for (const Town *town : Town::Iterate()) {
2319  if (town->cache.sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeTown(town->index));
2320  }
2321 
2322  for (const Sign *sign : Sign::Iterate()) {
2323  if (sign->sign.kdtree_valid) items.push_back(ViewportSignKdtreeItem::MakeSign(sign->index));
2324  }
2325 
2326  _viewport_sign_kdtree.Build(items.begin(), items.end());
2327 }
2328 
2329 
2330 static bool CheckClickOnLandscape(const Viewport *vp, int x, int y)
2331 {
2332  Point pt = TranslateXYToTileCoord(vp, x, y);
2333 
2334  if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
2335  return true;
2336 }
2337 
2338 static void PlaceObject()
2339 {
2340  Point pt;
2341  Window *w;
2342 
2343  pt = GetTileBelowCursor();
2344  if (pt.x == -1) return;
2345 
2346  if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
2347  pt.x += TILE_SIZE / 2;
2348  pt.y += TILE_SIZE / 2;
2349  }
2350 
2351  _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
2352  _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
2353 
2354  w = _thd.GetCallbackWnd();
2355  if (w != nullptr) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
2356 }
2357 
2358 
2359 bool HandleViewportClicked(const Viewport *vp, int x, int y)
2360 {
2361  const Vehicle *v = CheckClickOnVehicle(vp, x, y);
2362 
2363  if (_thd.place_mode & HT_VEHICLE) {
2364  if (v != nullptr && VehicleClicked(v)) return true;
2365  }
2366 
2367  /* Vehicle placement mode already handled above. */
2368  if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2369  PlaceObject();
2370  return true;
2371  }
2372 
2373  if (CheckClickOnViewportSign(vp, x, y)) return true;
2374  bool result = CheckClickOnLandscape(vp, x, y);
2375 
2376  if (v != nullptr) {
2377  Debug(misc, 2, "Vehicle {} (index {}) at {}", v->unitnumber, v->index, fmt::ptr(v));
2379  v = v->First();
2380  if (_ctrl_pressed && v->owner == _local_company) {
2381  StartStopVehicle(v, true);
2382  } else {
2384  }
2385  }
2386  return true;
2387  }
2388  return result;
2389 }
2390 
2391 void RebuildViewportOverlay(Window *w)
2392 {
2393  if (w->viewport->overlay != nullptr &&
2394  w->viewport->overlay->GetCompanyMask() != 0 &&
2395  w->viewport->overlay->GetCargoMask() != 0) {
2396  w->viewport->overlay->SetDirty();
2397  w->SetDirty();
2398  }
2399 }
2400 
2410 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
2411 {
2412  /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
2413  if (z == -1) {
2414  if ( x >= 0 && x <= (int)MapSizeX() * (int)TILE_SIZE - 1
2415  && y >= 0 && y <= (int)MapSizeY() * (int)TILE_SIZE - 1) {
2416  z = GetSlopePixelZ(x, y);
2417  } else {
2418  z = TileHeightOutsideMap(x / (int)TILE_SIZE, y / (int)TILE_SIZE);
2419  }
2420  }
2421 
2422  Point pt = MapXYZToViewport(w->viewport, x, y, z);
2424 
2425  if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
2426 
2427  if (instant) {
2428  w->viewport->scrollpos_x = pt.x;
2429  w->viewport->scrollpos_y = pt.y;
2430  RebuildViewportOverlay(w);
2431  }
2432 
2433  w->viewport->dest_scrollpos_x = pt.x;
2434  w->viewport->dest_scrollpos_y = pt.y;
2435  return true;
2436 }
2437 
2445 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
2446 {
2447  return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
2448 }
2449 
2456 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
2457 {
2458  return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
2459 }
2460 
2466 {
2467  TileIndex old;
2468 
2469  old = _thd.redsq;
2470  _thd.redsq = tile;
2471 
2472  if (tile != old) {
2473  if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
2474  if (old != INVALID_TILE) MarkTileDirtyByTile(old);
2475  }
2476 }
2477 
2483 void SetTileSelectSize(int w, int h)
2484 {
2485  _thd.new_size.x = w * TILE_SIZE;
2486  _thd.new_size.y = h * TILE_SIZE;
2487  _thd.new_outersize.x = 0;
2488  _thd.new_outersize.y = 0;
2489 }
2490 
2491 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
2492 {
2493  _thd.offs.x = ox * TILE_SIZE;
2494  _thd.offs.y = oy * TILE_SIZE;
2495  _thd.new_outersize.x = sx * TILE_SIZE;
2496  _thd.new_outersize.y = sy * TILE_SIZE;
2497 }
2498 
2500 static HighLightStyle GetAutorailHT(int x, int y)
2501 {
2502  return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
2503 }
2504 
2509 {
2510  this->pos.x = 0;
2511  this->pos.y = 0;
2512  this->new_pos.x = 0;
2513  this->new_pos.y = 0;
2514 }
2515 
2521 {
2522  return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
2523 }
2524 
2530 {
2531  return FindWindowById(this->window_class, this->window_number);
2532 }
2533 
2534 
2535 
2544 {
2545  int x1;
2546  int y1;
2547 
2548  if (_thd.freeze) return;
2549 
2550  HighLightStyle new_drawstyle = HT_NONE;
2551  bool new_diagonal = false;
2552 
2553  if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
2554  x1 = _thd.selend.x;
2555  y1 = _thd.selend.y;
2556  if (x1 != -1) {
2557  int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
2558  int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
2559  x1 &= ~TILE_UNIT_MASK;
2560  y1 &= ~TILE_UNIT_MASK;
2561 
2562  if (_thd.IsDraggingDiagonal()) {
2563  new_diagonal = true;
2564  } else {
2565  if (x1 >= x2) Swap(x1, x2);
2566  if (y1 >= y2) Swap(y1, y2);
2567  }
2568  _thd.new_pos.x = x1;
2569  _thd.new_pos.y = y1;
2570  _thd.new_size.x = x2 - x1;
2571  _thd.new_size.y = y2 - y1;
2572  if (!new_diagonal) {
2573  _thd.new_size.x += TILE_SIZE;
2574  _thd.new_size.y += TILE_SIZE;
2575  }
2576  new_drawstyle = _thd.next_drawstyle;
2577  }
2578  } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
2579  Point pt = GetTileBelowCursor();
2580  x1 = pt.x;
2581  y1 = pt.y;
2582  if (x1 != -1) {
2583  switch (_thd.place_mode & HT_DRAG_MASK) {
2584  case HT_RECT:
2585  new_drawstyle = HT_RECT;
2586  break;
2587  case HT_POINT:
2588  new_drawstyle = HT_POINT;
2589  x1 += TILE_SIZE / 2;
2590  y1 += TILE_SIZE / 2;
2591  break;
2592  case HT_RAIL:
2593  /* Draw one highlighted tile in any direction */
2594  new_drawstyle = GetAutorailHT(pt.x, pt.y);
2595  break;
2596  case HT_LINE:
2597  switch (_thd.place_mode & HT_DIR_MASK) {
2598  case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
2599  case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
2600 
2601  case HT_DIR_HU:
2602  case HT_DIR_HL:
2603  new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2604  break;
2605 
2606  case HT_DIR_VL:
2607  case HT_DIR_VR:
2608  new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2609  break;
2610 
2611  default: NOT_REACHED();
2612  }
2613  _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
2614  _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
2615  break;
2616  default:
2617  NOT_REACHED();
2618  }
2619  _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
2620  _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
2621  }
2622  }
2623 
2624  /* redraw selection */
2625  if (_thd.drawstyle != new_drawstyle ||
2626  _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
2627  _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
2628  _thd.outersize.x != _thd.new_outersize.x ||
2629  _thd.outersize.y != _thd.new_outersize.y ||
2630  _thd.diagonal != new_diagonal) {
2631  /* Clear the old tile selection? */
2633 
2634  _thd.drawstyle = new_drawstyle;
2635  _thd.pos = _thd.new_pos;
2636  _thd.size = _thd.new_size;
2637  _thd.outersize = _thd.new_outersize;
2638  _thd.diagonal = new_diagonal;
2639  _thd.dirty = 0xff;
2640 
2641  /* Draw the new tile selection? */
2642  if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
2643  }
2644 }
2645 
2653 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_EXIT_VIEWPORT)
2654 {
2655  if (!_settings_client.gui.measure_tooltip) return;
2656  GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
2657 }
2658 
2659 static void HideMeasurementTooltips()
2660 {
2662 }
2663 
2666 {
2667  _thd.select_method = method;
2668  _thd.select_proc = process;
2669  _thd.selend.x = TileX(tile) * TILE_SIZE;
2670  _thd.selstart.x = TileX(tile) * TILE_SIZE;
2671  _thd.selend.y = TileY(tile) * TILE_SIZE;
2672  _thd.selstart.y = TileY(tile) * TILE_SIZE;
2673 
2674  /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
2675  * In effect, placement starts from the centre of a tile
2676  */
2677  if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
2678  _thd.selend.x += TILE_SIZE / 2;
2679  _thd.selend.y += TILE_SIZE / 2;
2680  _thd.selstart.x += TILE_SIZE / 2;
2681  _thd.selstart.y += TILE_SIZE / 2;
2682  }
2683 
2684  HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
2685  if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
2686  _thd.place_mode = HT_SPECIAL | others;
2687  _thd.next_drawstyle = HT_RECT | others;
2688  } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
2689  _thd.place_mode = HT_SPECIAL | others;
2690  _thd.next_drawstyle = _thd.drawstyle | others;
2691  } else {
2692  _thd.place_mode = HT_SPECIAL | others;
2693  _thd.next_drawstyle = HT_POINT | others;
2694  }
2696 }
2697 
2700 {
2701  _thd.select_method = VPM_X_AND_Y;
2702  _thd.select_proc = process;
2703  _thd.selstart.x = 0;
2704  _thd.selstart.y = 0;
2705  _thd.next_drawstyle = HT_RECT;
2706 
2708 }
2709 
2710 void VpSetPlaceSizingLimit(int limit)
2711 {
2712  _thd.sizelimit = limit;
2713 }
2714 
2721 {
2722  uint64 distance = DistanceManhattan(from, to) + 1;
2723 
2724  _thd.selend.x = TileX(to) * TILE_SIZE;
2725  _thd.selend.y = TileY(to) * TILE_SIZE;
2726  _thd.selstart.x = TileX(from) * TILE_SIZE;
2727  _thd.selstart.y = TileY(from) * TILE_SIZE;
2728  _thd.next_drawstyle = HT_RECT;
2729 
2730  /* show measurement only if there is any length to speak of */
2731  if (distance > 1) {
2732  ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance);
2733  } else {
2734  HideMeasurementTooltips();
2735  }
2736 }
2737 
2738 static void VpStartPreSizing()
2739 {
2740  _thd.selend.x = -1;
2742 }
2743 
2749 {
2750  int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
2751  int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
2752  int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
2753  int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
2754 
2755  switch (mode) {
2756  default: NOT_REACHED();
2757  case 0: // end piece is lower right
2758  if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2759  if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2760  return HT_DIR_Y;
2761 
2762  case 1:
2763  if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2764  if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2765  return HT_DIR_Y;
2766 
2767  case 2:
2768  if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
2769  if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
2770  return HT_DIR_X;
2771 
2772  case 3:
2773  if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
2774  if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
2775  return HT_DIR_X;
2776  }
2777 }
2778 
2792 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
2793 {
2794  uint start_x = TileX(start_tile);
2795  uint start_y = TileY(start_tile);
2796  uint end_x = TileX(end_tile);
2797  uint end_y = TileY(end_tile);
2798 
2799  switch (style & HT_DRAG_MASK) {
2800  case HT_RAIL:
2801  case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
2802 
2803  case HT_RECT:
2804  case HT_POINT: return (end_x != start_x && end_y < start_y);
2805  default: NOT_REACHED();
2806  }
2807 
2808  return false;
2809 }
2810 
2826 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
2827 {
2828  bool swap = SwapDirection(style, start_tile, end_tile);
2829  uint h0, h1; // Start height and end height.
2830 
2831  if (start_tile == end_tile) return 0;
2832  if (swap) Swap(start_tile, end_tile);
2833 
2834  switch (style & HT_DRAG_MASK) {
2835  case HT_RECT: {
2836  static const TileIndexDiffC heightdiff_area_by_dir[] = {
2837  /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
2838  /* End */ {0, 1}, /* Dragging east */ {1, 1} // Dragging south
2839  };
2840 
2841  /* In the case of an area we can determine whether we were dragging south or
2842  * east by checking the X-coordinates of the tiles */
2843  byte style_t = (byte)(TileX(end_tile) > TileX(start_tile));
2844  start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
2845  end_tile = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
2846  FALLTHROUGH;
2847  }
2848 
2849  case HT_POINT:
2850  h0 = TileHeight(start_tile);
2851  h1 = TileHeight(end_tile);
2852  break;
2853  default: { // All other types, this is mostly only line/autorail
2854  static const HighLightStyle flip_style_direction[] = {
2856  };
2857  static const TileIndexDiffC heightdiff_line_by_dir[] = {
2858  /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X */ {0, 1}, {1, 1}, // HT_DIR_Y
2859  /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
2860  /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
2861 
2862  /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X */ {1, 0}, {0, 0}, // HT_DIR_Y
2863  /* End */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
2864  /* End */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
2865  };
2866 
2867  distance %= 2; // we're only interested if the distance is even or uneven
2868  style &= HT_DIR_MASK;
2869 
2870  /* To handle autorail, we do some magic to be able to use a lookup table.
2871  * Firstly if we drag the other way around, we switch start&end, and if needed
2872  * also flip the drag-position. Eg if it was on the left, and the distance is even
2873  * that means the end, which is now the start is on the right */
2874  if (swap && distance == 0) style = flip_style_direction[style];
2875 
2876  /* Use lookup table for start-tile based on HighLightStyle direction */
2877  byte style_t = style * 2;
2878  assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
2879  h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
2880  uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
2881  h0 = std::max(h0, ht);
2882 
2883  /* Use lookup table for end-tile based on HighLightStyle direction
2884  * flip around side (lower/upper, left/right) based on distance */
2885  if (distance == 0) style_t = flip_style_direction[style] * 2;
2886  assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
2887  h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
2888  ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
2889  h1 = std::max(h1, ht);
2890  break;
2891  }
2892  }
2893 
2894  if (swap) Swap(h0, h1);
2895  return (int)(h1 - h0) * TILE_HEIGHT_STEP;
2896 }
2897 
2898 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
2899 
2906 static void CheckUnderflow(int &test, int &other, int mult)
2907 {
2908  if (test >= 0) return;
2909 
2910  other += mult * test;
2911  test = 0;
2912 }
2913 
2921 static void CheckOverflow(int &test, int &other, int max, int mult)
2922 {
2923  if (test <= max) return;
2924 
2925  other += mult * (test - max);
2926  test = max;
2927 }
2928 
2930 static void CalcRaildirsDrawstyle(int x, int y, int method)
2931 {
2932  HighLightStyle b;
2933 
2934  int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
2935  int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
2936  uint w = abs(dx) + TILE_SIZE;
2937  uint h = abs(dy) + TILE_SIZE;
2938 
2939  if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
2940  /* We 'force' a selection direction; first four rail buttons. */
2941  method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
2942  int raw_dx = _thd.selstart.x - _thd.selend.x;
2943  int raw_dy = _thd.selstart.y - _thd.selend.y;
2944  switch (method) {
2945  case VPM_FIX_X:
2946  b = HT_LINE | HT_DIR_Y;
2947  x = _thd.selstart.x;
2948  break;
2949 
2950  case VPM_FIX_Y:
2951  b = HT_LINE | HT_DIR_X;
2952  y = _thd.selstart.y;
2953  break;
2954 
2955  case VPM_FIX_HORIZONTAL:
2956  if (dx == -dy) {
2957  /* We are on a straight horizontal line. Determine the 'rail'
2958  * to build based the sub tile location. */
2960  } else {
2961  /* We are not on a straight line. Determine the rail to build
2962  * based on whether we are above or below it. */
2963  b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
2964 
2965  /* Calculate where a horizontal line through the start point and
2966  * a vertical line from the selected end point intersect and
2967  * use that point as the end point. */
2968  int offset = (raw_dx - raw_dy) / 2;
2969  x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
2970  y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
2971 
2972  /* 'Build' the last half rail tile if needed */
2973  if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
2974  if (dx + dy >= (int)TILE_SIZE) {
2975  x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2976  } else {
2977  y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
2978  }
2979  }
2980 
2981  /* Make sure we do not overflow the map! */
2982  CheckUnderflow(x, y, 1);
2983  CheckUnderflow(y, x, 1);
2984  CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
2985  CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
2986  assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
2987  }
2988  break;
2989 
2990  case VPM_FIX_VERTICAL:
2991  if (dx == dy) {
2992  /* We are on a straight vertical line. Determine the 'rail'
2993  * to build based the sub tile location. */
2994  b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2995  } else {
2996  /* We are not on a straight line. Determine the rail to build
2997  * based on whether we are left or right from it. */
2998  b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
2999 
3000  /* Calculate where a vertical line through the start point and
3001  * a horizontal line from the selected end point intersect and
3002  * use that point as the end point. */
3003  int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
3004  x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
3005  y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
3006 
3007  /* 'Build' the last half rail tile if needed */
3008  if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
3009  if (dx - dy < 0) {
3010  y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
3011  } else {
3012  x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
3013  }
3014  }
3015 
3016  /* Make sure we do not overflow the map! */
3017  CheckUnderflow(x, y, -1);
3018  CheckUnderflow(y, x, -1);
3019  CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
3020  CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
3021  assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
3022  }
3023  break;
3024 
3025  default:
3026  NOT_REACHED();
3027  }
3028  } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
3029  if (method & VPM_RAILDIRS) {
3030  b = GetAutorailHT(x, y);
3031  } else { // rect for autosignals on one tile
3032  b = HT_RECT;
3033  }
3034  } else if (h == TILE_SIZE) { // Is this in X direction?
3035  if (dx == (int)TILE_SIZE) { // 2x1 special handling
3036  b = (Check2x1AutoRail(3)) | HT_LINE;
3037  } else if (dx == -(int)TILE_SIZE) {
3038  b = (Check2x1AutoRail(2)) | HT_LINE;
3039  } else {
3040  b = HT_LINE | HT_DIR_X;
3041  }
3042  y = _thd.selstart.y;
3043  } else if (w == TILE_SIZE) { // Or Y direction?
3044  if (dy == (int)TILE_SIZE) { // 2x1 special handling
3045  b = (Check2x1AutoRail(1)) | HT_LINE;
3046  } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
3047  b = (Check2x1AutoRail(0)) | HT_LINE;
3048  } else {
3049  b = HT_LINE | HT_DIR_Y;
3050  }
3051  x = _thd.selstart.x;
3052  } else if (w > h * 2) { // still count as x dir?
3053  b = HT_LINE | HT_DIR_X;
3054  y = _thd.selstart.y;
3055  } else if (h > w * 2) { // still count as y dir?
3056  b = HT_LINE | HT_DIR_Y;
3057  x = _thd.selstart.x;
3058  } else { // complicated direction
3059  int d = w - h;
3060  _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
3061  _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
3062 
3063  /* four cases. */
3064  if (x > _thd.selstart.x) {
3065  if (y > _thd.selstart.y) {
3066  /* south */
3067  if (d == 0) {
3068  b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
3069  } else if (d >= 0) {
3070  x = _thd.selstart.x + h;
3071  b = HT_LINE | HT_DIR_VL;
3072  } else {
3073  y = _thd.selstart.y + w;
3074  b = HT_LINE | HT_DIR_VR;
3075  }
3076  } else {
3077  /* west */
3078  if (d == 0) {
3080  } else if (d >= 0) {
3081  x = _thd.selstart.x + h;
3082  b = HT_LINE | HT_DIR_HL;
3083  } else {
3084  y = _thd.selstart.y - w;
3085  b = HT_LINE | HT_DIR_HU;
3086  }
3087  }
3088  } else {
3089  if (y > _thd.selstart.y) {
3090  /* east */
3091  if (d == 0) {
3093  } else if (d >= 0) {
3094  x = _thd.selstart.x - h;
3095  b = HT_LINE | HT_DIR_HU;
3096  } else {
3097  y = _thd.selstart.y + w;
3098  b = HT_LINE | HT_DIR_HL;
3099  }
3100  } else {
3101  /* north */
3102  if (d == 0) {
3103  b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
3104  } else if (d >= 0) {
3105  x = _thd.selstart.x - h;
3106  b = HT_LINE | HT_DIR_VR;
3107  } else {
3108  y = _thd.selstart.y - w;
3109  b = HT_LINE | HT_DIR_VL;
3110  }
3111  }
3112  }
3113  }
3114 
3116  TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
3117  TileIndex t1 = TileVirtXY(x, y);
3118  uint distance = DistanceManhattan(t0, t1) + 1;
3119  byte index = 0;
3120  uint64 params[2];
3121 
3122  if (distance != 1) {
3123  int heightdiff = CalcHeightdiff(b, distance, t0, t1);
3124  /* If we are showing a tooltip for horizontal or vertical drags,
3125  * 2 tiles have a length of 1. To bias towards the ceiling we add
3126  * one before division. It feels more natural to count 3 lengths as 2 */
3127  if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
3128  distance = CeilDiv(distance, 2);
3129  }
3130 
3131  params[index++] = distance;
3132  if (heightdiff != 0) params[index++] = heightdiff;
3133  }
3134 
3135  ShowMeasurementTooltips(measure_strings_length[index], index, params);
3136  }
3137 
3138  _thd.selend.x = x;
3139  _thd.selend.y = y;
3140  _thd.next_drawstyle = b;
3141 }
3142 
3151 {
3152  int sx, sy;
3153  HighLightStyle style;
3154 
3155  if (x == -1) {
3156  _thd.selend.x = -1;
3157  return;
3158  }
3159 
3160  /* Special handling of drag in any (8-way) direction */
3161  if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
3162  _thd.selend.x = x;
3163  _thd.selend.y = y;
3164  CalcRaildirsDrawstyle(x, y, method);
3165  return;
3166  }
3167 
3168  /* Needed so level-land is placed correctly */
3169  if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
3170  x += TILE_SIZE / 2;
3171  y += TILE_SIZE / 2;
3172  }
3173 
3174  sx = _thd.selstart.x;
3175  sy = _thd.selstart.y;
3176 
3177  int limit = 0;
3178 
3179  switch (method) {
3180  case VPM_X_OR_Y: // drag in X or Y direction
3181  if (abs(sy - y) < abs(sx - x)) {
3182  y = sy;
3183  style = HT_DIR_X;
3184  } else {
3185  x = sx;
3186  style = HT_DIR_Y;
3187  }
3188  goto calc_heightdiff_single_direction;
3189 
3190  case VPM_X_LIMITED: // Drag in X direction (limited size).
3191  limit = (_thd.sizelimit - 1) * TILE_SIZE;
3192  FALLTHROUGH;
3193 
3194  case VPM_FIX_X: // drag in Y direction
3195  x = sx;
3196  style = HT_DIR_Y;
3197  goto calc_heightdiff_single_direction;
3198 
3199  case VPM_Y_LIMITED: // Drag in Y direction (limited size).
3200  limit = (_thd.sizelimit - 1) * TILE_SIZE;
3201  FALLTHROUGH;
3202 
3203  case VPM_FIX_Y: // drag in X direction
3204  y = sy;
3205  style = HT_DIR_X;
3206 
3207 calc_heightdiff_single_direction:;
3208  if (limit > 0) {
3209  x = sx + Clamp(x - sx, -limit, limit);
3210  y = sy + Clamp(y - sy, -limit, limit);
3211  }
3213  TileIndex t0 = TileVirtXY(sx, sy);
3214  TileIndex t1 = TileVirtXY(x, y);
3215  uint distance = DistanceManhattan(t0, t1) + 1;
3216  byte index = 0;
3217  uint64 params[2];
3218 
3219  if (distance != 1) {
3220  /* With current code passing a HT_LINE style to calculate the height
3221  * difference is enough. However if/when a point-tool is created
3222  * with this method, function should be called with new_style (below)
3223  * instead of HT_LINE | style case HT_POINT is handled specially
3224  * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
3225  int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
3226 
3227  params[index++] = distance;
3228  if (heightdiff != 0) params[index++] = heightdiff;
3229  }
3230 
3231  ShowMeasurementTooltips(measure_strings_length[index], index, params);
3232  }
3233  break;
3234 
3235  case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
3236  limit = (_thd.sizelimit - 1) * TILE_SIZE;
3237  x = sx + Clamp(x - sx, -limit, limit);
3238  y = sy + Clamp(y - sy, -limit, limit);
3239  FALLTHROUGH;
3240 
3241  case VPM_X_AND_Y: // drag an X by Y area
3243  static const StringID measure_strings_area[] = {
3244  STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
3245  };
3246 
3247  TileIndex t0 = TileVirtXY(sx, sy);
3248  TileIndex t1 = TileVirtXY(x, y);
3249  uint dx = Delta(TileX(t0), TileX(t1)) + 1;
3250  uint dy = Delta(TileY(t0), TileY(t1)) + 1;
3251  byte index = 0;
3252  uint64 params[3];
3253 
3254  /* If dragging an area (eg dynamite tool) and it is actually a single
3255  * row/column, change the type to 'line' to get proper calculation for height */
3256  style = (HighLightStyle)_thd.next_drawstyle;
3257  if (_thd.IsDraggingDiagonal()) {
3258  /* Determine the "area" of the diagonal dragged selection.
3259  * We assume the area is the number of tiles along the X
3260  * edge and the number of tiles along the Y edge. However,
3261  * multiplying these two numbers does not give the exact
3262  * number of tiles; basically we are counting the black
3263  * squares on a chess board and ignore the white ones to
3264  * make the tile counts at the edges match up. There is no
3265  * other way to make a proper count though.
3266  *
3267  * First convert to the rotated coordinate system. */
3268  int dist_x = TileX(t0) - TileX(t1);
3269  int dist_y = TileY(t0) - TileY(t1);
3270  int a_max = dist_x + dist_y;
3271  int b_max = dist_y - dist_x;
3272 
3273  /* Now determine the size along the edge, but due to the
3274  * chess board principle this counts double. */
3275  a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
3276  b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
3277 
3278  /* We get a 1x1 on normal 2x1 rectangles, due to it being
3279  * a seen as two sides. As the result for actual building
3280  * will be the same as non-diagonal dragging revert to that
3281  * behaviour to give it a more normally looking size. */
3282  if (a_max != 1 || b_max != 1) {
3283  dx = a_max;
3284  dy = b_max;
3285  }
3286  } else if (style & HT_RECT) {
3287  if (dx == 1) {
3288  style = HT_LINE | HT_DIR_Y;
3289  } else if (dy == 1) {
3290  style = HT_LINE | HT_DIR_X;
3291  }
3292  }
3293 
3294  if (dx != 1 || dy != 1) {
3295  int heightdiff = CalcHeightdiff(style, 0, t0, t1);
3296 
3297  params[index++] = dx - (style & HT_POINT ? 1 : 0);
3298  params[index++] = dy - (style & HT_POINT ? 1 : 0);
3299  if (heightdiff != 0) params[index++] = heightdiff;
3300  }
3301 
3302  ShowMeasurementTooltips(measure_strings_area[index], index, params);
3303  }
3304  break;
3305 
3306  default: NOT_REACHED();
3307  }
3308 
3309  _thd.selend.x = x;
3310  _thd.selend.y = y;
3311 }
3312 
3318 {
3320 
3321  /* stop drag mode if the window has been closed */
3322  Window *w = _thd.GetCallbackWnd();
3323  if (w == nullptr) {
3325  return ES_HANDLED;
3326  }
3327 
3328  /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
3329  if (_left_button_down) {
3331  /* Only register a drag event when the mouse moved. */
3332  if (_thd.new_pos.x == _thd.selstart.x && _thd.new_pos.y == _thd.selstart.y) return ES_HANDLED;
3333  _thd.selstart.x = _thd.new_pos.x;
3334  _thd.selstart.y = _thd.new_pos.y;
3335  }
3336 
3337  w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
3338  return ES_HANDLED;
3339  }
3340 
3341  /* Mouse button released. */
3344 
3345  /* Keep the selected tool, but reset it to the original mode. */
3346  HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
3347  if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
3348  _thd.place_mode = HT_RECT | others;
3349  } else if (_thd.select_method & VPM_SIGNALDIRS) {
3350  _thd.place_mode = HT_RECT | others;
3351  } else if (_thd.select_method & VPM_RAILDIRS) {
3352  _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
3353  } else {
3354  _thd.place_mode = HT_POINT | others;
3355  }
3356  SetTileSelectSize(1, 1);
3357 
3358  HideMeasurementTooltips();
3359  w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
3360 
3361  return ES_HANDLED;
3362 }
3363 
3372 {
3373  SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
3374 }
3375 
3376 #include "table/animcursors.h"
3377 
3386 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
3387 {
3388  if (_thd.window_class != WC_INVALID) {
3389  /* Undo clicking on button and drag & drop */
3390  Window *w = _thd.GetCallbackWnd();
3391  /* Call the abort function, but set the window class to something
3392  * that will never be used to avoid infinite loops. Setting it to
3393  * the 'next' window class must not be done because recursion into
3394  * this function might in some cases reset the newly set object to
3395  * place or not properly reset the original selection. */
3396  _thd.window_class = WC_INVALID;
3397  if (w != nullptr) {
3398  w->OnPlaceObjectAbort();
3399  HideMeasurementTooltips();
3400  }
3401  }
3402 
3403  /* Mark the old selection dirty, in case the selection shape or colour changes */
3405 
3406  SetTileSelectSize(1, 1);
3407 
3408  _thd.make_square_red = false;
3409 
3410  if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
3411  mode = HT_NONE;
3413  } else {
3415  }
3416 
3417  _thd.place_mode = mode;
3418  _thd.window_class = window_class;
3419  _thd.window_number = window_num;
3420 
3421  if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
3422  VpStartPreSizing();
3423  }
3424 
3425  if ((icon & ANIMCURSOR_FLAG) != 0) {
3427  } else {
3428  SetMouseCursor(icon, pal);
3429  }
3430 
3431 }
3432 
3435 {
3437 }
3438 
3439 Point GetViewportStationMiddle(const Viewport *vp, const Station *st)
3440 {
3441  int x = TileX(st->xy) * TILE_SIZE;
3442  int y = TileY(st->xy) * TILE_SIZE;
3443  int z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
3444 
3445  Point p = RemapCoords(x, y, z);
3446  p.x = UnScaleByZoom(p.x - vp->virtual_left, vp->zoom) + vp->left;
3447  p.y = UnScaleByZoom(p.y - vp->virtual_top, vp->zoom) + vp->top;
3448  return p;
3449 }
3450 
3455 };
3456 
3459 #ifdef WITH_SSE
3460  { &ViewportSortParentSpritesSSE41Checker, &ViewportSortParentSpritesSSE41 },
3461 #endif
3463 };
3464 
3467 {
3468  for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) {
3469  if (_vp_sprite_sorters[i].fct_checker()) {
3470  _vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter;
3471  break;
3472  }
3473  }
3474  assert(_vp_sprite_sorter != nullptr);
3475 }
3476 
3486 {
3487  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3488  switch (target) {
3489  case VST_EVERYONE:
3490  break;
3491  case VST_COMPANY:
3492  if (_local_company != (CompanyID)ref) return CommandCost();
3493  break;
3494  case VST_CLIENT:
3495  if (_network_own_client_id != (ClientID)ref) return CommandCost();
3496  break;
3497  default:
3498  return CMD_ERROR;
3499  }
3500 
3501  if (flags & DC_EXEC) {
3503  ScrollMainWindowToTile(tile);
3504  }
3505  return CommandCost();
3506 }
3507 
3508 void MarkCatchmentTilesDirty()
3509 {
3510  if (_viewport_highlight_town != nullptr) {
3512  return;
3513  }
3514  if (_viewport_highlight_station != nullptr) {
3517  _viewport_highlight_station = nullptr;
3518  } else {
3520  for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3521  MarkTileDirtyByTile(tile);
3522  }
3523  }
3524  }
3525 }
3526 
3533 void SetViewportCatchmentStation(const Station *st, bool sel)
3534 {
3537  if (sel && _viewport_highlight_station != st) {
3538  MarkCatchmentTilesDirty();
3540  _viewport_highlight_town = nullptr;
3541  MarkCatchmentTilesDirty();
3542  } else if (!sel && _viewport_highlight_station == st) {
3543  MarkCatchmentTilesDirty();
3544  _viewport_highlight_station = nullptr;
3545  }
3547 }
3548 
3555 void SetViewportCatchmentTown(const Town *t, bool sel)
3556 {
3559  if (sel && _viewport_highlight_town != t) {
3560  _viewport_highlight_station = nullptr;
3563  } else if (!sel && _viewport_highlight_town == t) {
3564  _viewport_highlight_town = nullptr;
3566  }
3568 }
DO_SHOW_COMPETITOR_SIGNS
@ DO_SHOW_COMPETITOR_SIGNS
Display signs, station names and waypoint names of opponent companies. Buoys and oilrig-stations are ...
Definition: openttd.h:51
ES_HANDLED
@ ES_HANDLED
The passed event is handled.
Definition: window_type.h:720
OppositeCorner
static Corner OppositeCorner(Corner corner)
Returns the opposite corner.
Definition: slope_func.h:184
Window::WindowIterator
Iterator to iterate all valid Windows.
Definition: window_gui.h:758
HT_DIR_HL
@ HT_DIR_HL
horizontal lower
Definition: tilehighlight_type.h:36
TileInfo::z
int z
Height.
Definition: tile_cmd.h:47
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
CalcRaildirsDrawstyle
static void CalcRaildirsDrawstyle(int x, int y, int method)
while dragging
Definition: viewport.cpp:2930
ViewportData
Data structure for a window viewport.
Definition: window_gui.h:192
SPRITE_MASK
@ SPRITE_MASK
The mask to for the main sprite.
Definition: sprites.h:1548
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition: base_station_base.h:63
SetTileSelectSize
void SetTileSelectSize(int w, int h)
Highlight w by h tiles at the cursor.
Definition: viewport.cpp:2483
ParentSpriteToDraw::image
SpriteID image
sprite to draw
Definition: viewport_sprite_sorter.h:31
IsCompanyBuildableVehicleType
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:89
ViewportDrawer::foundation_offset
Point foundation_offset[FOUNDATION_PART_END]
Pixel offset for ground sprites on the foundations.
Definition: viewport.cpp:181
ParentSpriteToDraw::x
int32 x
screen X coordinate of sprite
Definition: viewport_sprite_sorter.h:23
TileHighlightData::sizelimit
byte sizelimit
Whether the selection is limited in length, and what the maximum length is.
Definition: tilehighlight_type.h:62
TILE_ADD
#define TILE_ADD(x, y)
Adds two tiles together.
Definition: map_func.h:244
IsInsideMM
static constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:230
DrawAutorailSelection
static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
Draws autorail highlights.
Definition: viewport.cpp:960
TileHighlightData::size
Point size
Size, in tile "units", of the white/red selection area.
Definition: tilehighlight_type.h:48
factory.hpp
FindWindowFromPt
Window * FindWindowFromPt(int x, int y)
Do a search for a window at specific coordinates.
Definition: window.cpp:1826
DrawBox
void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
Draws the projection of a parallelepiped.
Definition: gfx.cpp:420
TileHighlightData::outersize
Point outersize
Size, in tile "units", of the blue coverage area excluding the side of the selected area.
Definition: tilehighlight_type.h:50
WC_INVALID
@ WC_INVALID
Invalid window.
Definition: window_type.h:700
CheckUnderflow
static void CheckUnderflow(int &test, int &other, int mult)
Check for underflowing the map.
Definition: viewport.cpp:2906
Blitter::SetPixel
virtual void SetPixel(void *video, int x, int y, uint8 colour)=0
Draw a pixel with a given colour on the video-buffer.
Pool::PoolItem<&_vehicle_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
ScrollMainWindowToTile
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Definition: viewport.cpp:2456
vehicle_gui.h
PALETTE_SEL_TILE_RED
static const PaletteID PALETTE_SEL_TILE_RED
makes a square red. is used when removing rails or other stuff
Definition: sprites.h:1563
VST_CLIENT
@ VST_CLIENT
Single player.
Definition: viewport_type.h:145
VPM_FIX_VERTICAL
@ VPM_FIX_VERTICAL
drag only in vertical direction
Definition: viewport_type.h:95
MAX_TILE_EXTENT_LEFT
static const int MAX_TILE_EXTENT_LEFT
Maximum left extent of tile relative to north corner.
Definition: viewport.cpp:109
AddDirtyBlock
void AddDirtyBlock(int left, int top, int right, int bottom)
Extend the internal _invalid_rect rectangle to contain the rectangle defined by the given parameters.
Definition: gfx.cpp:1724
TileSpriteToDraw::y
int32 y
screen Y coordinate of sprite
Definition: viewport.cpp:128
Vehicle::y_pos
int32 y_pos
y coordinate.
Definition: vehicle_base.h:284
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3156
UnScaleByZoomLower
static int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_NORMAL)
Definition: zoom_func.h:67
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
Vehicle::x_pos
int32 x_pos
x coordinate.
Definition: vehicle_base.h:283
ScrollWindowTo
bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
Definition: viewport.cpp:2410
VpHandlePlaceSizingDrag
EventState VpHandlePlaceSizingDrag()
Handle the mouse while dragging for placement/resizing.
Definition: viewport.cpp:3317
ZOOM_OUT
@ ZOOM_OUT
Zoom out (get helicopter view).
Definition: viewport_type.h:74
command_func.h
_animcursors
static const AnimCursor *const _animcursors[]
This is an array of pointers to all the animated cursor definitions we have above.
Definition: animcursors.h:85
ParentSpriteToDraw::zmax
int32 zmax
maximal world Z coordinate of bounding box
Definition: viewport_sprite_sorter.h:28
_tile_type_procs
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
Definition: landscape.cpp:64
TileInfo::x
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:43
HT_DIR_VR
@ HT_DIR_VR
vertical right
Definition: tilehighlight_type.h:38
GetTilePixelSlopeOutsideMap
Slope GetTilePixelSlopeOutsideMap(int x, int y, int *h)
Return the slope of a given tile, also for tiles outside the map (virtual "black" tiles).
Definition: tile_map.cpp:82
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
Kdtree
K-dimensional tree, specialised for 2-dimensional space.
Definition: kdtree.hpp:37
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3594
TileHighlightData::offs
Point offs
Offset, in tile "units", for the blue coverage area from the selected area's northern tile.
Definition: tilehighlight_type.h:49
_special_mouse_mode
SpecialMouseMode _special_mouse_mode
Mode of the mouse.
Definition: window.cpp:92
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:42
_left_button_down
bool _left_button_down
Is left mouse button pressed?
Definition: gfx.cpp:41
PALETTE_TILE_RED_PULSATING
static const PaletteID PALETTE_TILE_RED_PULSATING
pulsating red tile drawn if you try to build a wrong tunnel or raise/lower land where it is not possi...
Definition: sprites.h:1562
company_base.h
ViewportDragDropSelectionProcess
ViewportDragDropSelectionProcess
Drag and drop selection process, or, what to do with an area of land when you've selected it.
Definition: viewport_type.h:107
IsTransparencySet
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:48
TileSpriteToDraw::sub
const SubSprite * sub
only draw a rectangular part of the sprite
Definition: viewport.cpp:126
ZOOM_LVL_END
@ ZOOM_LVL_END
End for iteration.
Definition: zoom_type.h:28
Blitter
How all blitters should look like.
Definition: base.hpp:28
signs_func.h
ZOOM_LVL_OUT_16X
@ ZOOM_LVL_OUT_16X
Zoomed 16 times out.
Definition: zoom_type.h:26
Station
Station data structure.
Definition: station_base.h:454
TilePixelHeight
static uint TilePixelHeight(TileIndex tile)
Returns the height of a tile in pixels.
Definition: tile_map.h:72
DrawTileHighlightType
static void DrawTileHighlightType(const TileInfo *ti, TileHighlightType tht)
Draw tile highlight for coverage area highlight.
Definition: viewport.cpp:1038
Viewport::width
int width
Screen width of the viewport.
Definition: viewport_type.h:25
animcursors.h
Vehicle::z_pos
int32 z_pos
z coordinate.
Definition: vehicle_base.h:285
TileHighlightData::select_method
ViewportPlaceMethod select_method
The method which governs how tiles are selected.
Definition: tilehighlight_type.h:74
RemapCoords
static Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition: landscape.h:82
Window::viewport
ViewportData * viewport
Pointer to viewport data, if present.
Definition: window_gui.h:255
Viewport::height
int height
Screen height of the viewport.
Definition: viewport_type.h:26
BitmapTileIterator
Iterator to iterate over all tiles belonging to a bitmaptilearea.
Definition: bitmap_type.h:107
SetRedErrorSquare
void SetRedErrorSquare(TileIndex tile)
Set a tile to display a red error square.
Definition: viewport.cpp:2465
ViewportData::scrollpos_y
int32 scrollpos_y
Currently shown y coordinate (virtual screen coordinate of topleft corner of the viewport).
Definition: window_gui.h:195
TileHighlightData::new_size
Point new_size
New value for size; used to determine whether to redraw the selection.
Definition: tilehighlight_type.h:56
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
TileHighlightData::IsDraggingDiagonal
bool IsDraggingDiagonal()
Is the user dragging a 'diagonal rectangle'?
Definition: viewport.cpp:2520
HandleClickOnSign
void HandleClickOnSign(const Sign *si)
Handle clicking on a sign.
Definition: signs_gui.cpp:567
Viewport::top
int top
Screen coordinate top edge of the viewport.
Definition: viewport_type.h:24
ParentSpriteToDraw::ymin
int32 ymin
minimal world Y coordinate of bounding box
Definition: viewport_sprite_sorter.h:21
FindWindowById
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition: window.cpp:1161
ZOOM_LVL_COUNT
@ ZOOM_LVL_COUNT
Number of zoom levels.
Definition: zoom_type.h:30
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
IsHalftileSlope
static bool IsHalftileSlope(Slope s)
Checks for non-continuous slope on halftile foundations.
Definition: slope_func.h:47
ViewportDrawer
Data structure storing rendering information.
Definition: viewport.cpp:165
INVALID_TILE
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:108
PALETTE_TO_TRANSPARENT
static const PaletteID PALETTE_TO_TRANSPARENT
This sets the sprite to transparent.
Definition: sprites.h:1595
FOUNDATION_PART_HALFTILE
@ FOUNDATION_PART_HALFTILE
Second part (halftile foundation)
Definition: viewport.cpp:145
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
Sprite::height
uint16 height
Height of the sprite.
Definition: spritecache.h:18
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:16
_ctrl_pressed
bool _ctrl_pressed
Is Ctrl pressed?
Definition: gfx.cpp:38
AddTileSpriteToDraw
static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub=nullptr, int extra_offs_x=0, int extra_offs_y=0)
Schedules a tile sprite for drawing.
Definition: viewport.cpp:506
RemoveHalftileSlope
static Slope RemoveHalftileSlope(Slope s)
Removes a halftile slope from a slope.
Definition: slope_func.h:60
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:253
vehicle_base.h
DoZoomInOutWindow
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition: main_gui.cpp:92
ViewportSign::center
int32 center
The center position of the sign.
Definition: viewport_type.h:39
zoom_func.h
Sprite::x_offs
int16 x_offs
Number of pixels to shift the sprite to the right.
Definition: spritecache.h:20
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
LinkGraphOverlay::GetCargoMask
CargoTypes GetCargoMask()
Get a bitmask of the currently shown cargoes.
Definition: linkgraph_gui.h:73
ZoomLevel
ZoomLevel
All zoom levels we know.
Definition: zoom_type.h:19
VST_COMPANY
@ VST_COMPANY
All players in specific company.
Definition: viewport_type.h:144
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
VPM_FIX_Y
@ VPM_FIX_Y
drag only in Y axis
Definition: viewport_type.h:91
TileInfo::y
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:44
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
DrawString
int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition: gfx.cpp:644
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
town.h
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:215
ST_NORMAL
@ ST_NORMAL
The most basic (normal) sprite.
Definition: gfx_type.h:308
WindowNumber
int32 WindowNumber
Number to differentiate different windows of the same class.
Definition: window_type.h:713
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:338
_display_opt
byte _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
ViewportSign::top
int32 top
The top of the sign.
Definition: viewport_type.h:40
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
ViewportPlaceMethod
ViewportPlaceMethod
Viewport place method (type of highlighted area and placed objects)
Definition: viewport_type.h:88
Viewport::virtual_top
int virtual_top
Virtual top coordinate.
Definition: viewport_type.h:29
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:288
ViewportSign
Location information about a sign as seen on the viewport.
Definition: viewport_type.h:38
HT_DIR_Y
@ HT_DIR_Y
Y direction.
Definition: tilehighlight_type.h:34
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
TileSpriteToDraw::x
int32 x
screen X coordinate of sprite
Definition: viewport.cpp:127
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
SubSprite
Used to only draw a part of the sprite.
Definition: gfx_type.h:225
Kdtree::Build
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
Definition: kdtree.hpp:364
FR_TRANSPARENT
@ FR_TRANSPARENT
Makes the background transparent if set.
Definition: window_gui.h:32
GUISettings::zoom_max
ZoomLevel zoom_max
maximum zoom out level
Definition: settings_type.h:135
TileTypeProcs::draw_tile_proc
DrawTileProc * draw_tile_proc
Called to render the tile and its contents to the screen.
Definition: tile_cmd.h:146
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:62
_colour_gradient
byte _colour_gradient[COLOUR_END][8]
All 16 colour gradients 8 colours per gradient from darkest (0) to lightest (7)
Definition: gfx.cpp:55
MarkViewportDirty
static bool MarkViewportDirty(const Viewport *vp, int left, int top, int right, int bottom)
Marks a viewport as dirty for repaint if it displays (a part of) the area the needs to be repainted.
Definition: viewport.cpp:1924
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
Town::show_zone
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:96
autorail.h
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
GetTownIndex
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:22
ParentSpriteToDraw::xmin
int32 xmin
minimal world X coordinate of bounding box
Definition: viewport_sprite_sorter.h:20
ShowMeasurementTooltips
static void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond=TCC_EXIT_VIEWPORT)
Displays the measurement tooltips when selecting multiple tiles.
Definition: viewport.cpp:2653
Kdtree::Count
size_t Count() const
Get number of elements stored in tree.
Definition: kdtree.hpp:432
CheckClickOnViewportSign
static bool CheckClickOnViewportSign(const Viewport *vp, int x, int y, const ViewportSign *sign)
Test whether a sign is below the mouse.
Definition: viewport.cpp:2140
GetStringBoundingBox
Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition: gfx.cpp:890
ZOOM_LVL_BEGIN
@ ZOOM_LVL_BEGIN
Begin for iteration.
Definition: zoom_type.h:21
SwapDirection
static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
Check if the direction of start and end tile should be swapped based on the dragging-style.
Definition: viewport.cpp:2792
SlopeToSpriteOffset
static uint SlopeToSpriteOffset(Slope s)
Returns the Sprite offset for a given Slope.
Definition: slope_func.h:415
SPRITE_COMBINE_ACTIVE
@ SPRITE_COMBINE_ACTIVE
Sprite combining is active. AddSortableSpriteToDraw outputs child sprites.
Definition: viewport.cpp:156
CalcHeightdiff
static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
Calculates height difference between one tile and another.
Definition: viewport.cpp:2826
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:205
FOUNDATION_PART_NORMAL
@ FOUNDATION_PART_NORMAL
First part (normal foundation or no foundation)
Definition: viewport.cpp:144
Window::OnPlaceMouseUp
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
The user has dragged over the map when the tile highlight mode has been set.
Definition: window_gui.h:726
CheckClickOnVehicle
Vehicle * CheckClickOnVehicle(const Viewport *vp, int x, int y)
Find the vehicle close to the clicked coordinates.
Definition: vehicle.cpp:1216
TileHighlightData
Metadata about the current highlighting.
Definition: tilehighlight_type.h:46
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:269
VPM_RAILDIRS
@ VPM_RAILDIRS
all rail directions
Definition: viewport_type.h:98
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:45
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
MapSizeX
static uint MapSizeX()
Get the size of the map along the X.
Definition: map_func.h:72
GUISettings::measure_tooltip
bool measure_tooltip
show a permanent tooltip when dragging tools
Definition: settings_type.h:124
ViewportDrawer::last_foundation_child
int * last_foundation_child[FOUNDATION_PART_END]
Tail of ChildSprite list of the foundations. (index into child_screen_sprites_to_draw)
Definition: viewport.cpp:180
ViewportSSCSS::fct_checker
VpSorterChecker fct_checker
The check function.
Definition: viewport.cpp:3453
window_gui.h
ViewportDrawer::foundation
int foundation[FOUNDATION_PART_END]
Foundation sprites (index into parent_sprites_to_draw).
Definition: viewport.cpp:178
ToTileIndexDiff
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:230
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
_company_colours
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
Definition: company_cmd.cpp:48
ZOOM_IN
@ ZOOM_IN
Zoom in (get more detailed view).
Definition: viewport_type.h:73
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:157
Viewport
Data structure for viewport, display of a part of the world.
Definition: viewport_type.h:22
TILE_UNIT_MASK
static const uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition: tile_type.h:16
BaseStation::sign
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
Definition: base_station_base.h:54
DRAW_STRING_BUFFER
static const int DRAW_STRING_BUFFER
Size of the buffer used for drawing strings.
Definition: gfx_func.h:86
IsSteepSlope
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
IsInsideRotatedRectangle
bool IsInsideRotatedRectangle(int x, int y)
Checks whether a point is inside the selected a diagonal rectangle given by _thd.size and _thd....
Definition: viewport.cpp:800
CommandCost
Common return value for all commands.
Definition: command_type.h:24
InverseRemapCoords
static Point InverseRemapCoords(int x, int y)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
Definition: landscape.h:112
WSM_PRESIZE
@ WSM_PRESIZE
Presizing mode (docks, tunnels).
Definition: window_gui.h:925
Align
static T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition: math_func.hpp:35
GuiShowTooltips
void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition: misc_gui.cpp:773
ViewportDrawer::foundation_part
FoundationPart foundation_part
Currently active foundation for ground sprite drawing.
Definition: viewport.cpp:179
ParentSpriteToDraw::pal
PaletteID pal
palette to use
Definition: viewport_sprite_sorter.h:32
tilehighlight_func.h
TileHeight
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:29
CursorID
uint32 CursorID
The number of the cursor (sprite)
Definition: gfx_type.h:19
UpdateTileSelection
void UpdateTileSelection()
Updates tile highlighting for all cases.
Definition: viewport.cpp:2543
FS_NORMAL
@ FS_NORMAL
Index of the normal font in the font tables.
Definition: gfx_type.h:203
StartStopVehicle
void StartStopVehicle(const Vehicle *v, bool texteffect)
Executes CMD_START_STOP_VEHICLE for given vehicle.
Definition: vehicle_gui.cpp:2806
HT_DIR_VL
@ HT_DIR_VL
vertical left
Definition: tilehighlight_type.h:37
SetMouseCursor
void SetMouseCursor(CursorID sprite, PaletteID pal)
Assign a single non-animated sprite to the cursor.
Definition: gfx.cpp:1923
MAX_SPRITES
@ MAX_SPRITES
Maximum number of sprites that can be loaded at a given time.
Definition: sprites.h:1547
SetSelectionTilesDirty
static void SetSelectionTilesDirty()
Marks the selected tiles as dirty.
Definition: viewport.cpp:2015
ViewportDrawer::parent_sprites_to_sort
ParentSpriteToSortVector parent_sprites_to_sort
Parent sprite pointer array used for sorting.
Definition: viewport.cpp:171
VPM_FIX_X
@ VPM_FIX_X
drag only in X axis
Definition: viewport_type.h:90
DrawTileSelectionRect
static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
Draws a selection rectangle on a tile.
Definition: viewport.cpp:900
Viewport::virtual_left
int virtual_left
Virtual left coordinate.
Definition: viewport_type.h:28
SetObjectToPlace
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition: viewport.cpp:3386
TileHighlightData::window_number
WindowNumber window_number
The WindowNumber of the window that is responsible for the selection mode.
Definition: tilehighlight_type.h:69
Window::height
int height
Height of the window (number of pixels down in y direction)
Definition: window_gui.h:249
ANIMCURSOR_FLAG
static const CursorID ANIMCURSOR_FLAG
Flag for saying a cursor sprite is an animated cursor.
Definition: sprites.h:1495
VehicleClicked
bool VehicleClicked(const Vehicle *v)
Dispatch a "vehicle selected" event if any window waits for it.
Definition: vehicle_gui.cpp:3305
INVALID_VEHICLE
static const VehicleID INVALID_VEHICLE
Constant representing a non-existing vehicle.
Definition: vehicle_type.h:55
Window::SetDirty
void SetDirty() const
Mark entire window as dirty (in need of re-paint)
Definition: window.cpp:1008
Viewport::left
int left
Screen coordinate left edge of the viewport.
Definition: viewport_type.h:23
AddCombinedSprite
static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
Adds a child sprite to a parent sprite.
Definition: viewport.cpp:627
FS_SMALL
@ FS_SMALL
Index of the small font in the font tables.
Definition: gfx_type.h:204
ScrollWindowToTile
bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
Scrolls the viewport in a window to a given location.
Definition: viewport.cpp:2445
HT_DIAGONAL
@ HT_DIAGONAL
Also allow 'diagonal rectangles'. Only usable in combination with HT_RECT or HT_POINT.
Definition: tilehighlight_type.h:28
GUISettings::population_in_label
bool population_in_label
show the population of a town in its label?
Definition: settings_type.h:144
IsInsideBS
static bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
Definition: math_func.hpp:214
SpecializedStation< Station, false >::IsExpected
static bool IsExpected(const BaseStation *st)
Helper for checking whether the given station is of this type.
Definition: base_station_base.h:199
VpSorterChecker
bool(* VpSorterChecker)()
Type for method for checking whether a viewport sprite sorter exists.
Definition: viewport_sprite_sorter.h:45
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:47
ParentSpriteToDraw::sub
const SubSprite * sub
only draw a rectangular part of the sprite
Definition: viewport_sprite_sorter.h:33
MAX_BUILDING_PIXELS
static const uint MAX_BUILDING_PIXELS
Maximum height of a building in pixels in #ZOOM_LVL_BASE. (Also applies to "bridge buildings" on the ...
Definition: tile_type.h:20
ES_NOT_HANDLED
@ ES_NOT_HANDLED
The passed event is not handled.
Definition: window_type.h:721
Town::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:83
Corner
Corner
Enumeration of tile corners.
Definition: slope_type.h:22
HT_RAIL
@ HT_RAIL
autorail (one piece), lower bits: direction
Definition: tilehighlight_type.h:26
IsInvisibilitySet
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:59
ConstructionSettings::max_bridge_height
byte max_bridge_height
maximum height of bridges
Definition: settings_type.h:346
GetNorthernBridgeEnd
TileIndex GetNorthernBridgeEnd(TileIndex t)
Finds the northern end of a bridge starting at a middle tile.
Definition: bridge_map.cpp:39
ChildScreenSpriteToDraw::next
int next
next child to draw (-1 at the end)
Definition: viewport.cpp:138
EndSpriteCombine
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition: viewport.cpp:773
TilePixelHeightOutsideMap
static uint TilePixelHeightOutsideMap(int x, int y)
Returns the height of a tile in pixels, also for tiles outside the map (virtual "black" tiles).
Definition: tile_map.h:84
CheckOverflow
static void CheckOverflow(int &test, int &other, int max, int mult)
Check for overflowing the map.
Definition: viewport.cpp:2921
Window::OnPlaceObject
virtual void OnPlaceObject(Point pt, TileIndex tile)
The user clicked some place on the map when a tile highlight mode has been set.
Definition: window_gui.h:684
TileHeightOutsideMap
static uint TileHeightOutsideMap(int x, int y)
Returns the height of a tile, also for tiles outside the map (virtual "black" tiles).
Definition: tile_map.h:42
_string_colourmap
static const byte _string_colourmap[17]
Colour mapping for TextColour.
Definition: string_colours.h:11
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
linkgraph_gui.h
TC_IS_PALETTE_COLOUR
@ TC_IS_PALETTE_COLOUR
Colour value is already a real palette colour index, not an index of a StringColour.
Definition: gfx_type.h:276
ViewportSign::MarkDirty
void MarkDirty(ZoomLevel maxzoom=ZOOM_LVL_MAX) const
Mark the sign dirty in all viewports.
Definition: viewport.cpp:1478
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:141
ViewportSign::width_small
uint16 width_small
The width when zoomed out (small font)
Definition: viewport_type.h:42
HighlightTownLocalAuthorityTiles
static void HighlightTownLocalAuthorityTiles(const TileInfo *ti)
Highlights tiles insede local authority of selected towns.
Definition: viewport.cpp:1053
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:596
Window::SetWidgetDisabledState
void SetWidgetDisabledState(byte widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition: window_gui.h:321
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
ViewportDrawBoundingBoxes
static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
Draws the bounding boxes of all ParentSprites.
Definition: viewport.cpp:1656
DO_SHOW_STATION_NAMES
@ DO_SHOW_STATION_NAMES
Display station names.
Definition: openttd.h:46
safeguards.h
ViewportSign::width_normal
uint16 width_normal
The width when not zoomed out (normal font)
Definition: viewport_type.h:41
ParentSpriteToDraw::left
int32 left
minimal screen X coordinate of sprite (= x + sprite->x_offs), reference point for child sprites
Definition: viewport_sprite_sorter.h:35
Window::left
int left
x position of left edge of the window
Definition: window_gui.h:246
Sprite::width
uint16 width
Width of the sprite.
Definition: spritecache.h:19
TileHighlightData::make_square_red
bool make_square_red
Whether to give a tile a red selection.
Definition: tilehighlight_type.h:71
IsValidTile
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:161
ParentSpriteToDraw::zmin
int32 zmin
minimal world Z coordinate of bounding box
Definition: viewport_sprite_sorter.h:22
WindowClass
WindowClass
Window classes.
Definition: window_type.h:37
DivAwayFromZero
static int DivAwayFromZero(int a, uint b)
Computes (a / b) rounded away from zero.
Definition: math_func.hpp:319
RedrawScreenRect
void RedrawScreenRect(int left, int top, int right, int bottom)
Repaints a specific rectangle of the screen.
Definition: gfx.cpp:1609
SlopeWithThreeCornersRaised
static Slope SlopeWithThreeCornersRaised(Corner corner)
Returns the slope with all except one corner raised.
Definition: slope_func.h:206
HT_NONE
@ HT_NONE
default
Definition: tilehighlight_type.h:20
StartSpriteCombine
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition: viewport.cpp:763
GetHalftileSlopeCorner
static Corner GetHalftileSlopeCorner(Slope s)
Returns the leveled halftile of a halftile slope.
Definition: slope_func.h:148
TileHighlightData::pos
Point pos
Location, in tile "units", of the northern tile of the selected area.
Definition: tilehighlight_type.h:47
ParentSpriteToDraw::first_child
int32 first_child
the first child to draw.
Definition: viewport_sprite_sorter.h:38
VpSpriteSorter
void(* VpSpriteSorter)(ParentSpriteToSortVector *psd)
Type for the actual viewport sprite sorter.
Definition: viewport_sprite_sorter.h:47
SPRITE_COMBINE_NONE
@ SPRITE_COMBINE_NONE
Every AddSortableSpriteToDraw start its own bounding box.
Definition: viewport.cpp:154
ViewportDrawer::combine_sprites
SpriteCombineMode combine_sprites
Current mode of "sprite combining".
Definition: viewport.cpp:176
TileHighlightData::new_outersize
Point new_outersize
New value for outersize; used to determine whether to redraw the selection.
Definition: tilehighlight_type.h:57
waypoint_func.h
Viewport::virtual_width
int virtual_width
width << zoom
Definition: viewport_type.h:30
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
ScrollMainWindowTo
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
Scrolls the main window to given coordinates.
Definition: smallmap_gui.cpp:1883
ViewportData::dest_scrollpos_y
int32 dest_scrollpos_y
Current destination y coordinate to display (virtual screen coordinate of topleft corner of the viewp...
Definition: window_gui.h:197
MapSizeY
static uint MapSizeY()
Get the size of the map along the Y.
Definition: map_func.h:82
WSM_DRAGDROP
@ WSM_DRAGDROP
Drag&drop an object.
Definition: window_gui.h:923
OffsetGroundSprite
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition: viewport.cpp:595
WSM_SIZING
@ WSM_SIZING
Sizing mode.
Definition: window_gui.h:924
SpecializedStation< Waypoint, true >::From
static Waypoint * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
Definition: base_station_base.h:247
HT_DIR_MASK
@ HT_DIR_MASK
masks the drag-direction
Definition: tilehighlight_type.h:40
UnScaleByZoom
static int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
Definition: zoom_func.h:34
ZOOM_LVL_DETAIL
@ ZOOM_LVL_DETAIL
All zoomlevels below or equal to this, will result in details on the screen, like road-work,...
Definition: zoom_type.h:43
SetAnimatedMouseCursor
void SetAnimatedMouseCursor(const AnimCursor *table)
Assign an animation to the cursor.
Definition: gfx.cpp:1936
ShowStationViewWindow
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
Definition: station_gui.cpp:2117
_viewport_highlight_town
const Town * _viewport_highlight_town
Currently selected town for coverage area highlight.
Definition: viewport.cpp:998
stdafx.h
Window::window_number
WindowNumber window_number
Window number within the window class.
Definition: window_gui.h:241
landscape.h
PALETTE_MODIFIER_TRANSPARENT
@ PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition: sprites.h:1537
VpStartPlaceSizing
void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
highlighting tiles while only going over them with the mouse
Definition: viewport.cpp:2665
viewport_func.h
SA_HOR_CENTER
@ SA_HOR_CENTER
Horizontally center the text.
Definition: gfx_type.h:335
bridge_map.h
IsTileType
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
Window::AllWindows
Iterable ensemble of all valid Windows.
Definition: window_gui.h:803
InverseRemapCoords2
Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
Definition: landscape.cpp:107
ViewportAddLandscape
static void ViewportAddLandscape()
Add the landscape to the viewport, i.e.
Definition: viewport.cpp:1177
HT_VEHICLE
@ HT_VEHICLE
vehicle is accepted as target as well (bitmask)
Definition: tilehighlight_type.h:27
string_colours.h
FONT_HEIGHT_SMALL
#define FONT_HEIGHT_SMALL
Height of characters in the small (FS_SMALL) font.
Definition: gfx_func.h:203
AddSortableSpriteToDraw
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)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:667
ViewportSignKdtreeItem
Definition: viewport_kdtree.h:19
HT_DRAG
@ HT_DRAG
dragging items in the depot windows
Definition: tilehighlight_type.h:24
GetAutorailHT
static HighLightStyle GetAutorailHT(int x, int y)
returns the best autorail highlight type from map coordinates
Definition: viewport.cpp:2500
_network_own_client_id
ClientID _network_own_client_id
Our client identifier.
Definition: network.cpp:64
MarkAllViewportsDirty
bool MarkAllViewportsDirty(int left, int top, int right, int bottom)
Mark all viewports that display an area as dirty (in need of repaint).
Definition: viewport.cpp:1963
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:57
ParentSpriteToDraw::ymax
int32 ymax
maximal world Y coordinate of bounding box
Definition: viewport_sprite_sorter.h:27
ChildScreenSpriteToDraw
Definition: viewport.cpp:131
GUISettings::zoom_min
ZoomLevel zoom_min
minimum zoom out level
Definition: settings_type.h:134
TileHighlightData::dirty
byte dirty
Whether the build station window needs to redraw due to the changed selection.
Definition: tilehighlight_type.h:58
EconomySettings::dist_local_authority
byte dist_local_authority
distance for town local authority, default 20
Definition: settings_type.h:516
TileHighlightData::drawstyle
HighLightStyle drawstyle
Lower bits 0-3 are reserved for detailed highlight information.
Definition: tilehighlight_type.h:64
TileHighlightData::place_mode
HighLightStyle place_mode
Method which is used to place the selection.
Definition: tilehighlight_type.h:67
MAX_TILE_EXTENT_BOTTOM
static const int MAX_TILE_EXTENT_BOTTOM
Maximum bottom extent of tile relative to north corner (worst case: SLOPE_STEEP_N).
Definition: viewport.cpp:112
PerformanceAccumulator
RAII class for measuring multi-step elements of performance.
Definition: framerate_type.h:114
ViewportAddString
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)
Add a string to draw in the viewport.
Definition: viewport.cpp:1301
CmdScrollViewport
CommandCost CmdScrollViewport(DoCommandFlag flags, TileIndex tile, ViewportScrollTarget target, uint32 ref)
Scroll players main viewport.
Definition: viewport.cpp:3485
VpStartDragging
void VpStartDragging(ViewportDragDropSelectionProcess process)
Drag over the map while holding the left mouse down.
Definition: viewport.cpp:2699
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
ViewportData::scrollpos_x
int32 scrollpos_x
Currently shown x coordinate (virtual screen coordinate of topleft corner of the viewport).
Definition: window_gui.h:194
ClampViewportToMap
static void ClampViewportToMap(const Viewport *vp, int *scroll_x, int *scroll_y)
Ensure that a given viewport has a valid scroll position.
Definition: viewport.cpp:1850
TileHighlightData::selstart
Point selstart
The location where the dragging started.
Definition: tilehighlight_type.h:60
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
vehicle_func.h
IsInRangeInclusive
static bool IsInRangeInclusive(int begin, int end, int check)
Check if the parameter "check" is inside the interval between begin and end, including both begin and...
Definition: viewport.cpp:788
station_base.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
Pool::PoolItem<&_town_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:386
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1598
ResetObjectToPlace
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
Definition: viewport.cpp:3434
strings_func.h
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:623
ParentSpriteToDraw::top
int32 top
minimal screen Y coordinate of sprite (= y + sprite->y_offs), reference point for child sprites
Definition: viewport_sprite_sorter.h:36
ScaleByZoom
static int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
Definition: zoom_func.h:22
SlopeWithOneCornerRaised
static Slope SlopeWithOneCornerRaised(Corner corner)
Returns the slope with a specific corner raised.
Definition: slope_func.h:99
MapMaxY
static uint MapMaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:111
Window::OnPlaceObjectAbort
virtual void OnPlaceObjectAbort()
The user cancelled a tile highlight mode that has been set.
Definition: window_gui.h:705
MP_VOID
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:55
AddChildSpriteToFoundation
static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
Adds a child sprite to the active foundation.
Definition: viewport.cpp:531
GetTilePixelZ
static int GetTilePixelZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.h:294
Blitter::MoveTo
virtual void * MoveTo(void *video, int x, int y)=0
Move the destination pointer the requested amount x and y, keeping in mind any pitch and bpp of the r...
Pool::PoolItem<&_station_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:367
TileXY
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:163
VPM_Y_LIMITED
@ VPM_Y_LIMITED
Drag only in Y axis with limited size.
Definition: viewport_type.h:97
TileHighlightData::diagonal
bool diagonal
Whether the dragged area is a 45 degrees rotated rectangle.
Definition: tilehighlight_type.h:51
SLOPE_N
@ SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:53
DrawTileSelection
static void DrawTileSelection(const TileInfo *ti)
Checks if the specified tile is selected and if so draws selection using correct selectionstyle.
Definition: viewport.cpp:1087
TileType
TileType
The different types of tiles.
Definition: tile_type.h:47
HT_DIR_END
@ HT_DIR_END
end marker
Definition: tilehighlight_type.h:39
FONT_HEIGHT_NORMAL
#define FONT_HEIGHT_NORMAL
Height of characters in the normal (FS_NORMAL) font.
Definition: gfx_func.h:206
ViewportScrollTarget
ViewportScrollTarget
Target of the viewport scrolling GS method.
Definition: viewport_type.h:142
HT_LINE
@ HT_LINE
used for autorail highlighting (longer stretches), lower bits: direction
Definition: tilehighlight_type.h:25
ViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport.cpp:1451
WidgetDimensions::fullbevel
RectPadding fullbevel
Always-scaled bevel border.
Definition: window_gui.h:46
PALETTE_SEL_TILE_BLUE
static const PaletteID PALETTE_SEL_TILE_BLUE
This draws a blueish square (catchment areas for example)
Definition: sprites.h:1564
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
LinkGraphOverlay::Draw
void Draw(const DrawPixelInfo *dpi)
Draw the linkgraph overlay or some part of it, in the area given.
Definition: linkgraph_gui.cpp:259
SetObjectToPlaceWnd
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition: viewport.cpp:3371
framerate_type.h
ParentSpriteToDraw::y
int32 y
screen Y coordinate of sprite
Definition: viewport_sprite_sorter.h:29
_vp_sprite_sorters
static ViewportSSCSS _vp_sprite_sorters[]
List of sorters ordered from best to worst.
Definition: viewport.cpp:3458
WC_TOOLTIPS
@ WC_TOOLTIPS
Tooltip window; Window numbers:
Definition: window_type.h:109
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:1998
GetViewportY
static int GetViewportY(Point tile)
Returns the y coordinate in the viewport coordinate system where the given tile is painted.
Definition: viewport.cpp:1168
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
ViewportSortParentSprites
static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
Sort parent sprites pointer array replicating the way original sorter did it.
Definition: viewport.cpp:1514
Kdtree::FindNearest
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Definition: kdtree.hpp:443
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:53
GetStationIndex
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:28
waypoint_base.h
EventState
EventState
State of handling an event.
Definition: window_type.h:719
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:50
HT_RECT
@ HT_RECT
rectangle (stations, depots, ...)
Definition: tilehighlight_type.h:21
VPM_FIX_HORIZONTAL
@ VPM_FIX_HORIZONTAL
drag only in horizontal direction
Definition: viewport_type.h:94
UpdateViewportPosition
void UpdateViewportPosition(Window *w)
Update the viewport position being displayed.
Definition: viewport.cpp:1874
VPM_X_AND_Y
@ VPM_X_AND_Y
area of land in X and Y directions
Definition: viewport_type.h:92
DO_SHOW_SIGNS
@ DO_SHOW_SIGNS
Display signs.
Definition: openttd.h:47
Sign
Definition: signs_base.h:22
Kdtree::FindContained
void FindContained(CoordT x1, CoordT y1, CoordT x2, CoordT y2, const Outputter &outputter) const
Find all items contained within the given rectangle.
Definition: kdtree.hpp:461
WSM_DRAGGING
@ WSM_DRAGGING
Dragging mode (trees).
Definition: window_gui.h:926
Window::window_class
WindowClass window_class
Window class.
Definition: window_gui.h:240
Sprite::y_offs
int16 y_offs
Number of pixels to shift the sprite downwards.
Definition: spritecache.h:21
Station::catchment_tiles
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
Definition: station_base.h:474
Check2x1AutoRail
static HighLightStyle Check2x1AutoRail(int mode)
returns information about the 2x1 piece to be build.
Definition: viewport.cpp:2748
OWNER_DEITY
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
WC_MAIN_WINDOW
@ WC_MAIN_WINDOW
Main window; Window numbers:
Definition: window_type.h:44
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:53
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:305
GetTileMaxPixelZ
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
HT_DRAG_MASK
@ HT_DRAG_MASK
Mask for the tile drag-type modes.
Definition: tilehighlight_type.h:29
ScaleByMapSize1D
static uint ScaleByMapSize1D(uint n)
Scales the given value by the maps circumference, where the given value is for a 256 by 256 map.
Definition: map_func.h:136
BaseStation
Base class for all station-ish types.
Definition: base_station_base.h:52
DO_SHOW_TOWN_NAMES
@ DO_SHOW_TOWN_NAMES
Display town names.
Definition: openttd.h:45
company_func.h
TileHighlightData::select_proc
ViewportDragDropSelectionProcess select_proc
The procedure that has to be called when the selection is done.
Definition: tilehighlight_type.h:75
SetViewportCatchmentStation
void SetViewportCatchmentStation(const Station *st, bool sel)
Select or deselect station for coverage area highlight.
Definition: viewport.cpp:3533
MapMaxX
static uint MapMaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:102
DrawGroundSpriteAt
void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite at a specific world-coordinate relative to the current tile.
Definition: viewport.cpp:560
TO_SIGNS
@ TO_SIGNS
signs
Definition: transparency.h:23
Window::top
int top
y position of top edge of the window
Definition: window_gui.h:247
FoundationPart
FoundationPart
Enumeration of multi-part foundations.
Definition: viewport.cpp:142
GetTileHighlightType
static TileHighlightType GetTileHighlightType(TileIndex t)
Get tile highlight type of coverage area for a given tile.
Definition: viewport.cpp:1005
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
Window::DrawViewport
void DrawViewport() const
Draw the viewport of this window.
Definition: viewport.cpp:1825
IsPtInWindowViewport
Viewport * IsPtInWindowViewport(const Window *w, int x, int y)
Is a xy position inside the viewport of the window?
Definition: viewport.cpp:402
VehicleID
uint32 VehicleID
The type all our vehicle IDs have.
Definition: vehicle_type.h:16
ViewportDrawDirtyBlocks
static void ViewportDrawDirtyBlocks()
Draw/colour the blocks that have been redrawn.
Definition: viewport.cpp:1674
DrawFrameRect
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition: widget.cpp:414
HighLightStyle
HighLightStyle
Highlighting draw styles.
Definition: tilehighlight_type.h:19
ParentSpriteToDraw
Parent sprite that should be drawn.
Definition: viewport_sprite_sorter.h:18
ChildScreenSpriteToDraw::sub
const SubSprite * sub
only draw a rectangular part of the sprite
Definition: viewport.cpp:134
ViewportData::follow_vehicle
VehicleID follow_vehicle
VehicleID to follow if following a vehicle, INVALID_VEHICLE otherwise.
Definition: window_gui.h:193
DrawSelectionSprite
static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part, int extra_offs_x=0, int extra_offs_y=0)
Draws sprites between ground sprite and everything above.
Definition: viewport.cpp:882
ShowVehicleViewWindow
void ShowVehicleViewWindow(const Vehicle *v)
Shows the vehicle view window of the given vehicle.
Definition: vehicle_gui.cpp:3295
LinkGraphOverlay::SetDirty
void SetDirty()
Mark the linkgraph dirty to be rebuilt next time Draw() is called.
Definition: linkgraph_gui.h:70
window_func.h
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
VpSetPresizeRange
void VpSetPresizeRange(TileIndex from, TileIndex to)
Highlights all tiles between a set of two tiles.
Definition: viewport.cpp:2720
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
Town
Town data structure.
Definition: town.h:50
Window::width
int width
width of the window (number of pixels to the right in x direction)
Definition: window_gui.h:248
VPM_X_LIMITED
@ VPM_X_LIMITED
Drag only in X axis with limited size.
Definition: viewport_type.h:96
Viewport::zoom
ZoomLevel zoom
The zoom level of the viewport.
Definition: viewport_type.h:33
AddChildSpriteScreen
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:823
ViewportData::dest_scrollpos_x
int32 dest_scrollpos_x
Current destination x coordinate to display (virtual screen coordinate of topleft corner of the viewp...
Definition: window_gui.h:196
GetBridgePixelHeight
static int GetBridgePixelHeight(TileIndex tile)
Get the height ('z') of a bridge in pixels.
Definition: bridge_map.h:84
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1767
VST_EVERYONE
@ VST_EVERYONE
All players.
Definition: viewport_type.h:143
TileHighlightData::window_class
WindowClass window_class
The WindowClass of the window that is responsible for the selection mode.
Definition: tilehighlight_type.h:68
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1191
LinkGraphOverlay::GetCompanyMask
uint32 GetCompanyMask()
Get a bitmask of the currently shown companies.
Definition: linkgraph_gui.h:76
TILE_HEIGHT_STEP
static const int TILE_HEIGHT_STEP
One Z unit tile height difference is displayed as 50m.
Definition: viewport_func.h:19
Window::OnPlaceDrag
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
The user is dragging over the map when the tile highlight mode has been set.
Definition: window_gui.h:715
ViewportSortParentSpritesChecker
static bool ViewportSortParentSpritesChecker()
This fallback sprite checker always exists.
Definition: viewport.cpp:1508
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:326
ViewportSSCSS::fct_sorter
VpSpriteSorter fct_sorter
The sorting function.
Definition: viewport.cpp:3454
ZOOM_LVL_NORMAL
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition: zoom_type.h:22
SPR_CURSOR_MOUSE
static const CursorID SPR_CURSOR_MOUSE
Cursor sprite numbers.
Definition: sprites.h:1378
CeilDiv
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:280
BaseStation::IsInUse
bool IsInUse() const
Check whether the base station currently is in use; in use means that it is not scheduled for deletio...
Definition: base_station_base.h:165
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:46
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:588
Window
Data structure for an opened window.
Definition: window_gui.h:213
TILE_PIXELS
static const uint TILE_PIXELS
Pixel distance between tile columns/rows in #ZOOM_LVL_BASE.
Definition: tile_type.h:17
GetTileType
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
MAX_TILE_EXTENT_RIGHT
static const int MAX_TILE_EXTENT_RIGHT
Maximum right extent of tile relative to north corner.
Definition: viewport.cpp:110
TileHighlightData::next_drawstyle
HighLightStyle next_drawstyle
Queued, but not yet drawn style.
Definition: tilehighlight_type.h:65
_viewport_highlight_station
const Station * _viewport_highlight_station
Currently selected station for coverage area highlight.
Definition: viewport.cpp:997
VpSelectTilesWithMethod
void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
Selects tiles while dragging.
Definition: viewport.cpp:3150
TranslateXYToTileCoord
Point TranslateXYToTileCoord(const Viewport *vp, int x, int y, bool clamp_to_map)
Translate screen coordinate in a viewport to underlying tile coordinate.
Definition: viewport.cpp:426
MAX_TILE_EXTENT_TOP
static const int MAX_TILE_EXTENT_TOP
Maximum top extent of tile relative to north corner (not considering bridges).
Definition: viewport.cpp:111
InitializeSpriteSorter
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Definition: viewport.cpp:3466
viewport_sprite_sorter.h
Viewport::virtual_height
int virtual_height
height << zoom
Definition: viewport_type.h:31
Swap
static void Swap(T &a, T &b)
Type safe swap operation.
Definition: math_func.hpp:241
HT_POINT
@ HT_POINT
point (lower land, raise land, level land, ...)
Definition: tilehighlight_type.h:22
GetTilePixelSlope
static Slope GetTilePixelSlope(TileIndex tile, int *h)
Return the slope of a given tile.
Definition: tile_map.h:280
WidgetDimensions::scaled
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition: window_gui.h:68
VPM_X_AND_Y_LIMITED
@ VPM_X_AND_Y_LIMITED
area of land of limited size
Definition: viewport_type.h:93
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
HT_DIR_HU
@ HT_DIR_HU
horizontal upper
Definition: tilehighlight_type.h:35
Window::SetWidgetDirty
void SetWidgetDirty(byte widget_index) const
Invalidate a widget, i.e.
Definition: window.cpp:621
SpriteCombineMode
SpriteCombineMode
Mode of "sprite combining".
Definition: viewport.cpp:153
HandleZoomMessage
void HandleZoomMessage(Window *w, const Viewport *vp, byte widget_zoom_in, byte widget_zoom_out)
Update the status of the zoom-buttons according to the zoom-level of the viewport.
Definition: viewport.cpp:485
RemapCoords2
static Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition: landscape.h:98
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:69
CursorVars::pos
Point pos
logical mouse position
Definition: gfx_type.h:117
Sprite
Data structure describing a sprite.
Definition: spritecache.h:17
VPM_X_OR_Y
@ VPM_X_OR_Y
drag in X or Y direction
Definition: viewport_type.h:89
FOUNDATION_PART_NONE
@ FOUNDATION_PART_NONE
Neither foundation nor groundsprite drawn yet.
Definition: viewport.cpp:143
StringSpriteToDraw
Definition: viewport.cpp:114
DO_SHOW_WAYPOINT_NAMES
@ DO_SHOW_WAYPOINT_NAMES
Display waypoint names.
Definition: openttd.h:50
InitializeWindowViewport
void InitializeWindowViewport(Window *w, int x, int y, int width, int height, uint32 follow_flags, ZoomLevel zoom)
Initialize viewport of the window for use.
Definition: viewport.cpp:224
TileHighlightData::new_pos
Point new_pos
New value for pos; used to determine whether to redraw the selection.
Definition: tilehighlight_type.h:55
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
ShowWaypointWindow
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
Definition: waypoint_gui.cpp:183
HT_SPECIAL
@ HT_SPECIAL
special mode used for highlighting while dragging (and for tunnels/docks)
Definition: tilehighlight_type.h:23
ViewportSSCSS
Helper class for getting the best sprite sorter.
Definition: viewport.cpp:3452
town_kdtree.h
network_func.h
ViewportAddVehicles
void ViewportAddVehicles(DrawPixelInfo *dpi)
Add the vehicle sprites that should be drawn at a part of the screen.
Definition: vehicle.cpp:1122
TileHighlightData::redsq
TileIndex redsq
The tile that has to get a red selection.
Definition: tilehighlight_type.h:72
TileHighlightData::freeze
bool freeze
Freeze highlight in place.
Definition: tilehighlight_type.h:53
TileSpriteToDraw
Definition: viewport.cpp:123
VPM_SIGNALDIRS
@ VPM_SIGNALDIRS
similar to VMP_RAILDIRS, but with different cursor
Definition: viewport_type.h:99
viewport_cmd.h
signs_base.h
SLOPE_STEEP_N
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition: slope_type.h:69
PFE_DRAWWORLD
@ PFE_DRAWWORLD
Time spent drawing world viewports in GUI.
Definition: framerate_type.h:58
WSM_NONE
@ WSM_NONE
No special mouse mode.
Definition: window_gui.h:922
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:583
GUISettings::smooth_scroll
bool smooth_scroll
smooth scroll viewports
Definition: settings_type.h:123
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:604
TownCache::sign
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:43
Delta
static T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Definition: math_func.hpp:196
SignID
uint16 SignID
The type of the IDs of signs.
Definition: signs_type.h:14
TileHighlightData::selend
Point selend
The location where the drag currently ends.
Definition: tilehighlight_type.h:61
HT_DIR_X
@ HT_DIR_X
X direction.
Definition: tilehighlight_type.h:33
SetViewportCatchmentTown
void SetViewportCatchmentTown(const Town *t, bool sel)
Select or deselect town for coverage area highlight.
Definition: viewport.cpp:3555
TileHighlightData::GetCallbackWnd
Window * GetCallbackWnd()
Get the window that started the current highlighting.
Definition: viewport.cpp:2529
DrawPixelInfo
Data about how and where to blit pixels.
Definition: gfx_type.h:151
TileHighlightData::Reset
void Reset()
Reset tile highlighting.
Definition: viewport.cpp:2508
TileVirtXY
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition: map_func.h:194
IsBridgeAbove
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
ParentSpriteToDraw::xmax
int32 xmax
maximal world X coordinate of bounding box
Definition: viewport_sprite_sorter.h:26
SPRITE_COMBINE_PENDING
@ SPRITE_COMBINE_PENDING
Sprite combining will start with the next unclipped sprite.
Definition: viewport.cpp:155
DrawSpriteViewport
void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
Draw a sprite in a viewport.
Definition: gfx.cpp:1031