gfx.cpp

Go to the documentation of this file.
00001 /* $Id: gfx.cpp 26018 2013-11-16 21:05:26Z 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 
00012 #include "stdafx.h"
00013 #include "gfx_layout.h"
00014 #include "progress.h"
00015 #include "zoom_func.h"
00016 #include "blitter/factory.hpp"
00017 #include "video/video_driver.hpp"
00018 #include "strings_func.h"
00019 #include "settings_type.h"
00020 #include "network/network.h"
00021 #include "network/network_func.h"
00022 #include "window_func.h"
00023 #include "newgrf_debug.h"
00024 
00025 #include "table/palettes.h"
00026 #include "table/sprites.h"
00027 #include "table/control_codes.h"
00028 
00029 byte _dirkeys;        
00030 bool _fullscreen;
00031 CursorVars _cursor;
00032 bool _ctrl_pressed;   
00033 bool _shift_pressed;  
00034 byte _fast_forward;
00035 bool _left_button_down;     
00036 bool _left_button_clicked;  
00037 bool _right_button_down;    
00038 bool _right_button_clicked; 
00039 DrawPixelInfo _screen;
00040 bool _screen_disable_anim = false;   
00041 bool _exit_game;
00042 GameMode _game_mode;
00043 SwitchMode _switch_mode;  
00044 PauseModeByte _pause_mode;
00045 Palette _cur_palette;
00046 
00047 static byte _stringwidth_table[FS_END][224]; 
00048 DrawPixelInfo *_cur_dpi;
00049 byte _colour_gradient[COLOUR_END][8];
00050 
00051 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
00052 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZOOM_LVL_NORMAL);
00053 
00054 static ReusableBuffer<uint8> _cursor_backup;
00055 
00063 static Rect _invalid_rect;
00064 static const byte *_colour_remap_ptr;
00065 static byte _string_colourremap[3]; 
00066 
00067 static const uint DIRTY_BLOCK_HEIGHT   = 8;
00068 static const uint DIRTY_BLOCK_WIDTH    = 64;
00069 
00070 static uint _dirty_bytes_per_line = 0;
00071 static byte *_dirty_blocks = NULL;
00072 extern uint _dirty_block_colour;
00073 
00074 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
00075 {
00076   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00077 
00078   if (xo == 0 && yo == 0) return;
00079 
00080   if (_cursor.visible) UndrawMouseCursor();
00081 
00082 #ifdef ENABLE_NETWORK
00083   if (_networking) NetworkUndrawChatMessage();
00084 #endif /* ENABLE_NETWORK */
00085 
00086   blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
00087   /* This part of the screen is now dirty. */
00088   _video_driver->MakeDirty(left, top, width, height);
00089 }
00090 
00091 
00106 void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
00107 {
00108   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00109   const DrawPixelInfo *dpi = _cur_dpi;
00110   void *dst;
00111   const int otop = top;
00112   const int oleft = left;
00113 
00114   if (dpi->zoom != ZOOM_LVL_NORMAL) return;
00115   if (left > right || top > bottom) return;
00116   if (right < dpi->left || left >= dpi->left + dpi->width) return;
00117   if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
00118 
00119   if ( (left -= dpi->left) < 0) left = 0;
00120   right = right - dpi->left + 1;
00121   if (right > dpi->width) right = dpi->width;
00122   right -= left;
00123   assert(right > 0);
00124 
00125   if ( (top -= dpi->top) < 0) top = 0;
00126   bottom = bottom - dpi->top + 1;
00127   if (bottom > dpi->height) bottom = dpi->height;
00128   bottom -= top;
00129   assert(bottom > 0);
00130 
00131   dst = blitter->MoveTo(dpi->dst_ptr, left, top);
00132 
00133   switch (mode) {
00134     default: // FILLRECT_OPAQUE
00135       blitter->DrawRect(dst, right, bottom, (uint8)colour);
00136       break;
00137 
00138     case FILLRECT_RECOLOUR:
00139       blitter->DrawColourMappingRect(dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
00140       break;
00141 
00142     case FILLRECT_CHECKER: {
00143       byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
00144       do {
00145         for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
00146         dst = blitter->MoveTo(dst, 0, 1);
00147       } while (--bottom > 0);
00148       break;
00149     }
00150   }
00151 }
00152 
00167 static inline void GfxDoDrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8 colour, int width, int dash = 0)
00168 {
00169   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00170 
00171   assert(width > 0);
00172 
00173   if (y2 == y) {
00174     /* Special case: horizontal line. */
00175     blitter->DrawLine(video,
00176         Clamp(x, 0, screen_width), y,
00177         Clamp(x2, 0, screen_width), y2,
00178         screen_width, screen_height, colour, width, dash);
00179     return;
00180   }
00181   if (x2 == x) {
00182     /* Special case: vertical line. */
00183     blitter->DrawLine(video,
00184         x, Clamp(y, 0, screen_height),
00185         x2, Clamp(y2, 0, screen_height),
00186         screen_width, screen_height, colour, width, dash);
00187     return;
00188   }
00189 
00190   int grade_y = y2 - y;
00191   int grade_x = x2 - x;
00192 
00193   /* prevent integer overflows. */
00194   int margin = 1;
00195   while (INT_MAX / abs(grade_y) < max(abs(x), abs(screen_width - x))) {
00196     grade_y /= 2;
00197     grade_x /= 2;
00198     margin  *= 2; // account for rounding errors
00199   }
00200 
00201   /* If the line is outside the screen on the same side at X positions 0
00202    * and screen_width, we don't need to draw anything. */
00203   int offset_0 = y - x * grade_y / grade_x;
00204   int offset_width = y + (screen_width - x) * grade_y / grade_x;
00205   if ((offset_0 > screen_height + width / 2 + margin && offset_width > screen_height + width / 2 + margin) ||
00206       (offset_0 < -width / 2 - margin && offset_width < -width / 2 - margin)) {
00207     return;
00208   }
00209 
00210   /* It is possible to use the line equation to further reduce the amount of
00211    * work the blitter has to do by shortening the effective line segment.
00212    * However, in order to get that right and prevent the flickering effects
00213    * of rounding errors so much additional code has to be run here that in
00214    * the general case the effect is not noticable. */
00215 
00216   blitter->DrawLine(video, x, y, x2, y2, screen_width, screen_height, colour, width, dash);
00217 }
00218 
00230 static inline bool GfxPreprocessLine(DrawPixelInfo *dpi, int &x, int &y, int &x2, int &y2, int width)
00231 {
00232   x -= dpi->left;
00233   x2 -= dpi->left;
00234   y -= dpi->top;
00235   y2 -= dpi->top;
00236 
00237   /* Check simple clipping */
00238   if (x + width / 2 < 0           && x2 + width / 2 < 0          ) return false;
00239   if (y + width / 2 < 0           && y2 + width / 2 < 0          ) return false;
00240   if (x - width / 2 > dpi->width  && x2 - width / 2 > dpi->width ) return false;
00241   if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return false;
00242   return true;
00243 }
00244 
00245 void GfxDrawLine(int x, int y, int x2, int y2, int colour, int width, int dash)
00246 {
00247   DrawPixelInfo *dpi = _cur_dpi;
00248   if (GfxPreprocessLine(dpi, x, y, x2, y2, width)) {
00249     GfxDoDrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour, width, dash);
00250   }
00251 }
00252 
00253 void GfxDrawLineUnscaled(int x, int y, int x2, int y2, int colour)
00254 {
00255   DrawPixelInfo *dpi = _cur_dpi;
00256   if (GfxPreprocessLine(dpi, x, y, x2, y2, 1)) {
00257     GfxDoDrawLine(dpi->dst_ptr,
00258         UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
00259         UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
00260         UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
00261   }
00262 }
00263 
00277 void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
00278 {
00279   /*           ....
00280    *         ..    ....
00281    *       ..          ....
00282    *     ..                ^
00283    *   <--__(dx1,dy1)    /(dx2,dy2)
00284    *   :    --__       /   :
00285    *   :        --__ /     :
00286    *   :            *(x,y) :
00287    *   :            |      :
00288    *   :            |     ..
00289    *    ....        |(dx3,dy3)
00290    *        ....    | ..
00291    *            ....V.
00292    */
00293 
00294   static const byte colour = PC_WHITE;
00295 
00296   GfxDrawLineUnscaled(x, y, x + dx1, y + dy1, colour);
00297   GfxDrawLineUnscaled(x, y, x + dx2, y + dy2, colour);
00298   GfxDrawLineUnscaled(x, y, x + dx3, y + dy3, colour);
00299 
00300   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
00301   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
00302   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
00303   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
00304   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
00305   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
00306 }
00307 
00312 static void SetColourRemap(TextColour colour)
00313 {
00314   if (colour == TC_INVALID) return;
00315 
00316   /* Black strings have no shading ever; the shading is black, so it
00317    * would be invisible at best, but it actually makes it illegible. */
00318   bool no_shade   = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
00319   bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
00320   colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
00321 
00322   _string_colourremap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
00323   _string_colourremap[2] = no_shade ? 0 : 1;
00324   _colour_remap_ptr = _string_colourremap;
00325 }
00326 
00342 static int DrawLayoutLine(const ParagraphLayouter::Line *line, int y, int left, int right, StringAlignment align, bool underline, bool truncation)
00343 {
00344   if (line->CountRuns() == 0) return 0;
00345 
00346   int w = line->GetWidth();
00347   int h = line->GetLeading();
00348 
00349   /*
00350    * The following is needed for truncation.
00351    * Depending on the text direction, we either remove bits at the rear
00352    * or the front. For this we shift the entire area to draw so it fits
00353    * within the left/right bounds and the side we do not truncate it on.
00354    * Then we determine the truncation location, i.e. glyphs that fall
00355    * outside of the range min_x - max_x will not be drawn; they are thus
00356    * the truncated glyphs.
00357    *
00358    * At a later step we insert the dots.
00359    */
00360 
00361   int max_w = right - left + 1; // The maximum width.
00362 
00363   int offset_x = 0;  // The offset we need for positioning the glyphs
00364   int min_x = left;  // The minimum x position to draw normal glyphs on.
00365   int max_x = right; // The maximum x position to draw normal glyphs on.
00366 
00367   truncation &= max_w < w;         // Whether we need to do truncation.
00368   int dot_width = 0;               // Cache for the width of the dot.
00369   const Sprite *dot_sprite = NULL; // Cache for the sprite of the dot.
00370 
00371   if (truncation) {
00372     /*
00373      * Assumption may be made that all fonts of a run are of the same size.
00374      * In any case, we'll use these dots for the abbreviation, so even if
00375      * another size would be chosen it won't have truncated too little for
00376      * the truncation dots.
00377      */
00378     FontCache *fc = ((const Font*)line->GetVisualRun(0)->GetFont())->fc;
00379     GlyphID dot_glyph = fc->MapCharToGlyph('.');
00380     dot_width = fc->GetGlyphWidth(dot_glyph);
00381     dot_sprite = fc->GetGlyph(dot_glyph);
00382 
00383     if (_current_text_dir == TD_RTL) {
00384       min_x += 3 * dot_width;
00385       offset_x = w - 3 * dot_width - max_w;
00386     } else {
00387       max_x -= 3 * dot_width;
00388     }
00389 
00390     w = max_w;
00391   }
00392 
00393   /* In case we have a RTL language we swap the alignment. */
00394   if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
00395 
00396   /* right is the right most position to draw on. In this case we want to do
00397    * calculations with the width of the string. In comparison right can be
00398    * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
00399    * So most +1/-1 additions are to move from lengthof to 'indices'.
00400    */
00401   switch (align & SA_HOR_MASK) {
00402     case SA_LEFT:
00403       /* right + 1 = left + w */
00404       right = left + w - 1;
00405       break;
00406 
00407     case SA_HOR_CENTER:
00408       left  = RoundDivSU(right + 1 + left - w, 2);
00409       /* right + 1 = left + w */
00410       right = left + w - 1;
00411       break;
00412 
00413     case SA_RIGHT:
00414       left = right + 1 - w;
00415       break;
00416 
00417     default:
00418       NOT_REACHED();
00419   }
00420 
00421   for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
00422     const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index);
00423     const Font *f = (const Font*)run->GetFont();
00424 
00425     FontCache *fc = f->fc;
00426     TextColour colour = f->colour;
00427     SetColourRemap(colour);
00428 
00429     DrawPixelInfo *dpi = _cur_dpi;
00430     int dpi_left  = dpi->left;
00431     int dpi_right = dpi->left + dpi->width - 1;
00432 
00433     bool draw_shadow = fc->GetDrawGlyphShadow() && colour != TC_BLACK;
00434 
00435     for (int i = 0; i < run->GetGlyphCount(); i++) {
00436       GlyphID glyph = run->GetGlyphs()[i];
00437 
00438       /* Not a valid glyph (empty) */
00439       if (glyph == 0xFFFF) continue;
00440 
00441       int begin_x = (int)run->GetPositions()[i * 2]     + left - offset_x;
00442       int end_x   = (int)run->GetPositions()[i * 2 + 2] + left - offset_x  - 1;
00443       int top     = (int)run->GetPositions()[i * 2 + 1] + y;
00444 
00445       /* Truncated away. */
00446       if (truncation && (begin_x < min_x || end_x > max_x)) continue;
00447 
00448       const Sprite *sprite = fc->GetGlyph(glyph);
00449       /* Check clipping (the "+ 1" is for the shadow). */
00450       if (begin_x + sprite->x_offs > dpi_right || begin_x + sprite->x_offs + sprite->width /* - 1 + 1 */ < dpi_left) continue;
00451 
00452       if (draw_shadow && (glyph & SPRITE_GLYPH) == 0) {
00453         SetColourRemap(TC_BLACK);
00454         GfxMainBlitter(sprite, begin_x + 1, top + 1, BM_COLOUR_REMAP);
00455         SetColourRemap(colour);
00456       }
00457       GfxMainBlitter(sprite, begin_x, top, BM_COLOUR_REMAP);
00458     }
00459   }
00460 
00461   if (truncation) {
00462     int x = (_current_text_dir == TD_RTL) ? left : (right - 3 * dot_width);
00463     for (int i = 0; i < 3; i++, x += dot_width) {
00464       GfxMainBlitter(dot_sprite, x, y, BM_COLOUR_REMAP);
00465     }
00466   }
00467 
00468   if (underline) {
00469     GfxFillRect(left, y + h, right, y + h, _string_colourremap[1]);
00470   }
00471 
00472   return (align & SA_HOR_MASK) == SA_RIGHT ? left : right;
00473 }
00474 
00491 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00492 {
00493   /* The string may contain control chars to change the font, just use the biggest font for clipping. */
00494   int max_height = max(max(FONT_HEIGHT_SMALL, FONT_HEIGHT_NORMAL), max(FONT_HEIGHT_LARGE, FONT_HEIGHT_MONO));
00495 
00496   /* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
00497   int extra = max_height / 2;
00498 
00499   if (_cur_dpi->top + _cur_dpi->height + extra < top || _cur_dpi->top > top + max_height + extra ||
00500       _cur_dpi->left + _cur_dpi->width + extra < left || _cur_dpi->left > right + extra) {
00501     return 0;
00502   }
00503 
00504   Layouter layout(str, INT32_MAX, colour, fontsize);
00505   if (layout.Length() == 0) return 0;
00506 
00507   return DrawLayoutLine(*layout.Begin(), top, left, right, align, underline, true);
00508 }
00509 
00526 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00527 {
00528   char buffer[DRAW_STRING_BUFFER];
00529   GetString(buffer, str, lastof(buffer));
00530   return DrawString(left, right, top, buffer, colour, align, underline, fontsize);
00531 }
00532 
00539 int GetStringHeight(const char *str, int maxw, FontSize fontsize)
00540 {
00541   Layouter layout(str, maxw, TC_FROMSTRING, fontsize);
00542   return layout.GetBounds().height;
00543 }
00544 
00551 int GetStringHeight(StringID str, int maxw)
00552 {
00553   char buffer[DRAW_STRING_BUFFER];
00554   GetString(buffer, str, lastof(buffer));
00555   return GetStringHeight(buffer, maxw);
00556 }
00557 
00564 int GetStringLineCount(StringID str, int maxw)
00565 {
00566   char buffer[DRAW_STRING_BUFFER];
00567   GetString(buffer, str, lastof(buffer));
00568 
00569   Layouter layout(buffer, maxw);
00570   return layout.Length();
00571 }
00572 
00579 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00580 {
00581   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00582   return box;
00583 }
00584 
00591 Dimension GetStringMultiLineBoundingBox(const char *str, const Dimension &suggestion)
00592 {
00593   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00594   return box;
00595 }
00596 
00612 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00613 {
00614   int maxw = right - left + 1;
00615   int maxh = bottom - top + 1;
00616 
00617   /* It makes no sense to even try if it can't be drawn anyway, or
00618    * do we really want to support fonts of 0 or less pixels high? */
00619   if (maxh <= 0) return top;
00620 
00621   Layouter layout(str, maxw, colour, fontsize);
00622   int total_height = layout.GetBounds().height;
00623   int y;
00624   switch (align & SA_VERT_MASK) {
00625     case SA_TOP:
00626       y = top;
00627       break;
00628 
00629     case SA_VERT_CENTER:
00630       y = RoundDivSU(bottom + top - total_height, 2);
00631       break;
00632 
00633     case SA_BOTTOM:
00634       y = bottom - total_height;
00635       break;
00636 
00637     default: NOT_REACHED();
00638   }
00639 
00640   int last_line = top;
00641   int first_line = bottom;
00642 
00643   for (const ParagraphLayouter::Line **iter = layout.Begin(); iter != layout.End(); iter++) {
00644     const ParagraphLayouter::Line *line = *iter;
00645 
00646     int line_height = line->GetLeading();
00647     if (y >= top && y < bottom) {
00648       last_line = y + line_height;
00649       if (first_line > y) first_line = y;
00650 
00651       DrawLayoutLine(line, y, left, right, align, underline, false);
00652     }
00653     y += line_height;
00654   }
00655 
00656   return ((align & SA_VERT_MASK) == SA_BOTTOM) ? first_line : last_line;
00657 }
00658 
00674 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00675 {
00676   char buffer[DRAW_STRING_BUFFER];
00677   GetString(buffer, str, lastof(buffer));
00678   return DrawStringMultiLine(left, right, top, bottom, buffer, colour, align, underline, fontsize);
00679 }
00680 
00691 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
00692 {
00693   Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
00694   return layout.GetBounds();
00695 }
00696 
00703 Dimension GetStringBoundingBox(StringID strid)
00704 {
00705   char buffer[DRAW_STRING_BUFFER];
00706 
00707   GetString(buffer, strid, lastof(buffer));
00708   return GetStringBoundingBox(buffer);
00709 }
00710 
00719 Point GetCharPosInString(const char *str, const char *ch, FontSize start_fontsize)
00720 {
00721   Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
00722   return layout.GetCharPosition(ch);
00723 }
00724 
00732 const char *GetCharAtPosition(const char *str, int x, FontSize start_fontsize)
00733 {
00734   if (x < 0) return NULL;
00735 
00736   Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
00737   return layout.GetCharAtPosition(x);
00738 }
00739 
00747 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
00748 {
00749   SetColourRemap(colour);
00750   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
00751 }
00752 
00760 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
00761 {
00762   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
00763 
00764   if (offset != NULL) {
00765     offset->x = UnScaleByZoom(sprite->x_offs, zoom);
00766     offset->y = UnScaleByZoom(sprite->y_offs, zoom);
00767   }
00768 
00769   Dimension d;
00770   d.width  = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
00771   d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
00772   return d;
00773 }
00774 
00783 void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
00784 {
00785   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
00786   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
00787     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
00788     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
00789   } else if (pal != PAL_NONE) {
00790     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
00791     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
00792   } else {
00793     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
00794   }
00795 }
00796 
00806 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
00807 {
00808   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
00809   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
00810     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
00811     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite, zoom);
00812   } else if (pal != PAL_NONE) {
00813     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
00814     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite, zoom);
00815   } else {
00816     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite, zoom);
00817   }
00818 }
00819 
00820 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
00821 {
00822   const DrawPixelInfo *dpi = _cur_dpi;
00823   Blitter::BlitterParams bp;
00824 
00825   /* Amount of pixels to clip from the source sprite */
00826   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left * ZOOM_LVL_BASE       ) : 0);
00827   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top  * ZOOM_LVL_BASE       ) : 0);
00828   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + (sub->right + 1)  * ZOOM_LVL_BASE)) : 0);
00829   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_LVL_BASE)) : 0);
00830 
00831   if (clip_left + clip_right >= sprite->width) return;
00832   if (clip_top + clip_bottom >= sprite->height) return;
00833 
00834   /* Move to the correct offset */
00835   x += sprite->x_offs;
00836   y += sprite->y_offs;
00837 
00838   /* Copy the main data directly from the sprite */
00839   bp.sprite = sprite->data;
00840   bp.sprite_width = sprite->width;
00841   bp.sprite_height = sprite->height;
00842   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
00843   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
00844   bp.top = 0;
00845   bp.left = 0;
00846   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
00847   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
00848 
00849   x += ScaleByZoom(bp.skip_left, dpi->zoom);
00850   y += ScaleByZoom(bp.skip_top, dpi->zoom);
00851 
00852   bp.dst = dpi->dst_ptr;
00853   bp.pitch = dpi->pitch;
00854   bp.remap = _colour_remap_ptr;
00855 
00856   assert(sprite->width > 0);
00857   assert(sprite->height > 0);
00858 
00859   if (bp.width <= 0) return;
00860   if (bp.height <= 0) return;
00861 
00862   y -= dpi->top;
00863   /* Check for top overflow */
00864   if (y < 0) {
00865     bp.height -= -UnScaleByZoom(y, dpi->zoom);
00866     if (bp.height <= 0) return;
00867     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
00868     y = 0;
00869   } else {
00870     bp.top = UnScaleByZoom(y, dpi->zoom);
00871   }
00872 
00873   /* Check for bottom overflow */
00874   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
00875   if (y > 0) {
00876     bp.height -= UnScaleByZoom(y, dpi->zoom);
00877     if (bp.height <= 0) return;
00878   }
00879 
00880   x -= dpi->left;
00881   /* Check for left overflow */
00882   if (x < 0) {
00883     bp.width -= -UnScaleByZoom(x, dpi->zoom);
00884     if (bp.width <= 0) return;
00885     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
00886     x = 0;
00887   } else {
00888     bp.left = UnScaleByZoom(x, dpi->zoom);
00889   }
00890 
00891   /* Check for right overflow */
00892   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
00893   if (x > 0) {
00894     bp.width -= UnScaleByZoom(x, dpi->zoom);
00895     if (bp.width <= 0) return;
00896   }
00897 
00898   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
00899   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
00900 
00901   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
00902   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
00903     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00904     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
00905     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
00906 
00907     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
00908 
00909     if (topleft <= clicked && clicked <= bottomright) {
00910       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
00911       if (offset < (uint)bp.width) {
00912         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
00913       }
00914     }
00915   }
00916 
00917   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
00918 }
00919 
00920 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id, ZoomLevel zoom)
00921 {
00922   const DrawPixelInfo *dpi = _cur_dpi;
00923   Blitter::BlitterParams bp;
00924 
00925   /* Amount of pixels to clip from the source sprite */
00926   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
00927   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
00928   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
00929   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
00930 
00931   if (clip_left + clip_right >= sprite->width) return;
00932   if (clip_top + clip_bottom >= sprite->height) return;
00933 
00934   /* Scale it */
00935   x = ScaleByZoom(x, zoom);
00936   y = ScaleByZoom(y, zoom);
00937 
00938   /* Move to the correct offset */
00939   x += sprite->x_offs;
00940   y += sprite->y_offs;
00941 
00942   /* Copy the main data directly from the sprite */
00943   bp.sprite = sprite->data;
00944   bp.sprite_width = sprite->width;
00945   bp.sprite_height = sprite->height;
00946   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, zoom);
00947   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, zoom);
00948   bp.top = 0;
00949   bp.left = 0;
00950   bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
00951   bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
00952 
00953   x += ScaleByZoom(bp.skip_left, zoom);
00954   y += ScaleByZoom(bp.skip_top, zoom);
00955 
00956   bp.dst = dpi->dst_ptr;
00957   bp.pitch = dpi->pitch;
00958   bp.remap = _colour_remap_ptr;
00959 
00960   assert(sprite->width > 0);
00961   assert(sprite->height > 0);
00962 
00963   if (bp.width <= 0) return;
00964   if (bp.height <= 0) return;
00965 
00966   y -= ScaleByZoom(dpi->top, zoom);
00967   /* Check for top overflow */
00968   if (y < 0) {
00969     bp.height -= -UnScaleByZoom(y, zoom);
00970     if (bp.height <= 0) return;
00971     bp.skip_top += -UnScaleByZoom(y, zoom);
00972     y = 0;
00973   } else {
00974     bp.top = UnScaleByZoom(y, zoom);
00975   }
00976 
00977   /* Check for bottom overflow */
00978   y += ScaleByZoom(bp.height - dpi->height, zoom);
00979   if (y > 0) {
00980     bp.height -= UnScaleByZoom(y, zoom);
00981     if (bp.height <= 0) return;
00982   }
00983 
00984   x -= ScaleByZoom(dpi->left, zoom);
00985   /* Check for left overflow */
00986   if (x < 0) {
00987     bp.width -= -UnScaleByZoom(x, zoom);
00988     if (bp.width <= 0) return;
00989     bp.skip_left += -UnScaleByZoom(x, zoom);
00990     x = 0;
00991   } else {
00992     bp.left = UnScaleByZoom(x, zoom);
00993   }
00994 
00995   /* Check for right overflow */
00996   x += ScaleByZoom(bp.width - dpi->width, zoom);
00997   if (x > 0) {
00998     bp.width -= UnScaleByZoom(x, zoom);
00999     if (bp.width <= 0) return;
01000   }
01001 
01002   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, zoom));
01003   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, zoom));
01004 
01005   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01006   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01007     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01008     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01009     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01010 
01011     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01012 
01013     if (topleft <= clicked && clicked <= bottomright) {
01014       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01015       if (offset < (uint)bp.width) {
01016         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01017       }
01018     }
01019   }
01020 
01021   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, zoom);
01022 }
01023 
01024 void DoPaletteAnimations();
01025 
01026 void GfxInitPalettes()
01027 {
01028   memcpy(&_cur_palette, &_palette, sizeof(_cur_palette));
01029   DoPaletteAnimations();
01030 }
01031 
01032 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01033 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01034 
01035 void DoPaletteAnimations()
01036 {
01037   /* Animation counter for the palette animation. */
01038   static int palette_animation_counter = 0;
01039   palette_animation_counter += 8;
01040 
01041   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01042   const Colour *s;
01043   const ExtraPaletteValues *ev = &_extra_palette_values;
01044   Colour old_val[PALETTE_ANIM_SIZE];
01045   const uint old_tc = palette_animation_counter;
01046   uint i;
01047   uint j;
01048 
01049   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01050     palette_animation_counter = 0;
01051   }
01052 
01053   Colour *palette_pos = &_cur_palette.palette[PALETTE_ANIM_START];  // Points to where animations are taking place on the palette
01054   /* Makes a copy of the current animation palette in old_val,
01055    * so the work on the current palette could be compared, see if there has been any changes */
01056   memcpy(old_val, palette_pos, sizeof(old_val));
01057 
01058   /* Fizzy Drink bubbles animation */
01059   s = ev->fizzy_drink;
01060   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01061   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01062     *palette_pos++ = s[j];
01063     j++;
01064     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01065   }
01066 
01067   /* Oil refinery fire animation */
01068   s = ev->oil_refinery;
01069   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01070   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01071     *palette_pos++ = s[j];
01072     j++;
01073     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01074   }
01075 
01076   /* Radio tower blinking */
01077   {
01078     byte i = (palette_animation_counter >> 1) & 0x7F;
01079     byte v;
01080 
01081     if (i < 0x3f) {
01082       v = 255;
01083     } else if (i < 0x4A || i >= 0x75) {
01084       v = 128;
01085     } else {
01086       v = 20;
01087     }
01088     palette_pos->r = v;
01089     palette_pos->g = 0;
01090     palette_pos->b = 0;
01091     palette_pos++;
01092 
01093     i ^= 0x40;
01094     if (i < 0x3f) {
01095       v = 255;
01096     } else if (i < 0x4A || i >= 0x75) {
01097       v = 128;
01098     } else {
01099       v = 20;
01100     }
01101     palette_pos->r = v;
01102     palette_pos->g = 0;
01103     palette_pos->b = 0;
01104     palette_pos++;
01105   }
01106 
01107   /* Handle lighthouse and stadium animation */
01108   s = ev->lighthouse;
01109   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01110   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01111     *palette_pos++ = s[j];
01112     j++;
01113     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01114   }
01115 
01116   /* Dark blue water */
01117   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01118   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01119   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01120     *palette_pos++ = s[j];
01121     j++;
01122     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01123   }
01124 
01125   /* Glittery water */
01126   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01127   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01128   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01129     *palette_pos++ = s[j];
01130     j += 3;
01131     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01132   }
01133 
01134   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01135     palette_animation_counter = old_tc;
01136   } else {
01137     if (memcmp(old_val, &_cur_palette.palette[PALETTE_ANIM_START], sizeof(old_val)) != 0 && _cur_palette.count_dirty == 0) {
01138       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01139       _cur_palette.first_dirty = PALETTE_ANIM_START;
01140       _cur_palette.count_dirty = PALETTE_ANIM_SIZE;
01141     }
01142   }
01143 }
01144 
01150 TextColour GetContrastColour(uint8 background)
01151 {
01152   Colour c = _cur_palette.palette[background];
01153   /* Compute brightness according to http://www.w3.org/TR/AERT#color-contrast.
01154    * The following formula computes 1000 * brightness^2, with brightness being in range 0 to 255. */
01155   uint sq1000_brightness = c.r * c.r * 299 + c.g * c.g * 587 + c.b * c.b * 114;
01156   /* Compare with threshold brightness 128 (50%) */
01157   return sq1000_brightness < 128 * 128 * 1000 ? TC_WHITE : TC_BLACK;
01158 }
01159 
01164 void LoadStringWidthTable(bool monospace)
01165 {
01166   for (FontSize fs = monospace ? FS_MONO : FS_BEGIN; fs < (monospace ? FS_END : FS_MONO); fs++) {
01167     for (uint i = 0; i != 224; i++) {
01168       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01169     }
01170   }
01171 
01172   ReInitAllWindows();
01173 }
01174 
01181 byte GetCharacterWidth(FontSize size, WChar key)
01182 {
01183   /* Use _stringwidth_table cache if possible */
01184   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01185 
01186   return GetGlyphWidth(size, key);
01187 }
01188 
01194 byte GetDigitWidth(FontSize size)
01195 {
01196   byte width = 0;
01197   for (char c = '0'; c <= '9'; c++) {
01198     width = max(GetCharacterWidth(size, c), width);
01199   }
01200   return width;
01201 }
01202 
01209 void GetBroadestDigit(uint *front, uint *next, FontSize size)
01210 {
01211   int width = -1;
01212   for (char c = '9'; c >= '0'; c--) {
01213     int w = GetCharacterWidth(size, c);
01214     if (w > width) {
01215       width = w;
01216       *next = c - '0';
01217       if (c != '0') *front = c - '0';
01218     }
01219   }
01220 }
01221 
01222 void ScreenSizeChanged()
01223 {
01224   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01225   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01226 
01227   /* check the dirty rect */
01228   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01229   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01230 
01231   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01232   _cursor.visible = false;
01233 }
01234 
01235 void UndrawMouseCursor()
01236 {
01237   /* Don't undraw the mouse cursor if the screen is not ready */
01238   if (_screen.dst_ptr == NULL) return;
01239 
01240   if (_cursor.visible) {
01241     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01242     _cursor.visible = false;
01243     blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), _cursor_backup.GetBuffer(), _cursor.draw_size.x, _cursor.draw_size.y);
01244     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01245   }
01246 }
01247 
01248 void DrawMouseCursor()
01249 {
01250 #if defined(WINCE)
01251   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01252   return;
01253 #endif
01254 
01255   /* Don't draw the mouse cursor if the screen is not ready */
01256   if (_screen.dst_ptr == NULL) return;
01257 
01258   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01259   int x;
01260   int y;
01261   int w;
01262   int h;
01263 
01264   /* Redraw mouse cursor but only when it's inside the window */
01265   if (!_cursor.in_window) return;
01266 
01267   /* Don't draw the mouse cursor if it's already drawn */
01268   if (_cursor.visible) {
01269     if (!_cursor.dirty) return;
01270     UndrawMouseCursor();
01271   }
01272 
01273   w = _cursor.size.x;
01274   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01275   if (x < 0) {
01276     w += x;
01277     x = 0;
01278   }
01279   if (w > _screen.width - x) w = _screen.width - x;
01280   if (w <= 0) return;
01281   _cursor.draw_pos.x = x;
01282   _cursor.draw_size.x = w;
01283 
01284   h = _cursor.size.y;
01285   y = _cursor.pos.y + _cursor.offs.y;
01286   if (y < 0) {
01287     h += y;
01288     y = 0;
01289   }
01290   if (h > _screen.height - y) h = _screen.height - y;
01291   if (h <= 0) return;
01292   _cursor.draw_pos.y = y;
01293   _cursor.draw_size.y = h;
01294 
01295   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01296 
01297   /* Make backup of stuff below cursor */
01298   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01299 
01300   /* Draw cursor on screen */
01301   _cur_dpi = &_screen;
01302   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01303 
01304   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01305 
01306   _cursor.visible = true;
01307   _cursor.dirty = false;
01308 }
01309 
01310 void RedrawScreenRect(int left, int top, int right, int bottom)
01311 {
01312   assert(right <= _screen.width && bottom <= _screen.height);
01313   if (_cursor.visible) {
01314     if (right > _cursor.draw_pos.x &&
01315         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01316         bottom > _cursor.draw_pos.y &&
01317         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01318       UndrawMouseCursor();
01319     }
01320   }
01321 
01322 #ifdef ENABLE_NETWORK
01323   if (_networking) NetworkUndrawChatMessage();
01324 #endif /* ENABLE_NETWORK */
01325 
01326   DrawOverlappedWindowForAll(left, top, right, bottom);
01327 
01328   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01329 }
01330 
01336 void DrawDirtyBlocks()
01337 {
01338   byte *b = _dirty_blocks;
01339   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01340   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01341   int x;
01342   int y;
01343 
01344   if (HasModalProgress()) {
01345     /* We are generating the world, so release our rights to the map and
01346      * painting while we are waiting a bit. */
01347     _modal_progress_paint_mutex->EndCritical();
01348     _modal_progress_work_mutex->EndCritical();
01349 
01350     /* Wait a while and update _realtime_tick so we are given the rights */
01351     if (!IsFirstModalProgressLoop()) CSleep(MODAL_PROGRESS_REDRAW_TIMEOUT);
01352     _realtime_tick += MODAL_PROGRESS_REDRAW_TIMEOUT;
01353     _modal_progress_paint_mutex->BeginCritical();
01354     _modal_progress_work_mutex->BeginCritical();
01355 
01356     /* When we ended with the modal progress, do not draw the blocks.
01357      * Simply let the next run do so, otherwise we would be loading
01358      * the new state (and possibly change the blitter) when we hold
01359      * the drawing lock, which we must not do. */
01360     if (_switch_mode != SM_NONE && !HasModalProgress()) return;
01361   }
01362 
01363   y = 0;
01364   do {
01365     x = 0;
01366     do {
01367       if (*b != 0) {
01368         int left;
01369         int top;
01370         int right = x + DIRTY_BLOCK_WIDTH;
01371         int bottom = y;
01372         byte *p = b;
01373         int h2;
01374 
01375         /* First try coalescing downwards */
01376         do {
01377           *p = 0;
01378           p += _dirty_bytes_per_line;
01379           bottom += DIRTY_BLOCK_HEIGHT;
01380         } while (bottom != h && *p != 0);
01381 
01382         /* Try coalescing to the right too. */
01383         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01384         assert(h2 > 0);
01385         p = b;
01386 
01387         while (right != w) {
01388           byte *p2 = ++p;
01389           int h = h2;
01390           /* Check if a full line of dirty flags is set. */
01391           do {
01392             if (!*p2) goto no_more_coalesc;
01393             p2 += _dirty_bytes_per_line;
01394           } while (--h != 0);
01395 
01396           /* Wohoo, can combine it one step to the right!
01397            * Do that, and clear the bits. */
01398           right += DIRTY_BLOCK_WIDTH;
01399 
01400           h = h2;
01401           p2 = p;
01402           do {
01403             *p2 = 0;
01404             p2 += _dirty_bytes_per_line;
01405           } while (--h != 0);
01406         }
01407         no_more_coalesc:
01408 
01409         left = x;
01410         top = y;
01411 
01412         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01413         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01414         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01415         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01416 
01417         if (left < right && top < bottom) {
01418           RedrawScreenRect(left, top, right, bottom);
01419         }
01420 
01421       }
01422     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01423   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01424 
01425   ++_dirty_block_colour;
01426   _invalid_rect.left = w;
01427   _invalid_rect.top = h;
01428   _invalid_rect.right = 0;
01429   _invalid_rect.bottom = 0;
01430 }
01431 
01447 void SetDirtyBlocks(int left, int top, int right, int bottom)
01448 {
01449   byte *b;
01450   int width;
01451   int height;
01452 
01453   if (left < 0) left = 0;
01454   if (top < 0) top = 0;
01455   if (right > _screen.width) right = _screen.width;
01456   if (bottom > _screen.height) bottom = _screen.height;
01457 
01458   if (left >= right || top >= bottom) return;
01459 
01460   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01461   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01462   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01463   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01464 
01465   left /= DIRTY_BLOCK_WIDTH;
01466   top  /= DIRTY_BLOCK_HEIGHT;
01467 
01468   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01469 
01470   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01471   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01472 
01473   assert(width > 0 && height > 0);
01474 
01475   do {
01476     int i = width;
01477 
01478     do b[--i] = 0xFF; while (i != 0);
01479 
01480     b += _dirty_bytes_per_line;
01481   } while (--height != 0);
01482 }
01483 
01490 void MarkWholeScreenDirty()
01491 {
01492   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01493 }
01494 
01509 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01510 {
01511   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01512   const DrawPixelInfo *o = _cur_dpi;
01513 
01514   n->zoom = ZOOM_LVL_NORMAL;
01515 
01516   assert(width > 0);
01517   assert(height > 0);
01518 
01519   if ((left -= o->left) < 0) {
01520     width += left;
01521     if (width <= 0) return false;
01522     n->left = -left;
01523     left = 0;
01524   } else {
01525     n->left = 0;
01526   }
01527 
01528   if (width > o->width - left) {
01529     width = o->width - left;
01530     if (width <= 0) return false;
01531   }
01532   n->width = width;
01533 
01534   if ((top -= o->top) < 0) {
01535     height += top;
01536     if (height <= 0) return false;
01537     n->top = -top;
01538     top = 0;
01539   } else {
01540     n->top = 0;
01541   }
01542 
01543   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01544   n->pitch = o->pitch;
01545 
01546   if (height > o->height - top) {
01547     height = o->height - top;
01548     if (height <= 0) return false;
01549   }
01550   n->height = height;
01551 
01552   return true;
01553 }
01554 
01559 void UpdateCursorSize()
01560 {
01561   CursorVars *cv = &_cursor;
01562   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01563 
01564   cv->size.y = UnScaleByZoom(p->height, ZOOM_LVL_GUI);
01565   cv->size.x = UnScaleByZoom(p->width, ZOOM_LVL_GUI);
01566   cv->offs.x = UnScaleByZoom(p->x_offs, ZOOM_LVL_GUI);
01567   cv->offs.y = UnScaleByZoom(p->y_offs, ZOOM_LVL_GUI);
01568 
01569   cv->dirty = true;
01570 }
01571 
01577 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01578 {
01579   CursorVars *cv = &_cursor;
01580   if (cv->sprite == cursor) return;
01581 
01582   cv->sprite = cursor;
01583   cv->pal    = pal;
01584   UpdateCursorSize();
01585 
01586   cv->short_vehicle_offset = 0;
01587 }
01588 
01589 static void SwitchAnimatedCursor()
01590 {
01591   const AnimCursor *cur = _cursor.animate_cur;
01592 
01593   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01594 
01595   SetCursorSprite(cur->sprite, _cursor.pal);
01596 
01597   _cursor.animate_timeout = cur->display_time;
01598   _cursor.animate_cur     = cur + 1;
01599 }
01600 
01601 void CursorTick()
01602 {
01603   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01604     SwitchAnimatedCursor();
01605   }
01606 }
01607 
01614 void SetMouseCursor(CursorID sprite, PaletteID pal)
01615 {
01616   /* Turn off animation */
01617   _cursor.animate_timeout = 0;
01618   /* Set cursor */
01619   SetCursorSprite(sprite, pal);
01620 }
01621 
01627 void SetAnimatedMouseCursor(const AnimCursor *table)
01628 {
01629   _cursor.animate_list = table;
01630   _cursor.animate_cur = NULL;
01631   _cursor.pal = PAL_NONE;
01632   SwitchAnimatedCursor();
01633 }
01634 
01635 bool ChangeResInGame(int width, int height)
01636 {
01637   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
01638 }
01639 
01640 bool ToggleFullScreen(bool fs)
01641 {
01642   bool result = _video_driver->ToggleFullscreen(fs);
01643   if (_fullscreen != fs && _num_resolutions == 0) {
01644     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
01645   }
01646   return result;
01647 }
01648 
01649 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
01650 {
01651   int x = pa->width - pb->width;
01652   if (x != 0) return x;
01653   return pa->height - pb->height;
01654 }
01655 
01656 void SortResolutions(int count)
01657 {
01658   QSortT(_resolutions, count, &compare_res);
01659 }