-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
421 lines (376 loc) · 13.4 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Portable float & float16 pfm/phm image viewer
// Copyright Silicon Studio K.K. 2023
// author: Vivien Oddou
// BSD License
#include <iostream>
#include <ios>
#include <fstream>
#include <iterator>
#include <string_view>
#include <algorithm>
#include <simd_routines.h> // auto generated by ispc and located in the build folder (config from cmake custom target)
#include <nana/gui.hpp>
#include <nana/gui/widgets/label.hpp>
#include <nana/gui/widgets/button.hpp>
#include <nana/gui/widgets/group.hpp>
#include <nana/gui/widgets/picture.hpp>
#include <nana/gui/widgets/slider.hpp>
#include <nana/gui/widgets/spinbox.hpp>
#include <nana/gui/widgets/scroll.hpp>
#include <nana/gui/filebox.hpp>
#include <nana/gui/msgbox.hpp>
#include <nana/paint/graphics.hpp>
#ifdef _WIN32
#define WINONLY(x) x
#include <io.h>
#include <fcntl.h>
#else
#define WINONLY(x)
#endif
namespace fs = std::filesystem;
using std::vector;
using std::string_view;
using namespace nana;
// image metadata
struct pfm_header
{
std::string magic;
int w = 0, h = 0;
float scale_endian;
char get_magic2ndchar() const { return magic.length() >= 2 ? magic[1] : 0; }
bool is_half() const { return tolower(get_magic2ndchar()) == 'h'; }
bool is_mono() const { return islower(get_magic2ndchar()); }
int num_channels() const { return is_mono() ? 1 : 3; }
size_t calc_raw_size() const { return w * h * num_channels() * sizeof(float) / (is_half() ? 2 : 1); }
};
// check for input pipe, e.g: `$> PfmViewer.exe < file.pfm`
bool pending_data(std::istream& is)
{
is.seekg(0, is.end);
auto length = is.tellg();
is.seekg(0, is.beg);
return !(length < 0);
}
// one-liner helper
msgbox message(std::string const& title, msgbox::icon_t ico, msgbox::button_t btn)
{
msgbox m({}, title, btn);
m.icon(ico);
return m;
}
// booleans to checkboxes
// unfortunately nana doesn't appear to use real signal/slot, I haven't found a way to += supplementary callbacks.
// therefore, we chain callbacks manually
template< typename AdditionalCallbackT >
void data_bind(checkbox& cb, bool& data, AdditionalCallbackT&& tocall)
{
cb.check(data);
cb.events().checked([&]() { data = cb.checked(); tocall(); });
}
// using uint8 in ispc causes performance warnings so we use int8 on -128,127 range
// this function is the "signed to unsigned" remap
uint8_t stou(int8_t i)
{
return uint8_t((int)i + 128);
}
// customization point of min for size type
size min(size const& a, size const& b)
{
return {std::min(a.width, b.width), std::min(a.height, b.height)};
}
struct app_settings
{
float exposure = 1.f; // multiplier (not really EV)
bool gamma = true;
bool tone = true;
bool flipy = false;
};
// do file prompting, or pipe/file parsing, and deserialize
void load_pfm_and_raw(int argc /*in*/, char* argv[] /*in*/, pfm_header& pfm /*out*/, vector<char>& raw /*out*/)
{
std::istream* in = nullptr;
fs::path inpath;
std::ifstream infile;
if ((argc >= 2 && argv[1][0] == '-') || pending_data(std::cin)) // input is piped on stdin?
{
in = &std::cin;
in->rdbuf()->pubsetbuf(nullptr, 0); // deactivate buffering otherwise the stream explodes with failbit after 3450 bytes read
}
else if (argc <= 1) // no command line -> open file dialog
{
filebox picker{nullptr, true};
picker.title("Pick image file");
picker.add_filter("Portable half map (.phm)", "*.phm");
picker.add_filter("Portable float map (.pfm)", "*.pfm");
vector<fs::path> paths = picker.show();
if (!paths.empty())
inpath = paths[0];
}
else if (argc >= 2)
inpath = argv[1];
if (!inpath.empty())
{
infile.open(inpath, std::ifstream::in | std::ifstream::binary);
in = &infile;
}
if (!in || !*in) throw std::exception("no good input");
in->exceptions(std::ifstream::failbit | std::ifstream::badbit); // instant give up in case of issues
*in >> pfm.magic >> pfm.w >> pfm.h >> pfm.scale_endian;
std::cout << "magic:" << pfm.magic << " w:" << pfm.w << " h:" << pfm.h << " scale_endian: " << pfm.scale_endian << "\n";
size_t alloc = pfm.calc_raw_size();
if (alloc == 0)
{
(message("No data", msgbox::icon_information, msgbox::ok) << "Width and height are 0 or not found")();
throw std::runtime_error("input data problem");
}
if (alloc > 1'000'000'000)
{
(message("Calculated image size too large", msgbox::icon_error, msgbox::ok)
<< "More than 1GiB of data needed because of parsed width:" << pfm.w << " and height:" << pfm.h)();
throw std::runtime_error("input too big");
}
raw.resize(alloc);
std::cout << "about to read " << alloc << " bytes\n";
in->ignore(1); // jump the last \n after scale_endian
*in >> std::noskipws;
in->clear();
freopen(nullptr, "rb", stdin); // go in binary mode from here
WINONLY(_setmode(fileno(stdin), O_BINARY | O_RDONLY));
// read bulk:
in->sync();
in->read(raw.data(), alloc);
if (auto cnt = in->gcount(); cnt != alloc)
std::cout << "not enough data read (" << cnt << " instead of " << alloc << " expected)\n";
else if (std::cin.rdbuf()->in_avail() > 0)
std::cout << "remaining data not read " << std::cin.rdbuf()->in_avail() << "\n";
else
std::cout << "success\n";
}
// Transform the HDR source image to a displayable SDR image
void raw_to_rgb(pfm_header const& pfm, vector<char> const& raw, vector<int8_t>& rgb /*out*/, app_settings const& state)
{
// perform slow operations (pow, polynomials, divisions, minmax reduce...) using avx512 SIMD
if (state.tone)
{
if (state.gamma)
{
if (pfm.is_half())
ispc::ToneAllF16PixelsAndToGamma((uint16_t*)raw.data(), rgb.data(), raw.size() / 2, state.exposure);
else
ispc::ToneAllF32PixelsAndToGamma((float*)raw.data(), rgb.data(), raw.size() / 4, state.exposure);
}
else
{
if (pfm.is_half())
ispc::ToneAllF16Pixels((uint16_t*)raw.data(), rgb.data(), raw.size() / 2, state.exposure);
else
ispc::ToneAllF32Pixels((float*)raw.data(), rgb.data(), raw.size() / 4, state.exposure);
}
}
else
{
if (state.gamma)
{
if (pfm.is_half())
ispc::GammaAllF16Pixels((uint16_t*)raw.data(), rgb.data(), raw.size() / 2, state.exposure);
else
ispc::GammaAllF32Pixels((float*)raw.data(), rgb.data(), raw.size() / 4, state.exposure);
}
else
{
if (pfm.is_half())
ispc::ToSignedRgbAllF16Pixels((uint16_t*)raw.data(), rgb.data(), raw.size() / 2, state.exposure);
else
ispc::ToSignedRgbAllF32Pixels((float*)raw.data(), rgb.data(), raw.size() / 4, state.exposure);
}
}
}
// transfer signed-byte RGB image vector to a GUI-compatible surface
void rgb_to_graphics(pfm_header const& pfm, vector<int8_t> const& rgb, paint::graphics& surface, bool flipy)
{
if (pfm.num_channels() == 3)
{
//#pragma omp parallel for schedule(static) // cannot be parallelized because .set_pixel is stateful and isn't using TLS
for (int y = 0; y < pfm.h; ++y)
for (int x = 0; x < pfm.w; ++x)
{
int realy = flipy ? pfm.h - y - 1 : y;
int8_t const* p = &rgb[3 * (realy * pfm.w + x)];
surface.set_pixel(x, y, {stou(p[0]), stou(p[1]), stou(p[2])});
}
}
else
{
for (int y = 0; y < pfm.h; ++y)
for (int x = 0; x < pfm.w; ++x)
{
int realy = flipy ? pfm.h - y - 1 : y;
uint8_t bw{stou(rgb[realy * pfm.w + x])};
surface.set_pixel(x, y, {bw, bw, bw});
}
}
}
// extract statistics from HDR image
std::pair<float, float> min_max(pfm_header const& pfm, vector<char> const& raw)
{
float mi, ma;
if (pfm.is_half())
ispc::GetMinMaxF16((uint16_t*)raw.data(), raw.size() / 2, mi, ma);
else
ispc::GetMinMaxF32((float*)raw.data(), raw.size() / 4, mi, ma);
return {mi, ma};
}
// leightweight process control
struct lwpctl
{
std::mutex m;
std::condition_variable cv;
bool dirty = false;
bool quit = false;
void wait()
{
std::unique_lock lk(m);
cv.wait(lk, [&] {return dirty || quit; });
dirty = false;
}
void trigger_recompute()
{
{
std::lock_guard lk(m);
dirty = true;
}
cv.notify_one();
}
void set_quit()
{
{
std::lock_guard lk(m);
quit = true;
}
cv.notify_one();
}
};
int main(int argc, char* argv[])
{
pfm_header pfm;
vector<char> raw;
try
{
load_pfm_and_raw(argc, argv, pfm, raw);
}
catch (std::ios_base::failure& e)
{
(message("Exception in input stream", msgbox::icon_error, msgbox::ok) << e.what())();
return 1;
}
catch (...)
{
return 2;
}
vector<int8_t> rgb;
rgb.resize(pfm.w * pfm.h * pfm.num_channels());
app_settings state;
raw_to_rgb(pfm, raw, rgb, state);
auto [rangemin, rangemax] = min_max(pfm, raw);
paint::graphics surface(size(pfm.w, pfm.h));
rgb_to_graphics(pfm, rgb, surface, state.flipy);
// main window
static const int initial_width_right_pane = 200;
static const int initial_width_window = 1600;
static const int initial_height_window = 1000;
form mainwd{API::make_center(std::min(pfm.w, initial_width_window) + initial_width_right_pane,
std::min(pfm.h, initial_height_window))};
mainwd.caption("Silicon Studio PFM/PHM Viewer");
// image zone:
panel<false> panelZone{mainwd};
picture pic{panelZone};
nana::scroll<false> scrollH{panelZone};
nana::scroll<true> scrollV{panelZone};
auto resetAmounts = [&]()
{
scrollH.amount(std::max(0, pfm.w - (int)panelZone.size().width + 16));
scrollV.amount(std::max(0, pfm.h - (int)panelZone.size().height + 16));
};
panelZone.events().resized(resetAmounts);
place l2{panelZone};
l2.div("<vert <<sub><scrollV weight=16>> <scrollH weight=16>>");
l2["sub"] << pic;
l2["scrollV"] << scrollV;
l2["scrollH"] << scrollH;
l2.collocate();
drawing dr{pic};
dr.draw([&](paint::graphics& a_g)
{
rectangle dst{{0,0}, min(panelZone.size(), a_g.size())};
point src{(int)scrollH.value(), (int)scrollV.value()};
a_g.bitblt(dst, surface, src);
});
scrollH.events().value_changed([&]() { API::refresh_window(pic); });
scrollV.events().value_changed([&]() { API::refresh_window(pic); });
// control panel zone:
group opts_gp{mainwd, "Options"};
opts_gp.radio_mode(false);
panel<false> ctrls{mainwd};
place ctrlgrid{ctrls};
label ev_lbl{ctrls};
ev_lbl.caption("exposure:");
slider ev_slider{ctrls};
ev_slider.maximum(200);
ev_slider.value(100); // 1*100
label maxev_lbl{ctrls};
maxev_lbl.caption("ev-range max:");
spinbox maxev_spin{ctrls};
maxev_spin.range(0.0, 1000000.0, 0.1);
maxev_spin.value("2");
maxev_spin.events().text_changed([&]()
{
ev_slider.maximum(100 * maxev_spin.to_double());
});
ctrlgrid.div("<ctrlgrid grid=[2,2]>");
ctrlgrid["ctrlgrid"] << ev_lbl << ev_slider << maxev_lbl << maxev_spin;
ctrlgrid.collocate();
label curexp_lbl{mainwd};
auto refresh_curexp_lbl = [&]() {curexp_lbl.caption("EV: " + std::to_string(state.exposure)); };
refresh_curexp_lbl();
label activity{mainwd};
lwpctl pc;
// we need a thread because HDC pixel transfer is slow
auto image_recomputer = [&]()
{
for (;;)
{
pc.wait();
if (pc.quit) return;
activity.caption("CPU activity: compute...");
raw_to_rgb(pfm, raw, rgb, state);
activity.caption("CPU activity: copy pixels...");
rgb_to_graphics(pfm, rgb, surface, state.flipy);
activity.caption("");
API::refresh_window(pic);
}
};
// use std thread. nana::thread::pool thing is horrendous and super slow. don't use it.
std::thread worker(image_recomputer);
ev_slider.events().value_changed([&]()
{
state.exposure = ev_slider.value() / 100.f;
refresh_curexp_lbl();
pc.trigger_recompute();
});
data_bind(opts_gp.add_option("Gamma"), state.gamma, [&](){pc.trigger_recompute();});
data_bind(opts_gp.add_option("Filmic tone"), state.tone, [&](){pc.trigger_recompute();});
data_bind(opts_gp.add_option("Flip Y"), state.flipy, [&](){pc.trigger_recompute();});
label info{mainwd};
info.caption("source range: " + std::to_string(rangemin) + ", " + std::to_string(rangemax));
place layout{mainwd};
layout.div("<picdisplay>|200<vert controls arrange=[100,64,24,24,24]>");
layout["picdisplay"] << panelZone;
layout["controls"] << opts_gp << ctrls << curexp_lbl << info << activity;
layout.collocate();
mainwd.show();
exec();
// stop the refresher thread otherwise we get an assert in the CRT
pc.set_quit();
worker.join();
return 0;
}