gfx.cpp

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