-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.h
2731 lines (2228 loc) · 94.5 KB
/
environment.h
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/************************************************************************/
/* */
/* envutil - utility to convert between environment formats */
/* */
/* Copyright 2024 by Kay F. Jahnke */
/* */
/* The git repository for this software is at */
/* */
/* https://github.com/kfjahnke/envutil */
/* */
/* Please direct questions, bug reports, and contributions to */
/* */
/* [email protected] */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#include <filesystem>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/texture.h>
// some versions of OIIO yield a plain pointer, some a shared_ptr.
typedef decltype ( OIIO::TextureSystem::create() ) ts_ptr_t ;
#include "zimt/prefilter.h"
#include "zimt/bspline.h"
#include "zimt/eval.h"
#include "metrics.h"
#include "twining.h"
#include "geometry.h"
#if defined(ENVUTIL_ENVIRONMENT_H) == defined(HWY_TARGET_TOGGLE)
#ifdef ENVUTIL_ENVIRONMENT_H
#undef ENVUTIL_ENVIRONMENT_H
#else
#define ENVUTIL_ENVIRONMENT_H
#endif
HWY_BEFORE_NAMESPACE() ;
BEGIN_ZIMT_SIMD_NAMESPACE(project)
using OIIO::ImageInput ;
using OIIO::TypeDesc ;
using OIIO::ImageSpec ;
bool verbose = true ;
// This functor 'looks at' a full spherical image. It receives
// 2D lat/lon coordinates and yields pixel values. Pick-up is done
// with bilinear interpolation. For this demo program, we keep it
// simple, so this is a stripped-down version of what's used in
// envutil - we omit using OIIO's 'environment' function and
// also the use of 'twining'.
template < std::size_t nchannels >
struct eval_latlon
: public zimt::unary_functor
< v2_t , zimt::xel_t < float , nchannels > , LANES >
{
typedef zimt::xel_t < float , nchannels > px_t ;
typedef zimt::simdized_type < px_t , LANES > px_v ;
// latlon contains a view to an image in 2:1 aspect ratio in
// spherical projection.
const zimt::view_t < 2 , px_t > & latlon ;
// scaling factor to move from model space coordinates to
// image coordinates
const float scale ;
eval_latlon ( const zimt::view_t < 2 , px_t > & _latlon )
: latlon ( _latlon ) ,
scale ( _latlon.shape[1] / M_PI )
{ }
// direct lookup from the lat/lon image with bilinear interpolation.
// we expect incoming coordinates which are outside the range of
// the lat/lon image to be 'close' to the range and avoid the
// calculations which would be required to accept completely
// arbitrary coordinates (this would require a divison)
// The same applies to neighbouring pixels needed for bilinear
// interpolation. The special geometry of a full spherical is
// honoured: periodicity in the horizontal and periodicity with
// a longitute jump of pi over the poles.
template < typename I , typename O >
void eval ( const I & _in , O & out )
{
// we have incoming model space coordinates, in[0] is the
// longitude in the range of [-pi,pi] and in[1] is the
// latitude in the range of [-pi/2,pi/2]. First we move
// to image coordinates.
const zimt::xel_t < float , 2 > shift { M_PI , M_PI_2 } ;
auto in = ( _in + shift ) * scale ;
// if the coordinate is now precisely zero, this corresponds
// to a pick-up point at the top or left margin of the UL
// pixel, which is 0.5 away from it's center
in -= .5f ;
// now we move to discrete values for the index calculations
// the nearest discrete coordinate with components smaller
// than or equal to 'in' is found by applying 'floor'. We
// store the result in 'uli' for 'upper left index'.
v2i_v uli { floor ( in[0] ) , floor ( in[1] ) } ;
// the distance of this coordinate, both in horizontal and
// vertical direction, is stored in 'wr' ('weight right'),
// and it will be used to weight the right-hand part of the
// constituents (ur and lr)
auto wr = in - uli ;
// 'wl' ('weight left') is used for the opposite constituents,
// namely ul and ll.
auto wl = 1.0f - wr ;
// from the discrete upper left value, we derive it's three
// neighbours downwards and to the right.
v2i_v uri ( uli ) ;
uri[0] += 1 ;
v2i_v lli ( uli ) ;
lli[1] += 1 ;
v2i_v lri ( lli ) ;
lri[0] += 1 ;
// shorthand for width and height
int w = latlon.shape[0] ;
int h = latlon.shape[1] ;
// first we look at the vertical axis and map excessive values
// back into the range. Note how this isn't as straightforward
// as handling the horizontal: The continuation is on the
// opposite hemisphere (add w/2 to the horizontal component)
// then mirror on the pole. Note also that this won't work with
// completely arbitrary coordinates, which would be more expensive
// mathematically and isn't needed in this context.
uli[0] ( uli[1] < 0 ) += w / 2 ;
uli[1] ( uli[1] < 0 ) = 1 - uli[1] ; // e.g. -1 -> 0, opposite
uri[0] ( uri[1] < 0 ) += w / 2 ;
uri[1] ( uri[1] < 0 ) = 1 - uri[1] ; // e.g. -1 -> 0, opposite
lli[0] ( lli[1] >= h ) += w / 2 ;
lli[1] ( lli[1] >= h ) = ( h - 1 ) - ( lli[1] - h ) ;
lri[0] ( lri[1] >= h ) += w / 2 ;
lri[1] ( lri[1] >= h ) = ( h - 1 ) - ( lri[1] - h ) ;
// now we look at the horizontal axis - the longitude axis -
// and map any coordinates which are outside the range back in,
// exploiting the periodicity. Note that the code for the vertical
// may have put values way outside the range (by adding w/2), but
// not so far as that they wouldn't be mapped back into the range
// now. We don't expect uri and lri to ever have negative values.
uli[0] ( uli[0] < 0 ) += w ;
lli[0] ( lli[0] < 0 ) += w ;
uli[0] ( uli[0] >= w ) -= w ;
uri[0] ( uri[0] >= w ) -= w ;
lli[0] ( lli[0] >= w ) -= w ;
lri[0] ( lri[0] >= w ) -= w ;
// base pointer for the gather operation
const auto * const p = (const float* const) ( latlon.data() ) ;
// problems on my mac: vectorized long doesn't work
zimt::xel_t < int , 2 > llstrides ( latlon.strides ) ;
int nch = nchannels ;
// obtain the four constituents by first truncating their
// coordinate to int and then gathering from p.
index_v idsdxl { uli[0] , uli[1] } ;
auto ofs = ( idsdxl * llstrides ) . sum() * nch ;
px_v pxul ;
pxul.gather ( p , ofs ) ;
index_v idsdxr { uri[0] , uri[1] } ;
ofs = ( idsdxr * llstrides ) . sum() * nch ;
px_v pxur ;
pxur.gather ( p , ofs ) ;
index_v idxll { lli[0] , lli[1] } ;
ofs = ( idxll * llstrides ) . sum() * nch ;
px_v pxll ;
pxll.gather ( p , ofs ) ;
index_v idxlr { lri[0] , lri[1] } ;
ofs = ( idxlr * llstrides ) . sum() * nch ;
px_v pxlr ;
pxlr.gather ( p , ofs ) ;
// apply the bilinear formula with the weights gleaned above
out = wl[1] * ( wl[0] * pxul + wr[0] * pxur ) ;
out += wr[1] * ( wl[0] * pxll + wr[0] * pxlr ) ;
}
} ;
// some helper code to pass OIIO texture option parameters as
// strings from the command line
std::map < std::string , OIIO::TextureOpt::Wrap >
wrap_map
{
{ "WrapDefault" , OIIO::TextureOpt::WrapDefault } ,
{ "WrapBlack" , OIIO::TextureOpt::WrapBlack } ,
{ "WrapClamp" , OIIO::TextureOpt::WrapClamp } ,
{ "WrapPeriodic" , OIIO::TextureOpt::WrapPeriodic } ,
{ "WrapMirror" , OIIO::TextureOpt::WrapMirror } ,
{ "WrapPeriodicPow2" , OIIO::TextureOpt::WrapPeriodicPow2 } ,
{ "WrapPeriodicSharedBorder" ,
OIIO::TextureOpt::WrapPeriodicSharedBorder }
} ;
std::map < std::string , OIIO::TextureOpt::MipMode >
mipmode_map
{
{ "MipModeDefault" , OIIO::TextureOpt::MipModeDefault } ,
{ "MipModeNoMIP" , OIIO::TextureOpt::MipModeNoMIP } ,
{ "MipModeOneLevel" , OIIO::TextureOpt::MipModeOneLevel } ,
{ "MipModeTrilinear" , OIIO::TextureOpt::MipModeTrilinear } ,
{ "MipModeAniso" , OIIO::TextureOpt::MipModeAniso } ,
// { "MipModeStochasticTrilinear" , OIIO::TextureOpt::MipModeStochasticTrilinear } ,
// { "MipModeStochasticAniso" , OIIO::TextureOpt::MipModeStochasticAniso }
} ;
std::map < std::string , OIIO::TextureOpt::InterpMode >
interpmode_map
{
{ "InterpClosest" , OIIO::TextureOpt::InterpClosest } ,
{ "InterpBilinear" , OIIO::TextureOpt::InterpBilinear } ,
{ "InterpBicubic" , OIIO::TextureOpt::InterpBicubic } ,
{ "InterpSmartBicubic" , OIIO::TextureOpt::InterpSmartBicubic }
} ;
template < typename T , typename U >
void cast_assign ( T& trg , const U& src )
{
trg = T ( src ) ;
}
template < std::size_t nchannels >
struct eval_env
: public zimt::unary_functor
< zimt::xel_t < float , 9 > ,
zimt::xel_t < float , nchannels > ,
LANES >
{
ts_ptr_t ts ;
OIIO::TextureOptBatch batch_options ;
OIIO::TextureSystem::TextureHandle * th ;
// pull in the c'tor arguments
eval_env()
{
ts = OIIO::TextureSystem::create() ;
ts->attribute ( "options" , args.tsoptions ) ;
// transfer all OIIO-related options from the arguments. This might
// be factored out (the same code is also used for cubemap processing
// via an OIIO texture) - but one might consider using different
// options for the two processes, so for now I just copy and paste.
for ( int i = 0 ; i < 16 ; i++ )
{
cast_assign ( batch_options.swidth[i] , args.stwidth ) ;
cast_assign ( batch_options.twidth[i] , args.stwidth ) ;
cast_assign ( batch_options.sblur[i] , args.stblur ) ;
cast_assign ( batch_options.tblur[i] , args.stblur ) ;
}
cast_assign ( batch_options.conservative_filter ,
args.conservative_filter ) ;
auto wrap_it = wrap_map.find ( args.swrap ) ;
assert ( wrap_it != wrap_map.end() ) ;
cast_assign ( batch_options.swrap , wrap_it->second ) ;
wrap_it = wrap_map.find ( args.twrap ) ;
assert ( wrap_it != wrap_map.end() ) ;
cast_assign ( batch_options.twrap , wrap_it->second ) ;
auto mip_it = mipmode_map.find ( args.mip ) ;
assert ( mip_it != mipmode_map.end() ) ;
cast_assign ( batch_options.mipmode , mip_it->second ) ;
auto interp_it = interpmode_map.find ( args.interp ) ;
assert ( interp_it != interpmode_map.end() ) ;
cast_assign ( batch_options.interpmode , interp_it->second ) ;
OIIO::ustring uenvironment ( args.input , 0 ) ;
th = ts->get_texture_handle ( uenvironment ) ;
}
// set up the eval function.
template < typename I , typename O >
void eval ( const I & crd9 , O & px )
{
// we convert to OIIO-compatible coordinates as we go, this
// requires changing the sign of the x and y axis (hence the
// seemingly wrong order of the differences for ds[0], ds[1],
// dt[0] and dt[1]). This is the only place where we need to
// do this in 'extract', because only here we are feeding 3D
// ray coordinates directly to OIIO code. OIIO's axis convention
// is the same as Imath's. They have the positive x axis pointing
// left and the positive y axis pointing down, whereas lux
// convention, which I use in the remainder of the program, has
// the positive x axis pointing right and the positive y axis
// pointing down ('latin book order'). Both systems have the
// positive z axis pointing forward.
crd3_v c3 { - crd9[0] , // note the sign change to move to
- crd9[1] , // OIIO-compatible 3D ray coordinates
crd9[2] } ;
crd3_v ds { crd9[0] - crd9[3] , // sic
crd9[1] - crd9[4] , // sic
crd9[5] - crd9[2] } ;
crd3_v dt { crd9[0] - crd9[6] , // sic
crd9[1] - crd9[7] , // sic
crd9[8] - crd9[2] } ;
// now we can call 'environment', but depending on the SIMD
// back-end, we provide the pointers which 'environment' needs
// in different ways. The first form would in fact work for all
// back-ends, but the second form is more concise. Note that,
// as of this writing, the OIIO code accepts the batched arguments
// but then proceeds to loop over them with single-point lookups,
// which kind of defeats the purpose of a SIMDized pipeline. But
// 'on this side' we're doing 'proper SIMD', and hope that OIIO
// will also eventually provide it.
#if defined USE_VC or defined USE_STDSIMD
// to interface with zimt's Vc and std::simd backends, we need to
// extract the data from the SIMDized objects and re-package the
// ouptut as a SIMDized object. The compiler will likely optimize
// this away and work the entire operation in registers, so let's
// call this a 'semantic manoevre'.
float scratch [ 4 * nchannels * LANES ] ;
c3.store ( scratch ) ;
ds.store ( scratch + nchannels * LANES ) ;
dt.store ( scratch + nchannels * LANES ) ;
ts->environment ( th , nullptr, batch_options ,
OIIO::Tex::RunMaskOn ,
scratch ,
scratch + nchannels * LANES ,
scratch + 2 * nchannels * LANES ,
nchannels ,
scratch + 3 * nchannels * LANES ) ;
px.load ( scratch + 3 * nchannels * LANES ) ;
#else
// the highway and zimt's own backend have an internal representation
// as a C vector of fundamentals, so we van use data() on them, making
// the code even simpler - though the code above would work just the
// same.
ts->environment ( th , nullptr, batch_options ,
OIIO::Tex::RunMaskOn ,
c3[0].data() ,
ds[0].data() ,
dt[0].data() ,
nchannels ,
px[0].data() ) ;
#endif
// and that's us done! the 'environment' function has returned pixel
// values, which have been passed as result to the zimt::transform
// process invoking this functor.
}
} ;
// functor to convert between pixels with different channel count.
// currently the only case occuring in this program is the very first
// one: the output will be the same as the input and the code is
// optimized away. This object is not well-tested. currently unused.
/*
template < typename T , std::size_t A , std::size_t B , std::size_t L >
struct repix
: public zimt::unary_functor < zimt::xel_t < T , A > ,
zimt::xel_t < T , B > ,
L >
{
typedef zimt::unary_functor < zimt::xel_t < T , A > ,
zimt::xel_t < T , B > ,
L >
base_t ;
using typename base_t::in_v ;
using typename base_t::out_v ;
void eval ( const in_v & in , out_v & out )
{
if constexpr ( A == B )
{
out = in ;
}
else if constexpr ( A == 1 )
{
out = in[0] ;
if constexpr ( B == 4 )
out[3] = 1.0 ;
}
else if constexpr ( B == 1 )
{
if constexpr ( A < 4 )
out = in.sum() / float ( A ) ;
else
{
out[0] = in[0] / in[4] ;
out[0] += in[1] / in[4] ;
out[0] += in[2] / in[4] ;
out[0] /= 3.0f ;
out[0] ( in[4] == 0 ) = 0 ;
}
}
else if constexpr ( A == 4 && B == 3 )
{
out[0] = in[0] ;
out[1] = in[1] ;
out[2] = in[2] ;
// TODO: should be (associated alpha)
// out[0] = in[0] / in[4] ;
// out[1] = in[1] / in[4] ;
// out[2] = in[2] / in[4] ;
// out[0] ( in[4] == 0 ) = 0 ;
// out[1] ( in[4] == 0 ) = 0 ;
// out[2] ( in[4] == 0 ) = 0 ;
}
else if constexpr ( A == 3 && B == 4 )
{
out[0] = in[0] ;
out[1] = in[1] ;
out[2] = in[2] ;
out[4] = 1 ;
}
}
} ;
*/
// sixfold_t provides an internal representation of a cubemap
// with widened support, to provide for easy mip-mapping and
// interpolation.
template < std::size_t nchannels , projection_t cbm_prj >
struct sixfold_t
: public metrics_t
{
// shorthand for pixels and SIMDized pixels
typedef zimt::xel_t < float , 2 > crd2_t ;
typedef zimt::xel_t < float , nchannels > px_t ;
typedef zimt::simdized_type < px_t , LANES > px_v ;
// pointers to an OIIO texture system and an OIIO texture handle.
// These are only used if the pick-up is done using OIIO's
// 'texture' function.
std::filesystem::path texture_file ;
ts_ptr_t ts ;
OIIO::TextureSystem::TextureHandle * th ;
// This array holds all the image data. I'll refer to this
// array as the 'IR image': the internal representation.
// The array's size is gleaned from the base class metrics_t,
// which is initialized first, so we can already use the
// members we inherit from it (here: section_px, the width
// of the IR image).
zimt::array_t < 2 , px_t > store ;
// pointer to the upper left corner of the topmost cubeface
// image inside the 'store' array
px_t * p_ul ;
typedef zimt::bspline < px_t , 2 > spl_t ;
std::shared_ptr < spl_t > p_bsp ;
zimt::grok_type < crd2_t , px_t , LANES > bsp_ev ;
sixfold_t ( std::size_t _face_px ,
double _face_fov = M_PI_2 ,
std::size_t _support_min_px = 4UL ,
std::size_t _tile_px = 64UL )
: metrics_t ( _face_px ,
_face_fov ,
_support_min_px ,
_tile_px ) ,
store ( { section_px , 6 * section_px } )
{
// let the user know the field of view of IR sections. This
// is only possible if the cube face images have even size,
// otherwise the cube face image's center can't coincide
// with a section's center - unless the section is also
// odd-sized, which only occurs when the tile size is one.
if ( verbose )
{
if ( left_frame_px != right_frame_px )
std::cout << "cube face is not centered in IR" << std::endl ;
else
std::cout << "IR sections have "
<< atan ( section_md / 2.0 ) * 360.0 / M_PI
<< " degrees fov" << std::endl ;
}
// find the location of the first cube face's upper left corner
// in the 'store' array
p_ul = store.data() ;
p_ul += ( left_frame_px * store.strides ) . sum() ;
auto * ps = new spl_t ( store , store , args.spline_degree ,
{ zimt::REFLECT , zimt::REFLECT } ,
-1 , left_frame_px ) ;
p_bsp.reset ( ps ) ;
bsp_ev = zimt::make_evaluator < spl_t , float , LANES > ( *p_bsp ) ;
}
// function to read the cube face image data from disk (via
// an OIIO-provided inp) - this version reads a single image
// with 1:6 aspect ratio containing six square cube face
// images, concatenated vertically, in openEXR order (left,
// right, top, bottom, front, back) and orientation (The top
// and bottom images are oriented so that they align vertically
// with the 'back' image)
// we can load cube maps with arbitrary field of view (as long
// as the field of view is at least ninety degrees). 'Normal'
// cubemaps will hold cube face images with precisely ninety
// degrees field of view, measured either center-to-center
// or edge-to-edge (see 'ctc'), but the scope of the 'load'
// functions is wider - the face_fov argument determines the
// precise extent.
// The six cube face images are separated and each one is
// stored in the corresponding section - right in the center
// for even cube face sizes, and as central as possible for
// odd cube face sizes - so the data are unmodified, but
// shifted to their place in the IR image. After the load,
// the frame of support is filled with interpolated values.
void load ( const std::unique_ptr<ImageInput> & inp )
{
assert ( inp != nullptr ) ;
const ImageSpec &spec = inp->spec() ;
int xres = spec.width ;
int yres = spec.height ;
// the calling code should already have looked at the image and
// gleaned the face width, but here we check again:
assert ( xres == face_px ) ;
assert ( yres == 6 * face_px ) ;
// read the six cube face images from the 1:6 stripe into the
// appropriate slots in the sixfold_t object's 'store' array.
if ( inp->supports ( "scanlines" ) )
{
if ( verbose )
{
std::cout << "input supports scanline-based access"
<< std::endl ;
}
// if the input is scanline-based, we copy batches of
// scanlines into the cube face slots in the store
for ( int face = 0 ; face < 6 ; face++ )
{
auto * p_trg = p_ul + face * offset_px ;
// for reference: OIIO's read_scanlines' signature
// virtual bool read_scanlines ( int subimage, int miplevel,
// int ybegin, int yend,
// int z, int chbegin, int chend,
// TypeDesc format, void *data,
// stride_t xstride = AutoStride,
// stride_t ystride = AutoStride)
// note how we read face_px scanlines in one go, using
// appropriate strides to place the image data inside the
// larger 'store' array, converting to float as we go along.
// The channels are capped at nchannels. We ask OIIO to
// provide float data.
// TODO: read_scanlines doesn't work with tile-based files
auto success =
inp->read_scanlines ( 0 , 0 ,
face * face_px , (face+1) * face_px ,
0 , 0 , nchannels ,
TypeDesc::FLOAT , p_trg ,
nchannels * 4 ,
nchannels * 4 * store.strides[1] ) ;
assert ( success ) ;
}
}
else
{
if ( verbose )
{
std::cout << "input is tiled" << std::endl ;
}
// if the input is not scanline-based, we read the entire image
// into a buffer, then copy the cube faces to the store. We can
// use a 3D array as a target, with the six cube faces 'on
// top of each other' populating the third spatial dimension.
// We need a large-ish amount of memory temporarily, but it's
// easier that way - if memory were an issue we'd have to work
// through the tiles and split them up to separate cube faces
// if the cube face images' size is not a multiple of the
// tile size.
zimt::array_t < 3 , px_t >
buffer ( { face_px , face_px , std::size_t ( 6 ) } ) ;
// and a view to the store with the same shape, but strides to
// match the metrics of the target memory area in the store
zimt::view_t < 3 , px_t >
target ( p_ul ,
{ 1L , long(section_px) , long(offset_px) } ,
{ face_px , face_px , std::size_t ( 6 ) } ) ;
// read the image data into the buffer
inp->read_image ( 0 , 0 , 0 , nchannels ,
TypeDesc::FLOAT ,
buffer.data() ) ;
// zimt handles the data transfer from the buffer to the view
target.copy_data ( buffer ) ;
}
}
// load six separate cube face images. It's assumed that all
// images exist and have the same geometry. This is essentially
// the same as the function above, but the code is simplified
// to always read an entire cube face image in one go.
void load ( const std::vector < std::string > & filename6 )
{
// make sure there are six file names
assert ( filename6.size() == 6 ) ;
// set up a buffer for a single cube face image
zimt::array_t < 2 , px_t >
buffer ( { face_px , face_px } ) ;
// read the six cube face images into the appropriate slots in
// the sixfold_t object's 'store' array.
for ( std::size_t face = 0 ; face < 6 ; face++ )
{
auto inp = ImageInput::open ( filename6[face] ) ;
assert ( inp != nullptr ) ;
if ( verbose )
std::cout << "load cube face image " << filename6[face]
<< std::endl ;
const ImageSpec &spec = inp->spec() ;
std::size_t w = spec.width ;
std::size_t h = spec.height ;
assert ( w == h ) ;
assert ( w == face_px ) ;
inp->read_image ( 0 , 0 , 0 , nchannels ,
TypeDesc::FLOAT ,
p_ul + face * offset_px ,
store.strides[0] * nchannels * 4 ,
store.strides[1] * nchannels * 4 ) ;
inp->close() ;
}
}
// We can use the fall-back bilinear interpolation to pick up
// pixel values from the IR image, but to use OIIO's 'texture'
// function, we need access to the texture system and - for
// speed - the texture handle. But we don't have these data
// when the sixfold_t is created - the texture has to be
// generated first, then stored to disk and then fed to the
// texture system. So we can only call this function later:
void gen_texture ( const std::string & ts_options )
{
// to load the texture with OIIO's texture system code, it
// has to be in a file, so we store the IR image to a temporary
// file:
auto temp_path = std::filesystem::temp_directory_path() ;
texture_file = temp_path / "temp_texture.exr" ;
if ( verbose )
std::cout << "saving generated texture to "
<< texture_file.string() << std::endl ;
save_array ( texture_file.string() , store ) ;
// now we can create to the texture system and receive
// a texture handle for the temporary file for fast access
ts = OIIO::TextureSystem::create() ;
if ( ts_options != std::string() )
{
if ( verbose )
std::cout << "adding texture system options: " << ts_options
<< std::endl ;
ts->attribute ( "options" , ts_options ) ;
}
OIIO::ustring uenvironment ( texture_file.string() , 0 ) ;
th = ts->get_texture_handle ( uenvironment ) ;
}
// given the cube face and the in-face coordinate, extract the
// corresponding pixel values from the internal representation
// of the cubemap held in the sixfold_t object. We have two
// variants here, the first one using nearest neighbour
// interpolation, the second bilinear. The first one is currently
// unused. The pick-up is not guaranteed to look up pixel data
// strictly inside the 90-degree cube face 'proper' but may
// glean some information from the support frame, so this has
// to be present. Initially we provide a one-pixel-wide
// support frame of mirrored pixels (if necessary - if the
// incoming partial images have 'inherent support' because
// they span more than ninety degrees, this is not necessary)
// which is enough for bilinear interpolation. Once we have
// filled in the support frame, we can use interpolators with
// wider support.
// TODO: really, this member function could also be labeled
// 'const', because it does not modify anything. But the
// contained functor bsp_ev does not have a const eval.
void cubemap_to_pixel ( const i_v & face ,
const crd2_v & in_face ,
px_v & px )
{
crd2_v pickup ;
get_pickup_coordinate_px ( face , in_face , pickup ) ;
bsp_ev.eval ( pickup , px ) ;
}
// this is the equivalent function to 'cubemap_to_pixel', above,
// using OIIO's 'texture' function to perform the gleaning of
// pixel data from the IR image. The IR image is not accessed
// directly, but provided via OIIO's texture system.
// On top of the pick-up coordinate (coming in in texture
// units in [0,1], rather than pixel units which are used in
// 'cubemap_to_pixel') we have the four derivatives and the
// OIIO texture batch options.
void get_filtered_px ( const crd2_v & pickup ,
px_v & px ,
const f_v & dsdx ,
const f_v & dtdx ,
const f_v & dsdy ,
const f_v & dtdy ,
OIIO::TextureOptBatch batch_options ) const
{
assert ( all_of ( pickup[0] >= 0.0f ) ) ;
assert ( all_of ( pickup[0] <= 1.0f ) ) ;
assert ( all_of ( pickup[1] >= 0.0f ) ) ;
assert ( all_of ( pickup[1] <= 1.0f ) ) ;
// code to truncate the pickup coordinate to int and gather,
// after restoring the pickup to pixel units. Uncomment this
// code to directly pick up pixels from the IR image with NN
// interpolation - this is to verify that the pick-up coordinate
// is indeed correct.
// auto x = pickup[0] * float ( store.shape[0] ) ;
// auto y = pickup[1] * float ( store.shape[1] ) ;
// index_v idx { x , y } ;
// const auto ofs = ( idx * store.strides ) . sum() * nchannels ;
// const auto * p = (float*) ( store.data() ) ;
//
// px.gather ( p , ofs ) ;
// return ;
// OIIO's 'texture' signature is quite a mouthful:
// virtual bool texture ( TextureHandle *texture_handle,
// Perthread *thread_info,
// TextureOptBatch &options,
// Tex::RunMask mask,
// const float *s, const float *t,
// const float *dsdx, const float *dtdx,
// const float *dsdy, const float *dtdy,
// std::size_t nchannels,
// float *result,
// float *dresultds = nullptr,
// float *dresultdt = nullptr)
#if defined USE_VC or defined USE_STDSIMD
// to interface with zimt's Vc and std::simd backends, we need to
// extract the data from the SIMDized objects and re-package the
// ouptut as a SIMDized object. The compiler will likely optimize
// this away and work the entire operation in registers, so let's
// call this a 'semantic manoevre'.
float scratch [ 6 * LANES + nchannels * LANES ] ;
pickup.store ( scratch ) ; // stores 2 * LANES
dsdx.store ( scratch + 2 * LANES ) ;
dtdx.store ( scratch + 3 * LANES ) ;
dsdy.store ( scratch + 4 * LANES ) ;
dtdy.store ( scratch + 5 * LANES ) ;
bool result =
ts->texture ( th , nullptr , batch_options , OIIO::Tex::RunMaskOn ,
scratch , scratch + LANES ,
scratch + 2 * LANES , scratch + 3 * LANES ,
scratch + 4 * LANES , scratch + 5 * LANES ,
nchannels , scratch + 6 * LANES ) ;
assert ( result ) ;
px.load ( scratch + 6 * LANES ) ;
#else
// zimt's own and the highway backend have a representation as
// a C vector of fundamentals and provide a 'data' function
// to yield it's address. This simplifies matters, we can pass
// these pointers to OIIO directly.
bool result =
ts->texture ( th , nullptr , batch_options , OIIO::Tex::RunMaskOn ,
pickup[0].data() , pickup[1].data() ,
dsdx.data() , dtdx.data() ,
dsdy.data() , dtdy.data() ,
nchannels , (float*) ( px[0].data() ) ) ;
#endif
}
// variant taking derivatives of the in-face coordinate, which
// are approximated by calculating the difference to a canonical
// (target image) coordinate one sample step to the right (x)
// or below (y), respectively. The derivatives are in texture
// units aready, and we also convert the pickup coordinate to
// texture units.
void cubemap_to_pixel ( const i_v & face ,
crd2_v in_face ,
px_v & px ,
const f_v & dsdx ,
const f_v & dtdx ,
const f_v & dsdy ,
const f_v & dtdy ,
OIIO::TextureOptBatch & bo ) const
{
crd2_v pickup_tx ;
// obtain the pickup coordinate in texture units (in [0,1])
get_pickup_coordinate_tx ( face , in_face , pickup_tx ) ;
// use OIIO to get the pixel value
get_filtered_px ( pickup_tx , px , dsdx , dtdx , dsdy , dtdy , bo ) ;
}
// After the cube faces have been read from disk, they are surrounded
// by black (or even undefined) pixels. We want to provide minimal
// support, this support's quality is not crucial, but it should not
// be black, but rather like mirroring on the edge, which this function
// does - it produces a one-pixel-wide frame with mirrored pixels
// around each of the cube faces. In the next step, we want to fill
// in the support frame around the cube faces proper, and we may have
// to access image data close to the margin. Rather than implementing
// the mirroring on the edge by manipulating the coordinate of the
// pick-up (e.g. clamping it) having the one-pixel-wide minimal
// support allows us to do the next stage without looking at the
// coordinates: we can be sure that the pick-up will not exceed
// the support area.
void mirror_around()
{
auto * p_base = store.data() ;
for ( int face = 0 ; face < 6 ; face++ )
{
// get a pointer to the upper left of the cube face 'proper'
auto * p_frame = p_base
+ face * section_px * store.strides[1]
+ ( left_frame_px * store.strides ) .sum() ;
// get a zimt view to the current cube face
zimt::view_t < 2 , px_t > cubeface
( p_frame , store.strides , { face_px , face_px } ) ;
// we use 2D discrete coordinates
typedef zimt::xel_t < int , 2 > ix_t ;
// mirror the horizontal edges
for ( int x = -1 ; x <= int ( face_px ) ; x++ )
{
ix_t src { x , 0 } ;
ix_t trg { x , -1 } ;
cubeface [ trg ] = cubeface [ src ] ;
src [ 1 ] = face_px - 1 ;
trg [ 1 ] = face_px ;
cubeface [ trg ] = cubeface [ src ] ;
}
// and the vertical edges
for ( int y = -1 ; y <= int ( face_px ) ; y++ )
{
ix_t src { 0 , y } ;
ix_t trg { -1 , y } ;
cubeface [ trg ] = cubeface [ src ] ;
src [ 0 ] = face_px - 1 ;
trg [ 0 ] = face_px ;
cubeface [ trg ] = cubeface [ src ] ;
}
}
}
// We set up an internal functor which we'll use to fill the frame
// of support pixels. This functor is local to struct sixfold_t
// because it has no practical use outside of this context and
// is tailor-made for the purpose (the member function fill_support
// just below it)
// this functor is used to fill the frame of support pixels in the
// array in the sixfold_t object. incoming, we have 2D coordinates,
// which, for the purpose at hand, will lie outside the cube face.
// But we can still convert these image coordinates to planar
// coordinates in 'model space' and then further to 'pickup'
// coordinates into the array in the sixfold_t object. When we
// pick up data from the neighbouring cube faces, we produce
// support around the cube face proper, 'regenerating' what would