ctt-intel-texture-compressor 0.2.0

Vendored Intel ISPC texture compressor bindings, based on intel_tex_2
Documentation
//! BC4 (RGTC1) block compression — single-channel (red).
//!
//! # Input format
//!
//! Expects an [`RSurface`] with **`R8`** pixel data (1 byte per pixel). Each
//! byte is an unsigned 8-bit value in `0..=255`. The ISPC kernel reads 4
//! consecutive bytes at a time as a packed u32, extracting one R sample per
//! byte.
//!
//! # Output
//!
//! Each 4×4 texel block is encoded into **8 bytes** (0.5 bytes/pixel).

use crate::RSurface;
use crate::bindings::kernel;

#[must_use]
pub fn calc_output_size(width: u32, height: u32) -> usize {
    // BC4 uses 8 bytes to store each 4×4 block, giving it an average data rate of 0.5 bytes per pixel.
    let block_count = (width.div_ceil(4) * height.div_ceil(4)) as usize;
    block_count * 8
}

#[must_use]
pub fn compress_blocks(surface: &RSurface) -> Vec<u8> {
    let output_size = calc_output_size(surface.width, surface.height);
    let mut output = vec![0u8; output_size];
    compress_blocks_into(surface, &mut output);
    output
}

/// Compresses an [`RSurface`] into BC4 blocks.
///
/// The surface must contain `R8` pixel data (1 byte per pixel), where each
/// byte is an unsigned 8-bit sample.
///
/// # Panics
///
/// Panics if `blocks.len()` does not equal [`calc_output_size`] for the given
/// surface dimensions.
pub fn compress_blocks_into(surface: &RSurface, blocks: &mut [u8]) {
    assert_eq!(
        blocks.len(),
        calc_output_size(surface.width, surface.height)
    );

    // SAFETY: The ISPC function does not mutate the source surface; the `*mut u8`
    // pointer type is an artifact of the C header declaration.
    let mut surface = kernel::rgba_surface {
        width: surface.width as i32,
        height: surface.height as i32,
        stride: surface.stride as i32,
        ptr: surface.data.as_ptr() as *mut u8,
    };

    unsafe {
        kernel::CompressBlocksBC4_ispc(&mut surface, blocks.as_mut_ptr());
    }
}