Remove second template parameter from class GUIList
[openttd/fttd.git] / src / screenshot.cpp
blobb463fa7463dd97d275682f45df93e22fa0e258e8
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 screenshot.cpp The creation of screenshots! */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "string.h"
15 #include "fileio_func.h"
16 #include "viewport_func.h"
17 #include "gfx_func.h"
18 #include "screenshot.h"
19 #include "blitter/blitter.h"
20 #include "zoom_func.h"
21 #include "core/endian_func.hpp"
22 #include "saveload/saveload.h"
23 #include "company_func.h"
24 #include "strings_func.h"
25 #include "error.h"
26 #include "window_gui.h"
27 #include "window_func.h"
28 #include "map/zoneheight.h"
29 #include "landscape.h"
31 #include "table/strings.h"
33 static const char * const SCREENSHOT_NAME = "screenshot"; ///< Default filename of a saved screenshot.
34 static const char * const HEIGHTMAP_NAME = "heightmap"; ///< Default filename of a saved heightmap.
36 char _screenshot_format_name[8]; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
37 uint _num_screenshot_formats; ///< Number of available screenshot formats.
38 uint _cur_screenshot_format; ///< Index of the currently selected screenshot format in #_screenshot_formats.
39 static sstring<128> _screenshot_name;///< Filename of the screenshot file.
40 char _full_screenshot_name[MAX_PATH]; ///< Pathname of the screenshot file.
42 /**
43 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
44 * @param userdata Pointer to user data.
45 * @param buf Destination buffer.
46 * @param y Line number of the first line to write.
47 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
48 * @param n Number of lines to write.
50 typedef void ScreenshotCallback(void *userdata, void *buf, uint y, uint pitch, uint n);
52 /**
53 * Function signature for a screenshot generation routine for one of the available formats.
54 * @param name Filename, including extension.
55 * @param callb Callback function for generating lines of pixels.
56 * @param userdata User data, passed on to \a callb.
57 * @param w Width of the image in pixels.
58 * @param h Height of the image in pixels.
59 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
60 * @param palette %Colour palette (for 8bpp images).
61 * @return File was written successfully.
63 typedef bool ScreenshotHandlerProc(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette);
65 /** Screenshot format information. */
66 struct ScreenshotFormat {
67 const char *name; ///< Name of the format.
68 const char *extension; ///< File extension, including leading dot.
69 ScreenshotHandlerProc *proc; ///< Function for writing the screenshot.
70 bool supports_32bpp; ///< Does this format support 32bpp images?
73 /*************************************************
74 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
75 *************************************************/
76 #if defined(_MSC_VER) || defined(__WATCOMC__)
77 #pragma pack(push, 1)
78 #endif
80 /** BMP File Header (stored in little endian) */
81 struct BitmapFileHeader {
82 uint16 type;
83 uint32 size;
84 uint32 reserved;
85 uint32 off_bits;
86 } GCC_PACK;
87 assert_compile(sizeof(BitmapFileHeader) == 14);
89 #if defined(_MSC_VER) || defined(__WATCOMC__)
90 #pragma pack(pop)
91 #endif
93 /** BMP Info Header (stored in little endian) */
94 struct BitmapInfoHeader {
95 uint32 size;
96 int32 width, height;
97 uint16 planes, bitcount;
98 uint32 compression, sizeimage, xpels, ypels, clrused, clrimp;
100 assert_compile(sizeof(BitmapInfoHeader) == 40);
102 /** Format of palette data in BMP header */
103 struct RgbQuad {
104 byte blue, green, red, reserved;
106 assert_compile(sizeof(RgbQuad) == 4);
109 * Generic .BMP writer
110 * @param name file name including extension
111 * @param callb callback used for gathering rendered image
112 * @param userdata parameters forwarded to \a callb
113 * @param w width in pixels
114 * @param h height in pixels
115 * @param pixelformat bits per pixel
116 * @param palette colour palette (for 8bpp mode)
117 * @return was everything ok?
118 * @see ScreenshotHandlerProc
120 static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
122 uint bpp; // bytes per pixel
123 switch (pixelformat) {
124 case 8: bpp = 1; break;
125 /* 32bpp mode is saved as 24bpp BMP */
126 case 32: bpp = 3; break;
127 /* Only implemented for 8bit and 32bit images so far */
128 default: return false;
131 FILE *f = fopen(name, "wb");
132 if (f == NULL) return false;
134 /* Each scanline must be aligned on a 32bit boundary */
135 uint bytewidth = Align(w * bpp, 4); // bytes per line in file
137 /* Size of palette. Only present for 8bpp mode */
138 uint pal_size = pixelformat == 8 ? sizeof(RgbQuad) * 256 : 0;
140 /* Setup the file header */
141 BitmapFileHeader bfh;
142 bfh.type = TO_LE16('MB');
143 bfh.size = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size + bytewidth * h);
144 bfh.reserved = 0;
145 bfh.off_bits = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size);
147 /* Setup the info header */
148 BitmapInfoHeader bih;
149 bih.size = TO_LE32(sizeof(BitmapInfoHeader));
150 bih.width = TO_LE32(w);
151 bih.height = TO_LE32(h);
152 bih.planes = TO_LE16(1);
153 bih.bitcount = TO_LE16(bpp * 8);
154 bih.compression = 0;
155 bih.sizeimage = 0;
156 bih.xpels = 0;
157 bih.ypels = 0;
158 bih.clrused = 0;
159 bih.clrimp = 0;
161 /* Write file header and info header */
162 if (fwrite(&bfh, sizeof(bfh), 1, f) != 1 || fwrite(&bih, sizeof(bih), 1, f) != 1) {
163 fclose(f);
164 return false;
167 if (pixelformat == 8) {
168 /* Convert the palette to the windows format */
169 RgbQuad rq[256];
170 for (uint i = 0; i < 256; i++) {
171 rq[i].red = palette[i].r;
172 rq[i].green = palette[i].g;
173 rq[i].blue = palette[i].b;
174 rq[i].reserved = 0;
176 /* Write the palette */
177 if (fwrite(rq, sizeof(rq), 1, f) != 1) {
178 fclose(f);
179 return false;
183 /* Try to use 64k of memory, store between 16 and 128 lines */
184 uint maxlines = Clamp(65536 / (w * pixelformat / 8), 16, 128); // number of lines per iteration
186 uint8 *buff = xmalloct<uint8>(maxlines * w * pixelformat / 8); // buffer which is rendered to
187 uint8 *line = AllocaM(uint8, bytewidth); // one line, stored to file
188 memset(line, 0, bytewidth);
190 /* Start at the bottom, since bitmaps are stored bottom up */
191 do {
192 uint n = min(h, maxlines);
193 h -= n;
195 /* Render the pixels */
196 callb(userdata, buff, h, w, n);
198 /* Write each line */
199 while (n-- != 0) {
200 if (pixelformat == 8) {
201 /* Move to 'line', leave last few pixels in line zeroed */
202 memcpy(line, buff + n * w, w);
203 } else {
204 /* Convert from 'native' 32bpp to BMP-like 24bpp.
205 * Works for both big and little endian machines */
206 Colour *src = ((Colour *)buff) + n * w;
207 byte *dst = line;
208 for (uint i = 0; i < w; i++) {
209 dst[i * 3 ] = src[i].b;
210 dst[i * 3 + 1] = src[i].g;
211 dst[i * 3 + 2] = src[i].r;
214 /* Write to file */
215 if (fwrite(line, bytewidth, 1, f) != 1) {
216 free(buff);
217 fclose(f);
218 return false;
221 } while (h != 0);
223 free(buff);
224 fclose(f);
226 return true;
229 /*********************************************************
230 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
231 *********************************************************/
232 #if defined(WITH_PNG)
233 #include <png.h>
235 #ifdef PNG_TEXT_SUPPORTED
236 #include "rev.h"
237 #include "newgrf_config.h"
238 #include "ai/ai_info.hpp"
239 #include "company_base.h"
240 #include "base_media_base.h"
241 #endif /* PNG_TEXT_SUPPORTED */
243 static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
245 DEBUG(misc, 0, "[libpng] error: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
246 longjmp(png_jmpbuf(png_ptr), 1);
249 static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
251 DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
255 * Generic .PNG file image writer.
256 * @param name Filename, including extension.
257 * @param callb Callback function for generating lines of pixels.
258 * @param userdata User data, passed on to \a callb.
259 * @param w Width of the image in pixels.
260 * @param h Height of the image in pixels.
261 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
262 * @param palette %Colour palette (for 8bpp images).
263 * @return File was written successfully.
264 * @see ScreenshotHandlerProc
266 static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
268 png_color rq[256];
269 FILE *f;
270 uint i, y, n;
271 uint maxlines;
272 uint bpp = pixelformat / 8;
273 png_structp png_ptr;
274 png_infop info_ptr;
276 /* only implemented for 8bit and 32bit images so far. */
277 if (pixelformat != 8 && pixelformat != 32) return false;
279 f = fopen(name, "wb");
280 if (f == NULL) return false;
282 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char *>(name), png_my_error, png_my_warning);
284 if (png_ptr == NULL) {
285 fclose(f);
286 return false;
289 info_ptr = png_create_info_struct(png_ptr);
290 if (info_ptr == NULL) {
291 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
292 fclose(f);
293 return false;
296 if (setjmp(png_jmpbuf(png_ptr))) {
297 png_destroy_write_struct(&png_ptr, &info_ptr);
298 fclose(f);
299 return false;
302 png_init_io(png_ptr, f);
304 png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
306 png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
307 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
309 #ifdef PNG_TEXT_SUPPORTED
310 /* Try to add some game metadata to the PNG screenshot so
311 * it's more useful for debugging and archival purposes. */
312 png_text_struct text[2];
313 memset(text, 0, sizeof(text));
314 text[0].key = const_cast<char *>("Software");
315 text[0].text = const_cast<char *>(_openttd_revision);
316 text[0].text_length = strlen(_openttd_revision);
317 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
319 sstring<8192> buf;
320 buf.fmt ("Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->get_name(), BaseGraphics::GetUsedSet()->version);
321 buf.append ("NewGRFs:\n");
322 for (const GRFConfig *c = _game_mode == GM_MENU ? NULL : _grfconfig; c != NULL; c = c->next) {
323 buf.append_fmt ("%08X ", BSWAP32(c->ident.grfid));
324 buf.append_md5sum (c->ident.md5sum);
325 buf.append_fmt (" %s\n", c->filename);
327 buf.append ("\nCompanies:\n");
328 const Company *c;
329 FOR_ALL_COMPANIES(c) {
330 if (c->ai_info == NULL) {
331 buf.append_fmt ("%2i: Human\n", (int)c->index);
332 } else {
333 buf.append_fmt ("%2i: %s (v%d)\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
336 text[1].key = const_cast<char *>("Description");
337 text[1].text = buf.data;
338 text[1].text_length = buf.length();
339 text[1].compression = PNG_TEXT_COMPRESSION_zTXt;
340 png_set_text(png_ptr, info_ptr, text, 2);
341 #endif /* PNG_TEXT_SUPPORTED */
343 if (pixelformat == 8) {
344 /* convert the palette to the .PNG format. */
345 for (i = 0; i != 256; i++) {
346 rq[i].red = palette[i].r;
347 rq[i].green = palette[i].g;
348 rq[i].blue = palette[i].b;
351 png_set_PLTE(png_ptr, info_ptr, rq, 256);
354 png_write_info(png_ptr, info_ptr);
355 png_set_flush(png_ptr, 512);
357 if (pixelformat == 32) {
358 png_color_8 sig_bit;
360 /* Save exact colour/alpha resolution */
361 sig_bit.alpha = 0;
362 sig_bit.blue = 8;
363 sig_bit.green = 8;
364 sig_bit.red = 8;
365 sig_bit.gray = 8;
366 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
368 #if TTD_ENDIAN == TTD_LITTLE_ENDIAN
369 png_set_bgr(png_ptr);
370 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
371 #else
372 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
373 #endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
376 /* use by default 64k temp memory */
377 maxlines = Clamp(65536 / w, 16, 128);
379 /* now generate the bitmap bits */
380 void *buff = xcalloct<uint8>(w * maxlines * bpp); // by default generate 128 lines at a time.
382 y = 0;
383 do {
384 /* determine # lines to write */
385 n = min(h - y, maxlines);
387 /* render the pixels into the buffer */
388 callb(userdata, buff, y, w, n);
389 y += n;
391 /* write them to png */
392 for (i = 0; i != n; i++) {
393 png_write_row(png_ptr, (png_bytep)buff + i * w * bpp);
395 } while (y != h);
397 png_write_end(png_ptr, info_ptr);
398 png_destroy_write_struct(&png_ptr, &info_ptr);
400 free(buff);
401 fclose(f);
402 return true;
404 #endif /* WITH_PNG */
407 /*************************************************
408 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
409 *************************************************/
411 /** Definition of a PCX file header. */
412 struct PcxHeader {
413 byte manufacturer;
414 byte version;
415 byte rle;
416 byte bpp;
417 uint32 unused;
418 uint16 xmax, ymax;
419 uint16 hdpi, vdpi;
420 byte pal_small[16 * 3];
421 byte reserved;
422 byte planes;
423 uint16 pitch;
424 uint16 cpal;
425 uint16 width;
426 uint16 height;
427 byte filler[54];
429 assert_compile(sizeof(PcxHeader) == 128);
432 * Generic .PCX file image writer.
433 * @param name Filename, including extension.
434 * @param callb Callback function for generating lines of pixels.
435 * @param userdata User data, passed on to \a callb.
436 * @param w Width of the image in pixels.
437 * @param h Height of the image in pixels.
438 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
439 * @param palette %Colour palette (for 8bpp images).
440 * @return File was written successfully.
441 * @see ScreenshotHandlerProc
443 static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
445 FILE *f;
446 uint maxlines;
447 uint y;
448 PcxHeader pcx;
449 bool success;
451 if (pixelformat == 32) {
452 DEBUG(misc, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
453 return false;
455 if (pixelformat != 8 || w == 0) return false;
457 f = fopen(name, "wb");
458 if (f == NULL) return false;
460 memset(&pcx, 0, sizeof(pcx));
462 /* setup pcx header */
463 pcx.manufacturer = 10;
464 pcx.version = 5;
465 pcx.rle = 1;
466 pcx.bpp = 8;
467 pcx.xmax = TO_LE16(w - 1);
468 pcx.ymax = TO_LE16(h - 1);
469 pcx.hdpi = TO_LE16(320);
470 pcx.vdpi = TO_LE16(320);
472 pcx.planes = 1;
473 pcx.cpal = TO_LE16(1);
474 pcx.width = pcx.pitch = TO_LE16(w);
475 pcx.height = TO_LE16(h);
477 /* write pcx header */
478 if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
479 fclose(f);
480 return false;
483 /* use by default 64k temp memory */
484 maxlines = Clamp(65536 / w, 16, 128);
486 /* now generate the bitmap bits */
487 uint8 *buff = xcalloct<uint8>(w * maxlines); // by default generate 128 lines at a time.
489 y = 0;
490 do {
491 /* determine # lines to write */
492 uint n = min(h - y, maxlines);
493 uint i;
495 /* render the pixels into the buffer */
496 callb(userdata, buff, y, w, n);
497 y += n;
499 /* write them to pcx */
500 for (i = 0; i != n; i++) {
501 const uint8 *bufp = buff + i * w;
502 byte runchar = bufp[0];
503 uint runcount = 1;
504 uint j;
506 /* for each pixel... */
507 for (j = 1; j < w; j++) {
508 uint8 ch = bufp[j];
510 if (ch != runchar || runcount >= 0x3f) {
511 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
512 if (fputc(0xC0 | runcount, f) == EOF) {
513 free(buff);
514 fclose(f);
515 return false;
518 if (fputc(runchar, f) == EOF) {
519 free(buff);
520 fclose(f);
521 return false;
523 runcount = 0;
524 runchar = ch;
526 runcount++;
529 /* write remaining bytes.. */
530 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
531 if (fputc(0xC0 | runcount, f) == EOF) {
532 free(buff);
533 fclose(f);
534 return false;
537 if (fputc(runchar, f) == EOF) {
538 free(buff);
539 fclose(f);
540 return false;
543 } while (y != h);
545 free(buff);
547 /* write 8-bit colour palette */
548 if (fputc(12, f) == EOF) {
549 fclose(f);
550 return false;
553 /* Palette is word-aligned, copy it to a temporary byte array */
554 byte tmp[256 * 3];
556 for (uint i = 0; i < 256; i++) {
557 tmp[i * 3 + 0] = palette[i].r;
558 tmp[i * 3 + 1] = palette[i].g;
559 tmp[i * 3 + 2] = palette[i].b;
561 success = fwrite(tmp, sizeof(tmp), 1, f) == 1;
563 fclose(f);
565 return success;
568 /*************************************************
569 **** GENERIC SCREENSHOT CODE
570 *************************************************/
572 /** Available screenshot formats. */
573 static const ScreenshotFormat _screenshot_formats[] = {
574 #if defined(WITH_PNG)
575 {"PNG", ".png", &MakePNGImage, true},
576 #endif
577 {"BMP", ".bmp", &MakeBMPImage, true},
578 {"PCX", ".pcx", &MakePCXImage, false},
581 /** Get filename extension of current screenshot file format. */
582 const char *GetCurrentScreenshotExtension()
584 return _screenshot_formats[_cur_screenshot_format].extension;
587 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
588 void InitializeScreenshotFormats()
590 uint j = 0;
591 for (uint i = 0; i < lengthof(_screenshot_formats); i++) {
592 /* skip leading dot when comparing */
593 if (!strcmp (_screenshot_format_name, _screenshot_formats[i].extension + 1)) {
594 j = i;
595 break;
598 _cur_screenshot_format = j;
599 _num_screenshot_formats = lengthof(_screenshot_formats);
603 * Give descriptive name of the screenshot format.
604 * @param i Number of the screenshot format.
605 * @return String constant describing the format.
607 const char *GetScreenshotFormatDesc(int i)
609 return _screenshot_formats[i].name;
613 * Determine whether a certain screenshot format support 32bpp images.
614 * @param i Number of the screenshot format.
615 * @return true if 32bpp is supported.
617 bool GetScreenshotFormatSupports_32bpp(int i)
619 return _screenshot_formats[i].supports_32bpp;
623 * Set the screenshot format to use.
624 * @param i Number of the format.
626 void SetScreenshotFormat(uint i)
628 assert(i < _num_screenshot_formats);
629 _cur_screenshot_format = i;
630 /* skip leading dot */
631 bstrcpy (_screenshot_format_name, _screenshot_formats[i].extension + 1);
635 * Callback of the screenshot generator that dumps the current video buffer.
636 * @see ScreenshotCallback
638 static void CurrentScreenCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
640 _screen_surface->export_lines (buf, pitch, y, n);
644 * generate a large piece of the world
645 * @param userdata Viewport area to draw
646 * @param buf Videobuffer with same bitdepth as current blitter
647 * @param y First line to render
648 * @param pitch Pitch of the videobuffer
649 * @param n Number of lines to render
651 static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
653 const ViewPort *vp = (ViewPort *)userdata;
654 assert (vp->left == 0);
655 assert (vp->top == 0);
657 int wx, left;
659 /* We are no longer rendering to the screen */
660 ttd_unique_ptr <Blitter::Surface> surface (Blitter::get()->create (buf, pitch, n, pitch, false));
661 /* Pretend this is part of a larger buffer. */
662 void *dst_ptr = surface->move (buf, 0, -y);
664 /* Render viewport in blocks of 1600 pixels width */
665 left = 0;
666 while (vp->width - left != 0) {
667 wx = min(vp->width - left, 1600);
668 ViewportDoDraw (surface.get(), dst_ptr, vp, left, y, wx, n);
669 left += wx;
674 * Construct a pathname for a screenshot file.
675 * @param default_fn Default filename.
676 * @param ext Extension to use, including leading dot.
677 * @param crashlog Create path for crash.png
678 * @return Pathname for a screenshot file.
680 static const char *MakeScreenshotName(const char *default_fn, const char *ext, bool crashlog = false)
682 bool generate = _screenshot_name.empty();
684 if (generate) {
685 if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
686 _screenshot_name.copy (default_fn);
687 } else {
688 GenerateDefaultSaveName (&_screenshot_name);
692 /* Add extension to screenshot file */
693 size_t len = _screenshot_name.length();
694 _screenshot_name.append (ext);
696 const char *screenshot_dir = crashlog ? _personal_dir : FiosGetScreenshotDir();
698 for (uint serial = 1;; serial++) {
699 if (snprintf(_full_screenshot_name, lengthof(_full_screenshot_name), "%s%s", screenshot_dir, _screenshot_name.c_str()) >= (int)lengthof(_full_screenshot_name)) {
700 /* We need more characters than MAX_PATH -> end with error */
701 _full_screenshot_name[0] = '\0';
702 break;
704 if (!generate) break; // allow overwriting of non-automatic filenames
705 if (!FileExists(_full_screenshot_name)) break;
706 /* If file exists try another one with same name, but just with a higher index */
707 _screenshot_name.truncate (len);
708 _screenshot_name.append_fmt ("#%u%s", serial, ext);
711 return _full_screenshot_name;
714 /** Make a screenshot of the current screen. */
715 static bool MakeSmallScreenshot(bool crashlog)
717 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
718 return sf->proc (MakeScreenshotName (SCREENSHOT_NAME, sf->extension, crashlog),
719 CurrentScreenCallback, NULL, _screen_width, _screen_height,
720 Blitter::get()->GetScreenDepth(), _cur_palette.palette);
724 * Configure a ViewPort for rendering (a part of) the map into a screenshot.
725 * @param t Screenshot type
726 * @param [out] vp Result viewport
728 void SetupScreenshotViewport(ScreenshotType t, ViewPort *vp)
730 /* Determine world coordinates of screenshot */
731 if (t == SC_WORLD) {
732 vp->zoom = ZOOM_LVL_WORLD_SCREENSHOT;
734 TileIndex north_tile = _settings_game.construction.freeform_edges ? TileXY(1, 1) : TileXY(0, 0);
735 TileIndex south_tile = MapSize() - 1;
737 /* We need to account for a hill or high building at tile 0,0. */
738 int extra_height_top = TilePixelHeight(north_tile) + 150;
739 /* If there is a hill at the bottom don't create a large black area. */
740 int reclaim_height_bottom = TilePixelHeight(south_tile);
742 vp->virtual_left = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, 0).x;
743 vp->virtual_top = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, extra_height_top).y;
744 vp->virtual_width = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, 0).x - vp->virtual_left + 1;
745 vp->virtual_height = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, reclaim_height_bottom).y - vp->virtual_top + 1;
746 } else {
747 vp->zoom = (t == SC_ZOOMEDIN) ? _settings_client.gui.zoom_min : ZOOM_LVL_VIEWPORT;
749 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
750 vp->virtual_left = w->viewport->virtual_left;
751 vp->virtual_top = w->viewport->virtual_top;
752 vp->virtual_width = w->viewport->virtual_width;
753 vp->virtual_height = w->viewport->virtual_height;
756 /* Compute pixel coordinates */
757 vp->left = 0;
758 vp->top = 0;
759 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
760 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
761 vp->overlay = NULL;
765 * Make a screenshot of the map.
766 * @param t Screenshot type: World or viewport screenshot
767 * @return true on success
769 static bool MakeLargeWorldScreenshot(ScreenshotType t)
771 ViewPort vp;
772 SetupScreenshotViewport(t, &vp);
773 assert (vp.left == 0);
774 assert (vp.top == 0);
776 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
777 return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension), LargeWorldCallback, &vp, vp.width, vp.height,
778 Blitter::get()->GetScreenDepth(), _cur_palette.palette);
782 * Callback for generating a heightmap. Supports 8bpp grayscale only.
783 * @param userdata Pointer to user data.
784 * @param buf Destination buffer.
785 * @param y Line number of the first line to write.
786 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
787 * @param n Number of lines to write.
788 * @see ScreenshotCallback
790 static void HeightmapCallback(void *userdata, void *buffer, uint y, uint pitch, uint n)
792 byte *buf = (byte *)buffer;
793 while (n > 0) {
794 TileIndex ti = TileXY(MapMaxX(), y);
795 for (uint x = MapMaxX(); true; x--) {
796 *buf = 256 * TileHeight(ti) / (1 + _settings_game.construction.max_heightlevel);
797 buf++;
798 if (x == 0) break;
799 ti = TILE_ADDXY(ti, -1, 0);
801 y++;
802 n--;
807 * Make a heightmap of the current map.
808 * @param filename Filename to use for saving.
810 bool MakeHeightmapScreenshot(const char *filename)
812 Colour palette[256];
813 for (uint i = 0; i < lengthof(palette); i++) {
814 palette[i].a = 0xff;
815 palette[i].r = i;
816 palette[i].g = i;
817 palette[i].b = i;
819 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
820 return sf->proc(filename, HeightmapCallback, NULL, MapSizeX(), MapSizeY(), 8, palette);
824 * Make an actual screenshot.
825 * @param t the type of screenshot to make.
826 * @param name the name to give to the screenshot.
827 * @return true iff the screenshot was made successfully
829 bool MakeScreenshot(ScreenshotType t, const char *name)
831 if (t == SC_VIEWPORT) {
832 /* First draw the dirty parts of the screen and only then change the name
833 * of the screenshot. This way the screenshot will always show the name
834 * of the previous screenshot in the 'successful' message instead of the
835 * name of the new screenshot (or an empty name). */
836 UndrawMouseCursor();
837 DrawDirtyBlocks();
840 _screenshot_name.clear();
841 if (name != NULL) _screenshot_name.copy (name);
843 bool ret;
844 switch (t) {
845 case SC_VIEWPORT:
846 ret = MakeSmallScreenshot(false);
847 break;
849 case SC_CRASHLOG:
850 ret = MakeSmallScreenshot(true);
851 break;
853 case SC_ZOOMEDIN:
854 case SC_DEFAULTZOOM:
855 case SC_WORLD:
856 ret = MakeLargeWorldScreenshot(t);
857 break;
859 case SC_HEIGHTMAP: {
860 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
861 ret = MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME, sf->extension));
862 break;
865 default:
866 NOT_REACHED();
869 if (ret) {
870 SetDParamStr(0, _screenshot_name.c_str());
871 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY, INVALID_STRING_ID, WL_WARNING);
872 } else {
873 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED, INVALID_STRING_ID, WL_ERROR);
876 return ret;