viewport.cpp

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

Generated on Thu Jan 20 22:57:43 2011 for OpenTTD by  doxygen 1.6.1