Translations update
[openttd/fttd.git] / src / gfx.cpp
blobb4f0ebe5aa4cb5bb0e543426a22ce5e33e4b7afe
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file gfx.cpp Handling of drawing text and other gfx related stuff. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "gfx_layout.h"
15 #include "progress.h"
16 #include "zoom_func.h"
17 #include "blitter/blitter.h"
18 #include "video/video_driver.hpp"
19 #include "strings_func.h"
20 #include "settings_type.h"
21 #include "network/network.h"
22 #include "network/network_func.h"
23 #include "window_func.h"
24 #include "newgrf_debug.h"
26 #include "table/palettes.h"
27 #include "table/string_colours.h"
28 #include "table/sprites.h"
29 #include "table/control_codes.h"
31 byte _dirkeys; ///< 1 = left, 2 = up, 4 = right, 8 = down
32 bool _fullscreen;
33 byte _support8bpp;
34 CursorVars _cursor;
35 static const AnimCursor *_cursor_animate_list; ///< in case of animated cursor, list of frames
36 static const AnimCursor *_cursor_animate_cur; ///< in case of animated cursor, current frame
37 static uint _cursor_animate_timeout; ///< in case of animated cursor, number of ticks to show the current cursor
39 bool _ctrl_pressed; ///< Is Ctrl pressed?
40 bool _shift_pressed; ///< Is Shift pressed?
41 byte _fast_forward;
42 bool _left_button_down; ///< Is left mouse button pressed?
43 bool _left_button_clicked; ///< Is left mouse button clicked?
44 bool _right_button_down; ///< Is right mouse button pressed?
45 bool _right_button_clicked; ///< Is right mouse button clicked?
47 ttd_unique_ptr <Blitter::Surface> _screen_surface;
48 int _screen_width, _screen_height;
50 bool _exit_game;
51 GameMode _game_mode;
52 SwitchMode _switch_mode; ///< The next mainloop command.
53 PauseModeByte _pause_mode;
54 Palette _cur_palette;
55 int _cur_palette_first_dirty;
56 int _cur_palette_count_dirty;
58 byte _colour_gradient[COLOUR_END][8];
60 static void GfxCharBlitter (BlitArea *dpi, const Sprite *sprite, int x, int y,
61 const byte *remap);
63 static Blitter::Buffer _cursor_backup;
65 ZoomLevelByte _gui_zoom; ///< GUI Zoom level
67 /**
68 * The rect for repaint.
70 * This rectangle defines the area which should be repaint by the video driver.
72 * @ingroup dirty
74 static Rect _invalid_rect;
76 static const uint DIRTY_BLOCK_HEIGHT = 8;
77 static const uint DIRTY_BLOCK_WIDTH = 64;
79 static uint _dirty_bytes_per_line = 0;
80 static byte *_dirty_blocks = NULL;
81 extern uint _dirty_block_colour;
84 /**
85 * Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
87 * @pre dpi->zoom == ZOOM_LVL_NORMAL, right >= left, bottom >= top
88 * @param dpi Area to blit to
89 * @param left Minimum X (inclusive)
90 * @param top Minimum Y (inclusive)
91 * @param right Maximum X (inclusive)
92 * @param bottom Maximum Y (inclusive)
93 * @param colour A 8 bit palette index (FILLRECT_OPAQUE and FILLRECT_CHECKER) or a recolour spritenumber (FILLRECT_RECOLOUR)
94 * @param mode
95 * FILLRECT_OPAQUE: Fill the rectangle with the specified colour
96 * FILLRECT_CHECKER: Like FILLRECT_OPAQUE, but only draw every second pixel (used to grey out things)
97 * FILLRECT_RECOLOUR: Apply a recolour sprite to every pixel in the rectangle currently on screen
99 void GfxFillRect (BlitArea *dpi, int left, int top, int right, int bottom, int colour, FillRectMode mode)
101 void *dst;
102 const int otopleft = top + left;
104 if (left > right || top > bottom) return;
105 if (right < dpi->left || left >= dpi->left + dpi->width) return;
106 if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
108 if ( (left -= dpi->left) < 0) left = 0;
109 right = right - dpi->left + 1;
110 if (right > dpi->width) right = dpi->width;
111 right -= left;
112 assert(right > 0);
114 if ( (top -= dpi->top) < 0) top = 0;
115 bottom = bottom - dpi->top + 1;
116 if (bottom > dpi->height) bottom = dpi->height;
117 bottom -= top;
118 assert(bottom > 0);
120 dst = dpi->surface->move (dpi->dst_ptr, left, top);
122 switch (mode) {
123 default: // FILLRECT_OPAQUE
124 dpi->surface->draw_rect (dst, right, bottom, (uint8)colour);
125 break;
127 case FILLRECT_RECOLOUR:
128 dpi->surface->recolour_rect (dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
129 break;
131 case FILLRECT_CHECKER: {
132 byte bo = (otopleft - left + dpi->left - top + dpi->top) & 1;
133 dpi->surface->draw_checker (dst, right, bottom, colour, bo);
134 break;
140 * Check line clipping by using a linear equation and draw the visible part of
141 * the line given by x/y and x2/y2.
142 * @param dpi Area to blit to.
143 * @param x X coordinate of first point.
144 * @param y Y coordinate of first point.
145 * @param x2 X coordinate of second point.
146 * @param y2 Y coordinate of second point.
147 * @param screen_width With of the screen to check clipping against.
148 * @param screen_height Height of the screen to check clipping against.
149 * @param colour Colour of the line.
150 * @param width Width of the line.
151 * @param dash Length of dashes for dashed lines. 0 means solid line.
153 static inline void GfxDoDrawLine (BlitArea *dpi, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8 colour, int width, int dash = 0)
155 assert(width > 0);
157 if (y2 == y || x2 == x) {
158 /* Special case: horizontal/vertical line. All checks already done in GfxPreprocessLine. */
159 } else {
160 int grade_y = y2 - y;
161 int grade_x = x2 - x;
163 /* Clipping rectangle. Slightly extended so we can ignore the width of the line. */
164 int extra = (int)CeilDiv(3 * width, 4); // not less then "width * sqrt(2) / 2"
165 int clip_left = -extra - x;
166 int clip_right = screen_width - 1 + extra - x;
168 /* prevent integer overflows. */
169 int margin = 1;
170 int dinf = max (abs (clip_left), abs (clip_right));
171 while (INT_MAX / abs(grade_y) < dinf) {
172 grade_y /= 2;
173 grade_x /= 2;
174 margin *= 2; // account for rounding errors
177 /* Imagine that the line is infinitely long and it intersects
178 * with infinitely long left and right edges of the clipping
179 * rectangle. If both intersection points are outside the
180 * clipping rectangle and both on the same side of it,
181 * we don't need to draw anything. */
182 int left_isec_y = y + clip_left * grade_y / grade_x;
183 int right_isec_y = y + clip_right * grade_y / grade_x;
185 int clip_bottom = screen_height - 1 + extra + margin;
186 if (left_isec_y > clip_bottom && right_isec_y > clip_bottom) return;
188 int clip_top = -extra - margin;
189 if (left_isec_y < clip_top && right_isec_y < clip_top) return;
191 /* It is possible to use the line equation to further reduce
192 * the amount of work the blitter has to do by shortening the
193 * effective line segment. However, in order to get that right
194 * and prevent the flickering effects of rounding errors so
195 * much additional code has to be run here that in the general
196 * case the effect is not noticable. */
199 dpi->surface->draw_line (dpi->dst_ptr, x, y, x2, y2, screen_width, screen_height, colour, width, dash);
203 * Align parameters of a line to the given DPI and check simple clipping.
204 * @param dpi Screen parameters to align with.
205 * @param x X coordinate of first point.
206 * @param y Y coordinate of first point.
207 * @param x2 X coordinate of second point.
208 * @param y2 Y coordinate of second point.
209 * @param width Width of the line.
210 * @return True if the line is likely to be visible, false if it's certainly
211 * invisible.
213 static inline bool GfxPreprocessLine (BlitArea *dpi, int &x, int &y, int &x2, int &y2, int width)
215 x -= dpi->left;
216 x2 -= dpi->left;
217 y -= dpi->top;
218 y2 -= dpi->top;
220 /* Check simple clipping */
221 if (x + width / 2 < 0 && x2 + width / 2 < 0 ) return false;
222 if (y + width / 2 < 0 && y2 + width / 2 < 0 ) return false;
223 if (x - width / 2 > dpi->width && x2 - width / 2 > dpi->width ) return false;
224 if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return false;
225 return true;
228 void GfxDrawLine (BlitArea *dpi, int x, int y, int x2, int y2, int colour, int width, int dash)
230 if (GfxPreprocessLine(dpi, x, y, x2, y2, width)) {
231 GfxDoDrawLine (dpi, x, y, x2, y2, dpi->width, dpi->height, colour, width, dash);
235 static void GfxDrawLineUnscaled (DrawPixelInfo *dpi, int x, int y, int x2, int y2, int colour)
237 if (GfxPreprocessLine(dpi, x, y, x2, y2, 1)) {
238 GfxDoDrawLine (dpi,
239 UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
240 UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
241 UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
246 * Draws the projection of a parallelepiped.
247 * This can be used to draw boxes in world coordinates.
248 * @param dpi Screen parameters to align with.
249 * @param x Screen X-coordinate of top front corner.
250 * @param y Screen Y-coordinate of top front corner.
251 * @param dx1 Screen X-length of first edge.
252 * @param dy1 Screen Y-length of first edge.
253 * @param dx2 Screen X-length of second edge.
254 * @param dy2 Screen Y-length of second edge.
255 * @param dx3 Screen X-length of third edge.
256 * @param dy3 Screen Y-length of third edge.
258 void DrawBox (DrawPixelInfo *dpi, int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
260 /* ....
261 * .. ....
262 * .. ....
263 * .. ^
264 * <--__(dx1,dy1) /(dx2,dy2)
265 * : --__ / :
266 * : --__ / :
267 * : *(x,y) :
268 * : | :
269 * : | ..
270 * .... |(dx3,dy3)
271 * .... | ..
272 * ....V.
275 static const byte colour = PC_WHITE;
277 GfxDrawLineUnscaled (dpi, x, y, x + dx1, y + dy1, colour);
278 GfxDrawLineUnscaled (dpi, x, y, x + dx2, y + dy2, colour);
279 GfxDrawLineUnscaled (dpi, x, y, x + dx3, y + dy3, colour);
281 GfxDrawLineUnscaled (dpi, x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
282 GfxDrawLineUnscaled (dpi, x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
283 GfxDrawLineUnscaled (dpi, x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
284 GfxDrawLineUnscaled (dpi, x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
285 GfxDrawLineUnscaled (dpi, x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
286 GfxDrawLineUnscaled (dpi, x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
290 * Set the colour remap to be for the given colour.
291 * @param remap the remap array.
292 * @param colour the new colour of the remap.
294 static void SetColourRemap (byte (&remap) [3], TextColour colour)
296 if (colour == TC_INVALID) return;
298 /* Black strings have no shading ever; the shading is black, so it
299 * would be invisible at best, but it actually makes it illegible. */
300 bool no_shade = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
301 bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
302 colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
304 /* The grf loader ensures that #ST_FONT sprites only use colours 0 to 2. */
305 remap[0] = 0;
306 remap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
307 remap[2] = no_shade ? 0 : 1;
311 * Drawing routine for drawing a laid out line of text.
312 * @param line String to draw.
313 * @param dpi The area to draw on.
314 * @param y The top most position to draw on.
315 * @param left The left most position to draw on.
316 * @param right The right most position to draw on.
317 * @param align The alignment of the string when drawing left-to-right. In the
318 * case a right-to-left language is chosen this is inverted so it
319 * will be drawn in the right direction.
320 * @param underline Whether to underline what has been drawn or not.
321 * @param truncation Whether to perform string truncation or not.
323 * @return In case of left or center alignment the right most pixel we have drawn to.
324 * In case of right alignment the left most pixel we have drawn to.
326 static int DrawLayoutLine (const ParagraphLayouter::Line *line,
327 BlitArea *dpi, int y, int left, int right,
328 StringAlignment align, bool underline, bool truncation)
330 if (line->CountRuns() == 0) return 0;
332 int w = line->GetWidth();
333 int h = line->GetLeading();
336 * The following is needed for truncation.
337 * Depending on the text direction, we either remove bits at the rear
338 * or the front. For this we shift the entire area to draw so it fits
339 * within the left/right bounds and the side we do not truncate it on.
340 * Then we determine the truncation location, i.e. glyphs that fall
341 * outside of the range min_x - max_x will not be drawn; they are thus
342 * the truncated glyphs.
344 * At a later step we insert the dots.
347 int max_w = right - left + 1; // The maximum width.
349 int offset_x = 0; // The offset we need for positioning the glyphs
350 int min_x = left; // The minimum x position to draw normal glyphs on.
351 int max_x = right; // The maximum x position to draw normal glyphs on.
353 truncation &= max_w < w; // Whether we need to do truncation.
354 int dot_width = 0; // Cache for the width of the dot.
355 const Sprite *dot_sprite = NULL; // Cache for the sprite of the dot.
357 if (truncation) {
359 * Assumption may be made that all fonts of a run are of the same size.
360 * In any case, we'll use these dots for the abbreviation, so even if
361 * another size would be chosen it won't have truncated too little for
362 * the truncation dots.
364 FontCache *fc = line->GetVisualRun(0)->GetFont()->fc;
365 GlyphID dot_glyph = fc->MapCharToGlyph('.');
366 dot_width = fc->GetGlyphWidth(dot_glyph);
367 dot_sprite = fc->GetGlyph(dot_glyph);
369 if (_current_text_dir == TD_RTL) {
370 min_x += 3 * dot_width;
371 offset_x = w - 3 * dot_width - max_w;
372 } else {
373 max_x -= 3 * dot_width;
376 w = max_w;
379 /* In case we have a RTL language we swap the alignment. */
380 if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
382 /* right is the right most position to draw on. In this case we want to do
383 * calculations with the width of the string. In comparison right can be
384 * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
385 * So most +1/-1 additions are to move from lengthof to 'indices'.
387 switch (align & SA_HOR_MASK) {
388 case SA_LEFT:
389 /* right + 1 = left + w */
390 right = left + w - 1;
391 break;
393 case SA_HOR_CENTER:
394 left = RoundDivSU(right + 1 + left - w, 2);
395 /* right + 1 = left + w */
396 right = left + w - 1;
397 break;
399 case SA_RIGHT:
400 left = right + 1 - w;
401 break;
403 default:
404 NOT_REACHED();
407 static const byte remap_black[3] = { 0, _string_colourmap[TC_BLACK], 0 };
408 byte remap[3];
409 memcpy (remap, remap_black, sizeof(remap));
410 TextColour colour = TC_BLACK;
411 bool draw_shadow = false;
412 for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
413 const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index);
414 const FontBase *f = run->GetFont();
416 FontCache *fc = f->fc;
417 colour = f->colour;
418 SetColourRemap (remap, colour);
420 int dpi_left = dpi->left;
421 int dpi_right = dpi->left + dpi->width - 1;
423 draw_shadow = colour != TC_BLACK && (colour & TC_NO_SHADE) == 0 && fc->GetDrawGlyphShadow();
425 for (int i = 0; i < run->GetGlyphCount(); i++) {
426 ParagraphLayouter::GlyphPos gp;
427 /* Not a valid glyph (empty) */
428 if (!run->GetGlyphPos (&gp, i)) continue;
430 int begin_x = gp.x0 + left - offset_x;
431 int end_x = gp.x1 + left - offset_x - 1;
432 int top = gp.y + y;
434 /* Truncated away. */
435 if (truncation && (begin_x < min_x || end_x > max_x)) continue;
437 const Sprite *sprite = fc->GetGlyph (gp.glyph);
438 /* Check clipping (the "+ 1" is for the shadow). */
439 if (begin_x + sprite->x_offs > dpi_right || begin_x + sprite->x_offs + sprite->width /* - 1 + 1 */ < dpi_left) continue;
441 if (draw_shadow && (gp.glyph & SPRITE_GLYPH) == 0) {
442 GfxCharBlitter (dpi, sprite, begin_x + 1, top + 1, remap_black);
444 GfxCharBlitter (dpi, sprite, begin_x, top, remap);
448 if (truncation) {
449 int x = (_current_text_dir == TD_RTL) ? left : (right - 3 * dot_width);
450 for (int i = 0; i < 3; i++, x += dot_width) {
451 if (draw_shadow) {
452 GfxCharBlitter (dpi, dot_sprite, x + 1, y + 1, remap_black);
454 GfxCharBlitter (dpi, dot_sprite, x, y, remap);
458 if (underline) {
459 GfxFillRect (dpi, left, y + h, right, y + h, remap[1]);
462 return (align & SA_HOR_MASK) == SA_RIGHT ? left : right;
466 * Draw string, possibly truncated to make it fit in its allocated space
468 * @param dpi The area to draw on.
469 * @param left The left most position to draw on.
470 * @param right The right most position to draw on.
471 * @param top The top most position to draw on.
472 * @param str String to draw.
473 * @param colour Colour used for drawing the string, see DoDrawString() for details
474 * @param align The alignment of the string when drawing left-to-right. In the
475 * case a right-to-left language is chosen this is inverted so it
476 * will be drawn in the right direction.
477 * @param underline Whether to underline what has been drawn or not.
478 * @param fontsize The size of the initial characters.
479 * @return In case of left or center alignment the right most pixel we have drawn to.
480 * In case of right alignment the left most pixel we have drawn to.
482 int DrawString (BlitArea *dpi, int left, int right, int top,
483 const char *str, TextColour colour, StringAlignment align,
484 bool underline, FontSize fontsize)
486 /* The string may contain control chars to change the font, just use the biggest font for clipping. */
487 int max_height = max(max(FONT_HEIGHT_SMALL, FONT_HEIGHT_NORMAL), max(FONT_HEIGHT_LARGE, FONT_HEIGHT_MONO));
489 /* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
490 int extra = max_height / 2;
492 if (dpi->top + dpi->height + extra < top || dpi->top > top + max_height + extra ||
493 dpi->left + dpi->width + extra < left || dpi->left > right + extra) {
494 return 0;
497 Layouter layout(str, INT32_MAX, colour, fontsize);
498 if (layout.empty()) return 0;
500 return DrawLayoutLine (layout.front().get(), dpi, top, left, right, align, underline, true);
504 * Draw string, possibly truncated to make it fit in its allocated space
506 * @param dpi The area to draw on.
507 * @param left The left most position to draw on.
508 * @param right The right most position to draw on.
509 * @param top The top most position to draw on.
510 * @param str String to draw.
511 * @param colour Colour used for drawing the string, see DoDrawString() for details
512 * @param align The alignment of the string when drawing left-to-right. In the
513 * case a right-to-left language is chosen this is inverted so it
514 * will be drawn in the right direction.
515 * @param underline Whether to underline what has been drawn or not.
516 * @param fontsize The size of the initial characters.
517 * @return In case of left or center alignment the right most pixel we have drawn to.
518 * In case of right alignment the left most pixel we have drawn to.
520 int DrawString (BlitArea *dpi, int left, int right, int top,
521 StringID str, TextColour colour, StringAlignment align,
522 bool underline, FontSize fontsize)
524 char buffer[DRAW_STRING_BUFFER];
525 GetString (buffer, str);
526 return DrawString (dpi, left, right, top, buffer, colour, align, underline, fontsize);
530 * Calculates height of string (in pixels). The string is changed to a multiline string if needed.
531 * @param str string to check
532 * @param maxw maximum string width
533 * @return height of pixels of string when it is drawn
535 uint GetStringHeight (const char *str, int maxw, FontSize fontsize)
537 Layouter layout(str, maxw, TC_FROMSTRING, fontsize);
538 return layout.GetBounds().height;
542 * Calculates height of string (in pixels). The string is changed to a multiline string if needed.
543 * @param str string to check
544 * @param maxw maximum string width
545 * @return height of pixels of string when it is drawn
547 uint GetStringHeight (StringID str, int maxw)
549 char buffer[DRAW_STRING_BUFFER];
550 GetString (buffer, str);
551 return GetStringHeight(buffer, maxw);
555 * Calculates number of lines of string. The string is changed to a multiline string if needed.
556 * @param str string to check
557 * @param maxw maximum string width
558 * @return number of lines of string when it is drawn
560 int GetStringLineCount(StringID str, int maxw)
562 char buffer[DRAW_STRING_BUFFER];
563 GetString (buffer, str);
565 Layouter layout(buffer, maxw);
566 return layout.size();
570 * Draw string, possibly over multiple lines.
572 * @param dpi The area to draw on.
573 * @param left The left most position to draw on.
574 * @param right The right most position to draw on.
575 * @param top The top most position to draw on.
576 * @param bottom The bottom most position to draw on.
577 * @param str String to draw.
578 * @param colour Colour used for drawing the string, see DoDrawString() for details
579 * @param align The horizontal and vertical alignment of the string.
580 * @param underline Whether to underline all strings
581 * @param fontsize The size of the initial characters.
583 * @return If \a align is #SA_BOTTOM, the top to where we have written, else the bottom to where we have written.
585 int DrawStringMultiLine (BlitArea *dpi, int left, int right, int top, int bottom,
586 const char *str, TextColour colour, StringAlignment align,
587 bool underline, FontSize fontsize)
589 int maxw = right - left + 1;
590 int maxh = bottom - top + 1;
592 /* It makes no sense to even try if it can't be drawn anyway, or
593 * do we really want to support fonts of 0 or less pixels high? */
594 if (maxh <= 0) return top;
596 Layouter layout(str, maxw, colour, fontsize);
597 int total_height = layout.GetBounds().height;
598 int y;
599 switch (align & SA_VERT_MASK) {
600 case SA_TOP:
601 y = top;
602 break;
604 case SA_VERT_CENTER:
605 y = RoundDivSU(bottom + top - total_height, 2);
606 break;
608 case SA_BOTTOM:
609 y = bottom - total_height;
610 break;
612 default: NOT_REACHED();
615 int last_line = top;
616 int first_line = bottom;
618 for (Layouter::const_iterator iter (layout.begin()); iter != layout.end(); iter++) {
619 const ParagraphLayouter::Line *line = iter->get();
621 int line_height = line->GetLeading();
622 if (y >= top && y < bottom) {
623 last_line = y + line_height;
624 if (first_line > y) first_line = y;
626 DrawLayoutLine (line, dpi, y, left, right, align, underline, false);
628 y += line_height;
631 return ((align & SA_VERT_MASK) == SA_BOTTOM) ? first_line : last_line;
635 * Draw string, possibly over multiple lines.
637 * @param dpi The area to draw on.
638 * @param left The left most position to draw on.
639 * @param right The right most position to draw on.
640 * @param top The top most position to draw on.
641 * @param bottom The bottom most position to draw on.
642 * @param str String to draw.
643 * @param colour Colour used for drawing the string, see DoDrawString() for details
644 * @param align The horizontal and vertical alignment of the string.
645 * @param underline Whether to underline all strings
646 * @param fontsize The size of the initial characters.
648 * @return If \a align is #SA_BOTTOM, the top to where we have written, else the bottom to where we have written.
650 int DrawStringMultiLine (BlitArea *dpi, int left, int right, int top, int bottom,
651 StringID str, TextColour colour, StringAlignment align,
652 bool underline, FontSize fontsize)
654 char buffer[DRAW_STRING_BUFFER];
655 GetString (buffer, str);
656 return DrawStringMultiLine (dpi, left, right, top, bottom, buffer, colour, align, underline, fontsize);
660 * Return the string dimension in pixels. The height and width are returned
661 * in a single Dimension value. TINYFONT, BIGFONT modifiers are only
662 * supported as the first character of the string. The returned dimensions
663 * are therefore a rough estimation correct for all the current strings
664 * but not every possible combination
665 * @param str string to calculate pixel-width
666 * @param start_fontsize Fontsize to start the text with
667 * @return string width and height in pixels
669 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
671 Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
672 return layout.GetBounds();
676 * Get bounding box of a string. Uses parameters set by #DParam if needed.
677 * Has the same restrictions as #GetStringBoundingBox(const char *str).
678 * @param strid String to examine.
679 * @return Width and height of the bounding box for the string in pixels.
681 Dimension GetStringBoundingBox(StringID strid)
683 char buffer[DRAW_STRING_BUFFER];
685 GetString (buffer, strid);
686 return GetStringBoundingBox(buffer);
690 * Draw single character horizontally centered around (x,y)
691 * @param dpi The area to draw on.
692 * @param c Character (glyph) to draw
693 * @param x X position to draw character
694 * @param y Y position to draw character
695 * @param colour Colour to use, see DoDrawString() for details
697 void DrawCharCentered (BlitArea *dpi, WChar c, int x, int y, TextColour colour)
699 byte remap[3];
700 SetColourRemap (remap, colour);
701 FontCache *fc = FontCache::Get (FS_NORMAL);
702 GfxCharBlitter (dpi, fc->GetCharGlyph (c),
703 x - fc->GetCharacterWidth(c) / 2, y, remap);
707 * Get the size of a sprite.
708 * @param sprid Sprite to examine.
709 * @param [out] offset Optionally returns the sprite position offset.
710 * @return Sprite size in pixels.
711 * @note The size assumes (0, 0) as top-left coordinate and ignores any part of the sprite drawn at the left or above that position.
713 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
715 const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
717 if (offset != NULL) {
718 offset->x = UnScaleByZoom(sprite->x_offs, zoom);
719 offset->y = UnScaleByZoom(sprite->y_offs, zoom);
722 Dimension d;
723 d.width = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
724 d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
725 return d;
729 * Set up blitter params to draw a sprite.
730 * @param bp The BlitterParams to set up.
731 * @param dpi The area to draw on.
732 * @param sprite The sprite to draw.
733 * @param x The X location to draw.
734 * @param y The Y location to draw.
735 * @param scaled Whether the X and Y are scaled or unscaled.
736 * @param sub Whether to only draw a sub set of the sprite.
737 * @param zoom The zoom level at which to draw the sprites.
738 * @return Whether there is anything to draw (false if sprite is off bounds).
740 static bool SetupBlitterParams (Blitter::BlitterParams *bp, BlitArea *dpi,
741 const Sprite * const sprite, int x, int y, bool scaled,
742 const SubSprite * const sub, ZoomLevel zoom)
744 /* Move to the correct offset */
745 x += sprite->x_offs;
746 y += sprite->y_offs;
748 if (sub == NULL) {
749 /* No clipping. */
750 bp->skip_left = 0;
751 bp->skip_top = 0;
752 bp->width = UnScaleByZoom (sprite->width, zoom);
753 bp->height = UnScaleByZoom (sprite->height, zoom);
754 } else {
755 assert (!scaled);
757 /* Amount of pixels to clip from the source sprite */
758 int clip_left = max (0, -sprite->x_offs + sub->left * ZOOM_LVL_BASE );
759 int clip_top = max (0, -sprite->y_offs + sub->top * ZOOM_LVL_BASE );
760 int clip_right = max (0, sprite->width - (-sprite->x_offs + (sub->right + 1) * ZOOM_LVL_BASE));
761 int clip_bottom = max (0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_LVL_BASE));
763 if (clip_left + clip_right >= sprite->width) return false;
764 if (clip_top + clip_bottom >= sprite->height) return false;
766 bp->skip_left = UnScaleByZoomLower (clip_left, zoom);
767 bp->skip_top = UnScaleByZoomLower (clip_top, zoom);
768 bp->width = UnScaleByZoom (sprite->width - clip_left - clip_right, zoom);
769 bp->height = UnScaleByZoom (sprite->height - clip_top - clip_bottom, zoom);
771 x += ScaleByZoom (bp->skip_left, zoom);
772 y += ScaleByZoom (bp->skip_top, zoom);
775 /* Copy the main data directly from the sprite */
776 bp->sprite = sprite;
777 bp->top = 0;
778 bp->left = 0;
780 bp->dst = dpi->dst_ptr;
781 bp->pitch = dpi->surface->pitch;
783 assert(sprite->width > 0);
784 assert(sprite->height > 0);
786 if (bp->width <= 0) return false;
787 if (bp->height <= 0) return false;
789 y -= scaled ? ScaleByZoom (dpi->top, zoom) : dpi->top;
790 int y_unscaled = UnScaleByZoom(y, zoom);
791 /* Check for top overflow */
792 if (y < 0) {
793 bp->height -= -y_unscaled;
794 if (bp->height <= 0) return false;
795 bp->skip_top += -y_unscaled;
796 y = 0;
797 } else {
798 bp->top = y_unscaled;
801 /* Check for bottom overflow */
802 y += scaled ? ScaleByZoom (bp->height - dpi->height, zoom) : ScaleByZoom (bp->height, zoom) - dpi->height;
803 if (y > 0) {
804 bp->height -= UnScaleByZoom (y, zoom);
805 if (bp->height <= 0) return false;
808 x -= scaled ? ScaleByZoom (dpi->left, zoom) : dpi->left;
809 int x_unscaled = UnScaleByZoom(x, zoom);
810 /* Check for left overflow */
811 if (x < 0) {
812 bp->width -= -x_unscaled;
813 if (bp->width <= 0) return false;
814 bp->skip_left += -x_unscaled;
815 x = 0;
816 } else {
817 bp->left = x_unscaled;
820 /* Check for right overflow */
821 x += scaled ? ScaleByZoom (bp->width - dpi->width, zoom) : ScaleByZoom (bp->width, zoom) - dpi->width;
822 if (x > 0) {
823 bp->width -= UnScaleByZoom (x, zoom);
824 if (bp->width <= 0) return false;
827 assert (bp->skip_left + bp->width <= UnScaleByZoom (sprite->width, zoom));
828 assert (bp->skip_top + bp->height <= UnScaleByZoom (sprite->height, zoom));
830 return true;
834 * The code for setting up the blitter mode and sprite information before finally drawing the sprite.
835 * @param dpi The area to draw on.
836 * @param img The sprite to draw.
837 * @param pal The palette to use.
838 * @param x The X location to draw.
839 * @param y The Y location to draw.
840 * @param scaled Whether the X and Y are scaled or unscaled.
841 * @param sub Whether to only draw a sub set of the sprite.
842 * @param zoom The zoom level at which to draw the sprites.
844 static void GfxBlitter (BlitArea *dpi, SpriteID img, PaletteID pal,
845 int x, int y, bool scaled, const SubSprite * const sub, ZoomLevel zoom)
847 SpriteID sprite_id = GB(img, 0, SPRITE_WIDTH);
848 const Sprite *sprite = GetSprite (sprite_id, ST_NORMAL);
850 Blitter::BlitterParams bp;
851 if (!SetupBlitterParams (&bp, dpi, sprite, x, y, scaled, sub, zoom)) {
852 return;
855 /* We do not want to catch the mouse. */
856 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
857 void *topleft = dpi->surface->move (bp.dst, bp.left, bp.top);
858 void *bottomright = dpi->surface->move (topleft, bp.width - 1, bp.height - 1);
860 void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
862 if (topleft <= clicked && clicked <= bottomright) {
863 uint offset = (((size_t)clicked - (size_t)topleft) / (Blitter::get()->screen_depth / 8)) % bp.pitch;
864 if (offset < (uint)bp.width) {
865 _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
870 byte string_remap[3];
871 BlitterMode mode;
872 if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
873 bp.remap = GetNonSprite (GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
874 mode = BM_TRANSPARENT;
876 } else if (pal == PAL_NONE) {
877 mode = BM_NORMAL;
879 } else if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) {
880 SetColourRemap (string_remap, (TextColour)GB(pal, 0, PALETTE_WIDTH));
881 bp.remap = string_remap;
882 mode = BM_COLOUR_REMAP;
884 } else {
885 bp.remap = GetNonSprite (GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
886 switch (pal) {
887 case PALETTE_CRASH: mode = BM_CRASH_REMAP; break;
888 case PALETTE_ALL_BLACK: mode = BM_BLACK_REMAP; break;
889 default: mode = BM_COLOUR_REMAP; break;
893 dpi->surface->draw (&bp, mode, zoom);
897 * Draw a sprite in a viewport.
898 * @param dpi The area to draw on.
899 * @param img Image number to draw
900 * @param pal Palette to use.
901 * @param x Left coordinate of image in viewport, scaled by zoom
902 * @param y Top coordinate of image in viewport, scaled by zoom
903 * @param sub If available, draw only specified part of the sprite
905 void DrawSpriteViewport (DrawPixelInfo *dpi, SpriteID img, PaletteID pal,
906 int x, int y, const SubSprite *sub)
908 GfxBlitter (dpi, img, pal, x, y, false, sub, dpi->zoom);
912 * Draw a sprite, not in a viewport
913 * @param dpi The area to draw on.
914 * @param img Image number to draw
915 * @param pal Palette to use.
916 * @param x Left coordinate of image in pixels
917 * @param y Top coordinate of image in pixels
919 void DrawSprite (BlitArea *dpi, SpriteID img, PaletteID pal, int x, int y)
921 x = ScaleByZoom (x, ZOOM_LVL_GUI);
922 y = ScaleByZoom (y, ZOOM_LVL_GUI);
924 GfxBlitter (dpi, img, pal, x, y, true, NULL, ZOOM_LVL_GUI);
927 static void GfxCharBlitter (BlitArea *dpi, const Sprite *sprite, int x, int y,
928 const byte *remap)
930 Blitter::BlitterParams bp;
931 if (SetupBlitterParams (&bp, dpi, sprite, x, y, false, NULL, ZOOM_LVL_NORMAL)) {
932 bp.remap = remap;
933 dpi->surface->draw (&bp, BM_COLOUR_REMAP, ZOOM_LVL_NORMAL);
938 * Compute the cycle in an animation.
939 * @param x Global animation counter.
940 * @param n Number of cycles in the animation.
941 * @param s Animation speed factor (higher is slower).
943 static inline uint get_animation_cycle (uint x, uint n, uint s)
945 return ((x & ((1 << s) - 1)) * n) >> s;
948 void DoPaletteAnimations()
950 /* Animation counter for the palette animation. */
951 static uint palette_animation_counter = 0;
952 palette_animation_counter++;
954 const Blitter::Info *blitter = Blitter::get();
955 bool noanim = (blitter != NULL) && (blitter->palette_animation == Blitter::PALETTE_ANIMATION_NONE);
956 const uint tc = noanim ? 0 : palette_animation_counter;
958 const Colour *s;
959 const ExtraPaletteValues *ev = &_extra_palette_values;
960 Colour old_val[PALETTE_ANIM_SIZE];
961 uint i;
962 uint j;
964 Colour *palette_pos = &_cur_palette[PALETTE_ANIM_START]; // Points to where animations are taking place on the palette
965 /* Makes a copy of the current animation palette in old_val,
966 * so the work on the current palette could be compared, see if there has been any changes */
967 memcpy(old_val, palette_pos, sizeof(old_val));
969 /* Fizzy Drink bubbles animation */
970 s = ev->fizzy_drink;
971 j = get_animation_cycle (~tc, EPV_CYCLES_FIZZY_DRINK, 4);
972 for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
973 *palette_pos++ = s[j];
974 j++;
975 if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
978 /* Oil refinery fire animation */
979 s = ev->oil_refinery;
980 j = get_animation_cycle (~tc, EPV_CYCLES_OIL_REFINERY, 4);
981 for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
982 *palette_pos++ = s[j];
983 j++;
984 if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
987 /* Radio tower blinking */
989 byte v = (((tc & 0x0F) - 0x3) > 0xA) ? 128 : 20;
990 bool b = (tc & 0x10) != 0;
992 palette_pos->r = b ? v : 255;
993 palette_pos->g = 0;
994 palette_pos->b = 0;
995 palette_pos++;
997 palette_pos->r = b ? 255 : v;
998 palette_pos->g = 0;
999 palette_pos->b = 0;
1000 palette_pos++;
1003 /* Handle lighthouse and stadium animation */
1004 s = ev->lighthouse;
1005 j = get_animation_cycle (tc, EPV_CYCLES_LIGHTHOUSE, 5);
1006 for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
1007 *palette_pos++ = s[j];
1008 j++;
1009 if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
1012 /* Dark blue water */
1013 s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
1014 j = get_animation_cycle (tc * 10, EPV_CYCLES_DARK_WATER, 8);
1015 for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
1016 *palette_pos++ = s[j];
1017 j++;
1018 if (j == EPV_CYCLES_DARK_WATER) j = 0;
1021 /* Glittery water */
1022 s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
1023 j = get_animation_cycle (tc, EPV_CYCLES_GLITTER_WATER, 6);
1024 for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
1025 *palette_pos++ = s[j];
1026 j += 3;
1027 if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
1030 if (!noanim && (memcmp (old_val, &_cur_palette[PALETTE_ANIM_START], sizeof(old_val)) != 0)
1031 && (_cur_palette_count_dirty == 0)) {
1032 /* Did we changed anything on the palette? Seems so. Mark it as dirty */
1033 _cur_palette_first_dirty = PALETTE_ANIM_START;
1034 _cur_palette_count_dirty = PALETTE_ANIM_SIZE;
1038 void GfxInitPalettes()
1040 assert_compile (sizeof(_cur_palette) == sizeof(_palette));
1041 memcpy(&_cur_palette, &_palette, sizeof(_cur_palette));
1042 _cur_palette_first_dirty = 0;
1043 _cur_palette_count_dirty = 256;
1044 DoPaletteAnimations();
1048 * Determine a contrasty text colour for a coloured background.
1049 * @param background Background colour.
1050 * @return TC_BLACK or TC_WHITE depending on what gives a better contrast.
1052 TextColour GetContrastColour(uint8 background)
1054 Colour c = _cur_palette[background];
1055 /* Compute brightness according to http://www.w3.org/TR/AERT#color-contrast.
1056 * The following formula computes 1000 * brightness^2, with brightness being in range 0 to 255. */
1057 uint sq1000_brightness = c.r * c.r * 299 + c.g * c.g * 587 + c.b * c.b * 114;
1058 /* Compare with threshold brightness 128 (50%) */
1059 return sq1000_brightness < 128 * 128 * 1000 ? TC_WHITE : TC_BLACK;
1063 * Initialize the font cache.
1064 * @param monospace Whether to load the monospace cache or the normal fonts.
1066 void LoadStringWidthTable(bool monospace)
1068 for (FontSize fs = monospace ? FS_MONO : FS_BEGIN; fs < (monospace ? FS_END : FS_MONO); fs++) {
1069 FontCache::Get(fs)->ClearFontCache();
1072 ReInitAllWindows();
1075 void ScreenSizeChanged()
1077 _dirty_bytes_per_line = CeilDiv (_screen_width, DIRTY_BLOCK_WIDTH);
1078 _dirty_blocks = xrealloct<byte> (_dirty_blocks, _dirty_bytes_per_line * CeilDiv (_screen_height, DIRTY_BLOCK_HEIGHT));
1080 /* check the dirty rect */
1081 if (_invalid_rect.right >= _screen_width) _invalid_rect.right = _screen_width;
1082 if (_invalid_rect.bottom >= _screen_height) _invalid_rect.bottom = _screen_height;
1084 /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
1085 _cursor.visible = false;
1088 void UndrawMouseCursor()
1090 /* Don't undraw the mouse cursor if the screen is not ready */
1091 if (!_screen_surface) return;
1093 if (_cursor.visible) {
1094 _cursor.visible = false;
1095 _screen_surface->paste (&_cursor_backup, _cursor.draw_pos.x, _cursor.draw_pos.y);
1096 VideoDriver::GetActiveDriver()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1100 void DrawMouseCursor()
1102 #if defined(WINCE)
1103 /* Don't ever draw the mouse for WinCE, as we work with a stylus */
1104 return;
1105 #endif
1107 /* Don't draw the mouse cursor if the screen is not ready */
1108 if (!_screen_surface) return;
1110 /* Redraw mouse cursor but only when it's inside the window */
1111 if (!_cursor.in_window) return;
1113 /* Don't draw the mouse cursor if it's already drawn */
1114 if (_cursor.visible) {
1115 if (!_cursor.dirty) return;
1116 UndrawMouseCursor();
1119 /* Determine visible area */
1120 int left = _cursor.pos.x + _cursor.total_offs.x;
1121 int width = _cursor.total_size.x;
1122 if (left < 0) {
1123 width += left;
1124 left = 0;
1126 if (left + width > _screen_width) {
1127 width = _screen_width - left;
1129 if (width <= 0) return;
1131 int top = _cursor.pos.y + _cursor.total_offs.y;
1132 int height = _cursor.total_size.y;
1133 if (top < 0) {
1134 height += top;
1135 top = 0;
1137 if (top + height > _screen_height) {
1138 height = _screen_height - top;
1140 if (height <= 0) return;
1142 _cursor.draw_pos.x = left;
1143 _cursor.draw_pos.y = top;
1144 _cursor.draw_size.x = width;
1145 _cursor.draw_size.y = height;
1147 /* Make backup of stuff below cursor */
1148 _screen_surface->copy (&_cursor_backup, _cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1150 /* Draw cursor on screen */
1151 BlitArea screen;
1152 screen.surface = _screen_surface.get();
1153 screen.dst_ptr = _screen_surface->ptr;
1154 screen.left = screen.top = 0;
1155 screen.width = _screen_width;
1156 screen.height = _screen_height;
1157 for (uint i = 0; i < _cursor.sprite_count; ++i) {
1158 DrawSprite (&screen, _cursor.sprite_seq[i].sprite, _cursor.sprite_seq[i].pal, _cursor.pos.x + _cursor.sprite_seq[i].pos, _cursor.pos.y);
1161 VideoDriver::GetActiveDriver()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1163 _cursor.visible = true;
1164 _cursor.dirty = false;
1167 static void RedrawScreenRect (int left, int top, int right, int bottom)
1169 assert (right <= _screen_width && bottom <= _screen_height);
1170 if (_cursor.visible) {
1171 if (right > _cursor.draw_pos.x &&
1172 left < _cursor.draw_pos.x + _cursor.draw_size.x &&
1173 bottom > _cursor.draw_pos.y &&
1174 top < _cursor.draw_pos.y + _cursor.draw_size.y) {
1175 UndrawMouseCursor();
1179 #ifdef ENABLE_NETWORK
1180 if (_networking) NetworkUndrawChatMessage();
1181 #endif /* ENABLE_NETWORK */
1183 DrawOverlappedWindowForAll(left, top, right, bottom);
1185 VideoDriver::GetActiveDriver()->MakeDirty(left, top, right - left, bottom - top);
1188 void ScrollScreenRect (int left, int top, int width, int height, int dx, int dy)
1190 assert ((dx != 0) || (dy != 0));
1192 if (abs(dx) >= width || abs(dy) >= height) {
1193 /* fully_outside */
1194 RedrawScreenRect (left, top, left + width, top + height);
1195 return;
1198 if (_cursor.visible) UndrawMouseCursor();
1200 #ifdef ENABLE_NETWORK
1201 if (_networking) NetworkUndrawChatMessage();
1202 #endif /* ENABLE_NETWORK */
1204 _screen_surface->scroll (left, top, width, height, dx, dy);
1206 int l = left;
1207 int w = width;
1208 if (dx > 0) {
1209 DrawOverlappedWindowForAll (left, top, dx + left, top + height);
1210 l += dx;
1211 w -= dx;
1212 } else if (dx < 0) {
1213 DrawOverlappedWindowForAll (left + width + dx, top, left + width, top + height);
1214 w += dx;
1217 if (dy > 0) {
1218 DrawOverlappedWindowForAll (l, top, w + l, top + dy);
1219 } else if (dy < 0) {
1220 DrawOverlappedWindowForAll (l, top + height + dy, w + l, top + height);
1223 VideoDriver::GetActiveDriver()->MakeDirty (left, top, width, height);
1227 * Repaints the rectangle blocks which are marked as 'dirty'.
1229 * @see SetDirtyBlocks
1231 void DrawDirtyBlocks()
1233 byte *b = _dirty_blocks;
1234 const int w = Align (_screen_width, DIRTY_BLOCK_WIDTH);
1235 const int h = Align (_screen_height, DIRTY_BLOCK_HEIGHT);
1236 int x;
1237 int y;
1239 if (HasModalProgress()) {
1240 /* We are generating the world, so release our rights to the map and
1241 * painting while we are waiting a bit. */
1242 _modal_progress_paint_mutex->EndCritical();
1243 _modal_progress_work_mutex->EndCritical();
1245 /* Wait a while and update _realtime_tick so we are given the rights */
1246 if (!IsFirstModalProgressLoop()) CSleep(MODAL_PROGRESS_REDRAW_TIMEOUT);
1247 _realtime_tick += MODAL_PROGRESS_REDRAW_TIMEOUT;
1248 _modal_progress_paint_mutex->BeginCritical();
1249 _modal_progress_work_mutex->BeginCritical();
1251 /* When we ended with the modal progress, do not draw the blocks.
1252 * Simply let the next run do so, otherwise we would be loading
1253 * the new state (and possibly change the blitter) when we hold
1254 * the drawing lock, which we must not do. */
1255 if (_switch_mode != SM_NONE && !HasModalProgress()) return;
1258 y = 0;
1259 do {
1260 x = 0;
1261 do {
1262 if (*b != 0) {
1263 int left;
1264 int top;
1265 int right = x + DIRTY_BLOCK_WIDTH;
1266 int bottom = y;
1267 byte *p = b;
1268 int h2;
1270 /* First try coalescing downwards */
1271 do {
1272 *p = 0;
1273 p += _dirty_bytes_per_line;
1274 bottom += DIRTY_BLOCK_HEIGHT;
1275 } while (bottom != h && *p != 0);
1277 /* Try coalescing to the right too. */
1278 h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
1279 assert(h2 > 0);
1280 p = b;
1282 while (right != w) {
1283 byte *p2 = ++p;
1284 int h = h2;
1285 /* Check if a full line of dirty flags is set. */
1286 do {
1287 if (!*p2) goto no_more_coalesc;
1288 p2 += _dirty_bytes_per_line;
1289 } while (--h != 0);
1291 /* Wohoo, can combine it one step to the right!
1292 * Do that, and clear the bits. */
1293 right += DIRTY_BLOCK_WIDTH;
1295 h = h2;
1296 p2 = p;
1297 do {
1298 *p2 = 0;
1299 p2 += _dirty_bytes_per_line;
1300 } while (--h != 0);
1302 no_more_coalesc:
1304 left = x;
1305 top = y;
1307 if (left < _invalid_rect.left ) left = _invalid_rect.left;
1308 if (top < _invalid_rect.top ) top = _invalid_rect.top;
1309 if (right > _invalid_rect.right ) right = _invalid_rect.right;
1310 if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
1312 if (left < right && top < bottom) {
1313 RedrawScreenRect(left, top, right, bottom);
1317 } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
1318 } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
1320 ++_dirty_block_colour;
1321 _invalid_rect.left = w;
1322 _invalid_rect.top = h;
1323 _invalid_rect.right = 0;
1324 _invalid_rect.bottom = 0;
1328 * This function extends the internal _invalid_rect rectangle as it
1329 * now contains the rectangle defined by the given parameters. Note
1330 * the point (0,0) is top left.
1332 * @param left The left edge of the rectangle
1333 * @param top The top edge of the rectangle
1334 * @param right The right edge of the rectangle
1335 * @param bottom The bottom edge of the rectangle
1336 * @see DrawDirtyBlocks
1338 * @todo The name of the function should be called like @c AddDirtyBlock as
1339 * it neither set a dirty rect nor add several dirty rects although
1340 * the function name is in plural. (Progman)
1342 void SetDirtyBlocks(int left, int top, int right, int bottom)
1344 byte *b;
1345 int width;
1346 int height;
1348 if (left < 0) left = 0;
1349 if (top < 0) top = 0;
1350 if (right > _screen_width) right = _screen_width;
1351 if (bottom > _screen_height) bottom = _screen_height;
1353 if (left >= right || top >= bottom) return;
1355 if (left < _invalid_rect.left ) _invalid_rect.left = left;
1356 if (top < _invalid_rect.top ) _invalid_rect.top = top;
1357 if (right > _invalid_rect.right ) _invalid_rect.right = right;
1358 if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
1360 left /= DIRTY_BLOCK_WIDTH;
1361 top /= DIRTY_BLOCK_HEIGHT;
1363 b = _dirty_blocks + top * _dirty_bytes_per_line + left;
1365 width = ((right - 1) / DIRTY_BLOCK_WIDTH) - left + 1;
1366 height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top + 1;
1368 assert(width > 0 && height > 0);
1370 do {
1371 int i = width;
1373 do b[--i] = 0xFF; while (i != 0);
1375 b += _dirty_bytes_per_line;
1376 } while (--height != 0);
1380 * This function mark the whole screen as dirty. This results in repainting
1381 * the whole screen. Use this with care as this function will break the
1382 * idea about marking only parts of the screen as 'dirty'.
1383 * @ingroup dirty
1385 void MarkWholeScreenDirty()
1387 SetDirtyBlocks (0, 0, _screen_width, _screen_height);
1391 * Set up a clipping area for only drawing into a certain area.
1392 * @param *o the parent BlitArea
1393 * @param *n the BlitArea that will be the clipping rectangle box allowed
1394 * for drawing
1395 * @param left,top,width,height the relative coordinates of the clipping
1396 * rectangle relative to the current area. This will most likely be the
1397 * offset from the calling window coordinates
1398 * @return return false if the requested rectangle is not possible with the
1399 * current dpi pointer. Only continue of the return value is true, or you'll
1400 * get some nasty results
1402 bool InitBlitArea (const BlitArea *o, BlitArea *n,
1403 int left, int top, int width, int height)
1405 assert(width > 0);
1406 assert(height > 0);
1408 if ((left -= o->left) < 0) {
1409 width += left;
1410 if (width <= 0) return false;
1411 n->left = -left;
1412 left = 0;
1413 } else {
1414 n->left = 0;
1417 if (width > o->width - left) {
1418 width = o->width - left;
1419 if (width <= 0) return false;
1421 n->width = width;
1423 if ((top -= o->top) < 0) {
1424 height += top;
1425 if (height <= 0) return false;
1426 n->top = -top;
1427 top = 0;
1428 } else {
1429 n->top = 0;
1432 n->dst_ptr = o->surface->move (o->dst_ptr, left, top);
1433 n->surface = o->surface;
1435 if (height > o->height - top) {
1436 height = o->height - top;
1437 if (height <= 0) return false;
1439 n->height = height;
1441 return true;
1445 * Update cursor dimension.
1446 * Called when changing cursor sprite resp. reloading grfs.
1448 void UpdateCursorSize()
1450 /* Ignore setting any cursor before the sprites are loaded. */
1451 if (GetMaxSpriteID() == 0) return;
1453 assert(_cursor.sprite_count <= lengthof(_cursor.sprite_seq));
1454 for (uint i = 0; i < _cursor.sprite_count; ++i) {
1455 const Sprite *p = GetSprite(GB(_cursor.sprite_seq[i].sprite, 0, SPRITE_WIDTH), ST_NORMAL);
1456 Point offs, size;
1457 offs.x = UnScaleGUI(p->x_offs) + _cursor.sprite_seq[i].pos;
1458 offs.y = UnScaleGUI(p->y_offs);
1459 size.x = UnScaleGUI(p->width);
1460 size.y = UnScaleGUI(p->height);
1462 if (i == 0) {
1463 _cursor.total_offs = offs;
1464 _cursor.total_size = size;
1465 } else {
1466 int right = max(_cursor.total_offs.x + _cursor.total_size.x, offs.x + size.x);
1467 int bottom = max(_cursor.total_offs.y + _cursor.total_size.y, offs.y + size.y);
1468 if (offs.x < _cursor.total_offs.x) _cursor.total_offs.x = offs.x;
1469 if (offs.y < _cursor.total_offs.y) _cursor.total_offs.y = offs.y;
1470 _cursor.total_size.x = right - _cursor.total_offs.x;
1471 _cursor.total_size.y = bottom - _cursor.total_offs.y;
1475 _cursor.dirty = true;
1479 * Switch cursor to different sprite.
1480 * @param cursor Sprite to draw for the cursor.
1481 * @param pal Palette to use for recolouring.
1483 static void SetCursorSprite(CursorID cursor, PaletteID pal)
1485 if (_cursor.sprite_count == 1 && _cursor.sprite_seq[0].sprite == cursor && _cursor.sprite_seq[0].pal == pal) return;
1487 _cursor.sprite_count = 1;
1488 _cursor.sprite_seq[0].sprite = cursor;
1489 _cursor.sprite_seq[0].pal = pal;
1490 _cursor.sprite_seq[0].pos = 0;
1492 UpdateCursorSize();
1495 static void SwitchAnimatedCursor()
1497 const AnimCursor *cur = _cursor_animate_cur;
1499 if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor_animate_list;
1501 SetCursorSprite(cur->sprite, _cursor.sprite_seq[0].pal);
1503 _cursor_animate_timeout = cur->display_time;
1504 _cursor_animate_cur = cur + 1;
1507 void CursorTick()
1509 if (_cursor_animate_timeout != 0 && --_cursor_animate_timeout == 0) {
1510 SwitchAnimatedCursor();
1515 * Set or unset the ZZZ cursor.
1516 * @param busy Whether to show the ZZZ cursor.
1518 void SetMouseCursorBusy(bool busy)
1520 if (busy) {
1521 if (_cursor.sprite_seq[0].sprite == SPR_CURSOR_MOUSE) SetMouseCursor (SPR_CURSOR_ZZZ);
1522 } else {
1523 if (_cursor.sprite_seq[0].sprite == SPR_CURSOR_ZZZ) SetMouseCursor (SPR_CURSOR_MOUSE);
1528 * Assign a single non-animated sprite to the cursor.
1529 * @param sprite Sprite to draw for the cursor.
1530 * @see SetAnimatedMouseCursor
1532 void SetMouseCursor (CursorID sprite)
1534 /* Turn off animation */
1535 _cursor_animate_timeout = 0;
1536 /* Set cursor */
1537 SetCursorSprite (sprite, PAL_NONE);
1541 * Assign an animation to the cursor.
1542 * @param table Array of animation states.
1543 * @see SetMouseCursor
1545 void SetAnimatedMouseCursor(const AnimCursor *table)
1547 _cursor_animate_list = table;
1548 _cursor_animate_cur = NULL;
1549 _cursor.sprite_seq[0].pal = PAL_NONE;
1550 SwitchAnimatedCursor();
1554 * Update cursor position on mouse movement.
1555 * @param x New X position.
1556 * @param y New Y position.
1557 * @param queued True, if the OS queues mouse warps after pending mouse movement events.
1558 * False, if the warp applies instantaneous.
1559 * @return true, if the OS cursor position should be warped back to this->pos.
1561 bool CursorVars::UpdateCursorPosition(int x, int y, bool queued_warp)
1563 /* Detecting relative mouse movement is somewhat tricky.
1564 * - There may be multiple mouse move events in the video driver queue (esp. when OpenTTD lags a bit).
1565 * - When we request warping the mouse position (return true), a mouse move event is appended at the end of the queue.
1567 * So, when this->fix_at is active, we use the following strategy:
1568 * - The first movement triggers the warp to reset the mouse position.
1569 * - Subsequent events have to compute movement relative to the previous event.
1570 * - The relative movement is finished, when we receive the event matching the warp.
1573 if (x == this->pos.x && y == this->pos.y) {
1574 /* Warp finished. */
1575 this->queued_warp = false;
1577 this->delta.x = 0;
1578 this->delta.y = 0;
1580 this->last_position.x = x;
1581 this->last_position.y = y;
1583 return false;
1586 this->delta.x = x - (this->queued_warp ? this->last_position.x : this->pos.x);
1587 this->delta.y = y - (this->queued_warp ? this->last_position.y : this->pos.y);
1589 this->last_position.x = x;
1590 this->last_position.y = y;
1592 bool need_warp = false;
1593 if (!this->fix_at) {
1594 this->queued_warp = false; // Cancel warping, we are no longer confining the position.
1595 this->dirty = true;
1596 this->pos.x = x;
1597 this->pos.y = y;
1598 } else if (this->delta.x != 0 || this->delta.y != 0) {
1599 /* Trigger warp.
1600 * Note: We also trigger warping again, if there is already a pending warp.
1601 * This makes it more tolerant about the OS or other software inbetween
1602 * botchering the warp. */
1603 this->queued_warp = queued_warp;
1604 need_warp = true;
1606 return need_warp;
1609 bool ChangeResInGame(int width, int height)
1611 return (_screen_width == width && _screen_height == height) || VideoDriver::GetActiveDriver()->ChangeResolution(width, height);
1614 bool ToggleFullScreen(bool fs)
1616 bool result = VideoDriver::GetActiveDriver()->ToggleFullscreen(fs);
1617 if (_fullscreen != fs && _num_resolutions == 0) {
1618 DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
1620 return result;
1623 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
1625 int x = pa->width - pb->width;
1626 if (x != 0) return x;
1627 return pa->height - pb->height;
1630 void SortResolutions(int count)
1632 QSortT(_resolutions, count, &compare_res);