gfx.cpp

Go to the documentation of this file.
00001 /* $Id: gfx.cpp 22651 2011-07-10 20:23:04Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "gfx_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)
00196 {
00197   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00198   DrawPixelInfo *dpi = _cur_dpi;
00199 
00200   x -= dpi->left;
00201   x2 -= dpi->left;
00202   y -= dpi->top;
00203   y2 -= dpi->top;
00204 
00205   /* Check clipping */
00206   if (x < 0 && x2 < 0) return;
00207   if (y < 0 && y2 < 0) return;
00208   if (x > dpi->width  && x2 > dpi->width)  return;
00209   if (y > dpi->height && y2 > dpi->height) return;
00210 
00211   blitter->DrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour);
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);
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 = 15;
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[_use_palette][colour];
00294   _string_colourremap[2] = no_shade ? 0 : (_use_palette == PAL_DOS ? 1 : 215);
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 
00626 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline)
00627 {
00628   char buffer[DRAW_STRING_BUFFER];
00629   strecpy(buffer, str, lastof(buffer));
00630   DrawStringParams params(colour);
00631   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00632 }
00633 
00647 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline)
00648 {
00649   char buffer[DRAW_STRING_BUFFER];
00650   GetString(buffer, str, lastof(buffer));
00651   DrawStringParams params(colour);
00652   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00653 }
00654 
00675 uint32 FormatStringLinebreaks(char *str, const char *last, int maxw, FontSize size)
00676 {
00677   int num = 0;
00678 
00679   assert(maxw > 0);
00680 
00681   for (;;) {
00682     /* The character *after* the last space. */
00683     char *last_space = NULL;
00684     int w = 0;
00685 
00686     for (;;) {
00687       WChar c = Utf8Consume(const_cast<const char **>(&str));
00688       /* whitespace is where we will insert the line-break */
00689       if (IsWhitespace(c)) last_space = str;
00690 
00691       if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00692         int char_w = GetCharacterWidth(size, c);
00693         w += char_w;
00694         if (w > maxw) {
00695           /* The string is longer than maximum width so we need to decide
00696            * what to do with it. */
00697           if (w == char_w) {
00698             /* The character is wider than allowed width; don't know
00699              * what to do with this case... bail out! */
00700             return num + (size << 16);
00701           }
00702           if (last_space == NULL) {
00703             /* No space has been found. Just terminate at our current
00704              * location. This usually happens for languages that do not
00705              * require spaces in strings, like Chinese, Japanese and
00706              * Korean. For other languages terminating mid-word might
00707              * not be the best, but terminating the whole string instead
00708              * of continuing the word at the next line is worse. */
00709             str = Utf8PrevChar(str);
00710             size_t len = strlen(str);
00711             char *terminator = str + len;
00712 
00713             /* The string location + length of the string + 1 for '\0'
00714              * always fits; otherwise there's no trailing '\0' and it
00715              * it not a valid string. */
00716             assert(terminator <= last);
00717             assert(*terminator == '\0');
00718 
00719             /* If the string is too long we have to terminate it earlier. */
00720             if (terminator == last) {
00721               /* Get the 'begin' of the previous character and make that
00722                * the terminator of the string; we truncate it 'early'. */
00723               *Utf8PrevChar(terminator) = '\0';
00724               len = strlen(str);
00725             }
00726             /* Also move the terminator! */
00727             memmove(str + 1, str, len + 1);
00728             *str = '\0';
00729             /* str needs to point to the character *after* the last space */
00730             str++;
00731           } else {
00732             /* A space is found; perfect place to terminate */
00733             str = last_space;
00734           }
00735           break;
00736         }
00737       } else {
00738         switch (c) {
00739           case '\0': return num + (size << 16);
00740           case SCC_SETX:  str++; break;
00741           case SCC_SETXY: str += 2; break;
00742           case SCC_TINYFONT: size = FS_SMALL; break;
00743           case SCC_BIGFONT:  size = FS_LARGE; break;
00744           case '\n': goto end_of_inner_loop;
00745         }
00746       }
00747     }
00748 end_of_inner_loop:
00749     /* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
00750      * and increase linecount. We use Utf8PrevChar() as also non 1 char long
00751      * whitespace seperators are supported */
00752     num++;
00753     char *s = Utf8PrevChar(str);
00754     *s++ = '\0';
00755 
00756     /* In which case (see above) we will shift remainder to left and close the gap */
00757     if (str - s >= 1) {
00758       for (; str[-1] != '\0';) *s++ = *str++;
00759     }
00760   }
00761 }
00762 
00763 
00772 static int GetMultilineStringHeight(const char *src, int num, FontSize start_fontsize)
00773 {
00774   int maxy = 0;
00775   int y = 0;
00776   int fh = GetCharacterHeight(start_fontsize);
00777 
00778   for (;;) {
00779     WChar c = Utf8Consume(&src);
00780 
00781     switch (c) {
00782       case 0:            y += fh; if (--num < 0) return maxy; break;
00783       case '\n':         y += fh;                             break;
00784       case SCC_SETX:     src++;                               break;
00785       case SCC_SETXY:    src++; y = (int)*src++;              break;
00786       case SCC_TINYFONT: fh = GetCharacterHeight(FS_SMALL);   break;
00787       case SCC_BIGFONT:  fh = GetCharacterHeight(FS_LARGE);   break;
00788       default:           maxy = max<int>(maxy, y + fh);       break;
00789     }
00790   }
00791 }
00792 
00793 
00800 int GetStringHeight(StringID str, int maxw)
00801 {
00802   char buffer[DRAW_STRING_BUFFER];
00803 
00804   GetString(buffer, str, lastof(buffer));
00805 
00806   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00807 
00808   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00809 }
00810 
00817 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00818 {
00819   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00820   return box;
00821 }
00822 
00838 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline)
00839 {
00840   int maxw = right - left + 1;
00841   int maxh = bottom - top + 1;
00842 
00843   /* It makes no sense to even try if it can't be drawn anyway, or
00844    * do we really want to support fonts of 0 or less pixels high? */
00845   if (maxh <= 0) return top;
00846 
00847   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
00848   int num = GB(tmp, 0, 16) + 1;
00849 
00850   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
00851   int total_height = num * mt;
00852 
00853   int skip_lines = 0;
00854   if (total_height > maxh) {
00855     if (maxh < mt) return top; //  Not enough room for a single line.
00856     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
00857       skip_lines = num;
00858       num = maxh / mt;
00859       skip_lines -= num;
00860     } else {
00861       num = maxh / mt;
00862     }
00863     total_height = num * mt;
00864   }
00865 
00866   int y;
00867   switch (align & SA_VERT_MASK) {
00868     case SA_TOP:
00869       y = top;
00870       break;
00871 
00872     case SA_VERT_CENTER:
00873       y = RoundDivSU(bottom + top - total_height, 2);
00874       break;
00875 
00876     case SA_BOTTOM:
00877       y = bottom - total_height;
00878       break;
00879 
00880     default: NOT_REACHED();
00881   }
00882 
00883   const char *src = str;
00884   DrawStringParams params(colour);
00885   int written_top = bottom; // Uppermost position of rendering a line of text
00886   for (;;) {
00887     if (skip_lines == 0) {
00888       char buf2[DRAW_STRING_BUFFER];
00889       strecpy(buf2, src, lastof(buf2));
00890       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
00891       if (written_top > y) written_top = y;
00892       y += mt;
00893       num--;
00894     }
00895 
00896     for (;;) {
00897       WChar c = Utf8Consume(&src);
00898       if (c == 0) {
00899         break;
00900       } else if (c == SCC_SETX) {
00901         src++;
00902       } else if (c == SCC_SETXY) {
00903         src += 2;
00904       } else if (skip_lines > 0) {
00905         /* Skipped drawing, so do additional processing to update params. */
00906         if (c >= SCC_BLUE && c <= SCC_BLACK) {
00907           params.SetColour((TextColour)(c - SCC_BLUE));
00908         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
00909           params.SetPreviousColour();
00910         } else if (c == SCC_TINYFONT) {
00911           params.SetFontSize(FS_SMALL);
00912         } else if (c == SCC_BIGFONT) {
00913           params.SetFontSize(FS_LARGE);
00914         }
00915 
00916       }
00917     }
00918     if (skip_lines > 0) skip_lines--;
00919     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
00920   }
00921 }
00922 
00937 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline)
00938 {
00939   char buffer[DRAW_STRING_BUFFER];
00940   strecpy(buffer, str, lastof(buffer));
00941   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00942 }
00943 
00958 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline)
00959 {
00960   char buffer[DRAW_STRING_BUFFER];
00961   GetString(buffer, str, lastof(buffer));
00962   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00963 }
00964 
00975 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
00976 {
00977   FontSize size = start_fontsize;
00978   Dimension br;
00979   uint max_width;
00980   WChar c;
00981 
00982   br.width = br.height = max_width = 0;
00983   for (;;) {
00984     c = Utf8Consume(&str);
00985     if (c == 0) break;
00986     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00987       br.width += GetCharacterWidth(size, c);
00988     } else {
00989       switch (c) {
00990         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
00991         case SCC_SETXY:
00992           br.width  = max((uint)*str++, br.width);
00993           br.height = max((uint)*str++, br.height);
00994           break;
00995         case SCC_TINYFONT: size = FS_SMALL; break;
00996         case SCC_BIGFONT:  size = FS_LARGE; break;
00997         case '\n':
00998           br.height += GetCharacterHeight(size);
00999           if (br.width > max_width) max_width = br.width;
01000           br.width = 0;
01001           break;
01002       }
01003     }
01004   }
01005   br.height += GetCharacterHeight(size);
01006 
01007   br.width  = max(br.width, max_width);
01008   return br;
01009 }
01010 
01017 Dimension GetStringBoundingBox(StringID strid)
01018 {
01019   char buffer[DRAW_STRING_BUFFER];
01020 
01021   GetString(buffer, strid, lastof(buffer));
01022   return GetStringBoundingBox(buffer);
01023 }
01024 
01032 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
01033 {
01034   SetColourRemap(colour);
01035   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
01036 }
01037 
01055 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
01056 {
01057   DrawPixelInfo *dpi = _cur_dpi;
01058   UChar c;
01059   int xo = x;
01060 
01061   if (!parse_string_also_when_clipped) {
01062     /* in "mode multiline", the available space have been verified. Not in regular one.
01063      * So if the string cannot be drawn, return the original start to say so.*/
01064     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
01065   }
01066 
01067 switch_colour:;
01068   SetColourRemap(params.cur_colour);
01069 
01070 check_bounds:
01071   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
01072 skip_char:;
01073     for (;;) {
01074       c = *string++;
01075       if (!IsPrintable(c)) goto skip_cont;
01076     }
01077   }
01078 
01079   for (;;) {
01080     c = *string++;
01081 skip_cont:;
01082     if (c == 0) {
01083       return x;  // Nothing more to draw, get out. And here is the new x position
01084     }
01085     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01086       if (x >= dpi->left + dpi->width) goto skip_char;
01087       if (x + _max_char_width >= dpi->left) {
01088         GfxMainBlitter(GetGlyph(params.fontsize, c), x, y, BM_COLOUR_REMAP);
01089       }
01090       x += GetCharacterWidth(params.fontsize, c);
01091     } else if (c == '\n') { // newline = {}
01092       x = xo;  // We require a new line, so the x coordinate is reset
01093       y += GetCharacterHeight(params.fontsize);
01094       goto check_bounds;
01095     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
01096       params.SetColour((TextColour)(c - SCC_BLUE));
01097       goto switch_colour;
01098     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
01099       params.SetPreviousColour();
01100       goto switch_colour;
01101     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
01102       /* The characters are handled before calling this. */
01103       NOT_REACHED();
01104     } else if (c == SCC_TINYFONT) { // {TINYFONT}
01105       params.SetFontSize(FS_SMALL);
01106     } else if (c == SCC_BIGFONT) { // {BIGFONT}
01107       params.SetFontSize(FS_LARGE);
01108     } else if (!IsTextDirectionChar(c)) {
01109       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
01110     }
01111   }
01112 }
01113 
01121 Dimension GetSpriteSize(SpriteID sprid, Point *offset)
01122 {
01123   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
01124 
01125   if (offset != NULL) {
01126     offset->x = sprite->x_offs;
01127     offset->y = sprite->y_offs;
01128   }
01129 
01130   Dimension d;
01131   d.width  = max<int>(0, sprite->x_offs + sprite->width);
01132   d.height = max<int>(0, sprite->y_offs + sprite->height);
01133   return d;
01134 }
01135 
01144 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
01145 {
01146   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01147   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01148     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01149     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
01150   } else if (pal != PAL_NONE) {
01151     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01152     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
01153   } else {
01154     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
01155   }
01156 }
01157 
01158 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
01159 {
01160   const DrawPixelInfo *dpi = _cur_dpi;
01161   Blitter::BlitterParams bp;
01162 
01163   /* Amount of pixels to clip from the source sprite */
01164   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
01165   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
01166   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
01167   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
01168 
01169   if (clip_left + clip_right >= sprite->width) return;
01170   if (clip_top + clip_bottom >= sprite->height) return;
01171 
01172   /* Move to the correct offset */
01173   x += sprite->x_offs;
01174   y += sprite->y_offs;
01175 
01176   /* Copy the main data directly from the sprite */
01177   bp.sprite = sprite->data;
01178   bp.sprite_width = sprite->width;
01179   bp.sprite_height = sprite->height;
01180   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
01181   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
01182   bp.top = 0;
01183   bp.left = 0;
01184   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
01185   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
01186 
01187   x += ScaleByZoom(bp.skip_left, dpi->zoom);
01188   y += ScaleByZoom(bp.skip_top, dpi->zoom);
01189 
01190   bp.dst = dpi->dst_ptr;
01191   bp.pitch = dpi->pitch;
01192   bp.remap = _colour_remap_ptr;
01193 
01194   assert(sprite->width > 0);
01195   assert(sprite->height > 0);
01196 
01197   if (bp.width <= 0) return;
01198   if (bp.height <= 0) return;
01199 
01200   y -= dpi->top;
01201   /* Check for top overflow */
01202   if (y < 0) {
01203     bp.height -= -UnScaleByZoom(y, dpi->zoom);
01204     if (bp.height <= 0) return;
01205     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
01206     y = 0;
01207   } else {
01208     bp.top = UnScaleByZoom(y, dpi->zoom);
01209   }
01210 
01211   /* Check for bottom overflow */
01212   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
01213   if (y > 0) {
01214     bp.height -= UnScaleByZoom(y, dpi->zoom);
01215     if (bp.height <= 0) return;
01216   }
01217 
01218   x -= dpi->left;
01219   /* Check for left overflow */
01220   if (x < 0) {
01221     bp.width -= -UnScaleByZoom(x, dpi->zoom);
01222     if (bp.width <= 0) return;
01223     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
01224     x = 0;
01225   } else {
01226     bp.left = UnScaleByZoom(x, dpi->zoom);
01227   }
01228 
01229   /* Check for right overflow */
01230   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
01231   if (x > 0) {
01232     bp.width -= UnScaleByZoom(x, dpi->zoom);
01233     if (bp.width <= 0) return;
01234   }
01235 
01236   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
01237   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
01238 
01239   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01240   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01241     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01242     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01243     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01244 
01245     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01246 
01247     if (topleft <= clicked && clicked <= bottomright) {
01248       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01249       if (offset < (uint)bp.width) {
01250         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01251       }
01252     }
01253   }
01254 
01255   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
01256 }
01257 
01258 void DoPaletteAnimations();
01259 
01260 void GfxInitPalettes()
01261 {
01262   memcpy(_cur_palette, _palettes[_use_palette], sizeof(_cur_palette));
01263 
01264   DoPaletteAnimations();
01265   _pal_first_dirty = 0;
01266   _pal_count_dirty = 256;
01267 }
01268 
01269 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01270 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01271 
01272 void DoPaletteAnimations()
01273 {
01274   /* Animation counter for the palette animation. */
01275   static int palette_animation_counter = 0;
01276   palette_animation_counter += 8;
01277 
01278   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01279   const Colour *s;
01280   const ExtraPaletteValues *ev = &_extra_palette_values;
01281   /* Amount of colours to be rotated.
01282    * A few more for the DOS palette, because the water colours are
01283    * 245-254 for DOS and 217-226 for Windows.  */
01284   const int colour_rotation_amount = (_use_palette == PAL_DOS) ? PALETTE_ANIM_SIZE_DOS : PALETTE_ANIM_SIZE_WIN;
01285   Colour old_val[PALETTE_ANIM_SIZE_DOS];
01286   const int oldval_size = colour_rotation_amount * sizeof(*old_val);
01287   const uint old_tc = palette_animation_counter;
01288   uint i;
01289   uint j;
01290 
01291   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01292     palette_animation_counter = 0;
01293   }
01294 
01295   Colour *palette_pos = &_cur_palette[PALETTE_ANIM_SIZE_START];  // Points to where animations are taking place on the palette
01296   /* Makes a copy of the current anmation palette in old_val,
01297    * so the work on the current palette could be compared, see if there has been any changes */
01298   memcpy(old_val, palette_pos, oldval_size);
01299 
01300   /* Dark blue water */
01301   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01302   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01303   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01304     *palette_pos++ = s[j];
01305     j++;
01306     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01307   }
01308 
01309   /* Glittery water; jumps over 3 colours each cycle! */
01310   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01311   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01312   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01313     *palette_pos++ = s[j];
01314     j += 3;
01315     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01316   }
01317 
01318   /* Fizzy Drink bubbles animation */
01319   s = ev->fizzy_drink;
01320   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01321   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01322     *palette_pos++ = s[j];
01323     j++;
01324     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01325   }
01326 
01327   /* Oil refinery fire animation */
01328   s = ev->oil_refinery;
01329   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01330   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01331     *palette_pos++ = s[j];
01332     j++;
01333     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01334   }
01335 
01336   /* Radio tower blinking */
01337   {
01338     byte i = (palette_animation_counter >> 1) & 0x7F;
01339     byte v;
01340 
01341     if (i < 0x3f) {
01342       v = 255;
01343     } else if (i < 0x4A || i >= 0x75) {
01344       v = 128;
01345     } else {
01346       v = 20;
01347     }
01348     palette_pos->r = v;
01349     palette_pos->g = 0;
01350     palette_pos->b = 0;
01351     palette_pos++;
01352 
01353     i ^= 0x40;
01354     if (i < 0x3f) {
01355       v = 255;
01356     } else if (i < 0x4A || i >= 0x75) {
01357       v = 128;
01358     } else {
01359       v = 20;
01360     }
01361     palette_pos->r = v;
01362     palette_pos->g = 0;
01363     palette_pos->b = 0;
01364     palette_pos++;
01365   }
01366 
01367   /* Handle lighthouse and stadium animation */
01368   s = ev->lighthouse;
01369   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01370   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01371     *palette_pos++ = s[j];
01372     j++;
01373     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01374   }
01375 
01376   /* Animate water for old DOS graphics */
01377   if (_use_palette == PAL_DOS) {
01378     /* Dark blue water DOS */
01379     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01380     j = EXTR(320, EPV_CYCLES_DARK_WATER);
01381     for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01382       *palette_pos++ = s[j];
01383       j++;
01384       if (j == EPV_CYCLES_DARK_WATER) j = 0;
01385     }
01386 
01387     /* Glittery water DOS */
01388     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01389     j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01390     for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01391       *palette_pos++ = s[j];
01392       j += 3;
01393       if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01394     }
01395   }
01396 
01397   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01398     palette_animation_counter = old_tc;
01399   } else {
01400     if (memcmp(old_val, &_cur_palette[PALETTE_ANIM_SIZE_START], oldval_size) != 0) {
01401       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01402       _pal_first_dirty = PALETTE_ANIM_SIZE_START;
01403       _pal_count_dirty = colour_rotation_amount;
01404     }
01405   }
01406 }
01407 
01408 
01410 void LoadStringWidthTable()
01411 {
01412   _max_char_height = 0;
01413   _max_char_width  = 0;
01414 
01415   for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
01416     _max_char_height = max<int>(_max_char_height, GetCharacterHeight(fs));
01417     for (uint i = 0; i != 224; i++) {
01418       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01419       _max_char_width = max<int>(_max_char_width, _stringwidth_table[fs][i]);
01420     }
01421   }
01422 
01423   /* Needed because they need to be 1 more than the widest. */
01424   _max_char_height++;
01425   _max_char_width++;
01426 
01427   ReInitAllWindows();
01428 }
01429 
01436 byte GetCharacterWidth(FontSize size, WChar key)
01437 {
01438   /* Use _stringwidth_table cache if possible */
01439   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01440 
01441   return GetGlyphWidth(size, key);
01442 }
01443 
01449 byte GetDigitWidth(FontSize size)
01450 {
01451   byte width = 0;
01452   for (char c = '0'; c <= '9'; c++) {
01453     width = max(GetCharacterWidth(size, c), width);
01454   }
01455   return width;
01456 }
01457 
01458 
01459 void ScreenSizeChanged()
01460 {
01461   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01462   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01463 
01464   /* check the dirty rect */
01465   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01466   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01467 
01468   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01469   _cursor.visible = false;
01470 }
01471 
01472 void UndrawMouseCursor()
01473 {
01474   /* Don't undraw the mouse cursor if the screen is not ready */
01475   if (_screen.dst_ptr == NULL) return;
01476 
01477   if (_cursor.visible) {
01478     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01479     _cursor.visible = false;
01480     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);
01481     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01482   }
01483 }
01484 
01485 void DrawMouseCursor()
01486 {
01487 #if defined(WINCE)
01488   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01489   return;
01490 #endif
01491 
01492   /* Don't draw the mouse cursor if the screen is not ready */
01493   if (_screen.dst_ptr == NULL) return;
01494 
01495   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01496   int x;
01497   int y;
01498   int w;
01499   int h;
01500 
01501   /* Redraw mouse cursor but only when it's inside the window */
01502   if (!_cursor.in_window) return;
01503 
01504   /* Don't draw the mouse cursor if it's already drawn */
01505   if (_cursor.visible) {
01506     if (!_cursor.dirty) return;
01507     UndrawMouseCursor();
01508   }
01509 
01510   w = _cursor.size.x;
01511   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01512   if (x < 0) {
01513     w += x;
01514     x = 0;
01515   }
01516   if (w > _screen.width - x) w = _screen.width - x;
01517   if (w <= 0) return;
01518   _cursor.draw_pos.x = x;
01519   _cursor.draw_size.x = w;
01520 
01521   h = _cursor.size.y;
01522   y = _cursor.pos.y + _cursor.offs.y;
01523   if (y < 0) {
01524     h += y;
01525     y = 0;
01526   }
01527   if (h > _screen.height - y) h = _screen.height - y;
01528   if (h <= 0) return;
01529   _cursor.draw_pos.y = y;
01530   _cursor.draw_size.y = h;
01531 
01532   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01533 
01534   /* Make backup of stuff below cursor */
01535   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01536 
01537   /* Draw cursor on screen */
01538   _cur_dpi = &_screen;
01539   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01540 
01541   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01542 
01543   _cursor.visible = true;
01544   _cursor.dirty = false;
01545 }
01546 
01547 void RedrawScreenRect(int left, int top, int right, int bottom)
01548 {
01549   assert(right <= _screen.width && bottom <= _screen.height);
01550   if (_cursor.visible) {
01551     if (right > _cursor.draw_pos.x &&
01552         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01553         bottom > _cursor.draw_pos.y &&
01554         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01555       UndrawMouseCursor();
01556     }
01557   }
01558 
01559 #ifdef ENABLE_NETWORK
01560   if (_networking) NetworkUndrawChatMessage();
01561 #endif /* ENABLE_NETWORK */
01562 
01563   DrawOverlappedWindowForAll(left, top, right, bottom);
01564 
01565   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01566 }
01567 
01573 void DrawDirtyBlocks()
01574 {
01575   byte *b = _dirty_blocks;
01576   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01577   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01578   int x;
01579   int y;
01580 
01581   if (IsGeneratingWorld()) {
01582     /* We are generating the world, so release our rights to the map and
01583      * painting while we are waiting a bit. */
01584     _genworld_paint_mutex->EndCritical();
01585     _genworld_mapgen_mutex->EndCritical();
01586 
01587     /* Wait a while and update _realtime_tick so we are given the rights */
01588     CSleep(GENWORLD_REDRAW_TIMEOUT);
01589     _realtime_tick += GENWORLD_REDRAW_TIMEOUT;
01590     _genworld_paint_mutex->BeginCritical();
01591     _genworld_mapgen_mutex->BeginCritical();
01592   }
01593 
01594   y = 0;
01595   do {
01596     x = 0;
01597     do {
01598       if (*b != 0) {
01599         int left;
01600         int top;
01601         int right = x + DIRTY_BLOCK_WIDTH;
01602         int bottom = y;
01603         byte *p = b;
01604         int h2;
01605 
01606         /* First try coalescing downwards */
01607         do {
01608           *p = 0;
01609           p += _dirty_bytes_per_line;
01610           bottom += DIRTY_BLOCK_HEIGHT;
01611         } while (bottom != h && *p != 0);
01612 
01613         /* Try coalescing to the right too. */
01614         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01615         assert(h2 > 0);
01616         p = b;
01617 
01618         while (right != w) {
01619           byte *p2 = ++p;
01620           int h = h2;
01621           /* Check if a full line of dirty flags is set. */
01622           do {
01623             if (!*p2) goto no_more_coalesc;
01624             p2 += _dirty_bytes_per_line;
01625           } while (--h != 0);
01626 
01627           /* Wohoo, can combine it one step to the right!
01628            * Do that, and clear the bits. */
01629           right += DIRTY_BLOCK_WIDTH;
01630 
01631           h = h2;
01632           p2 = p;
01633           do {
01634             *p2 = 0;
01635             p2 += _dirty_bytes_per_line;
01636           } while (--h != 0);
01637         }
01638         no_more_coalesc:
01639 
01640         left = x;
01641         top = y;
01642 
01643         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01644         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01645         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01646         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01647 
01648         if (left < right && top < bottom) {
01649           RedrawScreenRect(left, top, right, bottom);
01650         }
01651 
01652       }
01653     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01654   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01655 
01656   _invalid_rect.left = w;
01657   _invalid_rect.top = h;
01658   _invalid_rect.right = 0;
01659   _invalid_rect.bottom = 0;
01660 }
01661 
01677 void SetDirtyBlocks(int left, int top, int right, int bottom)
01678 {
01679   byte *b;
01680   int width;
01681   int height;
01682 
01683   if (left < 0) left = 0;
01684   if (top < 0) top = 0;
01685   if (right > _screen.width) right = _screen.width;
01686   if (bottom > _screen.height) bottom = _screen.height;
01687 
01688   if (left >= right || top >= bottom) return;
01689 
01690   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01691   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01692   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01693   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01694 
01695   left /= DIRTY_BLOCK_WIDTH;
01696   top  /= DIRTY_BLOCK_HEIGHT;
01697 
01698   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01699 
01700   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01701   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01702 
01703   assert(width > 0 && height > 0);
01704 
01705   do {
01706     int i = width;
01707 
01708     do b[--i] = 0xFF; while (i);
01709 
01710     b += _dirty_bytes_per_line;
01711   } while (--height != 0);
01712 }
01713 
01720 void MarkWholeScreenDirty()
01721 {
01722   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01723 }
01724 
01739 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01740 {
01741   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01742   const DrawPixelInfo *o = _cur_dpi;
01743 
01744   n->zoom = ZOOM_LVL_NORMAL;
01745 
01746   assert(width > 0);
01747   assert(height > 0);
01748 
01749   if ((left -= o->left) < 0) {
01750     width += left;
01751     if (width <= 0) return false;
01752     n->left = -left;
01753     left = 0;
01754   } else {
01755     n->left = 0;
01756   }
01757 
01758   if (width > o->width - left) {
01759     width = o->width - left;
01760     if (width <= 0) return false;
01761   }
01762   n->width = width;
01763 
01764   if ((top -= o->top) < 0) {
01765     height += top;
01766     if (height <= 0) return false;
01767     n->top = -top;
01768     top = 0;
01769   } else {
01770     n->top = 0;
01771   }
01772 
01773   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01774   n->pitch = o->pitch;
01775 
01776   if (height > o->height - top) {
01777     height = o->height - top;
01778     if (height <= 0) return false;
01779   }
01780   n->height = height;
01781 
01782   return true;
01783 }
01784 
01789 void UpdateCursorSize()
01790 {
01791   CursorVars *cv = &_cursor;
01792   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01793 
01794   cv->size.y = p->height;
01795   cv->size.x = p->width;
01796   cv->offs.x = p->x_offs;
01797   cv->offs.y = p->y_offs;
01798 
01799   cv->dirty = true;
01800 }
01801 
01807 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01808 {
01809   CursorVars *cv = &_cursor;
01810   if (cv->sprite == cursor) return;
01811 
01812   cv->sprite = cursor;
01813   cv->pal    = pal;
01814   UpdateCursorSize();
01815 
01816   cv->short_vehicle_offset = 0;
01817 }
01818 
01819 static void SwitchAnimatedCursor()
01820 {
01821   const AnimCursor *cur = _cursor.animate_cur;
01822 
01823   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01824 
01825   SetCursorSprite(cur->sprite, _cursor.pal);
01826 
01827   _cursor.animate_timeout = cur->display_time;
01828   _cursor.animate_cur     = cur + 1;
01829 }
01830 
01831 void CursorTick()
01832 {
01833   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01834     SwitchAnimatedCursor();
01835   }
01836 }
01837 
01844 void SetMouseCursor(CursorID sprite, PaletteID pal)
01845 {
01846   /* Turn off animation */
01847   _cursor.animate_timeout = 0;
01848   /* Set cursor */
01849   SetCursorSprite(sprite, pal);
01850 }
01851 
01857 void SetAnimatedMouseCursor(const AnimCursor *table)
01858 {
01859   _cursor.animate_list = table;
01860   _cursor.animate_cur = NULL;
01861   _cursor.pal = PAL_NONE;
01862   SwitchAnimatedCursor();
01863 }
01864 
01865 bool ChangeResInGame(int width, int height)
01866 {
01867   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
01868 }
01869 
01870 bool ToggleFullScreen(bool fs)
01871 {
01872   bool result = _video_driver->ToggleFullscreen(fs);
01873   if (_fullscreen != fs && _num_resolutions == 0) {
01874     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
01875   }
01876   return result;
01877 }
01878 
01879 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
01880 {
01881   int x = pa->width - pb->width;
01882   if (x != 0) return x;
01883   return pa->height - pb->height;
01884 }
01885 
01886 void SortResolutions(int count)
01887 {
01888   QSortT(_resolutions, count, &compare_res);
01889 }