forked from NVIDIA-RTX/RTXNTC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNtcCommandLine.cpp
More file actions
2149 lines (1802 loc) · 83.6 KB
/
NtcCommandLine.cpp
File metadata and controls
2149 lines (1802 loc) · 83.6 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
/*
* SPDX-FileCopyrightText: Copyright (c) 2023-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: LicenseRef-NvidiaProprietary
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include <argparse.h>
#include <cinttypes>
#include <cmath>
#include <cuda_runtime_api.h>
#include <donut/app/DeviceManager.h>
#include <filesystem>
#include <libntc/ntc.h>
#include <ntc-utils/DeviceUtils.h>
#include <ntc-utils/GraphicsDecompressionPass.h>
#include <ntc-utils/Manifest.h>
#include <ntc-utils/Misc.h>
#include <ntc-utils/Semantics.h>
#include <nvrhi/utils.h>
#include <stb_image.h>
#include <tinyexr.h>
#include "GraphicsPasses.h"
#include "Utils.h"
namespace fs = std::filesystem;
struct
{
const char* loadImagesPath = nullptr;
const char* loadManifestFileName = nullptr;
const char* saveImagesPath = nullptr;
const char* loadCompressedFileName = nullptr;
const char* saveCompressedFileName = nullptr;
ToolInputType inputType = ToolInputType::None;
std::vector<char const*> loadImagesList;
std::optional<ntc::BlockCompressedFormat> bcFormat;
ImageContainer imageFormat = ImageContainer::Auto;
int networkVersion = NTC_NETWORK_UNKNOWN;
bool compress = false;
bool decompress = false;
bool loadMips = false;
bool saveMips = false;
bool generateMips = false;
bool optimizeBC = false;
bool useVulkan = false;
bool useDX12 = false;
bool debug = false;
bool listAdapters = false;
bool listCudaDevices = false;
bool describe = false;
bool discardMaskedOutPixels = false;
bool enableCoopVec = true;
bool enableCoopVecInt8 = true;
bool enableCoopVecFP8 = true;
bool enableDP4a = true;
bool enableFloat16 = true;
bool printVersion = false;
int gridSizeScale = 4;
int highResFeatures = 8;
int lowResFeatures = 16;
int highResQuantBits = 2;
int lowResQuantBits = 4;
int adapterIndex = -1;
int cudaDevice = 0;
int benchmarkIterations = 1;
float experimentalKnob = 0.f;
float bitsPerPixel = NAN; // Use an "undefined" value to tell if something came from the command line
float targetPsnr = NAN;
float maxBitsPerPixel = NAN;
bool matchBcPsnr = false;
float minBcPsnr = 0.f;
float maxBcPsnr = INFINITY;
float bcPsnrOffset = 0.f;
int bcQuality = -1;
float bcPsnrThreshold = 0.2f;
std::optional<int> customWidth;
std::optional<int> customHeight;
ntc::CompressionSettings compressionSettings;
} g_options;
bool ProcessCommandLine(int argc, const char** argv)
{
const char* bcFormatString = nullptr;
const char* imageFormatString = nullptr;
const char* networkVersionString = nullptr;
const char* dimensionsString = nullptr;
struct argparse_option options[] = {
OPT_GROUP("Actions:"),
OPT_BOOLEAN('c', "compress", &g_options.compress, "Perform NTC compression"),
OPT_BOOLEAN('D', "decompress", &g_options.decompress, "Perform NTC decompression (implied when needed)"),
OPT_BOOLEAN('d', "describe", &g_options.describe, "Describe the contents of a compressed texture set"),
OPT_BOOLEAN('g', "generateMips", &g_options.generateMips, "Generate MIP level images before compression"),
OPT_STRING (0, "loadCompressed", &g_options.loadCompressedFileName, "Load compressed texture set from the specified file"),
OPT_STRING (0, "loadImages", &g_options.loadImagesPath, "Load channel images from the specified folder"),
OPT_STRING (0, "loadManifest", &g_options.loadManifestFileName, "Load channel images and their parameters using the specified JSON manifest file"),
OPT_BOOLEAN(0, "loadMips", &g_options.loadMips, "Load MIP level images from <loadImages>/mips/<texture>.<mip>.<ext> before compression"),
OPT_BOOLEAN(0, "optimizeBC", &g_options.optimizeBC, "Run slow BC compression and store acceleration info in the NTC package"),
OPT_STRING ('o', "saveCompressed", &g_options.saveCompressedFileName, "Save compressed texture set into the specified file"),
OPT_STRING ('i', "saveImages", &g_options.saveImagesPath, "Save channel images into the specified folder"),
OPT_BOOLEAN(0, "saveMips", &g_options.saveMips, "Save MIP level images into <saveImages>/mips/ after decompression"),
OPT_BOOLEAN(0, "version", &g_options.printVersion, "Print version information and exit"),
OPT_HELP(),
OPT_GROUP("Basic compression options:"),
OPT_FLOAT ('b', "bitsPerPixel", &g_options.bitsPerPixel, "Request an optimal compression configuration for the provided BPP value"),
OPT_FLOAT (0, "maxBitsPerPixel", &g_options.maxBitsPerPixel, "Maximum BPP value to use in the compression parameter search"),
OPT_FLOAT ('p', "targetPsnr", &g_options.targetPsnr, "Perform compression parameter search to reach at least the provided PSNR value"),
OPT_GROUP("Custom latent shape selection:"),
OPT_INTEGER(0, "gridSizeScale", &g_options.gridSizeScale, "Ratio of source image size to high-resolution feature grid size"),
OPT_INTEGER(0, "highResFeatures", &g_options.highResFeatures, "Number of features in the high-resolution grid"),
OPT_INTEGER(0, "highResQuantBits", &g_options.highResQuantBits, "Number of bits to use for encoding of high-resolution features"),
OPT_INTEGER(0, "lowResFeatures", &g_options.lowResFeatures, "Number of features in the low-resolution grid"),
OPT_INTEGER(0, "lowResQuantBits", &g_options.lowResQuantBits, "Number of bits to use for encoding of low-resolution features"),
OPT_GROUP("Training process controls:"),
OPT_FLOAT (0, "gridLearningRate", &g_options.compressionSettings.gridLearningRate, "Maximum learning rate for the feature grid"),
OPT_INTEGER(0, "kPixelsPerBatch", &g_options.compressionSettings.kPixelsPerBatch, "Number of kilopixels from the image to process in one training step"),
OPT_FLOAT (0, "networkLearningRate", &g_options.compressionSettings.networkLearningRate, "Maximum learning rate for the MLP weights"),
OPT_INTEGER(0, "randomSeed", &g_options.compressionSettings.randomSeed, "Random seed, set to a nonzero value to get more stable compression results"),
OPT_BOOLEAN(0, "stableTraining", &g_options.compressionSettings.stableTraining, "Use a more expensive but more numerically stable training algorithm for reproducible results"),
OPT_INTEGER(0, "stepsPerIteration", &g_options.compressionSettings.stepsPerIteration, "Training steps between progress reports"),
OPT_INTEGER('S', "trainingSteps", &g_options.compressionSettings.trainingSteps, "Total training step count"),
OPT_BOOLEAN(0, "fp8weights", &g_options.compressionSettings.trainFP8Weights, "Train a separate set of weights for FP8 inference (default on, use --no-fp8weights)"),
OPT_GROUP("Output settings:"),
OPT_STRING ('B', "bcFormat", &bcFormatString, "Set or override the BCn encoding format, BC1-BC7"),
OPT_STRING ('F', "imageFormat", &imageFormatString, "Set the output file format for color images: Auto (default), BMP, JPG, TGA, PNG, PNG16, EXR"),
OPT_STRING (0, "dimensions", &dimensionsString, "Set the dimensions of the NTC texture set before compression, in the 'WxH' format"),
OPT_GROUP("Advanced settings:"),
OPT_FLOAT (0, "bcPsnrThreshold", &g_options.bcPsnrThreshold, "PSNR loss threshold for BC7 optimization, in dB, default value is 0.2"),
OPT_INTEGER(0, "bcQuality", &g_options.bcQuality, "Quality knob for BC7 compression, [0, 255]"),
OPT_INTEGER(0, "benchmark", &g_options.benchmarkIterations, "Number of iterations to run over compute passes for benchmarking"),
OPT_BOOLEAN(0, "discardMaskedOutPixels", &g_options.discardMaskedOutPixels, "Ignore contents of pixels where alpha mask is 0.0 (requires the AlphaMask semantic)"),
OPT_FLOAT (0, "experimentalKnob", &g_options.experimentalKnob, "A parameter for NTC development, normally has no effect"),
OPT_BOOLEAN(0, "matchBcPsnr", &g_options.matchBcPsnr, "Perform compression parameter search to reach the PSNR value that BCn encoding provides"),
OPT_FLOAT (0, "minBcPsnr", &g_options.minBcPsnr, "When using --matchBcPsnr, minimum PSNR value to use for NTC compression"),
OPT_FLOAT (0, "maxBcPsnr", &g_options.maxBcPsnr, "When using --matchBcPsnr, maximum PSNR value to use for NTC compression"),
OPT_FLOAT (0, "bcPsnrOffset", &g_options.bcPsnrOffset, "When using --matchBcPsnr, offset to apply to BCn PSNR value before NTC compression"),
OPT_STRING ('V', "networkVersion", &networkVersionString, "Network version to use for compression: auto, small, medium, large, xlarge"),
OPT_GROUP("GPU and Graphics API settings:"),
OPT_INTEGER(0, "adapter", &g_options.adapterIndex, "Index of the graphics adapter to use"),
OPT_BOOLEAN(0, "coopVec", &g_options.enableCoopVec, "Enable all CoopVec extensions (default on, use --no-coopVec)"),
OPT_BOOLEAN(0, "coopVecFP8", &g_options.enableCoopVecFP8, "Enable CoopVec extensions for FP8 math (default on, use --no-coopVecFP8)"),
OPT_BOOLEAN(0, "coopVecInt8", &g_options.enableCoopVecInt8, "Enable CoopVec extensions for Int8 math (default on, use --no-coopVecInt8)"),
OPT_INTEGER(0, "cudaDevice", &g_options.cudaDevice, "Index of the CUDA device to use"),
OPT_BOOLEAN(0, "debug", &g_options.debug, "Enable debug features such as Vulkan validation layer or D3D12 debug runtime"),
OPT_BOOLEAN(0, "dp4a", &g_options.enableDP4a, "Enable DP4a instructions (default on, use --no-dp4a)"),
#if NTC_WITH_DX12
OPT_BOOLEAN(0, "dx12", &g_options.useDX12, "Use D3D12 API for graphics operations"),
#endif
OPT_BOOLEAN(0, "float16", &g_options.enableFloat16, "Enable Float16 instructions (default on, use --no-float16)"),
OPT_BOOLEAN(0, "listAdapters", &g_options.listAdapters, "Enumerate the graphics adapters present in the system"),
OPT_BOOLEAN(0, "listCudaDevices", &g_options.listCudaDevices, "Enumerate the CUDA devices present in the system"),
#if NTC_WITH_VULKAN
OPT_BOOLEAN(0, "vk", &g_options.useVulkan, "Use Vulkan API for graphics operations"),
#endif
OPT_END()
};
static const char* usages[] = {
"ntc-cli [input-files|input-directory] <actions...> [options...]",
nullptr
};
struct argparse argparse {};
argparse_init(&argparse, options, usages, 0);
argparse_describe(&argparse,
"\n"
"Neural texture compression and decompression tool.\n"
"\n"
"Inputs can be specified as positional arguments, in one of four modes:\n"
" - Directory with image files (same as --loadImages)\n"
" - Individual image files (.png, .tga, .jpg, .jpeg, .exr)\n"
" - Manifest file with .json extension (same as --loadManifest)\n"
" - Compressed texture set with .ntc extension (same as --loadCompressed)\n"
"\n"
"For the manifest file schema, please refer to docs/Manifest.md in the SDK.",
nullptr);
argparse_parse(&argparse, argc, argv);
bool const useGapi = g_options.useVulkan || g_options.useDX12;
if (useGapi && g_options.listAdapters)
return true;
if (g_options.listCudaDevices || g_options.printVersion)
return true;
if (!useGapi && g_options.listAdapters)
{
fprintf(stderr, "--listAdapters requires either --dx12 or --vk.\n");
return false;
}
if (g_options.useVulkan && g_options.useDX12)
{
fprintf(stderr, "Options --vk and --dx12 cannot be used at the same time.\n");
return false;
}
if (!g_options.enableCoopVec)
{
g_options.enableCoopVecInt8 = false;
g_options.enableCoopVecFP8 = false;
}
// Process explicit inputs
if (g_options.loadImagesPath)
{
if (!fs::is_directory(g_options.loadImagesPath))
{
fprintf(stderr, "Input directory '%s' does not exist or is not a directory.\n", g_options.loadImagesPath);
return false;
}
UpdateToolInputType(g_options.inputType, ToolInputType::Directory);
}
if (g_options.loadManifestFileName)
{
if (!fs::exists(g_options.loadManifestFileName))
{
fprintf(stderr, "Manifest file '%s' does not exist.\n", g_options.loadManifestFileName);
return false;
}
UpdateToolInputType(g_options.inputType, ToolInputType::Manifest);
}
if (g_options.loadCompressedFileName)
{
if (!fs::exists(g_options.loadCompressedFileName))
{
fprintf(stderr, "Input file '%s' does not exist.\n", g_options.loadCompressedFileName);
return false;
}
UpdateToolInputType(g_options.inputType, ToolInputType::CompressedTextureSet);
}
// Process positional arguments and detect their input types
for (int i = 0; argparse.out[i]; ++i)
{
char const* arg = argparse.out[i];
if (!arg[0])
continue;
fs::path argPath = arg;
if (fs::is_directory(argPath))
{
UpdateToolInputType(g_options.inputType, ToolInputType::Directory);
g_options.loadImagesPath = arg;
}
else if (fs::exists(argPath))
{
std::string extension = argPath.extension().string();
LowercaseString(extension);
if (extension == ".json")
{
UpdateToolInputType(g_options.inputType, ToolInputType::Manifest);
g_options.loadManifestFileName = arg;
}
else if (extension == ".ntc")
{
UpdateToolInputType(g_options.inputType, ToolInputType::CompressedTextureSet);
g_options.loadCompressedFileName = arg;
}
else if (IsSupportedImageFileExtension(extension))
{
UpdateToolInputType(g_options.inputType, ToolInputType::Images);
g_options.loadImagesList.push_back(arg);
}
else
{
fprintf(stderr, "Unknown input file type '%s'.\n", extension.c_str());
return false;
}
}
else
{
fprintf(stderr, "The file or directory '%s' specified as a positional argument does not exist.\n", arg);
return false;
}
}
if (g_options.inputType == ToolInputType::None)
{
fprintf(stderr, "No inputs.\n");
return false;
}
if (g_options.inputType == ToolInputType::Mixed)
{
fprintf(stderr, "Cannot process inputs of mismatching types (image files, directories, manifests, "
"compressed texture sets) or multiple inputs of the same type except for images.\n");
return false;
}
g_options.benchmarkIterations = std::max(g_options.benchmarkIterations, 1);
if (g_options.compress && g_options.inputType == ToolInputType::CompressedTextureSet)
{
fprintf(stderr, "Cannot compress an already compressed texture set.\n");
return false;
}
if ((g_options.saveCompressedFileName || g_options.decompress) &&
!(g_options.compress || g_options.inputType == ToolInputType::CompressedTextureSet))
{
fprintf(stderr, "To use --decompress or --saveCompressed, either --compress or --loadCompressed must be used.\n");
return false;
}
if (g_options.saveImagesPath && (g_options.compress || g_options.inputType == ToolInputType::CompressedTextureSet))
{
// When saving images from a compressed texture set, --decompress is implied.
g_options.decompress = true;
}
if (g_options.generateMips && g_options.loadMips)
{
fprintf(stderr, "Options --generateMips and --loadMips cannot be used at the same time.\n");
return false;
}
if (g_options.generateMips && g_options.inputType == ToolInputType::CompressedTextureSet)
{
fprintf(stderr, "To use --generateMips, uncompressed images must be loaded first.\n");
return false;
}
if (g_options.optimizeBC && !useGapi)
{
fprintf(stderr, "Option --optimizeBC requires either --vk or --dx12.\n");
return false;
}
if (g_options.optimizeBC && !g_options.decompress)
{
fprintf(stderr, "Option --optimizeBC requires --decompress.\n");
return false;
}
if ((g_options.bcQuality < 0 || g_options.bcQuality > 255) && g_options.bcQuality != -1)
{
fprintf(stderr, "The --bcQuality value (%d) must be between 0 and 255.\n", g_options.bcQuality);
return false;
}
if (g_options.bcPsnrThreshold < 0.f || g_options.bcPsnrThreshold > 10.f)
{
fprintf(stderr, "The --bcPsnrThreshold value (%f) must be between 0 and 10.\n", g_options.bcPsnrThreshold);
return false;
}
if (g_options.matchBcPsnr && !std::isnan(g_options.targetPsnr))
{
fprintf(stderr, "The --targetPsnr and --matchBcPsnr options cannot be used at the same time.");
return false;
}
if ((g_options.matchBcPsnr || !std::isnan(g_options.targetPsnr)) && !g_options.compress)
{
fprintf(stderr, "The --targetPsnr or --matchBcPsnr options require --compress.");
return false;
}
if (g_options.matchBcPsnr && !useGapi)
{
fprintf(stderr, "The --matchBcPsnr option requires either --vk or --dx12 (where available).");
return false;
}
if (bcFormatString)
{
g_options.bcFormat = ParseBlockCompressedFormat(bcFormatString, /* enableAuto = */ true);
if (!g_options.bcFormat.has_value())
{
fprintf(stderr, "Invalid --bcFormat value '%s'.\n", bcFormatString);
return false;
}
}
if (imageFormatString)
{
auto parsedFormat = ParseImageContainer(imageFormatString);
if (parsedFormat.has_value())
{
g_options.imageFormat = parsedFormat.value();
}
else
{
fprintf(stderr, "Invalid --imageFormat value '%s'.\n", imageFormatString);
return false;
}
}
if (networkVersionString && !g_options.compress)
{
fprintf(stderr, "The --networkVersion option is only applicable when --compress is used.");
return false;
}
if (networkVersionString)
{
auto parsedVersion = ParseNetworkVersion(networkVersionString);
if (parsedVersion.has_value())
{
g_options.networkVersion = parsedVersion.value();
}
else
{
fprintf(stderr, "Invalid --networkVersion value '%s'.\n", networkVersionString);
return false;
}
}
if (dimensionsString)
{
int width = 0, height = 0;
if (sscanf(dimensionsString, "%dx%d", &width, &height) != 2)
{
fprintf(stderr, "Invalid format for --dimensions '%s', must be 'WxH' where W and H are integers.\n",
dimensionsString);
return false;
}
if (width <= 0 || height <= 0)
{
fprintf(stderr, "Invalid values specified in --dimensions (%dx%d), must be 1x1 or more.\n",
width, height);
return false;
}
g_options.customWidth = width;
g_options.customHeight = height;
}
if (g_options.saveCompressedFileName)
{
fs::path outputPath = fs::path(g_options.saveCompressedFileName).parent_path();
if (!outputPath.empty() && !fs::is_directory(outputPath) && !fs::create_directories(outputPath))
{
fprintf(stderr, "Failed to create directories for '%s'.\n", outputPath.generic_string().c_str());
return false;
}
}
if (g_options.saveImagesPath)
{
fs::path outputPath = fs::path(g_options.saveImagesPath);
if (!fs::is_directory(outputPath) && !fs::create_directories(outputPath))
{
fprintf(stderr, "Failed to create directories for '%s'.\n", g_options.saveImagesPath);
return false;
}
}
return true;
}
bool SaveImagesFromTextureSet(ntc::IContext* context, ntc::ITextureSet* textureSet)
{
const ntc::TextureSetDesc& textureSetDesc = textureSet->GetDesc();
fs::path const outputPath = g_options.saveImagesPath;
bool mipsDirCreated = false;
int numTextures = textureSet->GetTextureCount();
std::mutex mutex;
bool anyErrors = false;
const int mips = g_options.saveMips ? textureSetDesc.mips : 1;
for (int textureIndex = 0; textureIndex < numTextures; ++textureIndex)
{
ntc::ITextureMetadata* texture = textureSet->GetTexture(textureIndex);
assert(texture);
ntc::BlockCompressedFormat bcFormat = texture->GetBlockCompressedFormat();
if (bcFormat != ntc::BlockCompressedFormat::None)
continue;
if (!mipsDirCreated && g_options.saveMips && textureSetDesc.mips > 1)
{
fs::path mipsPath = outputPath / "mips";
if (!fs::is_directory(mipsPath) && !fs::create_directories(mipsPath))
{
fprintf(stderr, "Failed to create directory '%s'.\n", mipsPath.generic_string().c_str());
return false;
}
mipsDirCreated = true;
}
const char* textureName = texture->GetName();
int firstChannel = 0;
int numChannels = 0;
texture->GetChannels(firstChannel, numChannels);
ntc::ChannelFormat channelFormat = texture->GetChannelFormat();
ntc::ColorSpace rgbColorSpace = texture->GetRgbColorSpace();
ntc::ColorSpace const alphaColorSpace = texture->GetAlphaColorSpace();
ImageContainer container = g_options.imageFormat;
// Select the container from texture's channel format if it wasn't provided explicitly
if (container == ImageContainer::Auto)
{
if (channelFormat == ntc::ChannelFormat::FLOAT16 || channelFormat == ntc::ChannelFormat::FLOAT32)
container = ImageContainer::EXR;
else if (channelFormat == ntc::ChannelFormat::UNORM16)
container = ImageContainer::PNG16;
else
container = ImageContainer::PNG;
}
// Pick the channel format suitable for our container
channelFormat = GetContainerChannelFormat(container);
// EXR uses linear data, request that from NTC
if (container == ImageContainer::EXR)
rgbColorSpace = ntc::ColorSpace::Linear;
ntc::ColorSpace const colorSpaces[4] = { rgbColorSpace, rgbColorSpace, rgbColorSpace, alphaColorSpace };
size_t const bytesPerComponent = ntc::GetBytesPerPixelComponent(channelFormat);
for (int mip = 0; mip < mips; ++mip)
{
int mipWidth = std::max(1, textureSetDesc.width >> mip);
int mipHeight = std::max(1, textureSetDesc.height >> mip);
size_t const mipDataSize = size_t(mipWidth) * size_t(mipHeight) * size_t(numChannels) * bytesPerComponent;
uint8_t* data = (uint8_t*)malloc(mipDataSize);
ntc::ReadChannelsParameters params;
params.page = ntc::TextureDataPage::Output;
params.mipLevel = mip;
params.firstChannel = firstChannel;
params.numChannels = numChannels;
params.pOutData = data;
params.addressSpace = ntc::AddressSpace::Host;
params.width = mipWidth;
params.height = mipHeight;
params.pixelStride = size_t(numChannels) * bytesPerComponent;
params.rowPitch = size_t(numChannels * mipWidth) * bytesPerComponent;
params.channelFormat = channelFormat;
params.dstColorSpaces = colorSpaces;
params.useDithering = true;
ntc::Status ntcStatus = textureSet->ReadChannels(params);
if (ntcStatus != ntc::Status::Ok)
{
fprintf(stderr, "Failed to read texture data for texture %d (%s) MIP %d, code = %s: %s\n",
textureIndex, textureName, mip, ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
free(data);
return false;
}
std::string outputFileName;
if (g_options.saveMips && mip > 0)
{
outputFileName = (outputPath / "mips" / textureName).generic_string();
char mipStr[8];
snprintf(mipStr, sizeof(mipStr), ".%02d", mip);
outputFileName += mipStr;
}
else
{
outputFileName = (outputPath / textureName).generic_string();
}
outputFileName += GetContainerExtension(container);
StartAsyncTask([&mutex, container, outputFileName, mipWidth, mipHeight, numChannels, channelFormat, data, &anyErrors]()
{
bool success = SaveImageToContainer(container, data, mipWidth, mipHeight, numChannels, outputFileName.c_str());
// The rest of this function is interlocked with other threads
std::lock_guard lockGuard(mutex);
if (!success)
{
anyErrors = true;
fprintf(stderr, "Failed to write a texture into '%s'\n", outputFileName.c_str());
}
else
{
printf("Saved image '%s': %dx%d pixels, %d channels, %s.\n", outputFileName.c_str(),
mipWidth, mipHeight, numChannels, ntc::ChannelFormatToString(channelFormat));
}
free(data);
});
}
}
WaitForAllTasks();
if (anyErrors)
return false;
return true;
}
bool PickLatentShape(ntc::LatentShape& outShape)
{
if (!std::isnan(g_options.targetPsnr) || g_options.matchBcPsnr)
{
// When doing adaptive compression, start with an empty latent space because the first configuration
// will be given by the adaptive compression session.
outShape = ntc::LatentShape::Empty();
}
else if (!std::isnan(g_options.bitsPerPixel))
{
float selectedBpp = 0.f;
if (ntc::PickLatentShape(g_options.bitsPerPixel, g_options.networkVersion, selectedBpp, outShape) != ntc::Status::Ok)
{
fprintf(stderr, "Cannot select a latent shape for %.3f bpp.\n", g_options.bitsPerPixel);
return false;
}
printf("Selected latent shape for %.3f bpp: --gridSizeScale %d --highResFeatures %d --lowResFeatures %d "
"--highResQuantBits %d --lowResQuantBits %d\n", selectedBpp, outShape.gridSizeScale, outShape.highResFeatures, outShape.lowResFeatures,
outShape.highResQuantBits, outShape.lowResQuantBits);
}
else
{
outShape.highResFeatures = g_options.highResFeatures;
outShape.lowResFeatures = g_options.lowResFeatures;
outShape.gridSizeScale = g_options.gridSizeScale;
outShape.highResQuantBits = g_options.highResQuantBits;
outShape.lowResQuantBits = g_options.lowResQuantBits;
}
return true;
}
ntc::ITextureSet* LoadImages(ntc::IContext* context, Manifest const& manifest, bool manifestIsGenerated)
{
ntc::TextureSetDesc textureSetDesc{};
textureSetDesc.mips = 1;
ntc::LatentShape latentShape;
if (!PickLatentShape(latentShape))
return nullptr;
// Count the number of MIP 0 images in the manifest
int numMipZeroImages = 0;
for (auto const& entry : manifest.textures)
{
if (entry.mipLevel == 0)
++numMipZeroImages;
}
if (numMipZeroImages > NTC_MAX_CHANNELS)
{
if (g_options.loadImagesPath)
{
fprintf(stderr, "Too many images (%d) found in the input folder. At most %d channels are supported.\n"
"Note: when loading images from a folder, a single material with all images is created. "
"To load a material with only some images from a folder, use manifest files or specify each image "
"on the command line separately.",
int(manifest.textures.size()), NTC_MAX_CHANNELS);
}
else
{
fprintf(stderr, "Too many images (%d) specified in the manifest. At most %d channels are supported.\n",
int(manifest.textures.size()), NTC_MAX_CHANNELS);
}
return nullptr;
}
struct SourceImageData
{
int width = 0;
int height = 0;
int channels = 0;
int storedChannels = 0;
int alphaMaskChannel = -1;
int firstChannel = -1;
int manifestIndex = 0;
bool verticalFlip = false;
std::string channelSwizzle;
std::array<stbi_uc*, NTC_MAX_MIPS> data {};
std::string name;
ntc::ChannelFormat channelFormat = ntc::ChannelFormat::UNORM8;
ntc::BlockCompressedFormat bcFormat = ntc::BlockCompressedFormat::None;
bool isSRGB = false;
SourceImageData()
{ }
SourceImageData(SourceImageData& other) = delete;
SourceImageData(SourceImageData&& other) = delete;
~SourceImageData()
{
for (auto mipLevel : data)
{
if (mipLevel)
stbi_image_free((void*)mipLevel);
}
data.fill(nullptr);
}
};
std::vector<std::shared_ptr<SourceImageData>> images;
std::mutex mutex;
bool anyErrors = false;
// Load the base images (mip level 0)
int entryIndex = 0;
for (const auto& entry : manifest.textures)
{
if (entry.mipLevel > 0)
continue;
StartAsyncTask([&mutex, &images, entry, entryIndex, &textureSetDesc, &anyErrors]()
{
std::shared_ptr<SourceImageData> image = std::make_shared<SourceImageData>();
fs::path const fileName = entry.fileName;
std::string extension = fileName.extension().generic_string();
LowercaseString(extension);
if (extension == ".exr")
{
LoadEXR((float**)&image->data[0], &image->width, &image->height, entry.fileName.c_str(), nullptr);
image->channels = 4;
image->channelFormat = ntc::ChannelFormat::FLOAT32;
}
else
{
FILE* imageFile = fopen(entry.fileName.c_str(), "rb");
if (imageFile)
{
bool is16bit = stbi_is_16_bit_from_file(imageFile);
fseek(imageFile, 0, SEEK_SET);
if (is16bit)
{
image->data[0] = (stbi_uc*)stbi_load_from_file_16(imageFile, &image->width, &image->height, &image->channels, STBI_rgb_alpha);
image->channelFormat = ntc::ChannelFormat::UNORM16;
}
else
{
image->data[0] = stbi_load_from_file(imageFile, &image->width, &image->height, &image->channels, STBI_rgb_alpha);
image->channelFormat = ntc::ChannelFormat::UNORM8;
}
fclose(imageFile);
}
}
// The rest of this function is interlocked with other threads
std::lock_guard lockGuard(mutex);
if (!image->data[0])
{
fprintf(stderr, "Failed to read image '%s'.\n", entry.fileName.c_str());
anyErrors = true;
return;
}
image->name = entry.entryName;
image->isSRGB = entry.isSRGB;
image->bcFormat = entry.bcFormat;
image->firstChannel = entry.firstChannel;
image->manifestIndex = entryIndex;
image->verticalFlip = entry.verticalFlip;
printf("Loaded image '%s': %dx%d pixels, %d channels.\n", fileName.filename().generic_string().c_str(),
image->width, image->height, image->channels);
image->channelSwizzle = entry.channelSwizzle;
if (image->channelSwizzle.empty())
image->storedChannels = image->channels;
else
image->storedChannels = image->channelSwizzle.size();
// Find the alpha mask semantic in the manifest, store the channel index
for (ImageSemanticBinding const& binding : entry.semantics)
{
if (binding.label == SemanticLabel::AlphaMask)
{
image->alphaMaskChannel = binding.firstChannel; // Default value is -1 which means "none"
}
}
textureSetDesc.width = std::max(image->width, textureSetDesc.width);
textureSetDesc.height = std::max(image->height, textureSetDesc.height);
images.push_back(image);
});
++entryIndex;
}
WaitForAllTasks();
if (images.empty())
{
fprintf(stderr, "No images loaded, exiting.\n");
return nullptr;
}
// Validate the names of images if there are multiple channels.
if (images.size() > 1)
{
for (size_t i = 0; i < images.size() - 1 && !anyErrors; ++i)
{
for (size_t ii = i + 1; ii < images.size(); ++ii)
{
if (images[i]->name == images[ii]->name)
{
fprintf(stderr, "Multiple images have the same name '%s'.\n"
"Make sure that input files have different and non-empty names (before extension).\n",
images[i]->name.c_str());
anyErrors = true;
break;
}
}
}
}
if (anyErrors)
{
return nullptr;
}
// Auto-generate the semantics and sRGB flags after loading the images: this needs per-image channel counts
if (manifestIsGenerated)
{
std::vector<SemanticBinding> semantics;
for (auto& image : images)
{
// We don't (currently) need the global semantic table, but we do look fir the alpha mask below
semantics.clear();
GuessImageSemantics(image->name, image->channels, image->channelFormat, image->manifestIndex,
image->isSRGB, semantics);
// If one of the channels is the alpha mask, remember that
for (auto const& binding : semantics)
{
if (binding.label == SemanticLabel::AlphaMask)
image->alphaMaskChannel = binding.firstChannel;
}
}
}
// Load the other mips
for (const auto& entry : manifest.textures)
{
if (entry.mipLevel == 0)
continue;
auto found = std::find_if(images.begin(), images.end(), [&entry](std::shared_ptr<SourceImageData> const& image)
{ return image->name == entry.entryName; });
if (found == images.end())
continue;
std::shared_ptr<SourceImageData> const& image = *found;
textureSetDesc.mips = std::max(textureSetDesc.mips, entry.mipLevel + 1);
StartAsyncTask([&mutex, &image, entry, &anyErrors]()
{
const fs::path fileName = entry.fileName;
std::string extension = fileName.extension().generic_string();
LowercaseString(extension);
int width = 0, height = 0;
ntc::ChannelFormat format = ntc::ChannelFormat::UNORM8;
if (extension == ".exr")
{
LoadEXR((float**)&image->data[entry.mipLevel], &width, &height, fileName.generic_string().c_str(), nullptr);
format = ntc::ChannelFormat::FLOAT32;
}
else
{
FILE* imageFile = fopen(entry.fileName.c_str(), "rb");
if (imageFile)
{
bool is16bit = stbi_is_16_bit_from_file(imageFile);
fseek(imageFile, 0, SEEK_SET);
if (is16bit)
{
image->data[entry.mipLevel] = (stbi_uc*)stbi_load_from_file_16(imageFile, &width, &height, nullptr, STBI_rgb_alpha);
format = ntc::ChannelFormat::UNORM16;
}
else
{
image->data[entry.mipLevel] = stbi_load_from_file(imageFile, &width, &height, nullptr, STBI_rgb_alpha);
format = ntc::ChannelFormat::UNORM8;
}
fclose(imageFile);
}
}
// The rest of this function is interlocked with other threads
std::lock_guard lockGuard(mutex);
if (!image->data[entry.mipLevel])
{
fprintf(stderr, "Failed to read image '%s'.\n", fileName.generic_string().c_str());
anyErrors = true;
return;
}
if (format != image->channelFormat)
{
fprintf(stderr, "Image '%s' has pixel format (%s) that differs from the base MIP's pixel format (%s).\n",
fileName.generic_string().c_str(), ntc::ChannelFormatToString(format), ntc::ChannelFormatToString(image->channelFormat));
anyErrors = true;
return;
}
const int expectedWidth = std::max(1, image->width >> entry.mipLevel);
const int expectedHeight = std::max(1, image->height >> entry.mipLevel);
if (width != expectedWidth || height != expectedHeight)
{
fprintf(stderr, "Image '%s' has incorrect dimensions for MIP level %d: expected %dx%d, got %dx%d.\n",
fileName.generic_string().c_str(), entry.mipLevel, expectedWidth, expectedHeight, width, height);
anyErrors = true;
return;
}
printf("Loaded image '%s': %dx%d pixels.\n", fileName.filename().generic_string().c_str(),
width, height);
});
}
WaitForAllTasks();
if (anyErrors)
{
return nullptr;
}
// Remember the max size of the input textures to create a staging buffer of sufficient size.
ntc::TextureSetFeatures textureSetFeatures;
textureSetFeatures.stagingBytesPerPixel = sizeof(float) * 4; // We might have FLOAT32 data on reads
textureSetFeatures.stagingWidth = textureSetDesc.width;
textureSetFeatures.stagingHeight = textureSetDesc.height;
// Override the dimensions from the manifest or command line, if specified.
// Command line has higher priority.
textureSetDesc.width = g_options.customWidth.value_or(manifest.width.value_or(textureSetDesc.width));
textureSetDesc.height = g_options.customHeight.value_or(manifest.height.value_or(textureSetDesc.height));
if (textureSetDesc.width * 2 < textureSetFeatures.stagingWidth ||
textureSetDesc.height * 2 < textureSetFeatures.stagingHeight)
{
printf("Warning: Texture set dimensions (%dx%d) are less than 1/2 of the maximum input image dimensions "
"(%dx%d). The resize operation uses a 2x2 bilinear filter, which may produce low quality output.\n",
textureSetDesc.width, textureSetDesc.height,
textureSetFeatures.stagingWidth, textureSetFeatures.stagingHeight);
}
// Maybe not loading mips, but generating them later
if (g_options.generateMips)
{
textureSetDesc.mips = int(floorf(std::log2f(float(std::max(textureSetDesc.width, textureSetDesc.height)))) + 1);
}
// Verify that we have images for all mips
if (g_options.loadMips)
{
for (auto& image : images)
{
for (int mip = 0; mip < textureSetDesc.mips; ++mip)
{
if (!image->data[mip])