viewport.cpp

Go to the documentation of this file.
00001 /* $Id: viewport.cpp 19856 2010-05-18 21:38:09Z 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 
00028 #include "stdafx.h"
00029 #include "landscape.h"
00030 #include "viewport_func.h"
00031 #include "station_base.h"
00032 #include "waypoint_base.h"
00033 #include "town.h"
00034 #include "signs_base.h"
00035 #include "signs_func.h"
00036 #include "variables.h"
00037 #include "vehicle_base.h"
00038 #include "vehicle_gui.h"
00039 #include "blitter/factory.hpp"
00040 #include "strings_func.h"
00041 #include "zoom_func.h"
00042 #include "vehicle_func.h"
00043 #include "company_func.h"
00044 #include "waypoint_func.h"
00045 #include "window_func.h"
00046 #include "tilehighlight_func.h"
00047 #include "window_gui.h"
00048 
00049 #include "table/sprites.h"
00050 #include "table/strings.h"
00051 
00052 PlaceProc *_place_proc;
00053 Point _tile_fract_coords;
00054 
00055 struct StringSpriteToDraw {
00056   StringID string;
00057   Colours colour;
00058   int32 x;
00059   int32 y;
00060   uint64 params[2];
00061   uint16 width;
00062 };
00063 
00064 struct TileSpriteToDraw {
00065   SpriteID image;
00066   PaletteID pal;
00067   const SubSprite *sub;           
00068   int32 x;                        
00069   int32 y;                        
00070 };
00071 
00072 struct ChildScreenSpriteToDraw {
00073   SpriteID image;
00074   PaletteID pal;
00075   const SubSprite *sub;           
00076   int32 x;
00077   int32 y;
00078   int next;                       
00079 };
00080 
00082 struct ParentSpriteToDraw {
00083   SpriteID image;                 
00084   PaletteID pal;                  
00085   const SubSprite *sub;           
00086 
00087   int32 x;                        
00088   int32 y;                        
00089 
00090   int32 left;                     
00091   int32 top;                      
00092 
00093   int32 xmin;                     
00094   int32 xmax;                     
00095   int32 ymin;                     
00096   int32 ymax;                     
00097   int zmin;                       
00098   int zmax;                       
00099 
00100   int first_child;                
00101   bool comparison_done;           
00102 };
00103 
00105 enum FoundationPart {
00106   FOUNDATION_PART_NONE     = 0xFF,  
00107   FOUNDATION_PART_NORMAL   = 0,     
00108   FOUNDATION_PART_HALFTILE = 1,     
00109   FOUNDATION_PART_END
00110 };
00111 
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 
00368 static Point TranslateXYToTileCoord(const ViewPort *vp, int x, int y)
00369 {
00370   Point pt;
00371   int a, b;
00372   uint z;
00373 
00374   if ( (uint)(x -= vp->left) >= (uint)vp->width ||
00375         (uint)(y -= vp->top) >= (uint)vp->height) {
00376         Point pt = {-1, -1};
00377         return pt;
00378   }
00379 
00380   x = (ScaleByZoom(x, vp->zoom) + vp->virtual_left) >> 2;
00381   y = (ScaleByZoom(y, vp->zoom) + vp->virtual_top) >> 1;
00382 
00383   a = y - x;
00384   b = y + x;
00385 
00386   /* we need to move variables in to the valid range, as the
00387    * GetTileZoomCenterWindow() function can call here with invalid x and/or y,
00388    * when the user tries to zoom out along the sides of the map */
00389   a = Clamp(a, -4 * TILE_SIZE, (int)(MapMaxX() * TILE_SIZE) - 1);
00390   b = Clamp(b, -4 * TILE_SIZE, (int)(MapMaxY() * TILE_SIZE) - 1);
00391 
00392   /* (a, b) is the X/Y-world coordinate that belongs to (x,y) if the landscape would be completely flat on height 0.
00393    * Now find the Z-world coordinate by fix point iteration.
00394    * This is a bit tricky because the tile height is non-continuous at foundations.
00395    * The clicked point should be approached from the back, otherwise there are regions that are not clickable.
00396    * (FOUNDATION_HALFTILE_LOWER on SLOPE_STEEP_S hides north halftile completely)
00397    * So give it a z-malus of 4 in the first iterations.
00398    */
00399   z = 0;
00400 
00401   int min_coord = _settings_game.construction.freeform_edges ? TILE_SIZE : 0;
00402 
00403   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;
00404   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;
00405   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;
00406 
00407   pt.x = Clamp(a + (int)z, min_coord, MapMaxX() * TILE_SIZE - 1);
00408   pt.y = Clamp(b + (int)z, min_coord, MapMaxY() * TILE_SIZE - 1);
00409 
00410   return pt;
00411 }
00412 
00413 /* When used for zooming, check area below current coordinates (x,y)
00414  * and return the tile of the zoomed out/in position (zoom_x, zoom_y)
00415  * when you just want the tile, make x = zoom_x and y = zoom_y */
00416 static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
00417 {
00418   Window *w;
00419   ViewPort *vp;
00420   Point pt;
00421 
00422   if ( (w = FindWindowFromPt(x, y)) != NULL &&
00423        (vp = IsPtInWindowViewport(w, x, y)) != NULL)
00424         return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
00425 
00426   pt.y = pt.x = -1;
00427   return pt;
00428 }
00429 
00430 Point GetTileBelowCursor()
00431 {
00432   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, _cursor.pos.x, _cursor.pos.y);
00433 }
00434 
00435 
00436 Point GetTileZoomCenterWindow(bool in, Window * w)
00437 {
00438   int x, y;
00439   ViewPort *vp = w->viewport;
00440 
00441   if (in) {
00442     x = ((_cursor.pos.x - vp->left) >> 1) + (vp->width >> 2);
00443     y = ((_cursor.pos.y - vp->top) >> 1) + (vp->height >> 2);
00444   } else {
00445     x = vp->width - (_cursor.pos.x - vp->left);
00446     y = vp->height - (_cursor.pos.y - vp->top);
00447   }
00448   /* Get the tile below the cursor and center on the zoomed-out center */
00449   return GetTileFromScreenXY(_cursor.pos.x, _cursor.pos.y, x + vp->left, y + vp->top);
00450 }
00451 
00458 void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte widget_zoom_out)
00459 {
00460   w->SetWidgetDisabledState(widget_zoom_in, vp->zoom == ZOOM_LVL_MIN);
00461   w->SetWidgetDirty(widget_zoom_in);
00462 
00463   w->SetWidgetDisabledState(widget_zoom_out, vp->zoom == ZOOM_LVL_MAX);
00464   w->SetWidgetDirty(widget_zoom_out);
00465 }
00466 
00479 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)
00480 {
00481   assert((image & SPRITE_MASK) < MAX_SPRITES);
00482 
00483   TileSpriteToDraw *ts = _vd.tile_sprites_to_draw.Append();
00484   ts->image = image;
00485   ts->pal = pal;
00486   ts->sub = sub;
00487   Point pt = RemapCoords(x, y, z);
00488   ts->x = pt.x + extra_offs_x;
00489   ts->y = pt.y + extra_offs_y;
00490 }
00491 
00504 static void AddChildSpriteToFoundation(SpriteID image, PaletteID pal, const SubSprite *sub, FoundationPart foundation_part, int extra_offs_x, int extra_offs_y)
00505 {
00506   assert(IsInsideMM(foundation_part, 0, FOUNDATION_PART_END));
00507   assert(_vd.foundation[foundation_part] != -1);
00508   Point offs = _vd.foundation_offset[foundation_part];
00509 
00510   /* Change the active ChildSprite list to the one of the foundation */
00511   int *old_child = _vd.last_child;
00512   _vd.last_child = _vd.last_foundation_child[foundation_part];
00513 
00514   AddChildSpriteScreen(image, pal, offs.x + extra_offs_x, offs.y + extra_offs_y, false, sub);
00515 
00516   /* Switch back to last ChildSprite list */
00517   _vd.last_child = old_child;
00518 }
00519 
00533 void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
00534 {
00535   /* Switch to first foundation part, if no foundation was drawn */
00536   if (_vd.foundation_part == FOUNDATION_PART_NONE) _vd.foundation_part = FOUNDATION_PART_NORMAL;
00537 
00538   if (_vd.foundation[_vd.foundation_part] != -1) {
00539     Point pt = RemapCoords(x, y, z);
00540     AddChildSpriteToFoundation(image, pal, sub, _vd.foundation_part, pt.x + extra_offs_x, pt.y + extra_offs_y);
00541   } else {
00542     AddTileSpriteToDraw(image, pal, _cur_ti->x + x, _cur_ti->y + y, _cur_ti->z + z, sub, extra_offs_x, extra_offs_y);
00543   }
00544 }
00545 
00556 void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
00557 {
00558   DrawGroundSpriteAt(image, pal, 0, 0, 0, sub, extra_offs_x, extra_offs_y);
00559 }
00560 
00568 void OffsetGroundSprite(int x, int y)
00569 {
00570   /* Switch to next foundation part */
00571   switch (_vd.foundation_part) {
00572     case FOUNDATION_PART_NONE:
00573       _vd.foundation_part = FOUNDATION_PART_NORMAL;
00574       break;
00575     case FOUNDATION_PART_NORMAL:
00576       _vd.foundation_part = FOUNDATION_PART_HALFTILE;
00577       break;
00578     default: NOT_REACHED();
00579   }
00580 
00581   /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
00582   if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = _vd.parent_sprites_to_draw.Length() - 1;
00583 
00584   _vd.foundation_offset[_vd.foundation_part].x = x;
00585   _vd.foundation_offset[_vd.foundation_part].y = y;
00586   _vd.last_foundation_child[_vd.foundation_part] = _vd.last_child;
00587 }
00588 
00600 static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, byte z, const SubSprite *sub)
00601 {
00602   Point pt = RemapCoords(x, y, z);
00603   const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
00604 
00605   if (pt.x + spr->x_offs >= _vd.dpi.left + _vd.dpi.width ||
00606       pt.x + spr->x_offs + spr->width <= _vd.dpi.left ||
00607       pt.y + spr->y_offs >= _vd.dpi.top + _vd.dpi.height ||
00608       pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
00609     return;
00610 
00611   const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1;
00612   AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub);
00613 }
00614 
00639 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)
00640 {
00641   int32 left, right, top, bottom;
00642 
00643   assert((image & SPRITE_MASK) < MAX_SPRITES);
00644 
00645   /* make the sprites transparent with the right palette */
00646   if (transparent) {
00647     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
00648     pal = PALETTE_TO_TRANSPARENT;
00649   }
00650 
00651   if (_vd.combine_sprites == SPRITE_COMBINE_ACTIVE) {
00652     AddCombinedSprite(image, pal, x, y, z, sub);
00653     return;
00654   }
00655 
00656   _vd.last_child = NULL;
00657 
00658   Point pt = RemapCoords(x, y, z);
00659   int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
00660 
00661   /* Compute screen extents of sprite */
00662   if (image == SPR_EMPTY_BOUNDING_BOX) {
00663     left = tmp_left = RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x;
00664     right           = RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1;
00665     top  = tmp_top  = RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y;
00666     bottom          = RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1;
00667   } else {
00668     const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
00669     left = tmp_left = (pt.x += spr->x_offs);
00670     right           = (pt.x +  spr->width );
00671     top  = tmp_top  = (pt.y += spr->y_offs);
00672     bottom          = (pt.y +  spr->height);
00673   }
00674 
00675   if (_draw_bounding_boxes && (image != SPR_EMPTY_BOUNDING_BOX)) {
00676     /* Compute maximal extents of sprite and it's bounding box */
00677     left   = min(left  , RemapCoords(x + w          , y + bb_offset_y, z + bb_offset_z).x);
00678     right  = max(right , RemapCoords(x + bb_offset_x, y + h          , z + bb_offset_z).x + 1);
00679     top    = min(top   , RemapCoords(x + bb_offset_x, y + bb_offset_y, z + dz         ).y);
00680     bottom = max(bottom, RemapCoords(x + w          , y + h          , z + bb_offset_z).y + 1);
00681   }
00682 
00683   /* Do not add the sprite to the viewport, if it is outside */
00684   if (left   >= _vd.dpi.left + _vd.dpi.width ||
00685       right  <= _vd.dpi.left                 ||
00686       top    >= _vd.dpi.top + _vd.dpi.height ||
00687       bottom <= _vd.dpi.top) {
00688     return;
00689   }
00690 
00691   ParentSpriteToDraw *ps = _vd.parent_sprites_to_draw.Append();
00692   ps->x = tmp_x;
00693   ps->y = tmp_y;
00694 
00695   ps->left = tmp_left;
00696   ps->top  = tmp_top;
00697 
00698   ps->image = image;
00699   ps->pal = pal;
00700   ps->sub = sub;
00701   ps->xmin = x + bb_offset_x;
00702   ps->xmax = x + max(bb_offset_x, w) - 1;
00703 
00704   ps->ymin = y + bb_offset_y;
00705   ps->ymax = y + max(bb_offset_y, h) - 1;
00706 
00707   ps->zmin = z + bb_offset_z;
00708   ps->zmax = z + max(bb_offset_z, dz) - 1;
00709 
00710   ps->comparison_done = false;
00711   ps->first_child = -1;
00712 
00713   _vd.last_child = &ps->first_child;
00714 
00715   if (_vd.combine_sprites == SPRITE_COMBINE_PENDING) _vd.combine_sprites = SPRITE_COMBINE_ACTIVE;
00716 }
00717 
00736 void StartSpriteCombine()
00737 {
00738   assert(_vd.combine_sprites == SPRITE_COMBINE_NONE);
00739   _vd.combine_sprites = SPRITE_COMBINE_PENDING;
00740 }
00741 
00746 void EndSpriteCombine()
00747 {
00748   assert(_vd.combine_sprites != SPRITE_COMBINE_NONE);
00749   _vd.combine_sprites = SPRITE_COMBINE_NONE;
00750 }
00751 
00762 void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub)
00763 {
00764   assert((image & SPRITE_MASK) < MAX_SPRITES);
00765 
00766   /* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
00767   if (_vd.last_child == NULL) return;
00768 
00769   /* make the sprites transparent with the right palette */
00770   if (transparent) {
00771     SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
00772     pal = PALETTE_TO_TRANSPARENT;
00773   }
00774 
00775   *_vd.last_child = _vd.child_screen_sprites_to_draw.Length();
00776 
00777   ChildScreenSpriteToDraw *cs = _vd.child_screen_sprites_to_draw.Append();
00778   cs->image = image;
00779   cs->pal = pal;
00780   cs->sub = sub;
00781   cs->x = x;
00782   cs->y = y;
00783   cs->next = -1;
00784 
00785   /* Append the sprite to the active ChildSprite list.
00786    * If the active ParentSprite is a foundation, update last_foundation_child as well.
00787    * Note: ChildSprites of foundations are NOT sequential in the vector, as selection sprites are added at last. */
00788   if (_vd.last_foundation_child[0] == _vd.last_child) _vd.last_foundation_child[0] = &cs->next;
00789   if (_vd.last_foundation_child[1] == _vd.last_child) _vd.last_foundation_child[1] = &cs->next;
00790   _vd.last_child = &cs->next;
00791 }
00792 
00793 static void AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2, Colours colour, uint16 width)
00794 {
00795   assert(width != 0);
00796   StringSpriteToDraw *ss = _vd.string_sprites_to_draw.Append();
00797   ss->string = string;
00798   ss->x = x;
00799   ss->y = y;
00800   ss->params[0] = params_1;
00801   ss->params[1] = params_2;
00802   ss->width = width;
00803   ss->colour = colour;
00804 }
00805 
00806 
00818 static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *ti, int z_offset, FoundationPart foundation_part)
00819 {
00820   /* FIXME: This is not totally valid for some autorail highlights, that extent over the edges of the tile. */
00821   if (_vd.foundation[foundation_part] == -1) {
00822     /* draw on real ground */
00823     AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
00824   } else {
00825     /* draw on top of foundation */
00826     AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset);
00827   }
00828 }
00829 
00836 static void DrawTileSelectionRect(const TileInfo *ti, PaletteID pal)
00837 {
00838   if (!IsValidTile(ti->tile)) return;
00839 
00840   SpriteID sel;
00841   if (IsHalftileSlope(ti->tileh)) {
00842     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
00843     SpriteID sel2 = SPR_HALFTILE_SELECTION_FLAT + halftile_corner;
00844     DrawSelectionSprite(sel2, pal, ti, 7 + TILE_HEIGHT, FOUNDATION_PART_HALFTILE);
00845 
00846     Corner opposite_corner = OppositeCorner(halftile_corner);
00847     if (IsSteepSlope(ti->tileh)) {
00848       sel = SPR_HALFTILE_SELECTION_DOWN;
00849     } else {
00850       sel = ((ti->tileh & SlopeWithOneCornerRaised(opposite_corner)) != 0 ? SPR_HALFTILE_SELECTION_UP : SPR_HALFTILE_SELECTION_FLAT);
00851     }
00852     sel += opposite_corner;
00853   } else {
00854     sel = SPR_SELECT_TILE + _tileh_to_sprite[ti->tileh];
00855   }
00856   DrawSelectionSprite(sel, pal, ti, 7, FOUNDATION_PART_NORMAL);
00857 }
00858 
00859 static bool IsPartOfAutoLine(int px, int py)
00860 {
00861   px -= _thd.selstart.x;
00862   py -= _thd.selstart.y;
00863 
00864   if ((_thd.drawstyle & ~HT_DIR_MASK) != HT_LINE) return false;
00865 
00866   switch (_thd.drawstyle & HT_DIR_MASK) {
00867     case HT_DIR_X:  return py == 0; // x direction
00868     case HT_DIR_Y:  return px == 0; // y direction
00869     case HT_DIR_HU: return px == -py || px == -py - 16; // horizontal upper
00870     case HT_DIR_HL: return px == -py || px == -py + 16; // horizontal lower
00871     case HT_DIR_VL: return px == py || px == py + 16; // vertival left
00872     case HT_DIR_VR: return px == py || px == py - 16; // vertical right
00873     default:
00874       NOT_REACHED();
00875   }
00876 }
00877 
00878 /* [direction][side] */
00879 static const HighLightStyle _autorail_type[6][2] = {
00880   { HT_DIR_X,  HT_DIR_X },
00881   { HT_DIR_Y,  HT_DIR_Y },
00882   { HT_DIR_HU, HT_DIR_HL },
00883   { HT_DIR_HL, HT_DIR_HU },
00884   { HT_DIR_VL, HT_DIR_VR },
00885   { HT_DIR_VR, HT_DIR_VL }
00886 };
00887 
00888 #include "table/autorail.h"
00889 
00896 static void DrawAutorailSelection(const TileInfo *ti, uint autorail_type)
00897 {
00898   SpriteID image;
00899   PaletteID pal;
00900   int offset;
00901 
00902   FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
00903   Slope autorail_tileh = RemoveHalftileSlope(ti->tileh);
00904   if (IsHalftileSlope(ti->tileh)) {
00905     static const uint _lower_rail[4] = { 5U, 2U, 4U, 3U };
00906     Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
00907     if (autorail_type != _lower_rail[halftile_corner]) {
00908       foundation_part = FOUNDATION_PART_HALFTILE;
00909       /* Here we draw the highlights of the "three-corners-raised"-slope. That looks ok to me. */
00910       autorail_tileh = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
00911     }
00912   }
00913 
00914   offset = _AutorailTilehSprite[autorail_tileh][autorail_type];
00915   if (offset >= 0) {
00916     image = SPR_AUTORAIL_BASE + offset;
00917     pal = PAL_NONE;
00918   } else {
00919     image = SPR_AUTORAIL_BASE - offset;
00920     pal = PALETTE_SEL_TILE_RED;
00921   }
00922 
00923   DrawSelectionSprite(image, _thd.make_square_red ? PALETTE_SEL_TILE_RED : pal, ti, 7, foundation_part);
00924 }
00925 
00930 static void DrawTileSelection(const TileInfo *ti)
00931 {
00932   /* Draw a red error square? */
00933   bool is_redsq = _thd.redsq == ti->tile;
00934   if (is_redsq) DrawTileSelectionRect(ti, PALETTE_TILE_RED_PULSATING);
00935 
00936   /* no selection active? */
00937   if (_thd.drawstyle == 0) return;
00938 
00939   /* Inside the inner area? */
00940   if (IsInsideBS(ti->x, _thd.pos.x, _thd.size.x) &&
00941       IsInsideBS(ti->y, _thd.pos.y, _thd.size.y)) {
00942     if (_thd.drawstyle & HT_RECT) {
00943       if (!is_redsq) DrawTileSelectionRect(ti, _thd.make_square_red ? PALETTE_SEL_TILE_RED : PAL_NONE);
00944     } else if (_thd.drawstyle & HT_POINT) {
00945       /* Figure out the Z coordinate for the single dot. */
00946       byte z = 0;
00947       FoundationPart foundation_part = FOUNDATION_PART_NORMAL;
00948       if (ti->tileh & SLOPE_N) {
00949         z += TILE_HEIGHT;
00950         if (RemoveHalftileSlope(ti->tileh) == SLOPE_STEEP_N) z += TILE_HEIGHT;
00951       }
00952       if (IsHalftileSlope(ti->tileh)) {
00953         Corner halftile_corner = GetHalftileSlopeCorner(ti->tileh);
00954         if ((halftile_corner == CORNER_W) || (halftile_corner == CORNER_E)) z += TILE_HEIGHT;
00955         if (halftile_corner != CORNER_S) {
00956           foundation_part = FOUNDATION_PART_HALFTILE;
00957           if (IsSteepSlope(ti->tileh)) z -= TILE_HEIGHT;
00958         }
00959       }
00960       DrawSelectionSprite(_cur_dpi->zoom <= ZOOM_LVL_DETAIL ? SPR_DOT : SPR_DOT_SMALL, PAL_NONE, ti, z, foundation_part);
00961     } else if (_thd.drawstyle & HT_RAIL) {
00962       /* autorail highlight piece under cursor */
00963       HighLightStyle type = _thd.drawstyle & HT_DIR_MASK;
00964       assert(type < HT_DIR_END);
00965       DrawAutorailSelection(ti, _autorail_type[type][0]);
00966     } else if (IsPartOfAutoLine(ti->x, ti->y)) {
00967       /* autorail highlighting long line */
00968       HighLightStyle dir = _thd.drawstyle & HT_DIR_MASK;
00969       uint side;
00970 
00971       if (dir == HT_DIR_X || dir == HT_DIR_Y) {
00972         side = 0;
00973       } else {
00974         TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
00975         side = Delta(Delta(TileX(start), TileX(ti->tile)), Delta(TileY(start), TileY(ti->tile)));
00976       }
00977 
00978       DrawAutorailSelection(ti, _autorail_type[dir][side]);
00979     }
00980     return;
00981   }
00982 
00983   /* Check if it's inside the outer area? */
00984   if (!is_redsq && _thd.outersize.x &&
00985       _thd.size.x < _thd.size.x + _thd.outersize.x &&
00986       IsInsideBS(ti->x, _thd.pos.x + _thd.offs.x, _thd.size.x + _thd.outersize.x) &&
00987       IsInsideBS(ti->y, _thd.pos.y + _thd.offs.y, _thd.size.y + _thd.outersize.y)) {
00988     /* Draw a blue rect. */
00989     DrawTileSelectionRect(ti, PALETTE_SEL_TILE_BLUE);
00990     return;
00991   }
00992 }
00993 
00994 static void ViewportAddLandscape()
00995 {
00996   int x, y, width, height;
00997   TileInfo ti;
00998   bool direction;
00999 
01000   _cur_ti = &ti;
01001 
01002   /* Transform into tile coordinates and round to closest full tile */
01003   x = ((_vd.dpi.top >> 1) - (_vd.dpi.left >> 2)) & ~TILE_UNIT_MASK;
01004   y = ((_vd.dpi.top >> 1) + (_vd.dpi.left >> 2) - TILE_SIZE) & ~TILE_UNIT_MASK;
01005 
01006   /* determine size of area */
01007   {
01008     Point pt = RemapCoords(x, y, 241);
01009     width = (_vd.dpi.left + _vd.dpi.width - pt.x + 95) >> 6;
01010     height = (_vd.dpi.top + _vd.dpi.height - pt.y) >> 5 << 1;
01011   }
01012 
01013   assert(width > 0);
01014   assert(height > 0);
01015 
01016   direction = false;
01017 
01018   do {
01019     int width_cur = width;
01020     int x_cur = x;
01021     int y_cur = y;
01022 
01023     do {
01024       TileType tt = MP_VOID;
01025 
01026       ti.x = x_cur;
01027       ti.y = y_cur;
01028 
01029       ti.z = 0;
01030 
01031       ti.tileh = SLOPE_FLAT;
01032       ti.tile = INVALID_TILE;
01033 
01034       if (0 <= x_cur && x_cur < (int)MapMaxX() * TILE_SIZE &&
01035           0 <= y_cur && y_cur < (int)MapMaxY() * TILE_SIZE) {
01036         TileIndex tile = TileVirtXY(x_cur, y_cur);
01037 
01038         if (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0)) {
01039           if (x_cur == ((int)MapMaxX() - 1) * TILE_SIZE || y_cur == ((int)MapMaxY() - 1) * TILE_SIZE) {
01040             uint maxh = max<uint>(TileHeight(tile), 1);
01041             for (uint h = 0; h < maxh; h++) {
01042               AddTileSpriteToDraw(SPR_SHADOW_CELL, PAL_NONE, ti.x, ti.y, h * TILE_HEIGHT);
01043             }
01044           }
01045 
01046           ti.tile = tile;
01047           ti.tileh = GetTileSlope(tile, &ti.z);
01048           tt = GetTileType(tile);
01049         }
01050       }
01051 
01052       _vd.foundation_part = FOUNDATION_PART_NONE;
01053       _vd.foundation[0] = -1;
01054       _vd.foundation[1] = -1;
01055       _vd.last_foundation_child[0] = NULL;
01056       _vd.last_foundation_child[1] = NULL;
01057 
01058       _tile_type_procs[tt]->draw_tile_proc(&ti);
01059 
01060       if ((x_cur == (int)MapMaxX() * TILE_SIZE && IsInsideMM(y_cur, 0, MapMaxY() * TILE_SIZE + 1)) ||
01061         (y_cur == (int)MapMaxY() * TILE_SIZE && IsInsideMM(x_cur, 0, MapMaxX() * TILE_SIZE + 1))) {
01062         TileIndex tile = TileVirtXY(x_cur, y_cur);
01063         ti.tile = tile;
01064         ti.tileh = GetTileSlope(tile, &ti.z);
01065         tt = GetTileType(tile);
01066       }
01067       if (ti.tile != INVALID_TILE) DrawTileSelection(&ti);
01068 
01069       y_cur += 0x10;
01070       x_cur -= 0x10;
01071     } while (--width_cur);
01072 
01073     if ((direction ^= 1) != 0) {
01074       y += 0x10;
01075     } else {
01076       x += 0x10;
01077     }
01078   } while (--height);
01079 }
01080 
01091 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)
01092 {
01093   bool small = dpi->zoom >= small_from;
01094 
01095   int left   = dpi->left;
01096   int top    = dpi->top;
01097   int right  = left + dpi->width;
01098   int bottom = top + dpi->height;
01099 
01100   int sign_height     = ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM, dpi->zoom);
01101   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, dpi->zoom);
01102 
01103   if (bottom < sign->top ||
01104       top   > sign->top + sign_height ||
01105       right < sign->center - sign_half_width ||
01106       left  > sign->center + sign_half_width) {
01107     return;
01108   }
01109 
01110   if (!small) {
01111     AddStringToDraw(sign->center - sign_half_width, sign->top, string_normal, params_1, params_2, colour, sign->width_normal);
01112   } else {
01113     int shadow_offset = 0;
01114     if (string_small_shadow != STR_NULL) {
01115       shadow_offset = 4;
01116       AddStringToDraw(sign->center - sign_half_width + shadow_offset, sign->top, string_small_shadow, params_1, params_2, INVALID_COLOUR, sign->width_small);
01117     }
01118     AddStringToDraw(sign->center - sign_half_width, sign->top - shadow_offset, string_small, params_1, params_2,
01119         colour, sign->width_small | 0x8000);
01120   }
01121 }
01122 
01123 static void ViewportAddTownNames(DrawPixelInfo *dpi)
01124 {
01125   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES) || _game_mode == GM_MENU) return;
01126 
01127   const Town *t;
01128   FOR_ALL_TOWNS(t) {
01129     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &t->sign,
01130         _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
01131         STR_VIEWPORT_TOWN_TINY_WHITE, STR_VIEWPORT_TOWN_TINY_BLACK,
01132         t->index, t->population);
01133   }
01134 }
01135 
01136 
01137 static void ViewportAddStationNames(DrawPixelInfo *dpi)
01138 {
01139   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || _game_mode == GM_MENU) return;
01140 
01141   const BaseStation *st;
01142   FOR_ALL_BASE_STATIONS(st) {
01143     /* Check whether the base station is a station or a waypoint */
01144     bool is_station = Station::IsExpected(st);
01145 
01146     /* Don't draw if the display options are disabled */
01147     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
01148 
01149     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &st->sign,
01150         is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT,
01151         (is_station ? STR_VIEWPORT_STATION : STR_VIEWPORT_WAYPOINT) + 1, STR_NULL,
01152         st->index, st->facilities, (st->owner == OWNER_NONE || !st->IsInUse()) ? COLOUR_GREY : _company_colours[st->owner]);
01153   }
01154 }
01155 
01156 
01157 static void ViewportAddSigns(DrawPixelInfo *dpi)
01158 {
01159   /* Signs are turned off or are invisible */
01160   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS)) return;
01161 
01162   const Sign *si;
01163   FOR_ALL_SIGNS(si) {
01164     ViewportAddString(dpi, ZOOM_LVL_OUT_4X, &si->sign,
01165         STR_WHITE_SIGN,
01166         IsTransparencySet(TO_SIGNS) ? STR_VIEWPORT_SIGN_SMALL_WHITE : STR_VIEWPORT_SIGN_SMALL_BLACK, STR_NULL,
01167         si->index, 0, (si->owner == OWNER_NONE) ? COLOUR_GREY : _company_colours[si->owner]);
01168   }
01169 }
01170 
01177 void ViewportSign::UpdatePosition(int center, int top, StringID str)
01178 {
01179   if (this->width_normal != 0) this->MarkDirty();
01180 
01181   this->top = top;
01182 
01183   char buffer[DRAW_STRING_BUFFER];
01184 
01185   GetString(buffer, str, lastof(buffer));
01186   this->width_normal = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
01187   this->center = center;
01188 
01189   /* zoomed out version */
01190   _cur_fontsize = FS_SMALL;
01191   this->width_small = VPSM_LEFT + Align(GetStringBoundingBox(buffer).width, 2) + VPSM_RIGHT;
01192   _cur_fontsize = FS_NORMAL;
01193 
01194   this->MarkDirty();
01195 }
01196 
01202 void ViewportSign::MarkDirty() const
01203 {
01204   /* We use ZOOM_LVL_MAX here, as every viewport can have another zoom,
01205    *  and there is no way for us to know which is the biggest. So make the
01206    *  biggest area dirty, and we are safe for sure.
01207    * We also add 1 to make sure the whole thing is redrawn. */
01208   MarkAllViewportsDirty(
01209     this->center - ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
01210     this->top    - ScaleByZoom(1, ZOOM_LVL_MAX),
01211     this->center + ScaleByZoom(this->width_normal / 2 + 1, ZOOM_LVL_MAX),
01212     this->top    + ScaleByZoom(VPSM_TOP + FONT_HEIGHT_NORMAL + VPSM_BOTTOM + 1, ZOOM_LVL_MAX));
01213 }
01214 
01215 static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
01216 {
01217   const TileSpriteToDraw *tsend = tstdv->End();
01218   for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) {
01219     DrawSprite(ts->image, ts->pal, ts->x, ts->y, ts->sub);
01220   }
01221 }
01222 
01224 static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
01225 {
01226   ParentSpriteToDraw **psdvend = psdv->End();
01227   ParentSpriteToDraw **psd = psdv->Begin();
01228   while (psd != psdvend) {
01229     ParentSpriteToDraw *ps = *psd;
01230 
01231     if (ps->comparison_done) {
01232       psd++;
01233       continue;
01234     }
01235 
01236     ps->comparison_done = true;
01237 
01238     for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) {
01239       ParentSpriteToDraw *ps2 = *psd2;
01240 
01241       if (ps2->comparison_done) continue;
01242 
01243       /* Decide which comparator to use, based on whether the bounding
01244        * boxes overlap
01245        */
01246       if (ps->xmax >= ps2->xmin && ps->xmin <= ps2->xmax && // overlap in X?
01247           ps->ymax >= ps2->ymin && ps->ymin <= ps2->ymax && // overlap in Y?
01248           ps->zmax >= ps2->zmin && ps->zmin <= ps2->zmax) { // overlap in Z?
01249         /* Use X+Y+Z as the sorting order, so sprites closer to the bottom of
01250          * the screen and with higher Z elevation, are drawn in front.
01251          * Here X,Y,Z are the coordinates of the "center of mass" of the sprite,
01252          * i.e. X=(left+right)/2, etc.
01253          * However, since we only care about order, don't actually divide / 2
01254          */
01255         if (ps->xmin + ps->xmax + ps->ymin + ps->ymax + ps->zmin + ps->zmax <=
01256             ps2->xmin + ps2->xmax + ps2->ymin + ps2->ymax + ps2->zmin + ps2->zmax) {
01257           continue;
01258         }
01259       } else {
01260         /* We only change the order, if it is definite.
01261          * I.e. every single order of X, Y, Z says ps2 is behind ps or they overlap.
01262          * That is: If one partial order says ps behind ps2, do not change the order.
01263          */
01264         if (ps->xmax < ps2->xmin ||
01265             ps->ymax < ps2->ymin ||
01266             ps->zmax < ps2->zmin) {
01267           continue;
01268         }
01269       }
01270 
01271       /* Move ps2 in front of ps */
01272       ParentSpriteToDraw *temp = ps2;
01273       for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) {
01274         *psd3 = *(psd3 - 1);
01275       }
01276       *psd = temp;
01277     }
01278   }
01279 }
01280 
01281 static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
01282 {
01283   const ParentSpriteToDraw * const *psd_end = psd->End();
01284   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
01285     const ParentSpriteToDraw *ps = *it;
01286     if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSprite(ps->image, ps->pal, ps->x, ps->y, ps->sub);
01287 
01288     int child_idx = ps->first_child;
01289     while (child_idx >= 0) {
01290       const ChildScreenSpriteToDraw *cs = csstdv->Get(child_idx);
01291       child_idx = cs->next;
01292       DrawSprite(cs->image, cs->pal, ps->left + cs->x, ps->top + cs->y, cs->sub);
01293     }
01294   }
01295 }
01296 
01301 static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
01302 {
01303   const ParentSpriteToDraw * const *psd_end = psd->End();
01304   for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
01305     const ParentSpriteToDraw *ps = *it;
01306     Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner
01307     Point pt2 = RemapCoords(ps->xmin    , ps->ymax + 1, ps->zmax + 1); // top left corner
01308     Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin    , ps->zmax + 1); // top right corner
01309     Point pt4 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmin    ); // bottom front corner
01310 
01311     DrawBox(        pt1.x,         pt1.y,
01312             pt2.x - pt1.x, pt2.y - pt1.y,
01313             pt3.x - pt1.x, pt3.y - pt1.y,
01314             pt4.x - pt1.x, pt4.y - pt1.y);
01315   }
01316 }
01317 
01318 static void ViewportDrawStrings(DrawPixelInfo *dpi, const StringSpriteToDrawVector *sstdv)
01319 {
01320   DrawPixelInfo dp;
01321   ZoomLevel zoom;
01322 
01323   _cur_dpi = &dp;
01324   dp = *dpi;
01325 
01326   zoom = dp.zoom;
01327   dp.zoom = ZOOM_LVL_NORMAL;
01328 
01329   dp.left   = UnScaleByZoom(dp.left,   zoom);
01330   dp.top    = UnScaleByZoom(dp.top,    zoom);
01331   dp.width  = UnScaleByZoom(dp.width,  zoom);
01332   dp.height = UnScaleByZoom(dp.height, zoom);
01333 
01334   const StringSpriteToDraw *ssend = sstdv->End();
01335   for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
01336     TextColour colour = TC_BLACK;
01337     bool small = HasBit(ss->width, 15);
01338     int w = GB(ss->width, 0, 15);
01339     int x = UnScaleByZoom(ss->x, zoom);
01340     int y = UnScaleByZoom(ss->y, zoom);
01341     int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
01342 
01343     SetDParam(0, ss->params[0]);
01344     SetDParam(1, ss->params[1]);
01345 
01346     if (ss->colour != INVALID_COLOUR) {
01347       /* Do not draw signs nor station names if they are set invisible */
01348       if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue;
01349 
01350       /* if we didn't draw a rectangle, or if transparant building is on,
01351        * draw the text in the colour the rectangle would have */
01352       if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) {
01353         /* Real colours need the IS_PALETTE_COLOUR flag
01354          * otherwise colours from _string_colourmap are assumed. */
01355         colour = (TextColour)_colour_gradient[ss->colour][6] | IS_PALETTE_COLOUR;
01356       }
01357 
01358       /* Draw the rectangle if 'tranparent station signs' is off,
01359        * or if we are drawing a general text sign (STR_WHITE_SIGN) */
01360       if (!IsTransparencySet(TO_SIGNS) || ss->string == STR_WHITE_SIGN) {
01361         DrawFrameRect(
01362           x, y, x + w, y + h, ss->colour,
01363           IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE
01364         );
01365       }
01366     }
01367 
01368     DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_CENTER);
01369   }
01370 }
01371 
01372 void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom)
01373 {
01374   DrawPixelInfo *old_dpi = _cur_dpi;
01375   _cur_dpi = &_vd.dpi;
01376 
01377   _vd.dpi.zoom = vp->zoom;
01378   int mask = ScaleByZoom(-1, vp->zoom);
01379 
01380   _vd.combine_sprites = SPRITE_COMBINE_NONE;
01381 
01382   _vd.dpi.width = (right - left) & mask;
01383   _vd.dpi.height = (bottom - top) & mask;
01384   _vd.dpi.left = left & mask;
01385   _vd.dpi.top = top & mask;
01386   _vd.dpi.pitch = old_dpi->pitch;
01387   _vd.last_child = NULL;
01388 
01389   int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
01390   int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
01391 
01392   _vd.dpi.dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(old_dpi->dst_ptr, x - old_dpi->left, y - old_dpi->top);
01393 
01394   ViewportAddLandscape();
01395   ViewportAddVehicles(&_vd.dpi);
01396 
01397   ViewportAddTownNames(&_vd.dpi);
01398   ViewportAddStationNames(&_vd.dpi);
01399   ViewportAddSigns(&_vd.dpi);
01400 
01401   DrawTextEffects(&_vd.dpi);
01402 
01403   if (_vd.tile_sprites_to_draw.Length() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
01404 
01405   ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End();
01406   for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) {
01407     *_vd.parent_sprites_to_sort.Append() = it;
01408   }
01409 
01410   ViewportSortParentSprites(&_vd.parent_sprites_to_sort);
01411   ViewportDrawParentSprites(&_vd.parent_sprites_to_sort, &_vd.child_screen_sprites_to_draw);
01412 
01413   if (_draw_bounding_boxes) ViewportDrawBoundingBoxes(&_vd.parent_sprites_to_sort);
01414 
01415   if (_vd.string_sprites_to_draw.Length() != 0) ViewportDrawStrings(&_vd.dpi, &_vd.string_sprites_to_draw);
01416 
01417   _cur_dpi = old_dpi;
01418 
01419   _vd.string_sprites_to_draw.Clear();
01420   _vd.tile_sprites_to_draw.Clear();
01421   _vd.parent_sprites_to_draw.Clear();
01422   _vd.parent_sprites_to_sort.Clear();
01423   _vd.child_screen_sprites_to_draw.Clear();
01424 }
01425 
01428 static void ViewportDrawChk(const ViewPort *vp, int left, int top, int right, int bottom)
01429 {
01430   if (ScaleByZoom(bottom - top, vp->zoom) * ScaleByZoom(right - left, vp->zoom) > 180000) {
01431     if ((bottom - top) > (right - left)) {
01432       int t = (top + bottom) >> 1;
01433       ViewportDrawChk(vp, left, top, right, t);
01434       ViewportDrawChk(vp, left, t, right, bottom);
01435     } else {
01436       int t = (left + right) >> 1;
01437       ViewportDrawChk(vp, left, top, t, bottom);
01438       ViewportDrawChk(vp, t, top, right, bottom);
01439     }
01440   } else {
01441     ViewportDoDraw(vp,
01442       ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
01443       ScaleByZoom(top - vp->top, vp->zoom) + vp->virtual_top,
01444       ScaleByZoom(right - vp->left, vp->zoom) + vp->virtual_left,
01445       ScaleByZoom(bottom - vp->top, vp->zoom) + vp->virtual_top
01446     );
01447   }
01448 }
01449 
01450 static inline void ViewportDraw(const ViewPort *vp, int left, int top, int right, int bottom)
01451 {
01452   if (right <= vp->left || bottom <= vp->top) return;
01453 
01454   if (left >= vp->left + vp->width) return;
01455 
01456   if (left < vp->left) left = vp->left;
01457   if (right > vp->left + vp->width) right = vp->left + vp->width;
01458 
01459   if (top >= vp->top + vp->height) return;
01460 
01461   if (top < vp->top) top = vp->top;
01462   if (bottom > vp->top + vp->height) bottom = vp->top + vp->height;
01463 
01464   ViewportDrawChk(vp, left, top, right, bottom);
01465 }
01466 
01470 void Window::DrawViewport() const
01471 {
01472   DrawPixelInfo *dpi = _cur_dpi;
01473 
01474   dpi->left += this->left;
01475   dpi->top += this->top;
01476 
01477   ViewportDraw(this->viewport, dpi->left, dpi->top, dpi->left + dpi->width, dpi->top + dpi->height);
01478 
01479   dpi->left -= this->left;
01480   dpi->top -= this->top;
01481 }
01482 
01483 static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
01484 {
01485   /* Centre of the viewport is hot spot */
01486   x += vp->virtual_width / 2;
01487   y += vp->virtual_height / 2;
01488 
01489   /* Convert viewport coordinates to map coordinates
01490    * Calculation is scaled by 4 to avoid rounding errors */
01491   int vx = -x + y * 2;
01492   int vy =  x + y * 2;
01493 
01494   /* clamp to size of map */
01495   vx = Clamp(vx, 0, MapMaxX() * TILE_SIZE * 4);
01496   vy = Clamp(vy, 0, MapMaxY() * TILE_SIZE * 4);
01497 
01498   /* Convert map coordinates to viewport coordinates */
01499   x = (-vx + vy) / 2;
01500   y = ( vx + vy) / 4;
01501 
01502   /* Remove centreing */
01503   x -= vp->virtual_width / 2;
01504   y -= vp->virtual_height / 2;
01505 }
01506 
01511 void UpdateViewportPosition(Window *w)
01512 {
01513   const ViewPort *vp = w->viewport;
01514 
01515   if (w->viewport->follow_vehicle != INVALID_VEHICLE) {
01516     const Vehicle *veh = Vehicle::Get(w->viewport->follow_vehicle);
01517     Point pt = MapXYZToViewport(vp, veh->x_pos, veh->y_pos, veh->z_pos);
01518 
01519     w->viewport->scrollpos_x = pt.x;
01520     w->viewport->scrollpos_y = pt.y;
01521     SetViewportPosition(w, pt.x, pt.y);
01522   } else {
01523     /* Ensure the destination location is within the map */
01524     ClampViewportToMap(vp, w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y);
01525 
01526     int delta_x = w->viewport->dest_scrollpos_x - w->viewport->scrollpos_x;
01527     int delta_y = w->viewport->dest_scrollpos_y - w->viewport->scrollpos_y;
01528 
01529     if (delta_x != 0 || delta_y != 0) {
01530       if (_settings_client.gui.smooth_scroll) {
01531         int max_scroll = ScaleByMapSize1D(512);
01532         /* Not at our desired positon yet... */
01533         w->viewport->scrollpos_x += Clamp(delta_x / 4, -max_scroll, max_scroll);
01534         w->viewport->scrollpos_y += Clamp(delta_y / 4, -max_scroll, max_scroll);
01535       } else {
01536         w->viewport->scrollpos_x = w->viewport->dest_scrollpos_x;
01537         w->viewport->scrollpos_y = w->viewport->dest_scrollpos_y;
01538       }
01539     }
01540 
01541     ClampViewportToMap(vp, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
01542 
01543     SetViewportPosition(w, w->viewport->scrollpos_x, w->viewport->scrollpos_y);
01544   }
01545 }
01546 
01556 static void MarkViewportDirty(const ViewPort *vp, int left, int top, int right, int bottom)
01557 {
01558   right -= vp->virtual_left;
01559   if (right <= 0) return;
01560 
01561   bottom -= vp->virtual_top;
01562   if (bottom <= 0) return;
01563 
01564   left = max(0, left - vp->virtual_left);
01565 
01566   if (left >= vp->virtual_width) return;
01567 
01568   top = max(0, top - vp->virtual_top);
01569 
01570   if (top >= vp->virtual_height) return;
01571 
01572   SetDirtyBlocks(
01573     UnScaleByZoomLower(left, vp->zoom) + vp->left,
01574     UnScaleByZoomLower(top, vp->zoom) + vp->top,
01575     UnScaleByZoom(right, vp->zoom) + vp->left + 1,
01576     UnScaleByZoom(bottom, vp->zoom) + vp->top + 1
01577   );
01578 }
01579 
01588 void MarkAllViewportsDirty(int left, int top, int right, int bottom)
01589 {
01590   Window *w;
01591   FOR_ALL_WINDOWS_FROM_BACK(w) {
01592     ViewPort *vp = w->viewport;
01593     if (vp != NULL) {
01594       assert(vp->width != 0);
01595       MarkViewportDirty(vp, left, top, right, bottom);
01596     }
01597   }
01598 }
01599 
01600 void MarkTileDirtyByTile(TileIndex tile)
01601 {
01602   Point pt = RemapCoords(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTileZ(tile));
01603   MarkAllViewportsDirty(
01604     pt.x - 31,
01605     pt.y - 122,
01606     pt.x - 31 + 67,
01607     pt.y - 122 + 154
01608   );
01609 }
01610 
01618 static void SetSelectionTilesDirty()
01619 {
01620   int x_start = _thd.pos.x;
01621   int y_start = _thd.pos.y;
01622 
01623   int x_size = _thd.size.x;
01624   int y_size = _thd.size.y;
01625 
01626   if (_thd.outersize.x != 0) {
01627     x_size  += _thd.outersize.x;
01628     x_start += _thd.offs.x;
01629     y_size  += _thd.outersize.y;
01630     y_start += _thd.offs.y;
01631   }
01632 
01633   x_size -= TILE_SIZE;
01634   y_size -= TILE_SIZE;
01635 
01636   assert(x_size >= 0);
01637   assert(y_size >= 0);
01638 
01639   int x_end = Clamp(x_start + x_size, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
01640   int y_end = Clamp(y_start + y_size, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
01641 
01642   x_start = Clamp(x_start, 0, MapSizeX() * TILE_SIZE - TILE_SIZE);
01643   y_start = Clamp(y_start, 0, MapSizeY() * TILE_SIZE - TILE_SIZE);
01644 
01645   /* make sure everything is multiple of TILE_SIZE */
01646   assert((x_end | y_end | x_start | y_start) % TILE_SIZE == 0);
01647 
01648   /* How it works:
01649    * Suppose we have to mark dirty rectangle of 3x4 tiles:
01650    *   x
01651    *  xxx
01652    * xxxxx
01653    *  xxxxx
01654    *   xxx
01655    *    x
01656    * This algorithm marks dirty columns of tiles, so it is done in 3+4-1 steps:
01657    * 1)  x     2)  x
01658    *    xxx       Oxx
01659    *   Oxxxx     xOxxx
01660    *    xxxxx     Oxxxx
01661    *     xxx       xxx
01662    *      x         x
01663    * And so forth...
01664    */
01665 
01666   int top_x = x_end; // coordinates of top dirty tile
01667   int top_y = y_start;
01668   int bot_x = top_x; // coordinates of bottom dirty tile
01669   int bot_y = top_y;
01670 
01671   do {
01672     Point top = RemapCoords2(top_x, top_y); // topmost dirty point
01673     Point bot = RemapCoords2(bot_x + TILE_SIZE - 1, bot_y + TILE_SIZE - 1); // bottommost point
01674 
01675     /* the 'x' coordinate of 'top' and 'bot' is the same (and always in the same distance from tile middle),
01676      * tile height/slope affects only the 'y' on-screen coordinate! */
01677 
01678     int l = top.x - (TILE_PIXELS - 2); // 'x' coordinate of left side of dirty rectangle
01679     int t = top.y;                     // 'y' coordinate of top side -//-
01680     int r = top.x + (TILE_PIXELS - 2); // right side of dirty rectangle
01681     int b = bot.y;                     // bottom -//-
01682 
01683     static const int OVERLAY_WIDTH = 4; // part of selection sprites is drawn outside the selected area
01684 
01685     /* For halftile foundations on SLOPE_STEEP_S the sprite extents some more towards the top */
01686     MarkAllViewportsDirty(l - OVERLAY_WIDTH, t - OVERLAY_WIDTH - TILE_HEIGHT, r + OVERLAY_WIDTH, b + OVERLAY_WIDTH);
01687 
01688     /* haven't we reached the topmost tile yet? */
01689     if (top_x != x_start) {
01690       top_x -= TILE_SIZE;
01691     } else {
01692       top_y += TILE_SIZE;
01693     }
01694 
01695     /* the way the bottom tile changes is different when we reach the bottommost tile */
01696     if (bot_y != y_end) {
01697       bot_y += TILE_SIZE;
01698     } else {
01699       bot_x -= TILE_SIZE;
01700     }
01701   } while (bot_x >= top_x);
01702 }
01703 
01704 
01705 void SetSelectionRed(bool b)
01706 {
01707   _thd.make_square_red = b;
01708   SetSelectionTilesDirty();
01709 }
01710 
01719 static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y, const ViewportSign *sign)
01720 {
01721   bool small = (vp->zoom >= ZOOM_LVL_OUT_4X);
01722   int sign_half_width = ScaleByZoom((small ? sign->width_small : sign->width_normal) / 2, vp->zoom);
01723   int sign_height = ScaleByZoom(VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM, vp->zoom);
01724 
01725   x = ScaleByZoom(x - vp->left, vp->zoom) + vp->virtual_left;
01726   y = ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top;
01727 
01728   return
01729       y >= sign->top &&
01730       y <  sign->top + sign_height &&
01731       x >= sign->center - sign_half_width &&
01732       x <  sign->center + sign_half_width;
01733 }
01734 
01735 static bool CheckClickOnTown(const ViewPort *vp, int x, int y)
01736 {
01737   if (!HasBit(_display_opt, DO_SHOW_TOWN_NAMES)) return false;
01738 
01739   const Town *t;
01740   FOR_ALL_TOWNS(t) {
01741     if (CheckClickOnViewportSign(vp, x, y, &t->sign)) {
01742       ShowTownViewWindow(t->index);
01743       return true;
01744     }
01745   }
01746 
01747   return false;
01748 }
01749 
01750 static bool CheckClickOnStation(const ViewPort *vp, int x, int y)
01751 {
01752   if (!(HasBit(_display_opt, DO_SHOW_STATION_NAMES) || HasBit(_display_opt, DO_SHOW_WAYPOINT_NAMES)) || IsInvisibilitySet(TO_SIGNS)) return false;
01753 
01754   const BaseStation *st;
01755   FOR_ALL_BASE_STATIONS(st) {
01756     /* Check whether the base station is a station or a waypoint */
01757     bool is_station = Station::IsExpected(st);
01758 
01759     /* Don't check if the display options are disabled */
01760     if (!HasBit(_display_opt, is_station ? DO_SHOW_STATION_NAMES : DO_SHOW_WAYPOINT_NAMES)) continue;
01761 
01762     if (CheckClickOnViewportSign(vp, x, y, &st->sign)) {
01763       if (is_station) {
01764         ShowStationViewWindow(st->index);
01765       } else {
01766         ShowWaypointWindow(Waypoint::From(st));
01767       }
01768       return true;
01769     }
01770   }
01771 
01772   return false;
01773 }
01774 
01775 
01776 static bool CheckClickOnSign(const ViewPort *vp, int x, int y)
01777 {
01778   /* Signs are turned off, or they are transparent and invisibility is ON, or company is a spectator */
01779   if (!HasBit(_display_opt, DO_SHOW_SIGNS) || IsInvisibilitySet(TO_SIGNS) || _local_company == COMPANY_SPECTATOR) return false;
01780 
01781   const Sign *si;
01782   FOR_ALL_SIGNS(si) {
01783     if (CheckClickOnViewportSign(vp, x, y, &si->sign)) {
01784       HandleClickOnSign(si);
01785       return true;
01786     }
01787   }
01788 
01789   return false;
01790 }
01791 
01792 
01793 static bool CheckClickOnLandscape(const ViewPort *vp, int x, int y)
01794 {
01795   Point pt = TranslateXYToTileCoord(vp, x, y);
01796 
01797   if (pt.x != -1) return ClickTile(TileVirtXY(pt.x, pt.y));
01798   return true;
01799 }
01800 
01801 
01802 bool HandleViewportClicked(const ViewPort *vp, int x, int y)
01803 {
01804   const Vehicle *v;
01805 
01806   if (CheckClickOnTown(vp, x, y)) return true;
01807   if (CheckClickOnStation(vp, x, y)) return true;
01808   if (CheckClickOnSign(vp, x, y)) return true;
01809   CheckClickOnLandscape(vp, x, y);
01810 
01811   v = CheckClickOnVehicle(vp, x, y);
01812   if (v != NULL) {
01813     DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
01814     if (IsCompanyBuildableVehicleType(v)) ShowVehicleViewWindow(v->First());
01815     return true;
01816   }
01817   return CheckClickOnLandscape(vp, x, y);
01818 }
01819 
01820 Vehicle *CheckMouseOverVehicle()
01821 {
01822   const Window *w;
01823   const ViewPort *vp;
01824 
01825   int x = _cursor.pos.x;
01826   int y = _cursor.pos.y;
01827 
01828   w = FindWindowFromPt(x, y);
01829   if (w == NULL) return NULL;
01830 
01831   vp = IsPtInWindowViewport(w, x, y);
01832   return (vp != NULL) ? CheckClickOnVehicle(vp, x, y) : NULL;
01833 }
01834 
01835 
01836 
01837 void PlaceObject()
01838 {
01839   Point pt;
01840   Window *w;
01841 
01842   pt = GetTileBelowCursor();
01843   if (pt.x == -1) return;
01844 
01845   if (_thd.place_mode == HT_POINT) {
01846     pt.x += 8;
01847     pt.y += 8;
01848   }
01849 
01850   _tile_fract_coords.x = pt.x & TILE_UNIT_MASK;
01851   _tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
01852 
01853   w = GetCallbackWnd();
01854   if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
01855 }
01856 
01857 
01866 bool ScrollWindowTo(int x, int y, int z, Window *w, bool instant)
01867 {
01868   /* The slope cannot be acquired outside of the map, so make sure we are always within the map. */
01869   if (z == -1) z = GetSlopeZ(Clamp(x, 0, MapSizeX() * TILE_SIZE - 1), Clamp(y, 0, MapSizeY() * TILE_SIZE - 1));
01870 
01871   Point pt = MapXYZToViewport(w->viewport, x, y, z);
01872   w->viewport->follow_vehicle = INVALID_VEHICLE;
01873 
01874   if (w->viewport->dest_scrollpos_x == pt.x && w->viewport->dest_scrollpos_y == pt.y)
01875     return false;
01876 
01877   if (instant) {
01878     w->viewport->scrollpos_x = pt.x;
01879     w->viewport->scrollpos_y = pt.y;
01880   }
01881 
01882   w->viewport->dest_scrollpos_x = pt.x;
01883   w->viewport->dest_scrollpos_y = pt.y;
01884   return true;
01885 }
01886 
01887 bool ScrollMainWindowToTile(TileIndex tile, bool instant)
01888 {
01889   return ScrollMainWindowTo(TileX(tile) * TILE_SIZE + TILE_SIZE / 2, TileY(tile) * TILE_SIZE + TILE_SIZE / 2, -1, instant);
01890 }
01891 
01892 void SetRedErrorSquare(TileIndex tile)
01893 {
01894   TileIndex old;
01895 
01896   old = _thd.redsq;
01897   _thd.redsq = tile;
01898 
01899   if (tile != old) {
01900     if (tile != INVALID_TILE) MarkTileDirtyByTile(tile);
01901     if (old  != INVALID_TILE) MarkTileDirtyByTile(old);
01902   }
01903 }
01904 
01909 void SetTileSelectSize(int w, int h)
01910 {
01911   _thd.new_size.x = w * TILE_SIZE;
01912   _thd.new_size.y = h * TILE_SIZE;
01913   _thd.new_outersize.x = 0;
01914   _thd.new_outersize.y = 0;
01915 }
01916 
01917 void SetTileSelectBigSize(int ox, int oy, int sx, int sy)
01918 {
01919   _thd.offs.x = ox * TILE_SIZE;
01920   _thd.offs.y = oy * TILE_SIZE;
01921   _thd.new_outersize.x = sx * TILE_SIZE;
01922   _thd.new_outersize.y = sy * TILE_SIZE;
01923 }
01924 
01926 static HighLightStyle GetAutorailHT(int x, int y)
01927 {
01928   return HT_RAIL | _autorail_piece[x & TILE_UNIT_MASK][y & TILE_UNIT_MASK];
01929 }
01930 
01938 void UpdateTileSelection()
01939 {
01940   int x1;
01941   int y1;
01942 
01943   _thd.new_drawstyle = HT_NONE;
01944 
01945   if (_thd.place_mode == HT_SPECIAL) {
01946     x1 = _thd.selend.x;
01947     y1 = _thd.selend.y;
01948     if (x1 != -1) {
01949       int x2 = _thd.selstart.x & ~TILE_UNIT_MASK;
01950       int y2 = _thd.selstart.y & ~TILE_UNIT_MASK;
01951       x1 &= ~TILE_UNIT_MASK;
01952       y1 &= ~TILE_UNIT_MASK;
01953 
01954       if (x1 >= x2) Swap(x1, x2);
01955       if (y1 >= y2) Swap(y1, y2);
01956       _thd.new_pos.x = x1;
01957       _thd.new_pos.y = y1;
01958       _thd.new_size.x = x2 - x1 + TILE_SIZE;
01959       _thd.new_size.y = y2 - y1 + TILE_SIZE;
01960       _thd.new_drawstyle = _thd.next_drawstyle;
01961     }
01962   } else if (_thd.place_mode != HT_NONE) {
01963     Point pt = GetTileBelowCursor();
01964     x1 = pt.x;
01965     y1 = pt.y;
01966     if (x1 != -1) {
01967       switch (_thd.place_mode & HT_DRAG_MASK) {
01968         case HT_RECT:
01969           _thd.new_drawstyle = HT_RECT;
01970           break;
01971         case HT_POINT:
01972           _thd.new_drawstyle = HT_POINT;
01973           x1 += TILE_SIZE / 2;
01974           y1 += TILE_SIZE / 2;
01975           break;
01976         case HT_RAIL:
01977           /* Draw one highlighted tile in any direction */
01978           _thd.new_drawstyle = GetAutorailHT(pt.x, pt.y);
01979           break;
01980         case HT_LINE:
01981           switch (_thd.place_mode & HT_DIR_MASK) {
01982             case HT_DIR_X: _thd.new_drawstyle = HT_LINE | HT_DIR_X; break;
01983             case HT_DIR_Y: _thd.new_drawstyle = HT_LINE | HT_DIR_Y; break;
01984 
01985             case HT_DIR_HU:
01986             case HT_DIR_HL:
01987               _thd.new_drawstyle = (pt.x & TILE_UNIT_MASK) + (pt.y & TILE_UNIT_MASK) <= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
01988               break;
01989 
01990             case HT_DIR_VL:
01991             case HT_DIR_VR:
01992               _thd.new_drawstyle = (pt.x & TILE_UNIT_MASK) > (pt.y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
01993               break;
01994 
01995             default: NOT_REACHED();
01996           }
01997           _thd.selstart.x = x1 & ~TILE_UNIT_MASK;
01998           _thd.selstart.y = y1 & ~TILE_UNIT_MASK;
01999           break;
02000         default:
02001           NOT_REACHED();
02002           break;
02003       }
02004       _thd.new_pos.x = x1 & ~TILE_UNIT_MASK;
02005       _thd.new_pos.y = y1 & ~TILE_UNIT_MASK;
02006     }
02007   }
02008 
02009   /* redraw selection */
02010   if (_thd.drawstyle != _thd.new_drawstyle ||
02011       _thd.pos.x != _thd.new_pos.x || _thd.pos.y != _thd.new_pos.y ||
02012       _thd.size.x != _thd.new_size.x || _thd.size.y != _thd.new_size.y ||
02013       _thd.outersize.x != _thd.new_outersize.x ||
02014       _thd.outersize.y != _thd.new_outersize.y) {
02015     /* clear the old selection? */
02016     if (_thd.drawstyle) SetSelectionTilesDirty();
02017 
02018     _thd.drawstyle = _thd.new_drawstyle;
02019     _thd.pos = _thd.new_pos;
02020     _thd.size = _thd.new_size;
02021     _thd.outersize = _thd.new_outersize;
02022     _thd.dirty = 0xff;
02023 
02024     /* draw the new selection? */
02025     if (_thd.new_drawstyle) SetSelectionTilesDirty();
02026   }
02027 }
02028 
02034 static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const uint64 params[])
02035 {
02036   if (!_settings_client.gui.measure_tooltip) return;
02037   GuiShowTooltips(str, paramcount, params, true);
02038 }
02039 
02041 void VpStartPlaceSizing(TileIndex tile, ViewportPlaceMethod method, ViewportDragDropSelectionProcess process)
02042 {
02043   _thd.select_method = method;
02044   _thd.select_proc   = process;
02045   _thd.selend.x = TileX(tile) * TILE_SIZE;
02046   _thd.selstart.x = TileX(tile) * TILE_SIZE;
02047   _thd.selend.y = TileY(tile) * TILE_SIZE;
02048   _thd.selstart.y = TileY(tile) * TILE_SIZE;
02049 
02050   /* Needed so several things (road, autoroad, bridges, ...) are placed correctly.
02051    * In effect, placement starts from the centre of a tile
02052    */
02053   if (method == VPM_X_OR_Y || method == VPM_FIX_X || method == VPM_FIX_Y) {
02054     _thd.selend.x += TILE_SIZE / 2;
02055     _thd.selend.y += TILE_SIZE / 2;
02056     _thd.selstart.x += TILE_SIZE / 2;
02057     _thd.selstart.y += TILE_SIZE / 2;
02058   }
02059 
02060   if (_thd.place_mode == HT_RECT) {
02061     _thd.place_mode = HT_SPECIAL;
02062     _thd.next_drawstyle = HT_RECT;
02063   } else if (_thd.place_mode & (HT_RAIL | HT_LINE)) {
02064     _thd.place_mode = HT_SPECIAL;
02065     _thd.next_drawstyle = _thd.drawstyle;
02066   } else {
02067     _thd.place_mode = HT_SPECIAL;
02068     _thd.next_drawstyle = HT_POINT;
02069   }
02070   _special_mouse_mode = WSM_SIZING;
02071 }
02072 
02073 void VpSetPlaceSizingLimit(int limit)
02074 {
02075   _thd.sizelimit = limit;
02076 }
02077 
02082 void VpSetPresizeRange(TileIndex from, TileIndex to)
02083 {
02084   uint64 distance = DistanceManhattan(from, to) + 1;
02085 
02086   _thd.selend.x = TileX(to) * TILE_SIZE;
02087   _thd.selend.y = TileY(to) * TILE_SIZE;
02088   _thd.selstart.x = TileX(from) * TILE_SIZE;
02089   _thd.selstart.y = TileY(from) * TILE_SIZE;
02090   _thd.next_drawstyle = HT_RECT;
02091 
02092   /* show measurement only if there is any length to speak of */
02093   if (distance > 1) ShowMeasurementTooltips(STR_MEASURE_LENGTH, 1, &distance);
02094 }
02095 
02096 static void VpStartPreSizing()
02097 {
02098   _thd.selend.x = -1;
02099   _special_mouse_mode = WSM_PRESIZE;
02100 }
02101 
02104 static HighLightStyle Check2x1AutoRail(int mode)
02105 {
02106   int fxpy = _tile_fract_coords.x + _tile_fract_coords.y;
02107   int sxpy = (_thd.selend.x & TILE_UNIT_MASK) + (_thd.selend.y & TILE_UNIT_MASK);
02108   int fxmy = _tile_fract_coords.x - _tile_fract_coords.y;
02109   int sxmy = (_thd.selend.x & TILE_UNIT_MASK) - (_thd.selend.y & TILE_UNIT_MASK);
02110 
02111   switch (mode) {
02112     default: NOT_REACHED();
02113     case 0: // end piece is lower right
02114       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
02115       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
02116       return HT_DIR_Y;
02117 
02118     case 1:
02119       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
02120       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
02121       return HT_DIR_Y;
02122 
02123     case 2:
02124       if (fxmy > 3 && sxmy < -3) return HT_DIR_VL;
02125       if (fxpy >= 20 && sxpy <= 12) return HT_DIR_HL;
02126       return HT_DIR_X;
02127 
02128     case 3:
02129       if (fxmy < -3 && sxmy > 3) return HT_DIR_VR;
02130       if (fxpy <= 12 && sxpy >= 20) return HT_DIR_HU;
02131       return HT_DIR_X;
02132   }
02133 }
02134 
02146 static bool SwapDirection(HighLightStyle style, TileIndex start_tile, TileIndex end_tile)
02147 {
02148   uint start_x = TileX(start_tile);
02149   uint start_y = TileY(start_tile);
02150   uint end_x = TileX(end_tile);
02151   uint end_y = TileY(end_tile);
02152 
02153   switch (style & HT_DRAG_MASK) {
02154     case HT_RAIL:
02155     case HT_LINE: return (end_x > start_x || (end_x == start_x && end_y > start_y));
02156 
02157     case HT_RECT:
02158     case HT_POINT: return (end_x != start_x && end_y < start_y);
02159     default: NOT_REACHED();
02160   }
02161 
02162   return false;
02163 }
02164 
02179 static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_tile, TileIndex end_tile)
02180 {
02181   bool swap = SwapDirection(style, start_tile, end_tile);
02182   byte style_t;
02183   uint h0, h1, ht; // start heigth, end height, and temp variable
02184 
02185   if (start_tile == end_tile) return 0;
02186   if (swap) Swap(start_tile, end_tile);
02187 
02188   switch (style & HT_DRAG_MASK) {
02189     case HT_RECT: {
02190       static const TileIndexDiffC heightdiff_area_by_dir[] = {
02191         /* Start */ {1, 0}, /* Dragging east */ {0, 0}, // Dragging south
02192         /* End   */ {0, 1}, /* Dragging east */ {1, 1}  // Dragging south
02193       };
02194 
02195       /* In the case of an area we can determine whether we were dragging south or
02196        * east by checking the X-coordinates of the tiles */
02197       style_t = (byte)(TileX(end_tile) > TileX(start_tile));
02198       start_tile = TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_area_by_dir[style_t]));
02199       end_tile   = TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_area_by_dir[2 + style_t]));
02200     }
02201     /* Fallthrough */
02202     case HT_POINT:
02203       h0 = TileHeight(start_tile);
02204       h1 = TileHeight(end_tile);
02205       break;
02206     default: { // All other types, this is mostly only line/autorail
02207       static const HighLightStyle flip_style_direction[] = {
02208         HT_DIR_X, HT_DIR_Y, HT_DIR_HL, HT_DIR_HU, HT_DIR_VR, HT_DIR_VL
02209       };
02210       static const TileIndexDiffC heightdiff_line_by_dir[] = {
02211         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_X  */ {0, 1}, {1, 1}, // HT_DIR_Y
02212         /* Start */ {1, 0}, {0, 0}, /* HT_DIR_HU */ {1, 0}, {1, 1}, // HT_DIR_HL
02213         /* Start */ {1, 0}, {1, 1}, /* HT_DIR_VL */ {0, 1}, {1, 1}, // HT_DIR_VR
02214 
02215         /* Start */ {0, 1}, {0, 0}, /* HT_DIR_X  */ {1, 0}, {0, 0}, // HT_DIR_Y
02216         /* End   */ {0, 1}, {0, 0}, /* HT_DIR_HU */ {1, 1}, {0, 1}, // HT_DIR_HL
02217         /* End   */ {1, 0}, {0, 0}, /* HT_DIR_VL */ {0, 0}, {0, 1}, // HT_DIR_VR
02218       };
02219 
02220       distance %= 2; // we're only interested if the distance is even or uneven
02221       style &= HT_DIR_MASK;
02222 
02223       /* To handle autorail, we do some magic to be able to use a lookup table.
02224        * Firstly if we drag the other way around, we switch start&end, and if needed
02225        * also flip the drag-position. Eg if it was on the left, and the distance is even
02226        * that means the end, which is now the start is on the right */
02227       if (swap && distance == 0) style = flip_style_direction[style];
02228 
02229       /* Use lookup table for start-tile based on HighLightStyle direction */
02230       style_t = style * 2;
02231       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
02232       h0 = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
02233       ht = TileHeight(TILE_ADD(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
02234       h0 = max(h0, ht);
02235 
02236       /* Use lookup table for end-tile based on HighLightStyle direction
02237        * flip around side (lower/upper, left/right) based on distance */
02238       if (distance == 0) style_t = flip_style_direction[style] * 2;
02239       assert(style_t < lengthof(heightdiff_line_by_dir) - 13);
02240       h1 = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
02241       ht = TileHeight(TILE_ADD(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
02242       h1 = max(h1, ht);
02243     } break;
02244   }
02245 
02246   if (swap) Swap(h0, h1);
02247   /* Minimap shows height in intervals of 25 meters, let's do the same */
02248   return (int)(h1 - h0) * 25;
02249 }
02250 
02251 static const StringID measure_strings_length[] = {STR_NULL, STR_MEASURE_LENGTH, STR_MEASURE_LENGTH_HEIGHTDIFF};
02252 
02259 static void CheckUnderflow(int &test, int &other, int mult)
02260 {
02261   if (test >= 0) return;
02262 
02263   other += mult * test;
02264   test = 0;
02265 }
02266 
02274 static void CheckOverflow(int &test, int &other, int max, int mult)
02275 {
02276   if (test <= max) return;
02277 
02278   other += mult * (test - max);
02279   test = max;
02280 }
02281 
02283 static void CalcRaildirsDrawstyle(TileHighlightData *thd, int x, int y, int method)
02284 {
02285   HighLightStyle b;
02286 
02287   int dx = thd->selstart.x - (thd->selend.x & ~TILE_UNIT_MASK);
02288   int dy = thd->selstart.y - (thd->selend.y & ~TILE_UNIT_MASK);
02289   uint w = abs(dx) + TILE_SIZE;
02290   uint h = abs(dy) + TILE_SIZE;
02291 
02292   if (method & ~(VPM_RAILDIRS | VPM_SIGNALDIRS)) {
02293     /* We 'force' a selection direction; first four rail buttons. */
02294     method &= ~(VPM_RAILDIRS | VPM_SIGNALDIRS);
02295     int raw_dx = thd->selstart.x - thd->selend.x;
02296     int raw_dy = thd->selstart.y - thd->selend.y;
02297     switch (method) {
02298       case VPM_FIX_X:
02299         b = HT_LINE | HT_DIR_Y;
02300         x = thd->selstart.x;
02301         break;
02302 
02303       case VPM_FIX_Y:
02304         b = HT_LINE | HT_DIR_X;
02305         y = thd->selstart.y;
02306         break;
02307 
02308       case VPM_FIX_HORIZONTAL:
02309         if (dx == -dy) {
02310           /* We are on a straight horizontal line. Determine the 'rail'
02311            * to build based the sub tile location. */
02312           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
02313         } else {
02314           /* We are not on a straight line. Determine the rail to build
02315            * based on whether we are above or below it. */
02316           b = dx + dy >= TILE_SIZE ? HT_LINE | HT_DIR_HU : HT_LINE | HT_DIR_HL;
02317 
02318           /* Calculate where a horizontal line through the start point and
02319            * a vertical line from the selected end point intersect and
02320            * use that point as the end point. */
02321           int offset = (raw_dx - raw_dy) / 2;
02322           x = thd->selstart.x - (offset & ~TILE_UNIT_MASK);
02323           y = thd->selstart.y + (offset & ~TILE_UNIT_MASK);
02324 
02325           /* 'Build' the last half rail tile if needed */
02326           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
02327             if (dx + dy >= TILE_SIZE) {
02328               x += (dx + dy < 0) ? TILE_SIZE : -TILE_SIZE;
02329             } else {
02330               y += (dx + dy < 0) ? TILE_SIZE : -TILE_SIZE;
02331             }
02332           }
02333 
02334           /* Make sure we do not overflow the map! */
02335           CheckUnderflow(x, y, 1);
02336           CheckUnderflow(y, x, 1);
02337           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, 1);
02338           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, 1);
02339           assert(x >= 0 && y >= 0 && x <= (int)MapMaxX() * TILE_SIZE && y <= (int)MapMaxY() * TILE_SIZE);
02340         }
02341         break;
02342 
02343       case VPM_FIX_VERTICAL:
02344         if (dx == dy) {
02345           /* We are on a straight vertical line. Determine the 'rail'
02346            * to build based the sub tile location. */
02347           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02348         } else {
02349           /* We are not on a straight line. Determine the rail to build
02350            * based on whether we are left or right from it. */
02351           b = dx < dy ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02352 
02353           /* Calculate where a vertical line through the start point and
02354            * a horizontal line from the selected end point intersect and
02355            * use that point as the end point. */
02356           int offset = (raw_dx + raw_dy + TILE_SIZE) / 2;
02357           x = thd->selstart.x - (offset & ~TILE_UNIT_MASK);
02358           y = thd->selstart.y - (offset & ~TILE_UNIT_MASK);
02359 
02360           /* 'Build' the last half rail tile if needed */
02361           if ((offset & TILE_UNIT_MASK) > (TILE_SIZE / 2)) {
02362             if (dx - dy < 0) {
02363               y += (dx > dy) ? TILE_SIZE : -TILE_SIZE;
02364             } else {
02365               x += (dx < dy) ? TILE_SIZE : -TILE_SIZE;
02366             }
02367           }
02368 
02369           /* Make sure we do not overflow the map! */
02370           CheckUnderflow(x, y, -1);
02371           CheckUnderflow(y, x, -1);
02372           CheckOverflow(x, y, (MapMaxX() - 1) * TILE_SIZE, -1);
02373           CheckOverflow(y, x, (MapMaxY() - 1) * TILE_SIZE, -1);
02374           assert(x >= 0 && y >= 0 && x <= (int)MapMaxX() * TILE_SIZE && y <= (int)MapMaxY() * TILE_SIZE);
02375         }
02376         break;
02377 
02378       default:
02379         NOT_REACHED();
02380     }
02381   } else if (TileVirtXY(thd->selstart.x, thd->selstart.y) == TileVirtXY(x, y)) { // check if we're only within one tile
02382     if (method & VPM_RAILDIRS) {
02383       b = GetAutorailHT(x, y);
02384     } else { // rect for autosignals on one tile
02385       b = HT_RECT;
02386     }
02387   } else if (h == TILE_SIZE) { // Is this in X direction?
02388     if (dx == TILE_SIZE) { // 2x1 special handling
02389       b = (Check2x1AutoRail(3)) | HT_LINE;
02390     } else if (dx == -TILE_SIZE) {
02391       b = (Check2x1AutoRail(2)) | HT_LINE;
02392     } else {
02393       b = HT_LINE | HT_DIR_X;
02394     }
02395     y = thd->selstart.y;
02396   } else if (w == TILE_SIZE) { // Or Y direction?
02397     if (dy == TILE_SIZE) { // 2x1 special handling
02398       b = (Check2x1AutoRail(1)) | HT_LINE;
02399     } else if (dy == -TILE_SIZE) { // 2x1 other direction
02400       b = (Check2x1AutoRail(0)) | HT_LINE;
02401     } else {
02402       b = HT_LINE | HT_DIR_Y;
02403     }
02404     x = thd->selstart.x;
02405   } else if (w > h * 2) { // still count as x dir?
02406     b = HT_LINE | HT_DIR_X;
02407     y = thd->selstart.y;
02408   } else if (h > w * 2) { // still count as y dir?
02409     b = HT_LINE | HT_DIR_Y;
02410     x = thd->selstart.x;
02411   } else { // complicated direction
02412     int d = w - h;
02413     thd->selend.x = thd->selend.x & ~TILE_UNIT_MASK;
02414     thd->selend.y = thd->selend.y & ~TILE_UNIT_MASK;
02415 
02416     /* four cases. */
02417     if (x > thd->selstart.x) {
02418       if (y > thd->selstart.y) {
02419         /* south */
02420         if (d == 0) {
02421           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02422         } else if (d >= 0) {
02423           x = thd->selstart.x + h;
02424           b = HT_LINE | HT_DIR_VL;
02425         } else {
02426           y = thd->selstart.y + w;
02427           b = HT_LINE | HT_DIR_VR;
02428         }
02429       } else {
02430         /* west */
02431         if (d == 0) {
02432           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
02433         } else if (d >= 0) {
02434           x = thd->selstart.x + h;
02435           b = HT_LINE | HT_DIR_HL;
02436         } else {
02437           y = thd->selstart.y - w;
02438           b = HT_LINE | HT_DIR_HU;
02439         }
02440       }
02441     } else {
02442       if (y > thd->selstart.y) {
02443         /* east */
02444         if (d == 0) {
02445           b = (x & TILE_UNIT_MASK) + (y & TILE_UNIT_MASK) >= TILE_SIZE ? HT_LINE | HT_DIR_HL : HT_LINE | HT_DIR_HU;
02446         } else if (d >= 0) {
02447           x = thd->selstart.x - h;
02448           b = HT_LINE | HT_DIR_HU;
02449         } else {
02450           y = thd->selstart.y + w;
02451           b = HT_LINE | HT_DIR_HL;
02452         }
02453       } else {
02454         /* north */
02455         if (d == 0) {
02456           b = (x & TILE_UNIT_MASK) > (y & TILE_UNIT_MASK) ? HT_LINE | HT_DIR_VL : HT_LINE | HT_DIR_VR;
02457         } else if (d >= 0) {
02458           x = thd->selstart.x - h;
02459           b = HT_LINE | HT_DIR_VR;
02460         } else {
02461           y = thd->selstart.y - w;
02462           b = HT_LINE | HT_DIR_VL;
02463         }
02464       }
02465     }
02466   }
02467 
02468   if (_settings_client.gui.measure_tooltip) {
02469     TileIndex t0 = TileVirtXY(thd->selstart.x, thd->selstart.y);
02470     TileIndex t1 = TileVirtXY(x, y);
02471     uint distance = DistanceManhattan(t0, t1) + 1;
02472     byte index = 0;
02473     uint64 params[2];
02474 
02475     if (distance != 1) {
02476       int heightdiff = CalcHeightdiff(b, distance, t0, t1);
02477       /* If we are showing a tooltip for horizontal or vertical drags,
02478        * 2 tiles have a length of 1. To bias towards the ceiling we add
02479        * one before division. It feels more natural to count 3 lengths as 2 */
02480       if ((b & HT_DIR_MASK) != HT_DIR_X && (b & HT_DIR_MASK) != HT_DIR_Y) {
02481         distance = (distance + 1) / 2;
02482       }
02483 
02484       params[index++] = distance;
02485       if (heightdiff != 0) params[index++] = heightdiff;
02486     }
02487 
02488     ShowMeasurementTooltips(measure_strings_length[index], index, params);
02489   }
02490 
02491   thd->selend.x = x;
02492   thd->selend.y = y;
02493   thd->next_drawstyle = b;
02494 }
02495 
02502 void VpSelectTilesWithMethod(int x, int y, ViewportPlaceMethod method)
02503 {
02504   int sx, sy;
02505   HighLightStyle style;
02506 
02507   if (x == -1) {
02508     _thd.selend.x = -1;
02509     return;
02510   }
02511 
02512   /* Special handling of drag in any (8-way) direction */
02513   if (method & (VPM_RAILDIRS | VPM_SIGNALDIRS)) {
02514     _thd.selend.x = x;
02515     _thd.selend.y = y;
02516     CalcRaildirsDrawstyle(&_thd, x, y, method);
02517     return;
02518   }
02519 
02520   /* Needed so level-land is placed correctly */
02521   if (_thd.next_drawstyle == HT_POINT) {
02522     x += TILE_SIZE / 2;
02523     y += TILE_SIZE / 2;
02524   }
02525 
02526   sx = _thd.selstart.x;
02527   sy = _thd.selstart.y;
02528 
02529   int limit = 0;
02530 
02531   switch (method) {
02532     case VPM_X_OR_Y: // drag in X or Y direction
02533       if (abs(sy - y) < abs(sx - x)) {
02534         y = sy;
02535         style = HT_DIR_X;
02536       } else {
02537         x = sx;
02538         style = HT_DIR_Y;
02539       }
02540       goto calc_heightdiff_single_direction;
02541 
02542     case VPM_X_LIMITED: // Drag in X direction (limited size).
02543       limit = (_thd.sizelimit - 1) * TILE_SIZE;
02544       /* Fallthrough. */
02545 
02546     case VPM_FIX_X: // drag in Y direction
02547       x = sx;
02548       style = HT_DIR_Y;
02549       goto calc_heightdiff_single_direction;
02550 
02551     case VPM_Y_LIMITED: // Drag in Y direction (limited size).
02552       limit = (_thd.sizelimit - 1) * TILE_SIZE;
02553       /* Fallthrough. */
02554 
02555     case VPM_FIX_Y: // drag in X direction
02556       y = sy;
02557       style = HT_DIR_X;
02558 
02559 calc_heightdiff_single_direction:;
02560       if (limit > 0) {
02561         x = sx + Clamp(x - sx, -limit, limit);
02562         y = sy + Clamp(y - sy, -limit, limit);
02563       }
02564       if (_settings_client.gui.measure_tooltip) {
02565         TileIndex t0 = TileVirtXY(sx, sy);
02566         TileIndex t1 = TileVirtXY(x, y);
02567         uint distance = DistanceManhattan(t0, t1) + 1;
02568         byte index = 0;
02569         uint64 params[2];
02570 
02571         if (distance != 1) {
02572           /* With current code passing a HT_LINE style to calculate the height
02573            * difference is enough. However if/when a point-tool is created
02574            * with this method, function should be called with new_style (below)
02575            * instead of HT_LINE | style case HT_POINT is handled specially
02576            * new_style := (_thd.next_drawstyle & HT_RECT) ? HT_LINE | style : _thd.next_drawstyle; */
02577           int heightdiff = CalcHeightdiff(HT_LINE | style, 0, t0, t1);
02578 
02579           params[index++] = distance;
02580           if (heightdiff != 0) params[index++] = heightdiff;
02581         }
02582 
02583         ShowMeasurementTooltips(measure_strings_length[index], index, params);
02584       } break;
02585 
02586     case VPM_X_AND_Y_LIMITED: // Drag an X by Y constrained rect area.
02587       limit = (_thd.sizelimit - 1) * TILE_SIZE;
02588       x = sx + Clamp(x - sx, -limit, limit);
02589       y = sy + Clamp(y - sy, -limit, limit);
02590       /* Fallthrough. */
02591 
02592     case VPM_X_AND_Y: { // drag an X by Y area
02593       if (_settings_client.gui.measure_tooltip) {
02594         static const StringID measure_strings_area[] = {
02595           STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
02596         };
02597 
02598         TileIndex t0 = TileVirtXY(sx, sy);
02599         TileIndex t1 = TileVirtXY(x, y);
02600         uint dx = Delta(TileX(t0), TileX(t1)) + 1;
02601         uint dy = Delta(TileY(t0), TileY(t1)) + 1;
02602         byte index = 0;
02603         uint64 params[3];
02604 
02605         /* If dragging an area (eg dynamite tool) and it is actually a single
02606          * row/column, change the type to 'line' to get proper calculation for height */
02607         style = (HighLightStyle)_thd.next_drawstyle;
02608         if (style & HT_RECT) {
02609           if (dx == 1) {
02610             style = HT_LINE | HT_DIR_Y;
02611           } else if (dy == 1) {
02612             style = HT_LINE | HT_DIR_X;
02613           }
02614         }
02615 
02616         if (dx != 1 || dy != 1) {
02617           int heightdiff = CalcHeightdiff(style, 0, t0, t1);
02618 
02619           params[index++] = dx;
02620           params[index++] = dy;
02621           if (heightdiff != 0) params[index++] = heightdiff;
02622         }
02623 
02624         ShowMeasurementTooltips(measure_strings_area[index], index, params);
02625       }
02626     break;
02627 
02628     }
02629     default: NOT_REACHED();
02630   }
02631 
02632   _thd.selend.x = x;
02633   _thd.selend.y = y;
02634 }
02635 
02640 bool VpHandlePlaceSizingDrag()
02641 {
02642   if (_special_mouse_mode != WSM_SIZING) return true;
02643 
02644   /* stop drag mode if the window has been closed */
02645   Window *w = FindWindowById(_thd.window_class, _thd.window_number);
02646   if (w == NULL) {
02647     ResetObjectToPlace();
02648     return false;
02649   }
02650 
02651   /* while dragging execute the drag procedure of the corresponding window (mostly VpSelectTilesWithMethod() ) */
02652   if (_left_button_down) {
02653     w->OnPlaceDrag(_thd.select_method, _thd.select_proc, GetTileBelowCursor());
02654     return false;
02655   }
02656 
02657   /* mouse button released..
02658    * keep the selected tool, but reset it to the original mode. */
02659   _special_mouse_mode = WSM_NONE;
02660   if (_thd.next_drawstyle == HT_RECT) {
02661     _thd.place_mode = HT_RECT;
02662   } else if (_thd.select_method & VPM_SIGNALDIRS) {
02663     _thd.place_mode = HT_RECT;
02664   } else if (_thd.select_method & VPM_RAILDIRS) {
02665     _thd.place_mode = (_thd.select_method & ~VPM_RAILDIRS) ? _thd.next_drawstyle : HT_RAIL;
02666   } else {
02667     _thd.place_mode = HT_POINT;
02668   }
02669   SetTileSelectSize(1, 1);
02670 
02671   w->OnPlaceMouseUp(_thd.select_method, _thd.select_proc, _thd.selend, TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y));
02672 
02673   return false;
02674 }
02675 
02676 void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
02677 {
02678   SetObjectToPlace(icon, pal, mode, w->window_class, w->window_number);
02679 }
02680 
02681 #include "table/animcursors.h"
02682 
02683 void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
02684 {
02685   /* undo clicking on button and drag & drop */
02686   if (_thd.place_mode != HT_NONE || _special_mouse_mode == WSM_DRAGDROP) {
02687     Window *w = FindWindowById(_thd.window_class, _thd.window_number);
02688     if (w != NULL) {
02689       /* Call the abort function, but set the window class to something
02690        * that will never be used to avoid infinite loops. Setting it to
02691        * the 'next' window class must not be done because recursion into
02692        * this function might in some cases reset the newly set object to
02693        * place or not properly reset the original selection. */
02694       _thd.window_class = WC_INVALID;
02695       w->OnPlaceObjectAbort();
02696     }
02697   }
02698 
02699   SetTileSelectSize(1, 1);
02700 
02701   _thd.make_square_red = false;
02702 
02703   if (mode == HT_DRAG) { // HT_DRAG is for dragdropping trains in the depot window
02704     mode = HT_NONE;
02705     _special_mouse_mode = WSM_DRAGDROP;
02706   } else {
02707     _special_mouse_mode = WSM_NONE;
02708   }
02709 
02710   _thd.place_mode = mode;
02711   _thd.window_class = window_class;
02712   _thd.window_number = window_num;
02713 
02714   if (mode == HT_SPECIAL) // special tools, like tunnels or docks start with presizing mode
02715     VpStartPreSizing();
02716 
02717   if ((icon & ANIMCURSOR_FLAG) != 0) {
02718     SetAnimatedMouseCursor(_animcursors[icon & ~ANIMCURSOR_FLAG]);
02719   } else {
02720     SetMouseCursor(icon, pal);
02721   }
02722 
02723 }
02724 
02725 void ResetObjectToPlace()
02726 {
02727   SetObjectToPlace(SPR_CURSOR_MOUSE, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
02728 }

Generated on Sat Jun 19 17:14:56 2010 for OpenTTD by  doxygen 1.6.1