ktx2-rw 0.2.2

A high-level Rust wrapper for KTX2 texture format with full Basis Universal support
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
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

const KTX_SOFTWARE_VERSION: &str = "4.4.0";
const KTX_SOFTWARE_URL: &str =
    "https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/v4.4.0.tar.gz";
const FALLBACK_PATH: &str = "/tmp/ktx-software-v4.4.0.tar.gz";

fn main() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let target = env::var("TARGET").unwrap();
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
    let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
    let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();

    // Check if we should build or use cached version
    let ktx_build_dir = out_dir.join("KTX-Software-build");
    let ktx_lib_path = ktx_build_dir.join("lib").join(get_lib_name(&target_os));

    if !ktx_lib_path.exists() {
        build_ktx_software(&out_dir, &target, &target_os, &target_arch, &target_env);
    }

    // Link the built library
    let lib_dir = ktx_build_dir.join("lib");
    println!("cargo:rustc-link-search=native={}", lib_dir.display());

    // Try to find what library was actually built and link appropriately
    if lib_dir.join("libktx.a").exists() || lib_dir.join("ktx.lib").exists() {
        println!("cargo:rustc-link-lib=static=ktx");
    } else if lib_dir.join("ktx.framework").exists() {
        // For iOS/macOS frameworks
        println!("cargo:rustc-link-search=framework={}", lib_dir.display());
        println!("cargo:rustc-link-lib=framework=ktx");
    } else if lib_dir.join("libktx.dylib").exists() || lib_dir.join("libktx.so").exists() {
        println!("cargo:rustc-link-lib=dylib=ktx");
    } else {
        // Fallback to static linking
        println!("cargo:rustc-link-lib=static=ktx");
    }

    // Link required system libraries
    link_system_libraries(&target_os, &target_env, &target);

    // Configure bindgen
    setup_bindgen(&out_dir, &target, &ktx_build_dir);

    // Invalidation rules
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-env-changed=TARGET");
    println!("cargo:rerun-if-env-changed=CARGO_CFG_TARGET_OS");
    println!("cargo:rerun-if-env-changed=CARGO_CFG_TARGET_ARCH");
}

fn build_ktx_software(
    out_dir: &Path,
    target: &str,
    target_os: &str,
    target_arch: &str,
    target_env: &str,
) {
    let ktx_source_dir = download_and_extract_ktx_software(out_dir);
    let ktx_build_dir = out_dir.join("KTX-Software-build");

    // Create build directory
    fs::create_dir_all(&ktx_build_dir).expect("Failed to create build directory");

    // Configure CMake
    let mut cmake_config = cmake::Config::new(&ktx_source_dir);

    // Basic configuration - match KTX-Software's official build approach
    cmake_config
        .define("BUILD_SHARED_LIBS", "OFF") // This automatically sets KHRONOS_STATIC
        .define("KTX_FEATURE_TOOLS", "OFF")
        .define("KTX_FEATURE_TESTS", "OFF")
        .define("KTX_FEATURE_LOADTEST_APPS", "OFF")
        .define("KTX_FEATURE_GL_UPLOAD", "OFF")
        .define("KTX_FEATURE_VK_UPLOAD", "OFF")
        .define("KTX_FEATURE_WRITE", "ON")
        .define("CMAKE_BUILD_TYPE", "Release")
        .profile("Release")
        .out_dir(&ktx_build_dir);

    // Configure BASISU options following KTX-Software's approach
    if target_arch == "x86_64" {
        cmake_config.define("BASISU_SUPPORT_SSE", "ON");
    } else {
        cmake_config.define("BASISU_SUPPORT_SSE", "OFF");
    }
    cmake_config.define("BASISU_SUPPORT_OPENCL", "OFF");

    // Platform-specific configuration
    configure_cmake_for_target(
        &mut cmake_config,
        target,
        target_os,
        target_arch,
        target_env,
    );

    // Build
    let dst = cmake_config.build();

    // Find the built library - it could be static, dynamic, or framework
    let lib_dir = dst.join("lib");
    let possible_locations = [
        (lib_dir.join("libktx.a"), "libktx.a", "static"), // Static library (preferred)
        (lib_dir.join("ktx.lib"), "ktx.lib", "static"),   // Windows static library
        (lib_dir.join("libktx.dylib"), "libktx.dylib", "dylib"), // macOS dynamic library
        (lib_dir.join("libktx.so"), "libktx.so", "dylib"), // Linux dynamic library
        (
            lib_dir.join("ktx.framework").join("ktx"),
            "ktx",
            "framework",
        ), // iOS/macOS framework
    ];

    let mut found_lib = None;
    for (lib_path, lib_name, lib_type) in &possible_locations {
        if lib_path.exists() {
            found_lib = Some((lib_path.clone(), lib_name.to_string(), lib_type.to_string()));
            break;
        }
    }

    let (_, _lib_name, lib_type) = found_lib.expect("No KTX library found after build");

    // Handle different library types
    if matches!(lib_type.as_str(), "dylib") {
        // Dynamic library built - user may need to configure library paths
    }
}

