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/>.
8 /** @file screenshot.cpp The creation of screenshots! */
11 #include "core/backup_type.hpp"
12 #include "fileio_func.h"
13 #include "viewport_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"
25 #include "textbuf_gui.h"
26 #include "window_gui.h"
27 #include "window_func.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 uint _num_screenshot_formats
; ///< Number of available screenshot formats.
42 uint _cur_screenshot_format
; ///< Index of the currently selected screenshot format in #_screenshot_formats.
43 static std::string _screenshot_name
; ///< Filename of the screenshot file.
44 std::string _full_screenshot_path
; ///< Pathname of the screenshot file.
45 uint _heightmap_highest_peak
; ///< When saving a heightmap, this contains the highest peak on the map.
48 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
49 * @param userdata Pointer to user data.
50 * @param buf Destination buffer.
51 * @param y Line number of the first line to write.
52 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
53 * @param n Number of lines to write.
55 typedef void ScreenshotCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
);
58 * Function signature for a screenshot generation routine for one of the available formats.
59 * @param name Filename, including extension.
60 * @param callb Callback function for generating lines of pixels.
61 * @param userdata User data, passed on to \a callb.
62 * @param w Width of the image in pixels.
63 * @param h Height of the image in pixels.
64 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
65 * @param palette %Colour palette (for 8bpp images).
66 * @return File was written successfully.
68 typedef bool ScreenshotHandlerProc(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
);
70 /** Screenshot format information. */
71 struct ScreenshotFormat
{
72 const char *extension
; ///< File extension.
73 ScreenshotHandlerProc
*proc
; ///< Function for writing the screenshot.
76 #define MKCOLOUR(x) TO_LE32X(x)
78 /*************************************************
79 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
80 *************************************************/
82 /** BMP File Header (stored in little endian) */
83 PACK(struct BitmapFileHeader
{
89 static_assert(sizeof(BitmapFileHeader
) == 14);
91 /** BMP Info Header (stored in little endian) */
92 struct BitmapInfoHeader
{
94 int32_t width
, height
;
95 uint16_t planes
, bitcount
;
96 uint32_t compression
, sizeimage
, xpels
, ypels
, clrused
, clrimp
;
98 static_assert(sizeof(BitmapInfoHeader
) == 40);
100 /** Format of palette data in BMP header */
102 byte blue
, green
, red
, reserved
;
104 static_assert(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
== nullptr) 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
+ static_cast<size_t>(bytewidth
) * h
);
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);
159 /* Write file header and info header */
160 if (fwrite(&bfh
, sizeof(bfh
), 1, f
) != 1 || fwrite(&bih
, sizeof(bih
), 1, f
) != 1) {
165 if (pixelformat
== 8) {
166 /* Convert the palette to the windows format */
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
;
174 /* Write the palette */
175 if (fwrite(rq
, sizeof(rq
), 1, f
) != 1) {
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_t *buff
= MallocT
<uint8_t>(maxlines
* w
* pixelformat
/ 8); // buffer which is rendered to
185 uint8_t *line
= CallocT
<uint8_t>(bytewidth
); // one line, stored to file
187 /* Start at the bottom, since bitmaps are stored bottom up */
189 uint n
= std::min(h
, maxlines
);
192 /* Render the pixels */
193 callb(userdata
, buff
, h
, w
, n
);
195 /* Write each line */
197 if (pixelformat
== 8) {
198 /* Move to 'line', leave last few pixels in line zeroed */
199 memcpy(line
, buff
+ n
* w
, w
);
201 /* Convert from 'native' 32bpp to BMP-like 24bpp.
202 * Works for both big and little endian machines */
203 Colour
*src
= ((Colour
*)buff
) + n
* w
;
205 for (uint i
= 0; i
< w
; i
++) {
206 dst
[i
* 3 ] = src
[i
].b
;
207 dst
[i
* 3 + 1] = src
[i
].g
;
208 dst
[i
* 3 + 2] = src
[i
].r
;
212 if (fwrite(line
, bytewidth
, 1, f
) != 1) {
228 /*********************************************************
229 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
230 *********************************************************/
231 #if defined(WITH_PNG)
234 #ifdef PNG_TEXT_SUPPORTED
236 #include "newgrf_config.h"
237 #include "ai/ai_info.hpp"
238 #include "company_base.h"
239 #include "base_media_base.h"
240 #endif /* PNG_TEXT_SUPPORTED */
242 static void PNGAPI
png_my_error(png_structp png_ptr
, png_const_charp message
)
244 Debug(misc
, 0, "[libpng] error: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
245 longjmp(png_jmpbuf(png_ptr
), 1);
248 static void PNGAPI
png_my_warning(png_structp png_ptr
, png_const_charp message
)
250 Debug(misc
, 1, "[libpng] warning: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
254 * Generic .PNG file image writer.
255 * @param name Filename, including extension.
256 * @param callb Callback function for generating lines of pixels.
257 * @param userdata User data, passed on to \a callb.
258 * @param w Width of the image in pixels.
259 * @param h Height of the image in pixels.
260 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
261 * @param palette %Colour palette (for 8bpp images).
262 * @return File was written successfully.
263 * @see ScreenshotHandlerProc
265 static bool MakePNGImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
271 uint bpp
= pixelformat
/ 8;
275 /* only implemented for 8bit and 32bit images so far. */
276 if (pixelformat
!= 8 && pixelformat
!= 32) return false;
278 f
= fopen(name
, "wb");
279 if (f
== nullptr) return false;
281 png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
, const_cast<char *>(name
), png_my_error
, png_my_warning
);
283 if (png_ptr
== nullptr) {
288 info_ptr
= png_create_info_struct(png_ptr
);
289 if (info_ptr
== nullptr) {
290 png_destroy_write_struct(&png_ptr
, (png_infopp
)nullptr);
295 if (setjmp(png_jmpbuf(png_ptr
))) {
296 png_destroy_write_struct(&png_ptr
, &info_ptr
);
301 png_init_io(png_ptr
, f
);
303 png_set_filter(png_ptr
, 0, PNG_FILTER_NONE
);
305 png_set_IHDR(png_ptr
, info_ptr
, w
, h
, 8, pixelformat
== 8 ? PNG_COLOR_TYPE_PALETTE
: PNG_COLOR_TYPE_RGB
,
306 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_DEFAULT
, PNG_FILTER_TYPE_DEFAULT
);
308 #ifdef PNG_TEXT_SUPPORTED
309 /* Try to add some game metadata to the PNG screenshot so
310 * it's more useful for debugging and archival purposes. */
311 png_text_struct text
[2];
312 memset(text
, 0, sizeof(text
));
313 text
[0].key
= const_cast<char *>("Software");
314 text
[0].text
= const_cast<char *>(_openttd_revision
);
315 text
[0].text_length
= strlen(_openttd_revision
);
316 text
[0].compression
= PNG_TEXT_COMPRESSION_NONE
;
319 message
.reserve(1024);
320 fmt::format_to(std::back_inserter(message
), "Graphics set: {} ({})\n", BaseGraphics::GetUsedSet()->name
, BaseGraphics::GetUsedSet()->version
);
321 message
+= "NewGRFs:\n";
322 for (const GRFConfig
*c
= _game_mode
== GM_MENU
? nullptr : _grfconfig
; c
!= nullptr; c
= c
->next
) {
323 fmt::format_to(std::back_inserter(message
), "{:08X} {} {}\n", BSWAP32(c
->ident
.grfid
), FormatArrayAsHex(c
->ident
.md5sum
), c
->filename
);
325 message
+= "\nCompanies:\n";
326 for (const Company
*c
: Company::Iterate()) {
327 if (c
->ai_info
== nullptr) {
328 fmt::format_to(std::back_inserter(message
), "{:2d}: Human\n", (int)c
->index
);
330 fmt::format_to(std::back_inserter(message
), "{:2d}: {} (v{})\n", (int)c
->index
, c
->ai_info
->GetName(), c
->ai_info
->GetVersion());
333 text
[1].key
= const_cast<char *>("Description");
334 text
[1].text
= const_cast<char *>(message
.c_str());
335 text
[1].text_length
= message
.size();
336 text
[1].compression
= PNG_TEXT_COMPRESSION_zTXt
;
337 png_set_text(png_ptr
, info_ptr
, text
, 2);
338 #endif /* PNG_TEXT_SUPPORTED */
340 if (pixelformat
== 8) {
341 /* convert the palette to the .PNG format. */
342 for (i
= 0; i
!= 256; i
++) {
343 rq
[i
].red
= palette
[i
].r
;
344 rq
[i
].green
= palette
[i
].g
;
345 rq
[i
].blue
= palette
[i
].b
;
348 png_set_PLTE(png_ptr
, info_ptr
, rq
, 256);
351 png_write_info(png_ptr
, info_ptr
);
352 png_set_flush(png_ptr
, 512);
354 if (pixelformat
== 32) {
357 /* Save exact colour/alpha resolution */
363 png_set_sBIT(png_ptr
, info_ptr
, &sig_bit
);
365 #if TTD_ENDIAN == TTD_LITTLE_ENDIAN
366 png_set_bgr(png_ptr
);
367 png_set_filler(png_ptr
, 0, PNG_FILLER_AFTER
);
369 png_set_filler(png_ptr
, 0, PNG_FILLER_BEFORE
);
370 #endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
373 /* use by default 64k temp memory */
374 maxlines
= Clamp(65536 / w
, 16, 128);
376 /* now generate the bitmap bits */
377 void *buff
= CallocT
<uint8_t>(static_cast<size_t>(w
) * maxlines
* bpp
); // by default generate 128 lines at a time.
381 /* determine # lines to write */
382 n
= std::min(h
- y
, maxlines
);
384 /* render the pixels into the buffer */
385 callb(userdata
, buff
, y
, w
, n
);
388 /* write them to png */
389 for (i
= 0; i
!= n
; i
++) {
390 png_write_row(png_ptr
, (png_bytep
)buff
+ i
* w
* bpp
);
394 png_write_end(png_ptr
, info_ptr
);
395 png_destroy_write_struct(&png_ptr
, &info_ptr
);
401 #endif /* WITH_PNG */
404 /*************************************************
405 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
406 *************************************************/
408 /** Definition of a PCX file header. */
417 byte pal_small
[16 * 3];
426 static_assert(sizeof(PcxHeader
) == 128);
429 * Generic .PCX file image writer.
430 * @param name Filename, including extension.
431 * @param callb Callback function for generating lines of pixels.
432 * @param userdata User data, passed on to \a callb.
433 * @param w Width of the image in pixels.
434 * @param h Height of the image in pixels.
435 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
436 * @param palette %Colour palette (for 8bpp images).
437 * @return File was written successfully.
438 * @see ScreenshotHandlerProc
440 static bool MakePCXImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
448 if (pixelformat
== 32) {
449 Debug(misc
, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
452 if (pixelformat
!= 8 || w
== 0) return false;
454 f
= fopen(name
, "wb");
455 if (f
== nullptr) return false;
457 memset(&pcx
, 0, sizeof(pcx
));
459 /* setup pcx header */
460 pcx
.manufacturer
= 10;
464 pcx
.xmax
= TO_LE16(w
- 1);
465 pcx
.ymax
= TO_LE16(h
- 1);
466 pcx
.hdpi
= TO_LE16(320);
467 pcx
.vdpi
= TO_LE16(320);
470 pcx
.cpal
= TO_LE16(1);
471 pcx
.width
= pcx
.pitch
= TO_LE16(w
);
472 pcx
.height
= TO_LE16(h
);
474 /* write pcx header */
475 if (fwrite(&pcx
, sizeof(pcx
), 1, f
) != 1) {
480 /* use by default 64k temp memory */
481 maxlines
= Clamp(65536 / w
, 16, 128);
483 /* now generate the bitmap bits */
484 uint8_t *buff
= CallocT
<uint8_t>(static_cast<size_t>(w
) * maxlines
); // by default generate 128 lines at a time.
488 /* determine # lines to write */
489 uint n
= std::min(h
- y
, maxlines
);
492 /* render the pixels into the buffer */
493 callb(userdata
, buff
, y
, w
, n
);
496 /* write them to pcx */
497 for (i
= 0; i
!= n
; i
++) {
498 const uint8_t *bufp
= buff
+ i
* w
;
499 byte runchar
= bufp
[0];
503 /* for each pixel... */
504 for (j
= 1; j
< w
; j
++) {
505 uint8_t ch
= bufp
[j
];
507 if (ch
!= runchar
|| runcount
>= 0x3f) {
508 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
509 if (fputc(0xC0 | runcount
, f
) == EOF
) {
515 if (fputc(runchar
, f
) == EOF
) {
526 /* write remaining bytes.. */
527 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
528 if (fputc(0xC0 | runcount
, f
) == EOF
) {
534 if (fputc(runchar
, f
) == EOF
) {
544 /* write 8-bit colour palette */
545 if (fputc(12, f
) == EOF
) {
550 /* Palette is word-aligned, copy it to a temporary byte array */
553 for (uint i
= 0; i
< 256; i
++) {
554 tmp
[i
* 3 + 0] = palette
[i
].r
;
555 tmp
[i
* 3 + 1] = palette
[i
].g
;
556 tmp
[i
* 3 + 2] = palette
[i
].b
;
558 success
= fwrite(tmp
, sizeof(tmp
), 1, f
) == 1;
565 /*************************************************
566 **** GENERIC SCREENSHOT CODE
567 *************************************************/
569 /** Available screenshot formats. */
570 static const ScreenshotFormat _screenshot_formats
[] = {
571 #if defined(WITH_PNG)
572 {"png", &MakePNGImage
},
574 {"bmp", &MakeBMPImage
},
575 {"pcx", &MakePCXImage
},
578 /** Get filename extension of current screenshot file format. */
579 const char *GetCurrentScreenshotExtension()
581 return _screenshot_formats
[_cur_screenshot_format
].extension
;
584 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
585 void InitializeScreenshotFormats()
588 for (uint i
= 0; i
< lengthof(_screenshot_formats
); i
++) {
589 if (_screenshot_format_name
.compare(_screenshot_formats
[i
].extension
) == 0) {
594 _cur_screenshot_format
= j
;
595 _num_screenshot_formats
= lengthof(_screenshot_formats
);
599 * Callback of the screenshot generator that dumps the current video buffer.
600 * @see ScreenshotCallback
602 static void CurrentScreenCallback(void *, void *buf
, uint y
, uint pitch
, uint n
)
604 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
605 void *src
= blitter
->MoveTo(_screen
.dst_ptr
, 0, y
);
606 blitter
->CopyImageToBuffer(src
, buf
, _screen
.width
, n
, pitch
);
610 * generate a large piece of the world
611 * @param userdata Viewport area to draw
612 * @param buf Videobuffer with same bitdepth as current blitter
613 * @param y First line to render
614 * @param pitch Pitch of the videobuffer
615 * @param n Number of lines to render
617 static void LargeWorldCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
)
619 Viewport
*vp
= (Viewport
*)userdata
;
623 /* We are no longer rendering to the screen */
624 DrawPixelInfo old_screen
= _screen
;
625 bool old_disable_anim
= _screen_disable_anim
;
627 _screen
.dst_ptr
= buf
;
628 _screen
.width
= pitch
;
630 _screen
.pitch
= pitch
;
631 _screen_disable_anim
= true;
633 AutoRestoreBackup
dpi_backup(_cur_dpi
, &dpi
);
637 dpi
.width
= vp
->width
;
639 dpi
.zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
643 /* Render viewport in blocks of 1600 pixels width */
645 while (vp
->width
- left
!= 0) {
646 wx
= std::min(vp
->width
- left
, 1600);
650 ScaleByZoom(left
- wx
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
651 ScaleByZoom(y
- vp
->top
, vp
->zoom
) + vp
->virtual_top
,
652 ScaleByZoom(left
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
653 ScaleByZoom((y
+ n
) - vp
->top
, vp
->zoom
) + vp
->virtual_top
657 /* Switch back to rendering to the screen */
658 _screen
= old_screen
;
659 _screen_disable_anim
= old_disable_anim
;
663 * Construct a pathname for a screenshot file.
664 * @param default_fn Default filename.
665 * @param ext Extension to use.
666 * @param crashlog Create path for crash.png
667 * @return Pathname for a screenshot file.
669 static const char *MakeScreenshotName(const char *default_fn
, const char *ext
, bool crashlog
= false)
671 bool generate
= _screenshot_name
.empty();
674 if (_game_mode
== GM_EDITOR
|| _game_mode
== GM_MENU
|| _local_company
== COMPANY_SPECTATOR
) {
675 _screenshot_name
= default_fn
;
677 _screenshot_name
= GenerateDefaultSaveName();
681 /* Handle user-specified filenames ending in # with automatic numbering */
682 if (_screenshot_name
.ends_with("#")) {
684 _screenshot_name
.pop_back();
687 size_t len
= _screenshot_name
.size();
688 /* Add extension to screenshot file */
689 _screenshot_name
+= fmt::format(".{}", ext
);
691 const char *screenshot_dir
= crashlog
? _personal_dir
.c_str() : FiosGetScreenshotDir();
693 for (uint serial
= 1;; serial
++) {
694 _full_screenshot_path
= fmt::format("{}{}", screenshot_dir
, _screenshot_name
);
696 if (!generate
) break; // allow overwriting of non-automatic filenames
697 if (!FileExists(_full_screenshot_path
)) break;
698 /* If file exists try another one with same name, but just with a higher index */
699 _screenshot_name
.erase(len
);
700 _screenshot_name
+= fmt::format("#{}.{}", serial
, ext
);
703 return _full_screenshot_path
.c_str();
706 /** Make a screenshot of the current screen. */
707 static bool MakeSmallScreenshot(bool crashlog
)
709 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
710 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
, crashlog
), CurrentScreenCallback
, nullptr, _screen
.width
, _screen
.height
,
711 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
715 * Configure a Viewport for rendering (a part of) the map into a screenshot.
716 * @param t Screenshot type
717 * @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).
718 * @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).
719 * @param[out] vp Result viewport
721 void SetupScreenshotViewport(ScreenshotType t
, Viewport
*vp
, uint32_t width
, uint32_t height
)
726 assert(width
== 0 && height
== 0);
728 Window
*w
= GetMainWindow();
729 vp
->virtual_left
= w
->viewport
->virtual_left
;
730 vp
->virtual_top
= w
->viewport
->virtual_top
;
731 vp
->virtual_width
= w
->viewport
->virtual_width
;
732 vp
->virtual_height
= w
->viewport
->virtual_height
;
734 /* Compute pixel coordinates */
737 vp
->width
= _screen
.width
;
738 vp
->height
= _screen
.height
;
739 vp
->overlay
= w
->viewport
->overlay
;
743 assert(width
== 0 && height
== 0);
745 /* Determine world coordinates of screenshot */
746 vp
->zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
748 TileIndex north_tile
= _settings_game
.construction
.freeform_edges
? TileXY(1, 1) : TileXY(0, 0);
749 TileIndex south_tile
= Map::Size() - 1;
751 /* We need to account for a hill or high building at tile 0,0. */
752 int extra_height_top
= TilePixelHeight(north_tile
) + 150;
753 /* If there is a hill at the bottom don't create a large black area. */
754 int reclaim_height_bottom
= TilePixelHeight(south_tile
);
756 vp
->virtual_left
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, 0).x
;
757 vp
->virtual_top
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, extra_height_top
).y
;
758 vp
->virtual_width
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, 0).x
- vp
->virtual_left
+ 1;
759 vp
->virtual_height
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, reclaim_height_bottom
).y
- vp
->virtual_top
+ 1;
761 /* Compute pixel coordinates */
764 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
765 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
766 vp
->overlay
= nullptr;
770 vp
->zoom
= (t
== SC_ZOOMEDIN
) ? _settings_client
.gui
.zoom_min
: ZOOM_LVL_VIEWPORT
;
772 Window
*w
= GetMainWindow();
773 vp
->virtual_left
= w
->viewport
->virtual_left
;
774 vp
->virtual_top
= w
->viewport
->virtual_top
;
776 if (width
== 0 || height
== 0) {
777 vp
->virtual_width
= w
->viewport
->virtual_width
;
778 vp
->virtual_height
= w
->viewport
->virtual_height
;
780 vp
->virtual_width
= width
<< vp
->zoom
;
781 vp
->virtual_height
= height
<< vp
->zoom
;
784 /* Compute pixel coordinates */
787 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
788 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
789 vp
->overlay
= nullptr;
796 * Make a screenshot of the map.
797 * @param t Screenshot type: World or viewport screenshot
798 * @param width the width of the screenshot of, or 0 for current viewport width.
799 * @param height the height of the screenshot of, or 0 for current viewport height.
800 * @return true on success
802 static bool MakeLargeWorldScreenshot(ScreenshotType t
, uint32_t width
= 0, uint32_t height
= 0)
805 SetupScreenshotViewport(t
, &vp
, width
, height
);
807 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
808 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
), LargeWorldCallback
, &vp
, vp
.width
, vp
.height
,
809 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
813 * Callback for generating a heightmap. Supports 8bpp grayscale only.
814 * @param buffer Destination buffer.
815 * @param y Line number of the first line to write.
816 * @param n Number of lines to write.
817 * @see ScreenshotCallback
819 static void HeightmapCallback(void *, void *buffer
, uint y
, uint
, uint n
)
821 byte
*buf
= (byte
*)buffer
;
823 TileIndex ti
= TileXY(Map::MaxX(), y
);
824 for (uint x
= Map::MaxX(); true; x
--) {
825 *buf
= 256 * TileHeight(ti
) / (1 + _heightmap_highest_peak
);
828 ti
= TILE_ADDXY(ti
, -1, 0);
836 * Make a heightmap of the current map.
837 * @param filename Filename to use for saving.
839 bool MakeHeightmapScreenshot(const char *filename
)
842 for (uint i
= 0; i
< lengthof(palette
); i
++) {
849 _heightmap_highest_peak
= 0;
850 for (TileIndex tile
= 0; tile
< Map::Size(); tile
++) {
851 uint h
= TileHeight(tile
);
852 _heightmap_highest_peak
= std::max(h
, _heightmap_highest_peak
);
855 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
856 return sf
->proc(filename
, HeightmapCallback
, nullptr, Map::SizeX(), Map::SizeY(), 8, palette
);
859 static ScreenshotType _confirmed_screenshot_type
; ///< Screenshot type the current query is about to confirm.
862 * Callback on the confirmation window for huge screenshots.
863 * @param confirmed true on confirmation
865 static void ScreenshotConfirmationCallback(Window
*, bool confirmed
)
867 if (confirmed
) MakeScreenshot(_confirmed_screenshot_type
, {});
872 * Ask for confirmation first if the screenshot will be huge.
873 * @param t Screenshot type: World, defaultzoom, heightmap or viewport screenshot
874 * @see MakeScreenshot
876 void MakeScreenshotWithConfirm(ScreenshotType t
)
879 SetupScreenshotViewport(t
, &vp
);
881 bool heightmap_or_minimap
= t
== SC_HEIGHTMAP
|| t
== SC_MINIMAP
;
882 uint64_t width
= (heightmap_or_minimap
? Map::SizeX() : vp
.width
);
883 uint64_t height
= (heightmap_or_minimap
? Map::SizeY() : vp
.height
);
885 if (width
* height
> 8192 * 8192) {
886 /* Ask for confirmation */
887 _confirmed_screenshot_type
= t
;
889 SetDParam(1, height
);
890 ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION
, STR_WARNING_SCREENSHOT_SIZE_MESSAGE
, nullptr, ScreenshotConfirmationCallback
);
892 /* Less than 64M pixels, just do it */
893 MakeScreenshot(t
, {});
899 * @param t the type of screenshot to make.
900 * @param name the name to give to the screenshot.
901 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
902 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
903 * @return true iff the screenshot was made successfully
905 static bool RealMakeScreenshot(ScreenshotType t
, std::string name
, uint32_t width
, uint32_t height
)
907 if (t
== SC_VIEWPORT
) {
908 /* First draw the dirty parts of the screen and only then change the name
909 * of the screenshot. This way the screenshot will always show the name
910 * of the previous screenshot in the 'successful' message instead of the
911 * name of the new screenshot (or an empty name). */
912 SetScreenshotWindowVisibility(true);
915 SetScreenshotWindowVisibility(false);
918 _screenshot_name
= name
;
923 ret
= MakeSmallScreenshot(false);
927 ret
= MakeSmallScreenshot(true);
932 ret
= MakeLargeWorldScreenshot(t
, width
, height
);
936 ret
= MakeLargeWorldScreenshot(t
);
940 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
941 ret
= MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME
, sf
->extension
));
946 ret
= MakeMinimapWorldScreenshot();
954 if (t
== SC_HEIGHTMAP
) {
955 SetDParamStr(0, _screenshot_name
);
956 SetDParam(1, _heightmap_highest_peak
);
957 ShowErrorMessage(STR_MESSAGE_HEIGHTMAP_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
959 SetDParamStr(0, _screenshot_name
);
960 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
963 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
970 * Schedule making a screenshot.
971 * Unconditionally take a screenshot of the requested type.
972 * @param t the type of screenshot to make.
973 * @param name the name to give to the screenshot.
974 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
975 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
976 * @return true iff the screenshot was successfully made.
977 * @see MakeScreenshotWithConfirm
979 bool MakeScreenshot(ScreenshotType t
, std::string name
, uint32_t width
, uint32_t height
)
981 if (t
== SC_CRASHLOG
) {
982 /* Video buffer might or might not be locked. */
983 VideoDriver::VideoBufferLocker lock
;
985 return RealMakeScreenshot(t
, name
, width
, height
);
988 VideoDriver::GetInstance()->QueueOnMainThread([=] { // Capture by value to not break scope.
989 RealMakeScreenshot(t
, name
, width
, height
);
996 static void MinimapScreenCallback(void *, void *buf
, uint y
, uint pitch
, uint n
)
998 uint32_t *ubuf
= (uint32_t *)buf
;
999 uint num
= (pitch
* n
);
1000 for (uint i
= 0; i
< num
; i
++) {
1001 uint row
= y
+ (int)(i
/ pitch
);
1002 uint col
= (Map::SizeX() - 1) - (i
% pitch
);
1004 TileIndex tile
= TileXY(col
, row
);
1005 byte val
= GetSmallMapOwnerPixels(tile
, GetTileType(tile
), IncludeHeightmap::Never
) & 0xFF;
1007 uint32_t colour_buf
= 0;
1008 colour_buf
= (_cur_palette
.palette
[val
].b
<< 0);
1009 colour_buf
|= (_cur_palette
.palette
[val
].g
<< 8);
1010 colour_buf
|= (_cur_palette
.palette
[val
].r
<< 16);
1013 ubuf
++; // Skip alpha
1018 * Make a minimap screenshot.
1020 bool MakeMinimapWorldScreenshot()
1022 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
1023 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
), MinimapScreenCallback
, nullptr, Map::SizeX(), Map::SizeY(), 32, _cur_palette
.palette
);