Hotfix: Conditional order comparator dropdown list was broken.
[openttd-joker.git] / src / screenshot.cpp
blob50c3955e947174cf81762e801e67925b0ba3df77
1 /* $Id: screenshot.cpp 26209 2014-01-02 22:41:58Z rubidium $ */
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 "fileio_func.h"
14 #include "viewport_func.h"
15 #include "gfx_func.h"
16 #include "screenshot.h"
17 #include "blitter/factory.hpp"
18 #include "zoom_func.h"
19 #include "core/endian_func.hpp"
20 #include "saveload/saveload.h"
21 #include "company_func.h"
22 #include "strings_func.h"
23 #include "error.h"
24 #include "window_gui.h"
25 #include "window_func.h"
26 #include "tile_map.h"
27 #include "landscape.h"
28 #include "smallmap_gui.h"
29 #include "smallmap_colours.h"
30 #include "industry.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 static const char * const SCREENSHOT_NAME = "screenshot"; ///< Default filename of a saved screenshot.
37 static const char * const HEIGHTMAP_NAME = "heightmap"; ///< Default filename of a saved heightmap.
39 char _screenshot_format_name[8]; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
40 uint _num_screenshot_formats; ///< Number of available screenshot formats.
41 uint _cur_screenshot_format; ///< Index of the currently selected screenshot format in #_screenshot_formats.
42 static char _screenshot_name[128]; ///< Filename of the screenshot file.
43 char _full_screenshot_name[MAX_PATH]; ///< Pathname of the screenshot file.
45 /**
46 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
47 * @param userdata Pointer to user data.
48 * @param buf Destination buffer.
49 * @param y Line number of the first line to write.
50 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
51 * @param n Number of lines to write.
53 typedef void ScreenshotCallback(void *userdata, void *buf, uint y, uint pitch, uint n);
55 /**
56 * Function signature for a screenshot generation routine for one of the available formats.
57 * @param name Filename, including extension.
58 * @param callb Callback function for generating lines of pixels.
59 * @param userdata User data, passed on to \a callb.
60 * @param w Width of the image in pixels.
61 * @param h Height of the image in pixels.
62 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
63 * @param palette %Colour palette (for 8bpp images).
64 * @return File was written successfully.
66 typedef bool ScreenshotHandlerProc(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette);
68 /** Screenshot format information. */
69 struct ScreenshotFormat {
70 const char *extension; ///< File extension.
71 ScreenshotHandlerProc *proc; ///< Function for writing the screenshot.
74 #define MKCOLOUR(x) TO_LE32X(x)
76 /*************************************************
77 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
78 *************************************************/
79 #if defined(_MSC_VER) || defined(__WATCOMC__)
80 #pragma pack(push, 1)
81 #endif
83 /** BMP File Header (stored in little endian) */
84 struct BitmapFileHeader {
85 uint16 type;
86 uint32 size;
87 uint32 reserved;
88 uint32 off_bits;
89 } GCC_PACK;
90 assert_compile(sizeof(BitmapFileHeader) == 14);
92 #if defined(_MSC_VER) || defined(__WATCOMC__)
93 #pragma pack(pop)
94 #endif
96 /** BMP Info Header (stored in little endian) */
97 struct BitmapInfoHeader {
98 uint32 size;
99 int32 width, height;
100 uint16 planes, bitcount;
101 uint32 compression, sizeimage, xpels, ypels, clrused, clrimp;
103 assert_compile(sizeof(BitmapInfoHeader) == 40);
105 /** Format of palette data in BMP header */
106 struct RgbQuad {
107 byte blue, green, red, reserved;
109 assert_compile(sizeof(RgbQuad) == 4);
112 * Generic .BMP writer
113 * @param name file name including extension
114 * @param callb callback used for gathering rendered image
115 * @param userdata parameters forwarded to \a callb
116 * @param w width in pixels
117 * @param h height in pixels
118 * @param pixelformat bits per pixel
119 * @param palette colour palette (for 8bpp mode)
120 * @return was everything ok?
121 * @see ScreenshotHandlerProc
123 static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
125 uint bpp; // bytes per pixel
126 switch (pixelformat) {
127 case 8: bpp = 1; break;
128 /* 32bpp mode is saved as 24bpp BMP */
129 case 32: bpp = 3; break;
130 /* Only implemented for 8bit and 32bit images so far */
131 default: return false;
134 FILE *f = fopen(name, "wb");
135 if (f == NULL) return false;
137 /* Each scanline must be aligned on a 32bit boundary */
138 uint bytewidth = Align(w * bpp, 4); // bytes per line in file
140 /* Size of palette. Only present for 8bpp mode */
141 uint pal_size = pixelformat == 8 ? sizeof(RgbQuad) * 256 : 0;
143 /* Setup the file header */
144 BitmapFileHeader bfh;
145 bfh.type = TO_LE16('MB');
146 bfh.size = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size + bytewidth * h);
147 bfh.reserved = 0;
148 bfh.off_bits = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size);
150 /* Setup the info header */
151 BitmapInfoHeader bih;
152 bih.size = TO_LE32(sizeof(BitmapInfoHeader));
153 bih.width = TO_LE32(w);
154 bih.height = TO_LE32(h);
155 bih.planes = TO_LE16(1);
156 bih.bitcount = TO_LE16(bpp * 8);
157 bih.compression = 0;
158 bih.sizeimage = 0;
159 bih.xpels = 0;
160 bih.ypels = 0;
161 bih.clrused = 0;
162 bih.clrimp = 0;
164 /* Write file header and info header */
165 if (fwrite(&bfh, sizeof(bfh), 1, f) != 1 || fwrite(&bih, sizeof(bih), 1, f) != 1) {
166 fclose(f);
167 return false;
170 if (pixelformat == 8) {
171 /* Convert the palette to the windows format */
172 RgbQuad rq[256];
173 for (uint i = 0; i < 256; i++) {
174 rq[i].red = palette[i].r;
175 rq[i].green = palette[i].g;
176 rq[i].blue = palette[i].b;
177 rq[i].reserved = 0;
179 /* Write the palette */
180 if (fwrite(rq, sizeof(rq), 1, f) != 1) {
181 fclose(f);
182 return false;
186 /* Try to use 64k of memory, store between 16 and 128 lines */
187 uint maxlines = Clamp(65536 / (w * pixelformat / 8), 16, 128); // number of lines per iteration
189 uint8 *buff = MallocT<uint8>(maxlines * w * pixelformat / 8); // buffer which is rendered to
190 uint8 *line = AllocaM(uint8, bytewidth); // one line, stored to file
191 memset(line, 0, bytewidth);
193 /* Start at the bottom, since bitmaps are stored bottom up */
194 do {
195 uint n = min(h, maxlines);
196 h -= n;
198 /* Render the pixels */
199 callb(userdata, buff, h, w, n);
201 /* Write each line */
202 while (n-- != 0) {
203 if (pixelformat == 8) {
204 /* Move to 'line', leave last few pixels in line zeroed */
205 memcpy(line, buff + n * w, w);
206 } else {
207 /* Convert from 'native' 32bpp to BMP-like 24bpp.
208 * Works for both big and little endian machines */
209 Colour *src = ((Colour *)buff) + n * w;
210 byte *dst = line;
211 for (uint i = 0; i < w; i++) {
212 dst[i * 3 ] = src[i].b;
213 dst[i * 3 + 1] = src[i].g;
214 dst[i * 3 + 2] = src[i].r;
217 /* Write to file */
218 if (fwrite(line, bytewidth, 1, f) != 1) {
219 free(buff);
220 fclose(f);
221 return false;
224 } while (h != 0);
226 free(buff);
227 fclose(f);
229 return true;
232 /*********************************************************
233 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
234 *********************************************************/
235 #if defined(WITH_PNG)
236 #include <png.h>
238 #ifdef PNG_TEXT_SUPPORTED
239 #include "rev.h"
240 #include "newgrf_config.h"
241 #include "ai/ai_info.hpp"
242 #include "company_base.h"
243 #include "base_media_base.h"
244 #endif /* PNG_TEXT_SUPPORTED */
246 static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
248 DEBUG(misc, 0, "[libpng] error: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
249 longjmp(png_jmpbuf(png_ptr), 1);
252 static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
254 DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
258 * Generic .PNG file image writer.
259 * @param name Filename, including extension.
260 * @param callb Callback function for generating lines of pixels.
261 * @param userdata User data, passed on to \a callb.
262 * @param w Width of the image in pixels.
263 * @param h Height of the image in pixels.
264 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
265 * @param palette %Colour palette (for 8bpp images).
266 * @return File was written successfully.
267 * @see ScreenshotHandlerProc
269 static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
271 png_color rq[256];
272 FILE *f;
273 uint i, y, n;
274 uint maxlines;
275 uint bpp = pixelformat / 8;
276 png_structp png_ptr;
277 png_infop info_ptr;
279 /* only implemented for 8bit and 32bit images so far. */
280 if (pixelformat != 8 && pixelformat != 32) return false;
282 f = fopen(name, "wb");
283 if (f == NULL) return false;
285 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char *>(name), png_my_error, png_my_warning);
287 if (png_ptr == NULL) {
288 fclose(f);
289 return false;
292 info_ptr = png_create_info_struct(png_ptr);
293 if (info_ptr == NULL) {
294 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
295 fclose(f);
296 return false;
299 if (setjmp(png_jmpbuf(png_ptr))) {
300 png_destroy_write_struct(&png_ptr, &info_ptr);
301 fclose(f);
302 return false;
305 png_init_io(png_ptr, f);
307 png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
309 png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
310 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
312 #ifdef PNG_TEXT_SUPPORTED
313 /* Try to add some game metadata to the PNG screenshot so
314 * it's more useful for debugging and archival purposes. */
315 png_text_struct text[2];
316 memset(text, 0, sizeof(text));
317 text[0].key = const_cast<char *>("Software");
318 text[0].text = const_cast<char *>(_openttd_revision);
319 text[0].text_length = strlen(_openttd_revision);
320 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
322 char buf[8192];
323 char *p = buf;
324 p += seprintf(p, lastof(buf), "Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->name, BaseGraphics::GetUsedSet()->version);
325 p = strecpy(p, "NewGRFs:\n", lastof(buf));
326 for (const GRFConfig *c = _game_mode == GM_MENU ? NULL : _grfconfig; c != NULL; c = c->next) {
327 p += seprintf(p, lastof(buf), "%08X ", BSWAP32(c->ident.grfid));
328 p = md5sumToString(p, lastof(buf), c->ident.md5sum);
329 p += seprintf(p, lastof(buf), " %s\n", c->filename);
331 p = strecpy(p, "\nCompanies:\n", lastof(buf));
332 const Company *c;
333 FOR_ALL_COMPANIES(c) {
334 if (c->ai_info == NULL) {
335 p += seprintf(p, lastof(buf), "%2i: Human\n", (int)c->index);
336 } else {
337 p += seprintf(p, lastof(buf), "%2i: %s (v%d)\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
340 text[1].key = const_cast<char *>("Description");
341 text[1].text = buf;
342 text[1].text_length = p - buf;
343 text[1].compression = PNG_TEXT_COMPRESSION_zTXt;
344 png_set_text(png_ptr, info_ptr, text, 2);
345 #endif /* PNG_TEXT_SUPPORTED */
347 if (pixelformat == 8) {
348 /* convert the palette to the .PNG format. */
349 for (i = 0; i != 256; i++) {
350 rq[i].red = palette[i].r;
351 rq[i].green = palette[i].g;
352 rq[i].blue = palette[i].b;
355 png_set_PLTE(png_ptr, info_ptr, rq, 256);
358 png_write_info(png_ptr, info_ptr);
359 png_set_flush(png_ptr, 512);
361 if (pixelformat == 32) {
362 png_color_8 sig_bit;
364 /* Save exact colour/alpha resolution */
365 sig_bit.alpha = 0;
366 sig_bit.blue = 8;
367 sig_bit.green = 8;
368 sig_bit.red = 8;
369 sig_bit.gray = 8;
370 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
372 #if TTD_ENDIAN == TTD_LITTLE_ENDIAN
373 png_set_bgr(png_ptr);
374 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
375 #else
376 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
377 #endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
380 /* use by default 64k temp memory */
381 maxlines = Clamp(65536 / w, 16, 128);
383 /* now generate the bitmap bits */
384 void *buff = CallocT<uint8>(w * maxlines * bpp); // by default generate 128 lines at a time.
386 y = 0;
387 do {
388 /* determine # lines to write */
389 n = min(h - y, maxlines);
391 /* render the pixels into the buffer */
392 callb(userdata, buff, y, w, n);
393 y += n;
395 /* write them to png */
396 for (i = 0; i != n; i++) {
397 png_write_row(png_ptr, (png_bytep)buff + i * w * bpp);
399 } while (y != h);
401 png_write_end(png_ptr, info_ptr);
402 png_destroy_write_struct(&png_ptr, &info_ptr);
404 free(buff);
405 fclose(f);
406 return true;
408 #endif /* WITH_PNG */
411 /*************************************************
412 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
413 *************************************************/
415 /** Definition of a PCX file header. */
416 struct PcxHeader {
417 byte manufacturer;
418 byte version;
419 byte rle;
420 byte bpp;
421 uint32 unused;
422 uint16 xmax, ymax;
423 uint16 hdpi, vdpi;
424 byte pal_small[16 * 3];
425 byte reserved;
426 byte planes;
427 uint16 pitch;
428 uint16 cpal;
429 uint16 width;
430 uint16 height;
431 byte filler[54];
433 assert_compile(sizeof(PcxHeader) == 128);
436 * Generic .PCX file image writer.
437 * @param name Filename, including extension.
438 * @param callb Callback function for generating lines of pixels.
439 * @param userdata User data, passed on to \a callb.
440 * @param w Width of the image in pixels.
441 * @param h Height of the image in pixels.
442 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
443 * @param palette %Colour palette (for 8bpp images).
444 * @return File was written successfully.
445 * @see ScreenshotHandlerProc
447 static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
449 FILE *f;
450 uint maxlines;
451 uint y;
452 PcxHeader pcx;
453 bool success;
455 if (pixelformat == 32) {
456 DEBUG(misc, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
457 return false;
459 if (pixelformat != 8 || w == 0) return false;
461 f = fopen(name, "wb");
462 if (f == NULL) return false;
464 memset(&pcx, 0, sizeof(pcx));
466 /* setup pcx header */
467 pcx.manufacturer = 10;
468 pcx.version = 5;
469 pcx.rle = 1;
470 pcx.bpp = 8;
471 pcx.xmax = TO_LE16(w - 1);
472 pcx.ymax = TO_LE16(h - 1);
473 pcx.hdpi = TO_LE16(320);
474 pcx.vdpi = TO_LE16(320);
476 pcx.planes = 1;
477 pcx.cpal = TO_LE16(1);
478 pcx.width = pcx.pitch = TO_LE16(w);
479 pcx.height = TO_LE16(h);
481 /* write pcx header */
482 if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
483 fclose(f);
484 return false;
487 /* use by default 64k temp memory */
488 maxlines = Clamp(65536 / w, 16, 128);
490 /* now generate the bitmap bits */
491 uint8 *buff = CallocT<uint8>(w * maxlines); // by default generate 128 lines at a time.
493 y = 0;
494 do {
495 /* determine # lines to write */
496 uint n = min(h - y, maxlines);
497 uint i;
499 /* render the pixels into the buffer */
500 callb(userdata, buff, y, w, n);
501 y += n;
503 /* write them to pcx */
504 for (i = 0; i != n; i++) {
505 const uint8 *bufp = buff + i * w;
506 byte runchar = bufp[0];
507 uint runcount = 1;
508 uint j;
510 /* for each pixel... */
511 for (j = 1; j < w; j++) {
512 uint8 ch = bufp[j];
514 if (ch != runchar || runcount >= 0x3f) {
515 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
516 if (fputc(0xC0 | runcount, f) == EOF) {
517 free(buff);
518 fclose(f);
519 return false;
522 if (fputc(runchar, f) == EOF) {
523 free(buff);
524 fclose(f);
525 return false;
527 runcount = 0;
528 runchar = ch;
530 runcount++;
533 /* write remaining bytes.. */
534 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
535 if (fputc(0xC0 | runcount, f) == EOF) {
536 free(buff);
537 fclose(f);
538 return false;
541 if (fputc(runchar, f) == EOF) {
542 free(buff);
543 fclose(f);
544 return false;
547 } while (y != h);
549 free(buff);
551 /* write 8-bit colour palette */
552 if (fputc(12, f) == EOF) {
553 fclose(f);
554 return false;
557 /* Palette is word-aligned, copy it to a temporary byte array */
558 byte tmp[256 * 3];
560 for (uint i = 0; i < 256; i++) {
561 tmp[i * 3 + 0] = palette[i].r;
562 tmp[i * 3 + 1] = palette[i].g;
563 tmp[i * 3 + 2] = palette[i].b;
565 success = fwrite(tmp, sizeof(tmp), 1, f) == 1;
567 fclose(f);
569 return success;
572 /*************************************************
573 **** GENERIC SCREENSHOT CODE
574 *************************************************/
576 /** Available screenshot formats. */
577 static const ScreenshotFormat _screenshot_formats[] = {
578 #if defined(WITH_PNG)
579 {"png", &MakePNGImage},
580 #endif
581 {"bmp", &MakeBMPImage},
582 {"pcx", &MakePCXImage},
585 /** Get filename extension of current screenshot file format. */
586 const char *GetCurrentScreenshotExtension()
588 return _screenshot_formats[_cur_screenshot_format].extension;
591 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
592 void InitializeScreenshotFormats()
594 uint j = 0;
595 for (uint i = 0; i < lengthof(_screenshot_formats); i++) {
596 if (!strcmp(_screenshot_format_name, _screenshot_formats[i].extension)) {
597 j = i;
598 break;
601 _cur_screenshot_format = j;
602 _num_screenshot_formats = lengthof(_screenshot_formats);
606 * Callback of the screenshot generator that dumps the current video buffer.
607 * @see ScreenshotCallback
609 static void CurrentScreenCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
611 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
612 void *src = blitter->MoveTo(_screen.dst_ptr, 0, y);
613 blitter->CopyImageToBuffer(src, buf, _screen.width, n, pitch);
617 * generate a large piece of the world
618 * @param userdata Viewport area to draw
619 * @param buf Videobuffer with same bitdepth as current blitter
620 * @param y First line to render
621 * @param pitch Pitch of the videobuffer
622 * @param n Number of lines to render
624 static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
626 ViewPort *vp = (ViewPort *)userdata;
627 DrawPixelInfo dpi, *old_dpi;
628 int wx, left;
630 /* We are no longer rendering to the screen */
631 DrawPixelInfo old_screen = _screen;
632 bool old_disable_anim = _screen_disable_anim;
634 _screen.dst_ptr = buf;
635 _screen.width = pitch;
636 _screen.height = n;
637 _screen.pitch = pitch;
638 _screen_disable_anim = true;
640 old_dpi = _cur_dpi;
641 _cur_dpi = &dpi;
643 dpi.dst_ptr = buf;
644 dpi.height = n;
645 dpi.width = vp->width;
646 dpi.pitch = pitch;
647 dpi.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
648 dpi.left = 0;
649 dpi.top = y;
651 /* Render viewport in blocks of 1600 pixels width */
652 left = 0;
653 while (vp->width - left != 0) {
654 wx = min(vp->width - left, 1600);
655 left += wx;
657 ViewportDoDraw(vp,
658 ScaleByZoom(left - wx - vp->left, vp->zoom) + vp->virtual_left,
659 ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top,
660 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
661 ScaleByZoom((y + n) - vp->top, vp->zoom) + vp->virtual_top
665 _cur_dpi = old_dpi;
667 /* Switch back to rendering to the screen */
668 _screen = old_screen;
669 _screen_disable_anim = old_disable_anim;
673 * Construct a pathname for a screenshot file.
674 * @param default_fn Default filename.
675 * @param ext Extension to use.
676 * @param crashlog Create path for crash.png
677 * @return Pathname for a screenshot file.
679 static const char *MakeScreenshotName(const char *default_fn, const char *ext, bool crashlog = false)
681 bool generate = StrEmpty(_screenshot_name);
683 if (generate) {
684 if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
685 strecpy(_screenshot_name, default_fn, lastof(_screenshot_name));
686 } else {
687 GenerateDefaultSaveName(_screenshot_name, lastof(_screenshot_name));
691 /* Add extension to screenshot file */
692 size_t len = strlen(_screenshot_name);
693 seprintf(&_screenshot_name[len], lastof(_screenshot_name), ".%s", ext);
695 const char *screenshot_dir = crashlog ? _personal_dir : FiosGetScreenshotDir();
697 for (uint serial = 1;; serial++) {
698 if (seprintf(_full_screenshot_name, lastof(_full_screenshot_name), "%s%s", screenshot_dir, _screenshot_name) >= (int)lengthof(_full_screenshot_name)) {
699 /* We need more characters than MAX_PATH -> end with error */
700 _full_screenshot_name[0] = '\0';
701 break;
703 if (!generate) break; // allow overwriting of non-automatic filenames
704 if (!FileExists(_full_screenshot_name)) break;
705 /* If file exists try another one with same name, but just with a higher index */
706 seprintf(&_screenshot_name[len], lastof(_screenshot_name) - len, "#%u.%s", serial, ext);
709 return _full_screenshot_name;
712 /** Make a screenshot of the current screen. */
713 static bool MakeSmallScreenshot(bool crashlog)
715 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
716 return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension, crashlog), CurrentScreenCallback, NULL, _screen.width, _screen.height,
717 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
721 * Configure a ViewPort for rendering (a part of) the map into a screenshot.
722 * @param t Screenshot type
723 * @param [out] vp Result viewport
725 void SetupScreenshotViewport(ScreenshotType t, ViewPort *vp)
727 /* Determine world coordinates of screenshot */
728 if (t == SC_WORLD) {
729 vp->zoom = ZOOM_LVL_WORLD_SCREENSHOT;
731 TileIndex north_tile = _settings_game.construction.freeform_edges ? TileXY(1, 1) : TileXY(0, 0);
732 TileIndex south_tile = MapSize() - 1;
734 /* We need to account for a hill or high building at tile 0,0. */
735 int extra_height_top = TilePixelHeight(north_tile) + 150;
736 /* If there is a hill at the bottom don't create a large black area. */
737 int reclaim_height_bottom = TilePixelHeight(south_tile);
739 vp->virtual_left = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, 0).x;
740 vp->virtual_top = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, extra_height_top).y;
741 vp->virtual_width = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, 0).x - vp->virtual_left + 1;
742 vp->virtual_height = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, reclaim_height_bottom).y - vp->virtual_top + 1;
743 } else {
744 vp->zoom = (t == SC_ZOOMEDIN) ? _settings_client.gui.zoom_min : ZOOM_LVL_VIEWPORT;
746 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
747 vp->virtual_left = w->viewport->virtual_left;
748 vp->virtual_top = w->viewport->virtual_top;
749 vp->virtual_width = w->viewport->virtual_width;
750 vp->virtual_height = w->viewport->virtual_height;
753 /* Compute pixel coordinates */
754 vp->left = 0;
755 vp->top = 0;
756 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
757 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
758 vp->overlay = NULL;
762 * Make a screenshot of the map.
763 * @param t Screenshot type: World or viewport screenshot
764 * @return true on success
766 static bool MakeLargeWorldScreenshot(ScreenshotType t)
768 ViewPort vp;
769 SetupScreenshotViewport(t, &vp);
771 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
772 return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension), LargeWorldCallback, &vp, vp.width, vp.height,
773 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
777 * Callback for generating a heightmap. Supports 8bpp grayscale only.
778 * @param userdata Pointer to user data.
779 * @param buf Destination buffer.
780 * @param y Line number of the first line to write.
781 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
782 * @param n Number of lines to write.
783 * @see ScreenshotCallback
785 static void HeightmapCallback(void *userdata, void *buffer, uint y, uint pitch, uint n)
787 byte *buf = (byte *)buffer;
788 while (n > 0) {
789 TileIndex ti = TileXY(MapMaxX(), y);
790 for (uint x = MapMaxX(); true; x--) {
791 *buf = 256 * TileHeight(ti) / (1 + _settings_game.construction.max_heightlevel);
792 buf++;
793 if (x == 0) break;
794 ti = TILE_ADDXY(ti, -1, 0);
796 y++;
797 n--;
802 * Make a heightmap of the current map.
803 * @param filename Filename to use for saving.
805 bool MakeHeightmapScreenshot(const char *filename)
807 Colour palette[256];
808 for (uint i = 0; i < lengthof(palette); i++) {
809 palette[i].a = 0xff;
810 palette[i].r = i;
811 palette[i].g = i;
812 palette[i].b = i;
814 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
815 return sf->proc(filename, HeightmapCallback, NULL, MapSizeX(), MapSizeY(), 8, palette);
819 * Show a a success or failure message indicating the result of a screenshot action
820 * @param ret whether the screenshot action was successful
822 static void ShowScreenshotResultMessage(bool ret)
824 if (ret) {
825 SetDParamStr(0, _screenshot_name);
826 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY, INVALID_STRING_ID, WL_WARNING);
827 } else {
828 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED, INVALID_STRING_ID, WL_ERROR);
833 * Return the colour a tile would be displayed with in the small map in mode "Owner".
835 * @param tile The tile of which we would like to get the colour.
836 * @param type The type of screenshot to create tile colors for.
837 * @return The colour of tile in the small map in mode "Owner"
839 static inline byte GetMinimapPixels(TileIndex tile, ScreenshotType type)
841 auto t = GetTileType(tile);
843 switch (type) {
844 case SC_MINIMAP: {
845 if (t == MP_STATION) {
846 switch (GetStationType(tile)) {
847 case STATION_RAIL: return MKCOLOUR(PC_LIGHT_BLUE);
848 case STATION_AIRPORT: return MKCOLOUR(0xCF);
849 case STATION_TRUCK: return MKCOLOUR(PC_ORANGE);
850 case STATION_BUS: return MKCOLOUR(PC_YELLOW);
851 case STATION_OILRIG: // FALLTHROUGH
852 case STATION_DOCK: return MKCOLOUR(PC_WHITE);
853 case STATION_BUOY: return MKCOLOUR(PC_WATER);
854 case STATION_WAYPOINT: return MKCOLOUR(PC_GREY);
855 default: NOT_REACHED();
859 if (IsBridgeAbove(tile)) {
860 return MKCOLOUR(PC_DARK_GREY);
863 switch (t) {
864 case MP_TUNNELBRIDGE: return MKCOLOUR(PC_DARK_GREY);
865 case MP_RAILWAY: return MKCOLOUR(PC_GREY);
866 case MP_ROAD: return MKCOLOUR(PC_BLACK);
867 case MP_HOUSE: return MKCOLOUR(0xB5);
868 case MP_WATER: return MKCOLOUR(PC_WATER);
869 case MP_INDUSTRY: return MKCOLOUR(0xA2);
870 default: return MKCOLOUR(0x51);
872 break;
875 case SC_MINI_HEIGHTMAP: {
876 if (t == MP_STATION) {
877 switch (GetStationType(tile)) {
878 case STATION_RAIL: return MKCOLOUR(PC_GREY);
879 case STATION_AIRPORT: return MKCOLOUR(PC_GREY);
880 case STATION_TRUCK: return MKCOLOUR(PC_BLACK);
881 case STATION_BUS: return MKCOLOUR(PC_BLACK);
882 case STATION_OILRIG: // FALLTHROUGH
883 case STATION_DOCK: return MKCOLOUR(PC_GREY);
884 case STATION_BUOY: return MKCOLOUR(PC_WATER);
885 case STATION_WAYPOINT: return MKCOLOUR(PC_GREY);
886 default: NOT_REACHED();
890 if (IsBridgeAbove(tile)) {
891 return MKCOLOUR(PC_DARK_GREY);
894 switch (t) {
895 case MP_TUNNELBRIDGE: return MKCOLOUR(PC_DARK_GREY);
896 case MP_RAILWAY: return MKCOLOUR(PC_GREY);
897 case MP_ROAD: return MKCOLOUR(PC_BLACK);
898 case MP_HOUSE: return MKCOLOUR(0xB5);
899 case MP_WATER: return MKCOLOUR(PC_WATER);
900 case MP_INDUSTRY: return MKCOLOUR(0xA2);
901 default:
903 auto tile_z = GetTileZ(tile);
904 auto max_z = _settings_game.construction.max_heightlevel;
906 auto color_index = (tile_z * 16) / max_z;
908 switch (color_index) {
909 case 0: return MKCOLOUR(0x50);
910 case 1: return MKCOLOUR(0x51);
911 case 2: return MKCOLOUR(0x52);
912 case 3: return MKCOLOUR(0x53);
913 case 4: return MKCOLOUR(0x54);
914 case 5: return MKCOLOUR(0x55);
915 case 6: return MKCOLOUR(0x56);
916 case 7: return MKCOLOUR(0x57);
917 case 8: return MKCOLOUR(0x3B);
918 case 9: return MKCOLOUR(0x3A);
919 case 10: return MKCOLOUR(0x39);
920 case 11: return MKCOLOUR(0x38);
921 case 12: return MKCOLOUR(0x37);
922 case 13: return MKCOLOUR(0x36);
923 case 14: return MKCOLOUR(0x35);
924 case 15: return MKCOLOUR(0x69);
925 default: return MKCOLOUR(0x46);
927 break;
930 break;
933 case SC_MINI_INDUSTRYMAP: {
934 if (t == MP_STATION) {
935 switch (GetStationType(tile)) {
936 case STATION_RAIL: return MKCOLOUR(PC_DARK_GREY);
937 case STATION_AIRPORT: return MKCOLOUR(GREY_SCALE(12));
938 case STATION_TRUCK: return MKCOLOUR(PC_GREY);
939 case STATION_BUS: return MKCOLOUR(PC_GREY);
940 case STATION_OILRIG: // FALLTHROUGH
941 case STATION_DOCK: return MKCOLOUR(PC_GREY);
942 case STATION_BUOY: return MKCOLOUR(PC_BLACK);
943 case STATION_WAYPOINT: return MKCOLOUR(PC_GREY);
944 default: NOT_REACHED();
948 if (IsBridgeAbove(tile)) {
949 return MKCOLOUR(GREY_SCALE(12));
952 switch (t) {
953 case MP_TUNNELBRIDGE: return MKCOLOUR(GREY_SCALE(12));
954 case MP_RAILWAY: return MKCOLOUR(PC_DARK_GREY);
955 case MP_ROAD: return MKCOLOUR(PC_GREY);
956 case MP_HOUSE: return MKCOLOUR(GREY_SCALE(4));
957 case MP_WATER: return MKCOLOUR(0x12);
958 case MP_INDUSTRY:
960 IndustryType type = Industry::GetByTile(tile)->type;
962 return GetIndustrySpec(type)->map_colour * 0x01010101;
964 default: return MKCOLOUR(GREY_SCALE(2));
966 break;
969 case SC_MINI_OWNERMAP: {
970 if (IsBridgeAbove(tile)) return MKCOLOUR(PC_DARK_GREY);
972 /* setup owner table */
973 const Company *c;
974 uint32 _owner_colours[OWNER_END + 1];
976 /* fill with some special colours */
977 _owner_colours[OWNER_TOWN] = MKCOLOUR(0x00994433);
978 _owner_colours[OWNER_NONE] = MKCOLOUR(0x54545454);
979 _owner_colours[OWNER_WATER] = MKCOLOUR(0x00000066);
980 _owner_colours[OWNER_END] = MKCOLOUR(0x20202020); // industry
982 /* now fill with the company colours */
983 FOR_ALL_COMPANIES(c) {
984 _owner_colours[c->index] =
985 _colour_gradient[c->colour][5];
988 Owner o = GetTileOwner(tile);
990 switch (GetTileType(tile)) {
991 case MP_HOUSE: return MKCOLOUR(GREY_SCALE(12));
992 case MP_INDUSTRY: return MKCOLOUR(PC_GREY);
994 case MP_RAILWAY: return _owner_colours[GetTileOwner(tile)];
996 case MP_STATION:
998 Owner o = GetTileOwner(tile);
1000 if (o == OWNER_TOWN || o == OWNER_NONE || o == OWNER_DEITY)
1002 return MKCOLOUR(PC_DARK_GREY);
1004 else
1006 return _owner_colours[GetTileOwner(tile)];
1010 case MP_ROAD:
1012 Owner o = GetTileOwner(tile);
1014 if (o == OWNER_TOWN || o == OWNER_NONE || o == OWNER_DEITY)
1016 return MKCOLOUR(PC_DARK_GREY);
1018 else
1020 return _owner_colours[GetTileOwner(tile)];
1024 case MP_TUNNELBRIDGE:
1026 Owner o = GetTileOwner(tile);
1028 if (o == OWNER_TOWN || o == OWNER_NONE || o == OWNER_DEITY)
1030 return MKCOLOUR(PC_DARK_GREY);
1032 else
1034 return _owner_colours[GetTileOwner(tile)];
1038 case MP_OBJECT: // FALLTHROUGH
1039 case MP_CLEAR: // FALLTHROUGH
1040 case MP_TREES: return MKCOLOUR(GREY_SCALE(2));
1041 case MP_WATER: return MKCOLOUR(0x12);
1042 case MP_VOID: return MKCOLOUR(PC_BLACK);
1043 default: NOT_REACHED();
1047 default:
1048 NOT_REACHED();
1052 static void MinimapCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
1054 ScreenshotType type = *(ScreenshotType*)userdata;
1055 uint8 *ubuf = (uint8 *)buf;
1057 uint num = (pitch * n);
1058 uint row, col;
1059 byte val;
1061 for (uint i = 0; i < num; i++) {
1062 row = y + (int)(i / pitch);
1063 col = (MapSizeX() - 1) - (i % pitch);
1065 TileIndex tile = TileXY(col, row);
1067 if (IsTileType(tile, MP_VOID)) {
1068 val = 0x00;
1070 else {
1071 val = GetMinimapPixels(tile, type);
1074 *ubuf = (uint8)_cur_palette.palette[val].b;
1075 ubuf += sizeof(uint8); *ubuf = (uint8)_cur_palette.palette[val].g;
1076 ubuf += sizeof(uint8); *ubuf = (uint8)_cur_palette.palette[val].r;
1077 ubuf += sizeof(uint8);
1078 ubuf += sizeof(uint8);
1083 * Saves the complete savemap in a PNG-file.
1085 static bool MakeFlatMinimapScreenshot(ScreenshotType screenshotType)
1087 _screenshot_name[0] = '\0';
1089 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
1090 return sf->proc(MakeScreenshotName("minimap", sf->extension), MinimapCallback, &screenshotType, MapSizeX(), MapSizeY(), 32, _cur_palette.palette);
1094 * Make an actual screenshot.
1095 * @param t the type of screenshot to make.
1096 * @param name the name to give to the screenshot.
1097 * @return true iff the screenshot was made successfully
1099 bool MakeScreenshot(ScreenshotType t, const char *name)
1101 if (t == SC_VIEWPORT) {
1102 /* First draw the dirty parts of the screen and only then change the name
1103 * of the screenshot. This way the screenshot will always show the name
1104 * of the previous screenshot in the 'successful' message instead of the
1105 * name of the new screenshot (or an empty name). */
1106 UndrawMouseCursor();
1107 DrawDirtyBlocks();
1110 _screenshot_name[0] = '\0';
1111 if (name != NULL) strecpy(_screenshot_name, name, lastof(_screenshot_name));
1113 bool ret;
1114 switch (t) {
1115 case SC_VIEWPORT:
1116 ret = MakeSmallScreenshot(false);
1117 break;
1119 case SC_CRASHLOG:
1120 ret = MakeSmallScreenshot(true);
1121 break;
1123 case SC_ZOOMEDIN:
1124 case SC_DEFAULTZOOM:
1125 case SC_WORLD:
1126 ret = MakeLargeWorldScreenshot(t);
1127 break;
1129 case SC_HEIGHTMAP: {
1130 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
1131 ret = MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME, sf->extension));
1132 break;
1135 case SC_MINIMAP: {
1136 ret = MakeFlatMinimapScreenshot(SC_MINIMAP);
1137 break;
1140 case SC_MINI_HEIGHTMAP: {
1141 ret = MakeFlatMinimapScreenshot(SC_MINI_HEIGHTMAP);
1142 break;
1145 case SC_MINI_INDUSTRYMAP: {
1146 ret = MakeFlatMinimapScreenshot(SC_MINI_INDUSTRYMAP);
1147 break;
1150 case SC_MINI_OWNERMAP: {
1151 ret = MakeFlatMinimapScreenshot(SC_MINI_OWNERMAP);
1152 break;
1155 default:
1156 NOT_REACHED();
1159 ShowScreenshotResultMessage(ret);
1161 return ret;
1165 * Callback for generating a smallmap screenshot.
1166 * @param userdata SmallMapWindow window pointer
1167 * @param buf Videobuffer with same bitdepth as current blitter
1168 * @param y First line to render
1169 * @param pitch Pitch of the videobuffer
1170 * @param n Number of lines to render
1172 static void SmallMapCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
1174 SmallMapWindow *window = static_cast<SmallMapWindow *>(userdata);
1175 window->ScreenshotCallbackHandler(buf, y, pitch, n);
1179 * Make a screenshot of the smallmap
1180 * @param width the width of the screenshot
1181 * @param height the height of the screenshot
1182 * @param window a pointer to the smallmap window to use, the current mode and zoom status of the window is used for the screenshot
1183 * @return true iff the screenshot was made successfully
1185 bool MakeSmallMapScreenshot(unsigned int width, unsigned int height, SmallMapWindow *window)
1187 _screenshot_name[0] = '\0';
1188 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
1189 bool ret = sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension), SmallMapCallback, window, width, height, BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
1190 ShowScreenshotResultMessage(ret);
1191 return ret;