viewport.cpp

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