gfx.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "gfx_func.h"
00014 #include "fontcache.h"
00015 #include "progress.h"
00016 #include "zoom_func.h"
00017 #include "blitter/factory.hpp"
00018 #include "video/video_driver.hpp"
00019 #include "strings_func.h"
00020 #include "settings_type.h"
00021 #include "network/network.h"
00022 #include "network/network_func.h"
00023 #include "window_func.h"
00024 #include "newgrf_debug.h"
00025 
00026 #include "table/palettes.h"
00027 #include "table/sprites.h"
00028 #include "table/control_codes.h"
00029 
00030 byte _dirkeys;        
00031 bool _fullscreen;
00032 CursorVars _cursor;
00033 bool _ctrl_pressed;   
00034 bool _shift_pressed;  
00035 byte _fast_forward;
00036 bool _left_button_down;     
00037 bool _left_button_clicked;  
00038 bool _right_button_down;    
00039 bool _right_button_clicked; 
00040 DrawPixelInfo _screen;
00041 bool _screen_disable_anim = false;   
00042 bool _exit_game;
00043 GameMode _game_mode;
00044 SwitchMode _switch_mode;  
00045 PauseModeByte _pause_mode;
00046 Palette _cur_palette;
00047 
00048 static Dimension _max_char_size[FS_END]; 
00049 static int _max_char_height; 
00050 static int _max_char_width;  
00051 static byte _stringwidth_table[FS_END][224]; 
00052 DrawPixelInfo *_cur_dpi;
00053 byte _colour_gradient[COLOUR_END][8];
00054 
00055 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
00056 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);
00057 
00062 struct DrawStringParams {
00063   FontSize fontsize;
00064   TextColour cur_colour, prev_colour;
00065 
00066   DrawStringParams(TextColour colour, FontSize fontsize) : fontsize(fontsize), cur_colour(colour), prev_colour(colour) {}
00067 
00072   inline void SetColour(TextColour c)
00073   {
00074     assert(c >=  TC_BLUE && c <= TC_BLACK);
00075     this->prev_colour = this->cur_colour;
00076     this->cur_colour = c;
00077   }
00078 
00080   inline void SetPreviousColour()
00081   {
00082     Swap(this->cur_colour, this->prev_colour);
00083   }
00084 
00089   inline void SetFontSize(FontSize f)
00090   {
00091     this->fontsize = f;
00092   }
00093 };
00094 
00095 static ReusableBuffer<uint8> _cursor_backup;
00096 
00104 static Rect _invalid_rect;
00105 static const byte *_colour_remap_ptr;
00106 static byte _string_colourremap[3]; 
00107 
00108 static const uint DIRTY_BLOCK_HEIGHT   = 8;
00109 static const uint DIRTY_BLOCK_WIDTH    = 64;
00110 
00111 static uint _dirty_bytes_per_line = 0;
00112 static byte *_dirty_blocks = NULL;
00113 
00114 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
00115 {
00116   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00117 
00118   if (xo == 0 && yo == 0) return;
00119 
00120   if (_cursor.visible) UndrawMouseCursor();
00121 
00122 #ifdef ENABLE_NETWORK
00123   if (_networking) NetworkUndrawChatMessage();
00124 #endif /* ENABLE_NETWORK */
00125 
00126   blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
00127   /* This part of the screen is now dirty. */
00128   _video_driver->MakeDirty(left, top, width, height);
00129 }
00130 
00131 
00146 void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
00147 {
00148   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00149   const DrawPixelInfo *dpi = _cur_dpi;
00150   void *dst;
00151   const int otop = top;
00152   const int oleft = left;
00153 
00154   if (dpi->zoom != ZOOM_LVL_NORMAL) return;
00155   if (left > right || top > bottom) return;
00156   if (right < dpi->left || left >= dpi->left + dpi->width) return;
00157   if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
00158 
00159   if ( (left -= dpi->left) < 0) left = 0;
00160   right = right - dpi->left + 1;
00161   if (right > dpi->width) right = dpi->width;
00162   right -= left;
00163   assert(right > 0);
00164 
00165   if ( (top -= dpi->top) < 0) top = 0;
00166   bottom = bottom - dpi->top + 1;
00167   if (bottom > dpi->height) bottom = dpi->height;
00168   bottom -= top;
00169   assert(bottom > 0);
00170 
00171   dst = blitter->MoveTo(dpi->dst_ptr, left, top);
00172 
00173   switch (mode) {
00174     default: // FILLRECT_OPAQUE
00175       blitter->DrawRect(dst, right, bottom, (uint8)colour);
00176       break;
00177 
00178     case FILLRECT_RECOLOUR:
00179       blitter->DrawColourMappingRect(dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
00180       break;
00181 
00182     case FILLRECT_CHECKER: {
00183       byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
00184       do {
00185         for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
00186         dst = blitter->MoveTo(dst, 0, 1);
00187       } while (--bottom > 0);
00188       break;
00189     }
00190   }
00191 }
00192 
00193 void GfxDrawLine(int x, int y, int x2, int y2, int colour, int width)
00194 {
00195   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00196   DrawPixelInfo *dpi = _cur_dpi;
00197 
00198   assert(width > 0);
00199 
00200   x -= dpi->left;
00201   x2 -= dpi->left;
00202   y -= dpi->top;
00203   y2 -= dpi->top;
00204 
00205   /* Check clipping */
00206   if (x + width / 2 < 0           && x2 + width / 2 < 0          ) return;
00207   if (y + width / 2 < 0           && y2 + width / 2 < 0          ) return;
00208   if (x - width / 2 > dpi->width  && x2 - width / 2 > dpi->width ) return;
00209   if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return;
00210 
00211   blitter->DrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour, width);
00212 }
00213 
00214 void GfxDrawLineUnscaled(int x, int y, int x2, int y2, int colour)
00215 {
00216   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00217   DrawPixelInfo *dpi = _cur_dpi;
00218 
00219   x -= dpi->left;
00220   x2 -= dpi->left;
00221   y -= dpi->top;
00222   y2 -= dpi->top;
00223 
00224   /* Check clipping */
00225   if (x < 0 && x2 < 0) return;
00226   if (y < 0 && y2 < 0) return;
00227   if (x > dpi->width  && x2 > dpi->width)  return;
00228   if (y > dpi->height && y2 > dpi->height) return;
00229 
00230   blitter->DrawLine(dpi->dst_ptr, UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
00231       UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
00232       UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
00233 }
00234 
00248 void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
00249 {
00250   /*           ....
00251    *         ..    ....
00252    *       ..          ....
00253    *     ..                ^
00254    *   <--__(dx1,dy1)    /(dx2,dy2)
00255    *   :    --__       /   :
00256    *   :        --__ /     :
00257    *   :            *(x,y) :
00258    *   :            |      :
00259    *   :            |     ..
00260    *    ....        |(dx3,dy3)
00261    *        ....    | ..
00262    *            ....V.
00263    */
00264 
00265   static const byte colour = PC_WHITE;
00266 
00267   GfxDrawLineUnscaled(x, y, x + dx1, y + dy1, colour);
00268   GfxDrawLineUnscaled(x, y, x + dx2, y + dy2, colour);
00269   GfxDrawLineUnscaled(x, y, x + dx3, y + dy3, colour);
00270 
00271   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
00272   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
00273   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
00274   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
00275   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
00276   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
00277 }
00278 
00283 static void SetColourRemap(TextColour colour)
00284 {
00285   if (colour == TC_INVALID) return;
00286 
00287   /* Black strings have no shading ever; the shading is black, so it
00288    * would be invisible at best, but it actually makes it illegible. */
00289   bool no_shade   = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
00290   bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
00291   colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
00292 
00293   _string_colourremap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
00294   _string_colourremap[2] = no_shade ? 0 : 1;
00295   _colour_remap_ptr = _string_colourremap;
00296 }
00297 
00298 #if !defined(WITH_ICU)
00299 typedef WChar UChar;
00300 static UChar *HandleBiDiAndArabicShapes(UChar *text) { return text; }
00301 #else
00302 #include <unicode/ubidi.h>
00303 #include <unicode/ushape.h>
00304 
00334 static UChar *HandleBiDiAndArabicShapes(UChar *buffer)
00335 {
00336   static UChar input_output[DRAW_STRING_BUFFER];
00337   UChar intermediate[DRAW_STRING_BUFFER];
00338 
00339   UChar *t = buffer;
00340   size_t length = 0;
00341   while (*t != '\0' && length < lengthof(input_output) - 1) {
00342     input_output[length++] = *t++;
00343   }
00344   input_output[length] = 0;
00345 
00346   UErrorCode err = U_ZERO_ERROR;
00347   UBiDi *para = ubidi_openSized((int32_t)length, 0, &err);
00348   if (para == NULL) return buffer;
00349 
00350   ubidi_setPara(para, input_output, (int32_t)length, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, &err);
00351   ubidi_writeReordered(para, intermediate, (int32_t)length, UBIDI_REMOVE_BIDI_CONTROLS, &err);
00352   length = u_shapeArabic(intermediate, (int32_t)length, input_output, lengthof(input_output), U_SHAPE_TEXT_DIRECTION_VISUAL_LTR | U_SHAPE_LETTERS_SHAPE, &err);
00353   ubidi_close(para);
00354 
00355   if (U_FAILURE(err)) return buffer;
00356 
00357   input_output[length] = '\0';
00358   return input_output;
00359 }
00360 #endif /* WITH_ICU */
00361 
00362 
00372 static int TruncateString(char *str, int maxw, bool ignore_setxy, FontSize start_fontsize)
00373 {
00374   int w = 0;
00375   FontSize size = start_fontsize;
00376   int ddd, ddd_w;
00377 
00378   WChar c;
00379   char *ddd_pos;
00380 
00381   ddd_w = ddd = GetCharacterWidth(size, '.') * 3;
00382 
00383   for (ddd_pos = str; (c = Utf8Consume(const_cast<const char **>(&str))) != '\0'; ) {
00384     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00385       w += GetCharacterWidth(size, c);
00386 
00387       if (w > maxw) {
00388         /* string got too big... insert dotdotdot, but make sure we do not
00389          * print anything beyond the string termination character. */
00390         for (int i = 0; *ddd_pos != '\0' && i < 3; i++, ddd_pos++) *ddd_pos = '.';
00391         *ddd_pos = '\0';
00392         return ddd_w;
00393       }
00394     } else {
00395       if (c == SCC_SETX) {
00396         if (!ignore_setxy) w = *str;
00397         str++;
00398       } else if (c == SCC_SETXY) {
00399         if (!ignore_setxy) w = *str;
00400         str += 2;
00401       } else if (c == SCC_TINYFONT) {
00402         size = FS_SMALL;
00403         ddd = GetCharacterWidth(size, '.') * 3;
00404       } else if (c == SCC_BIGFONT) {
00405         size = FS_LARGE;
00406         ddd = GetCharacterWidth(size, '.') * 3;
00407       } else if (c == '\n') {
00408         DEBUG(misc, 0, "Drawing string using newlines with DrawString instead of DrawStringMultiLine. Please notify the developers of this: [%s]", str);
00409       }
00410     }
00411 
00412     /* Remember the last position where three dots fit. */
00413     if (w + ddd < maxw) {
00414       ddd_w = w + ddd;
00415       ddd_pos = str;
00416     }
00417   }
00418 
00419   return w;
00420 }
00421 
00422 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped = false);
00423 
00430 static int GetStringWidth(const UChar *str, FontSize start_fontsize)
00431 {
00432   FontSize size = start_fontsize;
00433   int max_width;
00434   int width;
00435   WChar c;
00436 
00437   width = max_width = 0;
00438   for (;;) {
00439     c = *str++;
00440     if (c == 0) break;
00441     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00442       width += GetCharacterWidth(size, c);
00443     } else {
00444       switch (c) {
00445         case SCC_SETX:
00446         case SCC_SETXY:
00447           /* At this point there is no SCC_SETX(Y) anymore */
00448           NOT_REACHED();
00449           break;
00450         case SCC_TINYFONT: size = FS_SMALL; break;
00451         case SCC_BIGFONT:  size = FS_LARGE; break;
00452         case '\n':
00453           max_width = max(max_width, width);
00454           break;
00455       }
00456     }
00457   }
00458 
00459   return max(max_width, width);
00460 }
00461 
00480 static int DrawString(int left, int right, int top, char *str, const char *last, DrawStringParams &params, StringAlignment align, bool underline = false, bool truncate = true)
00481 {
00482   /* We need the outer limits of both left/right */
00483   int min_left = INT32_MAX;
00484   int max_right = INT32_MIN;
00485 
00486   int initial_left = left;
00487   int initial_right = right;
00488   int initial_top = top;
00489 
00490   if (truncate) TruncateString(str, right - left + 1, (align & SA_STRIP) == SA_STRIP, params.fontsize);
00491 
00492   /*
00493    * To support SETX and SETXY properly with RTL languages we have to
00494    * calculate the offsets from the right. To do this we need to split
00495    * the string and draw the parts separated by SETX(Y).
00496    * So here we split
00497    */
00498   static SmallVector<UChar *, 4> setx_offsets;
00499   setx_offsets.Clear();
00500 
00501   UChar draw_buffer[DRAW_STRING_BUFFER];
00502   UChar *p = draw_buffer;
00503 
00504   *setx_offsets.Append() = p;
00505 
00506   char *loc = str;
00507   for (;;) {
00508     WChar c;
00509     /* We cannot use Utf8Consume as we need the location of the SETX(Y) */
00510     size_t len = Utf8Decode(&c, loc);
00511     *p++ = c;
00512 
00513     if (c == '\0') break;
00514     if (p >= lastof(draw_buffer) - 3) {
00515       /* Make sure we never overflow (even if copying SCC_SETX(Y)). */
00516       *p = '\0';
00517       break;
00518     }
00519     if (c != SCC_SETX && c != SCC_SETXY) {
00520       loc += len;
00521       continue;
00522     }
00523 
00524     if (align & SA_STRIP) {
00525       /* We do not want to keep the SETX(Y)!. It was already copied, so
00526        * remove it and undo the incrementing of the pointer! */
00527       *p-- = '\0';
00528       loc += len + (c == SCC_SETXY ? 2 : 1);
00529       continue;
00530     }
00531 
00532     if ((align & SA_HOR_MASK) != SA_LEFT) {
00533       DEBUG(grf, 1, "Using SETX and/or SETXY when not aligned to the left. Fixing alignment...");
00534 
00535       /* For left alignment and change the left so it will roughly be in the
00536        * middle. This will never cause the string to be completely centered,
00537        * but once SETX is used you cannot be sure the actual content of the
00538        * string is centered, so it doesn't really matter. */
00539       align = SA_LEFT | SA_FORCE;
00540       initial_left = left = max(left, (left + right - (int)GetStringBoundingBox(str).width) / 2);
00541     }
00542 
00543     /* We add the begin of the string, but don't add it twice */
00544     if (p != draw_buffer) {
00545       *setx_offsets.Append() = p;
00546       p[-1] = '\0';
00547       *p++ = c;
00548     }
00549 
00550     /* Skip the SCC_SETX(Y) ... */
00551     loc += len;
00552     /* ... copy the x coordinate ... */
00553     *p++ = *loc++;
00554     /* ... and finally copy the y coordinate if it exists */
00555     if (c == SCC_SETXY) *p++ = *loc++;
00556   }
00557 
00558   /* In case we have a RTL language we swap the alignment. */
00559   if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && !(align & SA_STRIP) && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
00560 
00561   for (UChar **iter = setx_offsets.Begin(); iter != setx_offsets.End(); iter++) {
00562     UChar *to_draw = *iter;
00563     int offset = 0;
00564 
00565     /* Skip the SETX(Y) and set the appropriate offsets. */
00566     if (*to_draw == SCC_SETX || *to_draw == SCC_SETXY) {
00567       to_draw++;
00568       offset = *to_draw++;
00569       if (*to_draw == SCC_SETXY) top = initial_top + *to_draw++;
00570     }
00571 
00572     to_draw = HandleBiDiAndArabicShapes(to_draw);
00573     int w = GetStringWidth(to_draw, params.fontsize);
00574 
00575     /* right is the right most position to draw on. In this case we want to do
00576      * calculations with the width of the string. In comparison right can be
00577      * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
00578      * So most +1/-1 additions are to move from lengthof to 'indices'.
00579      */
00580     switch (align & SA_HOR_MASK) {
00581       case SA_LEFT:
00582         /* right + 1 = left + w */
00583         left = initial_left + offset;
00584         right = left + w - 1;
00585         break;
00586 
00587       case SA_HOR_CENTER:
00588         left  = RoundDivSU(initial_right + 1 + initial_left - w, 2);
00589         /* right + 1 = left + w */
00590         right = left + w - 1;
00591         break;
00592 
00593       case SA_RIGHT:
00594         left = initial_right + 1 - w - offset;
00595         break;
00596 
00597       default:
00598         NOT_REACHED();
00599     }
00600 
00601     min_left  = min(left, min_left);
00602     max_right = max(right, max_right);
00603 
00604     ReallyDoDrawString(to_draw, left, top, params, !truncate);
00605     if (underline) {
00606       GfxFillRect(left, top + FONT_HEIGHT_NORMAL, right, top + FONT_HEIGHT_NORMAL, _string_colourremap[1]);
00607     }
00608   }
00609 
00610   return (align & SA_HOR_MASK) == SA_RIGHT ? min_left : max_right;
00611 }
00612 
00627 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00628 {
00629   char buffer[DRAW_STRING_BUFFER];
00630   strecpy(buffer, str, lastof(buffer));
00631   DrawStringParams params(colour, fontsize);
00632   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00633 }
00634 
00649 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00650 {
00651   char buffer[DRAW_STRING_BUFFER];
00652   GetString(buffer, str, lastof(buffer));
00653   DrawStringParams params(colour, fontsize);
00654   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00655 }
00656 
00677 uint32 FormatStringLinebreaks(char *str, const char *last, int maxw, FontSize size)
00678 {
00679   int num = 0;
00680 
00681   assert(maxw > 0);
00682 
00683   for (;;) {
00684     /* The character *after* the last space. */
00685     char *last_space = NULL;
00686     int w = 0;
00687 
00688     for (;;) {
00689       WChar c = Utf8Consume(const_cast<const char **>(&str));
00690       /* whitespace is where we will insert the line-break */
00691       if (IsWhitespace(c)) last_space = str;
00692 
00693       if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00694         int char_w = GetCharacterWidth(size, c);
00695         w += char_w;
00696         if (w > maxw) {
00697           /* The string is longer than maximum width so we need to decide
00698            * what to do with it. */
00699           if (w == char_w) {
00700             /* The character is wider than allowed width; don't know
00701              * what to do with this case... bail out! */
00702             return num + (size << 16);
00703           }
00704           if (last_space == NULL) {
00705             /* No space has been found. Just terminate at our current
00706              * location. This usually happens for languages that do not
00707              * require spaces in strings, like Chinese, Japanese and
00708              * Korean. For other languages terminating mid-word might
00709              * not be the best, but terminating the whole string instead
00710              * of continuing the word at the next line is worse. */
00711             str = Utf8PrevChar(str);
00712             size_t len = strlen(str);
00713             char *terminator = str + len;
00714 
00715             /* The string location + length of the string + 1 for '\0'
00716              * always fits; otherwise there's no trailing '\0' and it
00717              * it not a valid string. */
00718             assert(terminator <= last);
00719             assert(*terminator == '\0');
00720 
00721             /* If the string is too long we have to terminate it earlier. */
00722             if (terminator == last) {
00723               /* Get the 'begin' of the previous character and make that
00724                * the terminator of the string; we truncate it 'early'. */
00725               *Utf8PrevChar(terminator) = '\0';
00726               len = strlen(str);
00727             }
00728             /* Also move the terminator! */
00729             memmove(str + 1, str, len + 1);
00730             *str = '\0';
00731             /* str needs to point to the character *after* the last space */
00732             str++;
00733           } else {
00734             /* A space is found; perfect place to terminate */
00735             str = last_space;
00736           }
00737           break;
00738         }
00739       } else {
00740         switch (c) {
00741           case '\0': return num + (size << 16);
00742           case SCC_SETX:  str++; break;
00743           case SCC_SETXY: str += 2; break;
00744           case SCC_TINYFONT: size = FS_SMALL; break;
00745           case SCC_BIGFONT:  size = FS_LARGE; break;
00746           case '\n': goto end_of_inner_loop;
00747         }
00748       }
00749     }
00750 end_of_inner_loop:
00751     /* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
00752      * and increase linecount. We use Utf8PrevChar() as also non 1 char long
00753      * whitespace seperators are supported */
00754     num++;
00755     char *s = Utf8PrevChar(str);
00756     *s++ = '\0';
00757 
00758     /* In which case (see above) we will shift remainder to left and close the gap */
00759     if (str - s >= 1) {
00760       for (; str[-1] != '\0';) *s++ = *str++;
00761     }
00762   }
00763 }
00764 
00765 
00774 static int GetMultilineStringHeight(const char *src, int num, FontSize start_fontsize)
00775 {
00776   int maxy = 0;
00777   int y = 0;
00778   int fh = GetCharacterHeight(start_fontsize);
00779 
00780   for (;;) {
00781     WChar c = Utf8Consume(&src);
00782 
00783     switch (c) {
00784       case 0:            y += fh; if (--num < 0) return maxy; break;
00785       case '\n':         y += fh;                             break;
00786       case SCC_SETX:     src++;                               break;
00787       case SCC_SETXY:    src++; y = (int)*src++;              break;
00788       case SCC_TINYFONT: fh = GetCharacterHeight(FS_SMALL);   break;
00789       case SCC_BIGFONT:  fh = GetCharacterHeight(FS_LARGE);   break;
00790       default:           maxy = max<int>(maxy, y + fh);       break;
00791     }
00792   }
00793 }
00794 
00795 
00802 int GetStringHeight(StringID str, int maxw)
00803 {
00804   char buffer[DRAW_STRING_BUFFER];
00805 
00806   GetString(buffer, str, lastof(buffer));
00807 
00808   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00809 
00810   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00811 }
00812 
00819 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00820 {
00821   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00822   return box;
00823 }
00824 
00825 
00832 int GetStringHeight(const char *str, int maxw)
00833 {
00834   char buffer[DRAW_STRING_BUFFER];
00835 
00836   strecpy(buffer, str, lastof(buffer));
00837 
00838   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00839 
00840   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00841 }
00842 
00849 Dimension GetStringMultiLineBoundingBox(const char *str, const Dimension &suggestion)
00850 {
00851   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00852   return box;
00853 }
00854 
00871 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00872 {
00873   int maxw = right - left + 1;
00874   int maxh = bottom - top + 1;
00875 
00876   /* It makes no sense to even try if it can't be drawn anyway, or
00877    * do we really want to support fonts of 0 or less pixels high? */
00878   if (maxh <= 0) return top;
00879 
00880   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
00881   int num = GB(tmp, 0, 16) + 1;
00882 
00883   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
00884   int total_height = num * mt;
00885 
00886   int skip_lines = 0;
00887   if (total_height > maxh) {
00888     if (maxh < mt) return top; //  Not enough room for a single line.
00889     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
00890       skip_lines = num;
00891       num = maxh / mt;
00892       skip_lines -= num;
00893     } else {
00894       num = maxh / mt;
00895     }
00896     total_height = num * mt;
00897   }
00898 
00899   int y;
00900   switch (align & SA_VERT_MASK) {
00901     case SA_TOP:
00902       y = top;
00903       break;
00904 
00905     case SA_VERT_CENTER:
00906       y = RoundDivSU(bottom + top - total_height, 2);
00907       break;
00908 
00909     case SA_BOTTOM:
00910       y = bottom - total_height;
00911       break;
00912 
00913     default: NOT_REACHED();
00914   }
00915 
00916   const char *src = str;
00917   DrawStringParams params(colour, fontsize);
00918   int written_top = bottom; // Uppermost position of rendering a line of text
00919   for (;;) {
00920     if (skip_lines == 0) {
00921       char buf2[DRAW_STRING_BUFFER];
00922       strecpy(buf2, src, lastof(buf2));
00923       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
00924       if (written_top > y) written_top = y;
00925       y += mt;
00926       num--;
00927     }
00928 
00929     for (;;) {
00930       WChar c = Utf8Consume(&src);
00931       if (c == 0) {
00932         break;
00933       } else if (c == SCC_SETX) {
00934         src++;
00935       } else if (c == SCC_SETXY) {
00936         src += 2;
00937       } else if (skip_lines > 0) {
00938         /* Skipped drawing, so do additional processing to update params. */
00939         if (c >= SCC_BLUE && c <= SCC_BLACK) {
00940           params.SetColour((TextColour)(c - SCC_BLUE));
00941         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
00942           params.SetPreviousColour();
00943         } else if (c == SCC_TINYFONT) {
00944           params.SetFontSize(FS_SMALL);
00945         } else if (c == SCC_BIGFONT) {
00946           params.SetFontSize(FS_LARGE);
00947         }
00948 
00949       }
00950     }
00951     if (skip_lines > 0) skip_lines--;
00952     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
00953   }
00954 }
00955 
00971 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00972 {
00973   char buffer[DRAW_STRING_BUFFER];
00974   strecpy(buffer, str, lastof(buffer));
00975   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline, fontsize);
00976 }
00977 
00993 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00994 {
00995   char buffer[DRAW_STRING_BUFFER];
00996   GetString(buffer, str, lastof(buffer));
00997   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline, fontsize);
00998 }
00999 
01010 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
01011 {
01012   FontSize size = start_fontsize;
01013   Dimension br;
01014   uint max_width;
01015   WChar c;
01016 
01017   br.width = br.height = max_width = 0;
01018   for (;;) {
01019     c = Utf8Consume(&str);
01020     if (c == 0) break;
01021     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01022       br.width += GetCharacterWidth(size, c);
01023     } else {
01024       switch (c) {
01025         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
01026         case SCC_SETXY:
01027           br.width  = max((uint)*str++, br.width);
01028           br.height = max((uint)*str++, br.height);
01029           break;
01030         case SCC_TINYFONT: size = FS_SMALL; break;
01031         case SCC_BIGFONT:  size = FS_LARGE; break;
01032         case '\n':
01033           br.height += GetCharacterHeight(size);
01034           if (br.width > max_width) max_width = br.width;
01035           br.width = 0;
01036           break;
01037       }
01038     }
01039   }
01040   br.height += GetCharacterHeight(size);
01041 
01042   br.width  = max(br.width, max_width);
01043   return br;
01044 }
01045 
01052 Dimension GetStringBoundingBox(StringID strid)
01053 {
01054   char buffer[DRAW_STRING_BUFFER];
01055 
01056   GetString(buffer, strid, lastof(buffer));
01057   return GetStringBoundingBox(buffer);
01058 }
01059 
01067 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
01068 {
01069   SetColourRemap(colour);
01070   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
01071 }
01072 
01090 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
01091 {
01092   DrawPixelInfo *dpi = _cur_dpi;
01093   bool draw_shadow = GetDrawGlyphShadow();
01094   UChar c;
01095   int xo = x;
01096 
01097   if (!parse_string_also_when_clipped) {
01098     /* in "mode multiline", the available space have been verified. Not in regular one.
01099      * So if the string cannot be drawn, return the original start to say so.*/
01100     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
01101   }
01102 
01103 switch_colour:;
01104   SetColourRemap(params.cur_colour);
01105 
01106 check_bounds:
01107   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
01108 skip_char:;
01109     for (;;) {
01110       c = *string++;
01111       if (!IsPrintable(c)) goto skip_cont;
01112     }
01113   }
01114 
01115   for (;;) {
01116     c = *string++;
01117 skip_cont:;
01118     if (c == 0) {
01119       return x;  // Nothing more to draw, get out. And here is the new x position
01120     }
01121     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01122       if (x >= dpi->left + dpi->width) goto skip_char;
01123       if (x + _max_char_width >= dpi->left) {
01124         const Sprite *glyph = GetGlyph(params.fontsize, c);
01125         if (draw_shadow && params.fontsize == FS_NORMAL && params.cur_colour != TC_BLACK && !(c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
01126           SetColourRemap(TC_BLACK);
01127           GfxMainBlitter(glyph, x + 1, y + 1, BM_COLOUR_REMAP);
01128           SetColourRemap(params.cur_colour);
01129         }
01130         GfxMainBlitter(glyph, x, y, BM_COLOUR_REMAP);
01131       }
01132       x += GetCharacterWidth(params.fontsize, c);
01133     } else if (c == '\n') { // newline = {}
01134       x = xo;  // We require a new line, so the x coordinate is reset
01135       y += GetCharacterHeight(params.fontsize);
01136       goto check_bounds;
01137     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
01138       params.SetColour((TextColour)(c - SCC_BLUE));
01139       goto switch_colour;
01140     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
01141       params.SetPreviousColour();
01142       goto switch_colour;
01143     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
01144       /* The characters are handled before calling this. */
01145       NOT_REACHED();
01146     } else if (c == SCC_TINYFONT) { // {TINYFONT}
01147       params.SetFontSize(FS_SMALL);
01148     } else if (c == SCC_BIGFONT) { // {BIGFONT}
01149       params.SetFontSize(FS_LARGE);
01150     } else if (!IsTextDirectionChar(c)) {
01151       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
01152     }
01153   }
01154 }
01155 
01163 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
01164 {
01165   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
01166 
01167   if (offset != NULL) {
01168     offset->x = UnScaleByZoom(sprite->x_offs, zoom);
01169     offset->y = UnScaleByZoom(sprite->y_offs, zoom);
01170   }
01171 
01172   Dimension d;
01173   d.width  = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
01174   d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
01175   return d;
01176 }
01177 
01186 void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
01187 {
01188   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01189   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01190     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01191     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
01192   } else if (pal != PAL_NONE) {
01193     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01194     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
01195   } else {
01196     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
01197   }
01198 }
01199 
01209 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
01210 {
01211   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01212   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01213     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01214     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite, zoom);
01215   } else if (pal != PAL_NONE) {
01216     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01217     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite, zoom);
01218   } else {
01219     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite, zoom);
01220   }
01221 }
01222 
01223 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
01224 {
01225   const DrawPixelInfo *dpi = _cur_dpi;
01226   Blitter::BlitterParams bp;
01227 
01228   /* Amount of pixels to clip from the source sprite */
01229   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left * ZOOM_LVL_BASE       ) : 0);
01230   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top  * ZOOM_LVL_BASE       ) : 0);
01231   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + (sub->right + 1)  * ZOOM_LVL_BASE)) : 0);
01232   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_LVL_BASE)) : 0);
01233 
01234   if (clip_left + clip_right >= sprite->width) return;
01235   if (clip_top + clip_bottom >= sprite->height) return;
01236 
01237   /* Move to the correct offset */
01238   x += sprite->x_offs;
01239   y += sprite->y_offs;
01240 
01241   /* Copy the main data directly from the sprite */
01242   bp.sprite = sprite->data;
01243   bp.sprite_width = sprite->width;
01244   bp.sprite_height = sprite->height;
01245   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
01246   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
01247   bp.top = 0;
01248   bp.left = 0;
01249   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
01250   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
01251 
01252   x += ScaleByZoom(bp.skip_left, dpi->zoom);
01253   y += ScaleByZoom(bp.skip_top, dpi->zoom);
01254 
01255   bp.dst = dpi->dst_ptr;
01256   bp.pitch = dpi->pitch;
01257   bp.remap = _colour_remap_ptr;
01258 
01259   assert(sprite->width > 0);
01260   assert(sprite->height > 0);
01261 
01262   if (bp.width <= 0) return;
01263   if (bp.height <= 0) return;
01264 
01265   y -= dpi->top;
01266   /* Check for top overflow */
01267   if (y < 0) {
01268     bp.height -= -UnScaleByZoom(y, dpi->zoom);
01269     if (bp.height <= 0) return;
01270     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
01271     y = 0;
01272   } else {
01273     bp.top = UnScaleByZoom(y, dpi->zoom);
01274   }
01275 
01276   /* Check for bottom overflow */
01277   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
01278   if (y > 0) {
01279     bp.height -= UnScaleByZoom(y, dpi->zoom);
01280     if (bp.height <= 0) return;
01281   }
01282 
01283   x -= dpi->left;
01284   /* Check for left overflow */
01285   if (x < 0) {
01286     bp.width -= -UnScaleByZoom(x, dpi->zoom);
01287     if (bp.width <= 0) return;
01288     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
01289     x = 0;
01290   } else {
01291     bp.left = UnScaleByZoom(x, dpi->zoom);
01292   }
01293 
01294   /* Check for right overflow */
01295   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
01296   if (x > 0) {
01297     bp.width -= UnScaleByZoom(x, dpi->zoom);
01298     if (bp.width <= 0) return;
01299   }
01300 
01301   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
01302   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
01303 
01304   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01305   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01306     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01307     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01308     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01309 
01310     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01311 
01312     if (topleft <= clicked && clicked <= bottomright) {
01313       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01314       if (offset < (uint)bp.width) {
01315         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01316       }
01317     }
01318   }
01319 
01320   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
01321 }
01322 
01323 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id, ZoomLevel zoom)
01324 {
01325   const DrawPixelInfo *dpi = _cur_dpi;
01326   Blitter::BlitterParams bp;
01327 
01328   /* Amount of pixels to clip from the source sprite */
01329   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
01330   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
01331   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
01332   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
01333 
01334   if (clip_left + clip_right >= sprite->width) return;
01335   if (clip_top + clip_bottom >= sprite->height) return;
01336 
01337   /* Scale it */
01338   x = ScaleByZoom(x, zoom);
01339   y = ScaleByZoom(y, zoom);
01340 
01341   /* Move to the correct offset */
01342   x += sprite->x_offs;
01343   y += sprite->y_offs;
01344 
01345   /* Copy the main data directly from the sprite */
01346   bp.sprite = sprite->data;
01347   bp.sprite_width = sprite->width;
01348   bp.sprite_height = sprite->height;
01349   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, zoom);
01350   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, zoom);
01351   bp.top = 0;
01352   bp.left = 0;
01353   bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
01354   bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
01355 
01356   x += ScaleByZoom(bp.skip_left, zoom);
01357   y += ScaleByZoom(bp.skip_top, zoom);
01358 
01359   bp.dst = dpi->dst_ptr;
01360   bp.pitch = dpi->pitch;
01361   bp.remap = _colour_remap_ptr;
01362 
01363   assert(sprite->width > 0);
01364   assert(sprite->height > 0);
01365 
01366   if (bp.width <= 0) return;
01367   if (bp.height <= 0) return;
01368 
01369   y -= ScaleByZoom(dpi->top, zoom);
01370   /* Check for top overflow */
01371   if (y < 0) {
01372     bp.height -= -UnScaleByZoom(y, zoom);
01373     if (bp.height <= 0) return;
01374     bp.skip_top += -UnScaleByZoom(y, zoom);
01375     y = 0;
01376   } else {
01377     bp.top = UnScaleByZoom(y, zoom);
01378   }
01379 
01380   /* Check for bottom overflow */
01381   y += ScaleByZoom(bp.height - dpi->height, zoom);
01382   if (y > 0) {
01383     bp.height -= UnScaleByZoom(y, zoom);
01384     if (bp.height <= 0) return;
01385   }
01386 
01387   x -= ScaleByZoom(dpi->left, zoom);
01388   /* Check for left overflow */
01389   if (x < 0) {
01390     bp.width -= -UnScaleByZoom(x, zoom);
01391     if (bp.width <= 0) return;
01392     bp.skip_left += -UnScaleByZoom(x, zoom);
01393     x = 0;
01394   } else {
01395     bp.left = UnScaleByZoom(x, zoom);
01396   }
01397 
01398   /* Check for right overflow */
01399   x += ScaleByZoom(bp.width - dpi->width, zoom);
01400   if (x > 0) {
01401     bp.width -= UnScaleByZoom(x, zoom);
01402     if (bp.width <= 0) return;
01403   }
01404 
01405   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, zoom));
01406   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, zoom));
01407 
01408   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01409   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01410     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01411     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01412     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01413 
01414     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01415 
01416     if (topleft <= clicked && clicked <= bottomright) {
01417       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01418       if (offset < (uint)bp.width) {
01419         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01420       }
01421     }
01422   }
01423 
01424   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, zoom);
01425 }
01426 
01427 void DoPaletteAnimations();
01428 
01429 void GfxInitPalettes()
01430 {
01431   memcpy(&_cur_palette, &_palette, sizeof(_cur_palette));
01432   DoPaletteAnimations();
01433 }
01434 
01435 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01436 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01437 
01438 void DoPaletteAnimations()
01439 {
01440   /* Animation counter for the palette animation. */
01441   static int palette_animation_counter = 0;
01442   palette_animation_counter += 8;
01443 
01444   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01445   const Colour *s;
01446   const ExtraPaletteValues *ev = &_extra_palette_values;
01447   Colour old_val[PALETTE_ANIM_SIZE];
01448   const uint old_tc = palette_animation_counter;
01449   uint i;
01450   uint j;
01451 
01452   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01453     palette_animation_counter = 0;
01454   }
01455 
01456   Colour *palette_pos = &_cur_palette.palette[PALETTE_ANIM_START];  // Points to where animations are taking place on the palette
01457   /* Makes a copy of the current anmation palette in old_val,
01458    * so the work on the current palette could be compared, see if there has been any changes */
01459   memcpy(old_val, palette_pos, sizeof(old_val));
01460 
01461   /* Fizzy Drink bubbles animation */
01462   s = ev->fizzy_drink;
01463   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01464   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01465     *palette_pos++ = s[j];
01466     j++;
01467     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01468   }
01469 
01470   /* Oil refinery fire animation */
01471   s = ev->oil_refinery;
01472   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01473   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01474     *palette_pos++ = s[j];
01475     j++;
01476     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01477   }
01478 
01479   /* Radio tower blinking */
01480   {
01481     byte i = (palette_animation_counter >> 1) & 0x7F;
01482     byte v;
01483 
01484     if (i < 0x3f) {
01485       v = 255;
01486     } else if (i < 0x4A || i >= 0x75) {
01487       v = 128;
01488     } else {
01489       v = 20;
01490     }
01491     palette_pos->r = v;
01492     palette_pos->g = 0;
01493     palette_pos->b = 0;
01494     palette_pos++;
01495 
01496     i ^= 0x40;
01497     if (i < 0x3f) {
01498       v = 255;
01499     } else if (i < 0x4A || i >= 0x75) {
01500       v = 128;
01501     } else {
01502       v = 20;
01503     }
01504     palette_pos->r = v;
01505     palette_pos->g = 0;
01506     palette_pos->b = 0;
01507     palette_pos++;
01508   }
01509 
01510   /* Handle lighthouse and stadium animation */
01511   s = ev->lighthouse;
01512   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01513   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01514     *palette_pos++ = s[j];
01515     j++;
01516     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01517   }
01518 
01519   /* Dark blue water */
01520   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01521   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01522   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01523     *palette_pos++ = s[j];
01524     j++;
01525     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01526   }
01527 
01528   /* Glittery water */
01529   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01530   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01531   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01532     *palette_pos++ = s[j];
01533     j += 3;
01534     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01535   }
01536 
01537   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01538     palette_animation_counter = old_tc;
01539   } else {
01540     if (memcmp(old_val, &_cur_palette.palette[PALETTE_ANIM_START], sizeof(old_val)) != 0 && _cur_palette.count_dirty == 0) {
01541       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01542       _cur_palette.first_dirty = PALETTE_ANIM_START;
01543       _cur_palette.count_dirty = PALETTE_ANIM_SIZE;
01544     }
01545   }
01546 }
01547 
01548 
01553 void LoadStringWidthTable(bool monospace)
01554 {
01555   for (FontSize fs = monospace ? FS_MONO : FS_BEGIN; fs < (monospace ? FS_END : FS_MONO); fs++) {
01556     _max_char_size[fs].width = 0;
01557     _max_char_size[fs].height = GetCharacterHeight(fs);
01558     for (uint i = 0; i != 224; i++) {
01559       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01560       _max_char_size[fs].width = max<int>(_max_char_size[fs].width, _stringwidth_table[fs][i]);
01561     }
01562 
01563     /* Needed because they need to be 1 more than the widest. */
01564     _max_char_size[fs].width++;
01565     _max_char_size[fs].height++;
01566   }
01567 
01568   _max_char_width  = 0;
01569   _max_char_height = 0;
01570   for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
01571     _max_char_width = max<int>(_max_char_width, _max_char_size[fs].width);
01572     _max_char_height = max<int>(_max_char_height, _max_char_size[fs].height);
01573   }
01574 
01575   ReInitAllWindows();
01576 }
01577 
01584 byte GetCharacterWidth(FontSize size, WChar key)
01585 {
01586   /* Use _stringwidth_table cache if possible */
01587   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01588 
01589   return GetGlyphWidth(size, key);
01590 }
01591 
01597 byte GetDigitWidth(FontSize size)
01598 {
01599   byte width = 0;
01600   for (char c = '0'; c <= '9'; c++) {
01601     width = max(GetCharacterWidth(size, c), width);
01602   }
01603   return width;
01604 }
01605 
01606 
01607 void ScreenSizeChanged()
01608 {
01609   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01610   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01611 
01612   /* check the dirty rect */
01613   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01614   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01615 
01616   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01617   _cursor.visible = false;
01618 }
01619 
01620 void UndrawMouseCursor()
01621 {
01622   /* Don't undraw the mouse cursor if the screen is not ready */
01623   if (_screen.dst_ptr == NULL) return;
01624 
01625   if (_cursor.visible) {
01626     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01627     _cursor.visible = false;
01628     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);
01629     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01630   }
01631 }
01632 
01633 void DrawMouseCursor()
01634 {
01635 #if defined(WINCE)
01636   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01637   return;
01638 #endif
01639 
01640   /* Don't draw the mouse cursor if the screen is not ready */
01641   if (_screen.dst_ptr == NULL) return;
01642 
01643   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01644   int x;
01645   int y;
01646   int w;
01647   int h;
01648 
01649   /* Redraw mouse cursor but only when it's inside the window */
01650   if (!_cursor.in_window) return;
01651 
01652   /* Don't draw the mouse cursor if it's already drawn */
01653   if (_cursor.visible) {
01654     if (!_cursor.dirty) return;
01655     UndrawMouseCursor();
01656   }
01657 
01658   w = _cursor.size.x;
01659   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01660   if (x < 0) {
01661     w += x;
01662     x = 0;
01663   }
01664   if (w > _screen.width - x) w = _screen.width - x;
01665   if (w <= 0) return;
01666   _cursor.draw_pos.x = x;
01667   _cursor.draw_size.x = w;
01668 
01669   h = _cursor.size.y;
01670   y = _cursor.pos.y + _cursor.offs.y;
01671   if (y < 0) {
01672     h += y;
01673     y = 0;
01674   }
01675   if (h > _screen.height - y) h = _screen.height - y;
01676   if (h <= 0) return;
01677   _cursor.draw_pos.y = y;
01678   _cursor.draw_size.y = h;
01679 
01680   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01681 
01682   /* Make backup of stuff below cursor */
01683   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01684 
01685   /* Draw cursor on screen */
01686   _cur_dpi = &_screen;
01687   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01688 
01689   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01690 
01691   _cursor.visible = true;
01692   _cursor.dirty = false;
01693 }
01694 
01695 void RedrawScreenRect(int left, int top, int right, int bottom)
01696 {
01697   assert(right <= _screen.width && bottom <= _screen.height);
01698   if (_cursor.visible) {
01699     if (right > _cursor.draw_pos.x &&
01700         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01701         bottom > _cursor.draw_pos.y &&
01702         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01703       UndrawMouseCursor();
01704     }
01705   }
01706 
01707 #ifdef ENABLE_NETWORK
01708   if (_networking) NetworkUndrawChatMessage();
01709 #endif /* ENABLE_NETWORK */
01710 
01711   DrawOverlappedWindowForAll(left, top, right, bottom);
01712 
01713   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01714 }
01715 
01721 void DrawDirtyBlocks()
01722 {
01723   byte *b = _dirty_blocks;
01724   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01725   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01726   int x;
01727   int y;
01728 
01729   if (HasModalProgress()) {
01730     /* We are generating the world, so release our rights to the map and
01731      * painting while we are waiting a bit. */
01732     _modal_progress_paint_mutex->EndCritical();
01733     _modal_progress_work_mutex->EndCritical();
01734 
01735     /* Wait a while and update _realtime_tick so we are given the rights */
01736     if (!IsFirstModalProgressLoop()) CSleep(MODAL_PROGRESS_REDRAW_TIMEOUT);
01737     _realtime_tick += MODAL_PROGRESS_REDRAW_TIMEOUT;
01738     _modal_progress_paint_mutex->BeginCritical();
01739     _modal_progress_work_mutex->BeginCritical();
01740 
01741     /* When we ended with the modal progress, do not draw the blocks.
01742      * Simply let the next run do so, otherwise we would be loading
01743      * the new state (and possibly change the blitter) when we hold
01744      * the drawing lock, which we must not do. */
01745     if (_switch_mode != SM_NONE && !HasModalProgress()) return;
01746   }
01747 
01748   y = 0;
01749   do {
01750     x = 0;
01751     do {
01752       if (*b != 0) {
01753         int left;
01754         int top;
01755         int right = x + DIRTY_BLOCK_WIDTH;
01756         int bottom = y;
01757         byte *p = b;
01758         int h2;
01759 
01760         /* First try coalescing downwards */
01761         do {
01762           *p = 0;
01763           p += _dirty_bytes_per_line;
01764           bottom += DIRTY_BLOCK_HEIGHT;
01765         } while (bottom != h && *p != 0);
01766 
01767         /* Try coalescing to the right too. */
01768         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01769         assert(h2 > 0);
01770         p = b;
01771 
01772         while (right != w) {
01773           byte *p2 = ++p;
01774           int h = h2;
01775           /* Check if a full line of dirty flags is set. */
01776           do {
01777             if (!*p2) goto no_more_coalesc;
01778             p2 += _dirty_bytes_per_line;
01779           } while (--h != 0);
01780 
01781           /* Wohoo, can combine it one step to the right!
01782            * Do that, and clear the bits. */
01783           right += DIRTY_BLOCK_WIDTH;
01784 
01785           h = h2;
01786           p2 = p;
01787           do {
01788             *p2 = 0;
01789             p2 += _dirty_bytes_per_line;
01790           } while (--h != 0);
01791         }
01792         no_more_coalesc:
01793 
01794         left = x;
01795         top = y;
01796 
01797         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01798         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01799         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01800         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01801 
01802         if (left < right && top < bottom) {
01803           RedrawScreenRect(left, top, right, bottom);
01804         }
01805 
01806       }
01807     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01808   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01809 
01810   _invalid_rect.left = w;
01811   _invalid_rect.top = h;
01812   _invalid_rect.right = 0;
01813   _invalid_rect.bottom = 0;
01814 }
01815 
01831 void SetDirtyBlocks(int left, int top, int right, int bottom)
01832 {
01833   byte *b;
01834   int width;
01835   int height;
01836 
01837   if (left < 0) left = 0;
01838   if (top < 0) top = 0;
01839   if (right > _screen.width) right = _screen.width;
01840   if (bottom > _screen.height) bottom = _screen.height;
01841 
01842   if (left >= right || top >= bottom) return;
01843 
01844   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01845   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01846   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01847   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01848 
01849   left /= DIRTY_BLOCK_WIDTH;
01850   top  /= DIRTY_BLOCK_HEIGHT;
01851 
01852   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01853 
01854   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01855   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01856 
01857   assert(width > 0 && height > 0);
01858 
01859   do {
01860     int i = width;
01861 
01862     do b[--i] = 0xFF; while (i != 0);
01863 
01864     b += _dirty_bytes_per_line;
01865   } while (--height != 0);
01866 }
01867 
01874 void MarkWholeScreenDirty()
01875 {
01876   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01877 }
01878 
01893 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01894 {
01895   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01896   const DrawPixelInfo *o = _cur_dpi;
01897 
01898   n->zoom = ZOOM_LVL_NORMAL;
01899 
01900   assert(width > 0);
01901   assert(height > 0);
01902 
01903   if ((left -= o->left) < 0) {
01904     width += left;
01905     if (width <= 0) return false;
01906     n->left = -left;
01907     left = 0;
01908   } else {
01909     n->left = 0;
01910   }
01911 
01912   if (width > o->width - left) {
01913     width = o->width - left;
01914     if (width <= 0) return false;
01915   }
01916   n->width = width;
01917 
01918   if ((top -= o->top) < 0) {
01919     height += top;
01920     if (height <= 0) return false;
01921     n->top = -top;
01922     top = 0;
01923   } else {
01924     n->top = 0;
01925   }
01926 
01927   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01928   n->pitch = o->pitch;
01929 
01930   if (height > o->height - top) {
01931     height = o->height - top;
01932     if (height <= 0) return false;
01933   }
01934   n->height = height;
01935 
01936   return true;
01937 }
01938 
01943 void UpdateCursorSize()
01944 {
01945   CursorVars *cv = &_cursor;
01946   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01947 
01948   cv->size.y = UnScaleByZoom(p->height, ZOOM_LVL_GUI);
01949   cv->size.x = UnScaleByZoom(p->width, ZOOM_LVL_GUI);
01950   cv->offs.x = UnScaleByZoom(p->x_offs, ZOOM_LVL_GUI);
01951   cv->offs.y = UnScaleByZoom(p->y_offs, ZOOM_LVL_GUI);
01952 
01953   cv->dirty = true;
01954 }
01955 
01961 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01962 {
01963   CursorVars *cv = &_cursor;
01964   if (cv->sprite == cursor) return;
01965 
01966   cv->sprite = cursor;
01967   cv->pal    = pal;
01968   UpdateCursorSize();
01969 
01970   cv->short_vehicle_offset = 0;
01971 }
01972 
01973 static void SwitchAnimatedCursor()
01974 {
01975   const AnimCursor *cur = _cursor.animate_cur;
01976 
01977   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01978 
01979   SetCursorSprite(cur->sprite, _cursor.pal);
01980 
01981   _cursor.animate_timeout = cur->display_time;
01982   _cursor.animate_cur     = cur + 1;
01983 }
01984 
01985 void CursorTick()
01986 {
01987   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01988     SwitchAnimatedCursor();
01989   }
01990 }
01991 
01998 void SetMouseCursor(CursorID sprite, PaletteID pal)
01999 {
02000   /* Turn off animation */
02001   _cursor.animate_timeout = 0;
02002   /* Set cursor */
02003   SetCursorSprite(sprite, pal);
02004 }
02005 
02011 void SetAnimatedMouseCursor(const AnimCursor *table)
02012 {
02013   _cursor.animate_list = table;
02014   _cursor.animate_cur = NULL;
02015   _cursor.pal = PAL_NONE;
02016   SwitchAnimatedCursor();
02017 }
02018 
02019 bool ChangeResInGame(int width, int height)
02020 {
02021   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
02022 }
02023 
02024 bool ToggleFullScreen(bool fs)
02025 {
02026   bool result = _video_driver->ToggleFullscreen(fs);
02027   if (_fullscreen != fs && _num_resolutions == 0) {
02028     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
02029   }
02030   return result;
02031 }
02032 
02033 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
02034 {
02035   int x = pa->width - pb->width;
02036   if (x != 0) return x;
02037   return pa->height - pb->height;
02038 }
02039 
02040 void SortResolutions(int count)
02041 {
02042   QSortT(_resolutions, count, &compare_res);
02043 }