{"id":13424,"library":"ktx-parse","title":"KTX 2.0 Parser and Serializer","description":"ktx-parse is a JavaScript/TypeScript library designed for parsing and serializing KTX 2.0 (`.ktx2`) container files. It provides programmatic access to the structure and metadata within KTX 2.0 files, including mipmap levels, data format descriptors, and key/value data. Crucially, this library focuses solely on the KTX 2.0 container format and does not include functionality for decompressing or compressing the actual texture data (e.g., Basis Universal, ETC1S, UASTC). Users must integrate separate transcoding libraries (like those from BinomialLLC or KhronosGroup) to handle the compressed GPU texture formats found inside the KTX 2.0 containers. The package is currently at version 1.1.0 and is actively maintained by Don McCurdy, known for his work on glTF-Transform. It offers robust type definitions for TypeScript users and is frequently adopted in 3D graphics and web applications that require efficient GPU texture streaming.","status":"active","version":"1.1.0","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","typescript"],"install":[{"cmd":"npm install ktx-parse","lang":"bash","label":"npm"},{"cmd":"yarn add ktx-parse","lang":"bash","label":"yarn"},{"cmd":"pnpm add ktx-parse","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary function for parsing a KTX 2.0 byte array. While CommonJS `require` is currently supported, ESM `import` is the idiomatic approach for modern TypeScript/JavaScript projects using this library.","wrong":"const { read } = require('ktx-parse');","symbol":"read","correct":"import { read } from 'ktx-parse';"},{"note":"Function for serializing a KTX2Container instance back into a KTX 2.0 byte array.","wrong":"const { write } = require('ktx-parse');","symbol":"write","correct":"import { write } from 'ktx-parse';"},{"note":"This is a TypeScript type import for the parsed KTX 2.0 container object. It is generally used for type hinting rather than direct runtime import.","wrong":null,"symbol":"KTX2Container","correct":"import type { KTX2Container } from 'ktx-parse';"}],"quickstart":{"code":"import { read, write } from 'ktx-parse';\nimport type { KTX2Container } from 'ktx-parse';\n\nasync function processKtx2File(url: string) {\n  try {\n    // Simulate fetching a .ktx2 file (e.g., from a server or local path)\n    console.log(`Fetching KTX2 file from ${url}...`);\n    const response = await fetch(url);\n    if (!response.ok) {\n      throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n    }\n    const arrayBuffer = await response.arrayBuffer();\n    const ktx2Bytes = new Uint8Array(arrayBuffer);\n\n    // Parse the KTX 2.0 file\n    console.log('Parsing KTX2 data...');\n    const container: KTX2Container = read(ktx2Bytes);\n\n    console.log('KTX2 Container parsed successfully:');\n    console.log(`  File format version: ${container.vkFormat}`); // vkFormat is one of the many header properties\n    console.log(`  Pixel Width: ${container.pixelWidth}`);\n    console.log(`  Pixel Height: ${container.pixelHeight}`);\n    console.log(`  Number of mip levels: ${container.levels.length}`);\n    console.log(`  Has Supercompression: ${container.supercompressionScheme !== null}`);\n\n    // Example: Accessing a mip level (level 0 is the largest)\n    if (container.levels.length > 0) {\n      const level0 = container.levels[0];\n      console.log(`  Mip Level 0 data size: ${level0.byteLength} bytes`);\n      // To actually use this data for rendering, you would need a transcoder.\n      // For example, if it's Basis Universal, use a Basis Universal WebAssembly transcoder.\n    }\n\n    // Example: Serialize the container back to bytes (e.g., after modifying metadata)\n    const modifiedKtx2Bytes = write(container);\n    console.log(`Serialized container back to ${modifiedKtx2Bytes.byteLength} bytes.`);\n\n  } catch (error) {\n    console.error('Error processing KTX2 file:', error);\n  }\n}\n\n// Replace with a real KTX2 file URL for testing\n// A common test asset could be a KTX2 file from glTF-Sample-Models or a similar source.\nprocessKtx2File('https://raw.githubusercontent.com/KhronosGroup/KTX-Sample-Assets/main/KTX-Software/images/test_images_ktx2/astc_8x8_rgba_ldr.ktx2');","lang":"typescript","description":"This quickstart demonstrates how to fetch a KTX 2.0 file, parse its binary data using `ktx-parse`, access key properties like dimensions and mipmap levels, and then serialize the container back into a byte array. It highlights that the raw texture data from `container.levels` requires external transcoders for decoding."},"warnings":[{"fix":"Integrate an appropriate texture transcoder (e.g., KhronosGroup/Universal-Texture-Transcoders) alongside ktx-parse to handle the compressed texture data. First, parse the KTX2 container, then pass the relevant mip level data to your chosen transcoder.","message":"ktx-parse is a container parser and serializer; it does not include functionality to decompress or compress the actual GPU texture data (e.g., Basis Universal, ETC1S, UASTC, ASTC) contained within the KTX 2.0 file. To display or process the texture pixels, you must integrate a separate WebAssembly-based texture transcoder (e.g., `basisu_wasm`, `ktx2decoder`, or a custom solution).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If modifications to the original source buffer are necessary, ensure that a deep copy of the `KTX2Container` data (especially mip levels and other binary fields) is made before performing any write operations on the source buffer.","message":"When accessing mip levels or other binary data from a parsed `KTX2Container`, the returned `Uint8Array`s are direct views into the original source `ArrayBuffer`. Modifying the underlying source buffer after parsing can lead to unexpected behavior or data corruption in the `KTX2Container` object.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify that the input data is a valid KTX 2.0 file. Check the file extension (`.ktx2`) and ensure the file is not corrupted during transfer or loading. If it's a KTX 1.x file, `ktx-parse` is not the correct library.","cause":"The provided `Uint8Array` or `ArrayBuffer` does not start with the magic identifier bytes for a KTX 2.0 file, indicating it's either not a KTX 2.0 file, is corrupted, or is an unsupported KTX 1.x file.","error":"Error: Missing KTX 2.0 identifier."},{"fix":"Always check `container.levels.length` before attempting to access individual mip levels. Ensure the KTX2 file is well-formed and contains the expected number of mip levels.","cause":"This often occurs when attempting to access `container.levels[x].byteLength` or `container.levels[x].data` for a mip level that does not exist or if the `levels` array is empty, which can happen with malformed KTX2 files or if basic validation wasn't performed.","error":"TypeError: Cannot read properties of undefined (reading 'byteLength') or similar when accessing texture data."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}