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
// Copyright (C) 2021 Paolo Jovon <paolo.jovon@gmail.com>
// SPDX-License-Identifier: Apache-2.0

//! Core types involving KTX [`Texture`]s.

use crate::{
    enums::{ktx_result, SuperCompressionScheme, TranscodeFlags, TranscodeFormat},
    sys, KtxError,
};
use std::marker::PhantomData;

/// A source of [`Texture`]s.
pub trait TextureSource<'a> {
    /// Attempts to create a new texture by consuming `self`.  
    fn create_texture(self) -> Result<Texture<'a>, KtxError>;
}

/// A sink of [`Texture`]s, e.g. something they can be written to.
#[cfg(feature = "write")]
pub trait TextureSink {
    /// Attempts to write `texture` to `self`.
    fn write_texture(&mut self, texture: &Texture) -> Result<(), KtxError>;
}

/// A KTX (1 or 2) texture.
///
/// This wraps both a [`sys::ktxTexture`] handle, and the [`TextureSource`] it was created from.
pub struct Texture<'a> {
    // Not actually dead - there most likely are raw pointers referencing this!!
    #[allow(dead_code)]
    pub(crate) source: Box<dyn TextureSource<'a> + 'a>,
    pub(crate) handle: *mut sys::ktxTexture,
    pub(crate) handle_phantom: PhantomData<&'a sys::ktxTexture>,
}

impl<'a> Texture<'a> {
    /// Attempts to create a new texture, consuming the given [`TextureSource`].
    pub fn new<S>(source: S) -> Result<Self, KtxError>
    where
        S: TextureSource<'a>,
    {
        source.create_texture()
    }

    /// Returns the pointer to the (C-allocated) underlying [`sys::ktxTexture`].
    ///
    /// **SAFETY**: Pointers are harmless. Dereferencing them is not!
    pub fn handle(&self) -> *mut sys::ktxTexture {
        self.handle
    }

    /// Returns the total size of image data, in bytes.
    pub fn data_size(&self) -> usize {
        // SAFETY: Safe if `self.handle` is sane.
        unsafe { sys::ktxTexture_GetDataSize(self.handle) as usize }
    }

    /// Returns a read-only view on the image data.
    pub fn data(&self) -> &[u8] {
        let data = unsafe { sys::ktxTexture_GetData(self.handle) };
        // SAFETY: Safe if `self.handle` is sane.
        unsafe { std::slice::from_raw_parts(data, self.data_size()) }
    }

    /// Returns a read-write view on the image data.
    pub fn data_mut(&mut self) -> &mut [u8] {
        let data = unsafe { sys::ktxTexture_GetData(self.handle) };
        // SAFETY: Safe if `self.handle` is sane.
        unsafe { std::slice::from_raw_parts_mut(data, self.data_size()) }
    }

    /// Returns the pitch (in bytes) of an image row at the specified image level.  
    /// This is rounded up to 1 if needed.
    pub fn row_pitch(&self, level: u32) -> usize {
        // SAFETY: Safe if `self.handle` is sane.
        //         `level` is not used for indexing internally; no bounds-checking required.
        unsafe { sys::ktxTexture_GetRowPitch(self.handle, level) as usize }
    }

    /// Returns the size (in bytes) of an element of the image.
    pub fn element_size(&self) -> usize {
        // SAFETY: Safe if `self.handle` is sane.
        unsafe { sys::ktxTexture_GetElementSize(self.handle) as usize }
    }

    /// Attempts to write the texture (in its native format, either KTX1 or KTX2) to `sink`.
    #[cfg(feature = "write")]
    pub fn write_to<T: TextureSink>(&self, sink: &mut T) -> Result<(), KtxError> {
        sink.write_texture(self)
    }

