OpenTTD Source 20261112-master-gbcbec5e63f
screenshot_png.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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/math_func.hpp"
12#include "debug.h"
13#include "screenshot_type.h"
14#include "3rdparty/fmt/ranges.h"
15
16#include <png.h>
17
18#ifdef PNG_TEXT_SUPPORTED
19#include "rev.h"
20#include "newgrf_config.h"
21#include "ai/ai_info.hpp"
22#include "company_base.h"
23#include "base_media_graphics.h"
24#endif /* PNG_TEXT_SUPPORTED */
25
26#include "safeguards.h"
27
28class ScreenshotProvider_Png : public ScreenshotProvider {
29public:
30 ScreenshotProvider_Png() : ScreenshotProvider("png", "PNG", 0) {}
31
32 bool MakeImage(std::string_view name, const ScreenshotCallback &callb, uint w, uint h, int pixelformat, const Colour *palette) const override
33 {
34 png_color rq[256];
35 uint i, y, n;
36 uint maxlines;
37 uint bpp = pixelformat / 8;
38 png_structp png_ptr;
39 png_infop info_ptr;
40
41 /* only implemented for 8bit and 32bit images so far. */
42 if (pixelformat != 8 && pixelformat != 32) return false;
43
44 auto of = FileHandle::Open(name, "wb");
45 if (!of.has_value()) return false;
46 auto &f = *of;
47
48 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &name, png_my_error, png_my_warning);
49
50 if (png_ptr == nullptr) {
51 return false;
52 }
53
54 info_ptr = png_create_info_struct(png_ptr);
55 if (info_ptr == nullptr) {
56 png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
57 return false;
58 }
59
60 if (setjmp(png_jmpbuf(png_ptr))) {
61 png_destroy_write_struct(&png_ptr, &info_ptr);
62 return false;
63 }
64
65 png_init_io(png_ptr, f);
66
67 png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
68
69 png_set_IHDR(png_ptr, info_ptr, w, h, 8, pixelformat == 8 ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
70 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
71
72#ifdef PNG_TEXT_SUPPORTED
73
74 /* Try to add some game metadata to the PNG screenshot so
75 * it's more useful for debugging and archival purposes. */
76 png_text_struct text[2]{};
77 text[0].key = const_cast<char *>("Software");
78 text[0].text = const_cast<char *>(_openttd_revision.c_str());
79 text[0].text_length = _openttd_revision.size();
80 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
81
82 std::string message;
83 message.reserve(1024);
84 format_append(message, "Graphics set: {} ({})\n", BaseGraphics::GetUsedSet()->name, fmt::join(BaseGraphics::GetUsedSet()->version, "."));
85 message += "NewGRFs:\n";
86 if (_game_mode != GameMode::Menu) {
87 for (const auto &c : _grfconfig) {
88 format_append(message, "{} {} {}\n", FormatArrayAsHex(c->ident.grfid), FormatArrayAsHex(c->ident.md5sum), c->filename);
89 }
90 }
91 message += "\nCompanies:\n";
92 for (const Company *c : Company::Iterate()) {
93 if (c->ai_info == nullptr) {
94 format_append(message, "{:2d}: Human\n", c->index);
95 } else {
96 format_append(message, "{:2d}: {} (v{})\n", c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
97 }
98 }
99 text[1].key = const_cast<char *>("Description");
100 text[1].text = const_cast<char *>(message.c_str());
101 text[1].text_length = message.size();
102 text[1].compression = PNG_TEXT_COMPRESSION_zTXt;
103 png_set_text(png_ptr, info_ptr, text, 2);
104
105#endif /* PNG_TEXT_SUPPORTED */
106
107 if (pixelformat == 8) {
108 /* convert the palette to the .PNG format. */
109 for (i = 0; i != 256; i++) {
110 rq[i].red = palette[i].r;
111 rq[i].green = palette[i].g;
112 rq[i].blue = palette[i].b;
113 }
114
115 png_set_PLTE(png_ptr, info_ptr, rq, 256);
116 }
117
118 png_write_info(png_ptr, info_ptr);
119 png_set_flush(png_ptr, 512);
120
121 if (pixelformat == 32) {
122 png_color_8 sig_bit;
123
124 /* Save exact colour/alpha resolution */
125 sig_bit.alpha = 0;
126 sig_bit.blue = 8;
127 sig_bit.green = 8;
128 sig_bit.red = 8;
129 sig_bit.gray = 8;
130 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
131
132 if constexpr (std::endian::native == std::endian::little) {
133 png_set_bgr(png_ptr);
134 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
135 } else {
136 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
137 }
138 }
139
140 /* use by default 64k temp memory */
141 maxlines = Clamp(65536 / w, 16, 128);
142
143 /* now generate the bitmap bits */
144 std::vector<uint8_t> buff(static_cast<size_t>(w) * maxlines * bpp); // by default generate 128 lines at a time.
145
146 y = 0;
147 do {
148 /* determine # lines to write */
149 n = std::min(h - y, maxlines);
150
151 /* render the pixels into the buffer */
152 callb(buff.data(), y, w, n);
153 y += n;
154
155 /* write them to png */
156 for (i = 0; i != n; i++) {
157 png_write_row(png_ptr, (png_bytep)buff.data() + i * w * bpp);
158 }
159 } while (y != h);
160
161 png_write_end(png_ptr, info_ptr);
162 png_destroy_write_struct(&png_ptr, &info_ptr);
163
164 return true;
165 }
166
167private:
168 static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
169 {
170 Debug(Facility::Misc, Severity::Critical, "[libpng] error: {} - {}", message, *static_cast<std::string_view *>(png_get_error_ptr(png_ptr)));
171 longjmp(png_jmpbuf(png_ptr), 1);
172 }
173
174 static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
175 {
176 Debug(Facility::Misc, Severity::Error, "[libpng] warning: {} - {}", message, *static_cast<std::string_view *>(png_get_error_ptr(png_ptr)));
177 }
178
179private:
180 static ScreenshotProvider_Png instance;
181};
182
183/* static */ ScreenshotProvider_Png ScreenshotProvider_Png::instance{};
AIInfo keeps track of all information of an AI, like Author, Description, ...
Generic functions for replacing base graphics data.
static const GraphicsSet * GetUsedSet()
static std::optional< FileHandle > Open(const std::string &filename, std::string_view mode)
Open an RAII file handle if possible.
Definition fileio.cpp:1218
bool MakeImage(std::string_view name, const ScreenshotCallback &callb, uint w, uint h, int pixelformat, const Colour *palette) const override
Create and write an image to a file.
Definition of stuff that is very close to a company, like the company struct itself.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
Integer math functions.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
GRFConfigList _grfconfig
First item in list of current GRF set up.
Functions to find and configure NewGRFs.
@ Menu
In the main menu.
Definition openttd.h:19
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
Types related to screenshot providers.
std::function< void(void *buf, uint y, uint pitch, uint n)> ScreenshotCallback
Callback function signature for generating lines of pixel data to be written to the screenshot file.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
static Pool::IterateWrapper< Company > Iterate(size_t from=0)