OpenTTD Source 20250218-master-g53dd1258a7
screenshot.cpp
Go to the documentation of this file.
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 */
7
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 "saveload/saveload.h"
20#include "company_func.h"
21#include "strings_func.h"
22#include "error.h"
23#include "textbuf_gui.h"
24#include "window_gui.h"
25#include "window_func.h"
26#include "tile_map.h"
27#include "landscape.h"
29#include "smallmap_gui.h"
30#include "screenshot_type.h"
31
32#include "table/strings.h"
33
34#include "safeguards.h"
35
36static const char * const SCREENSHOT_NAME = "screenshot";
37static const char * const HEIGHTMAP_NAME = "heightmap";
38
40static std::string _screenshot_name;
43
50{
52 if (providers.empty()) return nullptr;
53
54 auto it = std::ranges::find_if(providers, [](const auto &p) { return p->GetName() == _screenshot_format_name; });
55 if (it != std::end(providers)) return *it;
56
57 return providers.front();
58}
59
62{
63 auto provider = GetScreenshotProvider();
64 if (provider == nullptr) return {};
65
66 return provider->GetName();
67}
68
73static void CurrentScreenCallback(void *, void *buf, uint y, uint pitch, uint n)
74{
76 void *src = blitter->MoveTo(_screen.dst_ptr, 0, y);
77 blitter->CopyImageToBuffer(src, buf, _screen.width, n, pitch);
78}
79
88static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
89{
90 Viewport *vp = (Viewport *)userdata;
91 DrawPixelInfo dpi;
92 int wx, left;
93
94 /* We are no longer rendering to the screen */
95 DrawPixelInfo old_screen = _screen;
96 bool old_disable_anim = _screen_disable_anim;
97
98 _screen.dst_ptr = buf;
99 _screen.width = pitch;
100 _screen.height = n;
101 _screen.pitch = pitch;
103
104 AutoRestoreBackup dpi_backup(_cur_dpi, &dpi);
105
106 dpi.dst_ptr = buf;
107 dpi.height = n;
108 dpi.width = vp->width;
109 dpi.pitch = pitch;
110 dpi.zoom = ZOOM_LVL_WORLD_SCREENSHOT;
111 dpi.left = 0;
112 dpi.top = y;
113
114 /* Render viewport in blocks of 1600 pixels width */
115 left = 0;
116 while (vp->width - left != 0) {
117 wx = std::min(vp->width - left, 1600);
118 left += wx;
119
120 ViewportDoDraw(vp,
121 ScaleByZoom(left - wx - vp->left, vp->zoom) + vp->virtual_left,
122 ScaleByZoom(y - vp->top, vp->zoom) + vp->virtual_top,
123 ScaleByZoom(left - vp->left, vp->zoom) + vp->virtual_left,
124 ScaleByZoom((y + n) - vp->top, vp->zoom) + vp->virtual_top
125 );
126 }
127
128 /* Switch back to rendering to the screen */
129 _screen = old_screen;
130 _screen_disable_anim = old_disable_anim;
131}
132
140static const char *MakeScreenshotName(std::string_view default_fn, std::string_view ext, bool crashlog = false)
141{
142 bool generate = _screenshot_name.empty();
143
144 if (generate) {
145 if (_game_mode == GM_EDITOR || _game_mode == GM_MENU || _local_company == COMPANY_SPECTATOR) {
146 _screenshot_name = default_fn;
147 } else {
149 }
150 }
151
152 /* Handle user-specified filenames ending in # with automatic numbering */
153 if (_screenshot_name.ends_with("#")) {
154 generate = true;
155 _screenshot_name.pop_back();
156 }
157
158 size_t len = _screenshot_name.size();
159 /* Add extension to screenshot file */
160 _screenshot_name += fmt::format(".{}", ext);
161
162 const char *screenshot_dir = crashlog ? _personal_dir.c_str() : FiosGetScreenshotDir();
163
164 for (uint serial = 1;; serial++) {
165 _full_screenshot_path = fmt::format("{}{}", screenshot_dir, _screenshot_name);
166
167 if (!generate) break; // allow overwriting of non-automatic filenames
169 /* If file exists try another one with same name, but just with a higher index */
170 _screenshot_name.erase(len);
171 _screenshot_name += fmt::format("#{}.{}", serial, ext);
172 }
173
174 return _full_screenshot_path.c_str();
175}
176
178static bool MakeSmallScreenshot(bool crashlog)
179{
180 auto provider = GetScreenshotProvider();
181 if (provider == nullptr) return false;
182
183 return provider->MakeImage(MakeScreenshotName(SCREENSHOT_NAME, provider->GetName(), crashlog), CurrentScreenCallback, nullptr, _screen.width, _screen.height,
185}
186
194void SetupScreenshotViewport(ScreenshotType t, Viewport *vp, uint32_t width, uint32_t height)
195{
196 switch(t) {
197 case SC_VIEWPORT:
198 case SC_CRASHLOG: {
199 assert(width == 0 && height == 0);
200
201 Window *w = GetMainWindow();
206
207 /* Compute pixel coordinates */
208 vp->left = 0;
209 vp->top = 0;
210 vp->width = _screen.width;
211 vp->height = _screen.height;
212 vp->overlay = w->viewport->overlay;
213 break;
214 }
215 case SC_WORLD: {
216 assert(width == 0 && height == 0);
217
218 /* Determine world coordinates of screenshot */
220
222 TileIndex south_tile{Map::Size() - 1};
223
224 /* We need to account for a hill or high building at tile 0,0. */
225 int extra_height_top = TilePixelHeight(north_tile) + 150;
226 /* If there is a hill at the bottom don't create a large black area. */
227 int reclaim_height_bottom = TilePixelHeight(south_tile);
228
229 vp->virtual_left = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, 0).x;
230 vp->virtual_top = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(north_tile) * TILE_SIZE, extra_height_top).y;
231 vp->virtual_width = RemapCoords(TileX(north_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, 0).x - vp->virtual_left + 1;
232 vp->virtual_height = RemapCoords(TileX(south_tile) * TILE_SIZE, TileY(south_tile) * TILE_SIZE, reclaim_height_bottom).y - vp->virtual_top + 1;
233
234 /* Compute pixel coordinates */
235 vp->left = 0;
236 vp->top = 0;
237 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
238 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
239 vp->overlay = nullptr;
240 break;
241 }
242 default: {
244
245 Window *w = GetMainWindow();
248
249 if (width == 0 || height == 0) {
252 } else {
253 vp->virtual_width = width << vp->zoom;
254 vp->virtual_height = height << vp->zoom;
255 }
256
257 /* Compute pixel coordinates */
258 vp->left = 0;
259 vp->top = 0;
260 vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
261 vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
262 vp->overlay = nullptr;
263 break;
264 }
265 }
266}
267
275static bool MakeLargeWorldScreenshot(ScreenshotType t, uint32_t width = 0, uint32_t height = 0)
276{
277 auto provider = GetScreenshotProvider();
278 if (provider == nullptr) return false;
279
280 Viewport vp;
281 SetupScreenshotViewport(t, &vp, width, height);
282
283 return provider->MakeImage(MakeScreenshotName(SCREENSHOT_NAME, provider->GetName()), LargeWorldCallback, &vp, vp.width, vp.height,
285}
286
294static void HeightmapCallback(void *, void *buffer, uint y, uint, uint n)
295{
296 uint8_t *buf = (uint8_t *)buffer;
297 while (n > 0) {
298 TileIndex ti = TileXY(Map::MaxX(), y);
299 for (uint x = Map::MaxX(); true; x--) {
300 *buf = 256 * TileHeight(ti) / (1 + _heightmap_highest_peak);
301 buf++;
302 if (x == 0) break;
303 ti = TileAddXY(ti, -1, 0);
304 }
305 y++;
306 n--;
307 }
308}
309
314bool MakeHeightmapScreenshot(const char *filename)
315{
316 auto provider = GetScreenshotProvider();
317 if (provider == nullptr) return false;
318
319 Colour palette[256];
320 for (uint i = 0; i < lengthof(palette); i++) {
321 palette[i].a = 0xff;
322 palette[i].r = i;
323 palette[i].g = i;
324 palette[i].b = i;
325 }
326
328 for (const auto tile : Map::Iterate()) {
329 uint h = TileHeight(tile);
331 }
332
333 return provider->MakeImage(filename, HeightmapCallback, nullptr, Map::SizeX(), Map::SizeY(), 8, palette);
334}
335
337
342static void ScreenshotConfirmationCallback(Window *, bool confirmed)
343{
344 if (confirmed) MakeScreenshot(_confirmed_screenshot_type, {});
345}
346
354{
355 Viewport vp;
357
358 bool heightmap_or_minimap = t == SC_HEIGHTMAP || t == SC_MINIMAP;
359 uint64_t width = (heightmap_or_minimap ? Map::SizeX() : vp.width);
360 uint64_t height = (heightmap_or_minimap ? Map::SizeY() : vp.height);
361
362 if (width * height > 8192 * 8192) {
363 /* Ask for confirmation */
365 ShowQuery(
366 GetEncodedString(STR_WARNING_SCREENSHOT_SIZE_CAPTION),
367 GetEncodedString(STR_WARNING_SCREENSHOT_SIZE_MESSAGE, width, height), nullptr, ScreenshotConfirmationCallback);
368 } else {
369 /* Less than 64M pixels, just do it */
370 MakeScreenshot(t, {});
371 }
372}
373
382static bool RealMakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
383{
384 if (t == SC_VIEWPORT) {
385 /* First draw the dirty parts of the screen and only then change the name
386 * of the screenshot. This way the screenshot will always show the name
387 * of the previous screenshot in the 'successful' message instead of the
388 * name of the new screenshot (or an empty name). */
390 UndrawMouseCursor();
393 }
394
395 _screenshot_name = name;
396
397 bool ret;
398 switch (t) {
399 case SC_VIEWPORT:
400 ret = MakeSmallScreenshot(false);
401 break;
402
403 case SC_CRASHLOG:
404 ret = MakeSmallScreenshot(true);
405 break;
406
407 case SC_ZOOMEDIN:
408 case SC_DEFAULTZOOM:
409 ret = MakeLargeWorldScreenshot(t, width, height);
410 break;
411
412 case SC_WORLD:
414 break;
415
416 case SC_HEIGHTMAP: {
417 auto provider = GetScreenshotProvider();
418 if (provider == nullptr) {
419 ret = false;
420 } else {
421 ret = MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME, provider->GetName()));
422 }
423 break;
424 }
425
426 case SC_MINIMAP:
428 break;
429
430 default:
431 NOT_REACHED();
432 }
433
434 if (ret) {
435 if (t == SC_HEIGHTMAP) {
436 ShowErrorMessage(GetEncodedString(STR_MESSAGE_HEIGHTMAP_SUCCESSFULLY, _screenshot_name, _heightmap_highest_peak), {}, WL_WARNING);
437 } else {
438 ShowErrorMessage(GetEncodedString(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY, _screenshot_name), {}, WL_WARNING);
439 }
440 } else {
441 ShowErrorMessage(GetEncodedString(STR_ERROR_SCREENSHOT_FAILED), {}, WL_ERROR);
442 }
443
444 return ret;
445}
446
457bool MakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
458{
459 if (t == SC_CRASHLOG) {
460 /* Video buffer might or might not be locked. */
462
463 return RealMakeScreenshot(t, name, width, height);
464 }
465
466 VideoDriver::GetInstance()->QueueOnMainThread([=] { // Capture by value to not break scope.
467 RealMakeScreenshot(t, name, width, height);
468 });
469
470 return true;
471}
472
473
474static void MinimapScreenCallback(void *, void *buf, uint y, uint pitch, uint n)
475{
476 uint32_t *ubuf = (uint32_t *)buf;
477 uint num = (pitch * n);
478 for (uint i = 0; i < num; i++) {
479 uint row = y + (int)(i / pitch);
480 uint col = (Map::SizeX() - 1) - (i % pitch);
481
482 TileIndex tile = TileXY(col, row);
483 uint8_t val = GetSmallMapOwnerPixels(tile, GetTileType(tile), IncludeHeightmap::Never) & 0xFF;
484
485 uint32_t colour_buf = 0;
486 colour_buf = (_cur_palette.palette[val].b << 0);
487 colour_buf |= (_cur_palette.palette[val].g << 8);
488 colour_buf |= (_cur_palette.palette[val].r << 16);
489
490 *ubuf = colour_buf;
491 ubuf++; // Skip alpha
492 }
493}
494
499{
500 auto provider = GetScreenshotProvider();
501 if (provider == nullptr) return false;
502
503 return provider->MakeImage(MakeScreenshotName(SCREENSHOT_NAME, provider->GetName()), MinimapScreenCallback, nullptr, Map::SizeX(), Map::SizeY(), 32, _cur_palette.palette);
504}
Class for backupping variables and making sure they are restored later.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:138
How all blitters should look like.
Definition base.hpp:29
virtual void * MoveTo(void *video, int x, int y)=0
Move the destination pointer the requested amount x and y, keeping in mind any pitch and bpp of the r...
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual void CopyImageToBuffer(const void *video, void *dst, int width, int height, int dst_pitch)=0
Copy from the screen to a buffer in a palette format for 8bpp and RGBA format for 32bpp.
static std::vector< TProviderType * > & GetProviders()
Get the currently known sound loaders.
Base interface for a SoundLoader implementation.
void QueueOnMainThread(std::function< void()> &&func)
Queue a function to be called on the main thread with game state lock held and video buffer locked.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Functions related to errors.
@ WL_WARNING
Other information.
Definition error.h:25
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, const CommandCost &cc)
Display an error message in a window.
Factory to 'query' all available blitters.
std::string _personal_dir
custom directory for personal settings, saves, newgrf, etc.
Definition fileio.cpp:869
bool FileExists(const std::string &filename)
Test whether the given filename exists.
Definition fileio.cpp:133
Functions for Standard In/Out file operations.
const char * FiosGetScreenshotDir()
Get the directory for screenshots.
Definition fios.cpp:600
bool _screen_disable_anim
Disable palette animation (important for 32bpp-anim blitter during giant screenshot)
Definition gfx.cpp:46
Functions related to the gfx engine.
Palette _cur_palette
Current palette.
Definition palette.cpp:24
void DrawDirtyBlocks()
Repaints the rectangle blocks which are marked as 'dirty'.
Definition gfx.cpp:1397
Functions related to OTTD's landscape.
Point RemapCoords(int x, int y, int z)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:79
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:469
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:372
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:424
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:414
void ShowQuery(EncodedString &&caption, EncodedString &&message, Window *parent, QueryCallbackProc *callback, bool focus)
Show a confirmation window with standard 'yes' and 'no' buttons The window is aligned to the centre o...
A number of safeguards to prevent using unsafe methods.
std::string GenerateDefaultSaveName()
Get the default name for a savegame or screenshot.
Functions/types related to saving and loading games.
static void CurrentScreenCallback(void *, void *buf, uint y, uint pitch, uint n)
Callback of the screenshot generator that dumps the current video buffer.
static void ScreenshotConfirmationCallback(Window *, bool confirmed)
Callback on the confirmation window for huge screenshots.
void MakeScreenshotWithConfirm(ScreenshotType t)
Make a screenshot.
static ScreenshotType _confirmed_screenshot_type
Screenshot type the current query is about to confirm.
std::string _screenshot_format_name
Extension of the current screenshot format.
static bool MakeSmallScreenshot(bool crashlog)
Make a screenshot of the current screen.
static void HeightmapCallback(void *, void *buffer, uint y, uint, uint n)
Callback for generating a heightmap.
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
static const char *const SCREENSHOT_NAME
Default filename of a saved screenshot.
bool MakeMinimapWorldScreenshot()
Make a minimap screenshot.
static bool RealMakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
Make a screenshot.
static bool MakeLargeWorldScreenshot(ScreenshotType t, uint32_t width=0, uint32_t height=0)
Make a screenshot of the map.
std::string_view GetCurrentScreenshotExtension()
Get filename extension of current screenshot file format.
static std::string _screenshot_name
Filename of the screenshot file.
static ScreenshotProvider * GetScreenshotProvider()
Get the screenshot provider for the selected format.
bool MakeScreenshot(ScreenshotType t, std::string name, uint32_t width, uint32_t height)
Schedule making a screenshot.
void SetupScreenshotViewport(ScreenshotType t, Viewport *vp, uint32_t width, uint32_t height)
Configure a Viewport for rendering (a part of) the map into a screenshot.
std::string _full_screenshot_path
Pathname of the screenshot file.
static void LargeWorldCallback(void *userdata, void *buf, uint y, uint pitch, uint n)
generate a large piece of the world
static const char *const HEIGHTMAP_NAME
Default filename of a saved heightmap.
uint _heightmap_highest_peak
When saving a heightmap, this contains the highest peak on the map.
static const char * MakeScreenshotName(std::string_view default_fn, std::string_view ext, bool crashlog=false)
Construct a pathname for a screenshot file.
Functions to make screenshots.
ScreenshotType
Type of requested screenshot.
Definition screenshot.h:16
@ SC_VIEWPORT
Screenshot of viewport.
Definition screenshot.h:17
@ SC_CRASHLOG
Raw screenshot from blitter buffer.
Definition screenshot.h:18
@ SC_ZOOMEDIN
Fully zoomed in screenshot of the visible area.
Definition screenshot.h:19
@ SC_HEIGHTMAP
Heightmap of the world.
Definition screenshot.h:22
@ SC_WORLD
World screenshot.
Definition screenshot.h:21
@ SC_MINIMAP
Minimap screenshot.
Definition screenshot.h:23
@ SC_DEFAULTZOOM
Zoomed to default zoom level screenshot of the visible area.
Definition screenshot.h:20
void SetScreenshotWindowVisibility(bool hide)
Set the visibility of the screenshot window when taking a screenshot.
GUI functions related to screenshots.
Types related to screenshot providers.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:58
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:57
uint32_t GetSmallMapOwnerPixels(TileIndex tile, TileType t, IncludeHeightmap include_heightmap)
Return the colour a tile would be displayed with in the small map in mode "Owner".
Smallmap GUI functions.
@ Never
Never include the heightmap.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:277
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:103
Functions related to OTTD's strings.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
GUISettings gui
settings related to the GUI
bool freeform_edges
allow terraforming the tiles at the map edges
Data about how and where to blit pixels.
Definition gfx_type.h:156
ZoomLevel zoom_min
minimum zoom out level
ConstructionSettings construction
construction of things in-game
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:278
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:362
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition map_func.h:269
static debug_inline uint Size()
Get the size of the map.
Definition map_func.h:287
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition map_func.h:296
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition gfx_type.h:361
Helper struct to ensure the video buffer is locked and ready for drawing.
Data structure for viewport, display of a part of the world.
int top
Screen coordinate top edge of the viewport.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_top
Virtual top coordinate.
int virtual_left
Virtual left coordinate.
int virtual_width
width << zoom
int left
Screen coordinate left edge of the viewport.
int height
Screen height of the viewport.
int virtual_height
height << zoom
Data structure for an opened window.
Definition window_gui.h:272
ViewportData * viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
Stuff related to the text buffer GUI.
Map writing/reading functions for tiles.
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
uint TilePixelHeight(Tile tile)
Returns the height of a tile in pixels.
Definition tile_map.h:72
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
static const uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
Base of all video drivers.
Functions related to (drawing on) viewports.
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1124
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZOOM_LVL_MIN) When shifting right,...
Definition zoom_func.h:22
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_MIN) When shifting right,...
Definition zoom_func.h:34
@ ZOOM_LVL_WORLD_SCREENSHOT
Default zoom level for the world screen shot.
Definition zoom_type.h:36
@ ZOOM_LVL_VIEWPORT
Default zoom level for viewports.
Definition zoom_type.h:28