fn download_and_extract_ktx_software(out_dir: &Path) -> PathBuf {
    let ktx_source_dir = out_dir.join(format!("KTX-Software-{}", KTX_SOFTWARE_VERSION));

    // Skip download if already exists
    if ktx_source_dir.exists() {
        return ktx_source_dir;
    }

    // Only print download message when actually downloading

    // Create client with longer timeout
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(300))
        .build()
        .expect("Failed to create HTTP client");

    // Try fallback path first
    if std::path::Path::new(FALLBACK_PATH).exists() {
        let tar_gz_data = std::fs::read(FALLBACK_PATH).expect("Failed to read fallback archive");
        let tar_gz = flate2::read::GzDecoder::new(&tar_gz_data[..]);
        let mut archive = tar::Archive::new(tar_gz);
        archive
            .unpack(out_dir)
            .expect("Failed to extract KTX-Software");
        return ktx_source_dir;
    }

    // Download with retries
    let mut last_error = None;
    for attempt in 1..=3 {
        match client.get(KTX_SOFTWARE_URL).send() {
            Ok(response) => {
                match response.bytes() {
                    Ok(bytes) => {
                        // Extract tar.gz
                        let tar_gz = flate2::read::GzDecoder::new(&bytes[..]);
                        let mut archive = tar::Archive::new(tar_gz);
                        archive
                            .unpack(out_dir)
                            .expect("Failed to extract KTX-Software");

                        // Download successful
                        return ktx_source_dir;
                    }
                    Err(e) => {
                        last_error = Some(format!("Failed to read response body: {}", e));
                        if attempt < 3 {
                            std::thread::sleep(std::time::Duration::from_secs(5));
                        }
                    }
                }
            }
            Err(e) => {
                last_error = Some(format!("Failed to download KTX-Software: {}", e));
                if attempt < 3 {
                    std::thread::sleep(std::time::Duration::from_secs(5));
                }
            }
        }
    }

    panic!(
        "Download failed: {}. You can manually download {} and place it at {} to use as fallback",
        last_error.unwrap_or_else(|| "Unknown download error".to_string()),
        KTX_SOFTWARE_URL,
        FALLBACK_PATH
    );
}

