Silence uninitialised variable warnings in SSE blitters
[openttd/fttd.git] / src / screenshot.cpp
blob0a9c27a09a95404bcffdb1e36e4630a65efe03ea
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 "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 "map/zoneheight.h"
27 #include "landscape.h"
29 #include "table/strings.h"
31 static const char * const SCREENSHOT_NAME = "screenshot"; ///< Default filename of a saved screenshot.
32 static const char * const HEIGHTMAP_NAME = "heightmap"; ///< Default filename of a saved heightmap.
34 char _screenshot_format_name[8]; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
35 uint _num_screenshot_formats; ///< Number of available screenshot formats.
36 uint _cur_screenshot_format; ///< Index of the currently selected screenshot format in #_screenshot_formats.
37 static char _screenshot_name[128]; ///< Filename of the screenshot file.
38 char _full_screenshot_name[MAX_PATH]; ///< Pathname of the screenshot file.
40 /**
41 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
42 * @param userdata Pointer to user data.
43 * @param buf Destination buffer.
44 * @param y Line number of the first line to write.
45 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
46 * @param n Number of lines to write.
48 typedef void ScreenshotCallback(void *userdata, void *buf, uint y, uint pitch, uint n);
50 /**
51 * Function signature for a screenshot generation routine for one of the available formats.
52 * @param name Filename, including extension.
53 * @param callb Callback function for generating lines of pixels.
54 * @param userdata User data, passed on to \a callb.
55 * @param w Width of the image in pixels.
56 * @param h Height of the image in pixels.
57 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
58 * @param palette %Colour palette (for 8bpp images).
59 * @return File was written successfully.
61 typedef bool ScreenshotHandlerProc(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette);
63 /** Screenshot format information. */
64 struct ScreenshotFormat {
65 const char *name; ///< Name of the format.
66 const char *extension; ///< File extension.
67 ScreenshotHandlerProc *proc; ///< Function for writing the screenshot.
68 bool supports_32bpp; ///< Does this format support 32bpp images?
71 /*************************************************
72 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
73 *************************************************/
74 #if defined(_MSC_VER) || defined(__WATCOMC__)
75 #pragma pack(push, 1)
76 #endif
78 /** BMP File Header (stored in little endian) */
79 struct BitmapFileHeader {
80 uint16 type;
81 uint32 size;
82 uint32 reserved;
83 uint32 off_bits;
84 } GCC_PACK;
85 assert_compile(sizeof(BitmapFileHeader) == 14);
87 #if defined(_MSC_VER) || defined(__WATCOMC__)
88 #pragma pack(pop)
89 #endif
91 /** BMP Info Header (stored in little endian) */
92 struct BitmapInfoHeader {
93 uint32 size;
94 int32 width, height;
95 uint16 planes, bitcount;
96 uint32 compression, sizeimage, xpels, ypels, clrused, clrimp;
98 assert_compile(sizeof(BitmapInfoHeader) == 40);
100 /** Format of palette data in BMP header */
101 struct RgbQuad {
102 byte blue, green, red, reserved;
104 assert_compile(sizeof(RgbQuad) == 4);
107 * Generic .BMP writer
108 * @param name file name including extension
109 * @param callb callback used for gathering rendered image
110 * @param userdata parameters forwarded to \a callb
111 * @param w width in pixels
112 * @param h height in pixels
113 * @param pixelformat bits per pixel
114 * @param palette colour palette (for 8bpp mode)
115 * @return was everything ok?
116 * @see ScreenshotHandlerProc
118 static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
120 uint bpp; // bytes per pixel
121 switch (pixelformat) {
122 case 8: bpp = 1; break;
123 /* 32bpp mode is saved as 24bpp BMP */
124 case 32: bpp = 3; break;
125 /* Only implemented for 8bit and 32bit images so far */
126 default: return false;
129 FILE *f = fopen(name, "wb");
130 if (f == NULL) return false;
132 /* Each scanline must be aligned on a 32bit boundary */
133 uint bytewidth = Align(w * bpp, 4); // bytes per line in file
135 /* Size of palette. Only present for 8bpp mode */
136 uint pal_size = pixelformat == 8 ? sizeof(RgbQuad) * 256 : 0;
138 /* Setup the file header */
139 BitmapFileHeader bfh;
140 bfh.type = TO_LE16('MB');
141 bfh.size = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size + bytewidth * h);
142 bfh.reserved = 0;
143 bfh.off_bits = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size);
145 /* Setup the info header */
146 BitmapInfoHeader bih;
147 bih.size = TO_LE32(sizeof(BitmapInfoHeader));
148 bih.width = TO_LE32(w);
149 bih.height = TO_LE32(h);
150 bih.planes = TO_LE16(1);
151 bih.bitcount = TO_LE16(bpp * 8);
152 bih.compression = 0;
153 bih.sizeimage = 0;
154 bih.xpels = 0;
155 bih.ypels = 0;
156 bih.clrused = 0;
157 bih.clrimp = 0;
159 /* Write file header and info header */
160 if (fwrite(&bfh, sizeof(bfh), 1, f) != 1 || fwrite(&bih, sizeof(bih), 1, f) != 1) {
161 fclose(f);
162 return false;
165 if (pixelformat == 8) {
166 /* Convert the palette to the windows format */
167 RgbQuad rq[256];
168 for (uint i = 0; i < 256; i++) {
169 rq[i].red = palette[i].r;
170 rq[i].green = palette[i].g;
171 rq[i].blue = palette[i].b;
172 rq[i].reserved = 0;
174 /* Write the palette */
175 if (fwrite(rq, sizeof(rq), 1, f) != 1) {
176 fclose(f);
177 return false;
181 /* Try to use 64k of memory, store between 16 and 128 lines */
182 uint maxlines = Clamp(65536 / (w * pixelformat / 8), 16, 128); // number of lines per iteration
184 uint8 *buff = MallocT<uint8>(maxlines * w * pixelformat / 8); // buffer which is rendered to
185 uint8 *line = AllocaM(uint8, bytewidth); // one line, stored to file
186 memset(line, 0, bytewidth);
188 /* Start at the bottom, since bitmaps are stored bottom up */
189 do {
190 uint n = min(h, maxlines);
191 h -= n;
193 /* Render the pixels */
194 callb(userdata, buff, h, w, n);
196 /* Write each line */
197 while (n-- != 0) {
198 if (pixelformat == 8) {
199 /* Move to 'line', leave last few pixels in line zeroed */
200 memcpy(line, buff + n * w, w);
201 } else {
202 /* Convert from 'native' 32bpp to BMP-like 24bpp.
203 * Works for both big and little endian machines */
204 Colour *src = ((Colour *)buff) + n * w;
205 byte *dst = line;
206 for (uint i = 0; i < w; i++) {
207 dst[i * 3 ] = src[i].b;
208 dst[i * 3 + 1] = src[i].g;
209 dst[i * 3 + 2] = src[i].r;
212 /* Write to file */
213 if (fwrite(line, bytewidth, 1, f) != 1) {
214 free(buff);
215 fclose(f);
216 return false;
219 } while (h != 0);
221 free(buff);
222 fclose(f);
224 return true;
227 /*********************************************************
228 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
229 *********************************************************/
230 #if defined(WITH_PNG)
231 #include <png.h>
233 #ifdef PNG_TEXT_SUPPORTED
234 #include "rev.h"
235 #include "newgrf_config.h"
236 #include "ai/ai_info.hpp"
237 #include "company_base.h"
238 #include "base_media_base.h"
239 #endif /* PNG_TEXT_SUPPORTED */
241 static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
243 DEBUG(misc, 0, "[libpng] error: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
244 longjmp(png_jmpbuf(png_ptr), 1);
247 static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
249 DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (const char *)png_get_error_ptr(png_ptr));
253 * Generic .PNG file image writer.
254 * @param name Filename, including extension.
255 * @param callb Callback function for generating lines of pixels.
256 * @param userdata User data, passed on to \a callb.
257 * @param w Width of the image in pixels.
258 * @param h Height of the image in pixels.
259 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
260 * @param palette %Colour palette (for 8bpp images).
261 * @return File was written successfully.
262 * @see ScreenshotHandlerProc
264 static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
266 png_color rq[256];
267 FILE *f;
268 uint i, y, n;
269 uint maxlines;
270 uint bpp = pixelformat / 8;
271 png_structp png_ptr;
272 png_infop info_ptr;
274 /* only implemented for 8bit and 32bit images so far. */
275 if (pixelformat != 8 && pixelformat != 32) return false;
277 f = fopen(name, "wb");
278 if (f == NULL) return false;
280 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char *>(name), png_my_error, png_my_warning);
282 if (png_ptr == NULL) {
283 fclose(f);
284 return false;
287 info_ptr = png_create_info_struct(png_ptr);
288 if (info_ptr == NULL) {
289 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
290 fclose(f);
291 return false;
294 if (setjmp(png_jmpbuf(png_ptr))) {
295 png_destroy_write_struct(&png_ptr, &info_ptr);
296 fclose(f);
297 return false;
300 png_init_io(png_ptr, f);
302 png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
304 png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
305 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
307 #ifdef PNG_TEXT_SUPPORTED
308 /* Try to add some game metadata to the PNG screenshot so
309 * it's more useful for debugging and archival purposes. */
310 png_text_struct text[2];
311 memset(text, 0, sizeof(text));
312 text[0].key = const_cast<char *>("Software");
313 text[0].text = const_cast<char *>(_openttd_revision);
314 text[0].text_length = strlen(_openttd_revision);
315 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
317 char buf[8192];
318 char *p = buf;
319 p += seprintf(p, lastof(buf), "Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->name, BaseGraphics::GetUsedSet()->version);
320 p = strecpy(p, "NewGRFs:\n", lastof(buf));
321 for (const GRFConfig *c = _game_mode == GM_MENU ? NULL : _grfconfig; c != NULL; c = c->next) {
322 p += seprintf(p, lastof(buf), "%08X ", BSWAP32(c->ident.grfid));
323 p = md5sumToString(p, lastof(buf), c->ident.md5sum);
324 p += seprintf(p, lastof(buf), " %s\n", c->filename);
326 p = strecpy(p, "\nCompanies:\n", lastof(buf));
327 const Company *c;
328 FOR_ALL_COMPANIES(c) {
329 if (c->ai_info == NULL) {
330 p += seprintf(p, lastof(buf), "%2i: Human\n", (int)c->index);
331 } else {
332 p += seprintf(p, lastof(buf), "%2i: %s (v%d)\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
335 text[1].key = const_cast<char *>("Description");
336 text[1].text = buf;
337 text[1].text_length = p - buf;
338 text[1].compression = PNG_TEXT_COMPRESSION_zTXt;
339 png_set_text(png_ptr, info_ptr, text, 2);
340 #endif /* PNG_TEXT_SUPPORTED */
342 if (pixelformat == 8) {
343 /* convert the palette to the .PNG format. */
344 for (i = 0; i != 256; i++) {
345 rq[i].red = palette[i].r;
346 rq[i].green = palette[i].g;
347 rq[i].blue = palette[i].b;
350 png_set_PLTE(png_ptr, info_ptr, rq, 256);
353 png_write_info(png_ptr, info_ptr);
354 png_set_flush(png_ptr, 512);
356 if (pixelformat == 32) {
357 png_color_8 sig_bit;
359 /* Save exact colour/alpha resolution */
360 sig_bit.alpha = 0;
361 sig_bit.blue = 8;
362 sig_bit.green = 8;
363 sig_bit.red = 8;
364 sig_bit.gray = 8;
365 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
367 #if TTD_ENDIAN == TTD_LITTLE_ENDIAN
368 png_set_bgr(png_ptr);
369 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
370 #else
371 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
372 #endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
375 /* use by default 64k temp memory */
376 maxlines = Clamp(65536 / w, 16, 128);
378 /* now generate the bitmap bits */
379 void *buff = CallocT<uint8>(w * maxlines * bpp); // by default generate 128 lines at a time.
381 y = 0;
382 do {
383 /* determine # lines to write */
384 n = min(h - y, maxlines);
386 /* render the pixels into the buffer */
387 callb(userdata, buff, y, w, n);
388 y += n;
390 /* write them to png */
391 for (i = 0; i != n; i++) {
392 png_write_row(png_ptr, (png_bytep)buff + i * w * bpp);
394 } while (y != h);
396 png_write_end(png_ptr, info_ptr);
397 png_destroy_write_struct(&png_ptr, &info_ptr);
399 free(buff);
400 fclose(f);
401 return true;
403 #endif /* WITH_PNG */
406 /*************************************************
407 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
408 *************************************************/
410 /** Definition of a PCX file header. */
411 struct PcxHeader {
412 byte manufacturer;
413 byte version;
414 byte rle;
415 byte bpp;
416 uint32 unused;
417 uint16 xmax, ymax;
418 uint16 hdpi, vdpi;
419 byte pal_small[16 * 3];
420 byte reserved;
421 byte planes;
422 uint16 pitch;
423 uint16 cpal;
424 uint16 width;
425 uint16 height;
426 byte filler[54];
428 assert_compile(sizeof(PcxHeader) == 128);
431 * Generic .PCX file image writer.
432 * @param name Filename, including extension.
433 * @param callb Callback function for generating lines of pixels.
434 * @param userdata User data, passed on to \a callb.
435 * @param w Width of the image in pixels.
436 * @param h Height of the image in pixels.
437 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
438 * @param palette %Colour palette (for 8bpp images).
439 * @return File was written successfully.
440 * @see ScreenshotHandlerProc
442 static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
444 FILE *f;
445 uint maxlines;
446 uint y;
447 PcxHeader pcx;
448 bool success;
450 if (pixelformat == 32) {
451 DEBUG(misc, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
452 return false;
454 if (pixelformat != 8 || w == 0) return false;
456 f = fopen(name, "wb");
457 if (f == NULL) return false;
459 memset(&pcx, 0, sizeof(pcx));
461 /* setup pcx header */
462 pcx.manufacturer = 10;
463 pcx.version = 5;
464 pcx.rle = 1;
465 pcx.bpp = 8;
466 pcx.xmax = TO_LE16(w - 1);
467 pcx.ymax = TO_LE16(h - 1);
468 pcx.hdpi = TO_LE16(320);
469 pcx.vdpi = TO_LE16(320);
471 pcx.planes = 1;
472 pcx.cpal = TO_LE16(1);
473 pcx.width = pcx.pitch = TO_LE16(w);
474 pcx.height = TO_LE16(h);
476 /* write pcx header */
477 if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
478 fclose(f);
479 return false;
482 /* use by default 64k temp memory */
483 maxlines = Clamp(65536 / w, 16, 128);
485 /* now generate the bitmap bits */
486 uint8 *buff = CallocT<uint8>(w * maxlines); // by default generate 128 lines at a time.
488 y = 0;
489 do {
490 /* determine # lines to write */
491 uint n = min(h - y, maxlines);
492 uint i;
494 /* render the pixels into the buffer */
495 callb(userdata, buff, y, w, n);
496 y += n;
498 /* write them to pcx */
499 for (i = 0; i != n; i++) {
500 const uint8 *bufp = buff + i * w;
501 byte runchar = bufp[0];
502 uint runcount = 1;
503 uint j;
505 /* for each pixel... */
506 for (j = 1; j < w; j++) {
507 uint8 ch = bufp[j];
509 if (ch != runchar || runcount >= 0x3f) {
510 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
511 if (fputc(0xC0 | runcount, f) == EOF) {
512 free(buff);
513 fclose(f);
514 return false;
517 if (fputc(runchar, f) == EOF) {
518 free(buff);
519 fclose(f);
520 return false;
522 runcount = 0;
523 runchar = ch;
525 runcount++;
528 /* write remaining bytes.. */
529 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
530 if (fputc(0xC0 | runcount, f) == EOF) {
531 free(buff);
532 fclose(f);
533 return false;
536 if (fputc(runchar, f) == EOF) {
537 free(buff);
538 fclose(f);
539 return false;
542 } while (y != h);
544 free(buff);
546 /* write 8-bit colour palette */
547 if (fputc(12, f) == EOF) {
548 fclose(f);
549 return false;
552 /* Palette is word-aligned, copy it to a temporary byte array */
553 byte tmp[256 * 3];
555 for (uint i = 0; i < 256; i++) {
556 tmp[i * 3 + 0] = palette[i].r;
557 tmp[i * 3 + 1] = palette[i].g;
558 tmp[i * 3 + 2] = palette[i].b;
560 success = fwrite(tmp, sizeof(tmp), 1, f) == 1;
562 fclose(f);
564 return success;
567 /*************************************************
568 **** GENERIC SCREENSHOT CODE
569 *************************************************/
571 /** Available screenshot formats. */
572 static const ScreenshotFormat _screenshot_formats[] = {
573 #if defined(WITH_PNG)
574 {"PNG", "png", &MakePNGImage, true},
575 #endif
576 {"BMP", "bmp", &MakeBMPImage, true},
577 {"PCX", "pcx", &MakePCXImage, false},
580 /** Get filename extension of current screenshot file format. */
581 const char *GetCurrentScreenshotExtension()
583 return _screenshot_formats[_cur_screenshot_format].extension;
586 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
587 void InitializeScreenshotFormats()
589 uint j = 0;
590 for (uint i = 0; i < lengthof(_screenshot_formats); i++) {
591 if (!strcmp(_screenshot_format_name, _screenshot_formats[i].extension)) {
592 j = i;
593 break;
596 _cur_screenshot_format = j;
597 _num_screenshot_formats = lengthof(_screenshot_formats);
601 * Give descriptive name of the screenshot format.
602 * @param i Number of the screenshot format.
603 * @return String constant describing the format.
605 const char *GetScreenshotFormatDesc(int i)
607 return _screenshot_formats[i].name;
611 * Determine whether a certain screenshot format support 32bpp images.
612 * @param i Number of the screenshot format.
613 * @return true if 32bpp is supported.
615 bool GetScreenshotFormatSupports_32bpp(int i)
617 return _screenshot_formats[i].supports_32bpp;
621 * Set the screenshot format to use.
622 * @param i Number of the format.
624 void SetScreenshotFormat(uint i)
626 assert(i < _num_screenshot_formats);
627 _cur_screenshot_format = i;
628 strecpy(_screenshot_format_name, _screenshot_formats[i].extension, lastof(_screenshot_format_name));
632 * Callback of the screenshot generator that dumps the current video buffer.
633 * @see ScreenshotCallback
635 static void CurrentScreenCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
637 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
638 void *src = blitter->MoveTo(_screen.dst_ptr, 0, y);
639 blitter->CopyImageToBuffer(src, buf, _screen.width, n, pitch);
643 * generate a large piece of the world
644 * @param userdata Viewport area to draw
645 * @param buf Videobuffer with same bitdepth as current blitter
646 * @param y First line to render
647 * @param pitch Pitch of the videobuffer
648 * @param n Number of lines to render
650 static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
652 ViewPort *vp = (ViewPort *)userdata;
653 DrawPixelInfo dpi, *old_dpi;
654 int wx, left;
656 /* We are no longer rendering to the screen */
657 DrawPixelInfo old_screen = _screen;
658 bool old_disable_anim = _screen_disable_anim;
660 _screen.dst_ptr = buf;
661 _screen.width = pitch;
662 _screen.height = n;
663 _screen.pitch = pitch;
664 _screen_disable_anim = true;
666 old_dpi = _cur_dpi;
667 _cur_dpi = &dpi;
669 dpi.dst_ptr = buf;
670 dpi.height = n;
671 dpi.width = vp->width;
672 dpi.pitch = pitch;
673 dpi.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
674 dpi.left = 0;
675 dpi.top = y;
677 /* Render viewport in blocks of 1600 pixels width */
678 left = 0;
679 while (vp->width - left != 0) {
680 wx = min(vp->width - left, 1600);
681 left += wx;
683 ViewportDoDraw(vp,
684 ScaleByZoom(left - wx - vp->left, vp->zoom) + vp->virtual_left,
685 ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top,
686 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
687 ScaleByZoom((y + n) - vp->top, vp->zoom) + vp->virtual_top
691 _cur_dpi = old_dpi;
693 /* Switch back to rendering to the screen */
694 _screen = old_screen;
695 _screen_disable_anim = old_disable_anim;
699 * Construct a pathname for a screenshot file.
700 * @param default_fn Default filename.
701 * @param ext Extension to use.
702 * @param crashlog Create path for crash.png
703 * @return Pathname for a screenshot file.
705 static const char *MakeScreenshotName(const char *default_fn, const char *ext, bool crashlog = false)
707 bool generate = StrEmpty(_screenshot_name);
709 if (generate) {
710 if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
711 strecpy(_screenshot_name, default_fn, lastof(_screenshot_name));
712 } else {
713 GenerateDefaultSaveName(_screenshot_name, lastof(_screenshot_name));
717 /* Add extension to screenshot file */
718 size_t len = strlen(_screenshot_name);
719 snprintf(&_screenshot_name[len], lengthof(_screenshot_name) - len, ".%s", ext);
721 const char *screenshot_dir = crashlog ? _personal_dir : FiosGetScreenshotDir();
723 for (uint serial = 1;; serial++) {
724 if (snprintf(_full_screenshot_name, lengthof(_full_screenshot_name), "%s%s", screenshot_dir, _screenshot_name) >= (int)lengthof(_full_screenshot_name)) {
725 /* We need more characters than MAX_PATH -> end with error */
726 _full_screenshot_name[0] = '\0';
727 break;
729 if (!generate) break; // allow overwriting of non-automatic filenames
730 if (!FileExists(_full_screenshot_name)) break;
731 /* If file exists try another one with same name, but just with a higher index */
732 snprintf(&_screenshot_name[len], lengthof(_screenshot_name) - len, "#%u.%s", serial, ext);
735 return _full_screenshot_name;
738 /** Make a screenshot of the current screen. */
739 static bool MakeSmallScreenshot(bool crashlog)
741 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
742 return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension, crashlog), CurrentScreenCallback, NULL, _screen.width, _screen.height,
743 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
747 * Configure a ViewPort for rendering (a part of) the map into a screenshot.
748 * @param t Screenshot type
749 * @param [out] vp Result viewport
751 void SetupScreenshotViewport(ScreenshotType t, ViewPort *vp)
753 /* Determine world coordinates of screenshot */
754 if (t == SC_WORLD) {
755 vp->zoom = ZOOM_LVL_WORLD_SCREENSHOT;
757 TileIndex north_tile = _settings_game.construction.freeform_edges ? TileXY(1, 1) : TileXY(0, 0);
758 TileIndex south_tile = MapSize() - 1;
760 /* We need to account for a hill or high building at tile 0,0. */
761 int extra_height_top = TilePixelHeight(north_tile) + 150;
762 /* If there is a hill at the bottom don't create a large black area. */
763 int reclaim_height_bottom = TilePixelHeight(south_tile);
765 vp->virtual_left = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, 0).x;
766 vp->virtual_top = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, extra_height_top).y;
767 vp->virtual_width = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, 0).x - vp->virtual_left + 1;
768 vp->virtual_height = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, reclaim_height_bottom).y - vp->virtual_top + 1;
769 } else {
770 vp->zoom = (t == SC_ZOOMEDIN) ? _settings_client.gui.zoom_min : ZOOM_LVL_VIEWPORT;
772 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
773 vp->virtual_left = w->viewport->virtual_left;
774 vp->virtual_top = w->viewport->virtual_top;
775 vp->virtual_width = w->viewport->virtual_width;
776 vp->virtual_height = w->viewport->virtual_height;
779 /* Compute pixel coordinates */
780 vp->left = 0;
781 vp->top = 0;
782 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
783 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
784 vp->overlay = NULL;
788 * Make a screenshot of the map.
789 * @param t Screenshot type: World or viewport screenshot
790 * @return true on success
792 static bool MakeLargeWorldScreenshot(ScreenshotType t)
794 ViewPort vp;
795 SetupScreenshotViewport(t, &vp);
797 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
798 return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension), LargeWorldCallback, &vp, vp.width, vp.height,
799 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
803 * Callback for generating a heightmap. Supports 8bpp grayscale only.
804 * @param userdata Pointer to user data.
805 * @param buf Destination buffer.
806 * @param y Line number of the first line to write.
807 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
808 * @param n Number of lines to write.
809 * @see ScreenshotCallback
811 static void HeightmapCallback(void *userdata, void *buffer, uint y, uint pitch, uint n)
813 byte *buf = (byte *)buffer;
814 while (n > 0) {
815 TileIndex ti = TileXY(MapMaxX(), y);
816 for (uint x = MapMaxX(); true; x--) {
817 *buf = 16 * TileHeight(ti);
818 buf++;
819 if (x == 0) break;
820 ti = TILE_ADDXY(ti, -1, 0);
822 y++;
823 n--;
828 * Make a heightmap of the current map.
829 * @param filename Filename to use for saving.
831 bool MakeHeightmapScreenshot(const char *filename)
833 Colour palette[256];
834 for (uint i = 0; i < lengthof(palette); i++) {
835 palette[i].a = 0xff;
836 palette[i].r = i;
837 palette[i].g = i;
838 palette[i].b = i;
840 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
841 return sf->proc(filename, HeightmapCallback, NULL, MapSizeX(), MapSizeY(), 8, palette);
845 * Make an actual screenshot.
846 * @param t the type of screenshot to make.
847 * @param name the name to give to the screenshot.
848 * @return true iff the screenshot was made successfully
850 bool MakeScreenshot(ScreenshotType t, const char *name)
852 if (t == SC_VIEWPORT) {
853 /* First draw the dirty parts of the screen and only then change the name
854 * of the screenshot. This way the screenshot will always show the name
855 * of the previous screenshot in the 'successful' message instead of the
856 * name of the new screenshot (or an empty name). */
857 UndrawMouseCursor();
858 DrawDirtyBlocks();
861 _screenshot_name[0] = '\0';
862 if (name != NULL) strecpy(_screenshot_name, name, lastof(_screenshot_name));
864 bool ret;
865 switch (t) {
866 case SC_VIEWPORT:
867 ret = MakeSmallScreenshot(false);
868 break;
870 case SC_CRASHLOG:
871 ret = MakeSmallScreenshot(true);
872 break;
874 case SC_ZOOMEDIN:
875 case SC_DEFAULTZOOM:
876 case SC_WORLD:
877 ret = MakeLargeWorldScreenshot(t);
878 break;
880 case SC_HEIGHTMAP: {
881 const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
882 ret = MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME, sf->extension));
883 break;
886 default:
887 NOT_REACHED();
890 if (ret) {
891 SetDParamStr(0, _screenshot_name);
892 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY, INVALID_STRING_ID, WL_WARNING);
893 } else {
894 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED, INVALID_STRING_ID, WL_ERROR);
897 return ret;