├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── header.rs ├── lib.rs ├── read.rs └── slice.rs ├── test └── tests ├── babg-bc3.ktx ├── example.rs └── uffizi_rgba16f_cube.ktx /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - run: rustup update stable 14 | - uses: actions/checkout@v2 15 | - run: cargo test 16 | 17 | test_no_std: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - run: rustup update stable 21 | - run: rustup target add thumbv6m-none-eabi 22 | - uses: actions/checkout@v2 23 | - run: cargo check --target thumbv6m-none-eabi --no-default-features 24 | 25 | rustfmt: 26 | runs-on: ubuntu-latest 27 | steps: 28 | - run: rustup update stable 29 | - uses: actions/checkout@v2 30 | - run: cargo fmt -- --check 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.3.2 2 | * Support cubemap textures. For such textures each level will contain all 6 faces in order: +X, -X, +Y, -Y, +Z, -Z. 3 | 4 | # 0.3.1 5 | * Add new default feature `std` which can be disabled to allow no-std usage. 6 | 7 | # 0.3 8 | * `Ktx` now uses a generic `D: Deref` instead of requiring a slice. This supports owned data usage in addition to slice usage. The texture slice lifetime is now the shorter `Ktx` lifetime because of this. 9 | * Remove internal macros instead `AsRef` now provides `KtxInfo` allowing `Ktx`, `KtxHeader`, `KtxDecoder` to all implement `KtxInfo`. 10 | 11 | # 0.2 12 | * Add `ktx::Decoder` useful when reading from a file and/or compressed data. 13 | * Separate header logic into `KtxInfo` trait now provided by methods instead of direct field access. 14 | 15 | # 0.1 16 | Initial release supporting KTX formatted byte data. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ktx" 3 | version = "0.3.2" 4 | authors = ["Alex Butler "] 5 | edition = "2018" 6 | description = "KTX texture storage format parsing" 7 | repository = "https://github.com/alexheretic/ktx" 8 | keywords = ["ktx", "texture"] 9 | license = "Apache-2.0" 10 | readme="README.md" 11 | exclude = ["/tests/*.ktx"] 12 | 13 | [dependencies] 14 | byteorder = { version = "1.3", default-features = false } 15 | 16 | [features] 17 | default = ["std"] 18 | std = [] 19 | 20 | [dev-dependencies] 21 | blake2 = { version = "0.10", default-features = false } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ktx 2 | [![crates.io](https://img.shields.io/crates/v/ktx.svg)](https://crates.io/crates/ktx) 3 | [![Documentation](https://docs.rs/ktx/badge.svg)](https://docs.rs/ktx) 4 | ========== 5 | 6 | KTX v1 texture storage format parsing. 7 | 8 | Parses byte data according to [https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html](https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html). 9 | 10 | ```rust 11 | // Include & use static ktx data 12 | use ktx::{Ktx, include_ktx, KtxInfo}; 13 | 14 | let image: Ktx<_> = include_ktx!("../tests/babg-bc3.ktx"); 15 | assert_eq!(image.pixel_width(), 260); 16 | ``` 17 | 18 | ```rust 19 | // Read ktx data at runtime 20 | use ktx::KtxInfo; 21 | 22 | let decoder = ktx::Decoder::new(buf_reader)?; 23 | assert_eq!(decoder.pixel_width(), 260); 24 | ``` 25 | 26 | ## Minimum supported rust compiler 27 | This crate is maintained with [latest stable rust](https://gist.github.com/alexheretic/d1e98d8433b602e57f5d0a9637927e0c). 28 | -------------------------------------------------------------------------------- /src/header.rs: -------------------------------------------------------------------------------- 1 | use byteorder::{BigEndian, ByteOrder, LittleEndian}; 2 | 3 | pub(crate) const KTX1_IDENTIFIER: [u8; 12] = [ 4 | 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A, 5 | ]; 6 | 7 | /// KTX texture storage format parameters. 8 | /// 9 | /// See the [specification](https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html). 10 | pub trait KtxInfo { 11 | /// endianness contains the number 0x04030201 written as a 32 bit integer. If the file is little 12 | /// endian then this is represented as the bytes 0x01 0x02 0x03 0x04. If the file is big endian 13 | /// then this is represented as the bytes 0x04 0x03 0x02 0x01. When reading endianness as a 32 14 | /// bit integer produces the value 0x04030201 then the endianness of the file matches the the 15 | /// endianness of the program that is reading the file and no conversion is necessary. When 16 | /// reading endianness as a 32 bit integer produces the value 0x01020304 then the endianness of 17 | /// the file is opposite the endianness of the program that is reading the file, and in that 18 | /// case the program reading the file must endian convert all header bytes and, if glTypeSize > 19 | /// 1, all texture data to the endianness of the program (i.e. a little endian program must 20 | /// convert from big endian, and a big endian program must convert to little endian). 21 | fn big_endian(&self) -> bool; 22 | /// For compressed textures, glType must equal 0. For uncompressed textures, glType specifies the 23 | /// type parameter passed to glTex{,Sub}Image*D, usually one of the values from table 8.2 of the 24 | /// OpenGL 4.4 specification [OPENGL44] (UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.) 25 | /// 26 | /// [OPENGL44]: https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#refsGL44 27 | fn gl_type(&self) -> u32; 28 | /// glTypeSize specifies the data type size that should be used when endianness conversion is 29 | /// required for the texture data stored in the file. If glType is not 0, this should be the 30 | /// size in bytes corresponding to glType. For texture data which does not depend on platform 31 | /// endianness, including compressed texture data, glTypeSize must equal 1. 32 | fn gl_type_size(&self) -> u32; 33 | /// For compressed textures, glFormat must equal 0. For uncompressed textures, glFormat specifies 34 | /// the format parameter passed to glTex{,Sub}Image*D, usually one of the values from table 8.3 35 | /// of the OpenGL 4.4 specification [OPENGL44] (RGB, RGBA, BGRA, etc.) 36 | /// 37 | /// [OPENGL44]: https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#refsGL44 38 | fn gl_format(&self) -> u32; 39 | /// For compressed textures, glInternalFormat must equal the compressed internal format, usually 40 | /// one of the values from table 8.14 of the OpenGL 4.4 specification [OPENGL44]. For 41 | /// uncompressed textures, glInternalFormat specifies the internalformat parameter passed to 42 | /// glTexStorage*D or glTexImage*D, usually one of the sized internal formats from tables 8.12 & 43 | /// 8.13 of the OpenGL 4.4 specification [OPENGL44]. The sized format should be chosen to match 44 | /// the bit depth of the data provided. glInternalFormat is used when loading both compressed 45 | /// and uncompressed textures, except when loading into a context that does not support sized 46 | /// formats, such as an unextended OpenGL ES 2.0 context where the internalformat parameter is 47 | /// required to have the same value as the format parameter. 48 | /// 49 | /// [OPENGL44]: https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#refsGL44 50 | fn gl_internal_format(&self) -> u32; 51 | /// For both compressed and uncompressed textures, glBaseInternalFormat specifies the base 52 | /// internal format of the texture, usually one of the values from table 8.11 of the OpenGL 4.4 53 | /// specification [OPENGL44] (RGB, RGBA, ALPHA, etc.). For uncompressed textures, this value 54 | /// will be the same as glFormat and is used as the internalformat parameter when loading into a 55 | /// context that does not support sized formats, such as an unextended OpenGL ES 2.0 context. 56 | /// 57 | /// [OPENGL44]: https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#refsGL44 58 | fn gl_base_internal_format(&self) -> u32; 59 | /// The width of the texture image for level 0, in pixels. No rounding to block sizes should be 60 | /// applied for block compressed textures. 61 | fn pixel_width(&self) -> u32; 62 | /// The height of the texture image for level 0, in pixels. No rounding to block sizes should be 63 | /// applied for block compressed textures. 64 | /// 65 | /// For 1D textures this must be 0. 66 | fn pixel_height(&self) -> u32; 67 | /// The depth of the texture image for level 0, in pixels. No rounding to block sizes should be 68 | /// applied for block compressed textures. 69 | /// 70 | /// For 1D textures this must be 0. For 2D and cube textures this must be 0. 71 | fn pixel_depth(&self) -> u32; 72 | /// numberOfArrayElements specifies the number of array elements. If the texture is not an array 73 | /// texture, numberOfArrayElements must equal 0. 74 | fn array_elements(&self) -> u32; 75 | /// numberOfFaces specifies the number of cubemap faces. For cubemaps and cubemap arrays this 76 | /// should be 6. For non cubemaps this should be 1. Cube map faces are stored in the order: +X, 77 | /// -X, +Y, -Y, +Z, -Z. 78 | /// 79 | /// Due to GL_OES_compressed_paletted_texture [OESCPT] not defining the interaction between 80 | /// cubemaps and its GL_PALETTE* formats, if `glInternalFormat` is one of its GL_PALETTE* 81 | /// format, numberOfFaces must be 1 82 | /// 83 | /// [OESCPT]: https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#refsOESCPT 84 | fn faces(&self) -> u32; 85 | /// numberOfMipmapLevels must equal 1 for non-mipmapped textures. For mipmapped textures, it 86 | /// equals the number of mipmaps. Mipmaps are stored in order from largest size to smallest 87 | /// size. The first mipmap level is always level 0. A KTX file does not need to contain a 88 | /// complete mipmap pyramid. If numberOfMipmapLevels equals 0, it indicates that a full mipmap 89 | /// pyramid should be generated from level 0 at load time (this is usually not allowed for 90 | /// compressed formats). 91 | fn mipmap_levels(&self) -> u32; 92 | /// keyAndValueByteSize is the number of bytes of combined key and value data in one key/value 93 | /// pair following the header. This includes the size of the key, the NUL byte terminating the 94 | /// key, and all the bytes of data in the value. If the value is a UTF-8 string it should be NUL 95 | /// terminated and the keyAndValueByteSize should include the NUL character (but code that reads 96 | /// KTX files must not assume that value fields are NUL terminated). keyAndValueByteSize does 97 | /// not include the bytes in valuePadding. 98 | fn bytes_of_key_value_data(&self) -> u32; 99 | } 100 | 101 | /// KTX texture storage format header. Provides [`KtxInfo`](../header/trait.KtxInfo.html). 102 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 103 | pub struct KtxHeader { 104 | big_endian: bool, 105 | gl_type: u32, 106 | gl_type_size: u32, 107 | gl_format: u32, 108 | gl_internal_format: u32, 109 | gl_base_internal_format: u32, 110 | pixel_width: u32, 111 | pixel_height: u32, 112 | pixel_depth: u32, 113 | array_elements: u32, 114 | faces: u32, 115 | mipmap_levels: u32, 116 | bytes_of_key_value_data: u32, 117 | } 118 | 119 | impl KtxHeader { 120 | /// Reads first 64 bytes to parse KTX header data, returns a `KtxHeader`. 121 | pub fn new(first_64_bytes: &[u8]) -> Self { 122 | debug_assert!(first_64_bytes.len() >= 64); 123 | debug_assert_eq!(&first_64_bytes[..12], &KTX1_IDENTIFIER, "Not KTX1"); 124 | 125 | let big_endian = first_64_bytes[12] == 4; 126 | 127 | let mut vals: [u32; 12] = <_>::default(); 128 | if big_endian { 129 | BigEndian::read_u32_into(&first_64_bytes[16..64], &mut vals); 130 | } else { 131 | LittleEndian::read_u32_into(&first_64_bytes[16..64], &mut vals); 132 | } 133 | 134 | Self { 135 | big_endian, 136 | gl_type: vals[0], 137 | gl_type_size: vals[1], 138 | gl_format: vals[2], 139 | gl_internal_format: vals[3], 140 | gl_base_internal_format: vals[4], 141 | pixel_width: vals[5], 142 | pixel_height: vals[6], 143 | pixel_depth: vals[7], 144 | array_elements: vals[8], 145 | faces: vals[9], 146 | mipmap_levels: vals[10], 147 | bytes_of_key_value_data: vals[11], 148 | } 149 | } 150 | } 151 | 152 | impl AsRef for KtxHeader { 153 | #[inline] 154 | fn as_ref(&self) -> &Self { 155 | self 156 | } 157 | } 158 | 159 | impl KtxInfo for T 160 | where 161 | T: AsRef, 162 | { 163 | #[inline] 164 | fn big_endian(&self) -> bool { 165 | self.as_ref().big_endian 166 | } 167 | #[inline] 168 | fn gl_type(&self) -> u32 { 169 | self.as_ref().gl_type 170 | } 171 | #[inline] 172 | fn gl_type_size(&self) -> u32 { 173 | self.as_ref().gl_type_size 174 | } 175 | #[inline] 176 | fn gl_format(&self) -> u32 { 177 | self.as_ref().gl_format 178 | } 179 | #[inline] 180 | fn gl_internal_format(&self) -> u32 { 181 | self.as_ref().gl_internal_format 182 | } 183 | #[inline] 184 | fn gl_base_internal_format(&self) -> u32 { 185 | self.as_ref().gl_base_internal_format 186 | } 187 | #[inline] 188 | fn pixel_width(&self) -> u32 { 189 | self.as_ref().pixel_width 190 | } 191 | #[inline] 192 | fn pixel_height(&self) -> u32 { 193 | self.as_ref().pixel_height 194 | } 195 | #[inline] 196 | fn pixel_depth(&self) -> u32 { 197 | self.as_ref().pixel_depth 198 | } 199 | #[inline] 200 | fn array_elements(&self) -> u32 { 201 | self.as_ref().array_elements 202 | } 203 | #[inline] 204 | fn faces(&self) -> u32 { 205 | self.as_ref().faces 206 | } 207 | #[inline] 208 | fn mipmap_levels(&self) -> u32 { 209 | self.as_ref().mipmap_levels 210 | } 211 | #[inline] 212 | fn bytes_of_key_value_data(&self) -> u32 { 213 | self.as_ref().bytes_of_key_value_data 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! KTX v1 texture storage format parsing. 2 | //! 3 | //! Parses byte data according to 4 | //! [https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html](https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html). 5 | //! 6 | //! # Example: Include at compile time 7 | //! ``` 8 | //! # fn main() -> std::io::Result<()> { 9 | //! use ktx::{include_ktx, Ktx, KtxInfo}; 10 | //! 11 | //! // Include & use static ktx data 12 | //! let image: Ktx<_> = include_ktx!("../tests/babg-bc3.ktx"); 13 | //! assert_eq!(image.pixel_width(), 260); 14 | //! # Ok(()) } 15 | //! ``` 16 | //! 17 | //! # Example: Read at runtime 18 | //! ``` 19 | //! # fn main() -> std::io::Result<()> { 20 | //! # use std::{io::BufReader, fs::File}; 21 | //! use ktx::KtxInfo; 22 | //! 23 | //! # let mut buf_reader = BufReader::new(File::open("tests/babg-bc3.ktx").unwrap()); 24 | //! let decoder = ktx::Decoder::new(buf_reader)?; 25 | //! assert_eq!(decoder.pixel_width(), 260); 26 | //! # Ok(()) } 27 | //! ``` 28 | #![cfg_attr(not(feature = "std"), no_std)] 29 | #![allow(clippy::cast_lossless)] 30 | 31 | pub mod header; 32 | #[cfg(feature = "std")] 33 | pub mod read; 34 | pub mod slice; 35 | 36 | pub use header::KtxInfo; 37 | #[cfg(feature = "std")] 38 | pub use read::KtxDecoder as Decoder; 39 | pub use slice::Ktx; 40 | -------------------------------------------------------------------------------- /src/read.rs: -------------------------------------------------------------------------------- 1 | use crate::header::*; 2 | use byteorder::{BigEndian, ByteOrder, LittleEndian}; 3 | use std::{ 4 | fmt, 5 | io::{self, Read}, 6 | }; 7 | 8 | /// KTX texture storage format reader. Useful when reading from a file and/or compressed data. 9 | /// Provides [`KtxInfo`](../header/trait.KtxInfo.html). 10 | /// 11 | /// # Example 12 | /// ``` 13 | /// # use std::{io::BufReader, fs::File}; 14 | /// # fn main() -> std::io::Result<()> { 15 | /// use ktx::*; 16 | /// # let mut buf_reader = BufReader::new(File::open("tests/babg-bc3.ktx")?); 17 | /// let mut decoder = ktx::Decoder::new(buf_reader)?; 18 | /// 19 | /// assert_eq!(decoder.pixel_width(), 260); 20 | /// let texture_levels: Vec> = decoder.read_textures().collect(); 21 | /// # Ok(()) } 22 | /// ``` 23 | #[derive(Clone, Copy)] 24 | pub struct KtxDecoder { 25 | header: KtxHeader, 26 | data: R, 27 | } 28 | 29 | impl AsRef for KtxDecoder { 30 | #[inline] 31 | fn as_ref(&self) -> &KtxHeader { 32 | &self.header 33 | } 34 | } 35 | 36 | impl fmt::Debug for KtxDecoder { 37 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 38 | fmt.debug_struct("KtxDecoder") 39 | .field("header", &self.header) 40 | .finish() 41 | } 42 | } 43 | 44 | impl KtxDecoder { 45 | /// Reads KTX header data and returns a `KtxDecoder`. 46 | #[inline] 47 | pub fn new(mut data: R) -> io::Result { 48 | let mut header_data = [0; 64]; 49 | data.read_exact(&mut header_data)?; 50 | let header = KtxHeader::new(&header_data); 51 | Ok(Self { header, data }) 52 | } 53 | 54 | /// Consumes the `KtxDecoder` to returns an iterator reading texture levels starting at level 0. 55 | #[inline] 56 | pub fn read_textures(self) -> Textures { 57 | Textures { 58 | header: self.header, 59 | data: self.data, 60 | next_level: 0, 61 | } 62 | } 63 | 64 | /// Returns `KtxHeader`. Useful if this info is desired after consuming the `KtxDecoder`. 65 | /// 66 | /// # Example 67 | /// ``` 68 | /// # use std::{io::BufReader, fs::File}; 69 | /// # use ktx::*; 70 | /// # let mut reader = BufReader::new(File::open("tests/babg-bc3.ktx").unwrap()); 71 | /// # let mut decoder = ktx::Decoder::new(reader).unwrap(); 72 | /// let ktx_header = decoder.header(); 73 | /// assert_eq!(ktx_header.pixel_width(), 260); 74 | /// ``` 75 | #[inline] 76 | pub fn header(&self) -> KtxHeader { 77 | self.header 78 | } 79 | } 80 | 81 | /// Iterator that reads texture level data into `Vec`. 82 | /// 83 | /// For cubemap textures each level will contain all 6 faces 84 | /// in order: +X, -X, +Y, -Y, +Z, -Z. 85 | #[derive(Debug)] 86 | pub struct Textures { 87 | header: KtxHeader, 88 | data: R, 89 | next_level: u32, 90 | } 91 | 92 | impl Iterator for Textures { 93 | type Item = Vec; 94 | 95 | fn next(&mut self) -> Option { 96 | if self.next_level >= self.header.mipmap_levels() { 97 | None 98 | } else { 99 | // skip key-value data 100 | if self.next_level == 0 && self.header.bytes_of_key_value_data() != 0 { 101 | let mut discard = Vec::with_capacity(self.header.bytes_of_key_value_data() as _); 102 | self.data 103 | .by_ref() 104 | .take(self.header.bytes_of_key_value_data() as _) 105 | .read_to_end(&mut discard) 106 | .ok()?; 107 | } 108 | 109 | self.next_level += 1; 110 | let mut level_len = { 111 | let mut len = [0; 4]; 112 | self.data.read_exact(&mut len).ok()?; 113 | if self.header.big_endian() { 114 | BigEndian::read_u32(&len) 115 | } else { 116 | LittleEndian::read_u32(&len) 117 | } 118 | }; 119 | 120 | if self.header.array_elements() == 0 && self.header.faces() == 6 { 121 | // Multiply for each face, see https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#2.16 122 | level_len *= 6; 123 | } 124 | 125 | let mut level = Vec::with_capacity(level_len as _); 126 | self.data 127 | .by_ref() 128 | .take(level_len as _) 129 | .read_to_end(&mut level) 130 | .ok()?; 131 | Some(level) 132 | } 133 | } 134 | } 135 | 136 | impl std::iter::FusedIterator for Textures {} 137 | -------------------------------------------------------------------------------- /src/slice.rs: -------------------------------------------------------------------------------- 1 | use crate::header::*; 2 | use byteorder::{BigEndian, ByteOrder, LittleEndian}; 3 | use core::{fmt, ops::Deref}; 4 | 5 | /// KTX texture storage format data stored in a complete slice. 6 | /// Provides [`KtxInfo`](../header/trait.KtxInfo.html). 7 | /// 8 | /// See the [specification](https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html). 9 | /// 10 | /// # Example 11 | /// ``` 12 | /// # use ktx::*; 13 | /// let image: Ktx<_> = include_ktx!("../tests/babg-bc3.ktx"); 14 | /// let texture_levels: Vec<&[u8]> = image.textures().collect(); 15 | /// ``` 16 | #[derive(Clone, Copy)] 17 | pub struct Ktx { 18 | header: KtxHeader, 19 | ktx_data: D, 20 | texture_start: u32, 21 | } 22 | 23 | impl AsRef for Ktx { 24 | #[inline] 25 | fn as_ref(&self) -> &KtxHeader { 26 | &self.header 27 | } 28 | } 29 | 30 | impl fmt::Debug for Ktx { 31 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 32 | fmt.debug_struct("Ktx") 33 | .field("header", &self.header) 34 | .finish() 35 | } 36 | } 37 | 38 | impl Ktx 39 | where 40 | D: Deref, 41 | { 42 | /// Parses a complete KTX data slice and returns a `Ktx` instance. 43 | #[inline] 44 | pub fn new(ktx_data: D) -> Self { 45 | let header = KtxHeader::new(&ktx_data); 46 | let texture_start = 64 + header.bytes_of_key_value_data(); 47 | Self { 48 | header, 49 | ktx_data, 50 | texture_start, 51 | } 52 | } 53 | 54 | /// Returns texture data at the input level, starting at `0`. 55 | /// 56 | /// # Panics 57 | /// 58 | /// Input level is >= the `mipmap_levels` value. 59 | #[inline] 60 | pub fn texture_level(&self, level: u32) -> &[u8] { 61 | self.textures().nth(level as _).expect("invalid level") 62 | } 63 | 64 | /// Returns an iterator over the texture levels starting at level 0. 65 | #[inline] 66 | pub fn textures(&self) -> Textures<'_, D> { 67 | Textures { 68 | parent: self, 69 | next_level: 0, 70 | level_end: self.texture_start as _, 71 | } 72 | } 73 | } 74 | 75 | impl From for Ktx 76 | where 77 | D: Deref, 78 | { 79 | #[inline] 80 | fn from(d: D) -> Self { 81 | Ktx::new(d) 82 | } 83 | } 84 | 85 | /// Iterator over texture level data. 86 | /// 87 | /// For cubemap textures each level will contain all 6 faces 88 | /// in order: +X, -X, +Y, -Y, +Z, -Z. 89 | #[derive(Debug)] 90 | pub struct Textures<'a, D> { 91 | parent: &'a Ktx, 92 | next_level: u32, 93 | level_end: usize, 94 | } 95 | 96 | impl<'a, D> Iterator for Textures<'a, D> 97 | where 98 | D: Deref, 99 | { 100 | type Item = &'a [u8]; 101 | 102 | fn next(&mut self) -> Option { 103 | if self.next_level >= self.parent.mipmap_levels() { 104 | None 105 | } else { 106 | self.next_level += 1; 107 | 108 | let l_end = self.level_end; 109 | let mut next_lvl_len = if self.parent.big_endian() { 110 | BigEndian::read_u32(&self.parent.ktx_data[l_end..l_end + 4]) 111 | } else { 112 | LittleEndian::read_u32(&self.parent.ktx_data[l_end..l_end + 4]) 113 | }; 114 | 115 | if self.parent.array_elements() == 0 && self.parent.faces() == 6 { 116 | // Multiply for each face, see https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html#2.16 117 | next_lvl_len *= 6; 118 | } 119 | 120 | self.level_end = l_end + 4 + next_lvl_len as usize; 121 | Some(&self.parent.ktx_data[l_end + 4..self.level_end]) 122 | } 123 | } 124 | } 125 | 126 | impl core::iter::FusedIterator for Textures<'_, D> where D: Deref {} 127 | 128 | /// Wrapper for `include_bytes!` returning `Ktx<'static [u8]>` 129 | /// 130 | /// # Example 131 | /// ``` 132 | /// use ktx::{include_ktx, Ktx}; 133 | /// let image: Ktx<&'static [u8]> = include_ktx!("../tests/babg-bc3.ktx"); 134 | /// ``` 135 | #[macro_export] 136 | macro_rules! include_ktx { 137 | ($path:tt) => { 138 | $crate::Ktx::new(include_bytes!($path) as &[u8]) 139 | }; 140 | } 141 | -------------------------------------------------------------------------------- /test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # run CI-like set of tests 3 | set -eu 4 | 5 | dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 6 | cd "$dir" 7 | 8 | echo "==> test" 9 | cargo test 10 | echo "==> no_std" 11 | cargo build --target thumbv6m-none-eabi --no-default-features 12 | echo "==> rustfmt" 13 | cargo fmt -- --check 14 | -------------------------------------------------------------------------------- /tests/babg-bc3.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexheretic/ktx/98028e48657408d4b32aea753bb2d08f5c4af893/tests/babg-bc3.ktx -------------------------------------------------------------------------------- /tests/example.rs: -------------------------------------------------------------------------------- 1 | use blake2::{Blake2s256, Digest}; 2 | use ktx::*; 3 | use std::{ 4 | fs::File, 5 | io::{self, BufReader}, 6 | sync::Arc, 7 | }; 8 | 9 | #[test] 10 | fn include_logo_example() { 11 | let ktx = include_ktx!("babg-bc3.ktx"); 12 | 13 | assert!(!ktx.big_endian(), "!big_endian"); 14 | assert_eq!(ktx.gl_type(), 0, "gl_type"); 15 | assert_eq!(ktx.gl_type_size(), 1, "gl_type_size"); 16 | assert_eq!(ktx.gl_format(), 0, "gl_format"); 17 | assert_eq!(ktx.gl_internal_format(), 33779, "gl_internal_format"); 18 | assert_eq!( 19 | ktx.gl_base_internal_format(), 20 | 6408, 21 | "gl_base_internal_format" 22 | ); 23 | assert_eq!(ktx.pixel_width(), 260, "pixel_width"); 24 | assert_eq!(ktx.pixel_height(), 200, "pixel_height"); 25 | assert_eq!(ktx.pixel_depth(), 0, "pixel_depth"); 26 | assert_eq!(ktx.array_elements(), 0, "array_elements"); 27 | assert_eq!(ktx.faces(), 1, "faces"); 28 | assert_eq!(ktx.mipmap_levels(), 8, "mipmap_levels"); 29 | assert_eq!(ktx.bytes_of_key_value_data(), 0, "bytes_of_key_value_data"); 30 | } 31 | 32 | #[test] 33 | fn read_logo_example() -> io::Result<()> { 34 | let ktx = ktx::Decoder::new(BufReader::new(File::open("tests/babg-bc3.ktx")?))?; 35 | 36 | assert!(!ktx.big_endian(), "!big_endian"); 37 | assert_eq!(ktx.gl_type(), 0, "gl_type"); 38 | assert_eq!(ktx.gl_type_size(), 1, "gl_type_size"); 39 | assert_eq!(ktx.gl_format(), 0, "gl_format"); 40 | assert_eq!(ktx.gl_internal_format(), 33779, "gl_internal_format"); 41 | assert_eq!( 42 | ktx.gl_base_internal_format(), 43 | 6408, 44 | "gl_base_internal_format" 45 | ); 46 | assert_eq!(ktx.pixel_width(), 260, "pixel_width"); 47 | assert_eq!(ktx.pixel_height(), 200, "pixel_height"); 48 | assert_eq!(ktx.pixel_depth(), 0, "pixel_depth"); 49 | assert_eq!(ktx.array_elements(), 0, "array_elements"); 50 | assert_eq!(ktx.faces(), 1, "faces"); 51 | assert_eq!(ktx.mipmap_levels(), 8, "mipmap_levels"); 52 | assert_eq!(ktx.bytes_of_key_value_data(), 0, "bytes_of_key_value_data"); 53 | Ok(()) 54 | } 55 | 56 | #[test] 57 | fn owned_logo_example() { 58 | let owned_ktx_data: Arc<[u8]> = Arc::from(include_bytes!("babg-bc3.ktx").to_vec()); 59 | let ktx: Ktx> = Ktx::from(owned_ktx_data); 60 | 61 | assert_eq!(ktx.pixel_width(), 260, "pixel_width"); 62 | assert_eq!(ktx.pixel_height(), 200, "pixel_height"); 63 | } 64 | 65 | const LOGO_LEVEL_0_BLAKE: &str = "17ae9dcdc7b7f8c38a66fe00ab92759fde35f74cde2aa52449c2ecbca835a51b"; 66 | const LOGO_LEVEL_1_BLAKE: &str = "ae05372daa8bb0d45de4431db106e107266307e5a37b51825f10618a9605ee1b"; 67 | const LOGO_LEVEL_2_BLAKE: &str = "52ed1d989b8dca91538d68e1077d303a95baf6068d240316bc18c3d8ef5625ea"; 68 | const LOGO_LEVEL_3_BLAKE: &str = "3869a1ccc011b1c74255f2a7ccc2a2c5118a492599aea758c59e4b4b80e3bd6a"; 69 | const LOGO_LEVEL_4_BLAKE: &str = "5cca1fd6eeb47922490392884e2a5a177f791a37da64109705127b092f4073bc"; 70 | const LOGO_LEVEL_5_BLAKE: &str = "2e280b7441e1576d93a7cdf97f67e3fcecdefe209a34c10e9adf5a4158351884"; 71 | const LOGO_LEVEL_6_BLAKE: &str = "22703f682061beb020f2316cbcad901268f1ad7869fd1892062b9d50b92508c0"; 72 | const LOGO_LEVEL_7_BLAKE: &str = "971ccf807344ecef5e43d10bcd0bd9260d35b1632548d045ba2cbbbf8a50075a"; 73 | 74 | #[test] 75 | fn include_logo_example_textures() { 76 | let ktx = include_ktx!("babg-bc3.ktx"); 77 | let mut textures = ktx.textures(); 78 | 79 | assert_eq!( 80 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 81 | LOGO_LEVEL_0_BLAKE 82 | ); 83 | assert_eq!( 84 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 85 | LOGO_LEVEL_1_BLAKE 86 | ); 87 | assert_eq!( 88 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 89 | LOGO_LEVEL_2_BLAKE 90 | ); 91 | assert_eq!( 92 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 93 | LOGO_LEVEL_3_BLAKE 94 | ); 95 | assert_eq!( 96 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 97 | LOGO_LEVEL_4_BLAKE 98 | ); 99 | assert_eq!( 100 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 101 | LOGO_LEVEL_5_BLAKE 102 | ); 103 | assert_eq!( 104 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 105 | LOGO_LEVEL_6_BLAKE 106 | ); 107 | assert_eq!( 108 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 109 | LOGO_LEVEL_7_BLAKE 110 | ); 111 | assert_eq!(textures.next(), None); 112 | } 113 | 114 | #[test] 115 | fn read_logo_example_textures() -> io::Result<()> { 116 | let ktx = ktx::Decoder::new(BufReader::new(File::open("tests/babg-bc3.ktx")?))?; 117 | let mut textures = ktx.read_textures(); 118 | 119 | assert_eq!( 120 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 121 | LOGO_LEVEL_0_BLAKE 122 | ); 123 | assert_eq!( 124 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 125 | LOGO_LEVEL_1_BLAKE 126 | ); 127 | assert_eq!( 128 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 129 | LOGO_LEVEL_2_BLAKE 130 | ); 131 | assert_eq!( 132 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 133 | LOGO_LEVEL_3_BLAKE 134 | ); 135 | assert_eq!( 136 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 137 | LOGO_LEVEL_4_BLAKE 138 | ); 139 | assert_eq!( 140 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 141 | LOGO_LEVEL_5_BLAKE 142 | ); 143 | assert_eq!( 144 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 145 | LOGO_LEVEL_6_BLAKE 146 | ); 147 | assert_eq!( 148 | format!("{:x}", Blake2s256::digest(textures.next().unwrap())), 149 | LOGO_LEVEL_7_BLAKE 150 | ); 151 | assert_eq!(textures.next(), None); 152 | Ok(()) 153 | } 154 | 155 | #[test] 156 | fn logo_example_texture_level() { 157 | let ktx = include_ktx!("babg-bc3.ktx"); 158 | 159 | assert_eq!( 160 | format!("{:x}", Blake2s256::digest(ktx.texture_level(0))), 161 | LOGO_LEVEL_0_BLAKE 162 | ); 163 | assert_eq!( 164 | format!("{:x}", Blake2s256::digest(ktx.texture_level(4))), 165 | LOGO_LEVEL_4_BLAKE 166 | ); 167 | } 168 | 169 | #[test] 170 | fn logo_example_debug() { 171 | let dbg_string = format!("{:?}", include_ktx!("babg-bc3.ktx")); 172 | assert_eq!( 173 | &dbg_string, 174 | "Ktx { header: KtxHeader { big_endian: false, gl_type: 0, gl_type_size: 1, gl_format: 0, gl_internal_format: 33779, gl_base_internal_format: 6408, pixel_width: 260, pixel_height: 200, pixel_depth: 0, array_elements: 0, faces: 1, mipmap_levels: 8, bytes_of_key_value_data: 0 } }" 175 | ); 176 | } 177 | 178 | #[test] 179 | fn uffizi_6face_include() { 180 | let ktx = include_ktx!("uffizi_rgba16f_cube.ktx"); 181 | 182 | assert!(!ktx.big_endian(), "!big_endian"); 183 | assert_eq!(ktx.gl_type(), 5131, "gl_type"); 184 | assert_eq!(ktx.gl_type_size(), 2, "gl_type_size"); 185 | assert_eq!(ktx.gl_format(), 6408, "gl_format"); 186 | assert_eq!(ktx.gl_internal_format(), 34842, "gl_internal_format"); 187 | assert_eq!( 188 | ktx.gl_base_internal_format(), 189 | 6408, 190 | "gl_base_internal_format" 191 | ); 192 | assert_eq!(ktx.pixel_width(), 512, "pixel_width"); 193 | assert_eq!(ktx.pixel_height(), 512, "pixel_height"); 194 | assert_eq!(ktx.pixel_depth(), 0, "pixel_depth"); 195 | assert_eq!(ktx.array_elements(), 0, "array_elements"); 196 | assert_eq!(ktx.faces(), 6, "faces"); 197 | assert_eq!(ktx.mipmap_levels(), 10, "mipmap_levels"); 198 | assert_eq!(ktx.bytes_of_key_value_data(), 0, "bytes_of_key_value_data"); 199 | 200 | assert_eq!(ktx.textures().count(), 10, "ktx.textures().count()"); 201 | } 202 | 203 | #[test] 204 | fn uffizi_6face_read() { 205 | let ktx_file = BufReader::new(File::open("tests/uffizi_rgba16f_cube.ktx").unwrap()); 206 | let ktx = ktx::Decoder::new(ktx_file).unwrap(); 207 | 208 | assert!(!ktx.big_endian(), "!big_endian"); 209 | assert_eq!(ktx.gl_type(), 5131, "gl_type"); 210 | assert_eq!(ktx.gl_type_size(), 2, "gl_type_size"); 211 | assert_eq!(ktx.gl_format(), 6408, "gl_format"); 212 | assert_eq!(ktx.gl_internal_format(), 34842, "gl_internal_format"); 213 | assert_eq!( 214 | ktx.gl_base_internal_format(), 215 | 6408, 216 | "gl_base_internal_format" 217 | ); 218 | assert_eq!(ktx.pixel_width(), 512, "pixel_width"); 219 | assert_eq!(ktx.pixel_height(), 512, "pixel_height"); 220 | assert_eq!(ktx.pixel_depth(), 0, "pixel_depth"); 221 | assert_eq!(ktx.array_elements(), 0, "array_elements"); 222 | assert_eq!(ktx.faces(), 6, "faces"); 223 | assert_eq!(ktx.mipmap_levels(), 10, "mipmap_levels"); 224 | assert_eq!(ktx.bytes_of_key_value_data(), 0, "bytes_of_key_value_data"); 225 | 226 | assert_eq!( 227 | ktx.read_textures().count(), 228 | 10, 229 | "ktx.read_textures().count()" 230 | ); 231 | } 232 | -------------------------------------------------------------------------------- /tests/uffizi_rgba16f_cube.ktx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexheretic/ktx/98028e48657408d4b32aea753bb2d08f5c4af893/tests/uffizi_rgba16f_cube.ktx --------------------------------------------------------------------------------