fn configure_cmake_for_target(
    cmake_config: &mut cmake::Config,
    target: &str,
    target_os: &str,
    target_arch: &str,
    target_env: &str,
) {
    match target_os {
        "windows" => {
            cmake_config.define("CMAKE_SYSTEM_NAME", "Windows");
            if target_env == "gnu" {
                if target.contains("x86_64") {
                    cmake_config.define("CMAKE_SYSTEM_PROCESSOR", "x86_64");
                } else if target.contains("i686") {
                    cmake_config.define("CMAKE_SYSTEM_PROCESSOR", "i686");
                }

                // Configure for fully static linking with MinGW
                cmake_config.define("CMAKE_C_FLAGS", "-static -static-libgcc -static-libstdc++");
                cmake_config.define(
                    "CMAKE_CXX_FLAGS",
                    "-static -static-libgcc -static-libstdc++",
                );
                cmake_config.define(
                    "CMAKE_EXE_LINKER_FLAGS",
                    "-static -static-libgcc -static-libstdc++",
                );
                cmake_config.define(
                    "CMAKE_SHARED_LINKER_FLAGS",
                    "-static -static-libgcc -static-libstdc++",
                );

                // When cross-compiling from non-Windows, use Unix Makefiles instead of MinGW Makefiles
                if !cfg!(windows) {
                    cmake_config.generator("Unix Makefiles");
                } else {
                    cmake_config.generator("MinGW Makefiles");
                }
            } else {
                // For MSVC targets, only use Visual Studio generator on Windows host
                if cfg!(windows) {
                    cmake_config.generator("Visual Studio 17 2022");
                    if target_arch == "x86_64" {
                        cmake_config.define("CMAKE_GENERATOR_PLATFORM", "x64");
                    } else if target_arch == "aarch64" {
                        cmake_config.define("CMAKE_GENERATOR_PLATFORM", "ARM64");
                    }
                    // Force Release configuration to avoid CRT mismatch
                    cmake_config.define("CMAKE_CONFIGURATION_TYPES", "Release");
                    // Let KTX-Software handle all MSVC-specific configuration
                } else {
                    // Cross-compiling MSVC from non-Windows is not supported
                    panic!(
                        "Cross-compiling to Windows MSVC targets from non-Windows platforms is not supported. Use GNU targets instead (e.g., x86_64-pc-windows-gnu)"
                    );
                }
            }
        }
        "macos" => {
            cmake_config.define("CMAKE_SYSTEM_NAME", "Darwin");
            if target_arch == "aarch64" {
                cmake_config.define("CMAKE_OSX_ARCHITECTURES", "arm64");
                cmake_config.define("CMAKE_SYSTEM_PROCESSOR", "arm64");
            } else {
                cmake_config.define("CMAKE_OSX_ARCHITECTURES", "x86_64");
                cmake_config.define("CMAKE_SYSTEM_PROCESSOR", "x86_64");
            }
        }
        "linux" => {
            cmake_config.define("CMAKE_SYSTEM_NAME", "Linux");
            cmake_config.define("CMAKE_SYSTEM_PROCESSOR", target_arch);

            // Handle musl vs glibc
            if target_env == "musl" {
                // For musl, configure for static linking of C++ runtime
                // Use -U to undefine _FORTIFY_SOURCE first, then redefine to avoid redefinition errors
                cmake_config.define(
                    "CMAKE_C_FLAGS",
                    "-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -static-libgcc -fPIE",
                );
                cmake_config.define(
                    "CMAKE_CXX_FLAGS",
                    "-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -static-libgcc -static-libstdc++ -fPIE",
                );
                cmake_config.define("CMAKE_EXE_LINKER_FLAGS", "-static-libgcc -static-libstdc++");
                cmake_config.define(
                    "CMAKE_SHARED_LINKER_FLAGS",
                    "-static-libgcc -static-libstdc++",
                );
            }
        }
        "android" => {
            cmake_config.define("CMAKE_SYSTEM_NAME", "Android");
            cmake_config.define("CMAKE_ANDROID_API", "21");
            cmake_config.define(
                "CMAKE_ANDROID_ARCH_ABI",
                match target_arch {
                    "aarch64" => "arm64-v8a",
                    "arm" => "armeabi-v7a",
                    "x86_64" => "x86_64",
                    "i686" => "x86",
                    _ => target_arch,
                },
            );

            if let Ok(ndk_path) = env::var("ANDROID_NDK_ROOT") {
                cmake_config.define(
                    "CMAKE_TOOLCHAIN_FILE",
                    format!("{}/build/cmake/android.toolchain.cmake", ndk_path),
                );
            }
        }
        "ios" => {
            cmake_config.define("CMAKE_SYSTEM_NAME", "iOS");
            cmake_config.define("CMAKE_OSX_DEPLOYMENT_TARGET", "11.0");
            if target_arch == "aarch64" {
                cmake_config.define("CMAKE_OSX_ARCHITECTURES", "arm64");
            } else {
                cmake_config.define("CMAKE_OSX_ARCHITECTURES", "x86_64");
            }
        }
        _ => {
            // Generic Unix-like system
            cmake_config.define("CMAKE_SYSTEM_PROCESSOR", target_arch);
        }
    }
}

fn get_lib_name(target_os: &str) -> &'static str {
    match target_os {
        "windows" => "ktx.lib",
        _ => "libktx.a",
    }
}

