forked from KhronosGroup/KTX-Software
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtexture2.c
2353 lines (2153 loc) · 83.7 KB
/
texture2.c
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
/* -*- tab-width: 4; -*- */
/* vi: set sw=2 ts=4 expandtab: */
/*
* Copyright 2019-2020 The Khronos Group Inc.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @internal
* @file texture2.c
* @~English
*
* @brief ktxTexture2 implementation. Support for KTX2 format.
*
* @author Mark Callow, www.edgewise-consulting.com
*/
#if defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdlib.h>
#include <zstd.h>
#include <zstd_errors.h>
#include <KHR/khr_df.h>
#include "dfdutils/dfd.h"
#include "ktx.h"
#include "ktxint.h"
#include "stream.h"
#include "filestream.h"
#include "memstream.h"
#include "texture2.h"
#include "uthash.h"
#include "vk_format.h"
// FIXME: Test this #define and put it in a header somewhere.
//#define IS_BIG_ENDIAN (1 == *(unsigned char *)&(const int){0x01000000ul})
#define IS_BIG_ENDIAN 0
struct ktxTexture_vtbl ktxTexture2_vtbl;
struct ktxTexture_vtblInt ktxTexture2_vtblInt;
#if !defined(BITFIELD_ORDER_FROM_MSB)
// Most compilers, including all those tested so far, including clang, gcc
// and msvc, order bitfields from the lsb so these struct declarations work.
// Could this be because I've only tested on little-endian machines?
// These are preferred as they are much easier to manually initialize
// and verify.
struct sampleType {
uint32_t bitOffset: 16;
uint32_t bitLength: 8;
uint32_t channelType: 8; // Includes qualifiers
uint32_t samplePosition0: 8;
uint32_t samplePosition1: 8;
uint32_t samplePosition2: 8;
uint32_t samplePosition3: 8;
uint32_t lower;
uint32_t upper;
};
struct BDFD {
uint32_t vendorId: 17;
uint32_t descriptorType: 15;
uint32_t versionNumber: 16;
uint32_t descriptorBlockSize: 16;
uint32_t model: 8;
uint32_t primaries: 8;
uint32_t transfer: 8;
uint32_t flags: 8;
uint32_t texelBlockDimension0: 8;
uint32_t texelBlockDimension1: 8;
uint32_t texelBlockDimension2: 8;
uint32_t texelBlockDimension3: 8;
uint32_t bytesPlane0: 8;
uint32_t bytesPlane1: 8;
uint32_t bytesPlane2: 8;
uint32_t bytesPlane3: 8;
uint32_t bytesPlane4: 8;
uint32_t bytesPlane5: 8;
uint32_t bytesPlane6: 8;
uint32_t bytesPlane7: 8;
struct sampleType samples[6];
};
struct BDFD e5b9g9r9_ufloat_comparator = {
.vendorId = 0,
.descriptorType = 0,
.versionNumber = 2,
.descriptorBlockSize = sizeof(struct BDFD),
.model = KHR_DF_MODEL_RGBSDA,
.primaries = KHR_DF_PRIMARIES_BT709,
.transfer = KHR_DF_TRANSFER_LINEAR,
.flags = KHR_DF_FLAG_ALPHA_STRAIGHT,
.texelBlockDimension0 = 0,
.texelBlockDimension1 = 0,
.texelBlockDimension2 = 0,
.texelBlockDimension3 = 0,
.bytesPlane0 = 4,
.bytesPlane1 = 0,
.bytesPlane2 = 0,
.bytesPlane3 = 0,
.bytesPlane4 = 0,
.bytesPlane5 = 0,
.bytesPlane6 = 0,
.bytesPlane7 = 0,
.samples[0].bitOffset = 0,
.samples[0].bitLength = 8,
.samples[0].channelType = KHR_DF_CHANNEL_RGBSDA_RED,
.samples[0].samplePosition0 = 0,
.samples[0].samplePosition1 = 0,
.samples[0].samplePosition2 = 0,
.samples[0].samplePosition3 = 0,
.samples[0].lower = 0,
.samples[0].upper = 8448,
.samples[1].bitOffset = 27,
.samples[1].bitLength = 4,
.samples[1].channelType = KHR_DF_CHANNEL_RGBSDA_RED | KHR_DF_SAMPLE_DATATYPE_EXPONENT,
.samples[1].samplePosition0 = 0,
.samples[1].samplePosition1 = 0,
.samples[1].samplePosition2 = 0,
.samples[1].samplePosition3 = 0,
.samples[1].lower = 15,
.samples[1].upper = 31,
.samples[2].bitOffset = 9,
.samples[2].bitLength = 8,
.samples[2].channelType = KHR_DF_CHANNEL_RGBSDA_GREEN,
.samples[2].samplePosition0 = 0,
.samples[2].samplePosition1 = 0,
.samples[2].samplePosition2 = 0,
.samples[2].samplePosition3 = 0,
.samples[2].lower = 0,
.samples[2].upper = 8448,
.samples[3].bitOffset = 27,
.samples[3].bitLength = 4,
.samples[3].channelType = KHR_DF_CHANNEL_RGBSDA_GREEN | KHR_DF_SAMPLE_DATATYPE_EXPONENT,
.samples[3].samplePosition0 = 0,
.samples[3].samplePosition1 = 0,
.samples[3].samplePosition2 = 0,
.samples[3].samplePosition3 = 0,
.samples[3].lower = 15,
.samples[3].upper = 31,
.samples[4].bitOffset = 18,
.samples[4].bitLength = 8,
.samples[4].channelType = KHR_DF_CHANNEL_RGBSDA_BLUE,
.samples[4].samplePosition0 = 0,
.samples[4].samplePosition1 = 0,
.samples[4].samplePosition2 = 0,
.samples[4].samplePosition3 = 0,
.samples[4].lower = 0,
.samples[4].upper = 8448,
.samples[5].bitOffset = 27,
.samples[5].bitLength = 4,
.samples[5].channelType = KHR_DF_CHANNEL_RGBSDA_BLUE | KHR_DF_SAMPLE_DATATYPE_EXPONENT,
.samples[5].samplePosition0 = 0,
.samples[5].samplePosition1 = 0,
.samples[5].samplePosition2 = 0,
.samples[5].samplePosition3 = 0,
.samples[5].lower = 15,
.samples[5].upper = 31,
};
#else
// For compilers which order bitfields from the msb rather than lsb.
#define shift(x,val) ((val) << KHR_DF_SHIFT_ ## x)
#define sampleshift(x,val) ((val) << KHR_DF_SAMPLESHIFT_ ## x)
#define e5b9g9r9_bdbwordcount KHR_DFDSIZEWORDS(6)
ktx_uint32_t e5b9g9r9_ufloat_comparator[e5b9g9r9_bdbwordcount] = {
0, // descriptorType & vendorId
shift(DESCRIPTORBLOCKSIZE, e5b9g9r9_bdbwordcount * sizeof(ktx_uint32_t)) | shift(VERSIONNUMBER, 2),
// N.B. Allow various values of primaries, transfer & flags
shift(FLAGS, KHR_DF_FLAG_ALPHA_STRAIGHT) | shift(TRANSFER, KHR_DF_TRANSFER_LINEAR) | shift(PRIMARIES, KHR_DF_PRIMARIES_BT709) | shift(MODEL, KHR_DF_MODEL_RGBSDA),
0, // texelBlockDimension3~0
shift(BYTESPLANE0, 4), // All other bytesPlane fields are 0.
0, // bytesPlane7~4
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_RED) | sampleshift(BITLENGTH, 8) | sampleshift(BITOFFSET, 0),
0, // samplePosition3~0
0, // sampleLower
8448, // sampleUpper
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_RED | KHR_DF_SAMPLE_DATATYPE_EXPONENT) | sampleshift(BITLENGTH, 4) | sampleshift(BITOFFSET, 27),
0, // samplePosition3~0
15, // sampleLower
31, // sampleUpper
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_GREEN) | sampleshift(BITLENGTH, 8) | sampleshift(BITOFFSET, 9),
0, // samplePosition3~0
0, // sampleLower
8448, // sampleUpper
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_GREEN | KHR_DF_SAMPLE_DATATYPE_EXPONENT) | sampleshift(BITLENGTH, 4) | sampleshift(BITOFFSET, 27),
0, // samplePosition3~0
15, // sampleLower
31, // sampleUpper
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_BLUE) | sampleshift(BITLENGTH, 8) | sampleshift(BITOFFSET, 18),
0, // samplePosition3~0
0, // sampleLower
8448, // sampleUpper
sampleshift(CHANNELID, KHR_DF_CHANNEL_RGBSDA_BLUE | KHR_DF_SAMPLE_DATATYPE_EXPONENT) | sampleshift(BITLENGTH, 4) | sampleshift(BITOFFSET, 27),
0, // samplePosition3~0
15, // sampleLower
31, // sampleUpper
};
#endif
/**
* @private
* @~English
* @brief Initialize a ktxFormatSize object from the info in a DFD.
*
* This is used instead of referring to the DFD directly so code dealing
* with format info can be common to KTX 1 & 2.
*
* @param[in] This pointer the ktxTexture2 whose DFD to use.
* @param[in] fi pointer to the ktxFormatSize object to initialize.
*
* @return KTX_TRUE on success, otherwise KTX_FALSE.
*/
bool
ktxFormatSize_initFromDfd(ktxFormatSize* This, ktx_uint32_t* pDfd)
{
bool notDepthStencil = false;
uint32_t* pBdb = pDfd + 1;
// Check the DFD is of the expected type and version.
if (*pBdb != 0) {
// Either decriptorType or vendorId is not 0
return false;
}
if (KHR_DFDVAL(pBdb, VERSIONNUMBER) != KHR_DF_VERSIONNUMBER_1_3) {
return false;
}
// DFD has supported type and version. Process it.
This->blockWidth = KHR_DFDVAL(pBdb, TEXELBLOCKDIMENSION0) + 1;
This->blockHeight = KHR_DFDVAL(pBdb, TEXELBLOCKDIMENSION1) + 1;
This->blockDepth = KHR_DFDVAL(pBdb, TEXELBLOCKDIMENSION2) + 1;
This->blockSizeInBits = KHR_DFDVAL(pBdb, BYTESPLANE0) * 8;
This->paletteSizeInBits = 0; // No paletted formats in ktx v2.
This->flags = 0;
if (KHR_DFDVAL(pBdb, MODEL) >= KHR_DF_MODEL_DXT1A) {
// A block compressed format. Entire block is a single sample.
This->flags |= KTX_FORMAT_SIZE_COMPRESSED_BIT;
} else {
// An uncompressed format.
// Special case depth & depth stencil formats
if (KHR_DFDSVAL(pBdb, 0, CHANNELID) == KHR_DF_CHANNEL_RGBSDA_DEPTH) {
if (KHR_DFDSAMPLECOUNT(pBdb) == 1) {
This->flags |= KTX_FORMAT_SIZE_DEPTH_BIT;
} else if (KHR_DFDSAMPLECOUNT(pBdb) == 2) {
This->flags |= KTX_FORMAT_SIZE_STENCIL_BIT;
This->flags |= KTX_FORMAT_SIZE_DEPTH_BIT;
This->flags |= KTX_FORMAT_SIZE_PACKED_BIT;
} else {
return false;
}
} else if (KHR_DFDSVAL(pBdb, 0, CHANNELID) == KHR_DF_CHANNEL_RGBSDA_STENCIL) {
This->flags |= KTX_FORMAT_SIZE_STENCIL_BIT;
} else if (KHR_DFDSAMPLECOUNT(pBdb) == 6
#if !defined(BITFIELD_ORDER_FROM_MSB)
&& !memcmp(((uint32_t*)&e5b9g9r9_ufloat_comparator) + KHR_DF_WORD_TEXELBLOCKDIMENSION0, &pBdb[KHR_DF_WORD_TEXELBLOCKDIMENSION0], sizeof(e5b9g9r9_ufloat_comparator)-(KHR_DF_WORD_TEXELBLOCKDIMENSION0)*sizeof(uint32_t))) {
#else
&& !memcmp(&e5b9g9r9_ufloat_comparator[KHR_DF_WORD_TEXELBLOCKDIMENSION0], &pBdb[KHR_DF_WORD_TEXELBLOCKDIMENSION0], sizeof(e5b9g9r9_ufloat_comparator)-(KHR_DF_WORD_TEXELBLOCKDIMENSION0)*sizeof(uint32_t))) {
#endif
// Special case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 as interpretDFD
// only handles "simple formats", i.e. where channels are described
// in contiguous bits.
This->flags |= KTX_FORMAT_SIZE_PACKED_BIT;
} else {
InterpretedDFDChannel rgba[4];
uint32_t wordBytes;
enum InterpretDFDResult result;
result = interpretDFD(pDfd, &rgba[0], &rgba[1], &rgba[2], &rgba[3],
&wordBytes);
if (result >= i_UNSUPPORTED_ERROR_BIT)
return false;
if (result & i_PACKED_FORMAT_BIT)
This->flags |= KTX_FORMAT_SIZE_PACKED_BIT;
}
}
if (This->blockSizeInBits == 0) {
// The DFD shows a supercompressed texture. Complete the ktxFormatSize
// struct by figuring out the post inflation value for bytesPlane0.
// Setting it here simplifies stuff later in this file. Setting the
// post inflation block size here will not cause any problems for
// the following reasons. (1) in v2 files levelIndex is always used to
// calculate data size and, of course, for the level offsets. (2) Finer
// grain access to supercompressed data than levels is not possible.
uint32_t blockByteLength;
recreateBytesPlane0FromSampleInfo(pDfd, &blockByteLength);
This->blockSizeInBits = blockByteLength * 8;
}
return true;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Do the part of ktxTexture2 construction that is common to
* new textures and those constructed from a stream.
*
* @param[in] This pointer to a ktxTexture2-sized block of memory to
* initialize.
* @param[in] numLevels the number of levels the texture must have.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
* @exception KTX_OUT_OF_MEMORY Not enough memory for the texture data.
*/
static KTX_error_code
ktxTexture2_constructCommon(ktxTexture2* This, ktx_uint32_t numLevels)
{
assert(This != NULL);
ktx_size_t privateSize;
This->classId = ktxTexture2_c;
This->vtbl = &ktxTexture2_vtbl;
This->_protected->_vtbl = ktxTexture2_vtblInt;
privateSize = sizeof(ktxTexture2_private)
+ sizeof(ktxLevelIndexEntry) * (numLevels - 1);
This->_private = (ktxTexture2_private*)malloc(privateSize);
if (This->_private == NULL) {
return KTX_OUT_OF_MEMORY;
}
memset(This->_private, 0, privateSize);
return KTX_SUCCESS;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a new, empty, ktxTexture2.
*
* @param[in] This pointer to a ktxTexture2-sized block of memory to
* initialize.
* @param[in] createInfo pointer to a ktxTextureCreateInfo struct with
* information describing the texture.
* @param[in] storageAllocation
* enum indicating whether or not to allocate storage
* for the texture images.
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
* @exception KTX_OUT_OF_MEMORY Not enough memory for the texture or image data.
* @exception KTX_UNSUPPORTED_TEXTURE_TYPE
* The request VkFormat is one of the
* prohibited formats.
*/
static KTX_error_code
ktxTexture2_construct(ktxTexture2* This, ktxTextureCreateInfo* createInfo,
ktxTextureCreateStorageEnum storageAllocation)
{
ktxFormatSize formatSize;
KTX_error_code result;
memset(This, 0, sizeof(*This));
if (createInfo->vkFormat != VK_FORMAT_UNDEFINED) {
This->pDfd = vk2dfd(createInfo->vkFormat);
if (!This->pDfd)
return KTX_INVALID_VALUE; // Format is unknown or unsupported.
#ifdef _DEBUG
// If this fires, an unsupported format or incorrect DFD
// has crept into vk2dfd.
assert(ktxFormatSize_initFromDfd(&formatSize, This->pDfd));
#else
(void)ktxFormatSize_initFromDfd(&formatSize, This->pDfd);
#endif
} else {
// TODO: Validate createInfo->pDfd.
This->pDfd = (ktx_uint32_t*)malloc(*createInfo->pDfd);
if (!This->pDfd)
return KTX_OUT_OF_MEMORY;
memcpy(This->pDfd, createInfo->pDfd, *createInfo->pDfd);
if (ktxFormatSize_initFromDfd(&formatSize, This->pDfd)) {
result = KTX_UNSUPPORTED_TEXTURE_TYPE;
goto cleanup;
}
}
result = ktxTexture_construct(ktxTexture(This), createInfo, &formatSize);
if (result != KTX_SUCCESS)
return result;
result = ktxTexture2_constructCommon(This, createInfo->numLevels);
if (result != KTX_SUCCESS)
goto cleanup;;
This->vkFormat = createInfo->vkFormat;
// Ideally we'd set all these things in ktxFormatSize_initFromDfd
// but This->_protected is not allocated until ktxTexture_construct;
if (This->isCompressed)
This->_protected->_typeSize = 1;
else if (formatSize.flags & KTX_FORMAT_SIZE_PACKED_BIT)
This->_protected->_typeSize = formatSize.blockSizeInBits / 8;
else if (formatSize.flags & (KTX_FORMAT_SIZE_DEPTH_BIT | KTX_FORMAT_SIZE_STENCIL_BIT)) {
if (createInfo->vkFormat == VK_FORMAT_D16_UNORM_S8_UINT)
This->_protected->_typeSize = 2;
else
This->_protected->_typeSize = 4;
} else {
// Unpacked and uncompressed
uint32_t numComponents;
getDFDComponentInfoUnpacked(This->pDfd, &numComponents,
&This->_protected->_typeSize);
}
This->supercompressionScheme = KTX_SS_NONE;
This->_private->_requiredLevelAlignment
= ktxTexture2_calcRequiredLevelAlignment(This);
// Create levelIndex. Offsets are from start of the KTX2 stream.
ktxLevelIndexEntry* levelIndex = This->_private->_levelIndex;
ktx_uint32_t levelIndexSize;
This->_private->_firstLevelFileOffset = 0;
levelIndexSize = sizeof(ktxLevelIndexEntry) * This->numLevels;
for (ktx_uint32_t level = 0; level < This->numLevels; level++) {
levelIndex[level].uncompressedByteLength =
ktxTexture_calcLevelSize(ktxTexture(This), level,
KTX_FORMAT_VERSION_TWO);
levelIndex[level].byteLength =
levelIndex[level].uncompressedByteLength;
levelIndex[level].byteOffset =
ktxTexture_calcLevelOffset(ktxTexture(This), level);
}
// Allocate storage, if requested.
if (storageAllocation == KTX_TEXTURE_CREATE_ALLOC_STORAGE) {
This->dataSize
= ktxTexture_calcDataSizeTexture(ktxTexture(This));
This->pData = malloc(This->dataSize);
if (This->pData == NULL) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
}
return result;
cleanup:
ktxTexture2_destruct(This);
return result;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture by copying a source ktxTexture.
*
* @param[in] This pointer to a ktxTexture2-sized block of memory to
* initialize.
* @param[in] orig pointer to the source texture to copy.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_OUT_OF_MEMORY Not enough memory for the texture data.
*/
static KTX_error_code
ktxTexture2_constructCopy(ktxTexture2* This, ktxTexture2* orig)
{
KTX_error_code result;
memcpy(This, orig, sizeof(ktxTexture2));
// Zero all the pointers to make error handling easier
This->_protected = NULL;
This->_private = NULL;
This->pDfd = NULL;
This->kvData = NULL;
This->kvDataHead = NULL;
This->pData = NULL;
This->_protected =
(ktxTexture_protected*)malloc(sizeof(ktxTexture_protected));
if (!This->_protected)
return KTX_OUT_OF_MEMORY;
// Must come before memcpy of _protected so as to close an active stream.
if (!orig->pData && ktxTexture_isActiveStream((ktxTexture*)orig))
ktxTexture2_LoadImageData(orig, NULL, 0);
memcpy(This->_protected, orig->_protected, sizeof(ktxTexture_protected));
ktx_size_t privateSize = sizeof(ktxTexture2_private)
+ sizeof(ktxLevelIndexEntry) * (orig->numLevels - 1);
This->_private = (ktxTexture2_private*)malloc(privateSize);
if (This->_private == NULL) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
memcpy(This->_private, orig->_private, privateSize);
if (orig->_private->_sgdByteLength > 0) {
This->_private->_supercompressionGlobalData
= (ktx_uint8_t*)malloc(orig->_private->_sgdByteLength);
if (!This->_private->_supercompressionGlobalData) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
memcpy(This->_private->_supercompressionGlobalData,
orig->_private->_supercompressionGlobalData,
orig->_private->_sgdByteLength);
}
This->pDfd = (ktx_uint32_t*)malloc(*orig->pDfd);
if (!This->pDfd) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
memcpy(This->pDfd, orig->pDfd, *orig->pDfd);
if (orig->kvDataHead) {
ktxHashList_ConstructCopy(&This->kvDataHead, orig->kvDataHead);
} else if (orig->kvData) {
This->kvData = (ktx_uint8_t*)malloc(orig->kvDataLen);
if (!This->kvData) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
memcpy(This->kvData, orig->kvData, orig->kvDataLen);
}
// Can't share the image data as the data pointer is exposed in the
// ktxTexture2 structure. Changing it to a ref-counted pointer would
// break code. Maybe that's okay as we're still pre-release. But,
// since this constructor will be mostly be used when transcoding
// supercompressed images, it is probably not too big a deal to make
// a copy of the data.
This->pData = (ktx_uint8_t*)malloc(This->dataSize);
if (This->pData == NULL) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
memcpy(This->pData, orig->pData, orig->dataSize);
return KTX_SUCCESS;
cleanup:
if (This->_protected) free(This->_protected);
if (This->_private) {
if (This->_private->_supercompressionGlobalData)
free(This->_private->_supercompressionGlobalData);
free(This->_private);
}
if (This->pDfd) free (This->pDfd);
if (This->kvDataHead) ktxHashList_Destruct(&This->kvDataHead);
return result;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture from a ktxStream reading from a KTX source.
*
* The KTX header, which must have been read prior to calling this, is passed
* to the function.
*
* The stream object is copied into the constructed ktxTexture2.
*
* The create flag KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT should not be set,
* if the ktxTexture is ultimately to be uploaded to OpenGL or Vulkan. This
* will minimize memory usage by allowing, for example, loading the images
* directly from the source into a Vulkan staging buffer.
*
* The create flag KTX_TEXTURE_CREATE_RAW_KVDATA_BIT should not be used. It is
* provided solely to enable implementation of the @e libktx v1 API on top of
* ktxTexture.
*
* If either KTX_TEXTURE_CREATE_SKIP_KVDATA_BIT or
* KTX_TEXTURE_CREATE_RAW_KVDATA_BIT is set then the ktxTexture's orientation
* fields will be set to defaults even if the KTX source contains
* KTXorientation metadata.
*
* @param[in] This pointer to a ktxTexture2-sized block of memory to
* initialize.
* @param[in] pStream pointer to the stream to read.
* @param[in] pHeader pointer to a KTX header that has already been read from
* the stream.
* @param[in] createFlags bitmask requesting specific actions during creation.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_FILE_DATA_ERROR
* Source data is inconsistent with the KTX
* specification.
* @exception KTX_FILE_READ_ERROR
* An error occurred while reading the source.
* @exception KTX_FILE_UNEXPECTED_EOF
* Not enough data in the source.
* @exception KTX_OUT_OF_MEMORY Not enough memory to load either the images or
* the key-value data.
* @exception KTX_UNKNOWN_FILE_FORMAT
* The source is not in KTX format.
* @exception KTX_UNSUPPORTED_TEXTURE_TYPE
* The source describes a texture type not
* supported by OpenGL or Vulkan, e.g, a 3D array.
*/
KTX_error_code
ktxTexture2_constructFromStreamAndHeader(ktxTexture2* This, ktxStream* pStream,
KTX_header2* pHeader,
ktxTextureCreateFlags createFlags)
{
ktxTexture2_private* private;
KTX_error_code result;
KTX_supplemental_info suppInfo;
ktxStream* stream;
ktx_size_t levelIndexSize;
assert(pHeader != NULL && pStream != NULL);
memset(This, 0, sizeof(*This));
result = ktxTexture_constructFromStream(ktxTexture(This), pStream,
createFlags);
if (result != KTX_SUCCESS)
return result;
result = ktxCheckHeader2_(pHeader, &suppInfo);
if (result != KTX_SUCCESS)
goto cleanup;
// ktxCheckHeader2_ has done the max(1, levelCount) on pHeader->levelCount.
result = ktxTexture2_constructCommon(This, pHeader->levelCount);
if (result != KTX_SUCCESS)
goto cleanup;
private = This->_private;
stream = ktxTexture2_getStream(This);
/*
* Initialize from pHeader->info.
*/
This->vkFormat = pHeader->vkFormat;
This->supercompressionScheme = pHeader->supercompressionScheme;
This->_protected->_typeSize = pHeader->typeSize;
// Can these be done by a ktxTexture_constructFromStream?
This->numDimensions = suppInfo.textureDimension;
This->baseWidth = pHeader->pixelWidth;
assert(suppInfo.textureDimension > 0 && suppInfo.textureDimension < 4);
switch (suppInfo.textureDimension) {
case 1:
This->baseHeight = This->baseDepth = 1;
break;
case 2:
This->baseHeight = pHeader->pixelHeight;
This->baseDepth = 1;
break;
case 3:
This->baseHeight = pHeader->pixelHeight;
This->baseDepth = pHeader->pixelDepth;
break;
}
if (pHeader->layerCount > 0) {
This->numLayers = pHeader->layerCount;
This->isArray = KTX_TRUE;
} else {
This->numLayers = 1;
This->isArray = KTX_FALSE;
}
This->numFaces = pHeader->faceCount;
if (pHeader->faceCount == 6)
This->isCubemap = KTX_TRUE;
else
This->isCubemap = KTX_FALSE;
// ktxCheckHeader2_ does the max(1, levelCount) and sets
// suppInfo.generateMipmaps when it was originally 0.
This->numLevels = pHeader->levelCount;
This->generateMipmaps = suppInfo.generateMipmaps;
// Read level index
levelIndexSize = sizeof(ktxLevelIndexEntry) * This->numLevels;
result = stream->read(stream, &private->_levelIndex, levelIndexSize);
if (result != KTX_SUCCESS)
goto cleanup;
// Rebase index to start of data and save file offset.
private->_firstLevelFileOffset
= private->_levelIndex[This->numLevels-1].byteOffset;
for (ktx_uint32_t level = 0; level < This->numLevels; level++) {
private->_levelIndex[level].byteOffset
-= private->_firstLevelFileOffset;
}
// Read DFD
This->pDfd =
(ktx_uint32_t*)malloc(pHeader->dataFormatDescriptor.byteLength);
if (!This->pDfd) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
result = stream->read(stream, This->pDfd,
pHeader->dataFormatDescriptor.byteLength);
if (result != KTX_SUCCESS)
goto cleanup;
if (!ktxFormatSize_initFromDfd(&This->_protected->_formatSize, This->pDfd)) {
result = KTX_UNSUPPORTED_TEXTURE_TYPE;
goto cleanup;
}
This->isCompressed = (This->_protected->_formatSize.flags & KTX_FORMAT_SIZE_COMPRESSED_BIT);
This->_private->_requiredLevelAlignment
= ktxTexture2_calcRequiredLevelAlignment(This);
// Make an empty hash list.
ktxHashList_Construct(&This->kvDataHead);
// Load KVData.
if (pHeader->keyValueData.byteLength > 0) {
if (!(createFlags & KTX_TEXTURE_CREATE_SKIP_KVDATA_BIT)) {
ktx_uint32_t kvdLen = pHeader->keyValueData.byteLength;
ktx_uint8_t* pKvd;
pKvd = malloc(kvdLen);
if (pKvd == NULL) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
result = stream->read(stream, pKvd, kvdLen);
if (result != KTX_SUCCESS)
goto cleanup;
if (IS_BIG_ENDIAN) {
/* Swap the counts inside the key & value data. */
ktx_uint8_t* src = pKvd;
ktx_uint8_t* end = pKvd + kvdLen;
while (src < end) {
ktx_uint32_t keyAndValueByteSize = *((ktx_uint32_t*)src);
_ktxSwapEndian32(&keyAndValueByteSize, 1);
src += _KTX_PAD4(keyAndValueByteSize);
}
}
if (!(createFlags & KTX_TEXTURE_CREATE_RAW_KVDATA_BIT)) {
char* orientationStr;
ktx_uint32_t orientationLen;
ktx_uint32_t animData[3];
ktx_uint32_t animDataLen;
result = ktxHashList_Deserialize(&This->kvDataHead,
kvdLen, pKvd);
free(pKvd);
if (result != KTX_SUCCESS) {
goto cleanup;
}
result = ktxHashList_FindValue(&This->kvDataHead,
KTX_ORIENTATION_KEY,
&orientationLen,
(void**)&orientationStr);
assert(result != KTX_INVALID_VALUE);
if (result == KTX_SUCCESS) {
// Length includes the terminating NUL.
if (orientationLen != This->numDimensions + 1) {
// There needs to be an entry for each dimension of
// the texture.
result = KTX_FILE_DATA_ERROR;
goto cleanup;
} else {
switch (This->numDimensions) {
case 3:
This->orientation.z = orientationStr[2];
case 2:
This->orientation.y = orientationStr[1];
case 1:
This->orientation.x = orientationStr[0];
}
}
} else {
result = KTX_SUCCESS; // Not finding orientation is okay.
}
result = ktxHashList_FindValue(&This->kvDataHead,
KTX_ANIMDATA_KEY,
&animDataLen,
(void**)animData);
assert(result != KTX_INVALID_VALUE);
if (result == KTX_SUCCESS) {
if (animDataLen != sizeof(animData)) {
result = KTX_FILE_DATA_ERROR;
goto cleanup;
}
if (This->isArray) {
This->isVideo = KTX_TRUE;
This->duration = animData[0];
This->timescale = animData[1];
This->loopcount = animData[2];
} else {
// animData is only valid for array textures.
result = KTX_FILE_DATA_ERROR;
goto cleanup;
}
} else {
result = KTX_SUCCESS; // Not finding video is okay.
}
} else {
This->kvDataLen = kvdLen;
This->kvData = pKvd;
}
} else {
stream->skip(stream, pHeader->keyValueData.byteLength);
}
}
if (pHeader->supercompressionGlobalData.byteLength > 0) {
// There could be padding here so seek to the next item.
(void)stream->setpos(stream,
pHeader->supercompressionGlobalData.byteOffset);
// Read supercompressionGlobalData
private->_supercompressionGlobalData =
(ktx_uint8_t*)malloc(pHeader->supercompressionGlobalData.byteLength);
if (!private->_supercompressionGlobalData) {
result = KTX_OUT_OF_MEMORY;
goto cleanup;
}
private->_sgdByteLength
= pHeader->supercompressionGlobalData.byteLength;
result = stream->read(stream, private->_supercompressionGlobalData,
private->_sgdByteLength);
if (result != KTX_SUCCESS)
goto cleanup;
}
// Calculate size of the image data. Level 0 is the last level in the data.
This->dataSize = private->_levelIndex[0].byteOffset
+ private->_levelIndex[0].byteLength;
/*
* Load the images, if requested.
*/
if (createFlags & KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT) {
result = ktxTexture2_LoadImageData(This, NULL, 0);
}
if (result != KTX_SUCCESS)
goto cleanup;
return result;
cleanup:
ktxTexture2_destruct(This);
return result;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture from a ktxStream reading from a KTX source.
*
* The stream object is copied into the constructed ktxTexture2.
*
* The create flag KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT should not be set,
* if the ktxTexture is ultimately to be uploaded to OpenGL or Vulkan. This
* will minimize memory usage by allowing, for example, loading the images
* directly from the source into a Vulkan staging buffer.
*
* The create flag KTX_TEXTURE_CREATE_RAW_KVDATA_BIT should not be used. It is
* provided solely to enable implementation of the @e libktx v1 API on top of
* ktxTexture.
*
* @param[in] This pointer to a ktxTexture2-sized block of memory to
* initialize.
* @param[in] pStream pointer to the stream to read.
* @param[in] createFlags bitmask requesting specific actions during creation.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_FILE_READ_ERROR
* An error occurred while reading the source.
*
* For other exceptions see ktxTexture2_constructFromStreamAndHeader().
*/
static KTX_error_code
ktxTexture2_constructFromStream(ktxTexture2* This, ktxStream* pStream,
ktxTextureCreateFlags createFlags)
{
KTX_header2 header;
KTX_error_code result;
// Read header.
result = pStream->read(pStream, &header, KTX2_HEADER_SIZE);
if (result != KTX_SUCCESS)
return result;
#if IS_BIG_ENDIAN
// byte swap the header
#endif
return ktxTexture2_constructFromStreamAndHeader(This, pStream,
&header, createFlags);
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture from a stdio stream reading from a KTX source.
*
* See ktxTextureInt_constructFromStream for details.
*
* @note Do not close the stdio stream until you are finished with the texture
* object.
*
* @param[in] This pointer to a ktxTextureInt-sized block of memory to
* initialize.
* @param[in] stdioStream a stdio FILE pointer opened on the source.
* @param[in] createFlags bitmask requesting specific actions during creation.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_INVALID_VALUE Either @p stdiostream or @p This is null.
*
* For other exceptions, see ktxTexture_constructFromStream().
*/
static KTX_error_code
ktxTexture2_constructFromStdioStream(ktxTexture2* This, FILE* stdioStream,
ktxTextureCreateFlags createFlags)
{
KTX_error_code result;
ktxStream stream;
if (stdioStream == NULL || This == NULL)
return KTX_INVALID_VALUE;
result = ktxFileStream_construct(&stream, stdioStream, KTX_FALSE);
if (result == KTX_SUCCESS)
result = ktxTexture2_constructFromStream(This, &stream, createFlags);
return result;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture from a named KTX file.
*
* See ktxTextureInt_constructFromStream for details.
*
* @param[in] This pointer to a ktxTextureInt-sized block of memory to
* initialize.
* @param[in] filename pointer to a char array containing the file name.
* @param[in] createFlags bitmask requesting specific actions during creation.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_FILE_OPEN_FAILED The file could not be opened.
* @exception KTX_INVALID_VALUE @p filename is @c NULL.
*
* For other exceptions, see ktxTexture_constructFromStream().
*/
static KTX_error_code
ktxTexture2_constructFromNamedFile(ktxTexture2* This,
const char* const filename,
ktxTextureCreateFlags createFlags)
{
KTX_error_code result;
ktxStream stream;
FILE* file;
if (This == NULL || filename == NULL)
return KTX_INVALID_VALUE;
file = fopen(filename, "rb");
if (!file)
return KTX_FILE_OPEN_FAILED;
result = ktxFileStream_construct(&stream, file, KTX_TRUE);
if (result == KTX_SUCCESS)
result = ktxTexture2_constructFromStream(This, &stream, createFlags);
return result;
}
/**
* @memberof ktxTexture2 @private
* @~English
* @brief Construct a ktxTexture from KTX-formatted data in memory.
*
* See ktxTextureInt_constructFromStream for details.
*
* @param[in] This pointer to a ktxTextureInt-sized block of memory to
* initialize.
* @param[in] bytes pointer to the memory containing the serialized KTX data.
* @param[in] size length of the KTX data in bytes.
* @param[in] createFlags bitmask requesting specific actions during creation.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*
* @exception KTX_INVALID_VALUE Either @p bytes is NULL or @p size is 0.
*
* For other exceptions, see ktxTexture_constructFromStream().
*/
static KTX_error_code
ktxTexture2_constructFromMemory(ktxTexture2* This,
const ktx_uint8_t* bytes, ktx_size_t size,
ktxTextureCreateFlags createFlags)
{
KTX_error_code result;
ktxStream stream;
if (bytes == NULL || size == 0)
return KTX_INVALID_VALUE;
result = ktxMemStream_construct_ro(&stream, bytes, size);
if (result == KTX_SUCCESS)
result = ktxTexture2_constructFromStream(This, &stream, createFlags);
return result;
}