-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathmaketexture.cpp
More file actions
1993 lines (1763 loc) · 79.9 KB
/
maketexture.cpp
File metadata and controls
1993 lines (1763 loc) · 79.9 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
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
// Copyright Contributors to the OpenImageIO project.
// SPDX-License-Identifier: Apache-2.0
// https://github.com/AcademySoftwareFoundation/OpenImageIO
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <sstream>
#include <OpenImageIO/Imath.h>
#include <OpenImageIO/argparse.h>
#include <OpenImageIO/color.h>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/filter.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <OpenImageIO/imagebufalgo_util.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
#include <OpenImageIO/timer.h>
#include "imageio_pvt.h"
using namespace OIIO;
static spin_mutex maketx_mutex; // for anything that needs locking
static Filter2D*
setup_filter(const ImageSpec& dstspec, const ImageSpec& srcspec,
std::string filtername = std::string())
{
// Resize ratio
float wratio = float(dstspec.full_width) / float(srcspec.full_width);
float hratio = float(dstspec.full_height) / float(srcspec.full_height);
float w = std::max(1.0f, wratio);
float h = std::max(1.0f, hratio);
// Default filter, if none supplied
if (filtername.empty()) {
// No filter name supplied -- pick a good default
if (wratio > 1.0f || hratio > 1.0f)
filtername = "blackman-harris";
else
filtername = "lanczos3";
}
// Figure out the recommended filter width for the named filter
for (int i = 0, e = Filter2D::num_filters(); i < e; ++i) {
FilterDesc d;
Filter2D::get_filterdesc(i, &d);
if (filtername == d.name)
return Filter2D::create(filtername, w * d.width, h * d.width);
}
return NULL; // couldn't find a matching name
}
static TypeDesc
set_prman_options(TypeDesc out_dataformat, ImageSpec& configspec)
{
// Force separate planar image handling, and also emit prman metadata
configspec.attribute("planarconfig", "separate");
configspec.attribute("maketx:prman_metadata", 1);
// 8-bit : 64x64
if (out_dataformat == TypeDesc::UINT8 || out_dataformat == TypeDesc::INT8) {
configspec.tile_width = 64;
configspec.tile_height = 64;
}
// 16-bit : 64x32
// Force u16 -> s16
// In prman's txmake (last tested in 15.0)
// specifying -short creates a signed int representation
if (out_dataformat == TypeDesc::UINT16)
out_dataformat = TypeDesc::INT16;
if (out_dataformat == TypeDesc::INT16) {
configspec.tile_width = 64;
configspec.tile_height = 32;
}
// Float: 32x32
// In prman's txmake (last tested in 15.0)
// specifying -half or -float make 32x32 tile size
if (out_dataformat == TypeDesc::DOUBLE)
out_dataformat = TypeDesc::FLOAT;
if (out_dataformat == TypeDesc::HALF || out_dataformat == TypeDesc::FLOAT) {
configspec.tile_width = 32;
configspec.tile_height = 32;
}
return out_dataformat;
}
static TypeDesc
set_oiio_options(TypeDesc out_dataformat, ImageSpec& configspec)
{
// Interleaved channels are faster to read
configspec.attribute("planarconfig", "contig");
// Force fixed tile-size across the board
configspec.tile_width = 64;
configspec.tile_height = 64;
return out_dataformat;
}
static std::string
datestring(time_t t)
{
struct tm mytm;
Sysutil::get_local_time(&t, &mytm);
return Strutil::fmt::format("{:4d}:{:02d}:{:02d} {:02d}:{:02d}:{:02d}",
mytm.tm_year + 1900, mytm.tm_mon + 1,
mytm.tm_mday, mytm.tm_hour, mytm.tm_min,
mytm.tm_sec);
}
template<class SRCTYPE>
static void
interppixel_NDC_clamped(const ImageBuf& buf, float x, float y,
span<float> pixel, bool envlatlmode)
{
int fx = buf.spec().full_x;
int fy = buf.spec().full_y;
int fw = buf.spec().full_width;
int fh = buf.spec().full_height;
x = static_cast<float>(fx) + x * static_cast<float>(fw);
y = static_cast<float>(fy) + y * static_cast<float>(fh);
int n = buf.spec().nchannels;
float *p0 = OIIO_ALLOCA(float, 4 * n), *p1 = p0 + n, *p2 = p1 + n,
*p3 = p2 + n;
x -= 0.5f;
y -= 0.5f;
int xtexel, ytexel;
float xfrac, yfrac;
xfrac = floorfrac(x, &xtexel);
yfrac = floorfrac(y, &ytexel);
// Get the four texels
ImageBuf::ConstIterator<SRCTYPE> it(
buf, ROI(xtexel, xtexel + 2, ytexel, ytexel + 2), ImageBuf::WrapClamp);
for (int c = 0; c < n; ++c)
p0[c] = it[c];
++it;
for (int c = 0; c < n; ++c)
p1[c] = it[c];
++it;
for (int c = 0; c < n; ++c)
p2[c] = it[c];
++it;
for (int c = 0; c < n; ++c)
p3[c] = it[c];
if (envlatlmode) {
// For latlong environment maps, in order to conserve energy, we
// must weight the pixels by sin(t*PI) because pixels closer to
// the pole are actually less area on the sphere. Doing this
// wrong will tend to over-represent the high latitudes in
// low-res MIP levels. We fold the area weighting into our
// linear interpolation by adjusting yfrac.
int ynext = OIIO::clamp(ytexel + 1, buf.ymin(), buf.ymax());
ytexel = OIIO::clamp(ytexel, buf.ymin(), buf.ymax());
float w0 = (1.0f - yfrac)
* sinf((float)M_PI * (ytexel + 0.5f) / (float)fh);
float w1 = yfrac * sinf((float)M_PI * (ynext + 0.5f) / (float)fh);
yfrac = w1 / (w0 + w1);
}
// Bilinearly interpolate
bilerp(p0, p1, p2, p3, xfrac, yfrac, n, pixel.data());
}
// Resize src into dst, relying on the linear interpolation of
// interppixel_NDC_full or interppixel_NDC_clamped, for the pixel range.
template<class SRCTYPE>
static bool
resize_block_(ImageBuf& dst, const ImageBuf& src, ROI roi, bool envlatlmode)
{
int x0 = roi.xbegin, x1 = roi.xend, y0 = roi.ybegin, y1 = roi.yend;
const ImageSpec& srcspec(src.spec());
bool src_is_crop
= (srcspec.x > srcspec.full_x || srcspec.y > srcspec.full_y
|| srcspec.z > srcspec.full_z
|| srcspec.x + srcspec.width < srcspec.full_x + srcspec.full_width
|| srcspec.y + srcspec.height < srcspec.full_y + srcspec.full_height
|| srcspec.z + srcspec.depth < srcspec.full_z + srcspec.full_depth);
const ImageSpec& dstspec(dst.spec());
span<float> pel = OIIO_ALLOCA_SPAN(float, dstspec.nchannels);
float xoffset = (float)dstspec.full_x;
float yoffset = (float)dstspec.full_y;
float xscale = 1.0f / (float)dstspec.full_width;
float yscale = 1.0f / (float)dstspec.full_height;
int nchannels = dst.nchannels();
OIIO_DASSERT(dst.spec().format == TypeFloat);
ImageBuf::Iterator<float> d(dst, roi);
for (int y = y0; y < y1; ++y) {
float t = (y + 0.5f) * yscale + yoffset;
for (int x = x0; x < x1; ++x, ++d) {
float s = (x + 0.5f) * xscale + xoffset;
if (src_is_crop)
src.interppixel_NDC(s, t, pel);
else
interppixel_NDC_clamped<SRCTYPE>(src, s, t, pel, envlatlmode);
for (int c = 0; c < nchannels; ++c)
d[c] = pel[c];
}
}
return true;
}
// Helper function to compute the first bilerp pass into a scanline buffer
template<class SRCTYPE>
static void
halve_scanline(const SRCTYPE* s, const int nchannels, size_t sw, float* dst)
{
for (size_t i = 0; i < sw; i += 2, s += nchannels) {
for (int j = 0; j < nchannels; ++j, ++dst, ++s)
*dst = 0.5f * (float)(*s + *(s + nchannels));
}
}
// Bilinear resize performed as a 2-pass filter.
// Optimized to assume that the images are contiguous.
template<class SRCTYPE>
static bool
resize_block_2pass(ImageBuf& dst, const ImageBuf& src, ROI roi,
bool allow_shift)
{
// Two-pass filtering introduces a half-pixel shift for odd resolutions.
// Revert to correct bilerp sampling unless shift is explicitly allowed.
if (!allow_shift && (src.spec().width % 2 || src.spec().height % 2))
return resize_block_<SRCTYPE>(dst, src, roi, false);
OIIO_DASSERT(roi.ybegin + roi.height() <= dst.spec().height);
// Allocate two scanline buffers to hold the result of the first pass
const int nchannels = dst.nchannels();
const size_t row_elem = roi.width() * nchannels; // # floats in scanline
std::unique_ptr<float[]> S0(new float[row_elem]);
std::unique_ptr<float[]> S1(new float[row_elem]);
// We know that the buffers created for mipmapping are all contiguous,
// so we can skip the iterators for a bilerp resize entirely along with
// any NDC -> pixel math, and just directly traverse pixels.
const SRCTYPE* s = (const SRCTYPE*)src.localpixels();
SRCTYPE* d = (SRCTYPE*)dst.localpixels();
OIIO_DASSERT(s && d); // Assume contig bufs
d += roi.ybegin * dst.spec().width * nchannels; // Top of dst ROI
const size_t ystride = src.spec().width * nchannels; // Scanline offset
s += 2 * roi.ybegin * ystride; // Top of src ROI
// Run through destination rows, doing the two-pass bilerp filter
const size_t dw = roi.width(), dh = roi.height(); // Loop invariants
const size_t sw = dw * 2; // Handle odd res
for (size_t y = 0; y < dh; ++y) { // For each dst ROI row
halve_scanline<SRCTYPE>(s, nchannels, sw, &S0[0]);
s += ystride;
halve_scanline<SRCTYPE>(s, nchannels, sw, &S1[0]);
s += ystride;
const float *s0 = &S0[0], *s1 = &S1[0];
for (size_t x = 0; x < dw; ++x) { // For each dst ROI col
for (int i = 0; i < nchannels; ++i, ++s0, ++s1, ++d)
*d = (SRCTYPE)(0.5f * (*s0 + *s1)); // Average vertically
}
}
return true;
}
static bool
resize_block(ImageBuf& dst, const ImageBuf& src, ROI roi, bool envlatlmode,
bool allow_shift)
{
const ImageSpec& srcspec(src.spec());
const ImageSpec& dstspec(dst.spec());
OIIO_DASSERT(dstspec.nchannels == srcspec.nchannels);
OIIO_DASSERT(dst.localpixels());
bool ok;
if (src.localpixels() && // Not a cached image
!envlatlmode && // not latlong wrap mode
roi.xbegin == 0 && // Region x at origin
dstspec.width == roi.width() && // Full width ROI
dstspec.width == (srcspec.width / 2) && // Src is 2x resize
dstspec.format == srcspec.format && // Same formats
dstspec.x == 0 && dstspec.y == 0 && // Not a crop or overscan
srcspec.x == 0 && srcspec.y == 0) {
// If all these conditions are met, we have a special case that
// can be more highly optimized.
OIIO_DISPATCH_TYPES(ok, "resize_block_2pass", resize_block_2pass,
srcspec.format, dst, src, roi, allow_shift);
} else {
OIIO_ASSERT(dst.spec().format == TypeFloat);
OIIO_DISPATCH_TYPES(ok, "resize_block", resize_block_, srcspec.format,
dst, src, roi, envlatlmode);
}
return ok;
}
// Copy src into dst, but only for the range [x0,x1) x [y0,y1).
static void
check_nan_block(const ImageBuf& src, ROI roi, int& found_nonfinite)
{
int x0 = roi.xbegin, x1 = roi.xend, y0 = roi.ybegin, y1 = roi.yend;
const ImageSpec& spec(src.spec());
span<float> pel = OIIO_ALLOCA_SPAN(float, spec.nchannels);
for (int y = y0; y < y1; ++y) {
for (int x = x0; x < x1; ++x) {
src.getpixel(x, y, pel);
for (int c = 0; c < spec.nchannels; ++c) {
if (!isfinite(pel[c])) {
spin_lock lock(maketx_mutex);
// if (found_nonfinite < 3)
// std::cerr << "maketx ERROR: Found " << pel[c]
// << " at (x=" << x << ", y=" << y << ")\n";
++found_nonfinite;
break; // skip other channels, there's no point
}
}
}
}
}
inline Imath::V3f
latlong_to_dir(float s, float t, bool y_is_up = true)
{
float theta = 2.0f * M_PI * s;
float phi = t * M_PI;
float sinphi, cosphi;
sincos(phi, &sinphi, &cosphi);
if (y_is_up)
return Imath::V3f(sinphi * sinf(theta), cosphi, -sinphi * cosf(theta));
else
return Imath::V3f(-sinphi * cosf(theta), -sinphi * sinf(theta), cosphi);
}
template<class SRCTYPE>
static bool
lightprobe_to_envlatl(ImageBuf& dst, const ImageBuf& src, bool y_is_up,
ROI roi = ROI::All(), int nthreads = 0)
{
OIIO_ASSERT(dst.initialized() && src.nchannels() == dst.nchannels());
if (!roi.defined())
roi = get_roi(dst.spec());
roi.chend = std::min(roi.chend, dst.nchannels());
OIIO_ASSERT(dst.spec().format == TypeDesc::FLOAT);
ImageBufAlgo::parallel_image(roi, nthreads, [&](ROI roi) {
const ImageSpec& dstspec(dst.spec());
int nchannels = dstspec.nchannels;
span<float> pixel = OIIO_ALLOCA_SPAN(float, nchannels);
float dw = dstspec.width, dh = dstspec.height;
for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d) {
Imath::V3f V = latlong_to_dir((d.x() + 0.5f) / dw,
(dh - 1.0f - d.y() + 0.5f) / dh,
y_is_up);
float r = M_1_PI * acosf(V[2]) / hypotf(V[0], V[1]);
float u = (V[0] * r + 1.0f) * 0.5f;
float v = (V[1] * r + 1.0f) * 0.5f;
interppixel_NDC_clamped<SRCTYPE>(src, float(u), float(v), pixel,
false);
for (int c = roi.chbegin; c < roi.chend; ++c)
d[c] = pixel[c];
}
});
return true;
}
// compute slopes in pixel space using a Sobel gradient filter
template<class SRCTYPE>
static void
sobel_gradient(const ImageBuf& src, const ImageBuf::Iterator<float>& dstpix,
float* h, float* dh_ds, float* dh_dt)
{
static const float sobelweight_ds[9] = { -1.0f, 0.0f, 1.0f, -2.0f, 0.0f,
2.0f, -1.0f, 0.0f, 1.0f };
static const float sobelweight_dt[9] = { -1.0f, -2.0f, -1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 2.0f, 1.0f };
*dh_ds = *dh_dt = 0.0f;
ImageBuf::ConstIterator<SRCTYPE> srcpix(src, dstpix.x() - 1, dstpix.x() + 2,
dstpix.y() - 1, dstpix.y() + 2, 0,
1, ImageBuf::WrapClamp);
for (int i = 0; !srcpix.done(); ++srcpix, ++i) {
// accumulate to dh_ds and dh_dt using corresponding sobel 3x3 weights
float srcval = srcpix[0];
*dh_ds += sobelweight_ds[i] * srcval;
*dh_dt += sobelweight_dt[i] * srcval;
if (i == 4)
*h = srcval;
}
*dh_ds = *dh_ds / 8.0f; // sobel normalization
*dh_dt = *dh_dt / 8.0f;
}
// compute slopes from normal in s,t space
// Note: because we use getpixel(), it works for all src pixel types.
static void
normal_gradient(const ImageBuf& src, const ImageBuf::Iterator<float>& dstpix,
float* h, float* dh_ds, float* dh_dt)
{
// assume a normal defined in the tangent space
float n[3];
src.getpixel(dstpix.x(), dstpix.y(), make_span(n));
*h = -1.0f;
*dh_ds = -n[0] / n[2];
*dh_dt = -n[1] / n[2];
}
template<class SRCTYPE>
static bool
bump_to_bumpslopes(ImageBuf& dst, const ImageBuf& src,
const ImageSpec& configspec, std::ostream& outstream,
ROI roi = ROI::All(), int nthreads = 0)
{
if (!dst.initialized() || dst.nchannels() != 6
|| dst.spec().format != TypeDesc::FLOAT)
return false;
// detect bump input format according to channel count
void (*bump_filter)(const ImageBuf&, const ImageBuf::Iterator<float>&,
float*, float*, float*);
bump_filter = &sobel_gradient<SRCTYPE>;
float res_x = 1.0f;
float res_y = 1.0f;
string_view bumpformat = configspec.get_string_attribute(
"maketx:bumpformat");
if (Strutil::iequals(bumpformat, "height"))
bump_filter = &sobel_gradient<
SRCTYPE>; // default one considering height value in channel 0
else if (Strutil::iequals(bumpformat, "normal")) {
if (src.spec().nchannels < 3) {
outstream
<< "maketx ERROR: normal map requires 3 channels input map.\n";
return false;
}
bump_filter = &normal_gradient;
} else if (Strutil::iequals(
bumpformat,
"auto")) { // guess input bump format by analyzing channel count and component
if (src.spec().nchannels > 2
&& !ImageBufAlgo::isMonochrome(src)) // maybe it's a normal map?
bump_filter = &normal_gradient;
} else {
outstream << "maketx ERROR: Unknown input bump format " << bumpformat
<< ". Valid formats are height, normal or auto\n";
return false;
}
float uv_scale = configspec.get_float_attribute(
"maketx:uvslopes_scale",
configspec.get_float_attribute("uvslopes_scale"));
// If the input is an height map, does the derivatives needs to be UV normalized and scaled?
if (bump_filter == &sobel_gradient<SRCTYPE> && uv_scale != 0) {
if (uv_scale < 0) {
outstream
<< "maketx ERROR: Invalid uvslopes_scale value. The value must be >=0.\n";
return false;
}
// Note: the scale factor is used to prevent overflow if the half float format is used as destination.
// A scale factor of 256 is recommended to prevent overflowing for texture sizes up to 32k.
res_x = (float)src.spec().width / uv_scale;
res_y = (float)src.spec().height / uv_scale;
}
ImageBufAlgo::parallel_image(roi, nthreads, [&](ROI roi) {
// iterate on destination image
for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d) {
float h;
float dhds;
float dhdt;
bump_filter(src, d, &h, &dhds, &dhdt);
// h = height or h = -1.0f if a normal map
d[0] = h;
// first moments
d[1] = dhds * res_x;
d[2] = dhdt * res_y;
// second moments
d[3] = dhds * dhds * res_x * res_x;
d[4] = dhdt * dhdt * res_y * res_y;
d[5] = dhds * dhdt * res_x * res_y;
}
});
return true;
}
static void
fix_latl_edges(ImageBuf& buf)
{
int n = buf.nchannels();
span<float> left = OIIO_ALLOCA_SPAN(float, n);
span<float> right = OIIO_ALLOCA_SPAN(float, n);
// Make the whole first and last row be solid, since they are exactly
// on the pole
float wscale = 1.0f / (buf.spec().width);
for (int j = 0; j <= 1; ++j) {
int y = (j == 0) ? buf.ybegin() : buf.yend() - 1;
// use left for the sum, right for each new pixel
for (int c = 0; c < n; ++c)
left[c] = 0.0f;
for (int x = buf.xbegin(); x < buf.xend(); ++x) {
buf.getpixel(x, y, right);
for (int c = 0; c < n; ++c)
left[c] += right[c];
}
for (int c = 0; c < n; ++c)
left[c] *= wscale;
for (int x = buf.xbegin(); x < buf.xend(); ++x)
buf.setpixel(x, y, left);
}
// Make the left and right match, since they are both right on the
// prime meridian.
for (int y = buf.ybegin(); y < buf.yend(); ++y) {
buf.getpixel(buf.xbegin(), y, left);
buf.getpixel(buf.xend() - 1, y, right);
for (int c = 0; c < n; ++c)
left[c] = 0.5f * left[c] + 0.5f * right[c];
buf.setpixel(buf.xbegin(), y, left);
buf.setpixel(buf.xend() - 1, y, left);
}
}
inline std::string
formatres(const ImageSpec& spec)
{
return Strutil::fmt::format("{}x{}", spec.width, spec.height);
}
static void
maketx_merge_spec(ImageSpec& dstspec, const ImageSpec& srcspec)
{
for (size_t i = 0, e = srcspec.extra_attribs.size(); i < e; ++i) {
const ParamValue& p(srcspec.extra_attribs[i]);
ustring name = p.name();
if (Strutil::istarts_with(name.string(), "maketx:")) {
// Special instruction -- don't copy it to the destination spec
} else {
// just an attribute that should be set upon output
dstspec.attribute(name.string(), p.type(), p.data());
}
}
// Special case: we want "maketx:uvslopes_scale" to turn
// into "uvslopes_scale"
if (srcspec.extra_attribs.contains("maketx:uvslopes_scale"))
dstspec.attribute("uvslopes_scale",
srcspec.get_float_attribute("maketx:uvslopes_scale"));
}
static bool
write_mipmap(ImageBufAlgo::MakeTextureMode mode, std::shared_ptr<ImageBuf>& img,
const ImageSpec& outspec_template, std::string outputfilename,
ImageOutput* out, TypeDesc outputdatatype, bool mipmap,
string_view filtername, const ImageSpec& configspec,
std::ostream& outstream, double& stat_writetime,
double& stat_miptime, size_t& peak_mem)
{
using OIIO::errorfmt;
using OIIO::Strutil::sync::print; // Be sure to use synchronized one
bool envlatlmode = (mode == ImageBufAlgo::MakeTxEnvLatl);
bool orig_was_overscan = (img->spec().x || img->spec().y || img->spec().z
|| img->spec().full_x || img->spec().full_y
|| img->spec().full_z
|| img->spec().roi() != img->spec().roi_full());
ImageSpec outspec = outspec_template;
outspec.set_format(outputdatatype);
// Going from float to half is prone to generating Inf values if we had
// any floats that were out of the range that half can represent. Nobody
// wants Inf in textures; better to clamp.
bool clamp_half = (outspec.format == TypeHalf
&& (img->spec().format == TypeFloat
|| img->spec().format == TypeHalf));
if (mipmap && !out->supports("multiimage") && !out->supports("mipmap")) {
errorfmt("\"{} \" format does not support multires images",
outputfilename);
return false;
}
bool verbose = configspec.get_int_attribute("maketx:verbose") != 0;
bool src_samples_border = false;
// Some special constraints for OpenEXR
if (!strcmp(out->format_name(), "openexr")) {
// Always use "round down" mode
outspec.attribute("openexr:roundingmode", 0 /* ROUND_DOWN */);
if (!mipmap) {
// Send hint to OpenEXR driver that we won't specify a MIPmap
outspec.attribute("openexr:levelmode", 0 /* ONE_LEVEL */);
} else {
outspec.erase_attribute("openexr:levelmode");
}
// OpenEXR always uses border sampling for environment maps
if (envlatlmode) {
src_samples_border = true;
outspec.attribute("oiio:updirection", "y");
outspec.attribute("oiio:sampleborder", 1);
}
// For single channel images, dwaa/b compression only seems to work
// reliably when size > 16 and size is a power of two. Bug?
// FIXME: watch future OpenEXR releases to see if this gets fixed.
if (outspec.nchannels == 1
&& Strutil::istarts_with(outspec["compression"].get(), "dwa")) {
outspec.attribute("compression", "zip");
if (verbose)
outstream
<< "WARNING: Changing unsupported DWA compression for this case to zip.\n";
}
}
if (envlatlmode && src_samples_border)
fix_latl_edges(*img);
bool do_highlight_compensation
= configspec.get_int_attribute("maketx:highlightcomp", 0);
float sharpen = configspec.get_float_attribute("maketx:sharpen", 0.0f);
string_view sharpenfilt = "gaussian";
bool sharpen_first = true;
if (Strutil::istarts_with(filtername, "post-")) {
sharpen_first = false;
filtername.remove_prefix(5);
}
if (Strutil::istarts_with(filtername, "unsharp-")) {
filtername.remove_prefix(8);
sharpenfilt = filtername;
filtername = "lanczos3";
}
Timer writetimer;
if (!out->open(outputfilename.c_str(), outspec)) {
errorfmt("Could not open \"{}\" : {}", outputfilename, out->geterror());
return false;
}
// Write out the image
if (verbose) {
print(outstream, " Writing file: {}\n", outputfilename);
print(outstream, " Filter \"{}\"\n", filtername);
print(outstream, " Top level is {}x{}\n", outspec.width,
outspec.height);
}
if (clamp_half) {
std::shared_ptr<ImageBuf> tmp(new ImageBuf);
ImageBufAlgo::clamp(*tmp, *img, -HALF_MAX, HALF_MAX, true);
std::swap(tmp, img);
}
if (!img->write(out)) {
// ImageBuf::write transfers any errors from the ImageOutput to
// the ImageBuf.
errorfmt("Write failed: {}", img->geterror());
out->close();
return false;
}
double wtime = writetimer();
stat_writetime += wtime;
if (verbose) {
size_t mem = Sysutil::memory_used(true);
peak_mem = std::max(peak_mem, mem);
print(outstream, " {:-15s} ({}) write {}\n", formatres(outspec),
Strutil::memformat(mem), Strutil::timeintervalformat(wtime, 2));
}
if (mipmap) { // Mipmap levels:
if (verbose)
print(outstream, " Mipmapping...\n");
std::vector<std::string> mipimages;
std::string mipimages_unsplit = configspec.get_string_attribute(
"maketx:mipimages");
if (mipimages_unsplit.length())
Strutil::split(mipimages_unsplit, mipimages, ";");
bool allow_shift
= configspec.get_int_attribute("maketx:allow_pixel_shift") != 0;
std::shared_ptr<ImageBuf> small(new ImageBuf);
while (outspec.width > 1 || outspec.height > 1) {
Timer miptimer;
ImageSpec smallspec;
if (mipimages.size()) {
// Special case -- the user specified a custom MIP level
small->reset(mipimages[0]);
small->read(0, 0, true, TypeFloat);
smallspec = small->spec();
if (smallspec.nchannels != outspec.nchannels) {
outstream << "WARNING: Custom mip level \"" << mipimages[0]
<< " had the wrong number of channels.\n";
std::shared_ptr<ImageBuf> t(new ImageBuf(smallspec));
ImageBufAlgo::channels(*t, *small, outspec.nchannels,
cspan<int>(), cspan<float>(),
cspan<std::string>(), true);
std::swap(t, small);
}
smallspec.tile_width = outspec.tile_width;
smallspec.tile_height = outspec.tile_height;
smallspec.tile_depth = outspec.tile_depth;
mipimages.erase(mipimages.begin());
} else {
// Resize a factor of two smaller
smallspec = outspec;
if (!configspec.get_int_attribute("maketx:mipmap_metadata"))
smallspec.extra_attribs.free();
smallspec.width = img->spec().width;
smallspec.height = img->spec().height;
smallspec.depth = img->spec().depth;
if (smallspec.width > 1)
smallspec.width /= 2;
if (smallspec.height > 1)
smallspec.height /= 2;
smallspec.full_width = smallspec.width;
smallspec.full_height = smallspec.height;
smallspec.full_depth = smallspec.depth;
if (!allow_shift
|| configspec.get_int_attribute("maketx:forcefloat", 1))
smallspec.set_format(TypeDesc::FLOAT);
// Trick: to get the resize working properly, we reset
// both display and pixel windows to match, and have 0
// offset, AND doctor the big image to have its display
// and pixel windows match. Don't worry, the texture
// engine doesn't care what the upper MIP levels have
// for the window sizes, it uses level 0 to determine
// the relatinship between texture 0-1 space (display
// window) and the pixels.
smallspec.x = 0;
smallspec.y = 0;
smallspec.full_x = 0;
smallspec.full_y = 0;
small->reset(smallspec); // Realocate with new size
img->set_full(img->xbegin(), img->xend(), img->ybegin(),
img->yend(), img->zbegin(), img->zend());
if (filtername == "box" && !orig_was_overscan
&& sharpen <= 0.0f) {
ImageBufAlgo::parallel_image(get_roi(small->spec()),
std::bind(resize_block,
std::ref(*small),
std::cref(*img), _1,
envlatlmode,
allow_shift));
} else {
Filter2D* filter = setup_filter(small->spec(), img->spec(),
filtername);
if (!filter) {
errorfmt("Could not make filter \"{}\"", filtername);
return false;
}
if (verbose) {
print(outstream,
" Downsampling filter \"{}\" width = {}",
filter->name(), filter->width());
if (sharpen > 0.0f)
print(
outstream,
", sharpening {} with {} unsharp mask {} the resize",
sharpen, sharpenfilt,
(sharpen_first ? "before" : "after"));
print(outstream, "\n");
}
if (do_highlight_compensation)
ImageBufAlgo::rangecompress(*img, *img);
if (sharpen > 0.0f && sharpen_first) {
std::shared_ptr<ImageBuf> sharp(new ImageBuf);
bool uok = ImageBufAlgo::unsharp_mask(*sharp, *img,
sharpenfilt, 3.0,
sharpen, 0.0f);
if (!uok)
errorfmt("{}", sharp->geterror());
std::swap(img, sharp);
}
ImageBufAlgo::resize(*small, *img,
{ make_pv("filterptr", filter) });
if (sharpen > 0.0f && !sharpen_first) {
std::shared_ptr<ImageBuf> sharp(new ImageBuf);
bool uok = ImageBufAlgo::unsharp_mask(*sharp, *small,
sharpenfilt, 3.0,
sharpen, 0.0f);
if (!uok)
errorfmt("{}", sharp->geterror());
std::swap(small, sharp);
}
if (do_highlight_compensation) {
ImageBufAlgo::rangeexpand(*small, *small);
ImageBufAlgo::clamp(*small, *small, 0.0f,
std::numeric_limits<float>::max(),
true);
}
Filter2D::destroy(filter);
}
}
if (clamp_half)
ImageBufAlgo::clamp(*small, *small, -HALF_MAX, HALF_MAX, true);
double this_miptime = miptimer();
stat_miptime += this_miptime;
outspec = smallspec;
outspec.set_format(outputdatatype);
if (envlatlmode && src_samples_border)
fix_latl_edges(*small);
Timer writetimer;
// If the format explicitly supports MIP-maps, use that,
// otherwise try to simulate MIP-mapping with multi-image.
ImageOutput::OpenMode mode = out->supports("mipmap")
? ImageOutput::AppendMIPLevel
: ImageOutput::AppendSubimage;
if (!out->open(outputfilename.c_str(), outspec, mode)) {
errorfmt("Could not append \"{}\" : {}", outputfilename,
out->geterror());
return false;
}
if (!small->write(out)) {
// ImageBuf::write transfers any errors from the
// ImageOutput to the ImageBuf.
errorfmt("Error writing \"{}\" : {}", outputfilename,
small->geterror());
out->close();
return false;
}
double wtime = writetimer();
stat_writetime += wtime;
if (verbose) {
size_t mem = Sysutil::memory_used(true);
peak_mem = std::max(peak_mem, mem);
print(outstream, " {:-15s} ({}) downres {} write {}\n",
formatres(smallspec), Strutil::memformat(mem),
Strutil::timeintervalformat(this_miptime, 2),
Strutil::timeintervalformat(wtime, 2));
}
std::swap(img, small);
}
}
if (verbose)
print(outstream, " Wrote file: {} ({})\n", outputfilename,
Strutil::memformat(Sysutil::memory_used(true)));
writetimer.reset();
writetimer.start();
if (!out->close()) {
errorfmt("Error writing \"{}\" : {}", outputfilename, out->geterror());
return false;
}
stat_writetime += writetimer();
return true;
}
// Deconstruct the command line string, stripping directory names off of
// any arguments. This is used for "update mode" to not think it's doing
// a fresh maketx for relative paths and whatnot.
static std::string
stripdir_cmd_line(string_view cmdline)
{
std::string out;
bool firstarg = true;
int skipstrip = 0;
while (!cmdline.empty()) {
if (!firstarg)
out += ' ';
// Grab the next word or quoted string
string_view s;
if (!Strutil::parse_string(cmdline, s))
break;
// Uniformize commands that start with '-' and those that start
// with '--'.
if (Strutil::starts_with(s, "--"))
s.remove_prefix(1);
std::string stripped = s;
// Some commands are known to be followed by arguments that might
// contain slashes, yet not be filenames. Remember to skip those.
// In particular, we're looking for things that might have arbitrary
// strings including slashes, for example, attribute names and color
// space names.
if (Strutil::starts_with(s, "-")) {
static const char* one_arg_list[]
= { "-colorconfig", "-iscolorspace", "-tocolorspace",
"-ociolook", "-ociofiletransform", "-eraseattrib",
"-caption", "-keyword", "-text",
"-echo" };
static const char* two_arg_list[] = { "-attrib", "-sattrib",
"-iconfig", "-colorconvert",
"-ociodisplay" };
for (auto cmd : one_arg_list)
if (Strutil::starts_with(s, cmd))
skipstrip = 2; // including the command itself
for (auto cmd : two_arg_list)
if (Strutil::starts_with(s, cmd))
skipstrip = 3; // including the command itself
}
// Whatever's left when we're not disabling stripping for this arg,
// for anything that looks like a filename by having directory
// separators, strip out the directory name so that command lines
// appear to match even if filenames have different relative paths.
if (!skipstrip)
stripped = Filesystem::filename(stripped);
// Add the maybe-stripped string to the output, surrounding by
// double quotes if it contains any spaces.
if (stripped.find(' ') != std::string::npos)
out += Strutil::fmt::format("\"{}\"", stripped);
else
out += stripped;
firstarg = false;
skipstrip = std::max(0, skipstrip - 1);
}
return out;
}
static bool
make_texture_impl(ImageBufAlgo::MakeTextureMode mode, const ImageBuf* input,
std::string filename, std::string outputfilename,
const ImageSpec& _configspec, std::ostream* outstream_ptr)
{
using OIIO::errorfmt;
using OIIO::Strutil::sync::print; // Be sure to use synchronized one
OIIO_ASSERT(mode >= 0 && mode < ImageBufAlgo::_MakeTxLast);
double stat_readtime = 0;
double stat_writetime = 0;
double stat_resizetime = 0;
double stat_miptime = 0;
double stat_colorconverttime = 0;
size_t peak_mem = 0;
Timer alltime;
#define STATUS(task, timer) \
{ \
size_t mem = Sysutil::memory_used(true); \
peak_mem = std::max(peak_mem, mem); \
if (verbose) \
print(outstream, " {:-25s} {} ({})\n", task, \