# 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 "genworld.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 "thread/thread.h"
    00024 #include "window_func.h"
    00025 #include "newgrf_debug.h"
    00026
    00027 #include "table/palettes.h"
    00028 #include "table/sprites.h"
    00029 #include "table/control_codes.h"
    00030
    00031 byte _dirkeys;
    00032 bool _fullscreen;
    00033 CursorVars _cursor;
    00034 bool _ctrl_pressed;
    00035 bool _shift_pressed;
    00036 byte _fast_forward;
    00037 bool _left_button_down;
    00038 bool _left_button_clicked;
    00039 bool _right_button_down;
    00040 bool _right_button_clicked;
    00041 DrawPixelInfo _screen;
    00042 bool _screen_disable_anim = false;
    00043 bool _exit_game;
    00044 GameMode _game_mode;
    00045 SwitchMode _switch_mode;
    00046 PauseModeByte _pause_mode;
    00047 int _pal_first_dirty;
    00048 int _pal_count_dirty;
    00049
    00050 Colour _cur_palette[256];
    00051
    00052 static int _max_char_height;
    00053 static int _max_char_width;
    00054 static byte _stringwidth_table[FS_END][224];
    00055 DrawPixelInfo *_cur_dpi;
    00056 byte _colour_gradient[COLOUR_END][8];
    00057
    00058 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
    00059
    00064 struct DrawStringParams {
    00065   FontSize fontsize;
    00066   TextColour cur_colour, prev_colour;
    00067
    00068   DrawStringParams(TextColour colour) : fontsize(FS_NORMAL), cur_colour(colour), prev_colour(colour) {}
    00069
    00074   FORCEINLINE void SetColour(TextColour c)
    00075   {
    00076     assert(c >=  TC_BLUE && c <= TC_BLACK);
    00077     this->prev_colour = this->cur_colour;
    00078     this->cur_colour = c;
    00079   }
    00080
    00082   FORCEINLINE void SetPreviousColour()
    00083   {
    00084     Swap(this->cur_colour, this->prev_colour);
    00085   }
    00086
    00091   FORCEINLINE void SetFontSize(FontSize f)
    00092   {
    00093     this->fontsize = f;
    00094   }
    00095 };
    00096
    00097 static ReusableBuffer<uint8> _cursor_backup;
    00098
    00106 static Rect _invalid_rect;
    00107 static const byte *_colour_remap_ptr;
    00108 static byte _string_colourremap[3];
    00109
    00110 static const uint DIRTY_BLOCK_HEIGHT   = 8;
    00111 static const uint DIRTY_BLOCK_WIDTH    = 64;
    00112
    00113 static uint _dirty_bytes_per_line = 0;
    00114 static byte *_dirty_blocks = NULL;
    00115
    00116 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
    00117 {
    00118   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00119
    00120   if (xo == 0 && yo == 0) return;
    00121
    00122   if (_cursor.visible) UndrawMouseCursor();
    00123
    00124 #ifdef ENABLE_NETWORK
    00125   if (_networking) NetworkUndrawChatMessage();
    00126 #endif /* ENABLE_NETWORK */
    00127
    00128   blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
    00129   /* This part of the screen is now dirty. */
    00130   _video_driver->MakeDirty(left, top, width, height);
    00131 }
    00132
    00133
    00148 void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
    00149 {
    00150   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00151   const DrawPixelInfo *dpi = _cur_dpi;
    00152   void *dst;
    00153   const int otop = top;
    00154   const int oleft = left;
    00155
    00156   if (dpi->zoom != ZOOM_LVL_NORMAL) return;
    00157   if (left > right || top > bottom) return;
    00158   if (right < dpi->left || left >= dpi->left + dpi->width) return;
    00159   if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
    00160
    00161   if ( (left -= dpi->left) < 0) left = 0;
    00162   right = right - dpi->left + 1;
    00163   if (right > dpi->width) right = dpi->width;
    00164   right -= left;
    00165   assert(right > 0);
    00166
    00167   if ( (top -= dpi->top) < 0) top = 0;
    00168   bottom = bottom - dpi->top + 1;
    00169   if (bottom > dpi->height) bottom = dpi->height;
    00170   bottom -= top;
    00171   assert(bottom > 0);
    00172
    00173   dst = blitter->MoveTo(dpi->dst_ptr, left, top);
    00174
    00175   switch (mode) {
    00176     default: // FILLRECT_OPAQUE
    00177       blitter->DrawRect(dst, right, bottom, (uint8)colour);
    00178       break;
    00179
    00180     case FILLRECT_RECOLOUR:
    00181       blitter->DrawColourMappingRect(dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
    00182       break;
    00183
    00184     case FILLRECT_CHECKER: {
    00185       byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
    00186       do {
    00187         for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
    00188         dst = blitter->MoveTo(dst, 0, 1);
    00189       } while (--bottom > 0);
    00190       break;
    00191     }
    00192   }
    00193 }
    00194
    00195 void GfxDrawLine(int x, int y, int x2, int y2, int colour, int width)
    00196 {
    00197   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00198   DrawPixelInfo *dpi = _cur_dpi;
    00199
    00200   assert(width > 0);
    00201
    00202   x -= dpi->left;
    00203   x2 -= dpi->left;
    00204   y -= dpi->top;
    00205   y2 -= dpi->top;
    00206
    00207   /* Check clipping */
    00208   if (x + width / 2 < 0           && x2 + width / 2 < 0          ) return;
    00209   if (y + width / 2 < 0           && y2 + width / 2 < 0          ) return;
    00210   if (x - width / 2 > dpi->width  && x2 - width / 2 > dpi->width ) return;
    00211   if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return;
    00212
    00213   blitter->DrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour, width);
    00214 }
    00215
    00216 void GfxDrawLineUnscaled(int x, int y, int x2, int y2, int colour)
    00217 {
    00218   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00219   DrawPixelInfo *dpi = _cur_dpi;
    00220
    00221   x -= dpi->left;
    00222   x2 -= dpi->left;
    00223   y -= dpi->top;
    00224   y2 -= dpi->top;
    00225
    00226   /* Check clipping */
    00227   if (x < 0 && x2 < 0) return;
    00228   if (y < 0 && y2 < 0) return;
    00229   if (x > dpi->width  && x2 > dpi->width)  return;
    00230   if (y > dpi->height && y2 > dpi->height) return;
    00231
    00232   blitter->DrawLine(dpi->dst_ptr, UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
    00233       UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
    00234       UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
    00235 }
    00236
    00250 void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
    00251 {
    00252   /*           ....
    00253    *         ..    ....
    00254    *       ..          ....
    00255    *     ..                ^
    00256    *   <--__(dx1,dy1)    /(dx2,dy2)
    00257    *   :    --__       /   :
    00258    *   :        --__ /     :
    00259    *   :            *(x,y) :
    00260    *   :            |      :
    00261    *   :            |     ..
    00262    *    ....        |(dx3,dy3)
    00263    *        ....    | ..
    00264    *            ....V.
    00265    */
    00266
    00267   static const byte colour = PC_WHITE;
    00268
    00269   GfxDrawLineUnscaled(x, y, x + dx1, y + dy1, colour);
    00270   GfxDrawLineUnscaled(x, y, x + dx2, y + dy2, colour);
    00271   GfxDrawLineUnscaled(x, y, x + dx3, y + dy3, colour);
    00272
    00273   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
    00274   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
    00275   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
    00276   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
    00277   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
    00278   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
    00279 }
    00280
    00285 static void SetColourRemap(TextColour colour)
    00286 {
    00287   if (colour == TC_INVALID) return;
    00288
    00289   /* Black strings have no shading ever; the shading is black, so it
    00290    * would be invisible at best, but it actually makes it illegible. */
    00291   bool no_shade   = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
    00292   bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
    00293   colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
    00294
    00295   _string_colourremap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
    00296   _string_colourremap[2] = no_shade ? 0 : 1;
    00297   _colour_remap_ptr = _string_colourremap;
    00298 }
    00299
    00300 #if !defined(WITH_ICU)
    00301 typedef WChar UChar;
    00302 static UChar *HandleBiDiAndArabicShapes(UChar *text) { return text; }
    00303 #else
    00304 #include <unicode/ubidi.h>
    00305 #include <unicode/ushape.h>
    00306
    00336 static UChar *HandleBiDiAndArabicShapes(UChar *buffer)
    00337 {
    00338   static UChar input_output[DRAW_STRING_BUFFER];
    00339   UChar intermediate[DRAW_STRING_BUFFER];
    00340
    00341   UChar *t = buffer;
    00342   size_t length = 0;
    00343   while (*t != '\0' && length < lengthof(input_output) - 1) {
    00344     input_output[length++] = *t++;
    00345   }
    00346   input_output[length] = 0;
    00347
    00348   UErrorCode err = U_ZERO_ERROR;
    00349   UBiDi *para = ubidi_openSized((int32_t)length, 0, &err);
    00350   if (para == NULL) return buffer;
    00351
    00352   ubidi_setPara(para, input_output, (int32_t)length, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, &err);
    00353   ubidi_writeReordered(para, intermediate, (int32_t)length, UBIDI_REMOVE_BIDI_CONTROLS, &err);
    00354   length = u_shapeArabic(intermediate, (int32_t)length, input_output, lengthof(input_output), U_SHAPE_TEXT_DIRECTION_VISUAL_LTR | U_SHAPE_LETTERS_SHAPE, &err);
    00355   ubidi_close(para);
    00356
    00357   if (U_FAILURE(err)) return buffer;
    00358
    00359   input_output[length] = '\0';
    00360   return input_output;
    00361 }
    00362 #endif /* WITH_ICU */
    00363
    00364
    00374 static int TruncateString(char *str, int maxw, bool ignore_setxy, FontSize start_fontsize)
    00375 {
    00376   int w = 0;
    00377   FontSize size = start_fontsize;
    00378   int ddd, ddd_w;
    00379
    00380   WChar c;
    00381   char *ddd_pos;
    00382
    00383   ddd_w = ddd = GetCharacterWidth(size, '.') * 3;
    00384
    00385   for (ddd_pos = str; (c = Utf8Consume(const_cast<const char **>(&str))) != '\0'; ) {
    00386     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
    00387       w += GetCharacterWidth(size, c);
    00388
    00389       if (w > maxw) {
    00390         /* string got too big... insert dotdotdot, but make sure we do not
    00391          * print anything beyond the string termination character. */
    00392         for (int i = 0; *ddd_pos != '\0' && i < 3; i++, ddd_pos++) *ddd_pos = '.';
    00393         *ddd_pos = '\0';
    00394         return ddd_w;
    00395       }
    00396     } else {
    00397       if (c == SCC_SETX) {
    00398         if (!ignore_setxy) w = *str;
    00399         str++;
    00400       } else if (c == SCC_SETXY) {
    00401         if (!ignore_setxy) w = *str;
    00402         str += 2;
    00403       } else if (c == SCC_TINYFONT) {
    00404         size = FS_SMALL;
    00405         ddd = GetCharacterWidth(size, '.') * 3;
    00406       } else if (c == SCC_BIGFONT) {
    00407         size = FS_LARGE;
    00408         ddd = GetCharacterWidth(size, '.') * 3;
    00409       } else if (c == '\n') {
    00410         DEBUG(misc, 0, "Drawing string using newlines with DrawString instead of DrawStringMultiLine. Please notify the developers of this: [%s]", str);
    00411       }
    00412     }
    00413
    00414     /* Remember the last position where three dots fit. */
    00415     if (w + ddd < maxw) {
    00416       ddd_w = w + ddd;
    00417       ddd_pos = str;
    00418     }
    00419   }
    00420
    00421   return w;
    00422 }
    00423
    00424 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped = false);
    00425
    00432 static int GetStringWidth(const UChar *str, FontSize start_fontsize)
    00433 {
    00434   FontSize size = start_fontsize;
    00435   int max_width;
    00436   int width;
    00437   WChar c;
    00438
    00439   width = max_width = 0;
    00440   for (;;) {
    00441     c = *str++;
    00442     if (c == 0) break;
    00443     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
    00444       width += GetCharacterWidth(size, c);
    00445     } else {
    00446       switch (c) {
    00447         case SCC_SETX:
    00448         case SCC_SETXY:
    00449           /* At this point there is no SCC_SETX(Y) anymore */
    00450           NOT_REACHED();
    00451           break;
    00452         case SCC_TINYFONT: size = FS_SMALL; break;
    00453         case SCC_BIGFONT:  size = FS_LARGE; break;
    00454         case '\n':
    00455           max_width = max(max_width, width);
    00456           break;
    00457       }
    00458     }
    00459   }
    00460
    00461   return max(max_width, width);
    00462 }
    00463
    00482 static int DrawString(int left, int right, int top, char *str, const char *last, DrawStringParams &params, StringAlignment align, bool underline = false, bool truncate = true)
    00483 {
    00484   /* We need the outer limits of both left/right */
    00485   int min_left = INT32_MAX;
    00486   int max_right = INT32_MIN;
    00487
    00488   int initial_left = left;
    00489   int initial_right = right;
    00490   int initial_top = top;
    00491
    00492   if (truncate) TruncateString(str, right - left + 1, (align & SA_STRIP) == SA_STRIP, params.fontsize);
    00493
    00494   /*
    00495    * To support SETX and SETXY properly with RTL languages we have to
    00496    * calculate the offsets from the right. To do this we need to split
    00497    * the string and draw the parts separated by SETX(Y).
    00498    * So here we split
    00499    */
    00500   static SmallVector<UChar *, 4> setx_offsets;
    00501   setx_offsets.Clear();
    00502
    00503   UChar draw_buffer[DRAW_STRING_BUFFER];
    00504   UChar *p = draw_buffer;
    00505
    00506   *setx_offsets.Append() = p;
    00507
    00508   char *loc = str;
    00509   for (;;) {
    00510     WChar c;
    00511     /* We cannot use Utf8Consume as we need the location of the SETX(Y) */
    00512     size_t len = Utf8Decode(&c, loc);
    00513     *p++ = c;
    00514
    00515     if (c == '\0') break;
    00516     if (p >= lastof(draw_buffer) - 3) {
    00517       /* Make sure we never overflow (even if copying SCC_SETX(Y)). */
    00518       *p = '\0';
    00519       break;
    00520     }
    00521     if (c != SCC_SETX && c != SCC_SETXY) {
    00522       loc += len;
    00523       continue;
    00524     }
    00525
    00526     if (align & SA_STRIP) {
    00527       /* We do not want to keep the SETX(Y)!. It was already copied, so
    00528        * remove it and undo the incrementing of the pointer! */
    00529       *p-- = '\0';
    00530       loc += len + (c == SCC_SETXY ? 2 : 1);
    00531       continue;
    00532     }
    00533
    00534     if ((align & SA_HOR_MASK) != SA_LEFT) {
    00535       DEBUG(grf, 1, "Using SETX and/or SETXY when not aligned to the left. Fixing alignment...");
    00536
    00537       /* For left alignment and change the left so it will roughly be in the
    00538        * middle. This will never cause the string to be completely centered,
    00539        * but once SETX is used you cannot be sure the actual content of the
    00540        * string is centered, so it doesn't really matter. */
    00541       align = SA_LEFT | SA_FORCE;
    00542       initial_left = left = max(left, (left + right - (int)GetStringBoundingBox(str).width) / 2);
    00543     }
    00544
    00545     /* We add the begin of the string, but don't add it twice */
    00546     if (p != draw_buffer) {
    00547       *setx_offsets.Append() = p;
    00548       p[-1] = '\0';
    00549       *p++ = c;
    00550     }
    00551
    00552     /* Skip the SCC_SETX(Y) ... */
    00553     loc += len;
    00554     /* ... copy the x coordinate ... */
    00555     *p++ = *loc++;
    00556     /* ... and finally copy the y coordinate if it exists */
    00557     if (c == SCC_SETXY) *p++ = *loc++;
    00558   }
    00559
    00560   /* In case we have a RTL language we swap the alignment. */
    00561   if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && !(align & SA_STRIP) && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
    00562
    00563   for (UChar **iter = setx_offsets.Begin(); iter != setx_offsets.End(); iter++) {
    00564     UChar *to_draw = *iter;
    00565     int offset = 0;
    00566
    00567     /* Skip the SETX(Y) and set the appropriate offsets. */
    00568     if (*to_draw == SCC_SETX || *to_draw == SCC_SETXY) {
    00569       to_draw++;
    00570       offset = *to_draw++;
    00571       if (*to_draw == SCC_SETXY) top = initial_top + *to_draw++;
    00572     }
    00573
    00574     to_draw = HandleBiDiAndArabicShapes(to_draw);
    00575     int w = GetStringWidth(to_draw, params.fontsize);
    00576
    00577     /* right is the right most position to draw on. In this case we want to do
    00578      * calculations with the width of the string. In comparison right can be
    00579      * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
    00580      * So most +1/-1 additions are to move from lengthof to 'indices'.
    00581      */
    00582     switch (align & SA_HOR_MASK) {
    00583       case SA_LEFT:
    00584         /* right + 1 = left + w */
    00585         left = initial_left + offset;
    00586         right = left + w - 1;
    00587         break;
    00588
    00589       case SA_HOR_CENTER:
    00590         left  = RoundDivSU(initial_right + 1 + initial_left - w, 2);
    00591         /* right + 1 = left + w */
    00592         right = left + w - 1;
    00593         break;
    00594
    00595       case SA_RIGHT:
    00596         left = initial_right + 1 - w - offset;
    00597         break;
    00598
    00599       default:
    00600         NOT_REACHED();
    00601     }
    00602
    00603     min_left  = min(left, min_left);
    00604     max_right = max(right, max_right);
    00605
    00606     ReallyDoDrawString(to_draw, left, top, params, !truncate);
    00607     if (underline) {
    00608       GfxFillRect(left, top + FONT_HEIGHT_NORMAL, right, top + FONT_HEIGHT_NORMAL, _string_colourremap[1]);
    00609     }
    00610   }
    00611
    00612   return (align & SA_HOR_MASK) == SA_RIGHT ? min_left : max_right;
    00613 }
    00614
    00628 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline)
    00629 {
    00630   char buffer[DRAW_STRING_BUFFER];
    00631   strecpy(buffer, str, lastof(buffer));
    00632   DrawStringParams params(colour);
    00633   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
    00634 }
    00635
    00649 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline)
    00650 {
    00651   char buffer[DRAW_STRING_BUFFER];
    00652   GetString(buffer, str, lastof(buffer));
    00653   DrawStringParams params(colour);
    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
    00840 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline)
    00841 {
    00842   int maxw = right - left + 1;
    00843   int maxh = bottom - top + 1;
    00844
    00845   /* It makes no sense to even try if it can't be drawn anyway, or
    00846    * do we really want to support fonts of 0 or less pixels high? */
    00847   if (maxh <= 0) return top;
    00848
    00849   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
    00850   int num = GB(tmp, 0, 16) + 1;
    00851
    00852   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
    00853   int total_height = num * mt;
    00854
    00855   int skip_lines = 0;
    00856   if (total_height > maxh) {
    00857     if (maxh < mt) return top; //  Not enough room for a single line.
    00858     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
    00859       skip_lines = num;
    00860       num = maxh / mt;
    00861       skip_lines -= num;
    00862     } else {
    00863       num = maxh / mt;
    00864     }
    00865     total_height = num * mt;
    00866   }
    00867
    00868   int y;
    00869   switch (align & SA_VERT_MASK) {
    00870     case SA_TOP:
    00871       y = top;
    00872       break;
    00873
    00874     case SA_VERT_CENTER:
    00875       y = RoundDivSU(bottom + top - total_height, 2);
    00876       break;
    00877
    00878     case SA_BOTTOM:
    00879       y = bottom - total_height;
    00880       break;
    00881
    00882     default: NOT_REACHED();
    00883   }
    00884
    00885   const char *src = str;
    00886   DrawStringParams params(colour);
    00887   int written_top = bottom; // Uppermost position of rendering a line of text
    00888   for (;;) {
    00889     if (skip_lines == 0) {
    00890       char buf2[DRAW_STRING_BUFFER];
    00891       strecpy(buf2, src, lastof(buf2));
    00892       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
    00893       if (written_top > y) written_top = y;
    00894       y += mt;
    00895       num--;
    00896     }
    00897
    00898     for (;;) {
    00899       WChar c = Utf8Consume(&src);
    00900       if (c == 0) {
    00901         break;
    00902       } else if (c == SCC_SETX) {
    00903         src++;
    00904       } else if (c == SCC_SETXY) {
    00905         src += 2;
    00906       } else if (skip_lines > 0) {
    00907         /* Skipped drawing, so do additional processing to update params. */
    00908         if (c >= SCC_BLUE && c <= SCC_BLACK) {
    00909           params.SetColour((TextColour)(c - SCC_BLUE));
    00910         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
    00911           params.SetPreviousColour();
    00912         } else if (c == SCC_TINYFONT) {
    00913           params.SetFontSize(FS_SMALL);
    00914         } else if (c == SCC_BIGFONT) {
    00915           params.SetFontSize(FS_LARGE);
    00916         }
    00917
    00918       }
    00919     }
    00920     if (skip_lines > 0) skip_lines--;
    00921     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
    00922   }
    00923 }
    00924
    00939 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline)
    00940 {
    00941   char buffer[DRAW_STRING_BUFFER];
    00942   strecpy(buffer, str, lastof(buffer));
    00943   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
    00944 }
    00945
    00960 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline)
    00961 {
    00962   char buffer[DRAW_STRING_BUFFER];
    00963   GetString(buffer, str, lastof(buffer));
    00964   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
    00965 }
    00966
    00977 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
    00978 {
    00979   FontSize size = start_fontsize;
    00980   Dimension br;
    00981   uint max_width;
    00982   WChar c;
    00983
    00984   br.width = br.height = max_width = 0;
    00985   for (;;) {
    00986     c = Utf8Consume(&str);
    00987     if (c == 0) break;
    00988     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
    00989       br.width += GetCharacterWidth(size, c);
    00990     } else {
    00991       switch (c) {
    00992         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
    00993         case SCC_SETXY:
    00994           br.width  = max((uint)*str++, br.width);
    00995           br.height = max((uint)*str++, br.height);
    00996           break;
    00997         case SCC_TINYFONT: size = FS_SMALL; break;
    00998         case SCC_BIGFONT:  size = FS_LARGE; break;
    00999         case '\n':
    01000           br.height += GetCharacterHeight(size);
    01001           if (br.width > max_width) max_width = br.width;
    01002           br.width = 0;
    01003           break;
    01004       }
    01005     }
    01006   }
    01007   br.height += GetCharacterHeight(size);
    01008
    01009   br.width  = max(br.width, max_width);
    01010   return br;
    01011 }
    01012
    01019 Dimension GetStringBoundingBox(StringID strid)
    01020 {
    01021   char buffer[DRAW_STRING_BUFFER];
    01022
    01023   GetString(buffer, strid, lastof(buffer));
    01024   return GetStringBoundingBox(buffer);
    01025 }
    01026
    01034 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
    01035 {
    01036   SetColourRemap(colour);
    01037   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
    01038 }
    01039
    01057 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
    01058 {
    01059   DrawPixelInfo *dpi = _cur_dpi;
    01060   UChar c;
    01061   int xo = x;
    01062
    01063   if (!parse_string_also_when_clipped) {
    01064     /* in "mode multiline", the available space have been verified. Not in regular one.
    01065      * So if the string cannot be drawn, return the original start to say so.*/
    01066     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
    01067   }
    01068
    01069 switch_colour:;
    01070   SetColourRemap(params.cur_colour);
    01071
    01072 check_bounds:
    01073   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
    01074 skip_char:;
    01075     for (;;) {
    01076       c = *string++;
    01077       if (!IsPrintable(c)) goto skip_cont;
    01078     }
    01079   }
    01080
    01081   for (;;) {
    01082     c = *string++;
    01083 skip_cont:;
    01084     if (c == 0) {
    01085       return x;  // Nothing more to draw, get out. And here is the new x position
    01086     }
    01087     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
    01088       if (x >= dpi->left + dpi->width) goto skip_char;
    01089       if (x + _max_char_width >= dpi->left) {
    01090         GfxMainBlitter(GetGlyph(params.fontsize, c), x, y, BM_COLOUR_REMAP);
    01091       }
    01092       x += GetCharacterWidth(params.fontsize, c);
    01093     } else if (c == '\n') { // newline = {}
    01094       x = xo;  // We require a new line, so the x coordinate is reset
    01095       y += GetCharacterHeight(params.fontsize);
    01096       goto check_bounds;
    01097     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
    01098       params.SetColour((TextColour)(c - SCC_BLUE));
    01099       goto switch_colour;
    01100     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
    01101       params.SetPreviousColour();
    01102       goto switch_colour;
    01103     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
    01104       /* The characters are handled before calling this. */
    01105       NOT_REACHED();
    01106     } else if (c == SCC_TINYFONT) { // {TINYFONT}
    01107       params.SetFontSize(FS_SMALL);
    01108     } else if (c == SCC_BIGFONT) { // {BIGFONT}
    01109       params.SetFontSize(FS_LARGE);
    01110     } else if (!IsTextDirectionChar(c)) {
    01111       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
    01112     }
    01113   }
    01114 }
    01115
    01122 Dimension GetSpriteSize(SpriteID sprid)
    01123 {
    01124   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
    01125
    01126   Dimension d;
    01127   d.width  = max<int>(0, sprite->x_offs + sprite->width);
    01128   d.height = max<int>(0, sprite->y_offs + sprite->height);
    01129   return d;
    01130 }
    01131
    01140 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
    01141 {
    01142   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
    01143   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
    01144     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
    01145     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
    01146   } else if (pal != PAL_NONE) {
    01147     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
    01148     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
    01149   } else {
    01150     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
    01151   }
    01152 }
    01153
    01154 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
    01155 {
    01156   const DrawPixelInfo *dpi = _cur_dpi;
    01157   Blitter::BlitterParams bp;
    01158
    01159   /* Amount of pixels to clip from the source sprite */
    01160   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
    01161   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
    01162   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
    01163   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
    01164
    01165   if (clip_left + clip_right >= sprite->width) return;
    01166   if (clip_top + clip_bottom >= sprite->height) return;
    01167
    01168   /* Move to the correct offset */
    01169   x += sprite->x_offs;
    01170   y += sprite->y_offs;
    01171
    01172   /* Copy the main data directly from the sprite */
    01173   bp.sprite = sprite->data;
    01174   bp.sprite_width = sprite->width;
    01175   bp.sprite_height = sprite->height;
    01176   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
    01177   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
    01178   bp.top = 0;
    01179   bp.left = 0;
    01180   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
    01181   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
    01182
    01183   x += ScaleByZoom(bp.skip_left, dpi->zoom);
    01184   y += ScaleByZoom(bp.skip_top, dpi->zoom);
    01185
    01186   bp.dst = dpi->dst_ptr;
    01187   bp.pitch = dpi->pitch;
    01188   bp.remap = _colour_remap_ptr;
    01189
    01190   assert(sprite->width > 0);
    01191   assert(sprite->height > 0);
    01192
    01193   if (bp.width <= 0) return;
    01194   if (bp.height <= 0) return;
    01195
    01196   y -= dpi->top;
    01197   /* Check for top overflow */
    01198   if (y < 0) {
    01199     bp.height -= -UnScaleByZoom(y, dpi->zoom);
    01200     if (bp.height <= 0) return;
    01201     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
    01202     y = 0;
    01203   } else {
    01204     bp.top = UnScaleByZoom(y, dpi->zoom);
    01205   }
    01206
    01207   /* Check for bottom overflow */
    01208   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
    01209   if (y > 0) {
    01210     bp.height -= UnScaleByZoom(y, dpi->zoom);
    01211     if (bp.height <= 0) return;
    01212   }
    01213
    01214   x -= dpi->left;
    01215   /* Check for left overflow */
    01216   if (x < 0) {
    01217     bp.width -= -UnScaleByZoom(x, dpi->zoom);
    01218     if (bp.width <= 0) return;
    01219     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
    01220     x = 0;
    01221   } else {
    01222     bp.left = UnScaleByZoom(x, dpi->zoom);
    01223   }
    01224
    01225   /* Check for right overflow */
    01226   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
    01227   if (x > 0) {
    01228     bp.width -= UnScaleByZoom(x, dpi->zoom);
    01229     if (bp.width <= 0) return;
    01230   }
    01231
    01232   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
    01233   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
    01234
    01235   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
    01236   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
    01237     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    01238     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
    01239     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
    01240
    01241     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
    01242
    01243     if (topleft <= clicked && clicked <= bottomright) {
    01244       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
    01245       if (offset < (uint)bp.width) {
    01246         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
    01247       }
    01248     }
    01249   }
    01250
    01251   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
    01252 }
    01253
    01254 void DoPaletteAnimations();
    01255
    01256 void GfxInitPalettes()
    01257 {
    01258   memcpy(_cur_palette, _palette, sizeof(_cur_palette));
    01259
    01260   DoPaletteAnimations();
    01261   _pal_first_dirty = 0;
    01262   _pal_count_dirty = 256;
    01263 }
    01264
    01265 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
    01266 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
    01267
    01268 void DoPaletteAnimations()
    01269 {
    01270   /* Animation counter for the palette animation. */
    01271   static int palette_animation_counter = 0;
    01272   palette_animation_counter += 8;
    01273
    01274   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    01275   const Colour *s;
    01276   const ExtraPaletteValues *ev = &_extra_palette_values;
    01277   Colour old_val[PALETTE_ANIM_SIZE];
    01278   const uint old_tc = palette_animation_counter;
    01279   uint i;
    01280   uint j;
    01281
    01282   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
    01283     palette_animation_counter = 0;
    01284   }
    01285
    01286   Colour *palette_pos = &_cur_palette[PALETTE_ANIM_START];  // Points to where animations are taking place on the palette
    01287   /* Makes a copy of the current anmation palette in old_val,
    01288    * so the work on the current palette could be compared, see if there has been any changes */
    01289   memcpy(old_val, palette_pos, sizeof(old_val));
    01290
    01291   /* Fizzy Drink bubbles animation */
    01292   s = ev->fizzy_drink;
    01293   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
    01294   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
    01295     *palette_pos++ = s[j];
    01296     j++;
    01297     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
    01298   }
    01299
    01300   /* Oil refinery fire animation */
    01301   s = ev->oil_refinery;
    01302   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
    01303   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
    01304     *palette_pos++ = s[j];
    01305     j++;
    01306     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
    01307   }
    01308
    01309   /* Radio tower blinking */
    01310   {
    01311     byte i = (palette_animation_counter >> 1) & 0x7F;
    01312     byte v;
    01313
    01314     if (i < 0x3f) {
    01315       v = 255;
    01316     } else if (i < 0x4A || i >= 0x75) {
    01317       v = 128;
    01318     } else {
    01319       v = 20;
    01320     }
    01321     palette_pos->r = v;
    01322     palette_pos->g = 0;
    01323     palette_pos->b = 0;
    01324     palette_pos++;
    01325
    01326     i ^= 0x40;
    01327     if (i < 0x3f) {
    01328       v = 255;
    01329     } else if (i < 0x4A || i >= 0x75) {
    01330       v = 128;
    01331     } else {
    01332       v = 20;
    01333     }
    01334     palette_pos->r = v;
    01335     palette_pos->g = 0;
    01336     palette_pos->b = 0;
    01337     palette_pos++;
    01338   }
    01339
    01340   /* Handle lighthouse and stadium animation */
    01341   s = ev->lighthouse;
    01342   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
    01343   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
    01344     *palette_pos++ = s[j];
    01345     j++;
    01346     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
    01347   }
    01348
    01349   /* Dark blue water */
    01350   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
    01351   j = EXTR(320, EPV_CYCLES_DARK_WATER);
    01352   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
    01353     *palette_pos++ = s[j];
    01354     j++;
    01355     if (j == EPV_CYCLES_DARK_WATER) j = 0;
    01356   }
    01357
    01358   /* Glittery water */
    01359   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
    01360   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
    01361   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
    01362     *palette_pos++ = s[j];
    01363     j += 3;
    01364     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
    01365   }
    01366
    01367   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
    01368     palette_animation_counter = old_tc;
    01369   } else {
    01370     if (memcmp(old_val, &_cur_palette[PALETTE_ANIM_START], sizeof(old_val)) != 0) {
    01371       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
    01372       _pal_first_dirty = PALETTE_ANIM_START;
    01373       _pal_count_dirty = PALETTE_ANIM_SIZE;
    01374     }
    01375   }
    01376 }
    01377
    01378
    01380 void LoadStringWidthTable()
    01381 {
    01382   _max_char_height = 0;
    01383   _max_char_width  = 0;
    01384
    01385   for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
    01386     _max_char_height = max<int>(_max_char_height, GetCharacterHeight(fs));
    01387     for (uint i = 0; i != 224; i++) {
    01388       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
    01389       _max_char_width = max<int>(_max_char_width, _stringwidth_table[fs][i]);
    01390     }
    01391   }
    01392
    01393   /* Needed because they need to be 1 more than the widest. */
    01394   _max_char_height++;
    01395   _max_char_width++;
    01396
    01397   ReInitAllWindows();
    01398 }
    01399
    01406 byte GetCharacterWidth(FontSize size, WChar key)
    01407 {
    01408   /* Use _stringwidth_table cache if possible */
    01409   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
    01410
    01411   return GetGlyphWidth(size, key);
    01412 }
    01413
    01419 byte GetDigitWidth(FontSize size)
    01420 {
    01421   byte width = 0;
    01422   for (char c = '0'; c <= '9'; c++) {
    01423     width = max(GetCharacterWidth(size, c), width);
    01424   }
    01425   return width;
    01426 }
    01427
    01428
    01429 void ScreenSizeChanged()
    01430 {
    01431   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
    01432   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
    01433
    01434   /* check the dirty rect */
    01435   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
    01436   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
    01437
    01438   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
    01439   _cursor.visible = false;
    01440 }
    01441
    01442 void UndrawMouseCursor()
    01443 {
    01444   /* Don't undraw the mouse cursor if the screen is not ready */
    01445   if (_screen.dst_ptr == NULL) return;
    01446
    01447   if (_cursor.visible) {
    01448     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    01449     _cursor.visible = false;
    01450     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);
    01451     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
    01452   }
    01453 }
    01454
    01455 void DrawMouseCursor()
    01456 {
    01457 #if defined(WINCE)
    01458   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
    01459   return;
    01460 #endif
    01461
    01462   /* Don't draw the mouse cursor if the screen is not ready */
    01463   if (_screen.dst_ptr == NULL) return;
    01464
    01465   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    01466   int x;
    01467   int y;
    01468   int w;
    01469   int h;
    01470
    01471   /* Redraw mouse cursor but only when it's inside the window */
    01472   if (!_cursor.in_window) return;
    01473
    01474   /* Don't draw the mouse cursor if it's already drawn */
    01475   if (_cursor.visible) {
    01476     if (!_cursor.dirty) return;
    01477     UndrawMouseCursor();
    01478   }
    01479
    01480   w = _cursor.size.x;
    01481   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
    01482   if (x < 0) {
    01483     w += x;
    01484     x = 0;
    01485   }
    01486   if (w > _screen.width - x) w = _screen.width - x;
    01487   if (w <= 0) return;
    01488   _cursor.draw_pos.x = x;
    01489   _cursor.draw_size.x = w;
    01490
    01491   h = _cursor.size.y;
    01492   y = _cursor.pos.y + _cursor.offs.y;
    01493   if (y < 0) {
    01494     h += y;
    01495     y = 0;
    01496   }
    01497   if (h > _screen.height - y) h = _screen.height - y;
    01498   if (h <= 0) return;
    01499   _cursor.draw_pos.y = y;
    01500   _cursor.draw_size.y = h;
    01501
    01502   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
    01503
    01504   /* Make backup of stuff below cursor */
    01505   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
    01506
    01507   /* Draw cursor on screen */
    01508   _cur_dpi = &_screen;
    01509   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
    01510
    01511   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
    01512
    01513   _cursor.visible = true;
    01514   _cursor.dirty = false;
    01515 }
    01516
    01517 void RedrawScreenRect(int left, int top, int right, int bottom)
    01518 {
    01519   assert(right <= _screen.width && bottom <= _screen.height);
    01520   if (_cursor.visible) {
    01521     if (right > _cursor.draw_pos.x &&
    01522         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
    01523         bottom > _cursor.draw_pos.y &&
    01524         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
    01525       UndrawMouseCursor();
    01526     }
    01527   }
    01528
    01529 #ifdef ENABLE_NETWORK
    01530   if (_networking) NetworkUndrawChatMessage();
    01531 #endif /* ENABLE_NETWORK */
    01532
    01533   DrawOverlappedWindowForAll(left, top, right, bottom);
    01534
    01535   _video_driver->MakeDirty(left, top, right - left, bottom - top);
    01536 }
    01537
    01543 void DrawDirtyBlocks()
    01544 {
    01545   byte *b = _dirty_blocks;
    01546   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
    01547   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
    01548   int x;
    01549   int y;
    01550
    01551   if (IsGeneratingWorld()) {
    01552     /* We are generating the world, so release our rights to the map and
    01553      * painting while we are waiting a bit. */
    01554     _genworld_paint_mutex->EndCritical();
    01555     _genworld_mapgen_mutex->EndCritical();
    01556
    01557     /* Wait a while and update _realtime_tick so we are given the rights */
    01558     CSleep(GENWORLD_REDRAW_TIMEOUT);
    01559     _realtime_tick += GENWORLD_REDRAW_TIMEOUT;
    01560     _genworld_paint_mutex->BeginCritical();
    01561     _genworld_mapgen_mutex->BeginCritical();
    01562   }
    01563
    01564   y = 0;
    01565   do {
    01566     x = 0;
    01567     do {
    01568       if (*b != 0) {
    01569         int left;
    01570         int top;
    01571         int right = x + DIRTY_BLOCK_WIDTH;
    01572         int bottom = y;
    01573         byte *p = b;
    01574         int h2;
    01575
    01576         /* First try coalescing downwards */
    01577         do {
    01578           *p = 0;
    01579           p += _dirty_bytes_per_line;
    01580           bottom += DIRTY_BLOCK_HEIGHT;
    01581         } while (bottom != h && *p != 0);
    01582
    01583         /* Try coalescing to the right too. */
    01584         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
    01585         assert(h2 > 0);
    01586         p = b;
    01587
    01588         while (right != w) {
    01589           byte *p2 = ++p;
    01590           int h = h2;
    01591           /* Check if a full line of dirty flags is set. */
    01592           do {
    01593             if (!*p2) goto no_more_coalesc;
    01594             p2 += _dirty_bytes_per_line;
    01595           } while (--h != 0);
    01596
    01597           /* Wohoo, can combine it one step to the right!
    01598            * Do that, and clear the bits. */
    01599           right += DIRTY_BLOCK_WIDTH;
    01600
    01601           h = h2;
    01602           p2 = p;
    01603           do {
    01604             *p2 = 0;
    01605             p2 += _dirty_bytes_per_line;
    01606           } while (--h != 0);
    01607         }
    01608         no_more_coalesc:
    01609
    01610         left = x;
    01611         top = y;
    01612
    01613         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
    01614         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
    01615         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
    01616         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
    01617
    01618         if (left < right && top < bottom) {
    01619           RedrawScreenRect(left, top, right, bottom);
    01620         }
    01621
    01622       }
    01623     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
    01624   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
    01625
    01626   _invalid_rect.left = w;
    01627   _invalid_rect.top = h;
    01628   _invalid_rect.right = 0;
    01629   _invalid_rect.bottom = 0;
    01630 }
    01631
    01647 void SetDirtyBlocks(int left, int top, int right, int bottom)
    01648 {
    01649   byte *b;
    01650   int width;
    01651   int height;
    01652
    01653   if (left < 0) left = 0;
    01654   if (top < 0) top = 0;
    01655   if (right > _screen.width) right = _screen.width;
    01656   if (bottom > _screen.height) bottom = _screen.height;
    01657
    01658   if (left >= right || top >= bottom) return;
    01659
    01660   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
    01661   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
    01662   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
    01663   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
    01664
    01665   left /= DIRTY_BLOCK_WIDTH;
    01666   top  /= DIRTY_BLOCK_HEIGHT;
    01667
    01668   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
    01669
    01670   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
    01671   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
    01672
    01673   assert(width > 0 && height > 0);
    01674
    01675   do {
    01676     int i = width;
    01677
    01678     do b[--i] = 0xFF; while (i != 0);
    01679
    01680     b += _dirty_bytes_per_line;
    01681   } while (--height != 0);
    01682 }
    01683
    01690 void MarkWholeScreenDirty()
    01691 {
    01692   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
    01693 }
    01694
    01709 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
    01710 {
    01711   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    01712   const DrawPixelInfo *o = _cur_dpi;
    01713
    01714   n->zoom = ZOOM_LVL_NORMAL;
    01715
    01716   assert(width > 0);
    01717   assert(height > 0);
    01718
    01719   if ((left -= o->left) < 0) {
    01720     width += left;
    01721     if (width <= 0) return false;
    01722     n->left = -left;
    01723     left = 0;
    01724   } else {
    01725     n->left = 0;
    01726   }
    01727
    01728   if (width > o->width - left) {
    01729     width = o->width - left;
    01730     if (width <= 0) return false;
    01731   }
    01732   n->width = width;
    01733
    01734   if ((top -= o->top) < 0) {
    01735     height += top;
    01736     if (height <= 0) return false;
    01737     n->top = -top;
    01738     top = 0;
    01739   } else {
    01740     n->top = 0;
    01741   }
    01742
    01743   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
    01744   n->pitch = o->pitch;
    01745
    01746   if (height > o->height - top) {
    01747     height = o->height - top;
    01748     if (height <= 0) return false;
    01749   }
    01750   n->height = height;
    01751
    01752   return true;
    01753 }
    01754
    01759 void UpdateCursorSize()
    01760 {
    01761   CursorVars *cv = &_cursor;
    01762   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
    01763
    01764   cv->size.y = p->height;
    01765   cv->size.x = p->width;
    01766   cv->offs.x = p->x_offs;
    01767   cv->offs.y = p->y_offs;
    01768
    01769   cv->dirty = true;
    01770 }
    01771
    01777 static void SetCursorSprite(CursorID cursor, PaletteID pal)
    01778 {
    01779   CursorVars *cv = &_cursor;
    01780   if (cv->sprite == cursor) return;
    01781
    01782   cv->sprite = cursor;
    01783   cv->pal    = pal;
    01784   UpdateCursorSize();
    01785
    01786   cv->short_vehicle_offset = 0;
    01787 }
    01788
    01789 static void SwitchAnimatedCursor()
    01790 {
    01791   const AnimCursor *cur = _cursor.animate_cur;
    01792
    01793   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
    01794
    01795   SetCursorSprite(cur->sprite, _cursor.pal);
    01796
    01797   _cursor.animate_timeout = cur->display_time;
    01798   _cursor.animate_cur     = cur + 1;
    01799 }
    01800
    01801 void CursorTick()
    01802 {
    01803   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
    01804     SwitchAnimatedCursor();
    01805   }
    01806 }
    01807
    01814 void SetMouseCursor(CursorID sprite, PaletteID pal)
    01815 {
    01816   /* Turn off animation */
    01817   _cursor.animate_timeout = 0;
    01818   /* Set cursor */
    01819   SetCursorSprite(sprite, pal);
    01820 }
    01821
    01827 void SetAnimatedMouseCursor(const AnimCursor *table)
    01828 {
    01829   _cursor.animate_list = table;
    01830   _cursor.animate_cur = NULL;
    01831   _cursor.pal = PAL_NONE;
    01832   SwitchAnimatedCursor();
    01833 }
    01834
    01835 bool ChangeResInGame(int width, int height)
    01836 {
    01837   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
    01838 }
    01839
    01840 bool ToggleFullScreen(bool fs)
    01841 {
    01842   bool result = _video_driver->ToggleFullscreen(fs);
    01843   if (_fullscreen != fs && _num_resolutions == 0) {
    01844     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
    01845   }
    01846   return result;
    01847 }
    01848
    01849 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
    01850 {
    01851   int x = pa->width - pb->width;
    01852   if (x != 0) return x;
    01853   return pa->height - pb->height;
    01854 }
    01855
    01856 void SortResolutions(int count)
    01857 {
    01858   QSortT(_resolutions, count, &compare_res);
    01859 }