forked from AcademySoftwareFoundation/OpenImageIO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaketexture.cpp
More file actions
1558 lines (1372 loc) · 63.4 KB
/
maketexture.cpp
File metadata and controls
1558 lines (1372 loc) · 63.4 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 2013 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <sstream>
#include <memory>
#include <boost/version.hpp>
#include <OpenEXR/ImathMatrix.h>
#include <OpenEXR/half.h>
#include <OpenImageIO/argparse.h>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/timer.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <OpenImageIO/imagebufalgo_util.h>
#include <OpenImageIO/thread.h>
#include <OpenImageIO/filter.h>
#ifdef USE_BOOST_REGEX
# include <boost/regex.hpp>
using boost::regex;
using boost::regex_replace;
#else
# include <regex>
using std::regex;
using std::regex_replace;
#endif
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::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, 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 = 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 = Imath::clamp (ytexel+1, buf.ymin(), buf.ymax());
ytexel = Imath::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);
}
// 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());
float *pel = ALLOCA (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();
ASSERT (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_full (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);
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();
ASSERT(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());
DASSERT (dstspec.nchannels == srcspec.nchannels);
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 {
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());
float *pel = ALLOCA (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);
}
static bool
lightprobe_to_envlatl (ImageBuf &dst, const ImageBuf &src, bool y_is_up,
ROI roi=ROI::All(), int nthreads=0)
{
ASSERT (dst.initialized() && src.nchannels() == dst.nchannels());
if (! roi.defined())
roi = get_roi (dst.spec());
roi.chend = std::min (roi.chend, dst.nchannels());
ImageBufAlgo::parallel_image (roi, nthreads, [&](ROI roi){
const ImageSpec &dstspec (dst.spec());
int nchannels = dstspec.nchannels;
ASSERT (dstspec.format == TypeDesc::FLOAT);
float *pixel = ALLOCA (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<float> (src, float(u), float(v), pixel, false);
for (int c = roi.chbegin; c < roi.chend; ++c)
d[c] = pixel[c];
}
});
return true;
}
static void
fix_latl_edges (ImageBuf &buf)
{
int n = buf.nchannels();
float *left = ALLOCA (float, n);
float *right = ALLOCA (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);
}
}
static std::string
formatres (const ImageSpec &spec, bool extended=false)
{
std::string s;
s = Strutil::format("%dx%d", spec.width, spec.height);
if (extended) {
if (spec.x || spec.y)
s += Strutil::format("%+d%+d", spec.x, spec.y);
if (spec.width != spec.full_width || spec.height != spec.full_height ||
spec.x != spec.full_x || spec.y != spec.full_y) {
s += " (full/display window is ";
s += Strutil::format("%dx%d", spec.full_width, spec.full_height);
if (spec.full_x || spec.full_y)
s += Strutil::format("%+d%+d", spec.full_x, spec.full_y);
s += ")";
}
}
return s;
}
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());
}
}
}
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)
{
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);
ImageSpec outspec = outspec_template;
outspec.set_format (outputdatatype);
if (mipmap && !out->supports ("multiimage") && !out->supports ("mipmap")) {
outstream << "maketx ERROR: \"" << outputfilename
<< "\" format does not support multires images\n";
return false;
}
if (! mipmap && ! strcmp (out->format_name(), "openexr")) {
// Send hint to OpenEXR driver that we won't specify a MIPmap
outspec.attribute ("openexr:levelmode", 0 /* ONE_LEVEL */);
}
if (mipmap && ! strcmp (out->format_name(), "openexr")) {
outspec.attribute ("openexr:roundingmode", 0 /* ROUND_DOWN */);
}
// OpenEXR always uses border sampling for environment maps
bool src_samples_border = false;
if (envlatlmode && !strcmp(out->format_name(), "openexr")) {
src_samples_border = true;
outspec.attribute ("oiio:updirection", "y");
outspec.attribute ("oiio:sampleborder", 1);
}
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)) {
outstream << "maketx ERROR: Could not open \"" << outputfilename
<< "\" : " << out->geterror() << "\n";
return false;
}
// Write out the image
bool verbose = configspec.get_int_attribute ("maketx:verbose") != 0;
if (verbose) {
outstream << " Writing file: " << outputfilename << std::endl;
outstream << " Filter \"" << filtername << "\"\n";
outstream << " Top level is " << formatres(outspec) << std::endl;
}
if (! img->write (out)) {
// ImageBuf::write transfers any errors from the ImageOutput to
// the ImageBuf.
outstream << "maketx ERROR: Write failed \" : " << img->geterror() << "\n";
out->close ();
return false;
}
stat_writetime += writetimer();
if (mipmap) { // Mipmap levels:
if (verbose)
outstream << " Mipmapping...\n" << std::flush;
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, TypeDesc::FLOAT);
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,
NULL, NULL, NULL, 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;
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) {
outstream << "maketx ERROR: could not make filter \"" << filtername << "\"\n";
return false;
}
if (verbose) {
outstream << " Downsampling filter \"" << filter->name()
<< "\" width = " << filter->width();
if (sharpen > 0.0f) {
outstream << ", sharpening " << sharpen << " with "
<< sharpenfilt << " unsharp mask "
<< (sharpen_first ? "before" : "after")
<< " the resize";
}
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)
outstream << "maketx ERROR: " << sharp->geterror() << "\n";
std::swap (img, sharp);
}
ImageBufAlgo::resize (*small, *img, 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)
outstream << "maketx ERROR: " << sharp->geterror() << "\n";
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);
}
}
stat_miptime += miptimer();
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)) {
outstream << "maketx ERROR: Could not append \"" << outputfilename
<< "\" : " << out->geterror() << "\n";
return false;
}
if (! small->write (out)) {
// ImageBuf::write transfers any errors from the
// ImageOutput to the ImageBuf.
outstream << "maketx ERROR writing \"" << outputfilename
<< "\" : " << small->geterror() << "\n";
out->close ();
return false;
}
stat_writetime += writetimer();
if (verbose) {
size_t mem = Sysutil::memory_used(true);
peak_mem = std::max (peak_mem, mem);
outstream << Strutil::format (" %-15s (%s)",
formatres(smallspec),
Strutil::memformat(mem))
<< std::endl;
}
std::swap (img, small);
}
}
if (verbose)
outstream << " Wrote file: " << outputfilename << " ("
<< Strutil::memformat(Sysutil::memory_used(true)) << ")\n";
writetimer.reset ();
writetimer.start ();
if (! out->close ()) {
outstream << "maketx ERROR writing \"" << outputfilename
<< "\" : " << out->geterror() << "\n";
return false;
}
stat_writetime += writetimer ();
return true;
}
static bool
make_texture_impl (ImageBufAlgo::MakeTextureMode mode,
const ImageBuf *input,
std::string filename,
std::string outputfilename,
const ImageSpec &_configspec,
std::ostream *outstream_ptr)
{
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) \
outstream << Strutil::format (" %-25s %s (%s)\n", task, \
Strutil::timeintervalformat(timer,2), \
Strutil::memformat(mem)); \
}
ImageSpec configspec = _configspec;
std::stringstream localstream; // catch output when user doesn't want it
std::ostream &outstream (outstream_ptr ? *outstream_ptr : localstream);
bool from_filename = (input == NULL);
if (from_filename && ! Filesystem::exists (filename)) {
outstream << "maketx ERROR: \"" << filename << "\" does not exist\n";
return false;
}
std::shared_ptr<ImageBuf> src;
if (input == NULL) {
// No buffer supplied -- create one to read the file
src.reset (new ImageBuf(filename));
src->init_spec (filename, 0, 0); // force it to get the spec, not read
} else if (input->cachedpixels()) {
// Image buffer supplied that's backed by ImageCache -- create a
// copy (very light weight, just another cache reference)
src.reset (new ImageBuf(*input));
} else {
// Image buffer supplied that has pixels -- wrap it
src.reset (new ImageBuf(input->name(), input->spec(),
(void *)input->localpixels()));
}
ASSERT (src.get());
if (! outputfilename.length()) {
std::string fn = src->name();
if (fn.length()) {
if (Filesystem::extension(fn).length() > 1)
outputfilename = Filesystem::replace_extension (fn, ".tx");
else
outputfilename = outputfilename + ".tx";
} else {
outstream << "maketx: no output filename supplied\n";
return false;
}
}
// Write the texture to a temp file first, then rename it to the final
// destination (same directory). This improves robustness. There is less
// chance a crash during texture conversion will leave behind a
// partially formed tx with incomplete mipmaps levels which happesn to
// be extremely slow to use in a raytracer.
// We also force a unique filename to protect against multiple maketx
// processes running at the same time on the same file.
std::string extension = Filesystem::extension(outputfilename);
std::string tmpfilename = Filesystem::replace_extension (outputfilename, ".%%%%%%%%.temp"+extension);
tmpfilename = Filesystem::unique_path(tmpfilename);
// When was the input file last modified?
// This is only used when we're reading from a filename
std::time_t in_time;
if (from_filename)
in_time = Filesystem::last_write_time (src->name());
else
time (&in_time); // make it look initialized
// When in update mode, skip making the texture if the output already
// exists and has the same file modification time as the input file and
// was created with identical command line arguments.
bool updatemode = configspec.get_int_attribute ("maketx:updatemode");
if (updatemode && from_filename && Filesystem::exists(outputfilename) &&
in_time == Filesystem::last_write_time (outputfilename)) {
std::string lastcmdline;
if (ImageInput *in = ImageInput::open (outputfilename)) {
lastcmdline = in->spec().get_string_attribute ("Software");
ImageInput::destroy (in);
}
std::string newcmdline = configspec.get_string_attribute("maketx:full_command_line");
if (lastcmdline.size() && lastcmdline == newcmdline) {
outstream << "maketx: no update required for \""
<< outputfilename << "\"\n";
return true;
}
}
bool shadowmode = (mode == ImageBufAlgo::MakeTxShadow);
bool envlatlmode = (mode == ImageBufAlgo::MakeTxEnvLatl ||
mode == ImageBufAlgo::MakeTxEnvLatlFromLightProbe);
// Find an ImageIO plugin that can open the output file, and open it
std::string outformat = configspec.get_string_attribute ("maketx:fileformatname",
outputfilename);
ImageOutput *out = ImageOutput::create (outformat.c_str());
if (! out) {
outstream
<< "maketx ERROR: Could not find an ImageIO plugin to write "
<< outformat << " files:" << geterror() << "\n";
return false;
}
if (! out->supports ("tiles")) {
outstream << "maketx ERROR: \"" << outputfilename
<< "\" format does not support tiled images\n";
return false;
}
// The cache might mess with the apparent data format, so make sure
// it's the nativespec that we consult for data format of the file.
TypeDesc out_dataformat = src->nativespec().format;
if (configspec.format != TypeDesc::UNKNOWN)
out_dataformat = configspec.format;
// We cannot compute the prman / oiio options until after out_dataformat
// has been determined, as it's required (and can potentially change
// out_dataformat too!)
if (configspec.get_int_attribute("maketx:prman_options"))
out_dataformat = set_prman_options (out_dataformat, configspec);
else if (configspec.get_int_attribute("maketx:oiio_options"))
out_dataformat = set_oiio_options (out_dataformat, configspec);
// Read the full file locally if it's less than 1 GB, otherwise
// allow the ImageBuf to use ImageCache to manage memory.
int local_mb_thresh = configspec.get_int_attribute("maketx:read_local_MB",
1024);
bool read_local = (src->spec().image_bytes() < imagesize_t(local_mb_thresh * 1024*1024));
bool verbose = configspec.get_int_attribute ("maketx:verbose") != 0;
double misc_time_1 = alltime.lap();
STATUS ("prep", misc_time_1);
if (from_filename) {
if (verbose)
outstream << "Reading file: " << src->name() << std::endl;
if (! src->read (0, 0, read_local)) {
outstream << "maketx ERROR: Could not read \""
<< src->name() << "\" : " << src->geterror() << "\n";
return false;
}
}
stat_readtime += alltime.lap();
STATUS (Strutil::format("read \"%s\"", src->name()), stat_readtime);
if (mode == ImageBufAlgo::MakeTxEnvLatlFromLightProbe) {
ImageSpec newspec = src->spec();
newspec.width = newspec.full_width = src->spec().width;
newspec.height = newspec.full_height = src->spec().height/2;
newspec.tile_width = newspec.tile_height = 0;
newspec.format = TypeDesc::FLOAT;
std::shared_ptr<ImageBuf> latlong (new ImageBuf(newspec));
// Now lightprobe holds the original lightprobe, src is a blank
// image that will be the unwrapped latlong version of it.
lightprobe_to_envlatl (*latlong, *src, true);
// Carry on with the lat-long environment map from here on out
mode = ImageBufAlgo::MakeTxEnvLatl;
src = latlong;
}
// Some things require knowing a bunch about the pixel statistics.
bool constant_color_detect = configspec.get_int_attribute("maketx:constant_color_detect");
bool opaque_detect = configspec.get_int_attribute("maketx:opaque_detect");
bool compute_average_color = configspec.get_int_attribute("maketx:compute_average", 1);
ImageBufAlgo::PixelStats pixel_stats;
bool compute_stats = (constant_color_detect || opaque_detect || compute_average_color);
if (compute_stats)
ImageBufAlgo::computePixelStats (pixel_stats, *src);
// If requested - and we're a constant color - make a tiny texture instead
// Only safe if the full/display window is the same as the data window.
// Also note that this could affect the appearance when using "black"
// wrap mode at runtime.
std::vector<float> constantColor(src->nchannels());
bool isConstantColor = false;
if (compute_stats &&
src->spec().x == 0 && src->spec().y == 0 && src->spec().z == 0 &&
src->spec().full_x == 0 && src->spec().full_y == 0 &&
src->spec().full_z == 0 && src->spec().full_width == src->spec().width &&
src->spec().full_height == src->spec().height &&
src->spec().full_depth == src->spec().depth) {
isConstantColor = (pixel_stats.min == pixel_stats.max);
if (isConstantColor)
constantColor = pixel_stats.min;
if (isConstantColor && constant_color_detect) {
// Reset the image, to a new image, at the tile size
ImageSpec newspec = src->spec();
newspec.width = std::min (configspec.tile_width, src->spec().width);
newspec.height = std::min (configspec.tile_height, src->spec().height);
newspec.depth = std::min (configspec.tile_depth, src->spec().depth);
newspec.full_width = newspec.width;
newspec.full_height = newspec.height;
newspec.full_depth = newspec.depth;
std::string name = std::string(src->name()) + ".constant_color";
src->reset(name, newspec);
ImageBufAlgo::fill (*src, &constantColor[0]);
if (verbose) {
outstream << " Constant color image detected. ";
outstream << "Creating " << newspec.width << "x" << newspec.height << " texture instead.\n";
}
}
}
int nchannels = configspec.get_int_attribute ("maketx:nchannels", -1);
// If requested -- and alpha is 1.0 everywhere -- drop it.
if (opaque_detect &&
src->spec().alpha_channel == src->nchannels()-1 &&
nchannels <= 0 &&
pixel_stats.min[src->spec().alpha_channel] == 1.0f &&
pixel_stats.max[src->spec().alpha_channel] == 1.0f) {
if (verbose)
outstream << " Alpha==1 image detected. Dropping the alpha channel.\n";
std::shared_ptr<ImageBuf> newsrc (new ImageBuf(src->spec()));
ImageBufAlgo::channels (*newsrc, *src, src->nchannels()-1,
NULL, NULL, NULL, true);
std::swap (src, newsrc); // N.B. the old src will delete
}
// If requested - and we're a monochrome image - drop the extra channels
if (configspec.get_int_attribute("maketx:monochrome_detect") &&
nchannels <= 0 &&
src->nchannels() == 3 && src->spec().alpha_channel < 0 && // RGB only
ImageBufAlgo::isMonochrome(*src)) {
if (verbose)
outstream << " Monochrome image detected. Converting to single channel texture.\n";