    /// If this [`Texture`] really is a KTX1, returns KTX1-specific functionalities for it.
    pub fn ktx1<'b>(&'b mut self) -> Option<Ktx1<'b, 'a>> {
        // SAFETY: Safe if `self.handle` is sane.
        if unsafe { *self.handle }.classId == sys::class_id_ktxTexture1_c {
            Some(Ktx1 { texture: self })
        } else {
            None
        }
    }

    /// If this [`Texture`] really is a KTX2, returns KTX2-specific functionalities for it.
    pub fn ktx2<'b>(&'b mut self) -> Option<Ktx2<'b, 'a>> {
        // SAFETY: Safe if `self.handle` is sane.
        if unsafe { *self.handle }.classId == sys::class_id_ktxTexture2_c {
            Some(Ktx2 { texture: self })
        } else {
            None
        }
    }
}

impl<'a> Drop for Texture<'a> {
    fn drop(&mut self) {
        unsafe {
            let vtbl = (*self.handle).vtbl;
            if let Some(destroy_fn) = (*vtbl).Destroy {
                (destroy_fn)(self.handle as *mut sys::ktxTexture);
            }
        }
    }
}

/// KTX1-specific [`Texture`] functionality.
pub struct Ktx1<'a, 'b: 'a> {
    texture: &'a mut Texture<'b>,
}

impl<'a, 'b: 'a> Ktx1<'a, 'b> {
    /// Returns a pointer to the underlying (C-allocated) [`sys::ktxTexture1`].
    ///
    /// **SAFETY**: Pointers are harmless. Dereferencing them is not!
    pub fn handle(&self) -> *mut sys::ktxTexture1 {
        self.texture.handle as *mut sys::ktxTexture1
    }

    /// Returns the OpenGL format of the texture's data (e.g. `GL_RGBA`).
    ///
    /// Also see [`Self::gl_internal_format`], [`Self::gl_base_internal_format`].
    pub fn gl_format(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).glFormat }
    }

    /// Returns the OpenGL format of the texture's data (e.g. `GL_RGBA`).
    ///
    /// Also see [`Self::gl_format`], [`Self::gl_base_internal_format`].
    pub fn gl_internal_format(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).glFormat }
    }

    /// Returns the OpenGL base internal format of the texture's data (e.g. `GL_RGBA`).
    ///
    /// Also see [`Self::gl_format`], [`Self::gl_internal_format`].
    pub fn gl_base_internal_format(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).glBaseInternalformat }
    }

    /// Returns the OpenGL datatype of the texture's data (e.g. `GL_UNSIGNED_BYTE`).
    pub fn gl_type(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).glType }
    }

    /// Will this KTX1 need transcoding?
    pub fn needs_transcoding(&self) -> bool {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { sys::ktxTexture1_NeedsTranscoding(self.handle()) }
    }

    // TODO: WriteKTX2ToStream with a Rust stream (and to a memory slice?)
    //       Probably needs a TextureSink trait
}

/// KTX2-specific [`Texture`] functionality.
pub struct Ktx2<'a, 'b: 'a> {
    texture: &'a mut Texture<'b>,
}

