# viewport.cpp

Go to the documentation of this file.

    00001 /* $Id: viewport.cpp 26338 2014-02-15 12:19:46Z fonsinchen $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00029 #include "stdafx.h"
    00030 #include "landscape.h"
    00031 #include "viewport_func.h"
    00032 #include "station_base.h"
    00033 #include "waypoint_base.h"
    00034 #include "town.h"
    00035 #include "signs_base.h"
    00036 #include "signs_func.h"
    00037 #include "vehicle_base.h"
    00038 #include "vehicle_gui.h"
    00039 #include "blitter/factory.hpp"
    00040 #include "strings_func.h"
    00041 #include "zoom_func.h"
    00042 #include "vehicle_func.h"
    00043 #include "company_func.h"
    00044 #include "waypoint_func.h"
    00045 #include "window_func.h"
    00046 #include "tilehighlight_func.h"
    00047 #include "window_gui.h"
    00048 #include "linkgraph/linkgraph_gui.h"
    00049 #include "viewport_sprite_sorter.h"
    00050
    00051 #include "table/strings.h"
    00052 #include "table/palettes.h"
    00053
    00054 Point _tile_fract_coords;
    00055
    00056 struct StringSpriteToDraw {
    00057   StringID string;
    00058   Colours colour;
    00059   int32 x;
    00060   int32 y;
    00061   uint64 params[2];
    00062   uint16 width;
    00063 };
    00064
    00065 struct TileSpriteToDraw {
    00066   SpriteID image;
    00067   PaletteID pal;
    00068   const SubSprite *sub;
    00069   int32 x;
    00070   int32 y;
    00071 };
    00072
    00073 struct ChildScreenSpriteToDraw {
    00074   SpriteID image;
    00075   PaletteID pal;
    00076   const SubSprite *sub;
    00077   int32 x;
    00078   int32 y;
    00079   int next;
    00080 };
    00081
    00083 enum FoundationPart {
    00084   FOUNDATION_PART_NONE     = 0xFF,
    00085   FOUNDATION_PART_NORMAL   = 0,
    00086   FOUNDATION_PART_HALFTILE = 1,
    00087   FOUNDATION_PART_END
    00088 };
    00089
    00094 enum SpriteCombineMode {
    00095   SPRITE_COMBINE_NONE,
    00096   SPRITE_COMBINE_PENDING,
    00097   SPRITE_COMBINE_ACTIVE,
    00098 };
    00099
    00100 typedef SmallVector<TileSpriteToDraw, 64> TileSpriteToDrawVector;
    00101 typedef SmallVector<StringSpriteToDraw, 4> StringSpriteToDrawVector;
    00102 typedef SmallVector<ParentSpriteToDraw, 64> ParentSpriteToDrawVector;
    00103 typedef SmallVector<ChildScreenSpriteToDraw, 16> ChildScreenSpriteToDrawVector;
    00104
    00106 struct ViewportDrawer {
    00107   DrawPixelInfo dpi;
    00108
    00109   StringSpriteToDrawVector string_sprites_to_draw;
    00110   TileSpriteToDrawVector tile_sprites_to_draw;
    00111   ParentSpriteToDrawVector parent_sprites_to_draw;
    00112   ParentSpriteToSortVector parent_sprites_to_sort;
    00113   ChildScreenSpriteToDrawVector child_screen_sprites_to_draw;
    00114
    00115   int *last_child;
    00116
    00117   SpriteCombineMode combine_sprites;
    00118
    00119   int foundation[FOUNDATION_PART_END];
    00120   FoundationPart foundation_part;
    00121   int *last_foundation_child[FOUNDATION_PART_END];
    00122   Point foundation_offset[FOUNDATION_PART_END];
    00123 };
    00124
    00125 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom);
    00126
    00127 static ViewportDrawer _vd;
    00128
    00129 TileHighlightData _thd;
    00130 static TileInfo *_cur_ti;
    00131 bool _draw_bounding_boxes = false;
    00132 bool _draw_dirty_blocks = false;
    00133 uint _dirty_block_colour = 0;
    00134 static VpSpriteSorter _vp_sprite_sorter = NULL;
    00135
    00136 static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
    00137 {
    00138   Point p = RemapCoords(x, y, z);
    00139   p.x -= vp->virtual_width / 2;
    00140   p.y -= vp->virtual_height / 2;
    00141   return p;
    00142 }
    00143
    00144 void DeleteWindowViewport(Window *w)
    00145 {
    00146   if (w->viewport == NULL) return;
    00147
    00148   delete w->viewport->overlay;
    00149   free(w->viewport);
    00150   w->viewport = NULL;
    00151 }
    00152
    00165 void InitializeWindowViewport(Window *w, int x, int y,
    00166   int width, int height, uint32 follow_flags, ZoomLevel zoom)
    00167 {
    00168   assert(w->viewport == NULL);
    00169
    00170   ViewportData *vp = CallocT<ViewportData>(1);
    00171
    00172   vp->left = x + w->left;
    00173   vp->top = y + w->top;
    00174   vp->width = width;
    00175   vp->height = height;
    00176
    00177   vp->zoom = static_cast<ZoomLevel>(Clamp(zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
    00178
    00179   vp->virtual_width = ScaleByZoom(width, zoom);
    00180   vp->virtual_height = ScaleByZoom(height, zoom);
    00181
    00182   Point pt;
    00183
    00184   if (follow_flags & 0x80000000) {
    00185     const Vehicle *veh;
    00186
    00187     vp->follow_vehicle = (VehicleID)(follow_flags & 0xFFFFF);
    00188     veh = Vehicle::Get(vp->follow_vehicle);
    00189     pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
    00190   } else {
    00191     uint x = TileX(follow_flags) * TILE_SIZE;
    00192     uint y = TileY(follow_flags) * TILE_SIZE;
    00193
    00194     vp->follow_vehicle = INVALID_VEHICLE;
    00195     pt = MapXYZToViewport(vp, x, y, GetSlopePixelZ(x, y));
    00196   }
    00197
    00198   vp->scrollpos_x = pt.x;
    00199   vp->scrollpos_y = pt.y;
    00200   vp->dest_scrollpos_x = pt.x;
    00201   vp->dest_scrollpos_y = pt.y;
    00202
    00203   vp->overlay = NULL;
    00204
    00205   w->viewport = vp;
    00206   vp->virtual_left = 0;//pt.x;
    00207   vp->virtual_top = 0;//pt.y;
    00208 }
    00209
    00210 static Point _vp_move_offs;
    00211
    00212 static void DoSetViewportPosition(const Window *w, int left, int top, int width, int height)
    00213 {
    00214   FOR_ALL_WINDOWS_FROM_BACK_FROM(w, w) {
    00215     if (left + width > w->left &&
    00216         w->left + w->width > left &&
    00217         top + height > w->top &&
    00218         w->top + w->height > top) {
    00219
    00220       if (left < w->left) {
    00221         DoSetViewportPosition(w, left, top, w->left - left, height);
    00222         DoSetViewportPosition(w, left + (w->left - left), top, width - (w->left - left), height);
    00223         return;
    00224       }
    00225
    00226       if (left + width > w->left + w->width) {
    00227         DoSetViewportPosition(w, left, top, (w->left + w->width - left), height);
    00228         DoSetViewportPosition(w, left + (w->left + w->width - left), top, width - (w->left + w->width - left), height);
    00229         return;
    00230       }
    00231
    00232       if (top < w->top) {
    00233         DoSetViewportPosition(w, left, top, width, (w->top - top));
    00234         DoSetViewportPosition(w, left, top + (w->top - top), width, height - (w->top - top));
    00235         return;
    00236       }
    00237
    00238       if (top + height > w->top + w->height) {
    00239         DoSetViewportPosition(w, left, top, width, (w->top + w->height - top));
    00240         DoSetViewportPosition(w, left, top + (w->top + w->height - top), width, height - (w->top + w->height - top));
    00241         return;
    00242       }
    00243
    00244       return;
    00245     }
    00246   }
    00247
    00248   {
    00249     int xo = _vp_move_offs.x;
    00250     int yo = _vp_move_offs.y;
    00251
    00252     if (abs(xo) >= width || abs(yo) >= height) {
    00253       /* fully_outside */
    00254       RedrawScreenRect(left, top, left + width, top + height);
    00255       return;
    00256     }
    00257
    00258     GfxScroll(left, top, width, height, xo, yo);
    00259
    00260     if (xo > 0) {
    00261       RedrawScreenRect(left, top, xo + left, top + height);
    00262       left += xo;
    00263       width -= xo;
    00264     } else if (xo < 0) {
    00265       RedrawScreenRect(left + width + xo, top, left + width, top + height);
    00266       width += xo;
    00267     }
    00268
    00269     if (yo > 0) {
    00270       RedrawScreenRect(left, top, width + left, top + yo);
    00271     } else if (yo < 0) {
    00272       RedrawScreenRect(left, top + height + yo, width + left, top + height);
    00273     }
    00274   }
    00275 }
    00276
    00277 static void SetViewportPosition(Window *w, int x, int y)
    00278 {
    00279   ViewPort *vp = w->viewport;
    00280   int old_left = vp->virtual_left;
    00281   int old_top = vp->virtual_top;
    00282   int i;
    00283   int left, top, width, height;
    00284
    00285   vp->virtual_left = x;
    00286   vp->virtual_top = y;
    00287
    00288   /* Viewport is bound to its left top corner, so it must be rounded down (UnScaleByZoomLower)
    00289    * else glitch described in FS#1412 will happen (offset by 1 pixel with zoom level > NORMAL)
    00290    */
    00291   old_left = UnScaleByZoomLower(old_left, vp->zoom);
    00292   old_top = UnScaleByZoomLower(old_top, vp->zoom);
    00293   x = UnScaleByZoomLower(x, vp->zoom);
    00294   y = UnScaleByZoomLower(y, vp->zoom);
    00295
    00296   old_left -= x;
    00297   old_top -= y;
    00298
    00299   if (old_top == 0 && old_left == 0) return;
    00300
    00301   _vp_move_offs.x = old_left;
    00302   _vp_move_offs.y = old_top;
    00303
    00304   left = vp->left;
    00305   top = vp->top;
    00306   width = vp->width;
    00307   height = vp->height;
    00308
    00309   if (left < 0) {
    00310     width += left;
    00311     left = 0;
    00312   }
    00313
    00314   i = left + width - _screen.width;
    00315   if (i >= 0) width -= i;
    00316
    00317   if (width > 0) {
    00318     if (top < 0) {
    00319       height += top;
    00320       top = 0;
    00321     }
    00322
    00323     i = top + height - _screen.height;
    00324     if (i >= 0) height -= i;
    00325
    00326     if (height > 0) DoSetViewportPosition(w->z_front, left, top, width, height);
    00327   }
    00328 }
    00329
    00338 ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
    00339 {
    00340   ViewPort *vp = w->viewport;
    00341
    00342   if (vp != NULL &&
    00343       IsInsideMM(x, vp->left, vp->left + vp->width) &&
    00344       IsInsideMM(y, vp->top, vp->top + vp->height))
    00345     return vp;
    00346
    00347   return NULL;
    00348 }
    00349
    00357 static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
    00358 {
    00359   Point pt;
    00360   int a, b;
    00361   int z;
    00362
    00363   if ( (uint)(x -= vp->left) >= (uint)vp->width ||
    00364         (uint)(y -= vp->top) >= (uint)vp->height) {
    00365         Point pt = {-1, -1};
    00366         return pt;
    00367   }
    00368
    00369   x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> (2 + ZOOM_LVL_SHIFT);
    00370   y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> (1 + ZOOM_LVL_SHIFT);
    00371
    00372   a = y - x;
    00373   b = y + x;
    00374
    00375   /* we need to move variables in to the valid range, as the
    00376    * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
    00377    * when the user tries to zoom out along the sides of the map */
    00378   a = Clamp(a, -4 * (int)TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
    00379   b = Clamp(b, -4 * (int)TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
    00380
    00381   /* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
    00382    * Now find the Z-world coordinate by fix point iteration.
    00383    * This is a bit tricky because the tile height is non-continuous at foundations.
    00384    * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
    00385    * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
    00386    * So give it a z-malus of 4 in the first iterations.
    00387    */
    00388   z = 0;
    00389
    00390   int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
    00391
    00392   for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(a + max(z, 4) - 4, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + max(z, 4) - 4, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
    00393   for (int malus = 3; malus > 0; malus--) z = GetSlopePixelZ(Clamp(a + max(z, malus) - malus, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + max(z, malus) - malus, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
    00394   for (int i = 0; i < 5; i++) z = GetSlopePixelZ(Clamp(a + z, min_coord, MapMaxX() * TILE_SIZE - 1), Clamp(b + z, min_coord, MapMaxY() * TILE_SIZE - 1)) / 2;
    00395
    00396   pt.x = Clamp(a + z, min_coord, MapMaxX() * TILE_SIZE - 1);
    00397   pt.y = Clamp(b + z, min_coord, MapMaxY() * TILE_SIZE - 1);
    00398
    00399   return pt;
    00400 }
    00401
    00402 /* When used for zooming, check area below current coordinates (x,y)
    00403  * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
    00404  * when you just want the tile, make x = zoom_x and y = zoom_y */
    00405 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
    00406 {
    00407   Window *w;
    00408   ViewPort *vp;
    00409   Point pt;
    00410
    00411   if ( (w = FindWindowFromPt(x, y)) != NULL &&
    00412        (vp = IsPtInWindowViewport(w, x, y)) != NULL)
    00413         return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
    00414
    00415   pt.y = pt.x = -1;
    00416   return pt;
    00417 }
    00418
    00419 Point GetTileBelowCursor()
    00420 {
    00421   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
    00422 }
    00423
    00424
    00425 Point GetTileZoomCenterWindow(bool in, Window * w)
    00426 {
    00427   int x, y;
    00428   ViewPort *vp = w->viewport;
    00429
    00430   if (in) {
    00431     x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
    00432     y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
    00433   } else {
    00434     x = vp->width - (_cursor.pos.x - vp->left);
    00435     y = vp->height - (_cursor.pos.y - vp->top);
    00436   }
    00437   /* Get the tile below the cursor and center on the zoomed-out center */
    00438   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
    00439 }
    00440
    00449 void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
    00450 {
    00451   w->SetWidgetDisabledState(widget_zoom_in, vp->zoom <= _settings_client.gui.zoom_min);
    00452   w->SetWidgetDirty(widget_zoom_in);
    00453
    00454   w->SetWidgetDisabledState(widget_zoom_out, vp->zoom >= _settings_client.gui.zoom_max);
    00455   w->SetWidgetDirty(widget_zoom_out);
    00456 }
    00457
    00470 static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0)
    00471 {
    00472   assert((image & SPRITE_MASK) < MAX_SPRITES);
    00473
    00474   TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
    00475   ts->image = image;
    00476   ts->pal = pal;
    00477   ts->sub = sub;
    00478   Point pt = RemapCoords(x, y, z);
    00479   ts->x = pt.x + extra_offs_x;
    00480   ts->y = pt.y + extra_offs_y;
    00481 }
    00482
    00495 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
    00496 {
    00497   assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
    00498   assert(_vd.foundation[foundation_part] != -1);
    00499   Point offs = _vd.foundation_offset[foundation_part];
    00500
    00501   /* Change the active ChildSprite list to the one of the foundation */
    00502   int *old_child = _vd.last_child;
    00503   _vd.last_child = _vd.last_foundation_child[foundation_part];
    00504
    00505   AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub, false);
    00506
    00507   /* Switch back to last ChildSprite list */
    00508   _vd.last_child = old_child;
    00509 }
    00510
    00524 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
    00525 {
    00526   /* Switch to first foundation part, if no foundation was drawn */
    00527   if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
    00528
    00529   if (_vd.foundation[_vd.foundation_part] != -1) {
    00530     Point pt = RemapCoords(x, y, z);
    00531     AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x * ZOOM_LVL_BASE, pt.y + extra_offs_y * ZOOM_LVL_BASE);
    00532   } else {
    00533     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);
    00534   }
    00535 }
    00536
    00547 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
    00548 {
    00549   DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
    00550 }
    00551
    00559 void OffsetGroundSprite(int x, int y)
    00560 {
    00561   /* Switch to next foundation part */
    00562   switch (_vd.foundation_part) {
    00563     case FOUNDATION_PART_NONE:
    00564       _vd.foundation_part = FOUNDATION_PART_NORMAL;
    00565       break;
    00566     case FOUNDATION_PART_NORMAL:
    00567       _vd.foundation_part = FOUNDATION_PART_HALFTILE;
    00568       break;
    00569     default: NOT_REACHED();
    00570   }
    00571
    00572   /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
    00573   if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
    00574
    00575   _vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_LVL_BASE;
    00576   _vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_LVL_BASE;
    00577   _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
    00578 }
    00579
    00591 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z, const SubSprite *sub)
    00592 {
    00593   Point pt = RemapCoords(x, y, z);
    00594   const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
    00595
    00596   if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
    00597       pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
    00598       pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
    00599       pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
    00600     return;
    00601
    00602   const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
    00603   AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub, false);
    00604 }
    00605
    00631 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)
    00632 {
    00633   int32 left, right, top, bottom;
    00634
    00635   assert((image & SPRITE_MASK) < MAX_SPRITES);
    00636
    00637   /* make the sprites transparent with the right palette */
    00638   if (transparent) {
    00639     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
    00640     pal = PALETTE_TO_TRANSPARENT;
    00641   }
    00642
    00643   if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
    00644     AddCombinedSprite(image, pal, x, y, z, sub);
    00645     return;
    00646   }
    00647
    00648   _vd.last_child = NULL;
    00649
    00650   Point pt = RemapCoords(x, y, z);
    00651   int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
    00652
    00653   /* Compute screen extents of sprite */
    00654   if (image == SPR_EMPTY_BOUNDING_BOX) {
    00655     left = tmp_left = RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x;
    00656     right           = RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1;
    00657     top  = tmp_top  = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y;
    00658     bottom          = RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1;
    00659   } else {
    00660     const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
    00661     left = tmp_left = (pt.x += spr->x_offs);
    00662     right           = (pt.x +  spr->width );
    00663     top  = tmp_top  = (pt.y += spr->y_offs);
    00664     bottom          = (pt.y +  spr->height);
    00665   }
    00666
    00667   if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
    00668     /* Compute maximal extents of sprite and its bounding box */
    00669     left   = min(left  , RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x);
    00670     right  = max(right , RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1);
    00671     top    = min(top   , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y);
    00672     bottom = max(bottom, RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1);
    00673   }
    00674
    00675   /* Do not add the sprite to the viewport, if it is outside */
    00676   if (left   >= _vd.dpi.left + _vd.dpi.width ||
    00677       right  <= _vd.dpi.left                 ||
    00678       top    >= _vd.dpi.top + _vd.dpi.height ||
    00679       bottom <= _vd.dpi.top) {
    00680     return;
    00681   }
    00682
    00683   ParentSpriteToDraw *ps = _vd.parent_sprites_to_draw.Append();
    00684   ps->x = tmp_x;
    00685   ps->y = tmp_y;
    00686
    00687   ps->left = tmp_left;
    00688   ps->top  = tmp_top;
    00689
    00690   ps->image = image;
    00691   ps->pal = pal;
    00692   ps->sub = sub;
    00693   ps->xmin = x + bb_offset_x;
    00694   ps->xmax = x + max(bb_offset_x, w) - 1;
    00695
    00696   ps->ymin = y + bb_offset_y;
    00697   ps->ymax = y + max(bb_offset_y, h) - 1;
    00698
    00699   ps->zmin = z + bb_offset_z;
    00700   ps->zmax = z + max(bb_offset_z, dz) - 1;
    00701
    00702   ps->comparison_done = false;
    00703   ps->first_child = -1;
    00704
    00705   _vd.last_child = &ps->first_child;
    00706
    00707   if (_vd.combine_sprites == SPRITE_COMBINE_PENDING) _vd.combine_sprites = SPRITE_COMBINE_ACTIVE;
    00708 }
    00709
    00728 void StartSpriteCombine()
    00729 {
    00730   assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
    00731   _vd.combine_sprites = SPRITE_COMBINE_PENDING;
    00732 }
    00733
    00738 void EndSpriteCombine()
    00739 {
    00740   assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
    00741   _vd.combine_sprites = SPRITE_COMBINE_NONE;
    00742 }
    00743
    00753 static bool IsInRangeInclusive(int begin, int end, int check)
    00754 {
    00755   if (begin > end) Swap(begin, end);
    00756   return begin <= check && check <= end;
    00757 }
    00758
    00765 bool IsInsideRotatedRectangle(int x, int y)
    00766 {
    00767   int dist_a = (_thd.size.x + _thd.size.y);      // Rotated coordinate system for selected rectangle.
    00768   int dist_b = (_thd.size.x - _thd.size.y);      // We don't have to divide by 2. It's all relative!
    00769   int a = ((x - _thd.pos.x) + (y - _thd.pos.y)); // Rotated coordinate system for the point under scrutiny.
    00770   int b = ((x - _thd.pos.x) - (y - _thd.pos.y));
    00771
    00772   /* Check if a and b are between 0 and dist_a or dist_b respectively. */
    00773   return IsInRangeInclusive(dist_a, 0, a) && IsInRangeInclusive(dist_b, 0, b);
    00774 }
    00775
    00786 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
    00787 {
    00788   assert((image & SPRITE_MASK) < MAX_SPRITES);
    00789
    00790   /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
    00791   if (_vd.last_child == NULL) return;
    00792
    00793   /* make the sprites transparent with the right palette */
    00794   if (transparent) {
    00795     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
    00796     pal = PALETTE_TO_TRANSPARENT;
    00797   }
    00798
    00799   *_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
    00800
    00801   ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
    00802   cs->image = image;
    00803   cs->pal = pal;
    00804   cs->sub = sub;
    00805   cs->x = scale ? x * ZOOM_LVL_BASE : x;
    00806   cs->y = scale ? y * ZOOM_LVL_BASE : y;
    00807   cs->next = -1;
    00808
    00809   /* Append the sprite to the active ChildSprite list.
    00810    * If the active ParentSprite is a foundation, update last_foundation_child as well.
    00811    * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
    00812   if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
    00813   if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
    00814   _vd.last_child = &cs->next;
    00815 }
    00816
    00817 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
    00818 {
    00819   assert(width != 0);
    00820   StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
    00821   ss->string = string;
    00822   ss->x = x;
    00823   ss->y = y;
    00824   ss->params[0] = params_1;
    00825   ss->params[1] = params_2;
    00826   ss->width = width;
    00827   ss->colour = colour;
    00828 }
    00829
    00830
    00842 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
    00843 {
    00844   /* FIXME: This is not totally valid for some autorail highlights that extend over the edges of the tile. */
    00845   if (_vd.foundation[foundation_part] == -1) {
    00846     /* draw on real ground */
    00847     AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
    00848   } else {
    00849     /* draw on top of foundation */
    00850     AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset * ZOOM_LVL_BASE);
    00851   }
    00852 }
    00853
    00860 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
    00861 {
    00862   if (!IsValidTile(ti->tile)) return;
    00863
    00864   SpriteID sel;
    00865   if (IsHalftileSlope(ti->tileh)) {
    00866     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    00867     SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
    00868     DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
    00869
    00870     Corner opposite_corner = OppositeCorner(halftile_corner);
    00871     if (IsSteepSlope(ti->tileh)) {
    00872       sel = SPR_HALFTILE_SELECTION_DOWN;
    00873     } else {
    00874       sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
    00875     }
    00876     sel += opposite_corner;
    00877   } else {
    00878     sel = SPR_SELECT_TILE + SlopeToSpriteOffset(ti->tileh);
    00879   }
    00880   DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
    00881 }
    00882
    00883 static bool IsPartOfAutoLine(int px, int py)
    00884 {
    00885   px -= _thd.selstart.x;
    00886   py -= _thd.selstart.y;
    00887
    00888   if ((_thd.drawstyle & HT_DRAG_MASK) != HT_LINE) return false;
    00889
    00890   switch (_thd.drawstyle & HT_DIR_MASK) {
    00891     case HT_DIR_X:  return py == 0; // x direction
    00892     case HT_DIR_Y:  return px == 0; // y direction
    00893     case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
    00894     case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
    00895     case HT_DIR_VL: return px == py || px == py + 16; // vertical left
    00896     case HT_DIR_VR: return px == py || px == py - 16; // vertical right
    00897     default:
    00898       NOT_REACHED();
    00899   }
    00900 }
    00901
    00902 /* [direction][side] */
    00903 static const HighLightStyle _autorail_type[6][2] = {
    00904   { HT_DIR_X,  HT_DIR_X },
    00905   { HT_DIR_Y,  HT_DIR_Y },
    00906   { HT_DIR_HU, HT_DIR_HL },
    00907   { HT_DIR_HL, HT_DIR_HU },
    00908   { HT_DIR_VL, HT_DIR_VR },
    00909   { HT_DIR_VR, HT_DIR_VL }
    00910 };
    00911
    00912 #include "table/autorail.h"
    00913
    00920 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
    00921 {
    00922   SpriteID image;
    00923   PaletteID pal;
    00924   int offset;
    00925
    00926   FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
    00927   Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
    00928   if (IsHalftileSlope(ti->tileh)) {
    00929     static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
    00930     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    00931     if (autorail_type != _lower_rail[halftile_corner]) {
    00932       foundation_part = FOUNDATION_PART_HALFTILE;
    00933       /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
    00934       autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
    00935     }
    00936   }
    00937
    00938   offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
    00939   if (offset >= 0) {
    00940     image = SPR_AUTORAIL_BASE + offset;
    00941     pal = PAL_NONE;
    00942   } else {
    00943     image = SPR_AUTORAIL_BASE - offset;
    00944     pal = PALETTE_SEL_TILE_RED;
    00945   }
    00946
    00947   DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
    00948 }
    00949
    00954 static void DrawTileSelection(const TileInfo *ti)
    00955 {
    00956   /* Draw a red error square? */
    00957   bool is_redsq = _thd.redsq == ti->tile;
    00958   if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
    00959
    00960   /* No tile selection active? */
    00961   if ((_thd.drawstyle & HT_DRAG_MASK) == HT_NONE) return;
    00962
    00963   if (_thd.diagonal) { // We're drawing a 45 degrees rotated (diagonal) rectangle
    00964     if (IsInsideRotatedRectangle((int)ti->x, (int)ti->y)) goto draw_inner;
    00965     return;
    00966   }
    00967
    00968   /* Inside the inner area? */
    00969   if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
    00970       IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
    00971 draw_inner:
    00972     if (_thd.drawstyle & HT_RECT) {
    00973       if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
    00974     } else if (_thd.drawstyle & HT_POINT) {
    00975       /* Figure out the Z coordinate for the single dot. */
    00976       int z = 0;
    00977       FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
    00978       if (ti->tileh & SLOPE_N) {
    00979         z += TILE_HEIGHT;
    00980         if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
    00981       }
    00982       if (IsHalftileSlope(ti->tileh)) {
    00983         Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
    00984         if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
    00985         if (halftile_corner != CORNER_S) {
    00986           foundation_part = FOUNDATION_PART_HALFTILE;
    00987           if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
    00988         }
    00989       }
    00990       DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
    00991     } else if (_thd.drawstyle & HT_RAIL) {
    00992       /* autorail highlight piece under cursor */
    00993       HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
    00994       assert(type < HT_DIR_END);
    00995       DrawAutorailSelection(ti, _autorail_type[type][0]);
    00996     } else if (IsPartOfAutoLine(ti->x, ti->y)) {
    00997       /* autorail highlighting long line */
    00998       HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
    00999       uint side;
    01000
    01001       if (dir == HT_DIR_X || dir == HT_DIR_Y) {
    01002         side = 0;
    01003       } else {
    01004         TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
    01005         side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
    01006       }
    01007
    01008       DrawAutorailSelection(ti, _autorail_type[dir][side]);
    01009     }
    01010     return;
    01011   }
    01012
    01013   /* Check if it's inside the outer area? */
    01014   if (!is_redsq && _thd.outersize.x > 0 &&
    01015       IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
    01016       IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
    01017     /* Draw a blue rect. */
    01018     DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
    01019     return;
    01020   }
    01021 }
    01022
    01023 static void ViewportAddLandscape()
    01024 {
    01025   int x, y, width, height;
    01026   TileInfo ti;
    01027   bool direction;
    01028
    01029   _cur_ti = &ti;
    01030
    01031   /* Transform into tile coordinates and round to closest full tile */
    01032   x = ((_vd.dpi.top >> (1 + ZOOM_LVL_SHIFT)) - (_vd.dpi.left >> (2 + ZOOM_LVL_SHIFT))) & ~TILE_UNIT_MASK;
    01033   y = ((_vd.dpi.top >> (1 + ZOOM_LVL_SHIFT)) + (_vd.dpi.left >> (2 + ZOOM_LVL_SHIFT)) - TILE_SIZE) & ~TILE_UNIT_MASK;
    01034
    01035   /* determine size of area */
    01036   {
    01037     Point pt = RemapCoords(x, y, 241);
    01038     width = (_vd.dpi.left + _vd.dpi.width - pt.x + 96 * ZOOM_LVL_BASE - 1) >> (6 + ZOOM_LVL_SHIFT);
    01039     height = (_vd.dpi.top + _vd.dpi.height - pt.y) >> (5 + ZOOM_LVL_SHIFT) << 1;
    01040   }
    01041
    01042   assert(width > 0);
    01043   assert(height > 0);
    01044
    01045   direction = false;
    01046
    01047   do {
    01048     int width_cur = width;
    01049     uint x_cur = x;
    01050     uint y_cur = y;
    01051
    01052     do {
    01053       TileType tt = MP_VOID;
    01054
    01055       ti.x = x_cur;
    01056       ti.y = y_cur;
    01057
    01058       ti.z = 0;
    01059
    01060       ti.tileh = SLOPE_FLAT;
    01061       ti.tile = INVALID_TILE;
    01062
    01063       if (x_cur < MapMaxX() * TILE_SIZE &&
    01064           y_cur < MapMaxY() * TILE_SIZE) {
    01065         TileIndex tile = TileVirtXY(x_cur, y_cur);
    01066
    01067         if (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0)) {
    01068           if (x_cur == ((int)MapMaxX() - 1) * TILE_SIZE || y_cur == ((int)MapMaxY() - 1) * TILE_SIZE) {
    01069             uint maxh = max<uint>(TileHeight(tile), 1);
    01070             for (uint h = 0; h < maxh; h++) {
    01071               AddTileSpriteToDraw(SPR_SHADOW_CELL, PAL_NONE, ti.x, ti.y, h * TILE_HEIGHT);
    01072             }
    01073           }
    01074
    01075           ti.tile = tile;
    01076           ti.tileh = GetTilePixelSlope(tile, &ti.z);
    01077           tt = GetTileType(tile);
    01078         }
    01079       }
    01080
    01081       _vd.foundation_part = FOUNDATION_PART_NONE;
    01082       _vd.foundation[0] = -1;
    01083       _vd.foundation[1] = -1;
    01084       _vd.last_foundation_child[0] = NULL;
    01085       _vd.last_foundation_child[1] = NULL;
    01086
    01087       _tile_type_procs[tt]->draw_tile_proc(&ti);
    01088
    01089       if ((x_cur == (int)MapMaxX() * TILE_SIZE && IsInsideMM(y_cur, 0, MapMaxY() * TILE_SIZE + 1)) ||
    01090           (y_cur == (int)MapMaxY() * TILE_SIZE && IsInsideMM(x_cur, 0, MapMaxX() * TILE_SIZE + 1))) {
    01091         TileIndex tile = TileVirtXY(x_cur, y_cur);
    01092         ti.tile = tile;
    01093         ti.tileh = GetTilePixelSlope(tile, &ti.z);
    01094         tt = GetTileType(tile);
    01095       }
    01096       if (ti.tile != INVALID_TILE) DrawTileSelection(&ti);
    01097
    01098       y_cur += 0x10;
    01099       x_cur -= 0x10;
    01100     } while (--width_cur);
    01101
    01102     if ((direction ^= 1) != 0) {
    01103       y += 0x10;
    01104     } else {
    01105       x += 0x10;
    01106     }
    01107   } while (--height);
    01108 }
    01109
    01120 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)
    01121 {
    01122   bool small = dpi->zoom >= small_from;
    01123
    01124   int left   = dpi->left;
    01125   int top    = dpi->top;
    01126   int right  = left + dpi->width;
    01127   int bottom = top + dpi->height;
    01128
    01129   int sign_height     = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
    01130   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
    01131
    01132   if (bottom < sign->top ||
    01133       top   > sign->top + sign_height ||
    01134       right < sign->center - sign_half_width ||
    01135       left  > sign->center + sign_half_width) {
    01136     return;
    01137   }
    01138
    01139   if (!small) {
    01140     AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
    01141   } else {
    01142     int shadow_offset = 0;
    01143     if (string_small_shadow != STR_NULL) {
    01144       shadow_offset = 4;
    01145       AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
    01146     }
    01147     AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
    01148         colour, sign->width_small | 0x8000);
    01149   }
    01150 }
    01151
    01152 static void ViewportAddTownNames(DrawPixelInfo *dpi)
    01153 {
    01154   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
    01155
    01156   const Town *t;
    01157   FOR_ALL_TOWNS(t) {
    01158     ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &t->cache.sign,
    01159         _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
    01160         STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
    01161         t->index, t->cache.population);
    01162   }
    01163 }
    01164
    01165
    01166 static void ViewportAddStationNames(DrawPixelInfo *dpi)
    01167 {
    01168   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
    01169
    01170   const BaseStation *st;
    01171   FOR_ALL_BASE_STATIONS(st) {
    01172     /* Check whether the base station is a station or a waypoint */
    01173     bool is_station = Station::IsExpected(st);
    01174
    01175     /* Don't draw if the display options are disabled */
    01176     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
    01177
    01178     /* Don't draw if station is owned by another company and competitor station names are hidden. Stations owned by none are never ignored. */
    01179     if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != st->owner && st->owner != OWNER_NONE) continue;
    01180
    01181     ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &st->sign,
    01182         is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT,
    01183         (is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT) + 1, STR_NULL,
    01184         st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
    01185   }
    01186 }
    01187
    01188
    01189 static void ViewportAddSigns(DrawPixelInfo *dpi)
    01190 {
    01191   /* Signs are turned off or are invisible */
    01192   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
    01193
    01194   const Sign *si;
    01195   FOR_ALL_SIGNS(si) {
    01196     /* Don't draw if sign is owned by another company and competitor signs should be hidden.
    01197      * Note: It is intentional that also signs owned by OWNER_NONE are hidden. Bankrupt
    01198      * companies can leave OWNER_NONE signs after them. */
    01199     if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != si->owner && si->owner != OWNER_DEITY) continue;
    01200
    01201     ViewportAddString(dpi, ZOOM_LVL_OUT_16X, &si->sign,
    01202         STR_WHITE_SIGN,
    01203         (IsTransparencySet(TO_SIGNS) || si->owner == OWNER_DEITY) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
    01204         si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : (si->owner == OWNER_DEITY ? INVALID_COLOUR : _company_colours[si->owner]));
    01205   }
    01206 }
    01207
    01214 void ViewportSign::UpdatePosition(int center, int top, StringID str)
    01215 {
    01216   if (this->width_normal != 0) this->MarkDirty();
    01217
    01218   this->top = top;
    01219
    01220   char buffer[DRAW_STRING_BUFFER];
    01221
    01222   GetString(buffer, str, lastof(buffer));
    01223   this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
    01224   this->center = center;
    01225
    01226   /* zoomed out version */
    01227   this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer, FS_SMALL).width, 2) + VPSM_RIGHT;
    01228
    01229   this->MarkDirty();
    01230 }
    01231
    01238 void ViewportSign::MarkDirty(ZoomLevel maxzoom) const
    01239 {
    01240   Rect zoomlevels[ZOOM_LVL_COUNT];
    01241
    01242   for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
    01243     /* FIXME: This doesn't switch to width_small when appropriate. */
    01244     zoomlevels[zoom].left   = this->center - ScaleByZoom(this->width_normal / 2 + 1, zoom);
    01245     zoomlevels[zoom].top    = this->top    - ScaleByZoom(1, zoom);
    01246     zoomlevels[zoom].right  = this->center + ScaleByZoom(this->width_normal / 2 + 1, zoom);
    01247     zoomlevels[zoom].bottom = this->top    + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, zoom);
    01248   }
    01249
    01250   Window *w;
    01251   FOR_ALL_WINDOWS_FROM_BACK(w) {
    01252     ViewPort *vp = w->viewport;
    01253     if (vp != NULL && vp->zoom <= maxzoom) {
    01254       assert(vp->width != 0);
    01255       Rect &zl = zoomlevels[vp->zoom];
    01256       MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
    01257     }
    01258   }
    01259 }
    01260
    01261 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
    01262 {
    01263   const TileSpriteToDraw *tsend = tstdv->End();
    01264   for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
    01265     DrawSpriteViewport(ts->image, ts->pal, ts->x, ts->y, ts->sub);
    01266   }
    01267 }
    01268
    01270 static bool ViewportSortParentSpritesChecker()
    01271 {
    01272   return true;
    01273 }
    01274
    01276 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
    01277 {
    01278   ParentSpriteToDraw **psdvend = psdv->End();
    01279   ParentSpriteToDraw **psd = psdv->Begin();
    01280   while (psd != psdvend) {
    01281     ParentSpriteToDraw *ps = *psd;
    01282
    01283     if (ps->comparison_done) {
    01284       psd++;
    01285       continue;
    01286     }
    01287
    01288     ps->comparison_done = true;
    01289
    01290     for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
    01291       ParentSpriteToDraw *ps2 = *psd2;
    01292
    01293       if (ps2->comparison_done) continue;
    01294
    01295       /* Decide which comparator to use, based on whether the bounding
    01296        * boxes overlap
    01297        */
    01298       if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
    01299           ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
    01300           ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
    01301         /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
    01302          * the screen and with higher Z elevation, are drawn in front.
    01303          * Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
    01304          * i.e. X=(left+right)/2, etc.
    01305          * However, since we only care about order, don't actually divide / 2
    01306          */
    01307         if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
    01308             ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
    01309           continue;
    01310         }
    01311       } else {
    01312         /* We only change the order, if it is definite.
    01313          * I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
    01314          * That is: If one partial order says ps behind ps2, do not change the order.
    01315          */
    01316         if (ps->xmax < ps2->xmin ||
    01317             ps->ymax < ps2->ymin ||
    01318             ps->zmax < ps2->zmin) {
    01319           continue;
    01320         }
    01321       }
    01322
    01323       /* Move ps2 in front of ps */
    01324       ParentSpriteToDraw *temp = ps2;
    01325       for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
    01326         *psd3 = *(psd3 - 1);
    01327       }
    01328       *psd = temp;
    01329     }
    01330   }
    01331 }
    01332
    01333 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
    01334 {
    01335   const ParentSpriteToDraw * const *psd_end = psd->End();
    01336   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
    01337     const ParentSpriteToDraw *ps = *it;
    01338     if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
    01339
    01340     int child_idx = ps->first_child;
    01341     while (child_idx >= 0) {
    01342       const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
    01343       child_idx = cs->next;
    01344       DrawSpriteViewport(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
    01345     }
    01346   }
    01347 }
    01348
    01353 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
    01354 {
    01355   const ParentSpriteToDraw * const *psd_end = psd->End();
    01356   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
    01357     const ParentSpriteToDraw *ps = *it;
    01358     Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
    01359     Point pt2 = RemapCoords(ps->xmin    , ps->ymax + 1, ps->zmax + 1); // top left corner
    01360     Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin    , ps->zmax + 1); // top right corner
    01361     Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin    ); // bottom front corner
    01362
    01363     DrawBox(        pt1.x,         pt1.y,
    01364             pt2.x - pt1.x, pt2.y - pt1.y,
    01365             pt3.x - pt1.x, pt3.y - pt1.y,
    01366             pt4.x - pt1.x, pt4.y - pt1.y);
    01367   }
    01368 }
    01369
    01373 static void ViewportDrawDirtyBlocks()
    01374 {
    01375   Blitter *blitter = BlitterFactory::GetCurrentBlitter();
    01376   const DrawPixelInfo *dpi = _cur_dpi;
    01377   void *dst;
    01378   int right =  UnScaleByZoom(dpi->width,  dpi->zoom);
    01379   int bottom = UnScaleByZoom(dpi->height, dpi->zoom);
    01380
    01381   int colour = _string_colourmap[_dirty_block_colour & 0xF];
    01382
    01383   dst = dpi->dst_ptr;
    01384
    01385   byte bo = UnScaleByZoom(dpi->left + dpi->top, dpi->zoom) & 1;
    01386   do {
    01387     for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
    01388     dst = blitter->MoveTo(dst, 0, 1);
    01389   } while (--bottom > 0);
    01390 }
    01391
    01392 static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
    01393 {
    01394   const StringSpriteToDraw *ssend = sstdv->End();
    01395   for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
    01396     TextColour colour = TC_BLACK;
    01397     bool small = HasBit(ss->width, 15);
    01398     int w = GB(ss->width, 0, 15);
    01399     int x = UnScaleByZoom(ss->x, zoom);
    01400     int y = UnScaleByZoom(ss->y, zoom);
    01401     int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
    01402
    01403     SetDParam(0, ss->params[0]);
    01404     SetDParam(1, ss->params[1]);
    01405
    01406     if (ss->colour != INVALID_COLOUR) {
    01407       /* Do not draw signs nor station names if they are set invisible */
    01408       if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue;
    01409
    01410       if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) {
    01411         /* Don't draw the rectangle.
    01412          * Real colours need the TC_IS_PALETTE_COLOUR flag.
    01413          * Otherwise colours from _string_colourmap are assumed. */
    01414         colour = (TextColour)_colour_gradient[ss->colour][6] | TC_IS_PALETTE_COLOUR;
    01415       } else {
    01416         /* Draw the rectangle if 'transparent station signs' is off,
    01417          * or if we are drawing a general text sign (STR_WHITE_SIGN). */
    01418         DrawFrameRect(
    01419           x, y, x + w, y + h, ss->colour,
    01420           IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
    01421         );
    01422       }
    01423     }
    01424
    01425     DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_HOR_CENTER);
    01426   }
    01427 }
    01428
    01429 void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
    01430 {
    01431   DrawPixelInfo *old_dpi = _cur_dpi;
    01432   _cur_dpi = &_vd.dpi;
    01433
    01434   _vd.dpi.zoom = vp->zoom;
    01435   int mask = ScaleByZoom(-1, vp->zoom);
    01436
    01437   _vd.combine_sprites = SPRITE_COMBINE_NONE;
    01438
    01439   _vd.dpi.width = (right - left) & mask;
    01440   _vd.dpi.height = (bottom - top) & mask;
    01441   _vd.dpi.left = left & mask;
    01442   _vd.dpi.top = top & mask;
    01443   _vd.dpi.pitch = old_dpi->pitch;
    01444   _vd.last_child = NULL;
    01445
    01446   int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
    01447   int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
    01448
    01449   _vd.dpi.dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
    01450
    01451   ViewportAddLandscape();
    01452   ViewportAddVehicles(&_vd.dpi);
    01453
    01454   ViewportAddTownNames(&_vd.dpi);
    01455   ViewportAddStationNames(&_vd.dpi);
    01456   ViewportAddSigns(&_vd.dpi);
    01457
    01458   DrawTextEffects(&_vd.dpi);
    01459
    01460   if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
    01461
    01462   ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
    01463   for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
    01464     *_vd.parent_sprites_to_sort.Append() = it;
    01465   }
    01466
    01467   _vp_sprite_sorter(&_vd.parent_sprites_to_sort);
    01468   ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
    01469
    01470   if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
    01471   if (_draw_dirty_blocks) ViewportDrawDirtyBlocks();
    01472
    01473   DrawPixelInfo dp = _vd.dpi;
    01474   ZoomLevel zoom = _vd.dpi.zoom;
    01475   dp.zoom = ZOOM_LVL_NORMAL;
    01476   dp.width = UnScaleByZoom(dp.width, zoom);
    01477   dp.height = UnScaleByZoom(dp.height, zoom);
    01478   _cur_dpi = &dp;
    01479
    01480   if (vp->overlay != NULL && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
    01481     /* translate to window coordinates */
    01482     dp.left = x;
    01483     dp.top = y;
    01484     vp->overlay->Draw(&dp);
    01485   }
    01486
    01487   if (_vd.string_sprites_to_draw.Length() != 0) {
    01488     /* translate to world coordinates */
    01489     dp.left = UnScaleByZoom(_vd.dpi.left, zoom);
    01490     dp.top = UnScaleByZoom(_vd.dpi.top, zoom);
    01491     ViewportDrawStrings(zoom, &_vd.string_sprites_to_draw);
    01492   }
    01493
    01494   _cur_dpi = old_dpi;
    01495
    01496   _vd.string_sprites_to_draw.Clear();
    01497   _vd.tile_sprites_to_draw.Clear();
    01498   _vd.parent_sprites_to_draw.Clear();
    01499   _vd.parent_sprites_to_sort.Clear();
    01500   _vd.child_screen_sprites_to_draw.Clear();
    01501 }
    01502
    01507 static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
    01508 {
    01509   if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom) > 180000 * ZOOM_LVL_BASE * ZOOM_LVL_BASE) {
    01510     if ((bottom - top) > (right - left)) {
    01511       int t = (top + bottom) >> 1;
    01512       ViewportDrawChk(vp, left, top, right, t);
    01513       ViewportDrawChk(vp, left, t, right, bottom);
    01514     } else {
    01515       int t = (left + right) >> 1;
    01516       ViewportDrawChk(vp, left, top, t, bottom);
    01517       ViewportDrawChk(vp, t, top, right, bottom);
    01518     }
    01519   } else {
    01520     ViewportDoDraw(vp,
    01521       ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
    01522       ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
    01523       ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
    01524       ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
    01525     );
    01526   }
    01527 }
    01528
    01529 static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
    01530 {
    01531   if (right <= vp->left || bottom <= vp->top) return;
    01532
    01533   if (left >= vp->left + vp->width) return;
    01534
    01535   if (left < vp->left) left = vp->left;
    01536   if (right > vp->left + vp->width) right = vp->left + vp->width;
    01537
    01538   if (top >= vp->top + vp->height) return;
    01539
    01540   if (top < vp->top) top = vp->top;
    01541   if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
    01542
    01543   ViewportDrawChk(vp, left, top, right, bottom);
    01544 }
    01545
    01549 void Window::DrawViewport() const
    01550 {
    01551   DrawPixelInfo *dpi = _cur_dpi;
    01552
    01553   dpi->left += this->left;
    01554   dpi->top += this->top;
    01555
    01556   ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
    01557
    01558   dpi->left -= this->left;
    01559   dpi->top -= this->top;
    01560 }
    01561
    01562 static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
    01563 {
    01564   /* Centre of the viewport is hot spot */
    01565   x += vp->virtual_width / 2;
    01566   y += vp->virtual_height / 2;
    01567
    01568   /* Convert viewport coordinates to map coordinates
    01569    * Calculation is scaled by 4 to avoid rounding errors */
    01570   int vx = -x + y * 2;
    01571   int vy =  x + y * 2;
    01572
    01573   /* clamp to size of map */
    01574   vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4 * ZOOM_LVL_BASE);
    01575   vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4 * ZOOM_LVL_BASE);
    01576
    01577   /* Convert map coordinates to viewport coordinates */
    01578   x = (-vx + vy) / 2;
    01579   y = ( vx + vy) / 4;
    01580
    01581   /* Remove centering */
    01582   x -= vp->virtual_width / 2;
    01583   y -= vp->virtual_height / 2;
    01584 }
    01585
    01590 void UpdateViewportPosition(Window *w)
    01591 {
    01592   const ViewPort *vp = w->viewport;
    01593
    01594   if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
    01595     const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
    01596     Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
    01597
    01598     w->viewport->scrollpos_x = pt.x;
    01599     w->viewport->scrollpos_y = pt.y;
    01600     SetViewportPosition(w, pt.x, pt.y);
    01601   } else {
    01602     /* Ensure the destination location is within the map */
    01603     ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
    01604
    01605     int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
    01606     int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
    01607
    01608     bool update_overlay = false;
    01609     if (delta_x != 0 || delta_y != 0) {
    01610       if (_settings_client.gui.smooth_scroll) {
    01611         int max_scroll = ScaleByMapSize1D(512 * ZOOM_LVL_BASE);
    01612         /* Not at our desired position yet... */
    01613         w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
    01614         w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
    01615       } else {
    01616         w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
    01617         w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
    01618       }
    01619       update_overlay = (w->viewport->scrollpos_x == w->viewport->dest_scrollpos_x &&
    01620                 w->viewport->scrollpos_y == w->viewport->dest_scrollpos_y);
    01621     }
    01622
    01623     ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
    01624
    01625     SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
    01626     if (update_overlay) RebuildViewportOverlay(w);
    01627   }
    01628 }
    01629
    01639 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
    01640 {
    01641   right -= vp->virtual_left;
    01642   if (right <= 0) return;
    01643
    01644   bottom -= vp->virtual_top;
    01645   if (bottom <= 0) return;
    01646
    01647   left = max(0, left - vp->virtual_left);
    01648
    01649   if (left >= vp->virtual_width) return;
    01650
    01651   top = max(0, top - vp->virtual_top);
    01652
    01653   if (top >= vp->virtual_height) return;
    01654
    01655   SetDirtyBlocks(
    01656     UnScaleByZoomLower(left, vp->zoom) + vp->left,
    01657     UnScaleByZoomLower(top, vp->zoom) + vp->top,
    01658     UnScaleByZoom(right, vp->zoom) + vp->left + 1,
    01659     UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
    01660   );
    01661 }
    01662
    01671 void MarkAllViewportsDirty(int left, int top, int right, int bottom)
    01672 {
    01673   Window *w;
    01674   FOR_ALL_WINDOWS_FROM_BACK(w) {
    01675     ViewPort *vp = w->viewport;
    01676     if (vp != NULL) {
    01677       assert(vp->width != 0);
    01678       MarkViewportDirty(vp, left, top, right, bottom);
    01679     }
    01680   }
    01681 }
    01682
    01683 void ConstrainAllViewportsZoom()
    01684 {
    01685   Window *w;
    01686   FOR_ALL_WINDOWS_FROM_FRONT(w) {
    01687     if (w->viewport == NULL) continue;
    01688
    01689     ZoomLevel zoom = static_cast<ZoomLevel>(Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
    01690     if (zoom != w->viewport->zoom) {
    01691       while (w->viewport->zoom < zoom) DoZoomInOutWindow(ZOOM_OUT, w);
    01692       while (w->viewport->zoom > zoom) DoZoomInOutWindow(ZOOM_IN, w);
    01693     }
    01694   }
    01695 }
    01696
    01702 void MarkTileDirtyByTile(TileIndex tile)
    01703 {
    01704   Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTilePixelZ(tile));
    01705   MarkAllViewportsDirty(
    01706     pt.x - 31  * ZOOM_LVL_BASE,
    01707     pt.y - 122 * ZOOM_LVL_BASE,
    01708     pt.x - 31  * ZOOM_LVL_BASE + 67  * ZOOM_LVL_BASE,
    01709     pt.y - 122 * ZOOM_LVL_BASE + 154 * ZOOM_LVL_BASE
    01710   );
    01711 }
    01712
    01720 static void SetSelectionTilesDirty()
    01721 {
    01722   int x_size = _thd.size.x;
    01723   int y_size = _thd.size.y;
    01724
    01725   if (!_thd.diagonal) { // Selecting in a straight rectangle (or a single square)
    01726     int x_start = _thd.pos.x;
    01727     int y_start = _thd.pos.y;
    01728
    01729     if (_thd.outersize.x != 0) {
    01730       x_size  += _thd.outersize.x;
    01731       x_start += _thd.offs.x;
    01732       y_size  += _thd.outersize.y;
    01733       y_start += _thd.offs.y;
    01734     }
    01735
    01736     x_size -= TILE_SIZE;
    01737     y_size -= TILE_SIZE;
    01738
    01739     assert(x_size >= 0);
    01740     assert(y_size >= 0);
    01741
    01742     int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
    01743     int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
    01744
    01745     x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
    01746     y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
    01747
    01748     /* make sure everything is multiple of TILE_SIZE */
    01749     assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
    01750
    01751     /* How it works:
    01752      * Suppose we have to mark dirty rectangle of 3x4 tiles:
    01753      *   x
    01754      *  xxx
    01755      * xxxxx
    01756      *  xxxxx
    01757      *   xxx
    01758      *    x
    01759      * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
    01760      * 1)  x     2)  x
    01761      *    xxx       Oxx
    01762      *   Oxxxx     xOxxx
    01763      *    xxxxx     Oxxxx
    01764      *     xxx       xxx
    01765      *      x         x
    01766      * And so forth...
    01767      */
    01768
    01769     int top_x = x_end; // coordinates of top dirty tile
    01770     int top_y = y_start;
    01771     int bot_x = top_x; // coordinates of bottom dirty tile
    01772     int bot_y = top_y;
    01773
    01774     do {
    01775       /* topmost dirty point */
    01776       TileIndex top_tile = TileVirtXY(top_x, top_y);
    01777       Point top = RemapCoords(top_x, top_y, GetTileMaxPixelZ(top_tile));
    01778
    01779       /* bottommost point */
    01780       TileIndex bottom_tile = TileVirtXY(bot_x, bot_y);
    01781       Point bot = RemapCoords(bot_x + TILE_SIZE, bot_y + TILE_SIZE, GetTilePixelZ(bottom_tile)); // bottommost point
    01782
    01783       /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
    01784        * tile height/slope affects only the 'y' on-screen coordinate! */
    01785
    01786       int l = top.x - (TILE_PIXELS - 2) * ZOOM_LVL_BASE; // 'x' coordinate of left side of dirty rectangle
    01787       int t = top.y;                     // 'y' coordinate of top side -//-
    01788       int r = top.x + (TILE_PIXELS - 2) * ZOOM_LVL_BASE; // right side of dirty rectangle
    01789       int b = bot.y;                     // bottom -//-
    01790
    01791       static const int OVERLAY_WIDTH = 4 * ZOOM_LVL_BASE; // part of selection sprites is drawn outside the selected area
    01792
    01793       /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
    01794       MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT * ZOOM_LVL_BASE, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH * ZOOM_LVL_BASE);
    01795
    01796       /* haven't we reached the topmost tile yet? */
    01797       if (top_x != x_start) {
    01798         top_x -= TILE_SIZE;
    01799       } else {
    01800         top_y += TILE_SIZE;
    01801       }
    01802
    01803       /* the way the bottom tile changes is different when we reach the bottommost tile */
    01804       if (bot_y != y_end) {
    01805         bot_y += TILE_SIZE;
    01806       } else {
    01807         bot_x -= TILE_SIZE;
    01808       }
    01809     } while (bot_x >= top_x);
    01810   } else { // Selecting in a 45 degrees rotated (diagonal) rectangle.
    01811     /* a_size, b_size describe a rectangle with rotated coordinates */
    01812     int a_size = x_size + y_size, b_size = x_size - y_size;
    01813
    01814     int interval_a = a_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
    01815     int interval_b = b_size < 0 ? -(int)TILE_SIZE : (int)TILE_SIZE;
    01816
    01817     for (int a = -interval_a; a != a_size + interval_a; a += interval_a) {
    01818       for (int b = -interval_b; b != b_size + interval_b; b += interval_b) {
    01819         uint x = (_thd.pos.x + (a + b) / 2) / TILE_SIZE;
    01820         uint y = (_thd.pos.y + (a - b) / 2) / TILE_SIZE;
    01821
    01822         if (x < MapMaxX() && y < MapMaxY()) {
    01823           MarkTileDirtyByTile(TileXY(x, y));
    01824         }
    01825       }
    01826     }
    01827   }
    01828 }
    01829
    01830
    01831 void SetSelectionRed(bool b)
    01832 {
    01833   _thd.make_square_red = b;
    01834   SetSelectionTilesDirty();
    01835 }
    01836
    01845 static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y, const ViewportSign *sign)
    01846 {
    01847   bool small = (vp->zoom >= ZOOM_LVL_OUT_16X);
    01848   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
    01849   int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
    01850
    01851   x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
    01852   y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
    01853
    01854   return y >= sign->top && y < sign->top + sign_height &&
    01855       x >= sign->center - sign_half_width && x < sign->center + sign_half_width;
    01856 }
    01857
    01858 static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
    01859 {
    01860   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
    01861
    01862   const Town *t;
    01863   FOR_ALL_TOWNS(t) {
    01864     if (CheckClickOnViewportSign(vp, x, y, &t->cache.sign)) {
    01865       ShowTownViewWindow(t->index);
    01866       return true;
    01867     }
    01868   }
    01869
    01870   return false;
    01871 }
    01872
    01873 static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
    01874 {
    01875   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || IsInvisibilitySet(TO_SIGNS)) return false;
    01876
    01877   const BaseStation *st;
    01878   FOR_ALL_BASE_STATIONS(st) {
    01879     /* Check whether the base station is a station or a waypoint */
    01880     bool is_station = Station::IsExpected(st);
    01881
    01882     /* Don't check if the display options are disabled */
    01883     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
    01884
    01885     /* Don't check if competitor signs are not shown and the sign isn't owned by the local company */
    01886     if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != st->owner && st->owner != OWNER_NONE) continue;
    01887
    01888     if (CheckClickOnViewportSign(vp, x, y, &st->sign)) {
    01889       if (is_station) {
    01890         ShowStationViewWindow(st->index);
    01891       } else {
    01892         ShowWaypointWindow(Waypoint::From(st));
    01893       }
    01894       return true;
    01895     }
    01896   }
    01897
    01898   return false;
    01899 }
    01900
    01901
    01902 static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
    01903 {
    01904   /* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
    01905   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _local_company == COMPANY_SPECTATOR) return false;
    01906
    01907   const Sign *si;
    01908   FOR_ALL_SIGNS(si) {
    01909     /* If competitor signs are hidden, don't check signs that aren't owned by local company */
    01910     if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS) && _local_company != si->owner && si->owner != OWNER_DEITY) continue;
    01911     if (si->owner == OWNER_DEITY && _game_mode != GM_EDITOR) continue;
    01912
    01913     if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
    01914       HandleClickOnSign(si);
    01915       return true;
    01916     }
    01917   }
    01918
    01919   return false;
    01920 }
    01921
    01922
    01923 static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
    01924 {
    01925   Point pt = TranslateXYToTileCoord(vp, x, y);
    01926
    01927   if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
    01928   return true;
    01929 }
    01930
    01931 static void PlaceObject()
    01932 {
    01933   Point pt;
    01934   Window *w;
    01935
    01936   pt = GetTileBelowCursor();
    01937   if (pt.x == -1) return;
    01938
    01939   if ((_thd.place_mode & HT_DRAG_MASK) == HT_POINT) {
    01940     pt.x += TILE_SIZE / 2;
    01941     pt.y += TILE_SIZE / 2;
    01942   }
    01943
    01944   _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
    01945   _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
    01946
    01947   w = _thd.GetCallbackWnd();
    01948   if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
    01949 }
    01950
    01951
    01952 bool HandleViewportClicked(const ViewPort *vp, int x, int y)
    01953 {
    01954   const Vehicle *v = CheckClickOnVehicle(vp, x, y);
    01955
    01956   if (_thd.place_mode & HT_VEHICLE) {
    01957     if (v != NULL && VehicleClicked(v)) return true;
    01958   }
    01959
    01960   /* Vehicle placement mode already handled above. */
    01961   if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
    01962     PlaceObject();
    01963     return true;
    01964   }
    01965
    01966   if (CheckClickOnTown(vp, x, y)) return true;
    01967   if (CheckClickOnStation(vp, x, y)) return true;
    01968   if (CheckClickOnSign(vp, x, y)) return true;
    01969   bool result = CheckClickOnLandscape(vp, x, y);
    01970
    01971   if (v != NULL) {
    01972     DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
    01973     if (IsCompanyBuildableVehicleType(v)) {
    01974       v = v->First();
    01975       if (_ctrl_pressed && v->owner == _local_company) {
    01976         StartStopVehicle(v, true);
    01977       } else {
    01978         ShowVehicleViewWindow(v);
    01979       }
    01980     }
    01981     return true;
    01982   }
    01983   return result;
    01984 }
    01985
    01986 void RebuildViewportOverlay(Window *w)
    01987 {
    01988   if (w->viewport->overlay != NULL &&
    01989       w->viewport->overlay->GetCompanyMask() != 0 &&
    01990       w->viewport->overlay->GetCargoMask() != 0) {
    01991     w->viewport->overlay->RebuildCache();
    01992     w->SetDirty();
    01993   }
    01994 }
    01995
    02005 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
    02006 {
    02007   /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
    02008   if (z == -1) z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
    02009
    02010   Point pt = MapXYZToViewport(w->viewport, x, y, z);
    02011   w->viewport->follow_vehicle = INVALID_VEHICLE;
    02012
    02013   if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y) return false;
    02014
    02015   if (instant) {
    02016     w->viewport->scrollpos_x = pt.x;
    02017     w->viewport->scrollpos_y = pt.y;
    02018     RebuildViewportOverlay(w);
    02019   }
    02020
    02021   w->viewport->dest_scrollpos_x = pt.x;
    02022   w->viewport->dest_scrollpos_y = pt.y;
    02023   return true;
    02024 }
    02025
    02033 bool ScrollWindowToTile(TileIndex tile, Window *w, bool instant)
    02034 {
    02035   return ScrollWindowTo(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, -1, w, instant);
    02036 }
    02037
    02044 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
    02045 {
    02046   return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
    02047 }
    02048
    02053 void SetRedErrorSquare(TileIndex tile)
    02054 {
    02055   TileIndex old;
    02056
    02057   old = _thd.redsq;
    02058   _thd.redsq = tile;
    02059
    02060   if (tile != old) {
    02061     if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
    02062     if (old  != INVALID_TILE) MarkTileDirtyByTile(old);
    02063   }
    02064 }
    02065
    02071 void SetTileSelectSize(int w, int h)
    02072 {
    02073   _thd.new_size.x = w * TILE_SIZE;
    02074   _thd.new_size.y = h * TILE_SIZE;
    02075   _thd.new_outersize.x = 0;
    02076   _thd.new_outersize.y = 0;
    02077 }
    02078
    02079 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
    02080 {
    02081   _thd.offs.x = ox * TILE_SIZE;
    02082   _thd.offs.y = oy * TILE_SIZE;
    02083   _thd.new_outersize.x = sx * TILE_SIZE;
    02084   _thd.new_outersize.y = sy * TILE_SIZE;
    02085 }
    02086
    02088 static HighLightStyle GetAutorailHT(int x, int y)
    02089 {
    02090   return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
    02091 }
    02092
    02096 void TileHighlightData::Reset()
    02097 {
    02098   this->pos.x = 0;
    02099   this->pos.y = 0;
    02100   this->new_pos.x = 0;
    02101   this->new_pos.y = 0;
    02102 }
    02103
    02108 bool TileHighlightData::IsDraggingDiagonal()
    02109 {
    02110   return (this->place_mode & HT_DIAGONAL) != 0 && _ctrl_pressed && _left_button_down;
    02111 }
    02112
    02117 Window *TileHighlightData::GetCallbackWnd()
    02118 {
    02119   return FindWindowById(this->window_class, this->window_number);
    02120 }
    02121
    02122
    02123
    02131 void UpdateTileSelection()
    02132 {
    02133   int x1;
    02134   int y1;
    02135
    02136   HighLightStyle new_drawstyle = HT_NONE;
    02137   bool new_diagonal = false;
    02138
    02139   if ((_thd.place_mode & HT_DRAG_MASK) == HT_SPECIAL) {
    02140     x1 = _thd.selend.x;
    02141     y1 = _thd.selend.y;
    02142     if (x1 != -1) {
    02143       int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
    02144       int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
    02145       x1 &= ~TILE_UNIT_MASK;
    02146       y1 &= ~TILE_UNIT_MASK;
    02147
    02148       if (_thd.IsDraggingDiagonal()) {
    02149         new_diagonal = true;
    02150       } else {
    02151         if (x1 >= x2) Swap(x1, x2);
    02152         if (y1 >= y2) Swap(y1, y2);
    02153       }
    02154       _thd.new_pos.x = x1;
    02155       _thd.new_pos.y = y1;
    02156       _thd.new_size.x = x2 - x1;
    02157       _thd.new_size.y = y2 - y1;
    02158       if (!new_diagonal) {
    02159         _thd.new_size.x += TILE_SIZE;
    02160         _thd.new_size.y += TILE_SIZE;
    02161       }
    02162       new_drawstyle = _thd.next_drawstyle;
    02163     }
    02164   } else if ((_thd.place_mode & HT_DRAG_MASK) != HT_NONE) {
    02165     Point pt = GetTileBelowCursor();
    02166     x1 = pt.x;
    02167     y1 = pt.y;
    02168     if (x1 != -1) {
    02169       switch (_thd.place_mode & HT_DRAG_MASK) {
    02170         case HT_RECT:
    02171           new_drawstyle = HT_RECT;
    02172           break;
    02173         case HT_POINT:
    02174           new_drawstyle = HT_POINT;
    02175           x1 += TILE_SIZE / 2;
    02176           y1 += TILE_SIZE / 2;
    02177           break;
    02178         case HT_RAIL:
    02179           /* Draw one highlighted tile in any direction */
    02180           new_drawstyle = GetAutorailHT(pt.x, pt.y);
    02181           break;
    02182         case HT_LINE:
    02183           switch (_thd.place_mode & HT_DIR_MASK) {
    02184             case HT_DIR_X: new_drawstyle = HT_LINE | HT_DIR_X; break;
    02185             case HT_DIR_Y: new_drawstyle = HT_LINE | HT_DIR_Y; break;
    02186
    02187             case HT_DIR_HU:
    02188             case HT_DIR_HL:
    02189               new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
    02190               break;
    02191
    02192             case HT_DIR_VL:
    02193             case HT_DIR_VR:
    02194               new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02195               break;
    02196
    02197             default: NOT_REACHED();
    02198           }
    02199           _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
    02200           _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
    02201           break;
    02202         default:
    02203           NOT_REACHED();
    02204           break;
    02205       }
    02206       _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
    02207       _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
    02208     }
    02209   }
    02210
    02211   /* redraw selection */
    02212   if (_thd.drawstyle != new_drawstyle ||
    02213       _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
    02214       _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
    02215       _thd.outersize.x != _thd.new_outersize.x ||
    02216       _thd.outersize.y != _thd.new_outersize.y ||
    02217       _thd.diagonal    != new_diagonal) {
    02218     /* Clear the old tile selection? */
    02219     if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
    02220
    02221     _thd.drawstyle = new_drawstyle;
    02222     _thd.pos = _thd.new_pos;
    02223     _thd.size = _thd.new_size;
    02224     _thd.outersize = _thd.new_outersize;
    02225     _thd.diagonal = new_diagonal;
    02226     _thd.dirty = 0xff;
    02227
    02228     /* Draw the new tile selection? */
    02229     if ((new_drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
    02230   }
    02231 }
    02232
    02240 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_cond = TCC_LEFT_CLICK)
    02241 {
    02242   if (!_settings_client.gui.measure_tooltip) return;
    02243   GuiShowTooltips(_thd.GetCallbackWnd(), str, paramcount, params, close_cond);
    02244 }
    02245
    02247 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
    02248 {
    02249   _thd.select_method = method;
    02250   _thd.select_proc   = process;
    02251   _thd.selend.x = TileX(tile) * TILE_SIZE;
    02252   _thd.selstart.x = TileX(tile) * TILE_SIZE;
    02253   _thd.selend.y = TileY(tile) * TILE_SIZE;
    02254   _thd.selstart.y = TileY(tile) * TILE_SIZE;
    02255
    02256   /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
    02257    * In effect, placement starts from the centre of a tile
    02258    */
    02259   if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
    02260     _thd.selend.x += TILE_SIZE / 2;
    02261     _thd.selend.y += TILE_SIZE / 2;
    02262     _thd.selstart.x += TILE_SIZE / 2;
    02263     _thd.selstart.y += TILE_SIZE / 2;
    02264   }
    02265
    02266   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
    02267   if ((_thd.place_mode & HT_DRAG_MASK) == HT_RECT) {
    02268     _thd.place_mode = HT_SPECIAL | others;
    02269     _thd.next_drawstyle = HT_RECT | others;
    02270   } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
    02271     _thd.place_mode = HT_SPECIAL | others;
    02272     _thd.next_drawstyle = _thd.drawstyle | others;
    02273   } else {
    02274     _thd.place_mode = HT_SPECIAL | others;
    02275     _thd.next_drawstyle = HT_POINT | others;
    02276   }
    02277   _special_mouse_mode = WSM_SIZING;
    02278 }
    02279
    02280 void VpSetPlaceSizingLimit(int limit)
    02281 {
    02282   _thd.sizelimit = limit;
    02283 }
    02284
    02290 void VpSetPresizeRange(TileIndex from, TileIndex to)
    02291 {
    02292   uint64 distance = DistanceManhattan(from, to) + 1;
    02293
    02294   _thd.selend.x = TileX(to) * TILE_SIZE;
    02295   _thd.selend.y = TileY(to) * TILE_SIZE;
    02296   _thd.selstart.x = TileX(from) * TILE_SIZE;
    02297   _thd.selstart.y = TileY(from) * TILE_SIZE;
    02298   _thd.next_drawstyle = HT_RECT;
    02299
    02300   /* show measurement only if there is any length to speak of */
    02301   if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance, TCC_HOVER);
    02302 }
    02303
    02304 static void VpStartPreSizing()
    02305 {
    02306   _thd.selend.x = -1;
    02307   _special_mouse_mode = WSM_PRESIZE;
    02308 }
    02309
    02314 static HighLightStyle Check2x1AutoRail(int mode)
    02315 {
    02316   int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
    02317   int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
    02318   int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
    02319   int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
    02320
    02321   switch (mode) {
    02322     default: NOT_REACHED();
    02323     case 0: // end piece is lower right
    02324       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
    02325       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
    02326       return HT_DIR_Y;
    02327
    02328     case 1:
    02329       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
    02330       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
    02331       return HT_DIR_Y;
    02332
    02333     case 2:
    02334       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
    02335       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
    02336       return HT_DIR_X;
    02337
    02338     case 3:
    02339       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
    02340       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
    02341       return HT_DIR_X;
    02342   }
    02343 }
    02344
    02358 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
    02359 {
    02360   uint start_x = TileX(start_tile);
    02361   uint start_y = TileY(start_tile);
    02362   uint end_x = TileX(end_tile);
    02363   uint end_y = TileY(end_tile);
    02364
    02365   switch (style & HT_DRAG_MASK) {
    02366     case HT_RAIL:
    02367     case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
    02368
    02369     case HT_RECT:
    02370     case HT_POINT: return (end_x != start_x && end_y < start_y);
    02371     default: NOT_REACHED();
    02372   }
    02373
    02374   return false;
    02375 }
    02376
    02392 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
    02393 {
    02394   bool swap = SwapDirection(style, start_tile, end_tile);
    02395   uint h0, h1; // Start height and end height.
    02396
    02397   if (start_tile == end_tile) return 0;
    02398   if (swap) Swap(start_tile, end_tile);
    02399
    02400   switch (style & HT_DRAG_MASK) {
    02401     case HT_RECT: {
    02402       static const TileIndexDiffC heightdiff_area_by_dir[] = {
    02403         /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
    02404         /* End   */ {0, 1}, /* Dragging east */ {1, 1}  // Dragging south
    02405       };
    02406
    02407       /* In the case of an area we can determine whether we were dragging south or
    02408        * east by checking the X-coordinates of the tiles */
    02409       byte style_t = (byte)(TileX(end_tile) > TileX(start_tile));
    02410       start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
    02411       end_tile   = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
    02412       /* FALL THROUGH */
    02413     }
    02414
    02415     case HT_POINT:
    02416       h0 = TileHeight(start_tile);
    02417       h1 = TileHeight(end_tile);
    02418       break;
    02419     default: { // All other types, this is mostly only line/autorail
    02420       static const HighLightStyle flip_style_direction[] = {
    02421         HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
    02422       };
    02423       static const TileIndexDiffC heightdiff_line_by_dir[] = {
    02424         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X  */ {0, 1}, {1, 1}, // HT_DIR_Y
    02425         /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
    02426         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
    02427
    02428         /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X  */ {1, 0}, {0, 0}, // HT_DIR_Y
    02429         /* End   */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
    02430         /* End   */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
    02431       };
    02432
    02433       distance %= 2; // we're only interested if the distance is even or uneven
    02434       style &= HT_DIR_MASK;
    02435
    02436       /* To handle autorail, we do some magic to be able to use a lookup table.
    02437        * Firstly if we drag the other way around, we switch start&end, and if needed
    02438        * also flip the drag-position. Eg if it was on the left, and the distance is even
    02439        * that means the end, which is now the start is on the right */
    02440       if (swap && distance == 0) style = flip_style_direction[style];
    02441
    02442       /* Use lookup table for start-tile based on HighLightStyle direction */
    02443       byte style_t = style * 2;
    02444       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
    02445       h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
    02446       uint ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
    02447       h0 = max(h0, ht);
    02448
    02449       /* Use lookup table for end-tile based on HighLightStyle direction
    02450        * flip around side (lower/upper, left/right) based on distance */
    02451       if (distance == 0) style_t = flip_style_direction[style] * 2;
    02452       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
    02453       h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
    02454       ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
    02455       h1 = max(h1, ht);
    02456       break;
    02457     }
    02458   }
    02459
    02460   if (swap) Swap(h0, h1);
    02461   return (int)(h1 - h0) * TILE_HEIGHT_STEP;
    02462 }
    02463
    02464 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
    02465
    02472 static void CheckUnderflow(int &test, int &other, int mult)
    02473 {
    02474   if (test >= 0) return;
    02475
    02476   other += mult * test;
    02477   test = 0;
    02478 }
    02479
    02487 static void CheckOverflow(int &test, int &other, int max, int mult)
    02488 {
    02489   if (test <= max) return;
    02490
    02491   other += mult * (test - max);
    02492   test = max;
    02493 }
    02494
    02496 static void CalcRaildirsDrawstyle(int x, int y, int method)
    02497 {
    02498   HighLightStyle b;
    02499
    02500   int dx = _thd.selstart.x - (_thd.selend.x & ~TILE_UNIT_MASK);
    02501   int dy = _thd.selstart.y - (_thd.selend.y & ~TILE_UNIT_MASK);
    02502   uint w = abs(dx) + TILE_SIZE;
    02503   uint h = abs(dy) + TILE_SIZE;
    02504
    02505   if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
    02506     /* We 'force' a selection direction; first four rail buttons. */
    02507     method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
    02508     int raw_dx = _thd.selstart.x - _thd.selend.x;
    02509     int raw_dy = _thd.selstart.y - _thd.selend.y;
    02510     switch (method) {
    02511       case VPM_FIX_X:
    02512         b = HT_LINE | HT_DIR_Y;
    02513         x = _thd.selstart.x;
    02514         break;
    02515
    02516       case VPM_FIX_Y:
    02517         b = HT_LINE | HT_DIR_X;
    02518         y = _thd.selstart.y;
    02519         break;
    02520
    02521       case VPM_FIX_HORIZONTAL:
    02522         if (dx == -dy) {
    02523           /* We are on a straight horizontal line. Determine the 'rail'
    02524            * to build based the sub tile location. */
    02525           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02526         } else {
    02527           /* We are not on a straight line. Determine the rail to build
    02528            * based on whether we are above or below it. */
    02529           b = dx + dy >= (int)TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
    02530
    02531           /* Calculate where a horizontal line through the start point and
    02532            * a vertical line from the selected end point intersect and
    02533            * use that point as the end point. */
    02534           int offset = (raw_dx - raw_dy) / 2;
    02535           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
    02536           y = _thd.selstart.y + (offset & ~TILE_UNIT_MASK);
    02537
    02538           /* 'Build' the last half rail tile if needed */
    02539           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
    02540             if (dx + dy >= (int)TILE_SIZE) {
    02541               x += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02542             } else {
    02543               y += (dx + dy < 0) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02544             }
    02545           }
    02546
    02547           /* Make sure we do not overflow the map! */
    02548           CheckUnderflow(x, y, 1);
    02549           CheckUnderflow(y, x, 1);
    02550           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
    02551           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
    02552           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
    02553         }
    02554         break;
    02555
    02556       case VPM_FIX_VERTICAL:
    02557         if (dx == dy) {
    02558           /* We are on a straight vertical line. Determine the 'rail'
    02559            * to build based the sub tile location. */
    02560           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02561         } else {
    02562           /* We are not on a straight line. Determine the rail to build
    02563            * based on whether we are left or right from it. */
    02564           b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02565
    02566           /* Calculate where a vertical line through the start point and
    02567            * a horizontal line from the selected end point intersect and
    02568            * use that point as the end point. */
    02569           int offset = (raw_dx + raw_dy + (int)TILE_SIZE) / 2;
    02570           x = _thd.selstart.x - (offset & ~TILE_UNIT_MASK);
    02571           y = _thd.selstart.y - (offset & ~TILE_UNIT_MASK);
    02572
    02573           /* 'Build' the last half rail tile if needed */
    02574           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
    02575             if (dx - dy < 0) {
    02576               y += (dx > dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02577             } else {
    02578               x += (dx < dy) ? (int)TILE_SIZE : -(int)TILE_SIZE;
    02579             }
    02580           }
    02581
    02582           /* Make sure we do not overflow the map! */
    02583           CheckUnderflow(x, y, -1);
    02584           CheckUnderflow(y, x, -1);
    02585           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
    02586           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
    02587           assert(x >= 0 && y >= 0 && x <= (int)(MapMaxX() * TILE_SIZE) && y <= (int)(MapMaxY() * TILE_SIZE));
    02588         }
    02589         break;
    02590
    02591       default:
    02592         NOT_REACHED();
    02593     }
    02594   } else if (TileVirtXY(_thd.selstart.x, _thd.selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
    02595     if (method & VPM_RAILDIRS) {
    02596       b = GetAutorailHT(x, y);
    02597     } else { // rect for autosignals on one tile
    02598       b = HT_RECT;
    02599     }
    02600   } else if (h == TILE_SIZE) { // Is this in X direction?
    02601     if (dx == (int)TILE_SIZE) { // 2x1 special handling
    02602       b = (Check2x1AutoRail(3)) | HT_LINE;
    02603     } else if (dx == -(int)TILE_SIZE) {
    02604       b = (Check2x1AutoRail(2)) | HT_LINE;
    02605     } else {
    02606       b = HT_LINE | HT_DIR_X;
    02607     }
    02608     y = _thd.selstart.y;
    02609   } else if (w == TILE_SIZE) { // Or Y direction?
    02610     if (dy == (int)TILE_SIZE) { // 2x1 special handling
    02611       b = (Check2x1AutoRail(1)) | HT_LINE;
    02612     } else if (dy == -(int)TILE_SIZE) { // 2x1 other direction
    02613       b = (Check2x1AutoRail(0)) | HT_LINE;
    02614     } else {
    02615       b = HT_LINE | HT_DIR_Y;
    02616     }
    02617     x = _thd.selstart.x;
    02618   } else if (w > h * 2) { // still count as x dir?
    02619     b = HT_LINE | HT_DIR_X;
    02620     y = _thd.selstart.y;
    02621   } else if (h > w * 2) { // still count as y dir?
    02622     b = HT_LINE | HT_DIR_Y;
    02623     x = _thd.selstart.x;
    02624   } else { // complicated direction
    02625     int d = w - h;
    02626     _thd.selend.x = _thd.selend.x & ~TILE_UNIT_MASK;
    02627     _thd.selend.y = _thd.selend.y & ~TILE_UNIT_MASK;
    02628
    02629     /* four cases. */
    02630     if (x > _thd.selstart.x) {
    02631       if (y > _thd.selstart.y) {
    02632         /* south */
    02633         if (d == 0) {
    02634           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02635         } else if (d >= 0) {
    02636           x = _thd.selstart.x + h;
    02637           b = HT_LINE | HT_DIR_VL;
    02638         } else {
    02639           y = _thd.selstart.y + w;
    02640           b = HT_LINE | HT_DIR_VR;
    02641         }
    02642       } else {
    02643         /* west */
    02644         if (d == 0) {
    02645           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02646         } else if (d >= 0) {
    02647           x = _thd.selstart.x + h;
    02648           b = HT_LINE | HT_DIR_HL;
    02649         } else {
    02650           y = _thd.selstart.y - w;
    02651           b = HT_LINE | HT_DIR_HU;
    02652         }
    02653       }
    02654     } else {
    02655       if (y > _thd.selstart.y) {
    02656         /* east */
    02657         if (d == 0) {
    02658           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
    02659         } else if (d >= 0) {
    02660           x = _thd.selstart.x - h;
    02661           b = HT_LINE | HT_DIR_HU;
    02662         } else {
    02663           y = _thd.selstart.y + w;
    02664           b = HT_LINE | HT_DIR_HL;
    02665         }
    02666       } else {
    02667         /* north */
    02668         if (d == 0) {
    02669           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
    02670         } else if (d >= 0) {
    02671           x = _thd.selstart.x - h;
    02672           b = HT_LINE | HT_DIR_VR;
    02673         } else {
    02674           y = _thd.selstart.y - w;
    02675           b = HT_LINE | HT_DIR_VL;
    02676         }
    02677       }
    02678     }
    02679   }
    02680
    02681   if (_settings_client.gui.measure_tooltip) {
    02682     TileIndex t0 = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
    02683     TileIndex t1 = TileVirtXY(x, y);
    02684     uint distance = DistanceManhattan(t0, t1) + 1;
    02685     byte index = 0;
    02686     uint64 params[2];
    02687
    02688     if (distance != 1) {
    02689       int heightdiff = CalcHeightdiff(b, distance, t0, t1);
    02690       /* If we are showing a tooltip for horizontal or vertical drags,
    02691        * 2 tiles have a length of 1. To bias towards the ceiling we add
    02692        * one before division. It feels more natural to count 3 lengths as 2 */
    02693       if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
    02694         distance = CeilDiv(distance, 2);
    02695       }
    02696
    02697       params[index++] = distance;
    02698       if (heightdiff != 0) params[index++] = heightdiff;
    02699     }
    02700
    02701     ShowMeasurementTooltips(measure_strings_length[index], index, params);
    02702   }
    02703
    02704   _thd.selend.x = x;
    02705   _thd.selend.y = y;
    02706   _thd.next_drawstyle = b;
    02707 }
    02708
    02716 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
    02717 {
    02718   int sx, sy;
    02719   HighLightStyle style;
    02720
    02721   if (x == -1) {
    02722     _thd.selend.x = -1;
    02723     return;
    02724   }
    02725
    02726   /* Special handling of drag in any (8-way) direction */
    02727   if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
    02728     _thd.selend.x = x;
    02729     _thd.selend.y = y;
    02730     CalcRaildirsDrawstyle(x, y, method);
    02731     return;
    02732   }
    02733
    02734   /* Needed so level-land is placed correctly */
    02735   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_POINT) {
    02736     x += TILE_SIZE / 2;
    02737     y += TILE_SIZE / 2;
    02738   }
    02739
    02740   sx = _thd.selstart.x;
    02741   sy = _thd.selstart.y;
    02742
    02743   int limit = 0;
    02744
    02745   switch (method) {
    02746     case VPM_X_OR_Y: // drag in X or Y direction
    02747       if (abs(sy - y) < abs(sx - x)) {
    02748         y = sy;
    02749         style = HT_DIR_X;
    02750       } else {
    02751         x = sx;
    02752         style = HT_DIR_Y;
    02753       }
    02754       goto calc_heightdiff_single_direction;
    02755
    02756     case VPM_X_LIMITED: // Drag in X direction (limited size).
    02757       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02758       /* FALL THROUGH */
    02759
    02760     case VPM_FIX_X: // drag in Y direction
    02761       x = sx;
    02762       style = HT_DIR_Y;
    02763       goto calc_heightdiff_single_direction;
    02764
    02765     case VPM_Y_LIMITED: // Drag in Y direction (limited size).
    02766       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02767       /* FALL THROUGH */
    02768
    02769     case VPM_FIX_Y: // drag in X direction
    02770       y = sy;
    02771       style = HT_DIR_X;
    02772
    02773 calc_heightdiff_single_direction:;
    02774       if (limit > 0) {
    02775         x = sx + Clamp(x - sx, -limit, limit);
    02776         y = sy + Clamp(y - sy, -limit, limit);
    02777       }
    02778       if (_settings_client.gui.measure_tooltip) {
    02779         TileIndex t0 = TileVirtXY(sx, sy);
    02780         TileIndex t1 = TileVirtXY(x, y);
    02781         uint distance = DistanceManhattan(t0, t1) + 1;
    02782         byte index = 0;
    02783         uint64 params[2];
    02784
    02785         if (distance != 1) {
    02786           /* With current code passing a HT_LINE style to calculate the height
    02787            * difference is enough. However if/when a point-tool is created
    02788            * with this method, function should be called with new_style (below)
    02789            * instead of HT_LINE | style case HT_POINT is handled specially
    02790            * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
    02791           int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
    02792
    02793           params[index++] = distance;
    02794           if (heightdiff != 0) params[index++] = heightdiff;
    02795         }
    02796
    02797         ShowMeasurementTooltips(measure_strings_length[index], index, params);
    02798       }
    02799       break;
    02800
    02801     case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
    02802       limit = (_thd.sizelimit - 1) * TILE_SIZE;
    02803       x = sx + Clamp(x - sx, -limit, limit);
    02804       y = sy + Clamp(y - sy, -limit, limit);
    02805       /* FALL THROUGH */
    02806
    02807     case VPM_X_AND_Y: // drag an X by Y area
    02808       if (_settings_client.gui.measure_tooltip) {
    02809         static const StringID measure_strings_area[] = {
    02810           STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
    02811         };
    02812
    02813         TileIndex t0 = TileVirtXY(sx, sy);
    02814         TileIndex t1 = TileVirtXY(x, y);
    02815         uint dx = Delta(TileX(t0), TileX(t1)) + 1;
    02816         uint dy = Delta(TileY(t0), TileY(t1)) + 1;
    02817         byte index = 0;
    02818         uint64 params[3];
    02819
    02820         /* If dragging an area (eg dynamite tool) and it is actually a single
    02821          * row/column, change the type to 'line' to get proper calculation for height */
    02822         style = (HighLightStyle)_thd.next_drawstyle;
    02823         if (_thd.IsDraggingDiagonal()) {
    02824           /* Determine the "area" of the diagonal dragged selection.
    02825            * We assume the area is the number of tiles along the X
    02826            * edge and the number of tiles along the Y edge. However,
    02827            * multiplying these two numbers does not give the exact
    02828            * number of tiles; basically we are counting the black
    02829            * squares on a chess board and ignore the white ones to
    02830            * make the tile counts at the edges match up. There is no
    02831            * other way to make a proper count though.
    02832            *
    02833            * First convert to the rotated coordinate system. */
    02834           int dist_x = TileX(t0) - TileX(t1);
    02835           int dist_y = TileY(t0) - TileY(t1);
    02836           int a_max = dist_x + dist_y;
    02837           int b_max = dist_y - dist_x;
    02838
    02839           /* Now determine the size along the edge, but due to the
    02840            * chess board principle this counts double. */
    02841           a_max = abs(a_max + (a_max > 0 ? 2 : -2)) / 2;
    02842           b_max = abs(b_max + (b_max > 0 ? 2 : -2)) / 2;
    02843
    02844           /* We get a 1x1 on normal 2x1 rectangles, due to it being
    02845            * a seen as two sides. As the result for actual building
    02846            * will be the same as non-diagonal dragging revert to that
    02847            * behaviour to give it a more normally looking size. */
    02848           if (a_max != 1 || b_max != 1) {
    02849             dx = a_max;
    02850             dy = b_max;
    02851           }
    02852         } else if (style & HT_RECT) {
    02853           if (dx == 1) {
    02854             style = HT_LINE | HT_DIR_Y;
    02855           } else if (dy == 1) {
    02856             style = HT_LINE | HT_DIR_X;
    02857           }
    02858         }
    02859
    02860         if (dx != 1 || dy != 1) {
    02861           int heightdiff = CalcHeightdiff(style, 0, t0, t1);
    02862
    02863           params[index++] = dx - (style & HT_POINT ? 1 : 0);
    02864           params[index++] = dy - (style & HT_POINT ? 1 : 0);
    02865           if (heightdiff != 0) params[index++] = heightdiff;
    02866         }
    02867
    02868         ShowMeasurementTooltips(measure_strings_area[index], index, params);
    02869       }
    02870       break;
    02871
    02872     default: NOT_REACHED();
    02873   }
    02874
    02875   _thd.selend.x = x;
    02876   _thd.selend.y = y;
    02877 }
    02878
    02883 EventState VpHandlePlaceSizingDrag()
    02884 {
    02885   if (_special_mouse_mode != WSM_SIZING) return ES_NOT_HANDLED;
    02886
    02887   /* stop drag mode if the window has been closed */
    02888   Window *w = _thd.GetCallbackWnd();
    02889   if (w == NULL) {
    02890     ResetObjectToPlace();
    02891     return ES_HANDLED;
    02892   }
    02893
    02894   /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
    02895   if (_left_button_down) {
    02896     w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
    02897     return ES_HANDLED;
    02898   }
    02899
    02900   /* mouse button released..
    02901    * keep the selected tool, but reset it to the original mode. */
    02902   _special_mouse_mode = WSM_NONE;
    02903   HighLightStyle others = _thd.place_mode & ~(HT_DRAG_MASK | HT_DIR_MASK);
    02904   if ((_thd.next_drawstyle & HT_DRAG_MASK) == HT_RECT) {
    02905     _thd.place_mode = HT_RECT | others;
    02906   } else if (_thd.select_method & VPM_SIGNALDIRS) {
    02907     _thd.place_mode = HT_RECT | others;
    02908   } else if (_thd.select_method & VPM_RAILDIRS) {
    02909     _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : (HT_RAIL | others);
    02910   } else {
    02911     _thd.place_mode = HT_POINT | others;
    02912   }
    02913   SetTileSelectSize(1, 1);
    02914
    02915   w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
    02916
    02917   return ES_HANDLED;
    02918 }
    02919
    02920 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
    02921 {
    02922   SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
    02923 }
    02924
    02925 #include "table/animcursors.h"
    02926
    02927 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
    02928 {
    02929   if (_thd.window_class != WC_INVALID) {
    02930     /* Undo clicking on button and drag & drop */
    02931     Window *w = _thd.GetCallbackWnd();
    02932     /* Call the abort function, but set the window class to something
    02933      * that will never be used to avoid infinite loops. Setting it to
    02934      * the 'next' window class must not be done because recursion into
    02935      * this function might in some cases reset the newly set object to
    02936      * place or not properly reset the original selection. */
    02937     _thd.window_class = WC_INVALID;
    02938     if (w != NULL) w->OnPlaceObjectAbort();
    02939   }
    02940
    02941   /* Mark the old selection dirty, in case the selection shape or colour changes */
    02942   if ((_thd.drawstyle & HT_DRAG_MASK) != HT_NONE) SetSelectionTilesDirty();
    02943
    02944   SetTileSelectSize(1, 1);
    02945
    02946   _thd.make_square_red = false;
    02947
    02948   if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
    02949     mode = HT_NONE;
    02950     _special_mouse_mode = WSM_DRAGDROP;
    02951   } else {
    02952     _special_mouse_mode = WSM_NONE;
    02953   }
    02954
    02955   _thd.place_mode = mode;
    02956   _thd.window_class = window_class;
    02957   _thd.window_number = window_num;
    02958
    02959   if ((mode & HT_DRAG_MASK) == HT_SPECIAL) { // special tools, like tunnels or docks start with presizing mode
    02960     VpStartPreSizing();
    02961   }
    02962
    02963   if ((icon & ANIMCURSOR_FLAG) != 0) {
    02964     SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
    02965   } else {
    02966     SetMouseCursor(icon, pal);
    02967   }
    02968
    02969 }
    02970
    02971 void ResetObjectToPlace()
    02972 {
    02973   SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
    02974 }
    02975
    02976 Point GetViewportStationMiddle(const ViewPort *vp, const Station *st)
    02977 {
    02978   int x = TileX(st->xy) * TILE_SIZE;
    02979   int y = TileY(st->xy) * TILE_SIZE;
    02980   int z = GetSlopePixelZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
    02981
    02982   Point p = RemapCoords(x, y, z);
    02983   p.x = UnScaleByZoom(p.x - vp->virtual_left, vp->zoom) + vp->left;
    02984   p.y = UnScaleByZoom(p.y - vp->virtual_top, vp->zoom) + vp->top;
    02985   return p;
    02986 }
    02987
    02989 struct ViewportSSCSS {
    02990   VpSorterChecker fct_checker;
    02991   VpSpriteSorter fct_sorter;
    02992 };
    02993
    02995 static ViewportSSCSS _vp_sprite_sorters[] = {
    02996 #ifdef WITH_SSE
    02997   { &ViewportSortParentSpritesSSE41Checker, &ViewportSortParentSpritesSSE41 },
    02998 #endif
    02999   { &ViewportSortParentSpritesChecker, &ViewportSortParentSprites }
    03000 };
    03001
    03003 void InitializeSpriteSorter()
    03004 {
    03005   for (uint i = 0; i < lengthof(_vp_sprite_sorters); i++) {
    03006     if (_vp_sprite_sorters[i].fct_checker()) {
    03007       _vp_sprite_sorter = _vp_sprite_sorters[i].fct_sorter;
    03008       break;
    03009     }
    03010   }
    03011   assert(_vp_sprite_sorter != NULL);
    03012 }