fn link_system_libraries(target_os: &str, target_env: &str, target: &str) {
    match target_os {
        "macos" => {
            println!("cargo:rustc-link-lib=c++");
        }
        "linux" => {
            if target_env == "musl" {
                // For musl targets, we need to link C++ runtime statically
                // The KTX-Software library contains C++ code that requires these symbols
                // Add search paths for musl toolchain libraries
                println!(
                    "cargo:rustc-link-search=native=/usr/local/musl/x86_64-unknown-linux-musl/lib"
                );
                println!(
                    "cargo:rustc-link-search=native=/usr/local/musl/lib/gcc/x86_64-unknown-linux-musl/11.2.0"
                );
                println!("cargo:rustc-link-lib=static=stdc++");
                println!("cargo:rustc-link-lib=static=gcc_eh");
            } else {
                // For glibc, use dynamic linking
                println!("cargo:rustc-link-lib=stdc++");
            }
            println!("cargo:rustc-link-lib=m");
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=pthread");
        }
        "windows" => {
            if target_env == "gnu" {
                // MinGW/GNU environment - ensure C++ standard library is statically linked
                // This is critical when used as a dependency to provide C++ symbols
                // that are required by the embedded Basis Universal C++ code

                // Add search paths for MinGW libraries on different platforms
                // Handle different CI and development environments
                let mut found_lib_path = false;

                let arch = if target.contains("x86_64") {
                    "x86_64"
                } else {
                    "i686"
                };
                let triple = format!("{}-w64-mingw32", arch);

                // Always try to find MinGW libraries when targeting Windows GNU
                {
                    // Try Windows-native MinGW installations first (for Windows CI)
                    if cfg!(windows) {
                        let windows_mingw_paths = [
                            // MSYS2 installations
                            format!(
                                "C:/msys64/mingw{}/lib",
                                if arch == "x86_64" { "64" } else { "32" }
                            ),
                            format!("C:/msys64/{}/lib", triple),
                            // Standalone MinGW installations
                            format!("C:/mingw{}/lib", if arch == "x86_64" { "64" } else { "32" }),
                            "C:/MinGW/lib".to_string(),
                            // TDM-GCC installations
                            format!(
                                "C:/TDM-GCC-{}/lib",
                                if arch == "x86_64" { "64" } else { "32" }
                            ),
                            // GitHub Actions pre-installed paths
                            format!(
                                "C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw{}/lib",
                                if arch == "x86_64" { "64" } else { "32" }
                            ),
                        ];

                        for path_str in &windows_mingw_paths {
                            let path = std::path::Path::new(path_str);
                            if path.exists() {
                                println!("cargo:rustc-link-search=native={}", path.display());
                                found_lib_path = true;

                                // Also check for GCC subdirectories
                                let gcc_path = path.join("gcc").join(&triple);
                                if gcc_path.exists()
                                    && let Ok(gcc_entries) = std::fs::read_dir(&gcc_path)
                                {
                                    for gcc_entry in gcc_entries.flatten() {
                                        let entry_path = gcc_entry.path();
                                        if entry_path.is_dir() {
                                            println!(
                                                "cargo:rustc-link-search=native={}",
                                                entry_path.display()
                                            );
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }

                    // Try macOS Homebrew (for macOS cross-compilation)
                    if cfg!(target_os = "macos") {
                        for homebrew_path in [
                            "/opt/homebrew/Cellar/mingw-w64",
                            "/usr/local/Cellar/mingw-w64",
                        ] {
                            if let Ok(entries) = std::fs::read_dir(homebrew_path) {
                                for entry in entries.flatten() {
                                    let version_path = entry.path();
                                    let toolchain_path =
                                        version_path.join(format!("toolchain-{}", arch));
                                    if toolchain_path.exists() {
                                        let lib_path = toolchain_path.join(&triple).join("lib");
                                        if lib_path.exists() {
                                            println!(
                                                "cargo:rustc-link-search=native={}",
                                                lib_path.display()
                                            );
                                            found_lib_path = true;
                                        }

                                        let gcc_path =
                                            toolchain_path.join("lib").join("gcc").join(&triple);
                                        if gcc_path.exists()
                                            && let Ok(gcc_entries) = std::fs::read_dir(&gcc_path)
                                        {
                                            for gcc_entry in gcc_entries.flatten() {
                                                println!(
                                                    "cargo:rustc-link-search=native={}",
                                                    gcc_entry.path().display()
                                                );
                                            }
                                        }
                                        break;
                                    }
                                }
                                if found_lib_path {
                                    break;
                                }
                            }
                        }
                    }

                    // If not found via Homebrew, try standard Linux/CI paths
                    if !found_lib_path {
                        // Try standard system paths for MinGW
                        let standard_paths = [
                            // Standard Ubuntu/Debian MinGW package paths
                            format!("/usr/{}/lib", triple),
                            format!("/usr/lib/gcc/{}", triple),
                            format!("/usr/lib/gcc-mingw-w64-{}", arch),
                            format!("/usr/lib/gcc-cross/{}", triple),
                            // GitHub Actions specific paths
                            "/usr/share/mingw-w64/lib".to_string(),
                            "/usr/lib/mingw-w64".to_string(),
                            // Windows paths when running on Windows CI
                            "C:/msys64/mingw64/lib".to_string(),
                            "C:/msys64/mingw32/lib".to_string(),
                            "C:/mingw64/lib".to_string(),
                            "C:/mingw32/lib".to_string(),
                            // Standard MSYS2 paths
                            "/mingw64/lib".to_string(),
                            "/mingw32/lib".to_string(),
                            "/usr/lib".to_string(),
                        ];

                        for path_str in &standard_paths {
                            let path = std::path::Path::new(path_str);
                            if path.exists() {
                                println!("cargo:rustc-link-search=native={}", path.display());
                                found_lib_path = true;

                                // Also try to find GCC version subdirectories
                                if let Ok(entries) = std::fs::read_dir(path) {
                                    for entry in entries.flatten() {
                                        let entry_path = entry.path();
                                        if entry_path.is_dir()
                                            && entry_path
                                                .file_name()
                                                .unwrap()
                                                .to_string_lossy()
                                                .chars()
                                                .next()
                                                .unwrap_or('a')
                                                .is_ascii_digit()
                                        {
                                            // This looks like a version directory (starts with digit)
                                            println!(
                                                "cargo:rustc-link-search=native={}",
                                                entry_path.display()
                                            );
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }

                    // Last resort: try to use the toolchain from environment variables
                    if !found_lib_path {
                        // Check common environment variables
                        let env_vars =
                            ["MINGW_PREFIX", "MINGW_ROOT", "MSYSTEM_PREFIX", "MSYS2_ROOT"];
                        for env_var in &env_vars {
                            if let Ok(toolchain_path) = env::var(env_var) {
                                let lib_path = format!("{}/lib", toolchain_path);
                                let path = std::path::Path::new(&lib_path);
                                if path.exists() {
                                    println!("cargo:rustc-link-search=native={}", lib_path);
                                    found_lib_path = true;

                                    // Also try architecture-specific subdirectory
                                    let arch_lib_path = format!(
                                        "{}/mingw{}/lib",
                                        toolchain_path,
                                        if arch == "x86_64" { "64" } else { "32" }
                                    );
                                    let arch_path = std::path::Path::new(&arch_lib_path);
                                    if arch_path.exists() {
                                        println!(
                                            "cargo:rustc-link-search=native={}",
                                            arch_lib_path
                                        );
                                    }
                                    break;
                                }
                            }
                        }

                        // If still not found, try to detect via common Windows locations
                        if !found_lib_path && cfg!(windows) {
                            // Check if we can find MinGW via common installation patterns
                            let fallback_paths = [
                                "C:/tools/mingw64/lib".to_string(),
                                "C:/tools/msys2/mingw64/lib".to_string(),
                                format!(
                                    "{}/.cargo/bin/../lib",
                                    env::var("USERPROFILE").unwrap_or_default()
                                ),
                            ];

                            for path_str in &fallback_paths {
                                let path = std::path::Path::new(path_str);
                                if path.exists() {
                                    println!("cargo:rustc-link-search=native={}", path.display());
                                    found_lib_path = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                // Static linking is required for cross-compilation to Windows GNU
                // to ensure C++ symbols from Basis Universal are properly embedded
                if !found_lib_path {
                    let host_os = if cfg!(windows) {
                        "Windows"
                    } else if cfg!(target_os = "macos") {
                        "macOS"
                    } else {
                        "Linux"
                    };
                    panic!(
                        "Could not find MinGW C++ static libraries for cross-compilation to {}. \
                        Host OS: {}. \
                        Please ensure MinGW-w64 is properly installed. \
                        Common installation methods: \
                        - Windows: Install MSYS2 (https://www.msys2.org/) and run 'pacman -S mingw-w64-x86_64-toolchain' \
                        - macOS: Install via Homebrew 'brew install mingw-w64' \
                        - Linux: Install via package manager 'apt-get install gcc-mingw-w64' \
                        Searched paths include: \
                        - Windows: C:/msys64/mingw64/lib, C:/mingw64/lib \
                        - macOS: /opt/homebrew/Cellar/mingw-w64 \
                        - Linux: /usr/{}/lib, /usr/lib/gcc/{} \
                        - Environment variables: MINGW_PREFIX, MSYSTEM_PREFIX",
                        triple, host_os, triple, triple
                    );
                }

                println!("cargo:rustc-link-lib=static=stdc++");
                println!("cargo:rustc-link-lib=static=gcc_eh");
                println!("cargo:rustc-link-lib=static=winpthread");
                println!("cargo:rustc-link-lib=static=gcc");

                // Additional system libraries needed by KTX-Software
                println!("cargo:rustc-link-lib=kernel32");
                println!("cargo:rustc-link-lib=user32");
                println!("cargo:rustc-link-lib=gdi32");
                println!("cargo:rustc-link-lib=advapi32");
                println!("cargo:rustc-link-lib=ws2_32");
            }
            // For MSVC, let the CMake build system handle all library linking
        }
        "android" => {
            println!("cargo:rustc-link-lib=c++");
            println!("cargo:rustc-link-lib=m");
            println!("cargo:rustc-link-lib=dl");
        }
        "ios" => {
            println!("cargo:rustc-link-lib=c++");
        }
        _ => {
            println!("cargo:rustc-link-lib=stdc++");
            println!("cargo:rustc-link-lib=m");
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=pthread");
        }
    }
}

fn setup_bindgen(out_dir: &Path, target: &str, _ktx_build_dir: &Path) {
    let ktx_source_dir = out_dir.join(format!("KTX-Software-{}", KTX_SOFTWARE_VERSION));
    let header_path = ktx_source_dir.join("include").join("ktx.h");

    let mut builder = bindgen::Builder::default()
        .header(header_path.to_string_lossy())
        .clang_arg(format!("-I{}", ktx_source_dir.join("include").display()))
        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()));

    // Add target-specific configuration for cross-compilation
    if target.contains("windows") && !cfg!(windows) {
        // Cross-compiling to Windows
        if let Ok(mingw_path) = env::var("MINGW_PREFIX") {
            builder = builder
                .clang_arg(format!("-I{}/include", mingw_path))
                .clang_arg(format!("--sysroot={}", mingw_path));
        } else if cfg!(target_os = "macos") {
            // Use system MinGW installation on macOS
            let mingw_sysroot = if target.contains("x86_64") {
                "/opt/homebrew/opt/mingw-w64/toolchain-x86_64/x86_64-w64-mingw32"
            } else {
                "/opt/homebrew/opt/mingw-w64/toolchain-i686/i686-w64-mingw32"
            };

            builder = builder
                .clang_arg("-target")
                .clang_arg(target)
                .clang_arg(format!("--sysroot={}", mingw_sysroot))
                .clang_arg(format!("-I{}/include", mingw_sysroot));
        }
    } else if target.contains("android") {
        // Cross-compiling to Android
        if let Ok(ndk_path) = env::var("ANDROID_NDK_ROOT") {
            let android_api = "21"; // Minimum API level we're targeting
            let arch_triple = if target.contains("aarch64") {
                "aarch64-linux-android"
            } else if target.contains("armv7") || target.contains("arm") {
                "arm-linux-androideabi"
            } else if target.contains("x86_64") {
                "x86_64-linux-android"
            } else if target.contains("i686") {
                "i686-linux-android"
            } else {
                target
            };

            // Detect the host platform for the NDK prebuilt toolchain
            let host_tag = if cfg!(target_os = "macos") {
                "darwin-x86_64"
            } else if cfg!(target_os = "linux") {
                "linux-x86_64"
            } else if cfg!(target_os = "windows") {
                "windows-x86_64"
            } else {
                "linux-x86_64" // fallback
            };

            let sysroot = format!("{}/toolchains/llvm/prebuilt/{}/sysroot", ndk_path, host_tag);

            builder = builder
                .clang_arg("-target")
                .clang_arg(format!("{}{}", arch_triple, android_api))
                .clang_arg(format!("--sysroot={}", sysroot))
                .clang_arg(format!("-I{}/usr/include", sysroot))
                .clang_arg(format!("-I{}/usr/include/{}", sysroot, arch_triple))
                .clang_arg("-DANDROID");
        }
    }

    // Generate the bindings
    let bindings = builder.generate().expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}