Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "tex.h"
26 :
27 : #include "lib/alignment.h"
28 : #include "lib/allocators/dynarray.h"
29 : #include "lib/allocators/shared_ptr.h"
30 : #include "lib/bits.h"
31 : #include "lib/debug.h"
32 : #include "lib/posix/posix_types.h"
33 : #include "lib/tex/tex_codec.h"
34 :
35 : #include <algorithm>
36 : #include <bit>
37 : #include <cstdint>
38 : #include <cstring>
39 :
40 : static const StatusDefinition texStatusDefinitions[] =
41 : {
42 : { ERR::TEX_UNKNOWN_FORMAT, L"Unknown texture format" },
43 : { ERR::TEX_FMT_INVALID, L"Invalid/unsupported texture format" },
44 : { ERR::TEX_INVALID_COLOR_TYPE, L"Invalid color type" },
45 : { ERR::TEX_NOT_8BIT_PRECISION, L"Not 8-bit channel precision" },
46 : { ERR::TEX_INVALID_LAYOUT, L"Unsupported texel layout, e.g. right-to-left" },
47 : { ERR::TEX_COMPRESSED, L"Unsupported texture compression" },
48 : { WARN::TEX_INVALID_DATA, L"Warning: invalid texel data encountered" },
49 : { ERR::TEX_INVALID_SIZE, L"Texture size is incorrect" },
50 : { INFO::TEX_CODEC_CANNOT_HANDLE, L"Texture codec cannot handle the given format" }
51 : };
52 : STATUS_ADD_DEFINITIONS(texStatusDefinitions);
53 :
54 :
55 : //-----------------------------------------------------------------------------
56 : // validation
57 : //-----------------------------------------------------------------------------
58 :
59 : // be careful not to use other tex_* APIs here because they call us.
60 183 : Status Tex::validate() const
61 : {
62 183 : if(m_Flags & TEX_UNDEFINED_FLAGS)
63 : return ERR::_1;
64 :
65 : // pixel data (only check validity if the image is still in memory).
66 183 : if(m_Data)
67 : {
68 : // file size smaller than header+pixels.
69 : // possible causes: texture file header is invalid,
70 : // or file wasn't loaded completely.
71 183 : if(m_DataSize < m_Ofs + m_Width*m_Height*m_Bpp/8)
72 : return ERR::_2;
73 : }
74 :
75 : // bits per pixel
76 : // (we don't bother checking all values; a sanity check is enough)
77 183 : if(m_Bpp % 4 || m_Bpp > 32)
78 : return ERR::_3;
79 :
80 : // flags
81 : // .. DXT value
82 183 : const size_t dxt = m_Flags & TEX_DXT;
83 183 : if(dxt != 0 && dxt != 1 && dxt != DXT1A && dxt != 3 && dxt != 5)
84 : return ERR::_4;
85 : // .. orientation
86 183 : const size_t orientation = m_Flags & TEX_ORIENTATION;
87 183 : if(orientation == (TEX_BOTTOM_UP|TEX_TOP_DOWN))
88 0 : return ERR::_5;
89 :
90 : return INFO::OK;
91 : }
92 :
93 : #define CHECK_TEX(t) RETURN_STATUS_IF_ERR((t->validate()))
94 :
95 :
96 : // check if the given texture format is acceptable: 8bpp grey,
97 : // 24bpp color or 32bpp color+alpha (BGR / upside down are permitted).
98 : // basically, this is the "plain" format understood by all codecs and
99 : // tex_codec_plain_transform.
100 15 : Status tex_validate_plain_format(size_t bpp, size_t flags)
101 : {
102 15 : const bool alpha = (flags & TEX_ALPHA ) != 0;
103 15 : const bool grey = (flags & TEX_GREY ) != 0;
104 15 : const bool dxt = (flags & TEX_DXT ) != 0;
105 15 : const bool mipmaps = (flags & TEX_MIPMAPS) != 0;
106 :
107 15 : if(dxt || mipmaps)
108 0 : WARN_RETURN(ERR::TEX_FMT_INVALID);
109 :
110 : // grey must be 8bpp without alpha, or it's invalid.
111 15 : if(grey)
112 : {
113 0 : if(bpp == 8 && !alpha)
114 : return INFO::OK;
115 0 : WARN_RETURN(ERR::TEX_FMT_INVALID);
116 : }
117 :
118 15 : if(bpp == 24 && !alpha)
119 : return INFO::OK;
120 5 : if(bpp == 32 && alpha)
121 : return INFO::OK;
122 :
123 0 : WARN_RETURN(ERR::TEX_FMT_INVALID);
124 : }
125 :
126 :
127 : //-----------------------------------------------------------------------------
128 : // mipmaps
129 : //-----------------------------------------------------------------------------
130 :
131 59 : void tex_util_foreach_mipmap(size_t w, size_t h, size_t bpp, const std::uint8_t* pixels,
132 : int levels_to_skip, size_t data_padding, MipmapCB cb, void* RESTRICT cbData)
133 : {
134 59 : ENSURE(levels_to_skip >= 0 || levels_to_skip == TEX_BASE_LEVEL_ONLY);
135 :
136 59 : size_t level_w = w, level_h = h;
137 59 : const std::uint8_t* level_data = pixels;
138 :
139 : // we iterate through the loop (necessary to skip over image data),
140 : // but do not actually call back until the requisite number of
141 : // levels have been skipped (i.e. level == 0).
142 59 : int level = (levels_to_skip == TEX_BASE_LEVEL_ONLY)? 0 : -levels_to_skip;
143 :
144 : // until at level 1x1:
145 137 : for(;;)
146 : {
147 : // used to skip past this mip level in <data>
148 137 : const size_t level_dataSize = (size_t)(round_up(level_w, data_padding) * round_up(level_h, data_padding) * bpp/8);
149 :
150 137 : if(level >= 0)
151 137 : cb((size_t)level, level_w, level_h, level_data, level_dataSize, cbData);
152 :
153 137 : level_data += level_dataSize;
154 :
155 : // 1x1 reached - done
156 137 : if(level_w == 1 && level_h == 1)
157 : break;
158 103 : level_w /= 2;
159 103 : level_h /= 2;
160 : // if the texture is non-square, one of the dimensions will become
161 : // 0 before the other. to satisfy OpenGL's expectations, change it
162 : // back to 1.
163 103 : if(level_w == 0) level_w = 1;
164 103 : if(level_h == 0) level_h = 1;
165 103 : level++;
166 :
167 : // special case: no mipmaps, we were only supposed to call for
168 : // the base level
169 103 : if(levels_to_skip == TEX_BASE_LEVEL_ONLY)
170 : break;
171 : }
172 59 : }
173 :
174 :
175 : struct CreateLevelData
176 : {
177 : size_t num_components;
178 :
179 : size_t prev_level_w;
180 : size_t prev_level_h;
181 : const std::uint8_t* prev_level_data;
182 : size_t prev_level_dataSize;
183 : };
184 :
185 : // uses 2x2 box filter
186 2 : static void create_level(size_t level, size_t level_w, size_t level_h,
187 : const std::uint8_t* RESTRICT level_data, size_t level_dataSize, void* RESTRICT cbData)
188 : {
189 2 : CreateLevelData* cld = (CreateLevelData*)cbData;
190 2 : const size_t src_w = cld->prev_level_w;
191 2 : const size_t src_h = cld->prev_level_h;
192 2 : const std::uint8_t* src = cld->prev_level_data;
193 2 : std::uint8_t* dst = const_cast<std::uint8_t*>(level_data);
194 :
195 : // base level - must be copied over from source buffer
196 2 : if(level == 0)
197 : {
198 1 : ENSURE(level_dataSize == cld->prev_level_dataSize);
199 1 : memcpy(dst, src, level_dataSize);
200 : }
201 : else
202 : {
203 1 : const size_t num_components = cld->num_components;
204 1 : const size_t dx = num_components, dy = dx*src_w;
205 :
206 : // special case: image is too small for 2x2 filter
207 1 : if(cld->prev_level_w == 1 || cld->prev_level_h == 1)
208 : {
209 : // image is either a horizontal or vertical line.
210 : // their memory layout is the same (packed pixels), so no special
211 : // handling is needed; just pick max dimension.
212 0 : for(size_t y = 0; y < std::max(src_w, src_h); y += 2)
213 : {
214 0 : for(size_t i = 0; i < num_components; i++)
215 : {
216 0 : *dst++ = (src[0]+src[dx]+1)/2;
217 0 : src += 1;
218 : }
219 :
220 0 : src += dx; // skip to next pixel (since box is 2x2)
221 : }
222 : }
223 : // normal
224 : else
225 : {
226 2 : for(size_t y = 0; y < src_h; y += 2)
227 : {
228 2 : for(size_t x = 0; x < src_w; x += 2)
229 : {
230 4 : for(size_t i = 0; i < num_components; i++)
231 : {
232 3 : *dst++ = (src[0]+src[dx]+src[dy]+src[dx+dy]+2)/4;
233 3 : src += 1;
234 : }
235 :
236 1 : src += dx; // skip to next pixel (since box is 2x2)
237 : }
238 :
239 1 : src += dy; // skip to next row (since box is 2x2)
240 : }
241 : }
242 :
243 1 : ENSURE(dst == level_data + level_dataSize);
244 1 : ENSURE(src == cld->prev_level_data + cld->prev_level_dataSize);
245 : }
246 :
247 2 : cld->prev_level_data = level_data;
248 2 : cld->prev_level_dataSize = level_dataSize;
249 2 : cld->prev_level_w = level_w;
250 2 : cld->prev_level_h = level_h;
251 2 : }
252 :
253 :
254 1 : static Status add_mipmaps(Tex* t, size_t w, size_t h, size_t bpp, void* newData, size_t dataSize)
255 : {
256 : // this code assumes the image is of POT dimension; we don't
257 : // go to the trouble of implementing image scaling because
258 : // the only place this is used (backend textures) requires POT anyway.
259 1 : if(!std::has_single_bit(w) || !std::has_single_bit(h))
260 0 : WARN_RETURN(ERR::TEX_INVALID_SIZE);
261 1 : t->m_Flags |= TEX_MIPMAPS; // must come before tex_img_size!
262 1 : const size_t mipmap_size = t->img_size();
263 1 : std::shared_ptr<std::uint8_t> mipmapData;
264 1 : AllocateAligned(mipmapData, mipmap_size);
265 1 : CreateLevelData cld = { bpp/8, w, h, static_cast<const std::uint8_t*>(newData), dataSize };
266 1 : tex_util_foreach_mipmap(w, h, bpp, mipmapData.get(), 0, 1, create_level, &cld);
267 1 : t->m_Data = mipmapData;
268 1 : t->m_DataSize = mipmap_size;
269 1 : t->m_Ofs = 0;
270 :
271 1 : return INFO::OK;
272 : }
273 :
274 :
275 : //-----------------------------------------------------------------------------
276 : // pixel format conversion (transformation)
277 : //-----------------------------------------------------------------------------
278 :
279 : // handles BGR and row flipping in "plain" format (see below).
280 : //
281 : // called by codecs after they get their format-specific transforms out of
282 : // the way. note that this approach requires several passes over the image,
283 : // but is much easier to maintain than providing all<->all conversion paths.
284 : //
285 : // somewhat optimized (loops are hoisted, cache associativity accounted for)
286 14 : static Status plain_transform(Tex* t, size_t transforms)
287 : {
288 14 : CHECK_TEX(t);
289 :
290 : // extract texture info
291 14 : const size_t w = t->m_Width, h = t->m_Height, bpp = t->m_Bpp;
292 14 : const size_t flags = t->m_Flags;
293 14 : std::uint8_t* const srcStorage = t->get_data();
294 :
295 : // sanity checks (not errors, we just can't handle these cases)
296 : // .. unknown transform
297 14 : if(transforms & ~(TEX_BGR|TEX_ORIENTATION|TEX_MIPMAPS|TEX_ALPHA))
298 : return INFO::TEX_CODEC_CANNOT_HANDLE;
299 : // .. data is not in "plain" format
300 14 : RETURN_STATUS_IF_ERR(tex_validate_plain_format(bpp, flags));
301 : // .. nothing to do
302 14 : if(!transforms)
303 : return INFO::OK;
304 :
305 14 : const size_t srcSize = t->img_size();
306 14 : size_t dstSize = srcSize;
307 :
308 14 : if(transforms & TEX_ALPHA)
309 : {
310 : // add alpha channel
311 9 : if(bpp == 24)
312 : {
313 9 : dstSize = (srcSize / 3) * 4;
314 9 : t->m_Bpp = 32;
315 : }
316 : // remove alpha channel
317 : else if(bpp == 32)
318 : {
319 : return INFO::TEX_CODEC_CANNOT_HANDLE;
320 : }
321 : // can't have alpha with grayscale
322 : else
323 : {
324 : return INFO::TEX_CODEC_CANNOT_HANDLE;
325 : }
326 : }
327 :
328 : // allocate copy of the image data.
329 : // rationale: L1 cache is typically A2 => swapping in-place with a
330 : // line buffer leads to thrashing. we'll assume the whole texture*2
331 : // fits in cache, allocate a copy, and transfer directly from there.
332 : //
333 : // this is necessary even when not flipping because the initial data
334 : // is read-only.
335 14 : std::shared_ptr<std::uint8_t> dstStorage;
336 14 : AllocateAligned(dstStorage, dstSize);
337 :
338 : // setup row source/destination pointers (simplifies outer loop)
339 14 : std::uint8_t* dst = static_cast<std::uint8_t*>(dstStorage.get());
340 14 : const std::uint8_t* src;
341 14 : const size_t pitch = w * bpp/8; // source bpp (not necessarily dest bpp)
342 : // .. avoid y*pitch multiply in row loop; instead, add row_ofs.
343 14 : ssize_t row_ofs = (ssize_t)pitch;
344 :
345 : // flipping rows (0,1,2 -> 2,1,0)
346 14 : if(transforms & TEX_ORIENTATION)
347 : {
348 7 : src = static_cast<const std::uint8_t*>(srcStorage) + srcSize - pitch; // last row
349 7 : row_ofs = -(ssize_t)pitch;
350 : }
351 : // adding/removing alpha channel (can't convert in-place)
352 7 : else if(transforms & TEX_ALPHA)
353 : {
354 : src = static_cast<const std::uint8_t*>(srcStorage);
355 : }
356 : // do other transforms in-place
357 : else
358 : {
359 4 : src = static_cast<const std::uint8_t*>(dstStorage.get());
360 4 : memcpy(dstStorage.get(), srcStorage, srcSize);
361 : }
362 :
363 : // no conversion necessary
364 14 : if(!(transforms & (TEX_BGR | TEX_ALPHA)))
365 : {
366 2 : if(src != dst) // avoid overlapping memcpy if not flipping rows
367 : {
368 65 : for(size_t y = 0; y < h; y++)
369 : {
370 64 : memcpy(dst, src, pitch);
371 64 : dst += pitch;
372 64 : src += row_ofs;
373 : }
374 : }
375 : }
376 : // RGB -> BGRA, BGR -> RGBA
377 12 : else if(bpp == 24 && (transforms & TEX_ALPHA) && (transforms & TEX_BGR))
378 : {
379 87 : for(size_t y = 0; y < h; y++)
380 : {
381 4244 : for(size_t x = 0; x < w; x++)
382 : {
383 : // need temporaries in case src == dst (i.e. not flipping)
384 4166 : const std::uint8_t b = src[0], g = src[1], r = src[2];
385 4166 : dst[0] = r; dst[1] = g; dst[2] = b; dst[3] = 0xFF;
386 4166 : dst += 4;
387 4166 : src += 3;
388 : }
389 78 : src += row_ofs - pitch; // flip? previous row : stay
390 : }
391 : }
392 : // RGB -> RGBA, BGR -> BGRA
393 0 : else if(bpp == 24 && (transforms & TEX_ALPHA) && !(transforms & TEX_BGR))
394 : {
395 0 : for(size_t y = 0; y < h; y++)
396 : {
397 0 : for(size_t x = 0; x < w; x++)
398 : {
399 : // need temporaries in case src == dst (i.e. not flipping)
400 0 : const std::uint8_t r = src[0], g = src[1], b = src[2];
401 0 : dst[0] = r; dst[1] = g; dst[2] = b; dst[3] = 0xFF;
402 0 : dst += 4;
403 0 : src += 3;
404 : }
405 0 : src += row_ofs - pitch; // flip? previous row : stay
406 : }
407 : }
408 : // RGB <-> BGR
409 3 : else if(bpp == 24 && !(transforms & TEX_ALPHA))
410 : {
411 0 : for(size_t y = 0; y < h; y++)
412 : {
413 0 : for(size_t x = 0; x < w; x++)
414 : {
415 : // need temporaries in case src == dst (i.e. not flipping)
416 0 : const std::uint8_t b = src[0], g = src[1], r = src[2];
417 0 : dst[0] = r; dst[1] = g; dst[2] = b;
418 0 : dst += 3;
419 0 : src += 3;
420 : }
421 0 : src += row_ofs - pitch; // flip? previous row : stay
422 : }
423 : }
424 : // RGBA <-> BGRA
425 3 : else if(bpp == 32 && !(transforms & TEX_ALPHA))
426 : {
427 195 : for(size_t y = 0; y < h; y++)
428 : {
429 12480 : for(size_t x = 0; x < w; x++)
430 : {
431 : // need temporaries in case src == dst (i.e. not flipping)
432 12288 : const std::uint8_t b = src[0], g = src[1], r = src[2], a = src[3];
433 12288 : dst[0] = r; dst[1] = g; dst[2] = b; dst[3] = a;
434 12288 : dst += 4;
435 12288 : src += 4;
436 : }
437 192 : src += row_ofs - pitch; // flip? previous row : stay
438 : }
439 : }
440 : else
441 : {
442 0 : debug_warn(L"unsupported transform");
443 0 : return INFO::TEX_CODEC_CANNOT_HANDLE;
444 : }
445 :
446 14 : t->m_Data = dstStorage;
447 14 : t->m_DataSize = dstSize;
448 14 : t->m_Ofs = 0;
449 :
450 14 : if(!(t->m_Flags & TEX_MIPMAPS) && transforms & TEX_MIPMAPS)
451 1 : RETURN_STATUS_IF_ERR(add_mipmaps(t, w, h, bpp, dstStorage.get(), dstSize));
452 :
453 14 : CHECK_TEX(t);
454 : return INFO::OK;
455 14 : }
456 :
457 : // change the pixel format by flipping the state of all TEX_* flags
458 : // that are set in transforms.
459 15 : Status Tex::transform(size_t transforms)
460 : {
461 15 : CHECK_TEX(this);
462 :
463 15 : const size_t target_flags = m_Flags ^ transforms;
464 32 : size_t remaining_transforms;
465 32 : for(;;)
466 : {
467 32 : remaining_transforms = target_flags ^ m_Flags;
468 : // we're finished (all required transforms have been done)
469 32 : if(remaining_transforms == 0)
470 : return INFO::OK;
471 :
472 30 : Status ret = tex_codec_transform(this, remaining_transforms);
473 30 : UpdateMIPLevels();
474 30 : if(ret != INFO::OK)
475 : break;
476 : }
477 :
478 : // last chance
479 13 : RETURN_STATUS_IF_ERR(plain_transform(this, remaining_transforms));
480 13 : UpdateMIPLevels();
481 13 : return INFO::OK;
482 : }
483 :
484 :
485 : // change the pixel format to the new format specified by <new_flags>.
486 : // (note: this is equivalent to transform(t, t->flags^new_flags).
487 15 : Status Tex::transform_to(size_t new_flags)
488 : {
489 : // transform takes care of validating
490 15 : const size_t transforms = m_Flags ^ new_flags;
491 9 : return transform(transforms);
492 : }
493 :
494 :
495 : //-----------------------------------------------------------------------------
496 : // image orientation
497 : //-----------------------------------------------------------------------------
498 :
499 : // see "Default Orientation" in docs.
500 :
501 : static int global_orientation = TEX_TOP_DOWN;
502 :
503 : // set the orientation (either TEX_BOTTOM_UP or TEX_TOP_DOWN) to which
504 : // all loaded images will automatically be converted
505 : // (excepting file formats that don't specify their orientation, i.e. DDS).
506 0 : void tex_set_global_orientation(int o)
507 : {
508 0 : ENSURE(o == TEX_TOP_DOWN || o == TEX_BOTTOM_UP);
509 0 : global_orientation = o;
510 0 : }
511 :
512 :
513 14 : static void flip_to_global_orientation(Tex* t)
514 : {
515 : // (can't use normal CHECK_TEX due to void return)
516 14 : WARN_IF_ERR(t->validate());
517 :
518 14 : size_t orientation = t->m_Flags & TEX_ORIENTATION;
519 : // if codec knows which way around the image is (i.e. not DDS):
520 14 : if(orientation)
521 : {
522 : // flip image if necessary
523 1 : size_t transforms = orientation ^ global_orientation;
524 1 : WARN_IF_ERR(plain_transform(t, transforms));
525 : }
526 :
527 : // indicate image is at global orientation. this is still done even
528 : // if the codec doesn't know: the default orientation should be chosen
529 : // to make that work correctly (see "Default Orientation" in docs).
530 14 : t->m_Flags = (t->m_Flags & ~TEX_ORIENTATION) | global_orientation;
531 :
532 : // (can't use normal CHECK_TEX due to void return)
533 14 : WARN_IF_ERR(t->validate());
534 14 : }
535 :
536 :
537 : // indicate if the orientation specified by <src_flags> matches
538 : // dst_orientation (if the latter is 0, then the global_orientation).
539 : // (we ask for src_flags instead of src_orientation so callers don't
540 : // have to mask off TEX_ORIENTATION)
541 3 : bool tex_orientations_match(size_t src_flags, size_t dst_orientation)
542 : {
543 3 : const size_t src_orientation = src_flags & TEX_ORIENTATION;
544 3 : if(dst_orientation == 0)
545 3 : dst_orientation = global_orientation;
546 3 : return (src_orientation == dst_orientation);
547 : }
548 :
549 :
550 : //-----------------------------------------------------------------------------
551 : // misc. API
552 : //-----------------------------------------------------------------------------
553 :
554 : // indicate if <filename>'s extension is that of a texture format
555 : // supported by Tex::load. case-insensitive.
556 : //
557 : // rationale: Tex::load complains if the given file is of an
558 : // unsupported type. this API allows users to preempt that warning
559 : // (by checking the filename themselves), and also provides for e.g.
560 : // enumerating only images in a file picker.
561 : // an alternative might be a flag to suppress warning about invalid files,
562 : // but this is open to misuse.
563 0 : bool tex_is_known_extension(const VfsPath& pathname)
564 : {
565 0 : const ITexCodec* dummy;
566 : // found codec for it => known extension
567 0 : const OsPath extension = pathname.Extension();
568 0 : if(tex_codec_for_filename(extension, &dummy) == INFO::OK)
569 0 : return true;
570 :
571 : return false;
572 0 : }
573 :
574 :
575 : // store the given image data into a Tex object; this will be as if
576 : // it had been loaded via Tex::load.
577 : //
578 : // rationale: support for in-memory images is necessary for
579 : // emulation of glCompressedTexImage2D and useful overall.
580 : // however, we don't want to provide an alternate interface for each API;
581 : // these would have to be changed whenever fields are added to Tex.
582 : // instead, provide one entry point for specifying images.
583 : //
584 : // we need only add bookkeeping information and "wrap" it in
585 : // our Tex struct, hence the name.
586 13 : Status Tex::wrap(size_t w, size_t h, size_t bpp, size_t flags, const std::shared_ptr<std::uint8_t>& data,
587 : size_t ofs)
588 : {
589 13 : m_Width = w;
590 13 : m_Height = h;
591 13 : m_Bpp = bpp;
592 13 : m_Flags = flags;
593 13 : m_Data = data;
594 13 : m_DataSize = ofs + w*h*bpp/8;
595 13 : m_Ofs = ofs;
596 :
597 13 : CHECK_TEX(this);
598 :
599 13 : UpdateMIPLevels();
600 :
601 13 : return INFO::OK;
602 : }
603 :
604 :
605 : // free all resources associated with the image and make further
606 : // use of it impossible.
607 24 : void Tex::free()
608 : {
609 : // do not validate - this is called from Tex::load if loading
610 : // failed, so not all fields may be valid.
611 :
612 30 : m_Data.reset();
613 :
614 : // TODO: refactor fields zeroing.
615 18 : }
616 :
617 :
618 : //-----------------------------------------------------------------------------
619 : // getters
620 : //-----------------------------------------------------------------------------
621 :
622 : // returns a pointer to the image data (pixels), taking into account any
623 : // header(s) that may come before it.
624 37 : std::uint8_t* Tex::get_data()
625 : {
626 : // (can't use normal CHECK_TEX due to std::uint8_t* return value)
627 37 : WARN_IF_ERR(validate());
628 :
629 37 : std::uint8_t* p = m_Data.get();
630 37 : if(!p)
631 : return nullptr;
632 37 : return p + m_Ofs;
633 : }
634 :
635 : // returns color of 1x1 mipmap level
636 6 : std::uint32_t Tex::get_average_color() const
637 : {
638 : // require mipmaps
639 6 : if(!(m_Flags & TEX_MIPMAPS))
640 : return 0;
641 :
642 : // find the total size of image data
643 6 : size_t size = img_size();
644 :
645 : // compute the size of the last (1x1) mipmap level
646 6 : const size_t data_padding = (m_Flags & TEX_DXT)? 4 : 1;
647 6 : size_t last_level_size = (size_t)(data_padding * data_padding * m_Bpp/8);
648 :
649 : // construct a new texture based on the current one,
650 : // but only include the last mipmap level
651 : // do this so that we can use the general conversion methods for the pixel data
652 6 : Tex basetex;
653 6 : std::shared_ptr<uint8_t> data;
654 6 : WARN_IF_ERR(AllocateAligned(data, last_level_size));
655 6 : memcpy(data.get(), m_Data.get() + m_Ofs + size - last_level_size, last_level_size);
656 6 : basetex.wrap(1, 1, m_Bpp, m_Flags, data, 0);
657 :
658 : // convert to BGRA
659 6 : WARN_IF_ERR(basetex.transform_to(TEX_BGR | TEX_ALPHA));
660 :
661 : // extract components into std::uint32_t
662 6 : ENSURE(basetex.m_DataSize >= basetex.m_Ofs+4);
663 6 : std::uint8_t b = basetex.m_Data.get()[basetex.m_Ofs];
664 6 : std::uint8_t g = basetex.m_Data.get()[basetex.m_Ofs+1];
665 6 : std::uint8_t r = basetex.m_Data.get()[basetex.m_Ofs+2];
666 6 : std::uint8_t a = basetex.m_Data.get()[basetex.m_Ofs+3];
667 6 : return b + (g << 8) + (r << 16) + (a << 24);
668 6 : }
669 :
670 :
671 125 : static void add_level_size(size_t /*level*/, size_t /*level_w*/, size_t /*level_h*/,
672 : const std::uint8_t* RESTRICT /*level_data*/, size_t level_dataSize, void* RESTRICT cbData)
673 : {
674 125 : size_t* ptotal_size = (size_t*)cbData;
675 125 : *ptotal_size += level_dataSize;
676 125 : }
677 :
678 : // return total byte size of the image pixels. (including mipmaps!)
679 : // this is preferable to calculating manually because it's
680 : // less error-prone (e.g. confusing bits_per_pixel with bytes).
681 48 : size_t Tex::img_size() const
682 : {
683 : // (can't use normal CHECK_TEX due to size_t return value)
684 48 : WARN_IF_ERR(validate());
685 :
686 48 : const int levels_to_skip = (m_Flags & TEX_MIPMAPS)? 0 : TEX_BASE_LEVEL_ONLY;
687 48 : const size_t data_padding = (m_Flags & TEX_DXT)? 4 : 1;
688 48 : size_t out_size = 0;
689 48 : tex_util_foreach_mipmap(m_Width, m_Height, m_Bpp, 0, levels_to_skip, data_padding, add_level_size, &out_size);
690 48 : return out_size;
691 : }
692 :
693 :
694 : // return the minimum header size (i.e. offset to pixel data) of the
695 : // file format indicated by <fn>'s extension (that is all it need contain:
696 : // e.g. ".bmp"). returns 0 on error (i.e. no codec found).
697 : // this can be used to optimize calls to tex_write: when allocating the
698 : // buffer that will hold the image, allocate this much extra and
699 : // pass the pointer as base+hdr_size. this allows writing the header
700 : // directly into the output buffer and makes for zero-copy IO.
701 0 : size_t tex_hdr_size(const VfsPath& filename)
702 : {
703 0 : const ITexCodec* c;
704 :
705 0 : const OsPath extension = filename.Extension();
706 0 : WARN_RETURN_STATUS_IF_ERR(tex_codec_for_filename(extension, &c));
707 0 : return c->hdr_size(0);
708 0 : }
709 :
710 :
711 : //-----------------------------------------------------------------------------
712 : // read/write from memory and disk
713 : //-----------------------------------------------------------------------------
714 :
715 14 : Status Tex::decode(const std::shared_ptr<std::uint8_t>& Data, size_t DataSize)
716 : {
717 14 : const ITexCodec* c;
718 14 : RETURN_STATUS_IF_ERR(tex_codec_for_header(Data.get(), DataSize, &c));
719 :
720 : // make sure the entire header is available
721 14 : const size_t min_hdr_size = c->hdr_size(0);
722 14 : if(DataSize < min_hdr_size)
723 : return ERR::TEX_INCOMPLETE_HEADER;
724 14 : const size_t hdr_size = c->hdr_size(Data.get());
725 14 : if(DataSize < hdr_size)
726 : return ERR::TEX_INCOMPLETE_HEADER;
727 :
728 14 : m_Data = Data;
729 14 : m_DataSize = DataSize;
730 14 : m_Ofs = hdr_size;
731 :
732 14 : RETURN_STATUS_IF_ERR(c->decode(Data.get(), DataSize, this));
733 :
734 : // sanity checks
735 14 : if(!m_Width || !m_Height || m_Bpp > 32)
736 : return ERR::TEX_FMT_INVALID;
737 14 : if(m_DataSize < m_Ofs + img_size())
738 : return ERR::TEX_INVALID_SIZE;
739 :
740 14 : flip_to_global_orientation(this);
741 :
742 14 : CHECK_TEX(this);
743 :
744 14 : UpdateMIPLevels();
745 :
746 : return INFO::OK;
747 : }
748 :
749 :
750 0 : Status Tex::encode(const OsPath& extension, DynArray* da)
751 : {
752 0 : CHECK_TEX(this);
753 0 : WARN_RETURN_STATUS_IF_ERR(tex_validate_plain_format(m_Bpp, m_Flags));
754 :
755 : // we could be clever here and avoid the extra alloc if our current
756 : // memory block ensued from the same kind of texture file. this is
757 : // most likely the case if in_img == get_data() + c->hdr_size(0).
758 : // this would make for zero-copy IO.
759 :
760 0 : const size_t max_out_size = img_size()*4 + 256*KiB;
761 0 : RETURN_STATUS_IF_ERR(da_alloc(da, max_out_size));
762 :
763 0 : const ITexCodec* c;
764 0 : WARN_RETURN_STATUS_IF_ERR(tex_codec_for_filename(extension, &c));
765 :
766 : // encode into <da>
767 0 : Status err = c->encode(this, da);
768 0 : if(err < 0)
769 : {
770 0 : (void)da_free(da);
771 0 : WARN_RETURN(err);
772 : }
773 :
774 : return INFO::OK;
775 : }
776 :
777 70 : void Tex::UpdateMIPLevels()
778 : {
779 70 : m_MIPLevels.clear();
780 :
781 70 : if (m_Flags & TEX_MIPMAPS)
782 : {
783 : // We need to account the smallest 1x1 level.
784 14 : const size_t maxSide{std::max(m_Width, m_Height)};
785 28 : m_MIPLevels.reserve(std::bit_width(maxSide) + !std::has_single_bit(maxSide));
786 : }
787 :
788 70 : std::uint8_t* levelData = m_Data.get();
789 70 : levelData += m_Ofs;
790 :
791 70 : const std::uint32_t dataPadding = (m_Flags & TEX_DXT) != 0 ? 4 : 1;
792 70 : std::uint32_t levelWidth = m_Width, levelHeight = m_Height;
793 150 : for (;;)
794 : {
795 110 : const std::uint32_t levelDataSize = round_up(levelWidth, dataPadding) * round_up(levelHeight, dataPadding) * m_Bpp / 8;
796 110 : m_MIPLevels.emplace_back();
797 110 : m_MIPLevels.back().data = levelData;
798 110 : m_MIPLevels.back().dataSize = levelDataSize;
799 110 : m_MIPLevels.back().width = levelWidth;
800 110 : m_MIPLevels.back().height = levelHeight;
801 :
802 110 : if (!(m_Flags & TEX_MIPMAPS))
803 : break;
804 :
805 54 : if (levelWidth == 1 && levelHeight == 1)
806 : break;
807 :
808 40 : levelData += levelDataSize;
809 40 : levelWidth = std::max<std::uint32_t>(levelWidth / 2, 1);
810 40 : levelHeight = std::max<std::uint32_t>(levelHeight / 2, 1);
811 40 : }
812 70 : }
|