viewport.cpp

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