Debian Codegraph @

example3/example3.cpp

raw
1 // File: example3.cpp - Demonstrates how to use crnlib's simple block compression
2 // API's to manually pack images to DXTn compressed .DDS files. This example isn't multithreaded
3 // so it's not going to be fast.
4 // Also note that this sample only demonstrates traditional/vanilla 4x4 DXTn block compression (not CRN).
5
6 // See Copyright Notice and license at the end of inc/crnlib.h
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <math.h>
10 #include <algorithm>
11
12 #if !defined(_WIN32)
13 #include <libgen.h>
14 #endif
15
16 // CRN transcoder library.
17 #include "crnlib.h"
18 // .DDS file format definitions.
19 #include "dds_defs.h"
20
21 #include "crn_core.h"
22 #include "crn_strutils.h"
23 #include "crn_file_utils.h"
24
25 // stb_image, for loading/saving image files.
26 #ifdef _MSC_VER
27 #pragma warning(disable : 4244) // conversion from 'int' to 'uint8', possible loss of data
28 #pragma warning(disable : 4100) // unreferenced formal parameter
29 #pragma warning(disable : 4127) // conditional expression is constant
30 #endif
31
32 #define STB_IMAGE_IMPLEMENTATION
33 #include "stb_image.h"
34 #define STB_IMAGE_WRITE_IMPLEMENTATION
35 #include "stb_image_write.h"
36
37 using namespace crnlib;
38
39 typedef unsigned int uint;
40
41 const uint cDXTBlockSize = 4;
42
43 static int print_usage() {
44 printf("Description: Simple .DDS DXTn block compression using crnlib.\n");
45 printf("Copyright (c) 2010-2016 Binomial LLC\n");
46 printf("Usage: example3 [source_file] [options]\n");
47 printf("\n");
48 printf("Note: This simple example is not multithreaded, so it's not going to be\n");
49 printf("particularly fast.\n");
50 printf("\n");
51 printf("Supported source image formats:\n");
52 printf("Baseline JPEG, PNG, BMP, TGA, PSD, and HDR\n");
53 printf("\nOptions:\n");
54 printf("-out filename - Force output filename (always use .DDS extension).\n");
55 printf("-nonsrgb - Input is not sRGB: disables gamma filtering, perceptual metrics.\n");
56 printf("-pixelformat X - Output DXTn format. Supported formats:\n");
57 printf("DXT1, DXT3, DXT5, DXN_XY (ATI 3DC), DXN_YX (ATI 3DC), DXT5A (ATN1N)\n");
58 printf("If no output pixel format is specified, this example uses either DXT1 or DXT5.\n");
59 printf("-dxtquality X - DXTn quality: superfast, fast, normal, better, uber (default)\n");
60 printf("-setalphatoluma - Set alpha channel to luma before compression.\n");
61 printf("-converttoluma - Set RGB to luma before compression.\n");
62 return EXIT_FAILURE;
63 }
64
65 static int error(const char* pMsg, ...) {
66 va_list args;
67 va_start(args, pMsg);
68 char buf[512];
69 crnlib_vsnprintf(buf, sizeof(buf), pMsg, args);
70 va_end(args);
71 printf("%s", buf);
72 return EXIT_FAILURE;
73 }
74
75 int main(int argc, char* argv[]) {
76 printf("example3 - Version v%u.%02u Built " __DATE__ ", " __TIME__ "\n", CRNLIB_VERSION / 100, CRNLIB_VERSION % 100);
77
78 if (argc < 2)
79 return print_usage();
80
81 // Parse command line options
82 const char* pSrc_filename = argv[1];
83 char out_filename[FILENAME_MAX] = {'\0'};
84 crn_format fmt = cCRNFmtInvalid;
85 bool srgb_colorspace = true;
86 crn_dxt_quality dxt_quality = cCRNDXTQualityUber; // best quality, but slowest
87 bool set_alpha_to_luma = false;
88 bool convert_to_luma = false;
89
90 for (int i = 2; i < argc; i++) {
91 if (argv[i][0] == '/')
92 argv[i][0] = '-';
93
94 if (!crnlib_stricmp(argv[i], "-out")) {
95 if (++i >= argc)
96 return error("Expected output filename!");
97
98 strcpy_safe(out_filename, sizeof(out_filename), argv[i]);
99 } else if (!crnlib_stricmp(argv[i], "-nonsrgb"))
100 srgb_colorspace = false;
101 else if (!crnlib_stricmp(argv[i], "-pixelformat")) {
102 if (++i >= argc)
103 return error("Expected pixel format!");
104
105 uint f;
106 for (f = 0; f < cCRNFmtTotal; f++) {
107 crn_format actual_fmt = crn_get_fundamental_dxt_format(static_cast<crn_format>(f));
108 if (!crnlib_stricmp(argv[i], crn_get_format_string(actual_fmt))) {
109 fmt = actual_fmt;
110 break;
111 }
112 }
113 if (f == cCRNFmtTotal)
114 return error("Unrecognized pixel format: %s\n", argv[i]);
115 } else if (!crnlib_stricmp(argv[i], "-dxtquality")) {
116 if (++i >= argc)
117 return error("Expected DXTn quality!\n");
118
119 uint q;
120 for (q = 0; q < cCRNDXTQualityTotal; q++) {
121 if (!crnlib_stricmp(argv[i], crn_get_dxt_quality_string(static_cast<crn_dxt_quality>(q)))) {
122 dxt_quality = static_cast<crn_dxt_quality>(q);
123 break;
124 }
125 }
126 if (q == cCRNDXTQualityTotal)
127 return error("Unrecognized DXTn quality: %s\n", argv[i]);
128 } else if (!crnlib_stricmp(argv[i], "-setalphatoluma"))
129 set_alpha_to_luma = true;
130 else if (!crnlib_stricmp(argv[i], "-converttoluma"))
131 convert_to_luma = true;
132 else
133 return error("Invalid option: %s\n", argv[i]);
134 }
135
136 // Split the source filename into its various components.
137 dynamic_string drive, dir, fname, ext;
138 if (!file_utils::split_path(pSrc_filename, &drive, &dir, &fname, &ext))
139 return error("Invalid source filename!\n");
140
141 // Load the source image into memory.
142 printf("Loading source file: %s\n", pSrc_filename);
143 int width, height, actual_comps;
144 crn_uint32* pSrc_image = (crn_uint32*)stbi_load(pSrc_filename, &width, &height, &actual_comps, 4);
145 if (!pSrc_image)
146 return error("Unable to read source file\n");
147
148 if (fmt == cCRNFmtInvalid) {
149 // Format not specified - automatically choose the DXTn format.
150 fmt = (actual_comps > 3) ? cCRNFmtDXT5 : cCRNFmtDXT1;
151 }
152
153 if ((fmt == cCRNFmtDXT5A) && (actual_comps <= 3))
154 set_alpha_to_luma = true;
155
156 if ((set_alpha_to_luma) || (convert_to_luma)) {
157 for (int i = 0; i < width * height; i++) {
158 crn_uint32 r = pSrc_image[i] & 0xFF, g = (pSrc_image[i] >> 8) & 0xFF, b = (pSrc_image[i] >> 16) & 0xFF;
159 // Compute CCIR 601 luma.
160 crn_uint32 y = (19595U * r + 38470U * g + 7471U * b + 32768) >> 16U;
161 crn_uint32 a = (pSrc_image[i] >> 24) & 0xFF;
162 if (set_alpha_to_luma)
163 a = y;
164 if (convert_to_luma) {
165 r = y;
166 g = y;
167 b = y;
168 }
169 pSrc_image[i] = r | (g << 8) | (b << 16) | (a << 24);
170 }
171 }
172
173 printf("Source Dimensions: %ux%u, Actual Components: %u\n", width, height, actual_comps);
174
175 const uint num_blocks_x = (width + cDXTBlockSize - 1) / cDXTBlockSize;
176 const uint num_blocks_y = (height + cDXTBlockSize - 1) / cDXTBlockSize;
177 const uint bytes_per_block = crn_get_bytes_per_dxt_block(fmt);
178 const uint total_compressed_size = num_blocks_x * num_blocks_y * bytes_per_block;
179
180 printf("Block Dimensions: %ux%u, BytesPerBlock: %u, Total Compressed Size: %u\n", num_blocks_x, num_blocks_y, bytes_per_block, total_compressed_size);
181
182 void* pCompressed_data = malloc(total_compressed_size);
183 if (!pCompressed_data) {
184 stbi_image_free(pSrc_image);
185 return error("Out of memory!");
186 }
187
188 crn_comp_params comp_params;
189 comp_params.m_format = fmt;
190 comp_params.m_dxt_quality = dxt_quality;
191 comp_params.set_flag(cCRNCompFlagPerceptual, srgb_colorspace);
192 comp_params.set_flag(cCRNCompFlagDXT1AForTransparency, actual_comps > 3);
193
194 crn_block_compressor_context_t pContext = crn_create_block_compressor(comp_params);
195
196 printf("Compressing to %s: ", crn_get_format_string(fmt));
197
198 int prev_percentage_complete = -1;
199 for (crn_uint32 block_y = 0; block_y < num_blocks_y; block_y++) {
200 for (crn_uint32 block_x = 0; block_x < num_blocks_x; block_x++) {
201 crn_uint32 pixels[cDXTBlockSize * cDXTBlockSize];
202
203 // Exact block from image, clamping at the sides of non-divisible by 4 images to avoid artifacts.
204 crn_uint32* pDst_pixels = pixels;
205 for (uint y = 0; y < cDXTBlockSize; y++) {
206 const uint actual_y = std::min(height - 1U, (block_y * cDXTBlockSize) + y);
207 for (uint x = 0; x < cDXTBlockSize; x++) {
208 const uint actual_x = std::min(width - 1U, (block_x * cDXTBlockSize) + x);
209 *pDst_pixels++ = pSrc_image[actual_x + actual_y * width];
210 }
211 }
212
213 // Compress the DXTn block.
214 crn_compress_block(pContext, pixels, static_cast<crn_uint8*>(pCompressed_data) + (block_x + block_y * num_blocks_x) * bytes_per_block);
215 }
216
217 int percentage_complete = ((block_y + 1) * 100 + (num_blocks_y / 2)) / num_blocks_y;
218 if (percentage_complete != prev_percentage_complete) {
219 printf("\b\b\b\b%3u%%", percentage_complete);
220 prev_percentage_complete = percentage_complete;
221 }
222 }
223 printf("\n");
224
225 // Free the block compressor.
226 crn_free_block_compressor(pContext);
227 pContext = NULL;
228
229 // Now create the DDS file.
230 char dst_filename[FILENAME_MAX];
231 crnlib_snprintf(dst_filename, sizeof(dst_filename), "%s%s%s.dds", drive.get_ptr(), dir.get_ptr(), fname.get_ptr());
232 if (out_filename[0])
233 strcpy_safe(dst_filename, sizeof(dst_filename), out_filename);
234
235 printf("Writing DDS file: %s\n", dst_filename);
236
237 FILE* pDDS_file = NULL;
238 crn_fopen(&pDDS_file, dst_filename, "wb");
239 if (!pDDS_file) {
240 free(pCompressed_data);
241 return error("Failed creating destination file!\n");
242 }
243
244 // Write the 4-byte DDS signature (not endian safe, but whatever this is a sample).
245 fwrite(&crnlib::cDDSFileSignature, sizeof(crnlib::cDDSFileSignature), 1, pDDS_file);
246
247 // Prepare the DDS header.
248 crnlib::DDSURFACEDESC2 dds_desc;
249 memset(&dds_desc, 0, sizeof(dds_desc));
250 dds_desc.dwSize = sizeof(dds_desc);
251 dds_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
252 dds_desc.dwWidth = width;
253 dds_desc.dwHeight = height;
254
255 dds_desc.ddpfPixelFormat.dwSize = sizeof(crnlib::DDPIXELFORMAT);
256 dds_desc.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
257 dds_desc.ddpfPixelFormat.dwFourCC = crn_get_format_fourcc(fmt);
258 dds_desc.ddsCaps.dwCaps = DDSCAPS_TEXTURE;
259
260 // Set pitch/linearsize field (some DDS readers require this field to be non-zero).
261 uint bits_per_pixel = crn_get_format_bits_per_texel(fmt);
262 dds_desc.lPitch = (((dds_desc.dwWidth + 3) & ~3) * ((dds_desc.dwHeight + 3) & ~3) * bits_per_pixel) >> 3;
263 dds_desc.dwFlags |= DDSD_LINEARSIZE;
264
265 // Write the DDS header to the output file.
266 fwrite(&dds_desc, sizeof(dds_desc), 1, pDDS_file);
267
268 // Write the image's compressed data to the output file.
269 fwrite(pCompressed_data, total_compressed_size, 1, pDDS_file);
270 free(pCompressed_data);
271
272 stbi_image_free(pSrc_image);
273
274 if (fclose(pDDS_file) == EOF) {
275 return error("Failed writing to DDS file!\n");
276 }
277
278 return EXIT_SUCCESS;
279 }