Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/basis_universal/encoder/basisu_enc.cpp
20920 views
1
// basisu_enc.cpp
2
// Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.
3
//
4
// Licensed under the Apache License, Version 2.0 (the "License");
5
// you may not use this file except in compliance with the License.
6
// You may obtain a copy of the License at
7
//
8
// http://www.apache.org/licenses/LICENSE-2.0
9
//
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
#include "basisu_enc.h"
16
#include "basisu_resampler.h"
17
#include "basisu_resampler_filters.h"
18
#include "basisu_etc.h"
19
#include "../transcoder/basisu_transcoder.h"
20
#include "basisu_bc7enc.h"
21
#include "jpgd.h"
22
#include "pvpngreader.h"
23
#include "basisu_opencl.h"
24
#include "basisu_uastc_hdr_4x4_enc.h"
25
#include "basisu_astc_hdr_6x6_enc.h"
26
27
#include <vector>
28
29
#ifndef TINYEXR_USE_ZFP
30
#define TINYEXR_USE_ZFP (1)
31
#endif
32
#include <tinyexr.h>
33
34
#ifndef MINIZ_HEADER_FILE_ONLY
35
#define MINIZ_HEADER_FILE_ONLY
36
#endif
37
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
38
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
39
#endif
40
#include "basisu_miniz.h"
41
42
#if defined(_WIN32)
43
// For QueryPerformanceCounter/QueryPerformanceFrequency
44
#define WIN32_LEAN_AND_MEAN
45
#include <windows.h>
46
#endif
47
48
namespace basisu
49
{
50
uint64_t interval_timer::g_init_ticks, interval_timer::g_freq;
51
double interval_timer::g_timer_freq;
52
53
#if BASISU_SUPPORT_SSE
54
bool g_cpu_supports_sse41;
55
#endif
56
57
fast_linear_to_srgb g_fast_linear_to_srgb;
58
59
uint8_t g_hamming_dist[256] =
60
{
61
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
62
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
63
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
64
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
65
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
66
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
67
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
68
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
69
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
70
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
71
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
72
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
73
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
74
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
75
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
76
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
77
};
78
79
// This is a Public Domain 8x8 font from here:
80
// https://github.com/dhepper/font8x8/blob/master/font8x8_basic.h
81
const uint8_t g_debug_font8x8_basic[127 - 32 + 1][8] =
82
{
83
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 ( )
84
{ 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!)
85
{ 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (")
86
{ 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#)
87
{ 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($)
88
{ 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%)
89
{ 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&)
90
{ 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (')
91
{ 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (()
92
{ 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ())
93
{ 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*)
94
{ 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+)
95
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,)
96
{ 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-)
97
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.)
98
{ 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/)
99
{ 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0)
100
{ 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1)
101
{ 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2)
102
{ 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3)
103
{ 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4)
104
{ 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5)
105
{ 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6)
106
{ 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7)
107
{ 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8)
108
{ 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9)
109
{ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:)
110
{ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (;)
111
{ 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<)
112
{ 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=)
113
{ 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>)
114
{ 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?)
115
{ 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@)
116
{ 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A)
117
{ 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B)
118
{ 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C)
119
{ 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D)
120
{ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E)
121
{ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F)
122
{ 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G)
123
{ 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H)
124
{ 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I)
125
{ 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J)
126
{ 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K)
127
{ 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L)
128
{ 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M)
129
{ 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N)
130
{ 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O)
131
{ 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P)
132
{ 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q)
133
{ 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R)
134
{ 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S)
135
{ 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T)
136
{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U)
137
{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V)
138
{ 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W)
139
{ 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X)
140
{ 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y)
141
{ 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z)
142
{ 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([)
143
{ 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\)
144
{ 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (])
145
{ 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^)
146
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_)
147
{ 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`)
148
{ 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a)
149
{ 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b)
150
{ 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c)
151
{ 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d)
152
{ 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e)
153
{ 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f)
154
{ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g)
155
{ 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h)
156
{ 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i)
157
{ 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j)
158
{ 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k)
159
{ 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l)
160
{ 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m)
161
{ 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n)
162
{ 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o)
163
{ 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p)
164
{ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q)
165
{ 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r)
166
{ 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s)
167
{ 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t)
168
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u)
169
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v)
170
{ 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w)
171
{ 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x)
172
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y)
173
{ 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z)
174
{ 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({)
175
{ 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|)
176
{ 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (})
177
{ 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~)
178
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F
179
};
180
181
bool g_library_initialized;
182
std::mutex g_encoder_init_mutex;
183
184
// Encoder library initialization (just call once at startup)
185
bool basisu_encoder_init(bool use_opencl, bool opencl_force_serialization)
186
{
187
std::lock_guard<std::mutex> lock(g_encoder_init_mutex);
188
189
if (g_library_initialized)
190
return true;
191
192
detect_sse41();
193
194
basist::basisu_transcoder_init();
195
pack_etc1_solid_color_init();
196
//uastc_init();
197
bc7enc_compress_block_init(); // must be after uastc_init()
198
199
// Don't bother initializing the OpenCL module at all if it's been completely disabled.
200
if (use_opencl)
201
{
202
opencl_init(opencl_force_serialization);
203
}
204
205
interval_timer::init(); // make sure interval_timer globals are initialized from main thread to avoid TSAN reports
206
207
astc_hdr_enc_init();
208
basist::bc6h_enc_init();
209
astc_6x6_hdr::global_init();
210
211
g_library_initialized = true;
212
return true;
213
}
214
215
void basisu_encoder_deinit()
216
{
217
opencl_deinit();
218
219
g_library_initialized = false;
220
}
221
222
void error_vprintf(const char* pFmt, va_list args)
223
{
224
const uint32_t BUF_SIZE = 256;
225
char buf[BUF_SIZE];
226
227
va_list args_copy;
228
va_copy(args_copy, args);
229
int total_chars = vsnprintf(buf, sizeof(buf), pFmt, args_copy);
230
va_end(args_copy);
231
232
if (total_chars < 0)
233
{
234
assert(0);
235
return;
236
}
237
238
if (total_chars >= (int)BUF_SIZE)
239
{
240
basisu::vector<char> var_buf(total_chars + 1);
241
242
va_copy(args_copy, args);
243
int total_chars_retry = vsnprintf(var_buf.data(), var_buf.size(), pFmt, args_copy);
244
va_end(args_copy);
245
246
if (total_chars_retry < 0)
247
{
248
assert(0);
249
return;
250
}
251
252
fprintf(stderr, "ERROR: %s", var_buf.data());
253
}
254
else
255
{
256
fprintf(stderr, "ERROR: %s", buf);
257
}
258
}
259
260
void error_printf(const char *pFmt, ...)
261
{
262
va_list args;
263
va_start(args, pFmt);
264
error_vprintf(pFmt, args);
265
va_end(args);
266
}
267
268
#if defined(_WIN32)
269
void platform_sleep(uint32_t ms)
270
{
271
Sleep(ms);
272
}
273
#else
274
void platform_sleep(uint32_t ms)
275
{
276
// TODO
277
}
278
#endif
279
280
#if defined(_WIN32)
281
inline void query_counter(timer_ticks* pTicks)
282
{
283
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(pTicks));
284
}
285
inline void query_counter_frequency(timer_ticks* pTicks)
286
{
287
QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(pTicks));
288
}
289
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
290
#include <sys/time.h>
291
inline void query_counter(timer_ticks* pTicks)
292
{
293
struct timeval cur_time;
294
gettimeofday(&cur_time, NULL);
295
*pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
296
}
297
inline void query_counter_frequency(timer_ticks* pTicks)
298
{
299
*pTicks = 1000000;
300
}
301
#elif defined(__GNUC__)
302
#include <sys/timex.h>
303
inline void query_counter(timer_ticks* pTicks)
304
{
305
struct timeval cur_time;
306
gettimeofday(&cur_time, NULL);
307
*pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
308
}
309
inline void query_counter_frequency(timer_ticks* pTicks)
310
{
311
*pTicks = 1000000;
312
}
313
#else
314
#error TODO
315
#endif
316
317
interval_timer::interval_timer() : m_start_time(0), m_stop_time(0), m_started(false), m_stopped(false)
318
{
319
if (!g_timer_freq)
320
init();
321
}
322
323
void interval_timer::start()
324
{
325
query_counter(&m_start_time);
326
m_started = true;
327
m_stopped = false;
328
}
329
330
void interval_timer::stop()
331
{
332
assert(m_started);
333
query_counter(&m_stop_time);
334
m_stopped = true;
335
}
336
337
double interval_timer::get_elapsed_secs() const
338
{
339
assert(m_started);
340
if (!m_started)
341
return 0;
342
343
timer_ticks stop_time = m_stop_time;
344
if (!m_stopped)
345
query_counter(&stop_time);
346
347
timer_ticks delta = stop_time - m_start_time;
348
return delta * g_timer_freq;
349
}
350
351
void interval_timer::init()
352
{
353
if (!g_timer_freq)
354
{
355
query_counter_frequency(&g_freq);
356
g_timer_freq = 1.0f / g_freq;
357
query_counter(&g_init_ticks);
358
}
359
}
360
361
timer_ticks interval_timer::get_ticks()
362
{
363
if (!g_timer_freq)
364
init();
365
timer_ticks ticks;
366
query_counter(&ticks);
367
return ticks - g_init_ticks;
368
}
369
370
double interval_timer::ticks_to_secs(timer_ticks ticks)
371
{
372
if (!g_timer_freq)
373
init();
374
return ticks * g_timer_freq;
375
}
376
377
// Note this is linear<->sRGB, NOT REC709 which uses slightly different equations/transfer functions.
378
// However the gamuts/white points of REC709 and sRGB are the same.
379
float linear_to_srgb(float l)
380
{
381
assert(l >= 0.0f && l <= 1.0f);
382
if (l < .0031308f)
383
return saturate(l * 12.92f);
384
else
385
return saturate(1.055f * powf(l, 1.0f / 2.4f) - .055f);
386
}
387
388
float srgb_to_linear(float s)
389
{
390
assert(s >= 0.0f && s <= 1.0f);
391
if (s < .04045f)
392
return saturate(s * (1.0f / 12.92f));
393
else
394
return saturate(powf((s + .055f) * (1.0f / 1.055f), 2.4f));
395
}
396
397
const uint32_t MAX_32BIT_ALLOC_SIZE = 250000000;
398
399
bool load_tga(const char* pFilename, image& img)
400
{
401
int w = 0, h = 0, n_chans = 0;
402
uint8_t* pImage_data = read_tga(pFilename, w, h, n_chans);
403
404
if ((!pImage_data) || (!w) || (!h) || ((n_chans != 3) && (n_chans != 4)))
405
{
406
error_printf("Failed loading .TGA image \"%s\"!\n", pFilename);
407
408
if (pImage_data)
409
free(pImage_data);
410
411
return false;
412
}
413
414
if (sizeof(void *) == sizeof(uint32_t))
415
{
416
if (((uint64_t)w * h * n_chans) > MAX_32BIT_ALLOC_SIZE)
417
{
418
error_printf("Image \"%s\" is too large (%ux%u) to process in a 32-bit build!\n", pFilename, w, h);
419
420
if (pImage_data)
421
free(pImage_data);
422
423
return false;
424
}
425
}
426
427
img.resize(w, h);
428
429
const uint8_t *pSrc = pImage_data;
430
for (int y = 0; y < h; y++)
431
{
432
color_rgba *pDst = &img(0, y);
433
434
for (int x = 0; x < w; x++)
435
{
436
pDst->r = pSrc[0];
437
pDst->g = pSrc[1];
438
pDst->b = pSrc[2];
439
pDst->a = (n_chans == 3) ? 255 : pSrc[3];
440
441
pSrc += n_chans;
442
++pDst;
443
}
444
}
445
446
free(pImage_data);
447
448
return true;
449
}
450
451
bool load_qoi(const char* pFilename, image& img)
452
{
453
return false;
454
}
455
456
bool load_png(const uint8_t *pBuf, size_t buf_size, image &img, const char *pFilename)
457
{
458
interval_timer tm;
459
tm.start();
460
461
if (!buf_size)
462
return false;
463
464
uint32_t width = 0, height = 0, num_chans = 0;
465
void* pImage = pv_png::load_png(pBuf, buf_size, 4, width, height, num_chans);
466
467
if (!pImage)
468
{
469
error_printf("pv_png::load_png failed while loading image \"%s\"\n", pFilename);
470
return false;
471
}
472
473
img.grant_ownership(reinterpret_cast<color_rgba*>(pImage), width, height);
474
475
//debug_printf("Total load_png() time: %3.3f secs\n", tm.get_elapsed_secs());
476
477
return true;
478
}
479
480
bool load_png(const char* pFilename, image& img)
481
{
482
uint8_vec buffer;
483
if (!read_file_to_vec(pFilename, buffer))
484
{
485
error_printf("load_png: Failed reading file \"%s\"!\n", pFilename);
486
return false;
487
}
488
489
return load_png(buffer.data(), buffer.size(), img, pFilename);
490
}
491
492
bool load_jpg(const char *pFilename, image& img)
493
{
494
int width = 0, height = 0, actual_comps = 0;
495
uint8_t *pImage_data = jpgd::decompress_jpeg_image_from_file(pFilename, &width, &height, &actual_comps, 4, jpgd::jpeg_decoder::cFlagLinearChromaFiltering);
496
if (!pImage_data)
497
return false;
498
499
img.init(pImage_data, width, height, 4);
500
501
free(pImage_data);
502
503
return true;
504
}
505
506
bool load_jpg(const uint8_t* pBuf, size_t buf_size, image& img)
507
{
508
if (buf_size > INT_MAX)
509
{
510
assert(0);
511
return false;
512
}
513
514
int width = 0, height = 0, actual_comps = 0;
515
uint8_t* pImage_data = jpgd::decompress_jpeg_image_from_memory(pBuf, (int)buf_size, &width, &height, &actual_comps, 4, jpgd::jpeg_decoder::cFlagLinearChromaFiltering);
516
if (!pImage_data)
517
return false;
518
519
img.init(pImage_data, width, height, 4);
520
521
free(pImage_data);
522
523
return true;
524
}
525
526
bool load_image(const char* pFilename, image& img)
527
{
528
std::string ext(string_get_extension(std::string(pFilename)));
529
530
if (ext.length() == 0)
531
return false;
532
533
const char *pExt = ext.c_str();
534
535
if (strcasecmp(pExt, "png") == 0)
536
return load_png(pFilename, img);
537
if (strcasecmp(pExt, "tga") == 0)
538
return load_tga(pFilename, img);
539
if (strcasecmp(pExt, "qoi") == 0)
540
return load_qoi(pFilename, img);
541
if ( (strcasecmp(pExt, "jpg") == 0) || (strcasecmp(pExt, "jfif") == 0) || (strcasecmp(pExt, "jpeg") == 0) )
542
return load_jpg(pFilename, img);
543
544
return false;
545
}
546
547
static void convert_ldr_to_hdr_image(imagef &img, const image &ldr_img, bool ldr_srgb_to_linear, float linear_nit_multiplier = 1.0f, float ldr_black_bias = 0.0f)
548
{
549
img.resize(ldr_img.get_width(), ldr_img.get_height());
550
551
for (uint32_t y = 0; y < ldr_img.get_height(); y++)
552
{
553
for (uint32_t x = 0; x < ldr_img.get_width(); x++)
554
{
555
const color_rgba& c = ldr_img(x, y);
556
557
vec4F& d = img(x, y);
558
if (ldr_srgb_to_linear)
559
{
560
float r = (float)c[0];
561
float g = (float)c[1];
562
float b = (float)c[2];
563
564
if (ldr_black_bias > 0.0f)
565
{
566
// ASTC HDR is noticeably weaker dealing with blocks containing some pixels with components set to 0.
567
// Add a very slight bias less than .5 to avoid this difficulity. When the HDR image is mapped to SDR sRGB and rounded back to 8-bits, this bias will still result in zero.
568
// (FWIW, in reality, a physical monitor would be unlikely to have a perfectly zero black level.)
569
// This is purely optional and on most images it doesn't matter visually.
570
if (r == 0.0f)
571
r = ldr_black_bias;
572
if (g == 0.0f)
573
g = ldr_black_bias;
574
if (b == 0.0f)
575
b = ldr_black_bias;
576
}
577
578
// Compute how much linear light would be emitted by a SDR 80-100 nit monitor.
579
d[0] = srgb_to_linear(r * (1.0f / 255.0f)) * linear_nit_multiplier;
580
d[1] = srgb_to_linear(g * (1.0f / 255.0f)) * linear_nit_multiplier;
581
d[2] = srgb_to_linear(b * (1.0f / 255.0f)) * linear_nit_multiplier;
582
}
583
else
584
{
585
d[0] = c[0] * (1.0f / 255.0f) * linear_nit_multiplier;
586
d[1] = c[1] * (1.0f / 255.0f) * linear_nit_multiplier;
587
d[2] = c[2] * (1.0f / 255.0f) * linear_nit_multiplier;
588
}
589
d[3] = c[3] * (1.0f / 255.0f);
590
}
591
}
592
}
593
594
bool load_image_hdr(const void* pMem, size_t mem_size, imagef& img, uint32_t width, uint32_t height, hdr_image_type img_type, bool ldr_srgb_to_linear, float linear_nit_multiplier, float ldr_black_bias)
595
{
596
if ((!pMem) || (!mem_size))
597
{
598
assert(0);
599
return false;
600
}
601
602
switch (img_type)
603
{
604
case hdr_image_type::cHITRGBAHalfFloat:
605
{
606
if (mem_size != width * height * sizeof(basist::half_float) * 4)
607
{
608
assert(0);
609
return false;
610
}
611
612
if ((!width) || (!height))
613
{
614
assert(0);
615
return false;
616
}
617
618
const basist::half_float* pSrc_image_h = static_cast<const basist::half_float *>(pMem);
619
620
img.resize(width, height);
621
for (uint32_t y = 0; y < height; y++)
622
{
623
for (uint32_t x = 0; x < width; x++)
624
{
625
const basist::half_float* pSrc_pixel = &pSrc_image_h[x * 4];
626
627
vec4F& dst = img(x, y);
628
dst[0] = basist::half_to_float(pSrc_pixel[0]);
629
dst[1] = basist::half_to_float(pSrc_pixel[1]);
630
dst[2] = basist::half_to_float(pSrc_pixel[2]);
631
dst[3] = basist::half_to_float(pSrc_pixel[3]);
632
}
633
634
pSrc_image_h += (width * 4);
635
}
636
637
break;
638
}
639
case hdr_image_type::cHITRGBAFloat:
640
{
641
if (mem_size != width * height * sizeof(float) * 4)
642
{
643
assert(0);
644
return false;
645
}
646
647
if ((!width) || (!height))
648
{
649
assert(0);
650
return false;
651
}
652
653
img.resize(width, height);
654
memcpy((void *)img.get_ptr(), pMem, width * height * sizeof(float) * 4);
655
656
break;
657
}
658
case hdr_image_type::cHITJPGImage:
659
{
660
image ldr_img;
661
if (!load_jpg(static_cast<const uint8_t*>(pMem), mem_size, ldr_img))
662
return false;
663
664
convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
665
break;
666
}
667
case hdr_image_type::cHITPNGImage:
668
{
669
image ldr_img;
670
if (!load_png(static_cast<const uint8_t *>(pMem), mem_size, ldr_img))
671
return false;
672
673
convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
674
break;
675
}
676
case hdr_image_type::cHITEXRImage:
677
{
678
if (!read_exr(pMem, mem_size, img))
679
return false;
680
681
break;
682
}
683
case hdr_image_type::cHITHDRImage:
684
{
685
uint8_vec buf(mem_size);
686
memcpy(buf.get_ptr(), pMem, mem_size);
687
688
rgbe_header_info hdr;
689
if (!read_rgbe(buf, img, hdr))
690
return false;
691
692
break;
693
}
694
default:
695
assert(0);
696
return false;
697
}
698
699
return true;
700
}
701
702
bool is_image_filename_hdr(const char *pFilename)
703
{
704
std::string ext(string_get_extension(std::string(pFilename)));
705
706
if (ext.length() == 0)
707
return false;
708
709
const char* pExt = ext.c_str();
710
711
return ((strcasecmp(pExt, "hdr") == 0) || (strcasecmp(pExt, "exr") == 0));
712
}
713
714
// TODO: move parameters to struct, add a HDR clean flag to eliminate NaN's/Inf's
715
bool load_image_hdr(const char* pFilename, imagef& img, bool ldr_srgb_to_linear, float linear_nit_multiplier, float ldr_black_bias)
716
{
717
std::string ext(string_get_extension(std::string(pFilename)));
718
719
if (ext.length() == 0)
720
return false;
721
722
const char* pExt = ext.c_str();
723
724
if (strcasecmp(pExt, "hdr") == 0)
725
{
726
rgbe_header_info rgbe_info;
727
if (!read_rgbe(pFilename, img, rgbe_info))
728
return false;
729
return true;
730
}
731
732
if (strcasecmp(pExt, "exr") == 0)
733
{
734
int n_chans = 0;
735
if (!read_exr(pFilename, img, n_chans))
736
return false;
737
return true;
738
}
739
740
// Try loading image as LDR, then optionally convert to linear light.
741
{
742
image ldr_img;
743
if (!load_image(pFilename, ldr_img))
744
return false;
745
746
convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
747
}
748
749
return true;
750
}
751
752
bool save_png(const char* pFilename, const image &img, uint32_t image_save_flags, uint32_t grayscale_comp)
753
{
754
if (!img.get_total_pixels())
755
return false;
756
757
void* pPNG_data = nullptr;
758
size_t PNG_data_size = 0;
759
760
if (image_save_flags & cImageSaveGrayscale)
761
{
762
uint8_vec g_pixels(img.get_total_pixels());
763
uint8_t* pDst = &g_pixels[0];
764
765
for (uint32_t y = 0; y < img.get_height(); y++)
766
for (uint32_t x = 0; x < img.get_width(); x++)
767
*pDst++ = img(x, y)[grayscale_comp];
768
769
pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(g_pixels.data(), img.get_width(), img.get_height(), 1, &PNG_data_size, 1, false);
770
}
771
else
772
{
773
bool has_alpha = false;
774
775
if ((image_save_flags & cImageSaveIgnoreAlpha) == 0)
776
has_alpha = img.has_alpha();
777
778
if (!has_alpha)
779
{
780
uint8_vec rgb_pixels(img.get_total_pixels() * 3);
781
uint8_t* pDst = &rgb_pixels[0];
782
783
for (uint32_t y = 0; y < img.get_height(); y++)
784
{
785
const color_rgba* pSrc = &img(0, y);
786
for (uint32_t x = 0; x < img.get_width(); x++)
787
{
788
pDst[0] = pSrc->r;
789
pDst[1] = pSrc->g;
790
pDst[2] = pSrc->b;
791
792
pSrc++;
793
pDst += 3;
794
}
795
}
796
797
pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(rgb_pixels.data(), img.get_width(), img.get_height(), 3, &PNG_data_size, 1, false);
798
}
799
else
800
{
801
pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(img.get_ptr(), img.get_width(), img.get_height(), 4, &PNG_data_size, 1, false);
802
}
803
}
804
805
if (!pPNG_data)
806
return false;
807
808
bool status = write_data_to_file(pFilename, pPNG_data, PNG_data_size);
809
if (!status)
810
{
811
error_printf("save_png: Failed writing to filename \"%s\"!\n", pFilename);
812
}
813
814
free(pPNG_data);
815
816
return status;
817
}
818
819
bool read_file_to_vec(const char* pFilename, uint8_vec& data)
820
{
821
FILE* pFile = nullptr;
822
#ifdef _WIN32
823
fopen_s(&pFile, pFilename, "rb");
824
#else
825
pFile = fopen(pFilename, "rb");
826
#endif
827
if (!pFile)
828
return false;
829
830
fseek(pFile, 0, SEEK_END);
831
#ifdef _WIN32
832
int64_t filesize = _ftelli64(pFile);
833
#else
834
int64_t filesize = ftello(pFile);
835
#endif
836
if (filesize < 0)
837
{
838
fclose(pFile);
839
return false;
840
}
841
fseek(pFile, 0, SEEK_SET);
842
843
if (sizeof(size_t) == sizeof(uint32_t))
844
{
845
if (filesize > 0x70000000)
846
{
847
// File might be too big to load safely in one alloc
848
fclose(pFile);
849
return false;
850
}
851
}
852
853
if (!data.try_resize((size_t)filesize))
854
{
855
fclose(pFile);
856
return false;
857
}
858
859
if (filesize)
860
{
861
if (fread(&data[0], 1, (size_t)filesize, pFile) != (size_t)filesize)
862
{
863
fclose(pFile);
864
return false;
865
}
866
}
867
868
fclose(pFile);
869
return true;
870
}
871
872
bool read_file_to_data(const char* pFilename, void *pData, size_t len)
873
{
874
assert(pData && len);
875
if ((!pData) || (!len))
876
return false;
877
878
FILE* pFile = nullptr;
879
#ifdef _WIN32
880
fopen_s(&pFile, pFilename, "rb");
881
#else
882
pFile = fopen(pFilename, "rb");
883
#endif
884
if (!pFile)
885
return false;
886
887
fseek(pFile, 0, SEEK_END);
888
#ifdef _WIN32
889
int64_t filesize = _ftelli64(pFile);
890
#else
891
int64_t filesize = ftello(pFile);
892
#endif
893
894
if ((filesize < 0) || ((size_t)filesize < len))
895
{
896
fclose(pFile);
897
return false;
898
}
899
fseek(pFile, 0, SEEK_SET);
900
901
if (fread(pData, 1, (size_t)len, pFile) != (size_t)len)
902
{
903
fclose(pFile);
904
return false;
905
}
906
907
fclose(pFile);
908
return true;
909
}
910
911
bool write_data_to_file(const char* pFilename, const void* pData, size_t len)
912
{
913
FILE* pFile = nullptr;
914
#ifdef _WIN32
915
fopen_s(&pFile, pFilename, "wb");
916
#else
917
pFile = fopen(pFilename, "wb");
918
#endif
919
if (!pFile)
920
return false;
921
922
if (len)
923
{
924
if (fwrite(pData, 1, len, pFile) != len)
925
{
926
fclose(pFile);
927
return false;
928
}
929
}
930
931
return fclose(pFile) != EOF;
932
}
933
934
bool image_resample(const image &src, image &dst, bool srgb,
935
const char *pFilter, float filter_scale,
936
bool wrapping,
937
uint32_t first_comp, uint32_t num_comps)
938
{
939
assert((first_comp + num_comps) <= 4);
940
941
const int cMaxComps = 4;
942
943
const uint32_t src_w = src.get_width(), src_h = src.get_height();
944
const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
945
946
if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
947
{
948
printf("Image is too large!\n");
949
return false;
950
}
951
952
if (!src_w || !src_h || !dst_w || !dst_h)
953
return false;
954
955
if ((num_comps < 1) || (num_comps > cMaxComps))
956
return false;
957
958
if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
959
{
960
printf("Image is too large!\n");
961
return false;
962
}
963
964
if ((src_w == dst_w) && (src_h == dst_h))
965
{
966
dst = src;
967
return true;
968
}
969
970
float srgb_to_linear_table[256];
971
if (srgb)
972
{
973
for (int i = 0; i < 256; ++i)
974
srgb_to_linear_table[i] = srgb_to_linear((float)i * (1.0f/255.0f));
975
}
976
977
const int LINEAR_TO_SRGB_TABLE_SIZE = 8192;
978
uint8_t linear_to_srgb_table[LINEAR_TO_SRGB_TABLE_SIZE];
979
980
if (srgb)
981
{
982
for (int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i)
983
linear_to_srgb_table[i] = (uint8_t)clamp<int>((int)(255.0f * linear_to_srgb((float)i * (1.0f / (LINEAR_TO_SRGB_TABLE_SIZE - 1))) + .5f), 0, 255);
984
}
985
986
std::vector<float> samples[cMaxComps];
987
Resampler *resamplers[cMaxComps];
988
989
resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
990
wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
991
pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
992
samples[0].resize(src_w);
993
994
for (uint32_t i = 1; i < num_comps; ++i)
995
{
996
resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
997
wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
998
pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
999
samples[i].resize(src_w);
1000
}
1001
1002
uint32_t dst_y = 0;
1003
1004
for (uint32_t src_y = 0; src_y < src_h; ++src_y)
1005
{
1006
const color_rgba *pSrc = &src(0, src_y);
1007
1008
// Put source lines into resampler(s)
1009
for (uint32_t x = 0; x < src_w; ++x)
1010
{
1011
for (uint32_t c = 0; c < num_comps; ++c)
1012
{
1013
const uint32_t comp_index = first_comp + c;
1014
const uint32_t v = (*pSrc)[comp_index];
1015
1016
if (!srgb || (comp_index == 3))
1017
samples[c][x] = v * (1.0f / 255.0f);
1018
else
1019
samples[c][x] = srgb_to_linear_table[v];
1020
}
1021
1022
pSrc++;
1023
}
1024
1025
for (uint32_t c = 0; c < num_comps; ++c)
1026
{
1027
if (!resamplers[c]->put_line(&samples[c][0]))
1028
{
1029
for (uint32_t i = 0; i < num_comps; i++)
1030
delete resamplers[i];
1031
return false;
1032
}
1033
}
1034
1035
// Now retrieve any output lines
1036
for (;;)
1037
{
1038
uint32_t c;
1039
for (c = 0; c < num_comps; ++c)
1040
{
1041
const uint32_t comp_index = first_comp + c;
1042
1043
const float *pOutput_samples = resamplers[c]->get_line();
1044
if (!pOutput_samples)
1045
break;
1046
1047
const bool linear_flag = !srgb || (comp_index == 3);
1048
1049
color_rgba *pDst = &dst(0, dst_y);
1050
1051
for (uint32_t x = 0; x < dst_w; x++)
1052
{
1053
// TODO: Add dithering
1054
if (linear_flag)
1055
{
1056
int j = (int)(255.0f * pOutput_samples[x] + .5f);
1057
(*pDst)[comp_index] = (uint8_t)clamp<int>(j, 0, 255);
1058
}
1059
else
1060
{
1061
int j = (int)((LINEAR_TO_SRGB_TABLE_SIZE - 1) * pOutput_samples[x] + .5f);
1062
(*pDst)[comp_index] = linear_to_srgb_table[clamp<int>(j, 0, LINEAR_TO_SRGB_TABLE_SIZE - 1)];
1063
}
1064
1065
pDst++;
1066
}
1067
}
1068
if (c < num_comps)
1069
break;
1070
1071
++dst_y;
1072
}
1073
}
1074
1075
for (uint32_t i = 0; i < num_comps; ++i)
1076
delete resamplers[i];
1077
1078
return true;
1079
}
1080
1081
bool image_resample(const imagef& src, imagef& dst,
1082
const char* pFilter, float filter_scale,
1083
bool wrapping,
1084
uint32_t first_comp, uint32_t num_comps)
1085
{
1086
assert((first_comp + num_comps) <= 4);
1087
1088
const int cMaxComps = 4;
1089
1090
const uint32_t src_w = src.get_width(), src_h = src.get_height();
1091
const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
1092
1093
if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
1094
{
1095
printf("Image is too large!\n");
1096
return false;
1097
}
1098
1099
if (!src_w || !src_h || !dst_w || !dst_h)
1100
return false;
1101
1102
if ((num_comps < 1) || (num_comps > cMaxComps))
1103
return false;
1104
1105
if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
1106
{
1107
printf("Image is too large!\n");
1108
return false;
1109
}
1110
1111
if ((src_w == dst_w) && (src_h == dst_h) && (filter_scale == 1.0f))
1112
{
1113
dst = src;
1114
return true;
1115
}
1116
1117
std::vector<float> samples[cMaxComps];
1118
Resampler* resamplers[cMaxComps];
1119
1120
resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
1121
wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
1122
pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
1123
samples[0].resize(src_w);
1124
1125
for (uint32_t i = 1; i < num_comps; ++i)
1126
{
1127
resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
1128
wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
1129
pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
1130
samples[i].resize(src_w);
1131
}
1132
1133
uint32_t dst_y = 0;
1134
1135
for (uint32_t src_y = 0; src_y < src_h; ++src_y)
1136
{
1137
const vec4F* pSrc = &src(0, src_y);
1138
1139
// Put source lines into resampler(s)
1140
for (uint32_t x = 0; x < src_w; ++x)
1141
{
1142
for (uint32_t c = 0; c < num_comps; ++c)
1143
{
1144
const uint32_t comp_index = first_comp + c;
1145
const float v = (*pSrc)[comp_index];
1146
1147
samples[c][x] = v;
1148
}
1149
1150
pSrc++;
1151
}
1152
1153
for (uint32_t c = 0; c < num_comps; ++c)
1154
{
1155
if (!resamplers[c]->put_line(&samples[c][0]))
1156
{
1157
for (uint32_t i = 0; i < num_comps; i++)
1158
delete resamplers[i];
1159
return false;
1160
}
1161
}
1162
1163
// Now retrieve any output lines
1164
for (;;)
1165
{
1166
uint32_t c;
1167
for (c = 0; c < num_comps; ++c)
1168
{
1169
const uint32_t comp_index = first_comp + c;
1170
1171
const float* pOutput_samples = resamplers[c]->get_line();
1172
if (!pOutput_samples)
1173
break;
1174
1175
vec4F* pDst = &dst(0, dst_y);
1176
1177
for (uint32_t x = 0; x < dst_w; x++)
1178
{
1179
(*pDst)[comp_index] = pOutput_samples[x];
1180
pDst++;
1181
}
1182
}
1183
if (c < num_comps)
1184
break;
1185
1186
++dst_y;
1187
}
1188
}
1189
1190
for (uint32_t i = 0; i < num_comps; ++i)
1191
delete resamplers[i];
1192
1193
return true;
1194
}
1195
1196
void canonical_huffman_calculate_minimum_redundancy(sym_freq *A, int num_syms)
1197
{
1198
// See the paper "In-Place Calculation of Minimum Redundancy Codes" by Moffat and Katajainen
1199
if (!num_syms)
1200
return;
1201
1202
if (1 == num_syms)
1203
{
1204
A[0].m_key = 1;
1205
return;
1206
}
1207
1208
A[0].m_key += A[1].m_key;
1209
1210
int s = 2, r = 0, next;
1211
for (next = 1; next < (num_syms - 1); ++next)
1212
{
1213
if ((s >= num_syms) || (A[r].m_key < A[s].m_key))
1214
{
1215
A[next].m_key = A[r].m_key;
1216
A[r].m_key = next;
1217
++r;
1218
}
1219
else
1220
{
1221
A[next].m_key = A[s].m_key;
1222
++s;
1223
}
1224
1225
if ((s >= num_syms) || ((r < next) && A[r].m_key < A[s].m_key))
1226
{
1227
A[next].m_key = A[next].m_key + A[r].m_key;
1228
A[r].m_key = next;
1229
++r;
1230
}
1231
else
1232
{
1233
A[next].m_key = A[next].m_key + A[s].m_key;
1234
++s;
1235
}
1236
}
1237
A[num_syms - 2].m_key = 0;
1238
1239
for (next = num_syms - 3; next >= 0; --next)
1240
{
1241
A[next].m_key = 1 + A[A[next].m_key].m_key;
1242
}
1243
1244
int num_avail = 1, num_used = 0, depth = 0;
1245
r = num_syms - 2;
1246
next = num_syms - 1;
1247
while (num_avail > 0)
1248
{
1249
for ( ; (r >= 0) && ((int)A[r].m_key == depth); ++num_used, --r )
1250
;
1251
1252
for ( ; num_avail > num_used; --next, --num_avail)
1253
A[next].m_key = depth;
1254
1255
num_avail = 2 * num_used;
1256
num_used = 0;
1257
++depth;
1258
}
1259
}
1260
1261
void canonical_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
1262
{
1263
int i;
1264
uint32_t total = 0;
1265
if (code_list_len <= 1)
1266
return;
1267
1268
for (i = max_code_size + 1; i <= cHuffmanMaxSupportedInternalCodeSize; i++)
1269
pNum_codes[max_code_size] += pNum_codes[i];
1270
1271
for (i = max_code_size; i > 0; i--)
1272
total += (((uint32_t)pNum_codes[i]) << (max_code_size - i));
1273
1274
while (total != (1UL << max_code_size))
1275
{
1276
pNum_codes[max_code_size]--;
1277
for (i = max_code_size - 1; i > 0; i--)
1278
{
1279
if (pNum_codes[i])
1280
{
1281
pNum_codes[i]--;
1282
pNum_codes[i + 1] += 2;
1283
break;
1284
}
1285
}
1286
1287
total--;
1288
}
1289
}
1290
1291
sym_freq *canonical_huffman_radix_sort_syms(uint32_t num_syms, sym_freq *pSyms0, sym_freq *pSyms1)
1292
{
1293
uint32_t total_passes = 2, pass_shift, pass, i, hist[256 * 2];
1294
sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
1295
1296
clear_obj(hist);
1297
1298
for (i = 0; i < num_syms; i++)
1299
{
1300
uint32_t freq = pSyms0[i].m_key;
1301
1302
// We scale all input frequencies to 16-bits.
1303
assert(freq <= UINT16_MAX);
1304
1305
hist[freq & 0xFF]++;
1306
hist[256 + ((freq >> 8) & 0xFF)]++;
1307
}
1308
1309
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
1310
total_passes--;
1311
1312
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
1313
{
1314
const uint32_t *pHist = &hist[pass << 8];
1315
uint32_t offsets[256], cur_ofs = 0;
1316
for (i = 0; i < 256; i++)
1317
{
1318
offsets[i] = cur_ofs;
1319
cur_ofs += pHist[i];
1320
}
1321
1322
for (i = 0; i < num_syms; i++)
1323
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
1324
1325
sym_freq *t = pCur_syms;
1326
pCur_syms = pNew_syms;
1327
pNew_syms = t;
1328
}
1329
1330
return pCur_syms;
1331
}
1332
1333
bool huffman_encoding_table::init(uint32_t num_syms, const uint16_t *pFreq, uint32_t max_code_size)
1334
{
1335
if (max_code_size > cHuffmanMaxSupportedCodeSize)
1336
return false;
1337
if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
1338
return false;
1339
1340
uint32_t total_used_syms = 0;
1341
for (uint32_t i = 0; i < num_syms; i++)
1342
if (pFreq[i])
1343
total_used_syms++;
1344
1345
if (!total_used_syms)
1346
return false;
1347
1348
std::vector<sym_freq> sym_freq0(total_used_syms), sym_freq1(total_used_syms);
1349
for (uint32_t i = 0, j = 0; i < num_syms; i++)
1350
{
1351
if (pFreq[i])
1352
{
1353
sym_freq0[j].m_key = pFreq[i];
1354
sym_freq0[j++].m_sym_index = static_cast<uint16_t>(i);
1355
}
1356
}
1357
1358
sym_freq *pSym_freq = canonical_huffman_radix_sort_syms(total_used_syms, &sym_freq0[0], &sym_freq1[0]);
1359
1360
canonical_huffman_calculate_minimum_redundancy(pSym_freq, total_used_syms);
1361
1362
int num_codes[cHuffmanMaxSupportedInternalCodeSize + 1];
1363
clear_obj(num_codes);
1364
1365
for (uint32_t i = 0; i < total_used_syms; i++)
1366
{
1367
if (pSym_freq[i].m_key > cHuffmanMaxSupportedInternalCodeSize)
1368
return false;
1369
1370
num_codes[pSym_freq[i].m_key]++;
1371
}
1372
1373
canonical_huffman_enforce_max_code_size(num_codes, total_used_syms, max_code_size);
1374
1375
m_code_sizes.resize(0);
1376
m_code_sizes.resize(num_syms);
1377
1378
m_codes.resize(0);
1379
m_codes.resize(num_syms);
1380
1381
for (uint32_t i = 1, j = total_used_syms; i <= max_code_size; i++)
1382
for (uint32_t l = num_codes[i]; l > 0; l--)
1383
m_code_sizes[pSym_freq[--j].m_sym_index] = static_cast<uint8_t>(i);
1384
1385
uint32_t next_code[cHuffmanMaxSupportedInternalCodeSize + 1];
1386
1387
next_code[1] = 0;
1388
for (uint32_t j = 0, i = 2; i <= max_code_size; i++)
1389
next_code[i] = j = ((j + num_codes[i - 1]) << 1);
1390
1391
for (uint32_t i = 0; i < num_syms; i++)
1392
{
1393
uint32_t rev_code = 0, code, code_size;
1394
if ((code_size = m_code_sizes[i]) == 0)
1395
continue;
1396
if (code_size > cHuffmanMaxSupportedInternalCodeSize)
1397
return false;
1398
code = next_code[code_size]++;
1399
for (uint32_t l = code_size; l > 0; l--, code >>= 1)
1400
rev_code = (rev_code << 1) | (code & 1);
1401
m_codes[i] = static_cast<uint16_t>(rev_code);
1402
}
1403
1404
return true;
1405
}
1406
1407
bool huffman_encoding_table::init(uint32_t num_syms, const uint32_t *pSym_freq, uint32_t max_code_size)
1408
{
1409
if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
1410
return false;
1411
1412
uint16_vec sym_freq(num_syms);
1413
1414
uint32_t max_freq = 0;
1415
for (uint32_t i = 0; i < num_syms; i++)
1416
max_freq = maximum(max_freq, pSym_freq[i]);
1417
1418
if (max_freq < UINT16_MAX)
1419
{
1420
for (uint32_t i = 0; i < num_syms; i++)
1421
sym_freq[i] = static_cast<uint16_t>(pSym_freq[i]);
1422
}
1423
else
1424
{
1425
for (uint32_t i = 0; i < num_syms; i++)
1426
{
1427
if (pSym_freq[i])
1428
{
1429
uint32_t f = static_cast<uint32_t>((static_cast<uint64_t>(pSym_freq[i]) * 65534U + (max_freq >> 1)) / max_freq);
1430
sym_freq[i] = static_cast<uint16_t>(clamp<uint32_t>(f, 1, 65534));
1431
}
1432
}
1433
}
1434
1435
return init(num_syms, &sym_freq[0], max_code_size);
1436
}
1437
1438
void bitwise_coder::end_nonzero_run(uint16_vec &syms, uint32_t &run_size, uint32_t len)
1439
{
1440
if (run_size)
1441
{
1442
if (run_size < cHuffmanSmallRepeatSizeMin)
1443
{
1444
while (run_size--)
1445
syms.push_back(static_cast<uint16_t>(len));
1446
}
1447
else if (run_size <= cHuffmanSmallRepeatSizeMax)
1448
{
1449
syms.push_back(static_cast<uint16_t>(cHuffmanSmallRepeatCode | ((run_size - cHuffmanSmallRepeatSizeMin) << 6)));
1450
}
1451
else
1452
{
1453
assert((run_size >= cHuffmanBigRepeatSizeMin) && (run_size <= cHuffmanBigRepeatSizeMax));
1454
syms.push_back(static_cast<uint16_t>(cHuffmanBigRepeatCode | ((run_size - cHuffmanBigRepeatSizeMin) << 6)));
1455
}
1456
}
1457
1458
run_size = 0;
1459
}
1460
1461
void bitwise_coder::end_zero_run(uint16_vec &syms, uint32_t &run_size)
1462
{
1463
if (run_size)
1464
{
1465
if (run_size < cHuffmanSmallZeroRunSizeMin)
1466
{
1467
while (run_size--)
1468
syms.push_back(0);
1469
}
1470
else if (run_size <= cHuffmanSmallZeroRunSizeMax)
1471
{
1472
syms.push_back(static_cast<uint16_t>(cHuffmanSmallZeroRunCode | ((run_size - cHuffmanSmallZeroRunSizeMin) << 6)));
1473
}
1474
else
1475
{
1476
assert((run_size >= cHuffmanBigZeroRunSizeMin) && (run_size <= cHuffmanBigZeroRunSizeMax));
1477
syms.push_back(static_cast<uint16_t>(cHuffmanBigZeroRunCode | ((run_size - cHuffmanBigZeroRunSizeMin) << 6)));
1478
}
1479
}
1480
1481
run_size = 0;
1482
}
1483
1484
uint32_t bitwise_coder::emit_huffman_table(const huffman_encoding_table &tab)
1485
{
1486
const uint64_t start_bits = m_total_bits;
1487
1488
const uint8_vec &code_sizes = tab.get_code_sizes();
1489
1490
uint32_t total_used = tab.get_total_used_codes();
1491
put_bits(total_used, cHuffmanMaxSymsLog2);
1492
1493
if (!total_used)
1494
return 0;
1495
1496
uint16_vec syms;
1497
syms.reserve(total_used + 16);
1498
1499
uint32_t prev_code_len = UINT_MAX, zero_run_size = 0, nonzero_run_size = 0;
1500
1501
for (uint32_t i = 0; i <= total_used; ++i)
1502
{
1503
const uint32_t code_len = (i == total_used) ? 0xFF : code_sizes[i];
1504
assert((code_len == 0xFF) || (code_len <= 16));
1505
1506
if (code_len)
1507
{
1508
end_zero_run(syms, zero_run_size);
1509
1510
if (code_len != prev_code_len)
1511
{
1512
end_nonzero_run(syms, nonzero_run_size, prev_code_len);
1513
if (code_len != 0xFF)
1514
syms.push_back(static_cast<uint16_t>(code_len));
1515
}
1516
else if (++nonzero_run_size == cHuffmanBigRepeatSizeMax)
1517
end_nonzero_run(syms, nonzero_run_size, prev_code_len);
1518
}
1519
else
1520
{
1521
end_nonzero_run(syms, nonzero_run_size, prev_code_len);
1522
1523
if (++zero_run_size == cHuffmanBigZeroRunSizeMax)
1524
end_zero_run(syms, zero_run_size);
1525
}
1526
1527
prev_code_len = code_len;
1528
}
1529
1530
histogram h(cHuffmanTotalCodelengthCodes);
1531
for (uint32_t i = 0; i < syms.size(); i++)
1532
h.inc(syms[i] & 63);
1533
1534
huffman_encoding_table ct;
1535
if (!ct.init(h, 7))
1536
return 0;
1537
1538
assert(cHuffmanTotalSortedCodelengthCodes == cHuffmanTotalCodelengthCodes);
1539
1540
uint32_t total_codelength_codes;
1541
for (total_codelength_codes = cHuffmanTotalSortedCodelengthCodes; total_codelength_codes > 0; total_codelength_codes--)
1542
if (ct.get_code_sizes()[g_huffman_sorted_codelength_codes[total_codelength_codes - 1]])
1543
break;
1544
1545
assert(total_codelength_codes);
1546
1547
put_bits(total_codelength_codes, 5);
1548
for (uint32_t i = 0; i < total_codelength_codes; i++)
1549
put_bits(ct.get_code_sizes()[g_huffman_sorted_codelength_codes[i]], 3);
1550
1551
for (uint32_t i = 0; i < syms.size(); ++i)
1552
{
1553
const uint32_t l = syms[i] & 63, e = syms[i] >> 6;
1554
1555
put_code(l, ct);
1556
1557
if (l == cHuffmanSmallZeroRunCode)
1558
put_bits(e, cHuffmanSmallZeroRunExtraBits);
1559
else if (l == cHuffmanBigZeroRunCode)
1560
put_bits(e, cHuffmanBigZeroRunExtraBits);
1561
else if (l == cHuffmanSmallRepeatCode)
1562
put_bits(e, cHuffmanSmallRepeatExtraBits);
1563
else if (l == cHuffmanBigRepeatCode)
1564
put_bits(e, cHuffmanBigRepeatExtraBits);
1565
}
1566
1567
return (uint32_t)(m_total_bits - start_bits);
1568
}
1569
1570
bool huffman_test(int rand_seed)
1571
{
1572
histogram h(19);
1573
1574
// Feed in a fibonacci sequence to force large codesizes
1575
h[0] += 1; h[1] += 1; h[2] += 2; h[3] += 3;
1576
h[4] += 5; h[5] += 8; h[6] += 13; h[7] += 21;
1577
h[8] += 34; h[9] += 55; h[10] += 89; h[11] += 144;
1578
h[12] += 233; h[13] += 377; h[14] += 610; h[15] += 987;
1579
h[16] += 1597; h[17] += 2584; h[18] += 4181;
1580
1581
huffman_encoding_table etab;
1582
etab.init(h, 16);
1583
1584
{
1585
bitwise_coder c;
1586
c.init(1024);
1587
1588
c.emit_huffman_table(etab);
1589
for (int i = 0; i < 19; i++)
1590
c.put_code(i, etab);
1591
1592
c.flush();
1593
1594
basist::bitwise_decoder d;
1595
d.init(&c.get_bytes()[0], static_cast<uint32_t>(c.get_bytes().size()));
1596
1597
basist::huffman_decoding_table dtab;
1598
bool success = d.read_huffman_table(dtab);
1599
if (!success)
1600
{
1601
assert(0);
1602
printf("Failure 5\n");
1603
return false;
1604
}
1605
1606
for (uint32_t i = 0; i < 19; i++)
1607
{
1608
uint32_t s = d.decode_huffman(dtab);
1609
if (s != i)
1610
{
1611
assert(0);
1612
printf("Failure 5\n");
1613
return false;
1614
}
1615
}
1616
}
1617
1618
basisu::rand r;
1619
r.seed(rand_seed);
1620
1621
for (int iter = 0; iter < 500000; iter++)
1622
{
1623
printf("%u\n", iter);
1624
1625
uint32_t max_sym = r.irand(0, 8193);
1626
uint32_t num_codes = r.irand(1, 10000);
1627
uint_vec syms(num_codes);
1628
1629
for (uint32_t i = 0; i < num_codes; i++)
1630
{
1631
if (r.bit())
1632
syms[i] = r.irand(0, max_sym);
1633
else
1634
{
1635
int s = (int)(r.gaussian((float)max_sym / 2, (float)maximum<int>(1, max_sym / 2)) + .5f);
1636
s = basisu::clamp<int>(s, 0, max_sym);
1637
1638
syms[i] = s;
1639
}
1640
1641
}
1642
1643
histogram h1(max_sym + 1);
1644
for (uint32_t i = 0; i < num_codes; i++)
1645
h1[syms[i]]++;
1646
1647
huffman_encoding_table etab2;
1648
if (!etab2.init(h1, 16))
1649
{
1650
assert(0);
1651
printf("Failed 0\n");
1652
return false;
1653
}
1654
1655
bitwise_coder c;
1656
c.init(1024);
1657
1658
c.emit_huffman_table(etab2);
1659
1660
for (uint32_t i = 0; i < num_codes; i++)
1661
c.put_code(syms[i], etab2);
1662
1663
c.flush();
1664
1665
basist::bitwise_decoder d;
1666
d.init(&c.get_bytes()[0], (uint32_t)c.get_bytes().size());
1667
1668
basist::huffman_decoding_table dtab;
1669
bool success = d.read_huffman_table(dtab);
1670
if (!success)
1671
{
1672
assert(0);
1673
printf("Failed 2\n");
1674
return false;
1675
}
1676
1677
for (uint32_t i = 0; i < num_codes; i++)
1678
{
1679
uint32_t s = d.decode_huffman(dtab);
1680
if (s != syms[i])
1681
{
1682
assert(0);
1683
printf("Failed 4\n");
1684
return false;
1685
}
1686
}
1687
1688
}
1689
return true;
1690
}
1691
1692
void palette_index_reorderer::init(uint32_t num_indices, const uint32_t *pIndices, uint32_t num_syms, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
1693
{
1694
assert((num_syms > 0) && (num_indices > 0));
1695
assert((dist_func_weight >= 0.0f) && (dist_func_weight <= 1.0f));
1696
1697
clear();
1698
1699
m_remap_table.resize(num_syms);
1700
m_entries_picked.reserve(num_syms);
1701
m_total_count_to_picked.resize(num_syms);
1702
1703
if (num_indices <= 1)
1704
return;
1705
1706
prepare_hist(num_syms, num_indices, pIndices);
1707
find_initial(num_syms);
1708
1709
while (m_entries_to_do.size())
1710
{
1711
// Find the best entry to move into the picked list.
1712
uint32_t best_entry;
1713
double best_count;
1714
find_next_entry(best_entry, best_count, pDist_func, pCtx, dist_func_weight);
1715
1716
// We now have chosen an entry to place in the picked list, now determine which side it goes on.
1717
const uint32_t entry_to_move = m_entries_to_do[best_entry];
1718
1719
float side = pick_side(num_syms, entry_to_move, pDist_func, pCtx, dist_func_weight);
1720
1721
// Put entry_to_move either on the "left" or "right" side of the picked entries
1722
if (side <= 0)
1723
m_entries_picked.push_back(entry_to_move);
1724
else
1725
m_entries_picked.insert(m_entries_picked.begin(), entry_to_move);
1726
1727
// Erase best_entry from the todo list
1728
m_entries_to_do.erase(m_entries_to_do.begin() + best_entry);
1729
1730
// We've just moved best_entry to the picked list, so now we need to update m_total_count_to_picked[] to factor the additional count to best_entry
1731
for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
1732
m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], entry_to_move, num_syms);
1733
}
1734
1735
for (uint32_t i = 0; i < num_syms; i++)
1736
m_remap_table[m_entries_picked[i]] = i;
1737
}
1738
1739
void palette_index_reorderer::prepare_hist(uint32_t num_syms, uint32_t num_indices, const uint32_t *pIndices)
1740
{
1741
m_hist.resize(0);
1742
m_hist.resize(num_syms * num_syms);
1743
1744
for (uint32_t i = 0; i < num_indices; i++)
1745
{
1746
const uint32_t idx = pIndices[i];
1747
inc_hist(idx, (i < (num_indices - 1)) ? pIndices[i + 1] : -1, num_syms);
1748
inc_hist(idx, (i > 0) ? pIndices[i - 1] : -1, num_syms);
1749
}
1750
}
1751
1752
void palette_index_reorderer::find_initial(uint32_t num_syms)
1753
{
1754
uint32_t max_count = 0, max_index = 0;
1755
for (uint32_t i = 0; i < num_syms * num_syms; i++)
1756
if (m_hist[i] > max_count)
1757
max_count = m_hist[i], max_index = i;
1758
1759
uint32_t a = max_index / num_syms, b = max_index % num_syms;
1760
1761
const size_t ofs = m_entries_picked.size();
1762
1763
m_entries_picked.push_back(a);
1764
m_entries_picked.push_back(b);
1765
1766
for (uint32_t i = 0; i < num_syms; i++)
1767
if ((i != m_entries_picked[ofs + 1]) && (i != m_entries_picked[ofs]))
1768
m_entries_to_do.push_back(i);
1769
1770
for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
1771
for (uint32_t j = 0; j < m_entries_picked.size(); j++)
1772
m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], m_entries_picked[j], num_syms);
1773
}
1774
1775
void palette_index_reorderer::find_next_entry(uint32_t &best_entry, double &best_count, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
1776
{
1777
best_entry = 0;
1778
best_count = 0;
1779
1780
for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
1781
{
1782
const uint32_t u = m_entries_to_do[i];
1783
double total_count = m_total_count_to_picked[u];
1784
1785
if (pDist_func)
1786
{
1787
float w = maximum<float>((*pDist_func)(u, m_entries_picked.front(), pCtx), (*pDist_func)(u, m_entries_picked.back(), pCtx));
1788
assert((w >= 0.0f) && (w <= 1.0f));
1789
total_count = (total_count + 1.0f) * lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, w);
1790
}
1791
1792
if (total_count <= best_count)
1793
continue;
1794
1795
best_entry = i;
1796
best_count = total_count;
1797
}
1798
}
1799
1800
float palette_index_reorderer::pick_side(uint32_t num_syms, uint32_t entry_to_move, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
1801
{
1802
float which_side = 0;
1803
1804
int l_count = 0, r_count = 0;
1805
for (uint32_t j = 0; j < m_entries_picked.size(); j++)
1806
{
1807
const int count = get_hist(entry_to_move, m_entries_picked[j], num_syms), r = ((int)m_entries_picked.size() + 1 - 2 * (j + 1));
1808
which_side += static_cast<float>(r * count);
1809
if (r >= 0)
1810
l_count += r * count;
1811
else
1812
r_count += -r * count;
1813
}
1814
1815
if (pDist_func)
1816
{
1817
float w_left = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.front(), pCtx));
1818
float w_right = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.back(), pCtx));
1819
which_side = w_left * l_count - w_right * r_count;
1820
}
1821
return which_side;
1822
}
1823
1824
void image_metrics::calc(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool log)
1825
{
1826
assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
1827
1828
const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
1829
const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
1830
1831
double max_e = -1e+30f;
1832
double sum = 0.0f, sum_sqr = 0.0f;
1833
1834
m_has_neg = false;
1835
m_any_abnormal = false;
1836
m_hf_mag_overflow = false;
1837
1838
for (uint32_t y = 0; y < height; y++)
1839
{
1840
for (uint32_t x = 0; x < width; x++)
1841
{
1842
const vec4F& ca = a(x, y), &cb = b(x, y);
1843
1844
if (total_chans)
1845
{
1846
for (uint32_t c = 0; c < total_chans; c++)
1847
{
1848
float fa = ca[first_chan + c], fb = cb[first_chan + c];
1849
1850
if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
1851
m_hf_mag_overflow = true;
1852
1853
if ((fa < 0.0f) || (fb < 0.0f))
1854
m_has_neg = true;
1855
1856
if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
1857
m_any_abnormal = true;
1858
1859
const double delta = fabs(fa - fb);
1860
max_e = basisu::maximum<double>(max_e, delta);
1861
1862
if (log)
1863
{
1864
double log2_delta = log2f(basisu::maximum(0.0f, fa) + 1.0f) - log2f(basisu::maximum(0.0f, fb) + 1.0f);
1865
1866
sum += fabs(log2_delta);
1867
sum_sqr += log2_delta * log2_delta;
1868
}
1869
else
1870
{
1871
sum += fabs(delta);
1872
sum_sqr += delta * delta;
1873
}
1874
}
1875
}
1876
else
1877
{
1878
for (uint32_t c = 0; c < 3; c++)
1879
{
1880
float fa = ca[c], fb = cb[c];
1881
1882
if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
1883
m_hf_mag_overflow = true;
1884
1885
if ((fa < 0.0f) || (fb < 0.0f))
1886
m_has_neg = true;
1887
1888
if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
1889
m_any_abnormal = true;
1890
}
1891
1892
double ca_l = get_luminance(ca), cb_l = get_luminance(cb);
1893
1894
double delta = fabs(ca_l - cb_l);
1895
max_e = basisu::maximum(max_e, delta);
1896
1897
if (log)
1898
{
1899
double log2_delta = log2(basisu::maximum<double>(0.0f, ca_l) + 1.0f) - log2(basisu::maximum<double>(0.0f, cb_l) + 1.0f);
1900
1901
sum += fabs(log2_delta);
1902
sum_sqr += log2_delta * log2_delta;
1903
}
1904
else
1905
{
1906
sum += delta;
1907
sum_sqr += delta * delta;
1908
}
1909
}
1910
}
1911
}
1912
1913
m_max = (double)(max_e);
1914
1915
double total_values = (double)width * (double)height;
1916
if (avg_comp_error)
1917
total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
1918
1919
m_mean = (float)(sum / total_values);
1920
m_mean_squared = (float)(sum_sqr / total_values);
1921
m_rms = (float)sqrt(sum_sqr / total_values);
1922
1923
const double max_val = 1.0f;
1924
m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
1925
}
1926
1927
void image_metrics::calc_half(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
1928
{
1929
assert(total_chans);
1930
assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
1931
1932
const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
1933
const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
1934
1935
m_has_neg = false;
1936
m_hf_mag_overflow = false;
1937
m_any_abnormal = false;
1938
1939
uint_vec hist(65536);
1940
1941
for (uint32_t y = 0; y < height; y++)
1942
{
1943
for (uint32_t x = 0; x < width; x++)
1944
{
1945
const vec4F& ca = a(x, y), &cb = b(x, y);
1946
1947
for (uint32_t i = 0; i < 4; i++)
1948
{
1949
if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
1950
m_has_neg = true;
1951
1952
if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
1953
m_hf_mag_overflow = true;
1954
1955
if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
1956
m_any_abnormal = true;
1957
}
1958
1959
int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
1960
int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
1961
1962
for (uint32_t c = 0; c < total_chans; c++)
1963
hist[iabs(cah[first_chan + c] - cbh[first_chan + c]) & 65535]++;
1964
1965
} // x
1966
} // y
1967
1968
m_max = 0;
1969
double sum = 0.0f, sum2 = 0.0f;
1970
for (uint32_t i = 0; i < 65536; i++)
1971
{
1972
if (hist[i])
1973
{
1974
m_max = basisu::maximum<double>(m_max, (double)i);
1975
double v = (double)i * (double)hist[i];
1976
sum += v;
1977
sum2 += (double)i * v;
1978
}
1979
}
1980
1981
double total_values = (double)width * (double)height;
1982
if (avg_comp_error)
1983
total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
1984
1985
const float max_val = 65535.0f;
1986
m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
1987
m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
1988
m_rms = (float)sqrt(m_mean_squared);
1989
m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
1990
}
1991
1992
// Alt. variant, same as calc_half(), for validation.
1993
void image_metrics::calc_half2(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
1994
{
1995
assert(total_chans);
1996
assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
1997
1998
const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
1999
const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
2000
2001
m_has_neg = false;
2002
m_hf_mag_overflow = false;
2003
m_any_abnormal = false;
2004
2005
double sum = 0.0f, sum2 = 0.0f;
2006
m_max = 0;
2007
2008
for (uint32_t y = 0; y < height; y++)
2009
{
2010
for (uint32_t x = 0; x < width; x++)
2011
{
2012
const vec4F& ca = a(x, y), & cb = b(x, y);
2013
2014
for (uint32_t i = 0; i < 4; i++)
2015
{
2016
if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
2017
m_has_neg = true;
2018
2019
if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
2020
m_hf_mag_overflow = true;
2021
2022
if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
2023
m_any_abnormal = true;
2024
}
2025
2026
int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
2027
int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
2028
2029
for (uint32_t c = 0; c < total_chans; c++)
2030
{
2031
int diff = iabs(cah[first_chan + c] - cbh[first_chan + c]);
2032
if (diff)
2033
m_max = std::max<double>(m_max, (double)diff);
2034
2035
sum += diff;
2036
sum2 += squarei(cah[first_chan + c] - cbh[first_chan + c]);
2037
}
2038
2039
} // x
2040
} // y
2041
2042
double total_values = (double)width * (double)height;
2043
if (avg_comp_error)
2044
total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
2045
2046
const float max_val = 65535.0f;
2047
m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
2048
m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
2049
m_rms = (float)sqrt(m_mean_squared);
2050
m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
2051
}
2052
2053
void image_metrics::calc(const image &a, const image &b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool use_601_luma)
2054
{
2055
assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
2056
2057
const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
2058
const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
2059
2060
double hist[256];
2061
clear_obj(hist);
2062
2063
m_has_neg = false;
2064
m_any_abnormal = false;
2065
m_hf_mag_overflow = false;
2066
2067
for (uint32_t y = 0; y < height; y++)
2068
{
2069
for (uint32_t x = 0; x < width; x++)
2070
{
2071
const color_rgba &ca = a(x, y), &cb = b(x, y);
2072
2073
if (total_chans)
2074
{
2075
for (uint32_t c = 0; c < total_chans; c++)
2076
hist[iabs(ca[first_chan + c] - cb[first_chan + c])]++;
2077
}
2078
else
2079
{
2080
if (use_601_luma)
2081
hist[iabs(ca.get_601_luma() - cb.get_601_luma())]++;
2082
else
2083
hist[iabs(ca.get_709_luma() - cb.get_709_luma())]++;
2084
}
2085
}
2086
}
2087
2088
m_max = 0;
2089
double sum = 0.0f, sum2 = 0.0f;
2090
for (uint32_t i = 0; i < 256; i++)
2091
{
2092
if (hist[i])
2093
{
2094
m_max = basisu::maximum<double>(m_max, (double)i);
2095
double v = i * hist[i];
2096
sum += v;
2097
sum2 += i * v;
2098
}
2099
}
2100
2101
double total_values = (double)width * (double)height;
2102
if (avg_comp_error)
2103
total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
2104
2105
m_mean = (float)clamp<double>(sum / total_values, 0.0f, 255.0);
2106
m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, 255.0f * 255.0f);
2107
m_rms = (float)sqrt(m_mean_squared);
2108
m_psnr = m_rms ? (float)clamp<double>(log10(255.0 / m_rms) * 20.0f, 0.0f, 100.0f) : 100.0f;
2109
}
2110
2111
void print_image_metrics(const image& a, const image& b)
2112
{
2113
image_metrics im;
2114
im.calc(a, b, 0, 3);
2115
im.print("RGB ");
2116
2117
im.calc(a, b, 0, 4);
2118
im.print("RGBA ");
2119
2120
im.calc(a, b, 0, 1);
2121
im.print("R ");
2122
2123
im.calc(a, b, 1, 1);
2124
im.print("G ");
2125
2126
im.calc(a, b, 2, 1);
2127
im.print("B ");
2128
2129
im.calc(a, b, 3, 1);
2130
im.print("A ");
2131
2132
im.calc(a, b, 0, 0);
2133
im.print("Y 709 ");
2134
2135
im.calc(a, b, 0, 0, true, true);
2136
im.print("Y 601 ");
2137
}
2138
2139
void fill_buffer_with_random_bytes(void *pBuf, size_t size, uint32_t seed)
2140
{
2141
rand r(seed);
2142
2143
uint8_t *pDst = static_cast<uint8_t *>(pBuf);
2144
2145
while (size >= sizeof(uint32_t))
2146
{
2147
*(uint32_t *)pDst = r.urand32();
2148
pDst += sizeof(uint32_t);
2149
size -= sizeof(uint32_t);
2150
}
2151
2152
while (size)
2153
{
2154
*pDst++ = r.byte();
2155
size--;
2156
}
2157
}
2158
2159
uint32_t hash_hsieh(const uint8_t *pBuf, size_t len)
2160
{
2161
if (!pBuf || !len)
2162
return 0;
2163
2164
uint32_t h = static_cast<uint32_t>(len);
2165
2166
const uint32_t bytes_left = len & 3;
2167
len >>= 2;
2168
2169
while (len--)
2170
{
2171
const uint16_t *pWords = reinterpret_cast<const uint16_t *>(pBuf);
2172
2173
h += pWords[0];
2174
2175
const uint32_t t = (pWords[1] << 11) ^ h;
2176
h = (h << 16) ^ t;
2177
2178
pBuf += sizeof(uint32_t);
2179
2180
h += h >> 11;
2181
}
2182
2183
switch (bytes_left)
2184
{
2185
case 1:
2186
h += *reinterpret_cast<const signed char*>(pBuf);
2187
h ^= h << 10;
2188
h += h >> 1;
2189
break;
2190
case 2:
2191
h += *reinterpret_cast<const uint16_t *>(pBuf);
2192
h ^= h << 11;
2193
h += h >> 17;
2194
break;
2195
case 3:
2196
h += *reinterpret_cast<const uint16_t *>(pBuf);
2197
h ^= h << 16;
2198
h ^= (static_cast<signed char>(pBuf[sizeof(uint16_t)])) << 18;
2199
h += h >> 11;
2200
break;
2201
default:
2202
break;
2203
}
2204
2205
h ^= h << 3;
2206
h += h >> 5;
2207
h ^= h << 4;
2208
h += h >> 17;
2209
h ^= h << 25;
2210
h += h >> 6;
2211
2212
return h;
2213
}
2214
2215
job_pool::job_pool(uint32_t num_threads) :
2216
m_num_active_jobs(0)
2217
{
2218
m_kill_flag.store(false);
2219
m_num_active_workers.store(0);
2220
2221
assert(num_threads >= 1U);
2222
2223
debug_printf("job_pool::job_pool: %u total threads\n", num_threads);
2224
2225
if (num_threads > 1)
2226
{
2227
m_threads.resize(num_threads - 1);
2228
2229
for (int i = 0; i < ((int)num_threads - 1); i++)
2230
m_threads[i] = std::thread([this, i] { job_thread(i); });
2231
}
2232
}
2233
2234
job_pool::~job_pool()
2235
{
2236
debug_printf("job_pool::~job_pool\n");
2237
2238
// Notify all workers that they need to die right now.
2239
{
2240
std::lock_guard<std::mutex> lk(m_mutex);
2241
m_kill_flag.store(true);
2242
}
2243
2244
m_has_work.notify_all();
2245
2246
#ifdef __EMSCRIPTEN__
2247
for ( ; ; )
2248
{
2249
if (m_num_active_workers.load() <= 0)
2250
break;
2251
std::this_thread::sleep_for(std::chrono::milliseconds(50));
2252
}
2253
2254
// At this point all worker threads should be exiting or exited.
2255
// We could call detach(), but this seems to just call join() anyway.
2256
#endif
2257
2258
// Wait for all worker threads to exit.
2259
for (uint32_t i = 0; i < m_threads.size(); i++)
2260
m_threads[i].join();
2261
}
2262
2263
void job_pool::add_job(const std::function<void()>& job)
2264
{
2265
std::unique_lock<std::mutex> lock(m_mutex);
2266
2267
m_queue.emplace_back(job);
2268
2269
const size_t queue_size = m_queue.size();
2270
2271
lock.unlock();
2272
2273
if (queue_size > 1)
2274
m_has_work.notify_one();
2275
}
2276
2277
void job_pool::add_job(std::function<void()>&& job)
2278
{
2279
std::unique_lock<std::mutex> lock(m_mutex);
2280
2281
m_queue.emplace_back(std::move(job));
2282
2283
const size_t queue_size = m_queue.size();
2284
2285
lock.unlock();
2286
2287
if (queue_size > 1)
2288
{
2289
m_has_work.notify_one();
2290
}
2291
}
2292
2293
void job_pool::wait_for_all()
2294
{
2295
std::unique_lock<std::mutex> lock(m_mutex);
2296
2297
// Drain the job queue on the calling thread.
2298
while (!m_queue.empty())
2299
{
2300
std::function<void()> job(m_queue.back());
2301
m_queue.pop_back();
2302
2303
lock.unlock();
2304
2305
job();
2306
2307
lock.lock();
2308
}
2309
2310
// The queue is empty, now wait for all active jobs to finish up.
2311
#ifndef __EMSCRIPTEN__
2312
m_no_more_jobs.wait(lock, [this]{ return !m_num_active_jobs; } );
2313
#else
2314
// Avoid infinite blocking
2315
for (; ; )
2316
{
2317
if (m_no_more_jobs.wait_for(lock, std::chrono::milliseconds(50), [this] { return !m_num_active_jobs; }))
2318
{
2319
break;
2320
}
2321
}
2322
#endif
2323
}
2324
2325
void job_pool::job_thread(uint32_t index)
2326
{
2327
BASISU_NOTE_UNUSED(index);
2328
//debug_printf("job_pool::job_thread: starting %u\n", index);
2329
2330
m_num_active_workers.fetch_add(1);
2331
2332
while (!m_kill_flag)
2333
{
2334
std::unique_lock<std::mutex> lock(m_mutex);
2335
2336
// Wait for any jobs to be issued.
2337
#if 0
2338
m_has_work.wait(lock, [this] { return m_kill_flag || m_queue.size(); } );
2339
#else
2340
// For more safety vs. buggy RTL's. Worse case we stall for a second vs. locking up forever if something goes wrong.
2341
m_has_work.wait_for(lock, std::chrono::milliseconds(1000), [this] {
2342
return m_kill_flag || !m_queue.empty();
2343
});
2344
#endif
2345
2346
// Check to see if we're supposed to exit.
2347
if (m_kill_flag)
2348
break;
2349
2350
if (m_queue.empty())
2351
continue;
2352
2353
// Get the job and execute it.
2354
std::function<void()> job(m_queue.back());
2355
m_queue.pop_back();
2356
2357
++m_num_active_jobs;
2358
2359
lock.unlock();
2360
2361
job();
2362
2363
lock.lock();
2364
2365
--m_num_active_jobs;
2366
2367
// Now check if there are no more jobs remaining.
2368
const bool all_done = m_queue.empty() && !m_num_active_jobs;
2369
2370
lock.unlock();
2371
2372
if (all_done)
2373
m_no_more_jobs.notify_all();
2374
}
2375
2376
m_num_active_workers.fetch_add(-1);
2377
2378
//debug_printf("job_pool::job_thread: exiting\n");
2379
}
2380
2381
// .TGA image loading
2382
#pragma pack(push)
2383
#pragma pack(1)
2384
struct tga_header
2385
{
2386
uint8_t m_id_len;
2387
uint8_t m_cmap;
2388
uint8_t m_type;
2389
packed_uint<2> m_cmap_first;
2390
packed_uint<2> m_cmap_len;
2391
uint8_t m_cmap_bpp;
2392
packed_uint<2> m_x_org;
2393
packed_uint<2> m_y_org;
2394
packed_uint<2> m_width;
2395
packed_uint<2> m_height;
2396
uint8_t m_depth;
2397
uint8_t m_desc;
2398
};
2399
#pragma pack(pop)
2400
2401
const uint32_t MAX_TGA_IMAGE_SIZE = 16384;
2402
2403
enum tga_image_type
2404
{
2405
cITPalettized = 1,
2406
cITRGB = 2,
2407
cITGrayscale = 3
2408
};
2409
2410
uint8_t *read_tga(const uint8_t *pBuf, uint32_t buf_size, int &width, int &height, int &n_chans)
2411
{
2412
width = 0;
2413
height = 0;
2414
n_chans = 0;
2415
2416
if (buf_size <= sizeof(tga_header))
2417
return nullptr;
2418
2419
const tga_header &hdr = *reinterpret_cast<const tga_header *>(pBuf);
2420
2421
if ((!hdr.m_width) || (!hdr.m_height) || (hdr.m_width > MAX_TGA_IMAGE_SIZE) || (hdr.m_height > MAX_TGA_IMAGE_SIZE))
2422
return nullptr;
2423
2424
if (hdr.m_desc >> 6)
2425
return nullptr;
2426
2427
// Simple validation
2428
if ((hdr.m_cmap != 0) && (hdr.m_cmap != 1))
2429
return nullptr;
2430
2431
if (hdr.m_cmap)
2432
{
2433
if ((hdr.m_cmap_bpp == 0) || (hdr.m_cmap_bpp > 32))
2434
return nullptr;
2435
2436
// Nobody implements CMapFirst correctly, so we're not supporting it. Never seen it used, either.
2437
if (hdr.m_cmap_first != 0)
2438
return nullptr;
2439
}
2440
2441
const bool x_flipped = (hdr.m_desc & 0x10) != 0;
2442
const bool y_flipped = (hdr.m_desc & 0x20) == 0;
2443
2444
bool rle_flag = false;
2445
int file_image_type = hdr.m_type;
2446
if (file_image_type > 8)
2447
{
2448
file_image_type -= 8;
2449
rle_flag = true;
2450
}
2451
2452
const tga_image_type image_type = static_cast<tga_image_type>(file_image_type);
2453
2454
switch (file_image_type)
2455
{
2456
case cITRGB:
2457
if (hdr.m_depth == 8)
2458
return nullptr;
2459
break;
2460
case cITPalettized:
2461
if ((hdr.m_depth != 8) || (hdr.m_cmap != 1) || (hdr.m_cmap_len == 0))
2462
return nullptr;
2463
break;
2464
case cITGrayscale:
2465
if ((hdr.m_cmap != 0) || (hdr.m_cmap_len != 0))
2466
return nullptr;
2467
if ((hdr.m_depth != 8) && (hdr.m_depth != 16))
2468
return nullptr;
2469
break;
2470
default:
2471
return nullptr;
2472
}
2473
2474
uint32_t tga_bytes_per_pixel = 0;
2475
2476
switch (hdr.m_depth)
2477
{
2478
case 32:
2479
tga_bytes_per_pixel = 4;
2480
n_chans = 4;
2481
break;
2482
case 24:
2483
tga_bytes_per_pixel = 3;
2484
n_chans = 3;
2485
break;
2486
case 16:
2487
case 15:
2488
tga_bytes_per_pixel = 2;
2489
// For compatibility with stb_image_write.h
2490
n_chans = ((file_image_type == cITGrayscale) && (hdr.m_depth == 16)) ? 4 : 3;
2491
break;
2492
case 8:
2493
tga_bytes_per_pixel = 1;
2494
// For palettized RGBA support, which both FreeImage and stb_image support.
2495
n_chans = ((file_image_type == cITPalettized) && (hdr.m_cmap_bpp == 32)) ? 4 : 3;
2496
break;
2497
default:
2498
return nullptr;
2499
}
2500
2501
//const uint32_t bytes_per_line = hdr.m_width * tga_bytes_per_pixel;
2502
2503
const uint8_t *pSrc = pBuf + sizeof(tga_header);
2504
uint32_t bytes_remaining = buf_size - sizeof(tga_header);
2505
2506
if (hdr.m_id_len)
2507
{
2508
if (bytes_remaining < hdr.m_id_len)
2509
return nullptr;
2510
pSrc += hdr.m_id_len;
2511
bytes_remaining += hdr.m_id_len;
2512
}
2513
2514
color_rgba pal[256];
2515
for (uint32_t i = 0; i < 256; i++)
2516
pal[i].set(0, 0, 0, 255);
2517
2518
if ((hdr.m_cmap) && (hdr.m_cmap_len))
2519
{
2520
if (image_type == cITPalettized)
2521
{
2522
// Note I cannot find any files using 32bpp palettes in the wild (never seen any in ~30 years).
2523
if ( ((hdr.m_cmap_bpp != 32) && (hdr.m_cmap_bpp != 24) && (hdr.m_cmap_bpp != 15) && (hdr.m_cmap_bpp != 16)) || (hdr.m_cmap_len > 256) )
2524
return nullptr;
2525
2526
if (hdr.m_cmap_bpp == 32)
2527
{
2528
const uint32_t pal_size = hdr.m_cmap_len * 4;
2529
if (bytes_remaining < pal_size)
2530
return nullptr;
2531
2532
for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
2533
{
2534
pal[i].r = pSrc[i * 4 + 2];
2535
pal[i].g = pSrc[i * 4 + 1];
2536
pal[i].b = pSrc[i * 4 + 0];
2537
pal[i].a = pSrc[i * 4 + 3];
2538
}
2539
2540
bytes_remaining -= pal_size;
2541
pSrc += pal_size;
2542
}
2543
else if (hdr.m_cmap_bpp == 24)
2544
{
2545
const uint32_t pal_size = hdr.m_cmap_len * 3;
2546
if (bytes_remaining < pal_size)
2547
return nullptr;
2548
2549
for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
2550
{
2551
pal[i].r = pSrc[i * 3 + 2];
2552
pal[i].g = pSrc[i * 3 + 1];
2553
pal[i].b = pSrc[i * 3 + 0];
2554
pal[i].a = 255;
2555
}
2556
2557
bytes_remaining -= pal_size;
2558
pSrc += pal_size;
2559
}
2560
else
2561
{
2562
const uint32_t pal_size = hdr.m_cmap_len * 2;
2563
if (bytes_remaining < pal_size)
2564
return nullptr;
2565
2566
for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
2567
{
2568
const uint32_t v = pSrc[i * 2 + 0] | (pSrc[i * 2 + 1] << 8);
2569
2570
pal[i].r = (((v >> 10) & 31) * 255 + 15) / 31;
2571
pal[i].g = (((v >> 5) & 31) * 255 + 15) / 31;
2572
pal[i].b = ((v & 31) * 255 + 15) / 31;
2573
pal[i].a = 255;
2574
}
2575
2576
bytes_remaining -= pal_size;
2577
pSrc += pal_size;
2578
}
2579
}
2580
else
2581
{
2582
const uint32_t bytes_to_skip = (hdr.m_cmap_bpp >> 3) * hdr.m_cmap_len;
2583
if (bytes_remaining < bytes_to_skip)
2584
return nullptr;
2585
pSrc += bytes_to_skip;
2586
bytes_remaining += bytes_to_skip;
2587
}
2588
}
2589
2590
width = hdr.m_width;
2591
height = hdr.m_height;
2592
2593
const uint32_t source_pitch = width * tga_bytes_per_pixel;
2594
const uint32_t dest_pitch = width * n_chans;
2595
2596
uint8_t *pImage = (uint8_t *)malloc(dest_pitch * height);
2597
if (!pImage)
2598
return nullptr;
2599
2600
std::vector<uint8_t> input_line_buf;
2601
if (rle_flag)
2602
input_line_buf.resize(source_pitch);
2603
2604
int run_type = 0, run_remaining = 0;
2605
uint8_t run_pixel[4];
2606
memset(run_pixel, 0, sizeof(run_pixel));
2607
2608
for (int y = 0; y < height; y++)
2609
{
2610
const uint8_t *pLine_data;
2611
2612
if (rle_flag)
2613
{
2614
int pixels_remaining = width;
2615
uint8_t *pDst = &input_line_buf[0];
2616
2617
do
2618
{
2619
if (!run_remaining)
2620
{
2621
if (bytes_remaining < 1)
2622
{
2623
free(pImage);
2624
return nullptr;
2625
}
2626
2627
int v = *pSrc++;
2628
bytes_remaining--;
2629
2630
run_type = v & 0x80;
2631
run_remaining = (v & 0x7F) + 1;
2632
2633
if (run_type)
2634
{
2635
if (bytes_remaining < tga_bytes_per_pixel)
2636
{
2637
free(pImage);
2638
return nullptr;
2639
}
2640
2641
memcpy(run_pixel, pSrc, tga_bytes_per_pixel);
2642
pSrc += tga_bytes_per_pixel;
2643
bytes_remaining -= tga_bytes_per_pixel;
2644
}
2645
}
2646
2647
const uint32_t n = basisu::minimum<uint32_t>(pixels_remaining, run_remaining);
2648
pixels_remaining -= n;
2649
run_remaining -= n;
2650
2651
if (run_type)
2652
{
2653
for (uint32_t i = 0; i < n; i++)
2654
for (uint32_t j = 0; j < tga_bytes_per_pixel; j++)
2655
*pDst++ = run_pixel[j];
2656
}
2657
else
2658
{
2659
const uint32_t bytes_wanted = n * tga_bytes_per_pixel;
2660
2661
if (bytes_remaining < bytes_wanted)
2662
{
2663
free(pImage);
2664
return nullptr;
2665
}
2666
2667
memcpy(pDst, pSrc, bytes_wanted);
2668
pDst += bytes_wanted;
2669
2670
pSrc += bytes_wanted;
2671
bytes_remaining -= bytes_wanted;
2672
}
2673
2674
} while (pixels_remaining);
2675
2676
assert((pDst - &input_line_buf[0]) == (int)(width * tga_bytes_per_pixel));
2677
2678
pLine_data = &input_line_buf[0];
2679
}
2680
else
2681
{
2682
if (bytes_remaining < source_pitch)
2683
{
2684
free(pImage);
2685
return nullptr;
2686
}
2687
2688
pLine_data = pSrc;
2689
bytes_remaining -= source_pitch;
2690
pSrc += source_pitch;
2691
}
2692
2693
// Convert to 24bpp RGB or 32bpp RGBA.
2694
uint8_t *pDst = pImage + (y_flipped ? (height - 1 - y) : y) * dest_pitch + (x_flipped ? (width - 1) * n_chans : 0);
2695
const int dst_stride = x_flipped ? -((int)n_chans) : n_chans;
2696
2697
switch (hdr.m_depth)
2698
{
2699
case 32:
2700
assert(tga_bytes_per_pixel == 4 && n_chans == 4);
2701
for (int i = 0; i < width; i++, pLine_data += 4, pDst += dst_stride)
2702
{
2703
pDst[0] = pLine_data[2];
2704
pDst[1] = pLine_data[1];
2705
pDst[2] = pLine_data[0];
2706
pDst[3] = pLine_data[3];
2707
}
2708
break;
2709
case 24:
2710
assert(tga_bytes_per_pixel == 3 && n_chans == 3);
2711
for (int i = 0; i < width; i++, pLine_data += 3, pDst += dst_stride)
2712
{
2713
pDst[0] = pLine_data[2];
2714
pDst[1] = pLine_data[1];
2715
pDst[2] = pLine_data[0];
2716
}
2717
break;
2718
case 16:
2719
case 15:
2720
if (image_type == cITRGB)
2721
{
2722
assert(tga_bytes_per_pixel == 2 && n_chans == 3);
2723
for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
2724
{
2725
const uint32_t v = pLine_data[0] | (pLine_data[1] << 8);
2726
pDst[0] = (((v >> 10) & 31) * 255 + 15) / 31;
2727
pDst[1] = (((v >> 5) & 31) * 255 + 15) / 31;
2728
pDst[2] = ((v & 31) * 255 + 15) / 31;
2729
}
2730
}
2731
else
2732
{
2733
assert(image_type == cITGrayscale && tga_bytes_per_pixel == 2 && n_chans == 4);
2734
for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
2735
{
2736
pDst[0] = pLine_data[0];
2737
pDst[1] = pLine_data[0];
2738
pDst[2] = pLine_data[0];
2739
pDst[3] = pLine_data[1];
2740
}
2741
}
2742
break;
2743
case 8:
2744
assert(tga_bytes_per_pixel == 1);
2745
if (image_type == cITPalettized)
2746
{
2747
if (hdr.m_cmap_bpp == 32)
2748
{
2749
assert(n_chans == 4);
2750
for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
2751
{
2752
const uint32_t c = *pLine_data;
2753
pDst[0] = pal[c].r;
2754
pDst[1] = pal[c].g;
2755
pDst[2] = pal[c].b;
2756
pDst[3] = pal[c].a;
2757
}
2758
}
2759
else
2760
{
2761
assert(n_chans == 3);
2762
for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
2763
{
2764
const uint32_t c = *pLine_data;
2765
pDst[0] = pal[c].r;
2766
pDst[1] = pal[c].g;
2767
pDst[2] = pal[c].b;
2768
}
2769
}
2770
}
2771
else
2772
{
2773
assert(n_chans == 3);
2774
for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
2775
{
2776
const uint8_t c = *pLine_data;
2777
pDst[0] = c;
2778
pDst[1] = c;
2779
pDst[2] = c;
2780
}
2781
}
2782
break;
2783
default:
2784
assert(0);
2785
break;
2786
}
2787
} // y
2788
2789
return pImage;
2790
}
2791
2792
uint8_t *read_tga(const char *pFilename, int &width, int &height, int &n_chans)
2793
{
2794
width = height = n_chans = 0;
2795
2796
uint8_vec filedata;
2797
if (!read_file_to_vec(pFilename, filedata))
2798
return nullptr;
2799
2800
if (!filedata.size() || (filedata.size() > UINT32_MAX))
2801
return nullptr;
2802
2803
return read_tga(&filedata[0], (uint32_t)filedata.size(), width, height, n_chans);
2804
}
2805
2806
static inline void hdr_convert(const color_rgba& rgbe, vec4F& c)
2807
{
2808
if (rgbe[3] != 0)
2809
{
2810
float scale = ldexp(1.0f, rgbe[3] - 128 - 8);
2811
c.set((float)rgbe[0] * scale, (float)rgbe[1] * scale, (float)rgbe[2] * scale, 1.0f);
2812
}
2813
else
2814
{
2815
c.set(0.0f, 0.0f, 0.0f, 1.0f);
2816
}
2817
}
2818
2819
bool string_begins_with(const std::string& str, const char* pPhrase)
2820
{
2821
const size_t str_len = str.size();
2822
2823
const size_t phrase_len = strlen(pPhrase);
2824
assert(phrase_len);
2825
2826
if (str_len >= phrase_len)
2827
{
2828
#ifdef _MSC_VER
2829
if (_strnicmp(pPhrase, str.c_str(), phrase_len) == 0)
2830
#else
2831
if (strncasecmp(pPhrase, str.c_str(), phrase_len) == 0)
2832
#endif
2833
return true;
2834
}
2835
2836
return false;
2837
}
2838
2839
// Radiance RGBE (.HDR) image reading.
2840
// This code tries to preserve the original logic in Radiance's ray/src/common/color.c code:
2841
// https://www.radiance-online.org/cgi-bin/viewcvs.cgi/ray/src/common/color.c?revision=2.26&view=markup&sortby=log
2842
// Also see: https://flipcode.com/archives/HDR_Image_Reader.shtml.
2843
// https://github.com/LuminanceHDR/LuminanceHDR/blob/master/src/Libpfs/io/rgbereader.cpp.
2844
// https://radsite.lbl.gov/radiance/refer/filefmts.pdf
2845
// Buggy readers:
2846
// stb_image.h: appears to be a clone of rgbe.c, but with goto's (doesn't support old format files, doesn't support mixture of RLE/non-RLE scanlines)
2847
// http://www.graphics.cornell.edu/~bjw/rgbe.html - rgbe.c/h
2848
// http://www.graphics.cornell.edu/online/formats/rgbe/ - rgbe.c/.h - buggy
2849
bool read_rgbe(const uint8_vec &filedata, imagef& img, rgbe_header_info& hdr_info)
2850
{
2851
hdr_info.clear();
2852
2853
const uint32_t MAX_SUPPORTED_DIM = 65536;
2854
2855
if (filedata.size() < 4)
2856
return false;
2857
2858
// stb_image.h checks for the string "#?RADIANCE" or "#?RGBE" in the header.
2859
// The original Radiance header code doesn't care about the specific string.
2860
// opencv's reader only checks for "#?", so that's what we're going to do.
2861
if ((filedata[0] != '#') || (filedata[1] != '?'))
2862
return false;
2863
2864
//uint32_t width = 0, height = 0;
2865
bool is_rgbe = false;
2866
size_t cur_ofs = 0;
2867
2868
// Parse the lines until we encounter a blank line.
2869
std::string cur_line;
2870
for (; ; )
2871
{
2872
if (cur_ofs >= filedata.size())
2873
return false;
2874
2875
const uint32_t HEADER_TOO_BIG_SIZE = 4096;
2876
if (cur_ofs >= HEADER_TOO_BIG_SIZE)
2877
{
2878
// Header seems too large - something is likely wrong. Return failure.
2879
return false;
2880
}
2881
2882
uint8_t c = filedata[cur_ofs++];
2883
2884
if (c == '\n')
2885
{
2886
if (!cur_line.size())
2887
break;
2888
2889
if ((cur_line[0] == '#') && (!string_begins_with(cur_line, "#?")) && (!hdr_info.m_program.size()))
2890
{
2891
cur_line.erase(0, 1);
2892
while (cur_line.size() && (cur_line[0] == ' '))
2893
cur_line.erase(0, 1);
2894
2895
hdr_info.m_program = cur_line;
2896
}
2897
else if (string_begins_with(cur_line, "EXPOSURE=") && (cur_line.size() > 9))
2898
{
2899
hdr_info.m_exposure = atof(cur_line.c_str() + 9);
2900
hdr_info.m_has_exposure = true;
2901
}
2902
else if (string_begins_with(cur_line, "GAMMA=") && (cur_line.size() > 6))
2903
{
2904
hdr_info.m_exposure = atof(cur_line.c_str() + 6);
2905
hdr_info.m_has_gamma = true;
2906
}
2907
else if (cur_line == "FORMAT=32-bit_rle_rgbe")
2908
{
2909
is_rgbe = true;
2910
}
2911
2912
cur_line.resize(0);
2913
}
2914
else
2915
cur_line.push_back((char)c);
2916
}
2917
2918
if (!is_rgbe)
2919
return false;
2920
2921
// Assume and require the final line to have the image's dimensions. We're not supporting flipping.
2922
for (; ; )
2923
{
2924
if (cur_ofs >= filedata.size())
2925
return false;
2926
uint8_t c = filedata[cur_ofs++];
2927
if (c == '\n')
2928
break;
2929
cur_line.push_back((char)c);
2930
}
2931
2932
int comp[2] = { 1, 0 }; // y, x (major, minor)
2933
int dir[2] = { -1, 1 }; // -1, 1, (major, minor), for y -1=up
2934
uint32_t major_dim = 0, minor_dim = 0;
2935
2936
// Parse the dimension string, normally it'll be "-Y # +X #" (major, minor), rarely it differs
2937
for (uint32_t d = 0; d < 2; d++) // 0=major, 1=minor
2938
{
2939
const bool is_neg_x = (strncmp(&cur_line[0], "-X ", 3) == 0);
2940
const bool is_pos_x = (strncmp(&cur_line[0], "+X ", 3) == 0);
2941
const bool is_x = is_neg_x || is_pos_x;
2942
2943
const bool is_neg_y = (strncmp(&cur_line[0], "-Y ", 3) == 0);
2944
const bool is_pos_y = (strncmp(&cur_line[0], "+Y ", 3) == 0);
2945
const bool is_y = is_neg_y || is_pos_y;
2946
2947
if (cur_line.size() < 3)
2948
return false;
2949
2950
if (!is_x && !is_y)
2951
return false;
2952
2953
comp[d] = is_x ? 0 : 1;
2954
dir[d] = (is_neg_x || is_neg_y) ? -1 : 1;
2955
2956
uint32_t& dim = d ? minor_dim : major_dim;
2957
2958
cur_line.erase(0, 3);
2959
2960
while (cur_line.size())
2961
{
2962
char c = cur_line[0];
2963
if (c != ' ')
2964
break;
2965
cur_line.erase(0, 1);
2966
}
2967
2968
bool has_digits = false;
2969
while (cur_line.size())
2970
{
2971
char c = cur_line[0];
2972
cur_line.erase(0, 1);
2973
2974
if (c == ' ')
2975
break;
2976
2977
if ((c < '0') || (c > '9'))
2978
return false;
2979
2980
const uint32_t prev_dim = dim;
2981
dim = dim * 10 + (c - '0');
2982
if (dim < prev_dim)
2983
return false;
2984
2985
has_digits = true;
2986
}
2987
if (!has_digits)
2988
return false;
2989
2990
if ((dim < 1) || (dim > MAX_SUPPORTED_DIM))
2991
return false;
2992
}
2993
2994
// temp image: width=minor, height=major
2995
img.resize(minor_dim, major_dim);
2996
2997
std::vector<color_rgba> temp_scanline(minor_dim);
2998
2999
// Read the scanlines.
3000
for (uint32_t y = 0; y < major_dim; y++)
3001
{
3002
vec4F* pDst = &img(0, y);
3003
3004
if ((filedata.size() - cur_ofs) < 4)
3005
return false;
3006
3007
// Determine if the line uses the new or old format. See the logic in color.c.
3008
bool old_decrunch = false;
3009
if ((minor_dim < 8) || (minor_dim > 0x7FFF))
3010
{
3011
// Line is too short or long; must be old format.
3012
old_decrunch = true;
3013
}
3014
else if (filedata[cur_ofs] != 2)
3015
{
3016
// R is not 2, must be old format
3017
old_decrunch = true;
3018
}
3019
else
3020
{
3021
// c[0]/red is 2.Check GB and E for validity.
3022
color_rgba c;
3023
memcpy(&c, &filedata[cur_ofs], 4);
3024
3025
if ((c[1] != 2) || (c[2] & 0x80))
3026
{
3027
// G isn't 2, or the high bit of B is set which is impossible (image's > 0x7FFF pixels can't get here). Use old format.
3028
old_decrunch = true;
3029
}
3030
else
3031
{
3032
// Check B and E. If this isn't the minor_dim in network order, something is wrong. The pixel would also be denormalized, and invalid.
3033
uint32_t w = (c[2] << 8) | c[3];
3034
if (w != minor_dim)
3035
return false;
3036
3037
cur_ofs += 4;
3038
}
3039
}
3040
3041
if (old_decrunch)
3042
{
3043
uint32_t rshift = 0, x = 0;
3044
3045
while (x < minor_dim)
3046
{
3047
if ((filedata.size() - cur_ofs) < 4)
3048
return false;
3049
3050
color_rgba c;
3051
memcpy(&c, &filedata[cur_ofs], 4);
3052
cur_ofs += 4;
3053
3054
if ((c[0] == 1) && (c[1] == 1) && (c[2] == 1))
3055
{
3056
// We'll allow RLE matches to cross scanlines, but not on the very first pixel.
3057
if ((!x) && (!y))
3058
return false;
3059
3060
const uint32_t run_len = c[3] << rshift;
3061
const vec4F run_color(pDst[-1]);
3062
3063
if ((x + run_len) > minor_dim)
3064
return false;
3065
3066
for (uint32_t i = 0; i < run_len; i++)
3067
*pDst++ = run_color;
3068
3069
rshift += 8;
3070
x += run_len;
3071
}
3072
else
3073
{
3074
rshift = 0;
3075
3076
hdr_convert(c, *pDst);
3077
pDst++;
3078
x++;
3079
}
3080
}
3081
continue;
3082
}
3083
3084
// New format
3085
for (uint32_t s = 0; s < 4; s++)
3086
{
3087
uint32_t x_ofs = 0;
3088
while (x_ofs < minor_dim)
3089
{
3090
uint32_t num_remaining = minor_dim - x_ofs;
3091
3092
if (cur_ofs >= filedata.size())
3093
return false;
3094
3095
uint8_t count = filedata[cur_ofs++];
3096
if (count > 128)
3097
{
3098
count -= 128;
3099
if (count > num_remaining)
3100
return false;
3101
3102
if (cur_ofs >= filedata.size())
3103
return false;
3104
const uint8_t val = filedata[cur_ofs++];
3105
3106
for (uint32_t i = 0; i < count; i++)
3107
temp_scanline[x_ofs + i][s] = val;
3108
3109
x_ofs += count;
3110
}
3111
else
3112
{
3113
if ((!count) || (count > num_remaining))
3114
return false;
3115
3116
for (uint32_t i = 0; i < count; i++)
3117
{
3118
if (cur_ofs >= filedata.size())
3119
return false;
3120
const uint8_t val = filedata[cur_ofs++];
3121
3122
temp_scanline[x_ofs + i][s] = val;
3123
}
3124
3125
x_ofs += count;
3126
}
3127
} // while (x_ofs < minor_dim)
3128
} // c
3129
3130
// Convert all the RGBE pixels to float now
3131
for (uint32_t x = 0; x < minor_dim; x++, pDst++)
3132
hdr_convert(temp_scanline[x], *pDst);
3133
3134
assert((pDst - &img(0, y)) == (int)minor_dim);
3135
3136
} // y
3137
3138
// at here:
3139
// img(width,height)=image pixels as read from file, x=minor axis, y=major axis
3140
// width=minor axis dimension
3141
// height=major axis dimension
3142
// in file, pixels are emitted in minor order, them major (so major=scanlines in the file)
3143
3144
imagef final_img;
3145
if (comp[0] == 0) // if major axis is X
3146
final_img.resize(major_dim, minor_dim);
3147
else // major axis is Y, minor is X
3148
final_img.resize(minor_dim, major_dim);
3149
3150
// TODO: optimize the identity case
3151
for (uint32_t major_iter = 0; major_iter < major_dim; major_iter++)
3152
{
3153
for (uint32_t minor_iter = 0; minor_iter < minor_dim; minor_iter++)
3154
{
3155
const vec4F& p = img(minor_iter, major_iter);
3156
3157
uint32_t dst_x = 0, dst_y = 0;
3158
3159
// is the minor dim output x?
3160
if (comp[1] == 0)
3161
{
3162
// minor axis is x, major is y
3163
3164
// is minor axis (which is output x) flipped?
3165
if (dir[1] < 0)
3166
dst_x = minor_dim - 1 - minor_iter;
3167
else
3168
dst_x = minor_iter;
3169
3170
// is major axis (which is output y) flipped? -1=down in raster order, 1=up
3171
if (dir[0] < 0)
3172
dst_y = major_iter;
3173
else
3174
dst_y = major_dim - 1 - major_iter;
3175
}
3176
else
3177
{
3178
// minor axis is output y, major is output x
3179
3180
// is minor axis (which is output y) flipped?
3181
if (dir[1] < 0)
3182
dst_y = minor_iter;
3183
else
3184
dst_y = minor_dim - 1 - minor_iter;
3185
3186
// is major axis (which is output x) flipped?
3187
if (dir[0] < 0)
3188
dst_x = major_dim - 1 - major_iter;
3189
else
3190
dst_x = major_iter;
3191
}
3192
3193
final_img(dst_x, dst_y) = p;
3194
}
3195
}
3196
3197
final_img.swap(img);
3198
3199
return true;
3200
}
3201
3202
bool read_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
3203
{
3204
uint8_vec filedata;
3205
if (!read_file_to_vec(pFilename, filedata))
3206
return false;
3207
return read_rgbe(filedata, img, hdr_info);
3208
}
3209
3210
static uint8_vec& append_string(uint8_vec& buf, const char* pStr)
3211
{
3212
const size_t str_len = strlen(pStr);
3213
if (!str_len)
3214
return buf;
3215
3216
const size_t ofs = buf.size();
3217
buf.resize(ofs + str_len);
3218
memcpy(&buf[ofs], pStr, str_len);
3219
3220
return buf;
3221
}
3222
3223
static uint8_vec& append_string(uint8_vec& buf, const std::string& str)
3224
{
3225
if (!str.size())
3226
return buf;
3227
return append_string(buf, str.c_str());
3228
}
3229
3230
static inline void float2rgbe(color_rgba &rgbe, const vec4F &c)
3231
{
3232
const float red = c[0], green = c[1], blue = c[2];
3233
assert(red >= 0.0f && green >= 0.0f && blue >= 0.0f);
3234
3235
const float max_v = basisu::maximumf(basisu::maximumf(red, green), blue);
3236
3237
if (max_v < 1e-32f)
3238
rgbe.clear();
3239
else
3240
{
3241
int e;
3242
const float scale = frexp(max_v, &e) * 256.0f / max_v;
3243
rgbe[0] = (uint8_t)(clamp<int>((int)(red * scale), 0, 255));
3244
rgbe[1] = (uint8_t)(clamp<int>((int)(green * scale), 0, 255));
3245
rgbe[2] = (uint8_t)(clamp<int>((int)(blue * scale), 0, 255));
3246
rgbe[3] = (uint8_t)(e + 128);
3247
}
3248
}
3249
3250
const bool RGBE_FORCE_RAW = false;
3251
const bool RGBE_FORCE_OLD_CRUNCH = false; // note must readers (particularly stb_image.h's) don't properly support this, when they should
3252
3253
bool write_rgbe(uint8_vec &file_data, imagef& img, rgbe_header_info& hdr_info)
3254
{
3255
if (!img.get_width() || !img.get_height())
3256
return false;
3257
3258
const uint32_t width = img.get_width(), height = img.get_height();
3259
3260
file_data.resize(0);
3261
file_data.reserve(1024 + img.get_width() * img.get_height() * 4);
3262
3263
append_string(file_data, "#?RADIANCE\n");
3264
3265
if (hdr_info.m_has_exposure)
3266
append_string(file_data, string_format("EXPOSURE=%g\n", hdr_info.m_exposure));
3267
3268
if (hdr_info.m_has_gamma)
3269
append_string(file_data, string_format("GAMMA=%g\n", hdr_info.m_gamma));
3270
3271
append_string(file_data, "FORMAT=32-bit_rle_rgbe\n\n");
3272
append_string(file_data, string_format("-Y %u +X %u\n", height, width));
3273
3274
if (((width < 8) || (width > 0x7FFF)) || (RGBE_FORCE_RAW))
3275
{
3276
for (uint32_t y = 0; y < height; y++)
3277
{
3278
for (uint32_t x = 0; x < width; x++)
3279
{
3280
color_rgba rgbe;
3281
float2rgbe(rgbe, img(x, y));
3282
append_vector(file_data, (const uint8_t *)&rgbe, sizeof(rgbe));
3283
}
3284
}
3285
}
3286
else if (RGBE_FORCE_OLD_CRUNCH)
3287
{
3288
for (uint32_t y = 0; y < height; y++)
3289
{
3290
int prev_r = -1, prev_g = -1, prev_b = -1, prev_e = -1;
3291
uint32_t cur_run_len = 0;
3292
3293
for (uint32_t x = 0; x < width; x++)
3294
{
3295
color_rgba rgbe;
3296
float2rgbe(rgbe, img(x, y));
3297
3298
if ((rgbe[0] == prev_r) && (rgbe[1] == prev_g) && (rgbe[2] == prev_b) && (rgbe[3] == prev_e))
3299
{
3300
if (++cur_run_len == 255)
3301
{
3302
// this ensures rshift stays 0, it's lame but this path is only for testing readers
3303
color_rgba f(1, 1, 1, cur_run_len - 1);
3304
append_vector(file_data, (const uint8_t*)&f, sizeof(f));
3305
append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
3306
cur_run_len = 0;
3307
}
3308
}
3309
else
3310
{
3311
if (cur_run_len > 0)
3312
{
3313
color_rgba f(1, 1, 1, cur_run_len);
3314
append_vector(file_data, (const uint8_t*)&f, sizeof(f));
3315
3316
cur_run_len = 0;
3317
}
3318
3319
append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
3320
3321
prev_r = rgbe[0];
3322
prev_g = rgbe[1];
3323
prev_b = rgbe[2];
3324
prev_e = rgbe[3];
3325
}
3326
} // x
3327
3328
if (cur_run_len > 0)
3329
{
3330
color_rgba f(1, 1, 1, cur_run_len);
3331
append_vector(file_data, (const uint8_t*)&f, sizeof(f));
3332
}
3333
} // y
3334
}
3335
else
3336
{
3337
uint8_vec temp[4];
3338
for (uint32_t c = 0; c < 4; c++)
3339
temp[c].resize(width);
3340
3341
for (uint32_t y = 0; y < height; y++)
3342
{
3343
color_rgba rgbe(2, 2, width >> 8, width & 0xFF);
3344
append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
3345
3346
for (uint32_t x = 0; x < width; x++)
3347
{
3348
float2rgbe(rgbe, img(x, y));
3349
3350
for (uint32_t c = 0; c < 4; c++)
3351
temp[c][x] = rgbe[c];
3352
}
3353
3354
for (uint32_t c = 0; c < 4; c++)
3355
{
3356
int raw_ofs = -1;
3357
3358
uint32_t x = 0;
3359
while (x < width)
3360
{
3361
const uint32_t num_bytes_remaining = width - x;
3362
const uint32_t max_run_len = basisu::minimum<uint32_t>(num_bytes_remaining, 127);
3363
const uint8_t cur_byte = temp[c][x];
3364
3365
uint32_t run_len = 1;
3366
while (run_len < max_run_len)
3367
{
3368
if (temp[c][x + run_len] != cur_byte)
3369
break;
3370
run_len++;
3371
}
3372
3373
const uint32_t cost_to_keep_raw = ((raw_ofs != -1) ? 0 : 1) + run_len; // 0 or 1 bytes to start a raw run, then the repeated bytes issued as raw
3374
const uint32_t cost_to_take_run = 2 + 1; // 2 bytes to issue the RLE, then 1 bytes to start whatever follows it (raw or RLE)
3375
3376
if ((run_len >= 3) && (cost_to_take_run < cost_to_keep_raw))
3377
{
3378
file_data.push_back((uint8_t)(128 + run_len));
3379
file_data.push_back(cur_byte);
3380
3381
x += run_len;
3382
raw_ofs = -1;
3383
}
3384
else
3385
{
3386
if (raw_ofs < 0)
3387
{
3388
raw_ofs = (int)file_data.size();
3389
file_data.push_back(0);
3390
}
3391
3392
if (++file_data[raw_ofs] == 128)
3393
raw_ofs = -1;
3394
3395
file_data.push_back(cur_byte);
3396
3397
x++;
3398
}
3399
} // x
3400
3401
} // c
3402
} // y
3403
}
3404
3405
return true;
3406
}
3407
3408
bool write_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
3409
{
3410
uint8_vec file_data;
3411
if (!write_rgbe(file_data, img, hdr_info))
3412
return false;
3413
return write_vec_to_file(pFilename, file_data);
3414
}
3415
3416
bool read_exr(const char* pFilename, imagef& img, int& n_chans)
3417
{
3418
n_chans = 0;
3419
3420
int width = 0, height = 0;
3421
float* out_rgba = nullptr;
3422
const char* err = nullptr;
3423
3424
int status = LoadEXRWithLayer(&out_rgba, &width, &height, pFilename, nullptr, &err);
3425
n_chans = 4;
3426
if (status != 0)
3427
{
3428
error_printf("Failed loading .EXR image \"%s\"! (TinyEXR error: %s)\n", pFilename, err ? err : "?");
3429
FreeEXRErrorMessage(err);
3430
free(out_rgba);
3431
return false;
3432
}
3433
3434
const uint32_t MAX_SUPPORTED_DIM = 65536;
3435
if ((width < 1) || (height < 1) || (width > (int)MAX_SUPPORTED_DIM) || (height > (int)MAX_SUPPORTED_DIM))
3436
{
3437
error_printf("Invalid dimensions of .EXR image \"%s\"!\n", pFilename);
3438
free(out_rgba);
3439
return false;
3440
}
3441
3442
img.resize(width, height);
3443
3444
if (n_chans == 1)
3445
{
3446
const float* pSrc = out_rgba;
3447
vec4F* pDst = img.get_ptr();
3448
3449
for (int y = 0; y < height; y++)
3450
{
3451
for (int x = 0; x < width; x++)
3452
{
3453
(*pDst)[0] = pSrc[0];
3454
(*pDst)[1] = pSrc[1];
3455
(*pDst)[2] = pSrc[2];
3456
(*pDst)[3] = 1.0f;
3457
3458
pSrc += 4;
3459
++pDst;
3460
}
3461
}
3462
}
3463
else
3464
{
3465
memcpy((void *)img.get_ptr(), out_rgba, static_cast<size_t>(sizeof(float) * 4 * img.get_total_pixels()));
3466
}
3467
3468
free(out_rgba);
3469
return true;
3470
}
3471
3472
bool read_exr(const void* pMem, size_t mem_size, imagef& img)
3473
{
3474
float* out_rgba = nullptr;
3475
int width = 0, height = 0;
3476
const char* pErr = nullptr;
3477
int res = LoadEXRFromMemory(&out_rgba, &width, &height, (const uint8_t*)pMem, mem_size, &pErr);
3478
if (res < 0)
3479
{
3480
error_printf("Failed loading .EXR image from memory! (TinyEXR error: %s)\n", pErr ? pErr : "?");
3481
FreeEXRErrorMessage(pErr);
3482
free(out_rgba);
3483
return false;
3484
}
3485
3486
img.resize(width, height);
3487
memcpy((void *)img.get_ptr(), out_rgba, width * height * sizeof(float) * 4);
3488
free(out_rgba);
3489
3490
return true;
3491
}
3492
3493
bool write_exr(const char* pFilename, const imagef& img, uint32_t n_chans, uint32_t flags)
3494
{
3495
assert((n_chans == 1) || (n_chans == 3) || (n_chans == 4));
3496
3497
const bool linear_hint = (flags & WRITE_EXR_LINEAR_HINT) != 0,
3498
store_float = (flags & WRITE_EXR_STORE_FLOATS) != 0,
3499
no_compression = (flags & WRITE_EXR_NO_COMPRESSION) != 0;
3500
3501
const uint32_t width = img.get_width(), height = img.get_height();
3502
assert(width && height);
3503
3504
if (!width || !height)
3505
return false;
3506
3507
float_vec layers[4];
3508
float* image_ptrs[4];
3509
for (uint32_t c = 0; c < n_chans; c++)
3510
{
3511
layers[c].resize(width * height);
3512
image_ptrs[c] = layers[c].get_ptr();
3513
}
3514
3515
// ABGR
3516
int chan_order[4] = { 3, 2, 1, 0 };
3517
3518
if (n_chans == 1)
3519
{
3520
// Y
3521
chan_order[0] = 0;
3522
}
3523
else if (n_chans == 3)
3524
{
3525
// BGR
3526
chan_order[0] = 2;
3527
chan_order[1] = 1;
3528
chan_order[2] = 0;
3529
}
3530
else if (n_chans != 4)
3531
{
3532
assert(0);
3533
return false;
3534
}
3535
3536
for (uint32_t y = 0; y < height; y++)
3537
{
3538
for (uint32_t x = 0; x < width; x++)
3539
{
3540
const vec4F& p = img(x, y);
3541
3542
for (uint32_t c = 0; c < n_chans; c++)
3543
layers[c][x + y * width] = p[chan_order[c]];
3544
} // x
3545
} // y
3546
3547
EXRHeader header;
3548
InitEXRHeader(&header);
3549
3550
EXRImage image;
3551
InitEXRImage(&image);
3552
3553
image.num_channels = n_chans;
3554
image.images = (unsigned char**)image_ptrs;
3555
image.width = width;
3556
image.height = height;
3557
3558
header.num_channels = n_chans;
3559
3560
header.channels = (EXRChannelInfo*)calloc(header.num_channels, sizeof(EXRChannelInfo));
3561
3562
// Must be (A)BGR order, since most of EXR viewers expect this channel order.
3563
for (uint32_t i = 0; i < n_chans; i++)
3564
{
3565
char c = 'Y';
3566
if (n_chans == 3)
3567
c = "BGR"[i];
3568
else if (n_chans == 4)
3569
c = "ABGR"[i];
3570
3571
header.channels[i].name[0] = c;
3572
header.channels[i].name[1] = '\0';
3573
3574
header.channels[i].p_linear = linear_hint;
3575
}
3576
3577
header.pixel_types = (int*)calloc(header.num_channels, sizeof(int));
3578
header.requested_pixel_types = (int*)calloc(header.num_channels, sizeof(int));
3579
3580
if (!no_compression)
3581
header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
3582
3583
for (int i = 0; i < header.num_channels; i++)
3584
{
3585
// pixel type of input image
3586
header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
3587
3588
// pixel type of output image to be stored in .EXR
3589
header.requested_pixel_types[i] = store_float ? TINYEXR_PIXELTYPE_FLOAT : TINYEXR_PIXELTYPE_HALF;
3590
}
3591
3592
const char* pErr_msg = nullptr;
3593
3594
int ret = SaveEXRImageToFile(&image, &header, pFilename, &pErr_msg);
3595
if (ret != TINYEXR_SUCCESS)
3596
{
3597
error_printf("Save EXR err: %s\n", pErr_msg);
3598
FreeEXRErrorMessage(pErr_msg);
3599
}
3600
3601
free(header.channels);
3602
free(header.pixel_types);
3603
free(header.requested_pixel_types);
3604
3605
return (ret == TINYEXR_SUCCESS);
3606
}
3607
3608
void image::debug_text(uint32_t x_ofs, uint32_t y_ofs, uint32_t scale_x, uint32_t scale_y, const color_rgba& fg, const color_rgba* pBG, bool alpha_only, const char* pFmt, ...)
3609
{
3610
char buf[2048];
3611
3612
va_list args;
3613
va_start(args, pFmt);
3614
#ifdef _WIN32
3615
vsprintf_s(buf, sizeof(buf), pFmt, args);
3616
#else
3617
vsnprintf(buf, sizeof(buf), pFmt, args);
3618
#endif
3619
va_end(args);
3620
3621
const char* p = buf;
3622
3623
const uint32_t orig_x_ofs = x_ofs;
3624
3625
while (*p)
3626
{
3627
uint8_t c = *p++;
3628
if ((c < 32) || (c > 127))
3629
c = '.';
3630
3631
const uint8_t* pGlpyh = &g_debug_font8x8_basic[c - 32][0];
3632
3633
for (uint32_t y = 0; y < 8; y++)
3634
{
3635
uint32_t row_bits = pGlpyh[y];
3636
for (uint32_t x = 0; x < 8; x++)
3637
{
3638
const uint32_t q = row_bits & (1 << x);
3639
3640
const color_rgba* pColor = q ? &fg : pBG;
3641
if (!pColor)
3642
continue;
3643
3644
if (alpha_only)
3645
fill_box_alpha(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
3646
else
3647
fill_box(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
3648
}
3649
}
3650
3651
x_ofs += 8 * scale_x;
3652
if ((x_ofs + 8 * scale_x) > m_width)
3653
{
3654
x_ofs = orig_x_ofs;
3655
y_ofs += 8 * scale_y;
3656
}
3657
}
3658
}
3659
3660
// Very basic global Reinhard tone mapping, output converted to sRGB with no dithering, alpha is carried through unchanged.
3661
// Only used for debugging/development.
3662
void tonemap_image_reinhard(image &ldr_img, const imagef &hdr_img, float exposure, bool add_noise, bool per_component, bool luma_scaling)
3663
{
3664
uint32_t width = hdr_img.get_width(), height = hdr_img.get_height();
3665
3666
ldr_img.resize(width, height);
3667
3668
rand r;
3669
r.seed(128);
3670
3671
for (uint32_t y = 0; y < height; y++)
3672
{
3673
for (uint32_t x = 0; x < width; x++)
3674
{
3675
vec4F c(hdr_img(x, y));
3676
3677
if (per_component)
3678
{
3679
for (uint32_t t = 0; t < 3; t++)
3680
{
3681
if (c[t] <= 0.0f)
3682
{
3683
c[t] = 0.0f;
3684
}
3685
else
3686
{
3687
c[t] *= exposure;
3688
c[t] = c[t] / (1.0f + c[t]);
3689
}
3690
}
3691
}
3692
else
3693
{
3694
c[0] *= exposure;
3695
c[1] *= exposure;
3696
c[2] *= exposure;
3697
3698
const float L = 0.2126f * c[0] + 0.7152f * c[1] + 0.0722f * c[2];
3699
3700
float Lmapped = 0.0f;
3701
if (L > 0.0f)
3702
{
3703
//Lmapped = L / (1.0f + L);
3704
//Lmapped /= L;
3705
3706
Lmapped = 1.0f / (1.0f + L);
3707
}
3708
3709
c[0] = c[0] * Lmapped;
3710
c[1] = c[1] * Lmapped;
3711
c[2] = c[2] * Lmapped;
3712
3713
if (luma_scaling)
3714
{
3715
// Keeps the ratio of r/g/b intact
3716
float m = maximum(c[0], c[1], c[2]);
3717
if (m > 1.0f)
3718
{
3719
c /= m;
3720
}
3721
}
3722
}
3723
3724
c.clamp(0.0f, 1.0f);
3725
3726
c[3] = c[3] * 255.0f;
3727
3728
color_rgba& o = ldr_img(x, y);
3729
3730
if (add_noise)
3731
{
3732
c[0] = linear_to_srgb(c[0]) * 255.0f;
3733
c[1] = linear_to_srgb(c[1]) * 255.0f;
3734
c[2] = linear_to_srgb(c[2]) * 255.0f;
3735
3736
const float NOISE_AMP = .5f;
3737
c[0] += r.frand(-NOISE_AMP, NOISE_AMP);
3738
c[1] += r.frand(-NOISE_AMP, NOISE_AMP);
3739
c[2] += r.frand(-NOISE_AMP, NOISE_AMP);
3740
3741
c.clamp(0.0f, 255.0f);
3742
3743
o[0] = (uint8_t)fast_roundf_int(c[0]);
3744
o[1] = (uint8_t)fast_roundf_int(c[1]);
3745
o[2] = (uint8_t)fast_roundf_int(c[2]);
3746
o[3] = (uint8_t)fast_roundf_int(c[3]);
3747
}
3748
else
3749
{
3750
o[0] = g_fast_linear_to_srgb.convert(c[0]);
3751
o[1] = g_fast_linear_to_srgb.convert(c[1]);
3752
o[2] = g_fast_linear_to_srgb.convert(c[2]);
3753
o[3] = (uint8_t)fast_roundf_int(c[3]);
3754
}
3755
}
3756
}
3757
}
3758
3759
bool tonemap_image_compressive(image& dst_img, const imagef& hdr_test_img)
3760
{
3761
const uint32_t width = hdr_test_img.get_width();
3762
const uint32_t height = hdr_test_img.get_height();
3763
3764
uint16_vec orig_half_img(width * 3 * height);
3765
uint16_vec half_img(width * 3 * height);
3766
3767
int max_shift = 32;
3768
3769
for (uint32_t y = 0; y < height; y++)
3770
{
3771
for (uint32_t x = 0; x < width; x++)
3772
{
3773
const vec4F& p = hdr_test_img(x, y);
3774
3775
for (uint32_t i = 0; i < 3; i++)
3776
{
3777
if (p[i] < 0.0f)
3778
return false;
3779
if (p[i] > basist::MAX_HALF_FLOAT)
3780
return false;
3781
3782
uint32_t h = basist::float_to_half(p[i]);
3783
//uint32_t orig_h = h;
3784
3785
orig_half_img[(x + y * width) * 3 + i] = (uint16_t)h;
3786
3787
// Rotate sign bit into LSB
3788
//h = rot_left16((uint16_t)h, 1);
3789
//assert(rot_right16((uint16_t)h, 1) == orig_h);
3790
h <<= 1;
3791
3792
half_img[(x + y * width) * 3 + i] = (uint16_t)h;
3793
3794
// Determine # of leading zero bits, ignoring the sign bit
3795
if (h)
3796
{
3797
int lz = clz(h) - 16;
3798
assert(lz >= 0 && lz <= 16);
3799
3800
assert((h << lz) <= 0xFFFF);
3801
3802
max_shift = basisu::minimum<int>(max_shift, lz);
3803
}
3804
} // i
3805
} // x
3806
} // y
3807
3808
//printf("tonemap_image_compressive: Max leading zeros: %i\n", max_shift);
3809
3810
uint32_t high_hist[256];
3811
clear_obj(high_hist);
3812
3813
for (uint32_t y = 0; y < height; y++)
3814
{
3815
for (uint32_t x = 0; x < width; x++)
3816
{
3817
for (uint32_t i = 0; i < 3; i++)
3818
{
3819
uint16_t& hf = half_img[(x + y * width) * 3 + i];
3820
3821
assert(((uint32_t)hf << max_shift) <= 65535);
3822
3823
hf <<= max_shift;
3824
3825
uint32_t h = (uint8_t)(hf >> 8);
3826
high_hist[h]++;
3827
}
3828
} // x
3829
} // y
3830
3831
uint32_t total_vals_used = 0;
3832
int remap_old_to_new[256];
3833
for (uint32_t i = 0; i < 256; i++)
3834
remap_old_to_new[i] = -1;
3835
3836
for (uint32_t i = 0; i < 256; i++)
3837
{
3838
if (high_hist[i] != 0)
3839
{
3840
remap_old_to_new[i] = total_vals_used;
3841
total_vals_used++;
3842
}
3843
}
3844
3845
assert(total_vals_used >= 1);
3846
3847
//printf("tonemap_image_compressive: Total used high byte values: %u, unused: %u\n", total_vals_used, 256 - total_vals_used);
3848
3849
bool val_used[256];
3850
clear_obj(val_used);
3851
3852
int remap_new_to_old[256];
3853
for (uint32_t i = 0; i < 256; i++)
3854
remap_new_to_old[i] = -1;
3855
BASISU_NOTE_UNUSED(remap_new_to_old);
3856
3857
int prev_c = -1;
3858
BASISU_NOTE_UNUSED(prev_c);
3859
for (uint32_t i = 0; i < 256; i++)
3860
{
3861
if (remap_old_to_new[i] >= 0)
3862
{
3863
int c;
3864
if (total_vals_used <= 1)
3865
c = remap_old_to_new[i];
3866
else
3867
{
3868
c = (remap_old_to_new[i] * 255 + ((total_vals_used - 1) / 2)) / (total_vals_used - 1);
3869
3870
assert(c > prev_c);
3871
}
3872
3873
assert(!val_used[c]);
3874
3875
remap_new_to_old[c] = i;
3876
3877
remap_old_to_new[i] = c;
3878
prev_c = c;
3879
3880
//printf("%u ", c);
3881
3882
val_used[c] = true;
3883
}
3884
} // i
3885
//printf("\n");
3886
3887
dst_img.resize(width, height);
3888
3889
for (uint32_t y = 0; y < height; y++)
3890
{
3891
for (uint32_t x = 0; x < width; x++)
3892
{
3893
for (uint32_t c = 0; c < 3; c++)
3894
{
3895
uint16_t& v16 = half_img[(x + y * width) * 3 + c];
3896
3897
uint32_t hb = v16 >> 8;
3898
//uint32_t lb = v16 & 0xFF;
3899
3900
assert(remap_old_to_new[hb] != -1);
3901
assert(remap_old_to_new[hb] <= 255);
3902
assert(remap_new_to_old[remap_old_to_new[hb]] == (int)hb);
3903
3904
hb = remap_old_to_new[hb];
3905
3906
//v16 = (uint16_t)((hb << 8) | lb);
3907
3908
dst_img(x, y)[c] = (uint8_t)hb;
3909
}
3910
} // x
3911
} // y
3912
3913
return true;
3914
}
3915
3916
bool tonemap_image_compressive2(image& dst_img, const imagef& hdr_test_img)
3917
{
3918
const uint32_t width = hdr_test_img.get_width();
3919
const uint32_t height = hdr_test_img.get_height();
3920
3921
dst_img.resize(width, height);
3922
dst_img.set_all(color_rgba(0, 0, 0, 255));
3923
3924
basisu::vector<basist::half_float> half_img(width * 3 * height);
3925
3926
uint32_t low_h = UINT32_MAX, high_h = 0;
3927
3928
for (uint32_t y = 0; y < height; y++)
3929
{
3930
for (uint32_t x = 0; x < width; x++)
3931
{
3932
const vec4F& p = hdr_test_img(x, y);
3933
3934
for (uint32_t i = 0; i < 3; i++)
3935
{
3936
float f = p[i];
3937
3938
if (std::isnan(f) || std::isinf(f))
3939
f = 0.0f;
3940
else if (f < 0.0f)
3941
f = 0.0f;
3942
else if (f > basist::MAX_HALF_FLOAT)
3943
f = basist::MAX_HALF_FLOAT;
3944
3945
uint32_t h = basist::float_to_half(f);
3946
3947
low_h = minimum(low_h, h);
3948
high_h = maximum(high_h, h);
3949
3950
half_img[(x + y * width) * 3 + i] = (basist::half_float)h;
3951
3952
} // i
3953
} // x
3954
} // y
3955
3956
if (low_h == high_h)
3957
return false;
3958
3959
for (uint32_t y = 0; y < height; y++)
3960
{
3961
for (uint32_t x = 0; x < width; x++)
3962
{
3963
for (uint32_t i = 0; i < 3; i++)
3964
{
3965
basist::half_float h = half_img[(x + y * width) * 3 + i];
3966
3967
float f = (float)(h - low_h) / (float)(high_h - low_h);
3968
3969
int iv = basisu::clamp<int>((int)std::round(f * 255.0f), 0, 255);
3970
3971
dst_img(x, y)[i] = (uint8_t)iv;
3972
3973
} // i
3974
} // x
3975
} // y
3976
3977
return true;
3978
}
3979
3980
} // namespace basisu
3981
3982