Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
488 lines (442 loc) · 20.3 KB
/
Copy pathmain.cpp
File metadata and controls
488 lines (442 loc) · 20.3 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Portable float & float16 pfm/phm image viewer
// Copyright Silicon Studio K.K. 2023-2026
// author: Vivien Oddou
// BSD License
#include <iostream>
#include <ios>
#include <fstream>
#include <algorithm>
#include <atomic>
#include <thread>
#include <cmath>
#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>
#include <nana/paint/pixel_buffer.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 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; }
nana::size dims() const { return {(unsigned)w, (unsigned)h}; }
size_t num_elems() const { return (size_t)w * h * num_channels(); } // scalar components, all channels
size_t calc_raw_size() const { return num_elems() * (is_half() ? 2 : 4); }
};
// 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(); });
}
struct app_settings
{
float exposure = 1.f; // multiplier (not really EV)
bool gamma = true;
bool tone = true;
bool flipy = false;
};
// what part of the image the viewport shows
struct view_state
{
float zoom = 1.f; // screen pixels per source pixel
point pan; // scroll offset, in screen pixels, from the top-left of the zoomed image
// viewport coordinate where source pixel (0,0) lands: centered while the zoomed image is
// smaller than the viewport, driven by the scroll offset once it overflows.
point origin(nana::size vp, nana::size img) const
{
auto axis = [z = zoom](unsigned page, unsigned len, int off)
{ float span = len * z; return span <= page ? (int)((page - span) * .5f) : -off; };
return {axis(vp.width, img.width, pan.x), axis(vp.height, img.height, pan.y)};
}
};
static const float zoom_min = 1.f / 32, zoom_max = 32.f;
static const uint32_t backdrop = 0xFF1E1E1E; // shown around the image when it doesn't fill the viewport
// next zoom on the ladder (one notch = a factor of sqrt(2), so every other notch is a power of two)
float zoom_notch(float zoom, int dir)
{
float rung = std::log2(zoom) * 2;
rung = dir > 0 ? std::floor(rung + 1e-3f) + 1 : std::ceil(rung - 1e-3f) - 1;
return std::clamp(std::exp2(rung * .5f), zoom_min, zoom_max);
}
// the only invariant the pan has to uphold on its own; the far side is clamped by the scrollbars
point clamp_pan(point p) { return {std::max(0, p.x), std::max(0, p.y)}; }
// 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 || alloc > 2'000'000'000) // empty (or unparsed), or more than we are willing to allocate
{
(message("Unusable image size", msgbox::icon_error, msgbox::ok)
<< "parsed width:" << pfm.w << " and height:" << pfm.h << " would need " << alloc << " bytes")();
throw std::runtime_error("input data problem");
}
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.
// The eight ispc kernels are a cube indexed by (tone, gamma, half): tabulate it instead of nesting
// ifs. They share one calling convention, only the element type behind `vin` differs.
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
using kernel = void (*)(void*, int8_t*, int32_t, float);
static kernel const cube[2][2][2] = // [tone][gamma][half]
{
{{(kernel)ispc::ToSignedRgbAllF32Pixels, (kernel)ispc::ToSignedRgbAllF16Pixels},
{(kernel)ispc::GammaAllF32Pixels, (kernel)ispc::GammaAllF16Pixels}},
{{(kernel)ispc::ToneAllF32Pixels, (kernel)ispc::ToneAllF16Pixels},
{(kernel)ispc::ToneAllF32PixelsAndToGamma, (kernel)ispc::ToneAllF16PixelsAndToGamma}}
};
cube[state.tone][state.gamma][pfm.is_half()]((void*)raw.data(), rgb.data(),
(int32_t)pfm.num_elems(), state.exposure);
}
// transfer signed-byte RGB image vector to a GUI-compatible surface.
// paint::graphics::set_pixel goes down to one GDI call per pixel, which costs more than the whole
// tone mapping for a single scanline. Instead we fill a pixel_buffer (a plain 32bits BGRA bitmap in
// system memory) with SIMD, and hand the result to GDI in one blit.
// The buffer is viewport sized, not image sized: zoom and pan are resolved here, so the cost is
// bound by the window rather than by the image, and panning never has to touch the tone mapper.
void rgb_to_pixbuf(pfm_header const& pfm, vector<int8_t> const& rgb,
paint::pixel_buffer& pixbuf, view_state const& view, bool flipy)
{
int const nchan = pfm.num_channels();
int const dstw = (int)pixbuf.size().width, dsth = (int)pixbuf.size().height;
point const o = view.origin(pixbuf.size(), pfm.dims());
// a display row is a source row read forward or backward, so flipping is just a negative stride
int const stride = (flipy ? -1 : 1) * pfm.w * nchan;
int8_t* const src = (int8_t*)rgb.data() + (flipy ? (size_t)(pfm.h - 1) * pfm.w * nchan : 0);
auto row = [&](int y) { return &pixbuf.raw_ptr(y)->value; }; // pixel_color_t is a BGRA union
// rows are independent, these loops could be parallelized if ever needed
if (view.zoom == 1.f) // the default view: no resampling, so stay on the contiguous (gather free) packers
{
auto const pack = nchan == 3 ? ispc::PackRgbRowToBgra : ispc::PackMonoRowToBgra;
int const dx = std::max(0, o.x), ix = dx - o.x; // left margin, and first source column
int const cnt = std::max(0, std::min(dstw - dx, pfm.w - ix)); // columns actually covered by the image
for (int y = 0; y < dsth; ++y)
{
int const iy = y - o.y;
int const n = (unsigned)iy < (unsigned)pfm.h ? cnt : 0; // rows off the image are pure backdrop
std::fill(row(y), row(y) + (n ? dx : dstw), backdrop);
if (!n) continue;
pack(src + (ptrdiff_t)iy * stride + (ptrdiff_t)ix * nchan, row(y) + dx, n);
std::fill(row(y) + dx + n, row(y) + dstw, backdrop);
}
return;
}
float const step = 1.f / view.zoom; // source pixels per screen pixel
// zoomed out we'd drop most of the image on the floor: box-average the footprint instead
int const taps = std::clamp((int)std::ceil(step), 1, 4);
float const tapstep = step / taps;
// source coordinate of the first tap of destination pixel (0,0)
float const srcx0 = -o.x * step + tapstep * .5f, srcy0 = -o.y * step + tapstep * .5f;
for (int y = 0; y < dsth; ++y)
ispc::PackRowToBgraZoom(src, stride, nchan, pfm.w, pfm.h, row(y), dstw,
srcx0, srcy0 + y * step, step, tapstep, taps, backdrop);
}
// extract statistics from HDR image
std::pair<float, float> min_max(pfm_header const& pfm, vector<char> const& raw)
{
using kernel = void (*)(void*, int32_t, float&, float&);
kernel const k = pfm.is_half() ? (kernel)ispc::GetMinMaxF16 : (kernel)ispc::GetMinMaxF32;
float mi, ma;
k((void*)raw.data(), (int32_t)pfm.num_elems(), mi, ma);
return {mi, ma};
}
// leightweight process control. C++20 atomic wait/notify does the whole job: one counter,
// bumped per request, that the worker sleeps on until it differs from what it last saw.
struct lwpctl
{
static constexpr unsigned quit_token = ~0u; // 4 billion slider moves away from a legitimate value
std::atomic<unsigned> gen{0};
bool wait(unsigned& seen) // blocks until there is work; false means "shut down"
{
gen.wait(seen);
return (seen = gen.load()) != quit_token;
}
void trigger_recompute() { ++gen; gen.notify_one(); }
void set_quit() { gen = quit_token; gen.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;
view_state view;
raw_to_rgb(pfm, raw, rgb, state);
auto [rangemin, rangemax] = min_max(pfm, raw);
paint::pixel_buffer pixbuf; // viewport sized, (re)opened by the paint callback below
// 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};
place l2{panelZone};
l2.div("<vert <<sub><scrollV weight=16>> <scrollH weight=16>>");
l2["sub"] << pic;
l2["scrollV"] << scrollV;
l2["scrollH"] << scrollH;
l2.collocate();
// the scrollbars work in screen pixels of the zoomed image, so their geometry has to be
// recomputed whenever the zoom or the viewport changes. they also hold the authoritative pan.
auto sync_view = [&]()
{
nana::size const vp = pic.size(), img = pfm.dims();
if (vp.empty()) return; // not laid out yet
auto axis = [z = view.zoom](scroll_interface& bar, unsigned page, unsigned len, int& off)
{
bar.range(page);
bar.amount((size_t)std::max<float>((float)page, len * z));
bar.value(off); // clamped by the widget against amount - range
off = (int)bar.value(); // ... so read the pan back from it
};
axis(scrollH, vp.width, img.width, view.pan.x);
axis(scrollV, vp.height, img.height, view.pan.y);
};
pic.events().resized([&]() { sync_view(); });
drawing dr{pic};
dr.draw([&](paint::graphics& a_g)
{
if (a_g.size() != pixbuf.size())
pixbuf.open(a_g.size().width, a_g.size().height);
rgb_to_pixbuf(pfm, rgb, pixbuf, view, state.flipy);
pixbuf.paste(a_g.handle(), {0, 0});
});
scrollH.events().value_changed([&]() { view.pan.x = (int)scrollH.value(); API::refresh_window(pic); });
scrollV.events().value_changed([&]() { view.pan.y = (int)scrollV.value(); API::refresh_window(pic); });
// click-drag panning: grab the image and push it around, capture keeps it going outside the widget
point dragfrom, dragpan;
bool dragging = false;
pic.events().mouse_down([&](arg_mouse const& arg)
{
if (!(dragging = arg.left_button)) return;
dragfrom = arg.pos;
dragpan = view.pan;
pic.set_capture(true);
pic.cursor(cursor::hand);
});
pic.events().mouse_move([&](arg_mouse const& arg)
{
if (!dragging) return;
view.pan = clamp_pan(dragpan - (arg.pos - dragfrom));
sync_view();
API::refresh_window(pic);
});
pic.events().mouse_up([&](arg_mouse const&)
{
if (!dragging) return;
dragging = false;
pic.release_capture();
pic.cursor(cursor::arrow);
});
// 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();
// zoom zone:
panel<false> zoomctrls{mainwd};
place zoomgrid{zoomctrls};
label zoom_lbl{zoomctrls};
button zoom_out{zoomctrls}, zoom_in{zoomctrls}, zoom_11{zoomctrls}, zoom_fit{zoomctrls};
zoomgrid.div("<zg gap=2 arrange=[variable,22,22,32,32]>");
zoomgrid["zg"] << zoom_lbl;
auto refresh_zoom_lbl = [&]() { zoom_lbl.caption(std::to_string(std::lround(view.zoom * 100)) + "%"); };
auto viewport_center = [&]() { auto vp = pic.size(); return point{(int)vp.width / 2, (int)vp.height / 2}; };
// change zoom while pinning the source pixel currently under `at` (viewport coordinates)
auto zoom_about = [&](float newzoom, point at)
{
point const o = view.origin(pic.size(), pfm.dims());
float const sx = (at.x - o.x) / view.zoom, sy = (at.y - o.y) / view.zoom; // source pixel under `at`
view.zoom = std::clamp(newzoom, zoom_min, zoom_max);
view.pan = clamp_pan({(int)std::lround(sx * view.zoom) - at.x, (int)std::lround(sy * view.zoom) - at.y});
sync_view();
refresh_zoom_lbl();
API::refresh_window(pic);
};
// the four buttons differ only in caption and in how they pick a zoom, all about the middle of the view
auto zoom_button = [&](button& b, char const* caption, auto pick)
{
b.caption(caption);
b.events().click([&, pick]() { zoom_about(pick(pic.size()), viewport_center()); });
zoomgrid["zg"] << b;
};
zoom_button(zoom_out, "-", [&](nana::size) { return zoom_notch(view.zoom, -1); });
zoom_button(zoom_in, "+", [&](nana::size) { return zoom_notch(view.zoom, +1); });
zoom_button(zoom_11, "1:1", [ ](nana::size) { return 1.f; });
zoom_button(zoom_fit, "fit", [&](nana::size vp) { return std::min(vp.width / (float)pfm.w, vp.height / (float)pfm.h); });
zoomgrid.collocate();
// wheel zooms around the cursor, which is the one gesture that makes deep zoom usable
pic.events().mouse_wheel([&](arg_wheel const& arg)
{
float z = view.zoom;
for (unsigned n = std::max(1u, arg.distance / 120); n--; )
z = zoom_notch(z, arg.upwards ? +1 : -1);
zoom_about(z, arg.pos);
});
label activity{mainwd};
lwpctl pc;
// we need a thread because retoning a big image isn't instantaneous
auto image_recomputer = [&]()
{
for (unsigned seen = 0; pc.wait(seen); )
{
activity.caption("CPU activity: compute...");
raw_to_rgb(pfm, raw, rgb, state); // the viewport transfer itself happens in the paint callback
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,26,24,24]>");
layout["picdisplay"] << panelZone;
layout["controls"] << opts_gp << ctrls << curexp_lbl << zoomctrls << info << activity;
layout.collocate();
sync_view();
refresh_zoom_lbl();
mainwd.show();
exec();
// stop the refresher thread otherwise we get an assert in the CRT
pc.set_quit();
worker.join();
return 0;
}