Debian Codegraph @

src/engine/image_tool.cpp

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2020 - 2025 *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cstdint>
24 #include <cstring>
25 #include <memory>
26 #include <ostream>
27 #include <string_view>
28 #include <vector>
29
30 // Managing compiler warnings for SDL headers
31 #if defined( __GNUC__ )
32 #pragma GCC diagnostic push
33
34 #pragma GCC diagnostic ignored "-Wdouble-promotion"
35 #pragma GCC diagnostic ignored "-Wold-style-cast"
36 #pragma GCC diagnostic ignored "-Wswitch-default"
37 #endif
38
39 #include <SDL_error.h>
40 #include <SDL_pixels.h>
41 #include <SDL_stdinc.h>
42 #include <SDL_surface.h>
43 #include <SDL_version.h>
44
45 #if defined( WITH_IMAGE )
46 #include <SDL_image.h>
47 #endif
48
49 // Managing compiler warnings for SDL headers
50 #if defined( __GNUC__ )
51 #pragma GCC diagnostic pop
52 #endif
53
54 #include "agg_file.h"
55 #include "image_palette.h"
56 #include "image_tool.h"
57 #include "logging.h"
58 #include "serialize.h"
59 #include "system.h"
60
61 namespace
62 {
63 bool isPNGFilePath( const std::string_view path )
64 {
65 const std::string pngExtension( ".png" );
66 return path.size() >= pngExtension.size() && ( path.compare( path.size() - pngExtension.size(), pngExtension.size(), pngExtension ) == 0 );
67 }
68
69 std::vector<uint8_t> PALPalette()
70 {
71 const uint8_t * gamePalette = fheroes2::getGamePalette();
72
73 std::vector<uint8_t> palette( 256 * 3 );
74 for ( size_t i = 0; i < palette.size(); ++i ) {
75 palette[i] = gamePalette[i] << 2;
76 }
77
78 return palette;
79 }
80
81 #if defined( WITH_IMAGE )
82 bool SaveImage( const fheroes2::Image & image, const std::string & path )
83 #else
84 bool SaveImage( const fheroes2::Image & image, std::string path )
85 #endif
86 {
87 const std::vector<uint8_t> & palette = PALPalette();
88 const uint8_t * currentPalette = palette.data();
89
90 const int32_t width = image.width();
91 const int32_t height = image.height();
92
93 const std::unique_ptr<SDL_Surface, void ( * )( SDL_Surface * )> surface( SDL_CreateRGBSurface( 0, width, height, 8, 0, 0, 0, 0 ), SDL_FreeSurface );
94 if ( !surface ) {
95 ERROR_LOG( "Error while creating a SDL surface for an image to be saved under " << path << ". Error " << SDL_GetError() )
96 return false;
97 }
98
99 assert( surface->format->BitsPerPixel == 8 );
100
101 std::vector<SDL_Color> paletteSDL;
102 paletteSDL.resize( 256 );
103 for ( int32_t i = 0; i < 256; ++i ) {
104 const uint8_t * value = currentPalette + i * 3;
105 SDL_Color & col = paletteSDL[i];
106
107 col.r = *value;
108 col.g = *( value + 1 );
109 col.b = *( value + 2 );
110 col.a = 255;
111 }
112
113 SDL_SetPaletteColors( surface->format->palette, paletteSDL.data(), 0, 256 );
114
115 if ( surface->pitch != width ) {
116 const uint8_t * imageIn = image.image();
117
118 for ( int32_t i = 0; i < height; ++i ) {
119 memcpy( static_cast<uint8_t *>( surface->pixels ) + surface->pitch * i, imageIn + width * i, static_cast<size_t>( width ) );
120 }
121 }
122 else {
123 memcpy( surface->pixels, image.image(), static_cast<size_t>( width * height ) );
124 }
125
126 #if defined( WITH_IMAGE )
127 int res = 0;
128
129 if ( isPNGFilePath( path ) ) {
130 res = IMG_SavePNG( surface.get(), System::encLocalToUTF8( path ).c_str() );
131 }
132 else {
133 res = SDL_SaveBMP( surface.get(), System::encLocalToUTF8( path ).c_str() );
134 }
135 #else
136 if ( isPNGFilePath( path ) ) {
137 memcpy( path.data() + path.size() - 3, "bmp", 3 );
138 }
139
140 const int res = SDL_SaveBMP( surface.get(), System::encLocalToUTF8( path ).c_str() );
141 #endif
142
143 return res == 0;
144 }
145 }
146
147 namespace fheroes2
148 {
149 bool Save( const Image & image, const std::string & path, const uint8_t background )
150 {
151 if ( image.empty() || path.empty() )
152 return false;
153
154 Image temp( image.width(), image.height() );
155 temp.fill( background );
156
157 Blit( image, temp );
158
159 return SaveImage( temp, path );
160 }
161
162 bool Save( const Image & image, const std::string & path )
163 {
164 if ( image.empty() || path.empty() )
165 return false;
166
167 return SaveImage( image, path );
168 }
169
170 bool Load( const std::string & path, Image & image )
171 {
172 if ( image.singleLayer() ) {
173 // Output image should be double-layer!
174 assert( 0 );
175 return false;
176 }
177
178 std::unique_ptr<SDL_Surface, void ( * )( SDL_Surface * )> surface( nullptr, SDL_FreeSurface );
179 std::unique_ptr<SDL_Surface, void ( * )( SDL_Surface * )> loadedSurface( nullptr, SDL_FreeSurface );
180
181 #if defined( WITH_IMAGE )
182 loadedSurface.reset( IMG_Load( System::encLocalToUTF8( path ).c_str() ) );
183 #else
184 loadedSurface.reset( SDL_LoadBMP( System::encLocalToUTF8( path ).c_str() ) );
185 #endif
186 if ( !loadedSurface ) {
187 return false;
188 }
189
190 #if !SDL_VERSION_ATLEAST( 2, 0, 5 )
191 #error SDL_PIXELFORMAT_BGRA32 and other RGBA color variants are only supported since SDL 2.0.5
192 #endif
193
194 // Image loading functions can theoretically return SDL_Surface in any supported color format, so we will convert it to a specific format for subsequent
195 // processing
196 const std::unique_ptr<SDL_PixelFormat, void ( * )( SDL_PixelFormat * )> pixelFormat( SDL_AllocFormat( SDL_PIXELFORMAT_BGRA32 ), SDL_FreeFormat );
197 if ( !pixelFormat ) {
198 return false;
199 }
200
201 surface.reset( SDL_ConvertSurface( loadedSurface.get(), pixelFormat.get(), 0 ) );
202 if ( !surface ) {
203 return false;
204 }
205
206 assert( SDL_MUSTLOCK( surface.get() ) == SDL_FALSE && surface->format->BytesPerPixel == 4 );
207
208 image.resize( surface->w, surface->h );
209 image.reset();
210
211 const uint8_t * inY = static_cast<uint8_t *>( surface->pixels );
212 uint8_t * outY = image.image();
213 uint8_t * transformY = image.transform();
214
215 const uint8_t * inYEnd = inY + surface->h * surface->pitch;
216
217 for ( ; inY != inYEnd; inY += surface->pitch, outY += surface->w, transformY += surface->w ) {
218 const uint8_t * inX = inY;
219 uint8_t * outX = outY;
220 uint8_t * transformX = transformY;
221 const uint8_t * inXEnd = inX + surface->w * 4;
222
223 for ( ; inX != inXEnd; inX += 4, ++outX, ++transformX ) {
224 const uint8_t alpha = *( inX + 3 );
225 if ( alpha < 255 ) {
226 if ( alpha == 0 ) {
227 *outX = 0;
228 *transformX = 1;
229 }
230 else if ( *inX == 0 && *( inX + 1 ) == 0 && *( inX + 2 ) == 0 ) {
231 *outX = 0;
232 *transformX = 2;
233 }
234 else {
235 *outX = GetColorId( *( inX + 2 ), *( inX + 1 ), *inX );
236 *transformX = 0;
237 }
238 }
239 else {
240 *outX = GetColorId( *( inX + 2 ), *( inX + 1 ), *inX );
241 *transformX = 0;
242 }
243 }
244 }
245
246 return true;
247 }
248
249 Sprite decodeICNSprite( const uint8_t * data, const uint8_t * dataEnd, const ICNHeader & icnHeader )
250 {
251 Sprite sprite( icnHeader.width, icnHeader.height, icnHeader.offsetX, icnHeader.offsetY );
252 sprite.reset();
253
254 uint8_t * imageTransform = sprite.transform();
255
256 uint32_t posX = 0;
257
258 // The need for a transform layer can only be determined during ICN decoding.
259 bool noTransformLayer = true;
260
261 // When the 6th bit in animationFrames is set then it is Monochromatic ICN image.
262 const bool isMonochromatic = ( icnHeader.animationFrames & 0x20 );
263
264 if ( isMonochromatic ) {
265 while ( data < dataEnd ) {
266 if ( *data == 0 ) {
267 // 0x00 - end of row reached, go to the first pixel of next row.
268
269 noTransformLayer = noTransformLayer && ( static_cast<int32_t>( posX ) >= icnHeader.width );
270
271 imageTransform += icnHeader.width;
272 posX = 0;
273 ++data;
274 }
275 else if ( *data < 0x80 ) {
276 // 0x01-0x7F - number of black pixels.
277 // Image data is all already set to 0. Just set transform layer to 0.
278
279 const uint8_t pixelCount = *data;
280
281 memset( imageTransform + posX, static_cast<uint8_t>( 0 ), pixelCount );
282
283 ++data;
284 posX += pixelCount;
285 }
286 else if ( *data == 0x80 ) {
287 // 0x80 - end of image.
288
289 break;
290 }
291 else {
292 // 0x81 to 0xFF - number of empty (transparent) pixels + 0x80.
293 // The (n - 128) pixels are transparent.
294
295 noTransformLayer = false;
296
297 posX += *data - 0x80;
298 ++data;
299 }
300 }
301 }
302 else {
303 uint8_t * imageData = sprite.image();
304
305 while ( data < dataEnd ) {
306 if ( *data == 0 ) {
307 // 0x00 - end of row reached, go to the first pixel of next row.
308 // All of remaining pixels of current line are transparent.
309
310 noTransformLayer = noTransformLayer && ( static_cast<int32_t>( posX ) >= icnHeader.width );
311
312 imageData += icnHeader.width;
313 imageTransform += icnHeader.width;
314 posX = 0;
315 ++data;
316 }
317 else if ( *data < 0x80 ) {
318 // 0x01-0x7F - number N of sprite pixels.
319 // The next N bytes are the colors of the next N pixels.
320
321 const uint8_t pixelCount = *data;
322 ++data;
323
324 if ( data + pixelCount > dataEnd ) {
325 // Image data is corrupted - we can not read data beyond dataEnd.
326 break;
327 }
328
329 memcpy( imageData + posX, data, pixelCount );
330 memset( imageTransform + posX, static_cast<uint8_t>( 0 ), pixelCount );
331
332 data += pixelCount;
333 posX += pixelCount;
334 }
335 else if ( *data == 0x80 ) {
336 // 0x80 - end of image
337
338 noTransformLayer = noTransformLayer && ( static_cast<int32_t>( posX ) >= icnHeader.width );
339
340 break;
341 }
342 else if ( *data < 0xC0 ) {
343 // 0x81 to 0xBF - number of empty (transparent) pixels + 0x80. The (n - 128) pixels are transparent.
344
345 noTransformLayer = false;
346
347 posX += *data - 0x80;
348 ++data;
349 }
350 else if ( *data == 0xC0 ) {
351 // 0xC0 - put here N transform layer pixels.
352 // If the next byte modulo 4 is not null, N equals the next byte modulo 4,
353 // otherwise N equals the second next byte.
354
355 noTransformLayer = false;
356
357 ++data;
358
359 const uint8_t transformValue = *data;
360
361 const uint32_t countValue = transformValue & 0x03;
362 const uint32_t pixelCount = ( countValue != 0 ) ? countValue : *( ++data );
363
364 if ( transformValue & 0x40 ) {
365 // Transform layer data types:
366 // 0 - no transparency,
367 // 1 - full transparency (to skip image data),
368 // from 5 (light) to 2 (strong) - for darkening,
369 // from 10 (light) to 6 (strong) - for lightening
370 const uint8_t transformType = static_cast<uint8_t>( ( ( transformValue & 0x3C ) >> 2 ) + 2 );
371
372 if ( transformType < 16 ) {
373 memset( imageTransform + posX, transformType, pixelCount );
374 }
375 }
376
377 // TODO: Use ( transformValue & 0x80 ) to detect and store shining contour data bit.
378 // It is used for units on the Battlefield and for icons in the View World.
379
380 posX += pixelCount;
381
382 ++data;
383 }
384 else {
385 // 0xC1 - next byte stores the number of next pixels of same color, or
386 // 0xC2 to 0xFF - the number of pixels of same color plus 0xC0.
387 // Next byte is the color of these pixels.
388
389 const uint32_t pixelCount = ( *data == 0xC1 ) ? *( ++data ) : *data - 0xC0;
390 ++data;
391
392 memset( imageData + posX, *data, pixelCount );
393 memset( imageTransform + posX, static_cast<uint8_t>( 0 ), pixelCount );
394
395 posX += pixelCount;
396
397 ++data;
398 }
399 }
400 }
401
402 if ( noTransformLayer ) {
403 sprite._disableTransformLayer();
404 }
405
406 return sprite;
407 }
408
409 void decodeTILImages( const uint8_t * data, const size_t imageCount, const int32_t width, const int32_t height, std::vector<Image> & output )
410 {
411 assert( data != nullptr && imageCount > 0 && width > 0 && height > 0 );
412
413 output.resize( imageCount );
414
415 const size_t imageSize = static_cast<size_t>( width ) * height;
416
417 for ( size_t i = 0; i < imageCount; ++i ) {
418 Image & tilImage = output[i];
419 tilImage._disableTransformLayer();
420 tilImage.resize( width, height );
421 memcpy( tilImage.image(), data + i * imageSize, imageSize );
422 }
423 }
424
425 Sprite decodeBMPFile( const std::vector<uint8_t> & data )
426 {
427 if ( data.size() < 6 ) {
428 // It is an invalid BMP file.
429 return {};
430 }
431
432 ROStreamBuf imageStream( data );
433
434 const uint8_t blackColor = imageStream.get();
435 const uint8_t whiteColor = 11;
436
437 // Skip the second byte
438 imageStream.get();
439
440 const int32_t width = imageStream.getLE16();
441 const int32_t height = imageStream.getLE16();
442
443 if ( static_cast<int32_t>( data.size() ) != 6 + width * height ) {
444 // It is an invalid BMP file.
445 return {};
446 }
447
448 fheroes2::Sprite output( width, height );
449
450 const uint8_t * input = data.data() + 6;
451 uint8_t * image = output.image();
452 const uint8_t * imageEnd = image + static_cast<ptrdiff_t>( width ) * height;
453 uint8_t * transform = output.transform();
454
455 for ( ; image != imageEnd; ++image, ++transform, ++input ) {
456 if ( *input == 1 ) {
457 *image = whiteColor;
458 *transform = 0;
459 }
460 else if ( *input == 2 ) {
461 *image = blackColor;
462 *transform = 0;
463 }
464 else {
465 *transform = 1;
466 }
467 }
468
469 return output;
470 }
471
472 bool isPNGFormatSupported()
473 {
474 #if defined( WITH_IMAGE )
475 return true;
476 #else
477 return false;
478 #endif
479 }
480 }