Update: Translations from eints
[openttd-github.git] / src / screenshot.cpp
bloba5641fc5e9b1942885a0662aa4c9f516285952c7
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file screenshot.cpp The creation of screenshots! */
10 #include "stdafx.h"
11 #include "core/backup_type.hpp"
12 #include "fileio_func.h"
13 #include "viewport_func.h"
14 #include "gfx_func.h"
15 #include "screenshot.h"
16 #include "screenshot_gui.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_base.h"
22 #include "company_func.h"
23 #include "strings_func.h"
24 #include "error.h"
25 #include "textbuf_gui.h"
26 #include "window_gui.h"
27 #include "window_func.h"
28 #include "tile_map.h"
29 #include "landscape.h"
30 #include "video/video_driver.hpp"
31 #include "smallmap_gui.h"
33 #include "table/strings.h"
35 #include "safeguards.h"
37 static const char * const SCREENSHOT_NAME = "screenshot"; ///< Default filename of a saved screenshot.
38 static const char * const HEIGHTMAP_NAME = "heightmap"; ///< Default filename of a saved heightmap.
40 std::string _screenshot_format_name; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
41 static std::string _screenshot_name; ///< Filename of the screenshot file.
42 std::string _full_screenshot_path; ///< Pathname of the screenshot file.
43 uint _heightmap_highest_peak; ///< When saving a heightmap, this contains the highest peak on the map.
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_LE32(x)
76 /*************************************************
77 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
78 *************************************************/
80 /** BMP File Header (stored in little endian) */
81 PACK(struct BitmapFileHeader {
82 uint16_t type;
83 uint32_t size;
84 uint32_t reserved;
85 uint32_t off_bits;
86 });
87 static_assert(sizeof(BitmapFileHeader) == 14);
89 /** BMP Info Header (stored in little endian) */
90 struct BitmapInfoHeader {
91 uint32_t size;
92 int32_t width, height;
93 uint16_t planes, bitcount;
94 uint32_t compression, sizeimage, xpels, ypels, clrused, clrimp;
96 static_assert(sizeof(BitmapInfoHeader) == 40);
98 /** Format of palette data in BMP header */
99 struct RgbQuad {
100 uint8_t blue, green, red, reserved;
102 static_assert(sizeof(RgbQuad) == 4);
105 * Generic .BMP writer
106 * @param name file name including extension
107 * @param callb callback used for gathering rendered image
108 * @param userdata parameters forwarded to \a callb
109 * @param w width in pixels
110 * @param h height in pixels
111 * @param pixelformat bits per pixel
112 * @param palette colour palette (for 8bpp mode)
113 * @return was everything ok?
114 * @see ScreenshotHandlerProc
116 static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
118 uint bpp; // bytes per pixel
119 switch (pixelformat) {
120 case 8: bpp = 1; break;
121 /* 32bpp mode is saved as 24bpp BMP */
122 case 32: bpp = 3; break;
123 /* Only implemented for 8bit and 32bit images so far */
124 default: return false;
127 auto of = FileHandle::Open(name, "wb");
128 if (!of.has_value()) return false;
129 auto &f = *of;
131 /* Each scanline must be aligned on a 32bit boundary */
132 uint bytewidth = Align(w * bpp, 4); // bytes per line in file
134 /* Size of palette. Only present for 8bpp mode */
135 uint pal_size = pixelformat == 8 ? sizeof(RgbQuad) * 256 : 0;
137 /* Setup the file header */
138 BitmapFileHeader bfh;
139 bfh.type = TO_LE16('MB');
140 bfh.size = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size + static_cast<size_t>(bytewidth) * h);
141 bfh.reserved = 0;
142 bfh.off_bits = TO_LE32(sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + pal_size);
144 /* Setup the info header */
145 BitmapInfoHeader bih;
146 bih.size = TO_LE32(sizeof(BitmapInfoHeader));
147 bih.width = TO_LE32(w);
148 bih.height = TO_LE32(h);
149 bih.planes = TO_LE16(1);
150 bih.bitcount = TO_LE16(bpp * 8);
151 bih.compression = 0;
152 bih.sizeimage = 0;
153 bih.xpels = 0;
154 bih.ypels = 0;
155 bih.clrused = 0;
156 bih.clrimp = 0;
158 /* Write file header and info header */
159 if (fwrite(&bfh, sizeof(bfh), 1, f) != 1 || fwrite(&bih, sizeof(bih), 1, f) != 1) {
160 return false;
163 if (pixelformat == 8) {
164 /* Convert the palette to the windows format */
165 RgbQuad rq[256];
166 for (uint i = 0; i < 256; i++) {
167 rq[i].red = palette[i].r;
168 rq[i].green = palette[i].g;
169 rq[i].blue = palette[i].b;
170 rq[i].reserved = 0;
172 /* Write the palette */
173 if (fwrite(rq, sizeof(rq), 1, f) != 1) {
174 return false;
178 /* Try to use 64k of memory, store between 16 and 128 lines */
179 uint maxlines = Clamp(65536 / (w * pixelformat / 8), 16, 128); // number of lines per iteration
181 std::vector<uint8_t> buff(maxlines * w * pixelformat / 8); // buffer which is rendered to
182 std::vector<uint8_t> line(bytewidth); // one line, stored to file
184 /* Start at the bottom, since bitmaps are stored bottom up */
185 do {
186 uint n = std::min(h, maxlines);
187 h -= n;
189 /* Render the pixels */
190 callb(userdata, buff.data(), h, w, n);
192 /* Write each line */
193 while (n-- != 0) {
194 if (pixelformat == 8) {
195 /* Move to 'line', leave last few pixels in line zeroed */
196 memcpy(line.data(), buff.data() + n * w, w);
197 } else {
198 /* Convert from 'native' 32bpp to BMP-like 24bpp.
199 * Works for both big and little endian machines */
200 Colour *src = ((Colour *)buff.data()) + n * w;
201 uint8_t *dst = line.data();
202 for (uint i = 0; i < w; i++) {
203 dst[i * 3 ] = src[i].b;
204 dst[i * 3 + 1] = src[i].g;
205 dst[i * 3 + 2] = src[i].r;
208 /* Write to file */
209 if (fwrite(line.data(), bytewidth, 1, f) != 1) {
210 return false;
213 } while (h != 0);
216 return true;
219 /*********************************************************
220 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
221 *********************************************************/
222 #if defined(WITH_PNG)
223 #include <png.h>
225 #ifdef PNG_TEXT_SUPPORTED
226 #include "rev.h"
227 #include "newgrf_config.h"
228 #include "ai/ai_info.hpp"
229 #include "company_base.h"
230 #include "base_media_base.h"
231 #endif /* PNG_TEXT_SUPPORTED */
233 static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
235 Debug(misc, 0, "[libpng] error: {} - {}", message, (const char *)png_get_error_ptr(png_ptr));
236 longjmp(png_jmpbuf(png_ptr), 1);
239 static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
241 Debug(misc, 1, "[libpng] warning: {} - {}", message, (const char *)png_get_error_ptr(png_ptr));
245 * Generic .PNG file image writer.
246 * @param name Filename, including extension.
247 * @param callb Callback function for generating lines of pixels.
248 * @param userdata User data, passed on to \a callb.
249 * @param w Width of the image in pixels.
250 * @param h Height of the image in pixels.
251 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
252 * @param palette %Colour palette (for 8bpp images).
253 * @return File was written successfully.
254 * @see ScreenshotHandlerProc
256 static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
258 png_color rq[256];
259 uint i, y, n;
260 uint maxlines;
261 uint bpp = pixelformat / 8;
262 png_structp png_ptr;
263 png_infop info_ptr;
265 /* only implemented for 8bit and 32bit images so far. */
266 if (pixelformat != 8 && pixelformat != 32) return false;
268 auto of = FileHandle::Open(name, "wb");
269 if (!of.has_value()) return false;
270 auto &f = *of;
272 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char *>(name), png_my_error, png_my_warning);
274 if (png_ptr == nullptr) {
275 return false;
278 info_ptr = png_create_info_struct(png_ptr);
279 if (info_ptr == nullptr) {
280 png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
281 return false;
284 if (setjmp(png_jmpbuf(png_ptr))) {
285 png_destroy_write_struct(&png_ptr, &info_ptr);
286 return false;
289 png_init_io(png_ptr, f);
291 png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
293 png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
294 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
296 #ifdef PNG_TEXT_SUPPORTED
297 /* Try to add some game metadata to the PNG screenshot so
298 * it's more useful for debugging and archival purposes. */
299 png_text_struct text[2];
300 memset(text, 0, sizeof(text));
301 text[0].key = const_cast<char *>("Software");
302 text[0].text = const_cast<char *>(_openttd_revision);
303 text[0].text_length = strlen(_openttd_revision);
304 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
306 std::string message;
307 message.reserve(1024);
308 fmt::format_to(std::back_inserter(message), "Graphics set: {} ({})\n", BaseGraphics::GetUsedSet()->name, BaseGraphics::GetUsedSet()->version);
309 message += "NewGRFs:\n";
310 for (const GRFConfig *c = _game_mode == GM_MENU ? nullptr : _grfconfig; c != nullptr; c = c->next) {
311 fmt::format_to(std::back_inserter(message), "{:08X} {} {}\n", BSWAP32(c->ident.grfid), FormatArrayAsHex(c->ident.md5sum), c->filename);
313 message += "\nCompanies:\n";
314 for (const Company *c : Company::Iterate()) {
315 if (c->ai_info == nullptr) {
316 fmt::format_to(std::back_inserter(message), "{:2d}: Human\n", (int)c->index);
317 } else {
318 fmt::format_to(std::back_inserter(message), "{:2d}: {} (v{})\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
321 text[1].key = const_cast<char *>("Description");
322 text[1].text = const_cast<char *>(message.c_str());
323 text[1].text_length = message.size();
324 text[1].compression = PNG_TEXT_COMPRESSION_zTXt;
325 png_set_text(png_ptr, info_ptr, text, 2);
326 #endif /* PNG_TEXT_SUPPORTED */
328 if (pixelformat == 8) {
329 /* convert the palette to the .PNG format. */
330 for (i = 0; i != 256; i++) {
331 rq[i].red = palette[i].r;
332 rq[i].green = palette[i].g;
333 rq[i].blue = palette[i].b;
336 png_set_PLTE(png_ptr, info_ptr, rq, 256);
339 png_write_info(png_ptr, info_ptr);
340 png_set_flush(png_ptr, 512);
342 if (pixelformat == 32) {
343 png_color_8 sig_bit;
345 /* Save exact colour/alpha resolution */
346 sig_bit.alpha = 0;
347 sig_bit.blue = 8;
348 sig_bit.green = 8;
349 sig_bit.red = 8;
350 sig_bit.gray = 8;
351 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
353 if constexpr (std::endian::native == std::endian::little) {
354 png_set_bgr(png_ptr);
355 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
356 } else {
357 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
361 /* use by default 64k temp memory */
362 maxlines = Clamp(65536 / w, 16, 128);
364 /* now generate the bitmap bits */
365 std::vector<uint8_t> buff(static_cast<size_t>(w) * maxlines * bpp); // by default generate 128 lines at a time.
367 y = 0;
368 do {
369 /* determine # lines to write */
370 n = std::min(h - y, maxlines);
372 /* render the pixels into the buffer */
373 callb(userdata, buff.data(), y, w, n);
374 y += n;
376 /* write them to png */
377 for (i = 0; i != n; i++) {
378 png_write_row(png_ptr, (png_bytep)buff.data() + i * w * bpp);
380 } while (y != h);
382 png_write_end(png_ptr, info_ptr);
383 png_destroy_write_struct(&png_ptr, &info_ptr);
385 return true;
387 #endif /* WITH_PNG */
390 /*************************************************
391 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
392 *************************************************/
394 /** Definition of a PCX file header. */
395 struct PcxHeader {
396 uint8_t manufacturer;
397 uint8_t version;
398 uint8_t rle;
399 uint8_t bpp;
400 uint32_t unused;
401 uint16_t xmax, ymax;
402 uint16_t hdpi, vdpi;
403 uint8_t pal_small[16 * 3];
404 uint8_t reserved;
405 uint8_t planes;
406 uint16_t pitch;
407 uint16_t cpal;
408 uint16_t width;
409 uint16_t height;
410 uint8_t filler[54];
412 static_assert(sizeof(PcxHeader) == 128);
415 * Generic .PCX file image writer.
416 * @param name Filename, including extension.
417 * @param callb Callback function for generating lines of pixels.
418 * @param userdata User data, passed on to \a callb.
419 * @param w Width of the image in pixels.
420 * @param h Height of the image in pixels.
421 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
422 * @param palette %Colour palette (for 8bpp images).
423 * @return File was written successfully.
424 * @see ScreenshotHandlerProc
426 static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *userdata, uint w, uint h, int pixelformat, const Colour *palette)
428 uint maxlines;
429 uint y;
430 PcxHeader pcx;
431 bool success;
433 if (pixelformat == 32) {
434 Debug(misc, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
435 return false;
437 if (pixelformat != 8 || w == 0) return false;
439 auto of = FileHandle::Open(name, "wb");
440 if (!of.has_value()) return false;
441 auto &f = *of;
443 memset(&pcx, 0, sizeof(pcx));
445 /* setup pcx header */
446 pcx.manufacturer = 10;
447 pcx.version = 5;
448 pcx.rle = 1;
449 pcx.bpp = 8;
450 pcx.xmax = TO_LE16(w - 1);
451 pcx.ymax = TO_LE16(h - 1);
452 pcx.hdpi = TO_LE16(320);
453 pcx.vdpi = TO_LE16(320);
455 pcx.planes = 1;
456 pcx.cpal = TO_LE16(1);
457 pcx.width = pcx.pitch = TO_LE16(w);
458 pcx.height = TO_LE16(h);
460 /* write pcx header */
461 if (fwrite(&pcx, sizeof(pcx), 1, f) != 1) {
462 return false;
465 /* use by default 64k temp memory */
466 maxlines = Clamp(65536 / w, 16, 128);
468 /* now generate the bitmap bits */
469 std::vector<uint8_t> buff(static_cast<size_t>(w) * maxlines); // by default generate 128 lines at a time.
471 y = 0;
472 do {
473 /* determine # lines to write */
474 uint n = std::min(h - y, maxlines);
475 uint i;
477 /* render the pixels into the buffer */
478 callb(userdata, buff.data(), y, w, n);
479 y += n;
481 /* write them to pcx */
482 for (i = 0; i != n; i++) {
483 const uint8_t *bufp = buff.data() + i * w;
484 uint8_t runchar = bufp[0];
485 uint runcount = 1;
486 uint j;
488 /* for each pixel... */
489 for (j = 1; j < w; j++) {
490 uint8_t ch = bufp[j];
492 if (ch != runchar || runcount >= 0x3f) {
493 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
494 if (fputc(0xC0 | runcount, f) == EOF) {
495 return false;
498 if (fputc(runchar, f) == EOF) {
499 return false;
501 runcount = 0;
502 runchar = ch;
504 runcount++;
507 /* write remaining bytes.. */
508 if (runcount > 1 || (runchar & 0xC0) == 0xC0) {
509 if (fputc(0xC0 | runcount, f) == EOF) {
510 return false;
513 if (fputc(runchar, f) == EOF) {
514 return false;
517 } while (y != h);
519 /* write 8-bit colour palette */
520 if (fputc(12, f) == EOF) {
521 return false;
524 /* Palette is word-aligned, copy it to a temporary byte array */
525 uint8_t tmp[256 * 3];
527 for (uint i = 0; i < 256; i++) {
528 tmp[i * 3 + 0] = palette[i].r;
529 tmp[i * 3 + 1] = palette[i].g;
530 tmp[i * 3 + 2] = palette[i].b;
532 success = fwrite(tmp, sizeof(tmp), 1, f) == 1;
534 return success;
537 /*************************************************
538 **** GENERIC SCREENSHOT CODE
539 *************************************************/
541 /** Available screenshot formats. */
542 static const ScreenshotFormat _screenshot_formats[] = {
543 #if defined(WITH_PNG)
544 {"png", &MakePNGImage},
545 #endif
546 {"bmp", &MakeBMPImage},
547 {"pcx", &MakePCXImage},
550 /* The currently loaded screenshot format. Set to a valid value as it might be used in early crash logs, when InitializeScreenshotFormats has not been called yet. */
551 static const ScreenshotFormat *_cur_screenshot_format = std::begin(_screenshot_formats);
553 /** Get filename extension of current screenshot file format. */
554 const char *GetCurrentScreenshotExtension()
556 return _cur_screenshot_format->extension;
559 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
560 void InitializeScreenshotFormats()
562 for (auto &format : _screenshot_formats) {
563 if (_screenshot_format_name == format.extension) {
564 _cur_screenshot_format = &format;
565 return;
569 _cur_screenshot_format = std::begin(_screenshot_formats);
573 * Callback of the screenshot generator that dumps the current video buffer.
574 * @see ScreenshotCallback
576 static void CurrentScreenCallback(void *, void *buf, uint y, uint pitch, uint n)
578 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
579 void *src = blitter->MoveTo(_screen.dst_ptr, 0, y);
580 blitter->CopyImageToBuffer(src, buf, _screen.width, n, pitch);
584 * generate a large piece of the world
585 * @param userdata Viewport area to draw
586 * @param buf Videobuffer with same bitdepth as current blitter
587 * @param y First line to render
588 * @param pitch Pitch of the videobuffer
589 * @param n Number of lines to render
591 static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
593 Viewport *vp = (Viewport *)userdata;
594 DrawPixelInfo dpi;
595 int wx, left;
597 /* We are no longer rendering to the screen */
598 DrawPixelInfo old_screen = _screen;
599 bool old_disable_anim = _screen_disable_anim;
601 _screen.dst_ptr = buf;
602 _screen.width = pitch;
603 _screen.height = n;
604 _screen.pitch = pitch;
605 _screen_disable_anim = true;
607 AutoRestoreBackup dpi_backup(_cur_dpi, &dpi);
609 dpi.dst_ptr = buf;
610 dpi.height = n;
611 dpi.width = vp->width;
612 dpi.pitch = pitch;
613 dpi.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
614 dpi.left = 0;
615 dpi.top = y;
617 /* Render viewport in blocks of 1600 pixels width */
618 left = 0;
619 while (vp->width - left != 0) {
620 wx = std::min(vp->width - left, 1600);
621 left += wx;
623 ViewportDoDraw(vp,
624 ScaleByZoom(left - wx - vp->left, vp->zoom) + vp->virtual_left,
625 ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top,
626 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
627 ScaleByZoom((y + n) - vp->top, vp->zoom) + vp->virtual_top
631 /* Switch back to rendering to the screen */
632 _screen = old_screen;
633 _screen_disable_anim = old_disable_anim;
637 * Construct a pathname for a screenshot file.
638 * @param default_fn Default filename.
639 * @param ext Extension to use.
640 * @param crashlog Create path for crash.png
641 * @return Pathname for a screenshot file.
643 static const char *MakeScreenshotName(const char *default_fn, const char *ext, bool crashlog = false)
645 bool generate = _screenshot_name.empty();
647 if (generate) {
648 if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
649 _screenshot_name = default_fn;
650 } else {
651 _screenshot_name = GenerateDefaultSaveName();
655 /* Handle user-specified filenames ending in # with automatic numbering */
656 if (_screenshot_name.ends_with("#")) {
657 generate = true;
658 _screenshot_name.pop_back();
661 size_t len = _screenshot_name.size();
662 /* Add extension to screenshot file */
663 _screenshot_name += fmt::format(".{}", ext);
665 const char *screenshot_dir = crashlog ? _personal_dir.c_str() : FiosGetScreenshotDir();
667 for (uint serial = 1;; serial++) {
668 _full_screenshot_path = fmt::format("{}{}", screenshot_dir, _screenshot_name);
670 if (!generate) break; // allow overwriting of non-automatic filenames
671 if (!FileExists(_full_screenshot_path)) break;
672 /* If file exists try another one with same name, but just with a higher index */
673 _screenshot_name.erase(len);
674 _screenshot_name += fmt::format("#{}.{}", serial, ext);
677 return _full_screenshot_path.c_str();
680 /** Make a screenshot of the current screen. */
681 static bool MakeSmallScreenshot(bool crashlog)
683 return _cur_screenshot_format->proc(MakeScreenshotName(SCREENSHOT_NAME, _cur_screenshot_format->extension, crashlog), CurrentScreenCallback, nullptr, _screen.width, _screen.height,
684 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
688 * Configure a Viewport for rendering (a part of) the map into a screenshot.
689 * @param t Screenshot type
690 * @param width the width of the screenshot, or 0 for current viewport width (needs to be 0 with SC_VIEWPORT, SC_CRASHLOG, and SC_WORLD).
691 * @param height the height of the screenshot, or 0 for current viewport height (needs to be 0 with SC_VIEWPORT, SC_CRASHLOG, and SC_WORLD).
692 * @param[out] vp Result viewport
694 void SetupScreenshotViewport(ScreenshotType t, Viewport *vp, uint32_t width, uint32_t height)
696 switch(t) {
697 case SC_VIEWPORT:
698 case SC_CRASHLOG: {
699 assert(width == 0 && height == 0);
701 Window *w = GetMainWindow();
702 vp->virtual_left = w->viewport->virtual_left;
703 vp->virtual_top = w->viewport->virtual_top;
704 vp->virtual_width = w->viewport->virtual_width;
705 vp->virtual_height = w->viewport->virtual_height;
707 /* Compute pixel coordinates */
708 vp->left = 0;
709 vp->top = 0;
710 vp->width = _screen.width;
711 vp->height = _screen.height;
712 vp->overlay = w->viewport->overlay;
713 break;
715 case SC_WORLD: {
716 assert(width == 0 && height == 0);
718 /* Determine world coordinates of screenshot */
719 vp->zoom = ZOOM_LVL_WORLD_SCREENSHOT;
721 TileIndex north_tile = _settings_game.construction.freeform_edges ? TileXY(1, 1) : TileXY(0, 0);
722 TileIndex south_tile = Map::Size() - 1;
724 /* We need to account for a hill or high building at tile 0,0. */
725 int extra_height_top = TilePixelHeight(north_tile) + 150;
726 /* If there is a hill at the bottom don't create a large black area. */
727 int reclaim_height_bottom = TilePixelHeight(south_tile);
729 vp->virtual_left = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, 0).x;
730 vp->virtual_top = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, extra_height_top).y;
731 vp->virtual_width = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, 0).x - vp->virtual_left + 1;
732 vp->virtual_height = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, reclaim_height_bottom).y - vp->virtual_top + 1;
734 /* Compute pixel coordinates */
735 vp->left = 0;
736 vp->top = 0;
737 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
738 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
739 vp->overlay = nullptr;
740 break;
742 default: {
743 vp->zoom = (t == SC_ZOOMEDIN) ? _settings_client.gui.zoom_min : ZOOM_LVL_VIEWPORT;
745 Window *w = GetMainWindow();
746 vp->virtual_left = w->viewport->virtual_left;
747 vp->virtual_top = w->viewport->virtual_top;
749 if (width == 0 || height == 0) {
750 vp->virtual_width = w->viewport->virtual_width;
751 vp->virtual_height = w->viewport->virtual_height;
752 } else {
753 vp->virtual_width = width << vp->zoom;
754 vp->virtual_height = height << vp->zoom;
757 /* Compute pixel coordinates */
758 vp->left = 0;
759 vp->top = 0;
760 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
761 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
762 vp->overlay = nullptr;
763 break;
769 * Make a screenshot of the map.
770 * @param t Screenshot type: World or viewport screenshot
771 * @param width the width of the screenshot of, or 0 for current viewport width.
772 * @param height the height of the screenshot of, or 0 for current viewport height.
773 * @return true on success
775 static bool MakeLargeWorldScreenshot(ScreenshotType t, uint32_t width = 0, uint32_t height = 0)
777 Viewport vp;
778 SetupScreenshotViewport(t, &vp, width, height);
780 return _cur_screenshot_format->proc(MakeScreenshotName(SCREENSHOT_NAME, _cur_screenshot_format->extension), LargeWorldCallback, &vp, vp.width, vp.height,
781 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
785 * Callback for generating a heightmap. Supports 8bpp grayscale only.
786 * @param buffer Destination buffer.
787 * @param y Line number of the first line to write.
788 * @param n Number of lines to write.
789 * @see ScreenshotCallback
791 static void HeightmapCallback(void *, void *buffer, uint y, uint, uint n)
793 uint8_t *buf = (uint8_t *)buffer;
794 while (n > 0) {
795 TileIndex ti = TileXY(Map::MaxX(), y);
796 for (uint x = Map::MaxX(); true; x--) {
797 *buf = 256 * TileHeight(ti) / (1 + _heightmap_highest_peak);
798 buf++;
799 if (x == 0) break;
800 ti = TileAddXY(ti, -1, 0);
802 y++;
803 n--;
808 * Make a heightmap of the current map.
809 * @param filename Filename to use for saving.
811 bool MakeHeightmapScreenshot(const char *filename)
813 Colour palette[256];
814 for (uint i = 0; i < lengthof(palette); i++) {
815 palette[i].a = 0xff;
816 palette[i].r = i;
817 palette[i].g = i;
818 palette[i].b = i;
821 _heightmap_highest_peak = 0;
822 for (TileIndex tile = 0; tile < Map::Size(); tile++) {
823 uint h = TileHeight(tile);
824 _heightmap_highest_peak = std::max(h, _heightmap_highest_peak);
827 return _cur_screenshot_format->proc(filename, HeightmapCallback, nullptr, Map::SizeX(), Map::SizeY(), 8, palette);
830 static ScreenshotType _confirmed_screenshot_type; ///< Screenshot type the current query is about to confirm.
833 * Callback on the confirmation window for huge screenshots.
834 * @param confirmed true on confirmation
836 static void ScreenshotConfirmationCallback(Window *, bool confirmed)
838 if (confirmed) MakeScreenshot(_confirmed_screenshot_type, {});
842 * Make a screenshot.
843 * Ask for confirmation first if the screenshot will be huge.
844 * @param t Screenshot type: World, defaultzoom, heightmap or viewport screenshot
845 * @see MakeScreenshot
847 void MakeScreenshotWithConfirm(ScreenshotType t)
849 Viewport vp;
850 SetupScreenshotViewport(t, &vp);
852 bool heightmap_or_minimap = t == SC_HEIGHTMAP || t == SC_MINIMAP;
853 uint64_t width = (heightmap_or_minimap ? Map::SizeX() : vp.width);
854 uint64_t height = (heightmap_or_minimap ? Map::SizeY() : vp.height);
856 if (width * height > 8192 * 8192) {
857 /* Ask for confirmation */
858 _confirmed_screenshot_type = t;
859 SetDParam(0, width);
860 SetDParam(1, height);
861 ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION, STR_WARNING_SCREENSHOT_SIZE_MESSAGE, nullptr, ScreenshotConfirmationCallback);
862 } else {
863 /* Less than 64M pixels, just do it */
864 MakeScreenshot(t, {});
869 * Make a screenshot.
870 * @param t the type of screenshot to make.
871 * @param name the name to give to the screenshot.
872 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
873 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
874 * @return true iff the screenshot was made successfully
876 static bool RealMakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
878 if (t == SC_VIEWPORT) {
879 /* First draw the dirty parts of the screen and only then change the name
880 * of the screenshot. This way the screenshot will always show the name
881 * of the previous screenshot in the 'successful' message instead of the
882 * name of the new screenshot (or an empty name). */
883 SetScreenshotWindowVisibility(true);
884 UndrawMouseCursor();
885 DrawDirtyBlocks();
886 SetScreenshotWindowVisibility(false);
889 _screenshot_name = name;
891 bool ret;
892 switch (t) {
893 case SC_VIEWPORT:
894 ret = MakeSmallScreenshot(false);
895 break;
897 case SC_CRASHLOG:
898 ret = MakeSmallScreenshot(true);
899 break;
901 case SC_ZOOMEDIN:
902 case SC_DEFAULTZOOM:
903 ret = MakeLargeWorldScreenshot(t, width, height);
904 break;
906 case SC_WORLD:
907 ret = MakeLargeWorldScreenshot(t);
908 break;
910 case SC_HEIGHTMAP: {
911 ret = MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME, _cur_screenshot_format->extension));
912 break;
915 case SC_MINIMAP:
916 ret = MakeMinimapWorldScreenshot();
917 break;
919 default:
920 NOT_REACHED();
923 if (ret) {
924 if (t == SC_HEIGHTMAP) {
925 SetDParamStr(0, _screenshot_name);
926 SetDParam(1, _heightmap_highest_peak);
927 ShowErrorMessage(STR_MESSAGE_HEIGHTMAP_SUCCESSFULLY, INVALID_STRING_ID, WL_WARNING);
928 } else {
929 SetDParamStr(0, _screenshot_name);
930 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY, INVALID_STRING_ID, WL_WARNING);
932 } else {
933 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED, INVALID_STRING_ID, WL_ERROR);
936 return ret;
940 * Schedule making a screenshot.
941 * Unconditionally take a screenshot of the requested type.
942 * @param t the type of screenshot to make.
943 * @param name the name to give to the screenshot.
944 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
945 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
946 * @return true iff the screenshot was successfully made.
947 * @see MakeScreenshotWithConfirm
949 bool MakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
951 if (t == SC_CRASHLOG) {
952 /* Video buffer might or might not be locked. */
953 VideoDriver::VideoBufferLocker lock;
955 return RealMakeScreenshot(t, name, width, height);
958 VideoDriver::GetInstance()->QueueOnMainThread([=] { // Capture by value to not break scope.
959 RealMakeScreenshot(t, name, width, height);
962 return true;
966 static void MinimapScreenCallback(void *, void *buf, uint y, uint pitch, uint n)
968 uint32_t *ubuf = (uint32_t *)buf;
969 uint num = (pitch * n);
970 for (uint i = 0; i < num; i++) {
971 uint row = y + (int)(i / pitch);
972 uint col = (Map::SizeX() - 1) - (i % pitch);
974 TileIndex tile = TileXY(col, row);
975 uint8_t val = GetSmallMapOwnerPixels(tile, GetTileType(tile), IncludeHeightmap::Never) & 0xFF;
977 uint32_t colour_buf = 0;
978 colour_buf = (_cur_palette.palette[val].b << 0);
979 colour_buf |= (_cur_palette.palette[val].g << 8);
980 colour_buf |= (_cur_palette.palette[val].r << 16);
982 *ubuf = colour_buf;
983 ubuf++; // Skip alpha
988 * Make a minimap screenshot.
990 bool MakeMinimapWorldScreenshot()
992 return _cur_screenshot_format->proc(MakeScreenshotName(SCREENSHOT_NAME, _cur_screenshot_format->extension), MinimapScreenCallback, nullptr, Map::SizeX(), Map::SizeY(), 32, _cur_palette.palette);