-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
742 lines (635 loc) · 24.7 KB
/
main.cpp
File metadata and controls
742 lines (635 loc) · 24.7 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
#include <iostream>
#include <vector>
#include <filesystem>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include "ispc_texcomp.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
/**
* Simple resize function for uint8 images
* Performs nearest-neighbor interpolation for image resizing
*/
void stbir_resize_uint8(const unsigned char *input_pixels, int input_w, int input_h, int input_stride_in_bytes,
unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,
int num_channels) {
for (int y = 0; y < output_h; y++) {
for (int x = 0; x < output_w; x++) {
int in_x = x * input_w / output_w;
int in_y = y * input_h / output_h;
int in_idx = (in_y * input_w + in_x) * num_channels;
int out_idx = (y * output_w + x) * num_channels;
for (int c = 0; c < num_channels; c++) {
output_pixels[out_idx + c] = input_pixels[in_idx + c];
}
}
}
}
namespace fs = std::filesystem;
// DDS file format constants
#define DDSD_CAPS 0x1
#define DDSD_HEIGHT 0x2
#define DDSD_WIDTH 0x4
#define DDSD_PIXELFORMAT 0x1000
#define DDSD_LINEARSIZE 0x80000
#define DDPF_FOURCC 0x4
#define DDSCAPS_TEXTURE 0x1000
/**
* DDS pixel format structure
* Defines the pixel format information for DDS files
*/
struct DDS_PIXELFORMAT {
uint32_t dwSize;
uint32_t dwFlags;
uint32_t dwFourCC;
uint32_t dwRGBBitCount;
uint32_t dwRBitMask;
uint32_t dwGBitMask;
uint32_t dwBBitMask;
uint32_t dwABitMask;
};
/**
* DDS header structure
* Contains the metadata for the DDS file format
*/
struct DDS_HEADER {
char magic[4];
uint32_t dwSize;
uint32_t dwFlags;
uint32_t dwHeight;
uint32_t dwWidth;
uint32_t dwPitchOrLinearSize;
uint32_t dwDepth;
uint32_t dwMipMapCount;
uint32_t dwReserved1[11];
DDS_PIXELFORMAT ddspf;
uint32_t dwCaps;
uint32_t dwCaps2;
uint32_t dwCaps3;
uint32_t dwCaps4;
uint32_t dwReserved2;
};
/**
* DX10 extension header structure
* Used for BC4, BC5, BC6H and BC7 formats
*/
struct DX10_HEADER {
uint32_t dxgiFormat;
uint32_t resourceDim;
uint32_t miscFlag;
uint32_t arraySize;
uint32_t miscFlags2;
};
/**
* Supported compression formats enum
*/
enum class CompressionFormat {
DXT1, // Legacy RGB (no alpha)
DXT5, // Legacy RGBA (with alpha)
BC4, // Single channel (red only)
BC5, // Two channel (red & green)
BC6H, // HDR
BC7 // High-quality RGBA
};
/**
* Checks if a number is a power of two
*/
bool isPowerOfTwo(int n) {
return (n & (n-1)) == 0 && n > 0;
}
/**
* Rounds a value up to the nearest multiple of 4
* Required for proper block compression alignment
*/
int roundToMultipleOf4(int value) {
return ((value + 3) & ~3);
}
/**
* Determines if the image is in HDR format based on file extension
*/
bool isHDRImage(const fs::path& path) {
const std::string ext = path.extension().string();
return (ext == ".hdr" || ext == ".exr");
}
/**
* Preprocesses the input image for compression
* - Loads the image from disk
* - Optionally converts to RGBA format
* - Resizes to dimensions divisible by 4
*/
unsigned char* preprocessImage(const fs::path& inputPath, int& width, int& height, bool forceRGBA) {
int channels;
unsigned char* inputData = nullptr;
stbi_set_flip_vertically_on_load(false);
if (forceRGBA) {
inputData = stbi_load(inputPath.string().c_str(), &width, &height, &channels, 4);
channels = 4; // force rgba
} else {
inputData = stbi_load(inputPath.string().c_str(), &width, &height, &channels, 0);
}
if (!inputData) {
std::cerr << "Error while loading: " << inputPath << std::endl;
std::cerr << "Reason: " << stbi_failure_reason() << std::endl;
return nullptr;
}
std::cout << "Loaded image: " << width << "x" << height
<< ", channels: " << channels << std::endl;
const int newWidth = roundToMultipleOf4(width);
int newHeight = roundToMultipleOf4(height);
if (newWidth != width || newHeight != height || (forceRGBA && channels != 4)) {
std::cout << "Resizing image from " << width << "x" << height
<< " to " << newWidth << "x" << newHeight;
if (forceRGBA && channels != 4)
std::cout << " and adding RGBA conversion";
std::cout << std::endl;
unsigned char* resizedData = new unsigned char[newWidth * newHeight * 4];
if (channels != 4) {
unsigned char* tempData = new unsigned char[width * height * 4];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int srcIdx = (y * width + x) * channels;
int dstIdx = (y * width + x) * 4;
for (int c = 0; c < channels; c++) {
tempData[dstIdx + c] = inputData[srcIdx + c];
}
if (channels == 3) {
tempData[dstIdx + 3] = 255; // Add alpha for RGB
}
else if (channels == 1) {
tempData[dstIdx + 1] = tempData[dstIdx]; // Copy R to G
tempData[dstIdx + 2] = tempData[dstIdx]; // Copy R to B
tempData[dstIdx + 3] = 255; // Full alpha
}
// For grayscale + alpha, duplicate grayscale for RGB
else if (channels == 2) {
tempData[dstIdx + 2] = tempData[dstIdx]; // Copy R to B
tempData[dstIdx + 1] = tempData[dstIdx]; // Copy R to G
tempData[dstIdx + 3] = inputData[srcIdx + 1]; // Use original alpha
}
}
}
stbir_resize_uint8(tempData, width, height, width * 4,
resizedData, newWidth, newHeight, newWidth * 4, 4);
delete[] tempData;
} else {
stbir_resize_uint8(inputData, width, height, width * 4,
resizedData, newWidth, newHeight, newWidth * 4, 4);
}
// Free original channels
stbi_image_free(inputData);
// Update dimensions
width = newWidth;
height = newHeight;
return resizedData;
}
// If already RGBA, return directly
if (channels == 4 || forceRGBA) {
return inputData;
}
// Otherwise convert to RGBA if needed
auto* rgbaData = new unsigned char[width * height * 4];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int srcIdx = (y * width + x) * channels;
int dstIdx = (y * width + x) * 4;
// Copy existing channels
for (int c = 0; c < channels; c++) {
rgbaData[dstIdx + c] = inputData[srcIdx + c];
}
// If RGB, set alpha to 255
if (channels == 3) {
rgbaData[dstIdx + 3] = 255;
}
// If grayscale, set RGB equal and alpha to 255
else if (channels == 1) {
rgbaData[dstIdx + 1] = rgbaData[dstIdx];
rgbaData[dstIdx + 2] = rgbaData[dstIdx];
rgbaData[dstIdx + 3] = 255;
}
// If grayscale + alpha, duplicate for RGB
else if (channels == 2) {
rgbaData[dstIdx + 2] = rgbaData[dstIdx];
rgbaData[dstIdx + 1] = rgbaData[dstIdx];
rgbaData[dstIdx + 3] = inputData[srcIdx + 1];
}
}
}
stbi_image_free(inputData);
return rgbaData;
}
//------------------------------------------------------------------------------
// SPECIFIC COMPRESSION FUNCTIONS
//------------------------------------------------------------------------------
/**
* Compresses image data using DXT1 format (BC1)
* 8 bytes per 4x4 block, no alpha
*/
void compressDXT1(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
size_t blockCount = ((surface->width + 3) / 4) * ((surface->height + 3) / 4);
compressedData.resize(blockCount * 8); // DXT1 uses 8 bytes per block
// CompressBlocksBC1 has a different signature, doesn't require settings in some versions
CompressBlocksBC1(surface, compressedData.data());
}
/**
* Compresses image data using BC6H format
* 16 bytes per 4x4 block, optimized for HDR content
*/
void compressBC6H(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
size_t blockCount = ((surface->width + 3) / 4) * ((surface->height + 3) / 4);
compressedData.resize(blockCount * 16); // (16 bytes per block)
bc6h_enc_settings settings{};
GetProfile_bc6h_veryfast(&settings);
CompressBlocksBC6H(surface, compressedData.data(), &settings);
}
/**
* Compresses image data using BC7 format
* 16 bytes per 4x4 block, high quality RGBA compression
*/
void compressBC7(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
size_t blockCount = ((surface->width + 3) / 4) * ((surface->height + 3) / 4);
compressedData.resize(blockCount * 16); // (16 bytes per block)
bc7_enc_settings settings{};
GetProfile_alpha_ultrafast(&settings);
CompressBlocksBC7(surface, compressedData.data(), &settings);
}
/**
* Compresses image data using DXT5 format (BC3)
* 16 bytes per 4x4 block, with alpha channel
*/
void compressDXT5(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
size_t blockCount = ((surface->width + 3) / 4) * ((surface->height + 3) / 4);
compressedData.resize(blockCount * 16); // DXT5 uses 16 bytes per block
CompressBlocksBC3(surface, compressedData.data());
}
/**
* Compresses image data using BC4 format
* 8 bytes per 4x4 block, single channel (R only)
*/
void compressBC4(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
size_t blockCount = ((surface->width + 3) / 4) * ((surface->height + 3) / 4);
compressedData.resize(blockCount * 8); // BC4 uses 8 bytes per block
// BC4 compresses only the red channel of the image
// No settings required, ISPC doesn't have GetProfile for BC4
CompressBlocksBC4(surface, compressedData.data());
}
/**
* Structure for BC5 block (16 bytes)
* Contains two BC4 blocks - one for R channel and one for G channel
*/
struct BC5Block {
// R Channel (BC4)
uint8_t redEndpoints[2]; // [0] = max, [1] = min (for both BC4 and BC5)
uint8_t redIndices[6]; // 3 bits per pixel, 16 pixels = 48 bits = 6 bytes
// G Channel (BC4) (same structure)
uint8_t greenEndpoints[2];
uint8_t greenIndices[6];
};
/**
* Compresses a single channel using BC4 format
* Used as a component of BC5 compression
*/
void compressBC4Channel(const uint8_t* channelData, uint8_t* endpoints, uint8_t* indices) {
// Each channel is 1 byte (0-255)
uint8_t minVal = 255; // Default for pixel with max value (1 byte FF)
uint8_t maxVal = 0; // Default for minimum value
// Find min and max values in 4x4 block of 16 pixels
for (int i = 0; i < 16; i++) {
minVal = std::min(minVal, channelData[i]);
maxVal = std::max(maxVal, channelData[i]);
}
/* For example, if we have:
*
* 128, 130, 135, 140
* 125, 127, 132, 138
* 120, 122, 126, 130
* 118, 119, 121, 125
* MAX = 140, MIN = 118
*
* NOTE: We're working with one channel at a time in BC4
*/
// Store max and min values as first two bytes (see documentation)
endpoints[0] = maxVal; // BC4 stores max first
endpoints[1] = minVal; // then min
// Create palette slots
uint8_t palette[8];
// BC4 has two interpretation modes (See docs: https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression#bc5)
// First mode (maxVal > minVal): 8 interpolated values
// Second mode (maxVal <= minVal): 6 interpolated values + transparent + black
palette[0] = maxVal;
palette[1] = minVal;
// Calculate interpolated values for the palette
// Based on Microsoft documentation
if (maxVal > minVal) {
palette[2] = (6 * maxVal + 1 * minVal) / 7;
palette[3] = (5 * maxVal + 2 * minVal) / 7;
palette[4] = (4 * maxVal + 3 * minVal) / 7;
palette[5] = (3 * maxVal + 4 * minVal) / 7;
palette[6] = (2 * maxVal + 5 * minVal) / 7;
palette[7] = (1 * maxVal + 6 * minVal) / 7;
} else {
palette[2] = (4 * maxVal + 1 * minVal) / 5;
palette[3] = (3 * maxVal + 2 * minVal) / 5;
palette[4] = (2 * maxVal + 3 * minVal) / 5;
palette[5] = (1 * maxVal + 4 * minVal) / 5;
palette[6] = 0; // Special value (0)
palette[7] = 255; // Special value (255)
}
// For each pixel in the block, find the closest palette index and save it
uint8_t pixelIndices[16];
for (int i = 0; i < 16; i++) {
int bestDistance = 256;
int bestIndex = 0;
for (int j = 0; j < 8; j++) {
int distance = std::abs(static_cast<int>(channelData[i]) - static_cast<int>(palette[j]));
if (distance < bestDistance) {
bestDistance = distance;
bestIndex = j;
}
}
pixelIndices[i] = bestIndex;
}
// At this point we have a matrix with indices corresponding to values max 7 (3 bits max)
// Index compression
memset(indices, 0, 6); // Clear indices array
// Pixel order map, expected pixel indices (first, second, etc.)
static const uint8_t pixelOrder[16] = {
0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15
}; // See documentation, labeled as a,b,c,d... NOTE LSB and MSB
// Pack indices into 6 bytes (48 bits)
for (int i = 0; i < 16; i++) {
int logicalIndex = pixelOrder[i];
uint8_t index = pixelIndices[logicalIndex];
// Calculate which byte and bit position to place the index
// Each index takes 3 bits, so calculate bits used before current index
int bitOffset = i * 3;
// Find byte offset (1 byte = 8 bits, so simple division)
int byteOffset = bitOffset / 8;
// Find position within the byte with modulo
int bitPosition = bitOffset % 8;
// Insert bits at the calculated position
indices[byteOffset] |= (index & 0x07) << bitPosition;
// If index extends beyond byte boundary, insert remaining bits
// into the next byte
if (bitPosition > 5) {
indices[byteOffset + 1] |= (index & 0x07) >> (8 - bitPosition);
}
}
}
/**
* Compresses a 4x4 block using BC5 format
*/
void compressBC5Block(const uint8_t* blockData, int stride, BC5Block* bc5Block) {
// Extract R and G channels from 4x4 block (BC5 has only R and G, B is calculated later)
uint8_t redChannel[16];
uint8_t greenChannel[16];
int pixelIndex = 0; // Extract channels
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) { // 4x4 block (16 pixels)
int offset = y * stride + x * 4;
redChannel[pixelIndex] = blockData[offset + 0]; // R
greenChannel[pixelIndex] = blockData[offset + 1]; // G
pixelIndex++;
}
}
// Compress each channel with BC4, CAUTION: Working at block level
compressBC4Channel(redChannel, bc5Block->redEndpoints, bc5Block->redIndices);
compressBC4Channel(greenChannel, bc5Block->greenEndpoints, bc5Block->greenIndices);
}
/**
* Compresses RGBA image with BC5 format
*/
void compressImageBC5(const uint8_t* imageData, int width, int height, int stride, std::vector<uint8_t>& compressedData) {
// Calculate how many 4x4 blocks we have (16 pixels each)
int blocksWidth = (width + 3) / 4;
int blocksHeight = (height + 3) / 4;
int blockCount = blocksWidth * blocksHeight;
// Resize output buffer to hold blocks
compressedData.resize(blockCount * sizeof(BC5Block));
BC5Block* outputBlocks = reinterpret_cast<BC5Block*>(compressedData.data());
// Process each block
for (int blockY = 0; blockY < blocksHeight; blockY++) {
for (int blockX = 0; blockX < blocksWidth; blockX++) {
// Find block start position
int blockStartX = blockX * 4;
int blockStartY = blockY * 4;
int blockStartOffset = blockStartY * stride + blockStartX * 4;
// Compress the block (which then compresses one channel at a time)
int blockIndex = blockY * blocksWidth + blockX;
compressBC5Block(imageData + blockStartOffset, stride, &outputBlocks[blockIndex]);
}
}
}
/**
* Wrapper function for BC5 compression
*/
bool compressBC5(const uint8_t* imageData, int width, int height, int stride, std::vector<uint8_t>& compressedData) {
// Sanity check
if (width <= 0 || height <= 0 || stride < width * 4 || imageData == nullptr) {
return false;
}
compressImageBC5(imageData, width, height, stride, compressedData);
return true;
}
/**
* Improved BC5 compression function that accepts rgba_surface
* Wrapper for compatibility with other compression functions
*/
void compressBC5Improved(const rgba_surface* surface, std::vector<uint8_t>& compressedData) {
compressBC5(surface->ptr, surface->width, surface->height, surface->stride, compressedData);
}
/**
* Creates a DDS header for the compressed data
*/
DDS_HEADER createDDSHeader(int width, int height, size_t compressedSize, CompressionFormat format) {
DDS_HEADER header = {};
memcpy(header.magic, "DDS ", 4);
header.dwSize = 124;
header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE;
header.dwHeight = height;
header.dwWidth = width;
header.dwPitchOrLinearSize = compressedSize;
header.dwMipMapCount = 1;
header.ddspf.dwSize = sizeof(DDS_PIXELFORMAT);
header.ddspf.dwFlags = DDPF_FOURCC;
switch(format) {
case CompressionFormat::DXT1:
header.ddspf.dwFourCC = ('D' | ('X' << 8) | ('T' << 16) | ('1' << 24)); // "DXT1"
break;
case CompressionFormat::DXT5:
header.ddspf.dwFourCC = ('D' | ('X' << 8) | ('T' << 16) | ('5' << 24)); // "DXT5"
break;
case CompressionFormat::BC4:
case CompressionFormat::BC5:
case CompressionFormat::BC6H:
case CompressionFormat::BC7:
header.ddspf.dwFourCC = ('D' | ('X' << 8) | ('1' << 16) | ('0' << 24)); // "DX10"
break;
}
header.dwCaps = DDSCAPS_TEXTURE;
return header;
}
/**
* Saves compressed data to a DDS file
*/
bool saveDDSFile(const fs::path& outputPath, const DDS_HEADER& header,
CompressionFormat format, const std::vector<uint8_t>& compressedData) {
// Create output directory
fs::create_directories(outputPath.parent_path());
// Open output file
FILE* f = fopen(outputPath.string().c_str(), "wb");
if (!f) {
std::cerr << "Error opening output file: " << outputPath << "\n";
return false;
}
// Write base header
fwrite(&header, sizeof(DDS_HEADER), 1, f);
// Add flags for DX10 formats
if (format != CompressionFormat::DXT1 && format != CompressionFormat::DXT5) {
uint32_t dxgiFormat;
switch (format) {
case CompressionFormat::BC4:
dxgiFormat = 80u; // DXGI_FORMAT_BC4_UNORM
break;
case CompressionFormat::BC5:
dxgiFormat = 83u; // DXGI_FORMAT_BC5_UNORM
break;
case CompressionFormat::BC6H:
dxgiFormat = 95u; // DXGI_FORMAT_BC6H_UF16
break;
case CompressionFormat::BC7:
default:
dxgiFormat = 98u; // DXGI_FORMAT_BC7_UNORM
break;
}
DX10_HEADER dx10Header = {
dxgiFormat,
3, // D3D10_RESOURCE_DIMENSION_TEXTURE2D
0, // No flags
1, // Single texture
0 // No misc flags
};
fwrite(&dx10Header, sizeof(DX10_HEADER), 1, f);
}
// Write compressed data
fwrite(compressedData.data(), compressedData.size(), 1, f);
fclose(f);
return true;
}
/**
* Main function to compress an image to DDS format
*/
bool compressImageToDDS(const fs::path& inputPath, const fs::path& outputPath, CompressionFormat format) {
try {
std::cout << "Compression: " << inputPath << " -> " << outputPath << std::endl;
// Determine if HDR, if so force export to BC6H (designed for HDR)
bool isHDR = isHDRImage(inputPath);
if (isHDR && format != CompressionFormat::BC6H) {
std::cout << "HDR image detected, automatically switching to BC6H" << std::endl;
format = CompressionFormat::BC6H;
}
// Preprocess image for compatibility, force 4 channels (extras will be discarded if needed)
int width, height;
unsigned char* imageData = preprocessImage(inputPath, width, height, true);
if (!imageData) {
return false;
}
// Prepare RGBA surface for processing
rgba_surface surface{};
surface.ptr = imageData;
surface.width = width;
surface.height = height;
surface.stride = width * 4;
// Compress image using requested format
std::vector<uint8_t> compressedData;
switch (format) {
case CompressionFormat::DXT1:
compressDXT1(&surface, compressedData);
std::cout << "DXT1 compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
case CompressionFormat::DXT5:
compressDXT5(&surface, compressedData);
std::cout << "DXT5 compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
case CompressionFormat::BC4:
compressBC4(&surface, compressedData);
std::cout << "BC4 compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
case CompressionFormat::BC5:
compressBC5Improved(&surface, compressedData);
std::cout << "BC5 compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
case CompressionFormat::BC6H:
compressBC6H(&surface, compressedData);
std::cout << "BC6H compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
case CompressionFormat::BC7:
compressBC7(&surface, compressedData);
std::cout << "BC7 compression completed (" << compressedData.size() << " bytes)" << std::endl;
break;
}
// Create header and save file
DDS_HEADER header = createDDSHeader(width, height, compressedData.size(), format);
bool success = saveDDSFile(outputPath, header, format, compressedData);
// Free memory
delete[] imageData;
return success;
} catch (const std::exception& e) {
std::cerr << "Error during compression: " << e.what() << std::endl;
return false;
}
}
/**
* Main entry point
*/
int main(int argc, char* argv[]) {
// Verify arguments
if (argc < 3) {
std::cerr << "Usage: ddscompressor <input_file> <output_file> [format]\n";
std::cerr << " format: dxt1, dxt5, bc4, bc5, bc6h, bc7 (default: bc7)\n";
return 1;
}
fs::path inputPath = argv[1];
fs::path outputPath = argv[2];
// Check if input file exists
if (!fs::exists(inputPath)) {
std::cerr << "Error: input file '" << inputPath << "' not found.\n";
return 1;
}
// Get format from command line
CompressionFormat format = CompressionFormat::BC7; // Default
if (argc > 3) {
std::string formatStr = argv[3];
std::transform(formatStr.begin(), formatStr.end(), formatStr.begin(), ::tolower);
if (formatStr == "dxt1") {
format = CompressionFormat::DXT1;
} else if (formatStr == "dxt5") {
format = CompressionFormat::DXT5;
} else if (formatStr == "bc4") {
format = CompressionFormat::BC4;
} else if (formatStr == "bc5") {
format = CompressionFormat::BC5;
} else if (formatStr == "bc6h") {
format = CompressionFormat::BC6H;
} else if (formatStr == "bc7") {
format = CompressionFormat::BC7;
} else {
std::cerr << "Invalid format: " << formatStr << ". Using bc7...\n";
}
}
// Add dds extension if not present
if (outputPath.extension() != ".dds") {
outputPath = outputPath.string() + ".dds";
}
bool success = compressImageToDDS(inputPath, outputPath, format);
if (success) {
std::cout << "Compression completed successfully: " << outputPath << std::endl;
return 0;
}
std::cerr << "Error during compression.\n";
return 1;
}