impl<'a, 'b: 'a> Ktx2<'a, 'b> {
    /// Returns a pointer to the underlying (C-allocated) [`sys::ktxTexture2`].
    ///
    /// **SAFETY**: Pointers are harmless. Dereferencing them is not!
    pub fn handle(&self) -> *mut sys::ktxTexture2 {
        self.texture.handle as *mut sys::ktxTexture2
    }

    /// Returns the Vulkan format of the texture's data (e.g. `VK_R8G8B8A8_UNORM`).
    pub fn vk_format(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).vkFormat }
    }

    /// Returns the supercompression scheme in use for this texture's data.
    pub fn supercompression_scheme(&self) -> SuperCompressionScheme {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).supercompressionScheme.into() }
    }

    /// Is this a video texture?
    pub fn is_video(&self) -> bool {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).isVideo }
    }

    /// Returns the duration of the video texture (if [`Self::is_video`]).
    pub fn duration(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).duration }
    }

    /// Returns the timescale of the video texture (if [`Self::is_video`]).
    pub fn timescale(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).timescale }
    }

    /// Returns the loop count of the video texture (if [`Self::is_video`]).
    pub fn loop_count(&self) -> u32 {
        let handle = self.handle();
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX1
        unsafe { (*handle).loopcount }
    }

    /// Will this KTX2 need transcoding?
    pub fn needs_transcoding(&self) -> bool {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        unsafe { sys::ktxTexture2_NeedsTranscoding(self.handle()) }
    }

    /// Compresses a uncompressed KTX2 texture with Basis Universal.  
    /// `quality` is 1-255; 0 -> the default quality, 128. **Lower `quality` means better (but slower) compression**.
    pub fn compress_basis(&mut self, quality: u32) -> Result<(), KtxError> {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        let errcode = unsafe { sys::ktxTexture2_CompressBasis(self.handle(), quality as u32) };
        ktx_result(errcode, ())
    }

    /// Compresses the KTX2 texture's data with ZStandard compression.  
    /// `level` is 1-22; lower is faster (hence, worse compression).  
    /// Values over 20 may consume significant memory.
    pub fn deflate_zstd(&mut self, level: u32) -> Result<(), KtxError> {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        let errcode = unsafe { sys::ktxTexture2_DeflateZstd(self.handle(), level as u32) };
        ktx_result(errcode, ())
    }

    /// Returns the number of components of the KTX2 and the size in bytes of each components.
    pub fn component_info(&self) -> (u32, u32) {
        let mut num_components: u32 = 0;
        let mut component_size: u32 = 0;
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        unsafe {
            sys::ktxTexture2_GetComponentInfo(
                self.handle(),
                &mut num_components,
                &mut component_size,
            );
        }
        (num_components, component_size)
    }

    /// Returns the number of components of the KTX2, also considering compression.  
    ///
    /// **This may differ from values returned by [`Self::component_info`]:**
    /// - For uncompressed formats: this is the number of image components, as from [`Self::component_info`].
    /// - For block-compressed formats: 1 or 2, according to the DFD color model.
    /// - For Basis Universal-compressed textures: obtained by parsing channel IDs before any encoding and deflation.
    ///
    /// See [`sys::ktxTexture2_GetNumComponents`].
    pub fn num_components(&self) -> u32 {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        unsafe { sys::ktxTexture2_GetNumComponents(self.handle()) }
    }

    /// Returns the Opto-Electrical Transfer Function (OETF) for this KTX2, in KHR_DF format.  
    /// See <https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.inline.html#_emphasis_role_strong_emphasis_transferfunction_emphasis_emphasis>.
    pub fn oetf(&self) -> u32 {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        unsafe { sys::ktxTexture2_GetOETF(self.handle()) }
    }

    /// Does this KTX2 have premultiplied alpha?
    pub fn premultiplied_alpha(&self) -> bool {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        unsafe { sys::ktxTexture2_GetPremultipliedAlpha(self.handle()) }
    }

    /// Transcodes this KTX2 to the given format by using ETC1S (from Basis Universal) or UASTC.
    ///
    /// - BasisLZ supercompressed textures are turned back to ETC1S, then transcoded.
    /// - UASTC-compressed images are inflated (possibly, even deflating any ZStandard supercompression), then transcoded.
    /// - **All internal data of the texture may change, including the
    /// [DFD](https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.inline.html#_anchor_id_dataformatdescriptor_xreflabel_dataformatdescriptor_khronos_data_format_descriptor)**!
    pub fn transcode_basis(
        &mut self,
        format: TranscodeFormat,
        flags: TranscodeFlags,
    ) -> Result<(), KtxError> {
        // SAFETY: Safe if `self.texture.handle` is sane + actually a KTX2
        let errcode =
            unsafe { sys::ktxTexture2_TranscodeBasis(self.handle(), format as u32, flags.bits()) };
        ktx_result(errcode, ())
    }
}