1/**************************************************************************/
2/* image_loader_bmp.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "image_loader_bmp.h"
32
33#include "core/io/file_access_memory.h"
34
35static uint8_t get_mask_width(uint16_t mask) {
36 // Returns number of ones in the binary value of the parameter: mask.
37 // Uses a Simple pop_count.
38 uint8_t c = 0u;
39 for (; mask != 0u; mask &= mask - 1u) {
40 c++;
41 }
42 return c;
43}
44
45Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
46 const uint8_t *p_buffer,
47 const uint8_t *p_color_buffer,
48 const uint32_t color_table_size,
49 const bmp_header_s &p_header) {
50 Error err = OK;
51
52 if (p_buffer == nullptr) {
53 err = FAILED;
54 }
55
56 if (err == OK) {
57 size_t index = 0;
58 size_t width = (size_t)p_header.bmp_info_header.bmp_width;
59 size_t height = (size_t)p_header.bmp_info_header.bmp_height;
60 size_t bits_per_pixel = (size_t)p_header.bmp_info_header.bmp_bit_count;
61
62 // Check whether we can load it
63
64 if (bits_per_pixel == 1) {
65 // Requires bit unpacking...
66 ERR_FAIL_COND_V_MSG(width % 8 != 0, ERR_UNAVAILABLE,
67 vformat("1-bpp BMP images must have a width that is a multiple of 8, but the imported BMP is %d pixels wide.", int(width)));
68 ERR_FAIL_COND_V_MSG(height % 8 != 0, ERR_UNAVAILABLE,
69 vformat("1-bpp BMP images must have a height that is a multiple of 8, but the imported BMP is %d pixels tall.", int(height)));
70
71 } else if (bits_per_pixel == 2) {
72 // Requires bit unpacking...
73 ERR_FAIL_COND_V_MSG(width % 4 != 0, ERR_UNAVAILABLE,
74 vformat("2-bpp BMP images must have a width that is a multiple of 4, but the imported BMP is %d pixels wide.", int(width)));
75 ERR_FAIL_COND_V_MSG(height % 4 != 0, ERR_UNAVAILABLE,
76 vformat("2-bpp BMP images must have a height that is a multiple of 4, but the imported BMP is %d pixels tall.", int(height)));
77
78 } else if (bits_per_pixel == 4) {
79 // Requires bit unpacking...
80 ERR_FAIL_COND_V_MSG(width % 2 != 0, ERR_UNAVAILABLE,
81 vformat("4-bpp BMP images must have a width that is a multiple of 2, but the imported BMP is %d pixels wide.", int(width)));
82 ERR_FAIL_COND_V_MSG(height % 2 != 0, ERR_UNAVAILABLE,
83 vformat("4-bpp BMP images must have a height that is a multiple of 2, but the imported BMP is %d pixels tall.", int(height)));
84 }
85
86 // Image data (might be indexed)
87 Vector<uint8_t> data;
88 int data_len = 0;
89
90 if (bits_per_pixel <= 8) { // indexed
91 data_len = width * height;
92 } else { // color
93 data_len = width * height * 4;
94 }
95 ERR_FAIL_COND_V_MSG(data_len == 0, ERR_BUG, "Couldn't parse the BMP image data.");
96 err = data.resize(data_len);
97
98 uint8_t *data_w = data.ptrw();
99 uint8_t *write_buffer = data_w;
100
101 const uint32_t width_bytes = width * bits_per_pixel / 8;
102 const uint32_t line_width = (width_bytes + 3) & ~3;
103
104 // The actual data traversal is determined by
105 // the data width in case of 8/4/2/1 bit images
106 const uint32_t w = bits_per_pixel >= 16 ? width : width_bytes;
107 const uint8_t *line = p_buffer + (line_width * (height - 1));
108 const uint8_t *end_buffer = p_buffer + p_header.bmp_file_header.bmp_file_size - p_header.bmp_file_header.bmp_file_offset;
109
110 for (uint64_t i = 0; i < height; i++) {
111 const uint8_t *line_ptr = line;
112
113 for (unsigned int j = 0; j < w; j++) {
114 ERR_FAIL_COND_V(line_ptr >= end_buffer, ERR_FILE_CORRUPT);
115 switch (bits_per_pixel) {
116 case 1: {
117 uint8_t color_index = *line_ptr;
118
119 write_buffer[index + 0] = (color_index >> 7) & 1;
120 write_buffer[index + 1] = (color_index >> 6) & 1;
121 write_buffer[index + 2] = (color_index >> 5) & 1;
122 write_buffer[index + 3] = (color_index >> 4) & 1;
123 write_buffer[index + 4] = (color_index >> 3) & 1;
124 write_buffer[index + 5] = (color_index >> 2) & 1;
125 write_buffer[index + 6] = (color_index >> 1) & 1;
126 write_buffer[index + 7] = (color_index >> 0) & 1;
127
128 index += 8;
129 line_ptr += 1;
130 } break;
131 case 2: {
132 uint8_t color_index = *line_ptr;
133
134 write_buffer[index + 0] = (color_index >> 6) & 3;
135 write_buffer[index + 1] = (color_index >> 4) & 3;
136 write_buffer[index + 2] = (color_index >> 2) & 3;
137 write_buffer[index + 3] = color_index & 3;
138
139 index += 4;
140 line_ptr += 1;
141 } break;
142 case 4: {
143 uint8_t color_index = *line_ptr;
144
145 write_buffer[index + 0] = (color_index >> 4) & 0x0f;
146 write_buffer[index + 1] = color_index & 0x0f;
147
148 index += 2;
149 line_ptr += 1;
150 } break;
151 case 8: {
152 uint8_t color_index = *line_ptr;
153
154 write_buffer[index] = color_index;
155
156 index += 1;
157 line_ptr += 1;
158 } break;
159 case 16: {
160 uint16_t rgb = (static_cast<uint16_t>(line_ptr[1]) << 8) | line_ptr[0];
161 // A1R5G5B5/X1R5G5B5 => uint16_t
162 // [A/X]1R5G2 | G3B5 => uint8_t | uint8_t
163 uint8_t ba = (rgb & p_header.bmp_bitfield.alpha_mask) >> p_header.bmp_bitfield.alpha_offset; // Alpha 0b 1000 ...
164 uint8_t b0 = (rgb & p_header.bmp_bitfield.red_mask) >> p_header.bmp_bitfield.red_offset; // Red 0b 0111 1100 ...
165 uint8_t b1 = (rgb & p_header.bmp_bitfield.green_mask) >> p_header.bmp_bitfield.green_offset; // Green 0b 0000 0011 1110 ...
166 uint8_t b2 = (rgb & p_header.bmp_bitfield.blue_mask); // >> p_header.bmp_bitfield.blue_offset; // Blue 0b ... 0001 1111
167
168 // Next we apply some color scaling going from a variable value space to a 256 value space.
169 // This may be simplified some but left as is for legibility.
170 // float scaled_value = unscaled_value * byte_max_value / color_channel_maxium_value + rounding_offset;
171 float f0 = b0 * 255.0f / static_cast<float>(p_header.bmp_bitfield.red_max) + 0.5f;
172 float f1 = b1 * 255.0f / static_cast<float>(p_header.bmp_bitfield.green_max) + 0.5f;
173 float f2 = b2 * 255.0f / static_cast<float>(p_header.bmp_bitfield.blue_max) + 0.5f;
174 write_buffer[index + 0] = static_cast<uint8_t>(f0); // R
175 write_buffer[index + 1] = static_cast<uint8_t>(f1); // G
176 write_buffer[index + 2] = static_cast<uint8_t>(f2); // B
177
178 if (p_header.bmp_bitfield.alpha_mask_width > 0) {
179 write_buffer[index + 3] = ba * 0xFF; // Alpha value(Always true or false so no scaling)
180 } else {
181 write_buffer[index + 3] = 0xFF; // No Alpha channel, Show everything.
182 }
183
184 index += 4;
185 line_ptr += 2;
186 } break;
187 case 24: {
188 write_buffer[index + 2] = line_ptr[0];
189 write_buffer[index + 1] = line_ptr[1];
190 write_buffer[index + 0] = line_ptr[2];
191 write_buffer[index + 3] = 0xff;
192
193 index += 4;
194 line_ptr += 3;
195 } break;
196 case 32: {
197 write_buffer[index + 2] = line_ptr[0];
198 write_buffer[index + 1] = line_ptr[1];
199 write_buffer[index + 0] = line_ptr[2];
200 write_buffer[index + 3] = line_ptr[3];
201
202 index += 4;
203 line_ptr += 4;
204 } break;
205 }
206 }
207 line -= line_width;
208 }
209
210 if (p_color_buffer == nullptr || color_table_size == 0) { // regular pixels
211
212 p_image->set_data(width, height, false, Image::FORMAT_RGBA8, data);
213
214 } else { // data is in indexed format, extend it
215
216 // Palette data
217 Vector<uint8_t> palette_data;
218 palette_data.resize(color_table_size * 4);
219
220 uint8_t *palette_data_w = palette_data.ptrw();
221 uint8_t *pal = palette_data_w;
222
223 const uint8_t *cb = p_color_buffer;
224
225 for (unsigned int i = 0; i < color_table_size; ++i) {
226 pal[i * 4 + 0] = cb[2];
227 pal[i * 4 + 1] = cb[1];
228 pal[i * 4 + 2] = cb[0];
229 pal[i * 4 + 3] = 0xff;
230
231 cb += 4;
232 }
233 // Extend palette to image
234 Vector<uint8_t> extended_data;
235 extended_data.resize(data.size() * 4);
236
237 uint8_t *ex_w = extended_data.ptrw();
238 uint8_t *dest = ex_w;
239
240 const int num_pixels = width * height;
241
242 for (int i = 0; i < num_pixels; i++) {
243 dest[0] = pal[write_buffer[i] * 4 + 0];
244 dest[1] = pal[write_buffer[i] * 4 + 1];
245 dest[2] = pal[write_buffer[i] * 4 + 2];
246 dest[3] = pal[write_buffer[i] * 4 + 3];
247
248 dest += 4;
249 }
250 p_image->set_data(width, height, false, Image::FORMAT_RGBA8, extended_data);
251 }
252 }
253 return err;
254}
255
256Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) {
257 bmp_header_s bmp_header;
258 Error err = ERR_INVALID_DATA;
259
260 // A valid bmp file should always at least have a
261 // file header and a minimal info header
262 if (f->get_length() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) {
263 // File Header
264 bmp_header.bmp_file_header.bmp_signature = f->get_16();
265 if (bmp_header.bmp_file_header.bmp_signature == BITMAP_SIGNATURE) {
266 bmp_header.bmp_file_header.bmp_file_size = f->get_32();
267 bmp_header.bmp_file_header.bmp_file_padding = f->get_32();
268 bmp_header.bmp_file_header.bmp_file_offset = f->get_32();
269
270 // Info Header
271 bmp_header.bmp_info_header.bmp_header_size = f->get_32();
272 ERR_FAIL_COND_V_MSG(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT,
273 vformat("Couldn't parse the BMP info header. The file is likely corrupt: %s", f->get_path()));
274
275 bmp_header.bmp_info_header.bmp_width = f->get_32();
276 bmp_header.bmp_info_header.bmp_height = f->get_32();
277
278 bmp_header.bmp_info_header.bmp_planes = f->get_16();
279 ERR_FAIL_COND_V_MSG(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT,
280 vformat("Couldn't parse the BMP planes. The file is likely corrupt: %s", f->get_path()));
281
282 bmp_header.bmp_info_header.bmp_bit_count = f->get_16();
283 bmp_header.bmp_info_header.bmp_compression = f->get_32();
284 bmp_header.bmp_info_header.bmp_size_image = f->get_32();
285 bmp_header.bmp_info_header.bmp_pixels_per_meter_x = f->get_32();
286 bmp_header.bmp_info_header.bmp_pixels_per_meter_y = f->get_32();
287 bmp_header.bmp_info_header.bmp_colors_used = f->get_32();
288 bmp_header.bmp_info_header.bmp_important_colors = f->get_32();
289
290 switch (bmp_header.bmp_info_header.bmp_compression) {
291 case BI_BITFIELDS: {
292 bmp_header.bmp_bitfield.red_mask = f->get_32();
293 bmp_header.bmp_bitfield.green_mask = f->get_32();
294 bmp_header.bmp_bitfield.blue_mask = f->get_32();
295 bmp_header.bmp_bitfield.alpha_mask = f->get_32();
296
297 bmp_header.bmp_bitfield.red_mask_width = get_mask_width(bmp_header.bmp_bitfield.red_mask);
298 bmp_header.bmp_bitfield.green_mask_width = get_mask_width(bmp_header.bmp_bitfield.green_mask);
299 bmp_header.bmp_bitfield.blue_mask_width = get_mask_width(bmp_header.bmp_bitfield.blue_mask);
300 bmp_header.bmp_bitfield.alpha_mask_width = get_mask_width(bmp_header.bmp_bitfield.alpha_mask);
301
302 bmp_header.bmp_bitfield.alpha_offset = bmp_header.bmp_bitfield.red_mask_width + bmp_header.bmp_bitfield.green_mask_width + bmp_header.bmp_bitfield.blue_mask_width;
303 bmp_header.bmp_bitfield.red_offset = bmp_header.bmp_bitfield.green_mask_width + bmp_header.bmp_bitfield.blue_mask_width;
304 bmp_header.bmp_bitfield.green_offset = bmp_header.bmp_bitfield.blue_mask_width;
305
306 bmp_header.bmp_bitfield.red_max = (1 << bmp_header.bmp_bitfield.red_mask_width) - 1;
307 bmp_header.bmp_bitfield.green_max = (1 << bmp_header.bmp_bitfield.green_mask_width) - 1;
308 bmp_header.bmp_bitfield.blue_max = (1 << bmp_header.bmp_bitfield.blue_mask_width) - 1;
309 } break;
310 case BI_RLE8:
311 case BI_RLE4:
312 case BI_CMYKRLE8:
313 case BI_CMYKRLE4: {
314 // Stop parsing.
315 ERR_FAIL_V_MSG(ERR_UNAVAILABLE,
316 vformat("RLE compressed BMP files are not yet supported: %s", f->get_path()));
317 } break;
318 }
319 // Don't rely on sizeof(bmp_file_header) as structure padding
320 // adds 2 bytes offset leading to misaligned color table reading
321 uint32_t ct_offset = BITMAP_FILE_HEADER_SIZE + bmp_header.bmp_info_header.bmp_header_size;
322 f->seek(ct_offset);
323
324 uint32_t color_table_size = 0;
325
326 // bmp_colors_used may report 0 despite having a color table
327 // for 4 and 1 bit images, so don't rely on this information
328 if (bmp_header.bmp_info_header.bmp_bit_count <= 8) {
329 // Support 256 colors max
330 color_table_size = 1 << bmp_header.bmp_info_header.bmp_bit_count;
331 ERR_FAIL_COND_V_MSG(color_table_size == 0, ERR_BUG,
332 vformat("Couldn't parse the BMP color table: %s", f->get_path()));
333 }
334
335 Vector<uint8_t> bmp_color_table;
336 // Color table is usually 4 bytes per color -> [B][G][R][0]
337 bmp_color_table.resize(color_table_size * 4);
338 uint8_t *bmp_color_table_w = bmp_color_table.ptrw();
339 f->get_buffer(bmp_color_table_w, color_table_size * 4);
340
341 f->seek(bmp_header.bmp_file_header.bmp_file_offset);
342
343 uint32_t bmp_buffer_size = (bmp_header.bmp_file_header.bmp_file_size - bmp_header.bmp_file_header.bmp_file_offset);
344
345 Vector<uint8_t> bmp_buffer;
346 err = bmp_buffer.resize(bmp_buffer_size);
347 if (err == OK) {
348 uint8_t *bmp_buffer_w = bmp_buffer.ptrw();
349 f->get_buffer(bmp_buffer_w, bmp_buffer_size);
350
351 const uint8_t *bmp_buffer_r = bmp_buffer.ptr();
352 const uint8_t *bmp_color_table_r = bmp_color_table.ptr();
353 err = convert_to_image(p_image, bmp_buffer_r,
354 bmp_color_table_r, color_table_size, bmp_header);
355 }
356 }
357 }
358 return err;
359}
360
361void ImageLoaderBMP::get_recognized_extensions(List<String> *p_extensions) const {
362 p_extensions->push_back("bmp");
363}
364
365static Ref<Image> _bmp_mem_loader_func(const uint8_t *p_bmp, int p_size) {
366 Ref<FileAccessMemory> memfile;
367 memfile.instantiate();
368 Error open_memfile_error = memfile->open_custom(p_bmp, p_size);
369 ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for BMP image buffer.");
370
371 Ref<Image> img;
372 img.instantiate();
373 Error load_error = ImageLoaderBMP().load_image(img, memfile, false, 1.0f);
374 ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load BMP image.");
375 return img;
376}
377
378ImageLoaderBMP::ImageLoaderBMP() {
379 Image::_bmp_mem_loader_func = _bmp_mem_loader_func;
380}
381