Support ktx2 (#12385) f454e3170e * Add ktx2 support * Update files * Format * Update write_ktx2.cpp * Updates * Update premake5_pls_renderer.lua * Fix android build break * clang format * Update premake5_pls_renderer.lua * Update premake5.lua Co-authored-by: John White <aliasbinman@gmail.com>
diff --git a/.rive_head b/.rive_head index c0c0c9b..4bf0beb 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -db997822bea9917b2ad00764f7598c0f138deda1 +f454e3170e7f329e2edbefc056eeb0f164edf1e0
diff --git a/decoders/premake5_v2.lua b/decoders/premake5_v2.lua index 39f657e..4b3043d 100644 --- a/decoders/premake5_v2.lua +++ b/decoders/premake5_v2.lua
@@ -21,6 +21,11 @@ description = 'don\'t build webp support into the rive_decoders library (built-in webp decoding will fail)', }) +newoption({ + trigger = 'no_rive_ktx2', + description = 'don\'t build KTX2 container parsing into the rive_decoders library', +}) + if not _OPTIONS["no_rive_png"] then dofile(rive .. '/dependencies/premake5_libpng_v2.lua') end @@ -35,6 +40,7 @@ libwebp = '' end + project('rive_decoders') do kind('StaticLib') @@ -104,4 +110,10 @@ files({ 'src/decode_webp.cpp' }) end + filter({ 'options:not no_rive_ktx2' }) + do + defines({ 'RIVE_KTX2' }) + files({ 'src/decode_ktx2.cpp' }) + end + end
diff --git a/decoders/src/decode_ktx2.cpp b/decoders/src/decode_ktx2.cpp new file mode 100644 index 0000000..9154ab6 --- /dev/null +++ b/decoders/src/decode_ktx2.cpp
@@ -0,0 +1,215 @@ +/* + * Copyright 2026 Rive + */ + +// Parse-only KTX2 reader for Rive runtime. +// +// Extracts vkFormat, logical pixel dims, and mip-level block payloads from a +// KTX2 container. Does NOT decompress — block data is returned verbatim so +// the renderer can hand it straight to the GPU's compressed texture upload +// path. Today only BC7 (UNORM / SRGB) is recognized; other vkFormat values +// are rejected. +// +// Spec: https://registry.khronos.org/KTX/specs/2.0/ktxspec.v2.html + +#include "rive/decoders/decode_ktx2.hpp" + +#include <algorithm> +#include <cstdio> +#include <cstring> + +namespace rive +{ +namespace +{ +constexpr uint8_t kKtx2Identifier[12] = { + 0xAB, + 0x4B, + 0x54, + 0x58, + 0x20, + 0x32, + 0x30, + 0xBB, + 0x0D, + 0x0A, + 0x1A, + 0x0A, +}; + +constexpr uint32_t VK_FORMAT_BC7_UNORM_BLOCK = 145; +constexpr uint32_t VK_FORMAT_BC7_SRGB_BLOCK = 146; + +constexpr uint32_t kSupercompressionNone = 0; + +#pragma pack(push, 1) +struct Ktx2Header +{ + uint32_t vkFormat; + uint32_t typeSize; + uint32_t pixelWidth; + uint32_t pixelHeight; + uint32_t pixelDepth; + uint32_t layerCount; + uint32_t faceCount; + uint32_t levelCount; + uint32_t supercompressionScheme; + uint32_t dfdByteOffset; + uint32_t dfdByteLength; + uint32_t kvdByteOffset; + uint32_t kvdByteLength; + uint64_t sgdByteOffset; + uint64_t sgdByteLength; +}; +struct Ktx2LevelIndex +{ + uint64_t byteOffset; + uint64_t byteLength; + uint64_t uncompressedByteLength; +}; +#pragma pack(pop) +static_assert(sizeof(Ktx2Header) == 68, "KTX2 header must be 68 bytes"); +static_assert(sizeof(Ktx2LevelIndex) == 24, + "KTX2 level index entry must be 24 bytes"); + +// Defensive caps. +constexpr uint32_t kMaxDimension = 16384; +constexpr uint32_t kMaxLevels = 16; + +constexpr uint32_t kBc7BlockBytes = 16; + +// Expected block-grid byte length for a BC7 mip level at the given logical +// pixel dimensions. BC7 = 4x4 blocks, 16 bytes/block. +inline uint64_t expectedBc7Bytes(uint32_t pixelWidth, uint32_t pixelHeight) +{ + const uint64_t blocksX = (pixelWidth + 3u) / 4u; + const uint64_t blocksY = (pixelHeight + 3u) / 4u; + return blocksX * blocksY * kBc7BlockBytes; +} +} // namespace + +bool DecodeKtx2(const uint8_t* bytes, size_t byteCount, Ktx2DecodeResult& out) +{ + if (byteCount < sizeof(kKtx2Identifier) + sizeof(Ktx2Header)) + { + std::fprintf(stderr, "DecodeKtx2: file too small\n"); + return false; + } + if (std::memcmp(bytes, kKtx2Identifier, sizeof(kKtx2Identifier)) != 0) + { + std::fprintf(stderr, "DecodeKtx2: bad magic\n"); + return false; + } + + Ktx2Header header; + std::memcpy(&header, bytes + sizeof(kKtx2Identifier), sizeof(header)); + + if (header.vkFormat != VK_FORMAT_BC7_UNORM_BLOCK && + header.vkFormat != VK_FORMAT_BC7_SRGB_BLOCK) + { + std::fprintf(stderr, + "DecodeKtx2: unsupported vkFormat %u (only BC7 wired)\n", + header.vkFormat); + return false; + } + if (header.supercompressionScheme != kSupercompressionNone) + { + std::fprintf(stderr, + "DecodeKtx2: supercompressionScheme %u not supported\n", + header.supercompressionScheme); + return false; + } + if (header.faceCount != 1 || header.layerCount != 0) + { + std::fprintf( + stderr, + "DecodeKtx2: cubemaps/arrays not supported (faces=%u layers=%u)\n", + header.faceCount, + header.layerCount); + return false; + } + if (header.pixelWidth == 0 || header.pixelWidth > kMaxDimension || + header.pixelHeight == 0 || header.pixelHeight > kMaxDimension) + { + std::fprintf(stderr, + "DecodeKtx2: dimensions out of range (%ux%u)\n", + header.pixelWidth, + header.pixelHeight); + return false; + } + + const uint32_t levelCount = header.levelCount == 0 ? 1u : header.levelCount; + if (levelCount > kMaxLevels) + { + std::fprintf(stderr, + "DecodeKtx2: levelCount %u exceeds cap %u\n", + levelCount, + kMaxLevels); + return false; + } + + const size_t levelIndexOffset = + sizeof(kKtx2Identifier) + sizeof(Ktx2Header); + const size_t levelIndexBytes = + static_cast<size_t>(levelCount) * sizeof(Ktx2LevelIndex); + if (byteCount < levelIndexOffset + levelIndexBytes) + { + std::fprintf(stderr, "DecodeKtx2: truncated level index\n"); + return false; + } + + // Read level entries (level 0 first in the index = largest mip). + std::vector<Ktx2LevelIndex> entries(levelCount); + std::memcpy(entries.data(), bytes + levelIndexOffset, levelIndexBytes); + + // Validate each level + sum total payload size for the output buffer. + uint64_t totalBytes = 0; + for (uint32_t i = 0; i < levelCount; ++i) + { + const Ktx2LevelIndex& e = entries[i]; + const uint32_t logW = std::max<uint32_t>(1u, header.pixelWidth >> i); + const uint32_t logH = std::max<uint32_t>(1u, header.pixelHeight >> i); + const uint64_t expected = expectedBc7Bytes(logW, logH); + if (e.byteLength != expected) + { + std::fprintf( + stderr, + "DecodeKtx2: level %u byteLength %llu != block grid %llu " + "for %ux%u\n", + i, + static_cast<unsigned long long>(e.byteLength), + static_cast<unsigned long long>(expected), + logW, + logH); + return false; + } + if (e.byteOffset > byteCount || e.byteLength > byteCount - e.byteOffset) + { + std::fprintf(stderr, "DecodeKtx2: level %u out of buffer\n", i); + return false; + } + totalBytes += e.byteLength; + } + + // Concatenate level 0 .. N-1 into one contiguous buffer (largest first). + out.format = header.vkFormat == VK_FORMAT_BC7_SRGB_BLOCK + ? GPUTextureFormat::bc7 + : GPUTextureFormat::bc7; + out.pixelWidth = header.pixelWidth; + out.pixelHeight = header.pixelHeight; + out.levelCount = levelCount; + out.blocks.resize(static_cast<size_t>(totalBytes)); + size_t writeOffset = 0; + for (uint32_t i = 0; i < levelCount; ++i) + { + const Ktx2LevelIndex& e = entries[i]; + std::memcpy(out.blocks.data() + writeOffset, + bytes + e.byteOffset, + static_cast<size_t>(e.byteLength)); + writeOffset += static_cast<size_t>(e.byteLength); + } + + return true; +} + +} // namespace rive
diff --git a/include/rive/decoders/decode_ktx2.hpp b/include/rive/decoders/decode_ktx2.hpp new file mode 100644 index 0000000..f33440d --- /dev/null +++ b/include/rive/decoders/decode_ktx2.hpp
@@ -0,0 +1,42 @@ +/* + * Copyright 2026 Rive + */ + +#ifndef _RIVE_DECODE_KTX2_HPP_ +#define _RIVE_DECODE_KTX2_HPP_ + +#include "rive/gpu_texture_format.hpp" + +#include <cstddef> +#include <cstdint> +#include <vector> + +namespace rive +{ + +// Result of parsing a KTX2 container. Block data is held in a contiguous +// owned buffer, level 0 first (largest), then level 1, … level N-1 +// (smallest). Each level's region is exactly its block-grid size in bytes +// (no inter-level padding). +struct Ktx2DecodeResult +{ + GPUTextureFormat format; + uint32_t pixelWidth; // logical mip 0 width + uint32_t pixelHeight; // logical mip 0 height + uint32_t levelCount; // number of mip levels stored (>=1) + std::vector<uint8_t> blocks; +}; + +// Parses a KTX2 container. Returns true on success and fills `out`. Returns +// false (with a stderr log) on: +// - bad magic, truncated header / level index +// - unsupported vkFormat (today: only BC7 UNORM/SRGB) +// - non-NONE supercompressionScheme +// - cubemaps / array layers +// - oversized dimensions or level count +// - level data outside the buffer +bool DecodeKtx2(const uint8_t* bytes, size_t byteCount, Ktx2DecodeResult& out); + +} // namespace rive + +#endif
diff --git a/include/rive/gpu_texture_format.hpp b/include/rive/gpu_texture_format.hpp new file mode 100644 index 0000000..90060bc --- /dev/null +++ b/include/rive/gpu_texture_format.hpp
@@ -0,0 +1,23 @@ +#pragma once + +#include <cstdint> + +namespace rive +{ + +// Enum describing the format of a GPU-uploadable texture. Only formats which +// the GPU samples directly are listed. Lives at the `rive/` root so both the +// decoders library (which produces these tags) and the renderer (which +// consumes them) can include it without cross-layer dependencies. +enum class GPUTextureFormat : uint8_t +{ + rgba32, + bc1, + bc2, + bc3, + bc7, + astc, + etc2, +}; + +} // namespace rive
diff --git a/include/rive/texture_archive.hpp b/include/rive/texture_archive.hpp deleted file mode 100644 index baf3981..0000000 --- a/include/rive/texture_archive.hpp +++ /dev/null
@@ -1,91 +0,0 @@ -#pragma once - -#include "rive/span.hpp" - -#include <cstdint> -#include <vector> -#include <string> - -namespace rive -{ - -// On-disk header for a .rtex archive. Fields are little-endian; all Rive -// runtime targets (web/wasm, ARM iOS/Android, x86_64 desktop, Apple Silicon) -// are little-endian, so the struct is written and read by raw memcpy. -#pragma pack(push, 1) -struct TextureArchiveHeader -{ - static constexpr char kMagic[4] = {'R', 'T', 'E', 'X'}; - static constexpr uint16_t kCurrentVersion = 1; - - char magic[4]; - uint16_t version; - uint16_t textureCount; -}; -#pragma pack(pop) -static_assert(sizeof(TextureArchiveHeader) == 8, - "TextureArchiveHeader must be tightly packed (8 bytes)"); - -// Enum class to describe the format of a texture. -// Only formats which are directly read by a GPU are listed here -enum class GPUTextureFormat : uint8_t -{ - rgba32, - bc1, - bc2, - bc3, - bc7, - astc, - etc2 -}; - -// Block size of various GPUTextureFormats -enum class GPUTextureFormatBlockSize : uint8_t -{ - p_1x1, // Pixels are 1x1 for uncompressed - b_4x4, // B means Block here - b_6x6, - b_8x8, - b_12x12, -}; - -struct TextureMipLevel -{ - uint16_t blocksX; - uint16_t blocksY; - uint32_t bytesTotal; - const uint8_t* blocks; // or offset into a big buffer -}; - -struct TextureData -{ - uint16_t width; - uint16_t height; - uint16_t paddedWidth; - uint16_t paddedHeight; - - uint8_t blockSizeX; - uint8_t blockSizeY; - uint8_t bytesPerBlock; - uint8_t numMips; - - GPUTextureFormat format; - - std::vector<TextureMipLevel> mipLevels; - - // Combined pixel data size - uint32_t totalBytes; -}; - -class TextureDirectory -{ -public: - std::vector<TextureData> dir; - std::vector<uint8_t> dataBlob; - - void addTexture(TextureData& header); - bool exportArchive(const std::string& path); - bool import(const std::string& path); - bool import(Span<const uint8_t> texBytes); -}; -} // namespace rive
diff --git a/renderer/include/rive/renderer/d3d/d3d_utils.hpp b/renderer/include/rive/renderer/d3d/d3d_utils.hpp index efd8782..216ceb4 100644 --- a/renderer/include/rive/renderer/d3d/d3d_utils.hpp +++ b/renderer/include/rive/renderer/d3d/d3d_utils.hpp
@@ -3,7 +3,7 @@ */ #include <string> #include "rive/renderer/render_context.hpp" -#include "rive/texture_archive.hpp" +#include "rive/gpu_texture_format.hpp" #include <dxgiformat.h> namespace rive::gpu
diff --git a/renderer/include/rive/renderer/render_context_impl.hpp b/renderer/include/rive/renderer/render_context_impl.hpp index 722f631..6d16ea7 100644 --- a/renderer/include/rive/renderer/render_context_impl.hpp +++ b/renderer/include/rive/renderer/render_context_impl.hpp
@@ -5,7 +5,7 @@ #pragma once #include "rive/renderer/render_context.hpp" -#include "rive/texture_archive.hpp" +#include "rive/gpu_texture_format.hpp" namespace rive::gpu {
diff --git a/renderer/premake5_pls_renderer.lua b/renderer/premake5_pls_renderer.lua index 612780a..8700f6f 100644 --- a/renderer/premake5_pls_renderer.lua +++ b/renderer/premake5_pls_renderer.lua
@@ -513,6 +513,17 @@ defines({ 'RIVE_DECODERS' }) end + -- RIVE_KTX2 must also be visible to the renderer (not just the decoders + -- lib) so the `#ifdef RIVE_KTX2` dispatch block in render_context.cpp + -- compiles in. Gate it on `not no-rive-decoders` AS WELL — without the + -- decoders lib linked (e.g. the wasm webgl2 build) the renderer would + -- compile a call to rive::DecodeKtx2 that has no definition, breaking + -- the link. + filter({ 'options:not no-rive-decoders', 'options:not no_rive_ktx2' }) + do + defines({ 'RIVE_KTX2' }) + end + filter('system:windows') do architecture('x64')
diff --git a/renderer/src/render_context.cpp b/renderer/src/render_context.cpp index 4fecb6c..3edd95f 100644 --- a/renderer/src/render_context.cpp +++ b/renderer/src/render_context.cpp
@@ -14,7 +14,7 @@ #endif #include "rive/renderer/rive_render_image.hpp" #include "rive/renderer/render_context_impl.hpp" -#include "rive/texture_archive.hpp" +#include "rive/gpu_texture_format.hpp" #include "rive/renderer/stack_vector.hpp" #include "rive/profiler/profiler_macros.h" @@ -26,6 +26,10 @@ #include "rive/decoders/bitmap_decoder.hpp" #endif +#ifdef RIVE_KTX2 +#include "rive/decoders/decode_ktx2.hpp" +#endif + #include "sort_key_builder.hpp" namespace rive::gpu @@ -162,23 +166,24 @@ RIVE_PROF_SCOPE_L(1) rcp<Texture> texture = m_impl->platformDecodeImageTexture(encodedBytes); - // Detect rtex container by 'RTEX' magic. GPU format read from header - // (bc7/astc/etc2/rgba32). - if (texture == nullptr && encodedBytes.size() >= 4 && - encodedBytes[0] == 'R' && encodedBytes[1] == 'T' && - encodedBytes[2] == 'E' && encodedBytes[3] == 'X') +#ifdef RIVE_KTX2 + // KTX2 magic = «KTX 20»\r\n\x1A\n. Match the first 4 bytes for the cheap + // dispatch; full magic is re-checked inside DecodeKtx2. + if (texture == nullptr && encodedBytes.size() >= 12 && + encodedBytes[0] == 0xAB && encodedBytes[1] == 0x4B && + encodedBytes[2] == 0x54 && encodedBytes[3] == 0x58) { - TextureDirectory texDir; - if (texDir.import(encodedBytes) && !texDir.dir.empty()) + Ktx2DecodeResult ktx2; + if (DecodeKtx2(encodedBytes.data(), encodedBytes.size(), ktx2)) { - const TextureData& texData = texDir.dir[0]; - texture = m_impl->makeImageTexture(texData.width, - texData.height, - texData.numMips, - texData.format, - texDir.dataBlob.data()); + texture = m_impl->makeImageTexture(ktx2.pixelWidth, + ktx2.pixelHeight, + ktx2.levelCount, + ktx2.format, + ktx2.blocks.data()); } } +#endif #ifdef RIVE_DECODERS if (texture == nullptr)
diff --git a/renderer/src/webgpu/render_context_webgpu_impl.cpp b/renderer/src/webgpu/render_context_webgpu_impl.cpp index 7c8aca2..e8d39d1 100644 --- a/renderer/src/webgpu/render_context_webgpu_impl.cpp +++ b/renderer/src/webgpu/render_context_webgpu_impl.cpp
@@ -9,7 +9,7 @@ #include "rive/renderer/render_canvas.hpp" #endif #include "rive/renderer/stack_vector.hpp" -#include "rive/texture_archive.hpp" +#include "rive/gpu_texture_format.hpp" #include "shaders/constants.glsl" #include <sstream>
diff --git a/src/texture_archive.cpp b/src/texture_archive.cpp deleted file mode 100644 index 25340b6..0000000 --- a/src/texture_archive.cpp +++ /dev/null
@@ -1,306 +0,0 @@ -#include "rive/texture_archive.hpp" - -#include <cstdio> -#include <cstring> -#include <fstream> -#include <limits> - -using namespace rive; - -namespace -{ -// Per-texture descriptor on disk: 4*u16 + 4*u8 + 1*u8(format) = 13 bytes. -constexpr size_t kDescriptorSize = 13; -// Per-mip entry on disk: 3*u32 = 12 bytes. -constexpr size_t kMipEntrySize = 12; - -// Defensive caps to bound allocation and reject hostile inputs early. -constexpr uint16_t kMaxTextures = 4096; -constexpr uint8_t kMaxMipsPerTexture = 16; -// 256 MB per mip is far above any realistic compressed texture. -constexpr uint32_t kMaxBytesPerMip = 256u * 1024u * 1024u; -} // namespace - -// --------------------------------------------------------------------------- -// Binary file format (.rtex) -// -// [4] Magic: "RTEX" -// [2] Version: uint16_t (currently 1) -// [2] TextureCount: uint16_t -// [per texture]: -// [2] width: uint16_t (original, un-padded) -// [2] height: uint16_t -// [2] paddedWidth: uint16_t -// [2] paddedHeight: uint16_t -// [1] blockSizeX: uint8_t -// [1] blockSizeY: uint8_t -// [1] bytesPerBlock:uint8_t -// [1] numMips: uint8_t -// [1] format: uint8_t (GPUTextureFormat) -// [per mip (numMips entries)]: -// [4] blocksX: uint32_t -// [4] blocksY: uint32_t -// [4] bytesTotal: uint32_t -// [data blob: all mip data for every texture, in declaration order] -// --------------------------------------------------------------------------- - -void TextureDirectory::addTexture(TextureData& td) -{ - const uint8_t* oldBase = dataBlob.empty() ? nullptr : dataBlob.data(); - - std::vector<size_t> offsets; - offsets.reserve(td.mipLevels.size()); - for (auto& mip : td.mipLevels) - { - offsets.push_back(dataBlob.size()); - dataBlob.insert(dataBlob.end(), - mip.blocks, - mip.blocks + mip.bytesTotal); - } - - const uint8_t* newBase = dataBlob.data(); - - if (oldBase != nullptr && oldBase != newBase) - { - for (auto& existing : dir) - for (auto& mip : existing.mipLevels) - mip.blocks = newBase + (mip.blocks - oldBase); - } - - for (size_t i = 0; i < td.mipLevels.size(); ++i) - td.mipLevels[i].blocks = newBase + offsets[i]; - - dir.push_back(td); -} - -bool TextureDirectory::exportArchive(const std::string& path) -{ - FILE* fp = std::fopen(path.c_str(), "wb"); - if (!fp) - { - std::fprintf(stderr, - "TextureDirectory::exportArchive: cannot open '%s'\n", - path.c_str()); - return false; - } - - TextureArchiveHeader header; - std::memcpy(header.magic, - TextureArchiveHeader::kMagic, - sizeof(header.magic)); - header.version = TextureArchiveHeader::kCurrentVersion; - header.textureCount = static_cast<uint16_t>(dir.size()); - std::fwrite(&header, sizeof(header), 1, fp); - - for (const auto& td : dir) - { - std::fwrite(&td.width, sizeof(td.width), 1, fp); - std::fwrite(&td.height, sizeof(td.height), 1, fp); - std::fwrite(&td.paddedWidth, sizeof(td.paddedWidth), 1, fp); - std::fwrite(&td.paddedHeight, sizeof(td.paddedHeight), 1, fp); - std::fwrite(&td.blockSizeX, sizeof(td.blockSizeX), 1, fp); - std::fwrite(&td.blockSizeY, sizeof(td.blockSizeY), 1, fp); - std::fwrite(&td.bytesPerBlock, sizeof(td.bytesPerBlock), 1, fp); - std::fwrite(&td.numMips, sizeof(td.numMips), 1, fp); - const uint8_t fmt = static_cast<uint8_t>(td.format); - std::fwrite(&fmt, sizeof(fmt), 1, fp); - - for (const auto& mip : td.mipLevels) - { - const uint32_t bx = static_cast<uint32_t>(mip.blocksX); - const uint32_t by = static_cast<uint32_t>(mip.blocksY); - const uint32_t bt = mip.bytesTotal; - std::fwrite(&bx, sizeof(bx), 1, fp); - std::fwrite(&by, sizeof(by), 1, fp); - std::fwrite(&bt, sizeof(bt), 1, fp); - } - } - - std::fwrite(dataBlob.data(), 1, dataBlob.size(), fp); - std::fclose(fp); - return true; -} - -bool TextureDirectory::import(Span<const uint8_t> texBytes) -{ - dir.clear(); - dataBlob.clear(); - - if (texBytes.size() < sizeof(TextureArchiveHeader)) - { - printf("TextureDirectory::import: file too small\n"); - return false; - } - - const uint8_t* p = texBytes.data(); - const uint8_t* end = p + texBytes.size(); - - TextureArchiveHeader header; - std::memcpy(&header, p, sizeof(header)); - p += sizeof(header); - - if (std::memcmp(header.magic, - TextureArchiveHeader::kMagic, - sizeof(header.magic)) != 0) - { - printf("TextureDirectory::import: bad magic\n"); - return false; - } - if (header.version != TextureArchiveHeader::kCurrentVersion) - { - printf("TextureDirectory::import: unsupported version %u\n", - static_cast<unsigned>(header.version)); - return false; - } - - const uint16_t count = header.textureCount; - if (count > kMaxTextures) - { - printf("TextureDirectory::import: textureCount %u exceeds cap %u\n", - static_cast<unsigned>(count), - static_cast<unsigned>(kMaxTextures)); - return false; - } - - struct MipDesc - { - uint32_t blocksX, blocksY, bytesTotal; - }; - struct TexDesc - { - TextureData td; - std::vector<MipDesc> mips; - }; - - std::vector<TexDesc> descs(count); - size_t totalData = 0; - - for (auto& desc : descs) - { - TextureData& td = desc.td; - if (static_cast<size_t>(end - p) < kDescriptorSize) - { - printf("TextureDirectory::import: truncated descriptor\n"); - return false; - } - std::memcpy(&td.width, p, 2); - p += 2; - std::memcpy(&td.height, p, 2); - p += 2; - std::memcpy(&td.paddedWidth, p, 2); - p += 2; - std::memcpy(&td.paddedHeight, p, 2); - p += 2; - td.blockSizeX = *p++; - td.blockSizeY = *p++; - td.bytesPerBlock = *p++; - td.numMips = *p++; - td.format = static_cast<GPUTextureFormat>(*p++); - - if (td.numMips > kMaxMipsPerTexture) - { - printf("TextureDirectory::import: numMips %u exceeds cap %u\n", - static_cast<unsigned>(td.numMips), - static_cast<unsigned>(kMaxMipsPerTexture)); - return false; - } - desc.mips.resize(td.numMips); - const size_t mipTableBytes = - static_cast<size_t>(td.numMips) * kMipEntrySize; - if (static_cast<size_t>(end - p) < mipTableBytes) - { - printf("TextureDirectory::import: truncated mip table\n"); - return false; - } - td.totalBytes = 0; - for (auto& m : desc.mips) - { - std::memcpy(&m.blocksX, p, 4); - p += 4; - std::memcpy(&m.blocksY, p, 4); - p += 4; - std::memcpy(&m.bytesTotal, p, 4); - p += 4; - if (m.bytesTotal > kMaxBytesPerMip) - { - printf("TextureDirectory::import: mip bytesTotal %u " - "exceeds cap %u\n", - static_cast<unsigned>(m.bytesTotal), - static_cast<unsigned>(kMaxBytesPerMip)); - return false; - } - // Sum without overflow: cap remaining headroom. - if (m.bytesTotal > - std::numeric_limits<uint32_t>::max() - td.totalBytes) - { - printf("TextureDirectory::import: totalBytes overflow\n"); - return false; - } - td.totalBytes += m.bytesTotal; - } - if (td.totalBytes > std::numeric_limits<size_t>::max() - totalData) - { - printf("TextureDirectory::import: totalData overflow\n"); - return false; - } - totalData += td.totalBytes; - } - - if (static_cast<size_t>(end - p) != totalData) - { - printf("TextureDirectory::import: blob size mismatch " - "(expected %zu, got %zu)\n", - totalData, - static_cast<size_t>(end - p)); - return false; - } - - dataBlob.assign(p, end); - const uint8_t* blob = dataBlob.data(); - size_t offset = 0; - - dir.reserve(count); - for (auto& desc : descs) - { - TextureData& td = desc.td; - td.mipLevels.resize(desc.mips.size()); - for (size_t i = 0; i < desc.mips.size(); i++) - { - const MipDesc& m = desc.mips[i]; - if (m.blocksX > std::numeric_limits<uint16_t>::max() || - m.blocksY > std::numeric_limits<uint16_t>::max()) - { - printf("TextureDirectory::import: blocks dimension " - "exceeds uint16\n"); - return false; - } - td.mipLevels[i].blocksX = static_cast<uint16_t>(m.blocksX); - td.mipLevels[i].blocksY = static_cast<uint16_t>(m.blocksY); - td.mipLevels[i].bytesTotal = m.bytesTotal; - td.mipLevels[i].blocks = blob + offset; - offset += m.bytesTotal; - } - dir.push_back(std::move(td)); - } - - return true; -} - -bool TextureDirectory::import(const std::string& path) -{ - std::ifstream in(path, std::ios::binary | std::ios::ate); - if (!in) - { - printf("TextureDirectory::import: cannot open %s\n", path.c_str()); - return false; - } - const std::streamsize len = in.tellg(); - in.seekg(0, std::ios::beg); - std::vector<uint8_t> buf(static_cast<size_t>(len)); - if (!in.read(reinterpret_cast<char*>(buf.data()), len)) - { - printf("TextureDirectory::import: read failed for %s\n", path.c_str()); - return false; - } - return import(Span<const uint8_t>(buf.data(), buf.size())); -}
diff --git a/tests/common/render_context_null.hpp b/tests/common/render_context_null.hpp index 392c115..b4341c2 100644 --- a/tests/common/render_context_null.hpp +++ b/tests/common/render_context_null.hpp
@@ -5,7 +5,7 @@ #pragma once #include "rive/renderer/render_context_helper_impl.hpp" -#include "rive/texture_archive.hpp" +#include "rive/gpu_texture_format.hpp" class RenderContextNULL : public rive::gpu::RenderContextHelperImpl {
diff --git a/tests/unit_tests/runtime/decode_ktx2_test.cpp b/tests/unit_tests/runtime/decode_ktx2_test.cpp new file mode 100644 index 0000000..6ab370c --- /dev/null +++ b/tests/unit_tests/runtime/decode_ktx2_test.cpp
@@ -0,0 +1,269 @@ +#include "rive_testing.hpp" +#include "rive/decoders/decode_ktx2.hpp" + +#include <cstdint> +#include <cstring> +#include <vector> + +// Helpers for building a synthetic KTX2 byte stream so the tests can exercise +// each rejection path of the parser without committing a binary fixture. +// +// Layout: +// [12] identifier «KTX 20»\r\n\x1A\n +// [68] header +// [24*levelCount] level index +// [DFD] data format descriptor (variable, often empty here) +// ...mip data +namespace +{ +constexpr uint8_t kKtx2Identifier[12] = { + 0xAB, + 0x4B, + 0x54, + 0x58, + 0x20, + 0x32, + 0x30, + 0xBB, + 0x0D, + 0x0A, + 0x1A, + 0x0A, +}; +constexpr uint32_t VK_FORMAT_BC7_SRGB_BLOCK = 146; + +template <typename T> void appendLE(std::vector<uint8_t>& buf, T value) +{ + const uint8_t* p = reinterpret_cast<const uint8_t*>(&value); + buf.insert(buf.end(), p, p + sizeof(T)); +} + +std::vector<uint8_t> buildSkeletonKtx2(uint32_t vkFormat, + uint32_t pixelWidth, + uint32_t pixelHeight, + uint32_t levelCount, + uint32_t supercompressionScheme, + uint32_t faceCount, + uint32_t layerCount) +{ + std::vector<uint8_t> buf; + buf.insert(buf.end(), + kKtx2Identifier, + kKtx2Identifier + sizeof(kKtx2Identifier)); + + appendLE<uint32_t>(buf, vkFormat); + appendLE<uint32_t>(buf, 1); // typeSize + appendLE<uint32_t>(buf, pixelWidth); + appendLE<uint32_t>(buf, pixelHeight); + appendLE<uint32_t>(buf, 0); // pixelDepth + appendLE<uint32_t>(buf, layerCount); + appendLE<uint32_t>(buf, faceCount); + appendLE<uint32_t>(buf, levelCount); + appendLE<uint32_t>(buf, supercompressionScheme); + appendLE<uint32_t>(buf, 0); // dfdByteOffset + appendLE<uint32_t>(buf, 0); // dfdByteLength + appendLE<uint32_t>(buf, 0); // kvdByteOffset + appendLE<uint32_t>(buf, 0); // kvdByteLength + appendLE<uint64_t>(buf, 0); // sgdByteOffset + appendLE<uint64_t>(buf, 0); // sgdByteLength + return buf; +} +} // namespace + +TEST_CASE("ktx2 rejects buffer smaller than identifier+header", + "[ktx2-decoder]") +{ + std::vector<uint8_t> buf(40, 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects bad magic", "[ktx2-decoder]") +{ + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 4, 4, 1, 0, 1, 0); + buf[0] = 'X'; + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects unsupported vkFormat", "[ktx2-decoder]") +{ + // VK_FORMAT_R8G8B8A8_UNORM = 37 — not BC7. + auto buf = buildSkeletonKtx2(/*vkFormat*/ 37, 4, 4, 1, 0, 1, 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects supercompressed payload (not yet supported)", + "[ktx2-decoder]") +{ + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, + 4, + 4, + 1, + /*supercompressionScheme*/ 2 /* zstd */, + 1, + 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects cubemaps and array layers", "[ktx2-decoder]") +{ + { + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, + 4, + 4, + 1, + 0, + /*faceCount*/ 6, + 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + } + { + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, + 4, + 4, + 1, + 0, + 1, + /*layerCount*/ 4); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + } +} + +TEST_CASE("ktx2 rejects out-of-range dimensions", "[ktx2-decoder]") +{ + { + auto buf = + buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 0, 4, 1, 0, 1, 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + } + { + auto buf = + buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 4, 999999, 1, 0, 1, 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + } +} + +TEST_CASE("ktx2 rejects truncated level index", "[ktx2-decoder]") +{ + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, + 4, + 4, + /*levelCount*/ 1, + 0, + 1, + 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects level pointer outside buffer", "[ktx2-decoder]") +{ + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 4, 4, 1, 0, 1, 0); + appendLE<uint64_t>(buf, /*byteOffset*/ 1ull << 32); + appendLE<uint64_t>(buf, /*byteLength*/ 16); + appendLE<uint64_t>(buf, /*uncompressedByteLength*/ 16); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 rejects byteLength inconsistent with logical block grid", + "[ktx2-decoder]") +{ + // 4x4 image = 1 BC7 block = 16 bytes. Claiming 32 bytes mismatches. + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 4, 4, 1, 0, 1, 0); + const uint64_t levelOffset = buf.size() + 24; + appendLE<uint64_t>(buf, levelOffset); + appendLE<uint64_t>(buf, /*byteLength*/ 32); + appendLE<uint64_t>(buf, 32); + buf.resize(buf.size() + 32, 0); + rive::Ktx2DecodeResult out; + REQUIRE_FALSE(rive::DecodeKtx2(buf.data(), buf.size(), out)); +} + +TEST_CASE("ktx2 happy path: single 4x4 BC7 mip 0", "[ktx2-decoder]") +{ + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 4, 4, 1, 0, 1, 0); + const uint64_t levelOffset = buf.size() + 24; + appendLE<uint64_t>(buf, levelOffset); + appendLE<uint64_t>(buf, /*byteLength*/ 16); + appendLE<uint64_t>(buf, /*uncompressedByteLength*/ 16); + // 16 bytes of synthetic block payload — parser doesn't validate the + // BC7 bitstream, just copies the bytes through. + const uint8_t expected[16] = { + 0xDE, + 0xAD, + 0xBE, + 0xEF, + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + 0x06, + 0x07, + 0x08, + 0xCA, + 0xFE, + 0xBA, + 0xBE, + }; + buf.insert(buf.end(), expected, expected + 16); + + rive::Ktx2DecodeResult out; + REQUIRE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + REQUIRE(out.format == rive::GPUTextureFormat::bc7); + REQUIRE(out.pixelWidth == 4); + REQUIRE(out.pixelHeight == 4); + REQUIRE(out.levelCount == 1); + REQUIRE(out.blocks.size() == 16); + REQUIRE(std::memcmp(out.blocks.data(), expected, 16) == 0); +} + +TEST_CASE("ktx2 happy path: 8x8 with two mip levels concatenated", + "[ktx2-decoder]") +{ + // Mip 0 = 8x8 = 4 blocks (64 bytes). Mip 1 = 4x4 = 1 block (16 bytes). + // Level index lists level 0 first; on disk levels should sit smallest- + // first but the parser only reads each level by its own offset, so + // ordering within the buffer doesn't matter here. + auto buf = buildSkeletonKtx2(VK_FORMAT_BC7_SRGB_BLOCK, 8, 8, 2, 0, 1, 0); + + const uint64_t headerEnd = buf.size(); + const uint64_t levelIndexBytes = 24 * 2; + const uint64_t mip0Offset = headerEnd + levelIndexBytes; + const uint64_t mip0Bytes = 64; + const uint64_t mip1Offset = mip0Offset + mip0Bytes; + const uint64_t mip1Bytes = 16; + + // Level index entry 0 (mip 0, 8x8). + appendLE<uint64_t>(buf, mip0Offset); + appendLE<uint64_t>(buf, mip0Bytes); + appendLE<uint64_t>(buf, mip0Bytes); + // Level index entry 1 (mip 1, 4x4). + appendLE<uint64_t>(buf, mip1Offset); + appendLE<uint64_t>(buf, mip1Bytes); + appendLE<uint64_t>(buf, mip1Bytes); + + // Block payloads. Distinct fill bytes so the test can verify ordering. + buf.resize(buf.size() + mip0Bytes, 0xAA); + buf.resize(buf.size() + mip1Bytes, 0xBB); + + rive::Ktx2DecodeResult out; + REQUIRE(rive::DecodeKtx2(buf.data(), buf.size(), out)); + REQUIRE(out.pixelWidth == 8); + REQUIRE(out.pixelHeight == 8); + REQUIRE(out.levelCount == 2); + REQUIRE(out.blocks.size() == mip0Bytes + mip1Bytes); + // Output buffer is concatenated level 0 (largest) first, then level 1. + REQUIRE(out.blocks[0] == 0xAA); + REQUIRE(out.blocks[mip0Bytes - 1] == 0xAA); + REQUIRE(out.blocks[mip0Bytes] == 0xBB); + REQUIRE(out.blocks[mip0Bytes + mip1Bytes - 1] == 0xBB); +}
diff --git a/tests/unit_tests/runtime/texture_archive_test.cpp b/tests/unit_tests/runtime/texture_archive_test.cpp deleted file mode 100644 index 6e9667c..0000000 --- a/tests/unit_tests/runtime/texture_archive_test.cpp +++ /dev/null
@@ -1,495 +0,0 @@ -#include <catch.hpp> -#include "rive/texture_archive.hpp" - -#include <cstring> -#include <filesystem> -#include <fstream> -#include <vector> - -using namespace rive; - -// --------------------------------------------------------------------------- -// Helper: build a valid RTEX byte stream in memory. -// -// File layout (matches packages/runtime/src/texture_archive.cpp): -// [4] magic 'RTEX' -// [2] version (u16) -// [2] textureCount (u16) -// per texture: -// [2]x4 width, height, paddedWidth, paddedHeight (u16) -// [1]x4 blockSizeX, blockSizeY, bytesPerBlock, numMips (u8) -// [1] format (u8 GPUTextureFormat) -// per mip (numMips entries): -// [4] blocksX, blocksY, bytesTotal (i32 each) -// [blob] raw mip data, size == sum(bytesTotal) over all mips -// --------------------------------------------------------------------------- - -namespace -{ - -struct MipDesc -{ - int32_t blocksX; - int32_t blocksY; - int32_t bytesTotal; -}; - -struct TexDesc -{ - uint16_t width = 4, height = 4, paddedWidth = 4, paddedHeight = 4; - uint8_t blockSizeX = 4, blockSizeY = 4, bytesPerBlock = 16, numMips = 1; - GPUTextureFormat format = GPUTextureFormat::bc7; - std::vector<MipDesc> mips; -}; - -template <typename T> static void append(std::vector<uint8_t>& buf, T val) -{ - const uint8_t* p = reinterpret_cast<const uint8_t*>(&val); - buf.insert(buf.end(), p, p + sizeof(T)); -} - -static std::vector<uint8_t> buildArchive(uint16_t version, - const std::vector<TexDesc>& textures, - const std::vector<uint8_t>& dataBlob) -{ - std::vector<uint8_t> buf; - buf.insert(buf.end(), {'R', 'T', 'E', 'X'}); - append(buf, version); - append(buf, static_cast<uint16_t>(textures.size())); - - for (const auto& t : textures) - { - append(buf, t.width); - append(buf, t.height); - append(buf, t.paddedWidth); - append(buf, t.paddedHeight); - append(buf, t.blockSizeX); - append(buf, t.blockSizeY); - append(buf, t.bytesPerBlock); - append(buf, t.numMips); - append(buf, static_cast<uint8_t>(t.format)); - for (const auto& m : t.mips) - { - append(buf, m.blocksX); - append(buf, m.blocksY); - append(buf, m.bytesTotal); - } - } - - buf.insert(buf.end(), dataBlob.begin(), dataBlob.end()); - return buf; -} - -// Build a minimal valid single-texture archive with one 4x4 BC7 mip. -static std::vector<uint8_t> makeSimpleArchive() -{ - std::vector<uint8_t> blob(16, 0xAB); - - TexDesc tex; - tex.mips = {{1, 1, 16}}; - - return buildArchive(1, {tex}, blob); -} - -static std::string writeTempArchive(const std::vector<uint8_t>& bytes) -{ - static int counter = 0; - std::string path = (std::filesystem::temp_directory_path() / - ("rive_ta_test_" + std::to_string(counter++) + ".rtex")) - .string(); - std::ofstream out(path, std::ios::binary); - out.write(reinterpret_cast<const char*>(bytes.data()), - static_cast<std::streamsize>(bytes.size())); - out.close(); - return path; -} - -} // namespace - -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- - -TEST_CASE("TextureDirectory import: valid single BC7 texture", - "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - REQUIRE(dir.dir.size() == 1); - const TextureData& tex = dir.dir[0]; - CHECK(tex.width == 4); - CHECK(tex.height == 4); - CHECK(tex.paddedWidth == 4); - CHECK(tex.paddedHeight == 4); - CHECK(tex.blockSizeX == 4); - CHECK(tex.blockSizeY == 4); - CHECK(tex.bytesPerBlock == 16); - CHECK(tex.numMips == 1); - CHECK(tex.format == GPUTextureFormat::bc7); - CHECK(tex.totalBytes == 16); - - REQUIRE(tex.mipLevels.size() == 1); - CHECK(tex.mipLevels[0].blocksX == 1); - CHECK(tex.mipLevels[0].blocksY == 1); - CHECK(tex.mipLevels[0].bytesTotal == 16); -} - -TEST_CASE("TextureDirectory import: mip blocks pointer into dataBlob", - "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - const TextureMipLevel& mip = dir.dir[0].mipLevels[0]; - REQUIRE(mip.blocks != nullptr); - const uint8_t* blobBegin = dir.dataBlob.data(); - const uint8_t* blobEnd = blobBegin + dir.dataBlob.size(); - CHECK(mip.blocks >= blobBegin); - CHECK(mip.blocks + mip.bytesTotal <= blobEnd); - CHECK(mip.blocks[0] == 0xAB); -} - -TEST_CASE("TextureDirectory import: zero textures", "[texture_archive]") -{ - auto bytes = buildArchive(1, {}, {}); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - CHECK(dir.dir.empty()); - CHECK(dir.dataBlob.empty()); -} - -TEST_CASE("TextureDirectory import: multiple textures", "[texture_archive]") -{ - // tex0 + tex1 each contribute 16 bytes of contiguous mip data. - std::vector<uint8_t> blob(32); - std::fill(blob.begin(), blob.begin() + 16, 0x11); - std::fill(blob.begin() + 16, blob.end(), 0x22); - - TexDesc tex0, tex1; - tex0.mips = {{1, 1, 16}}; - tex1.mips = {{1, 1, 16}}; - - auto bytes = buildArchive(1, {tex0, tex1}, blob); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - REQUIRE(dir.dir.size() == 2); - CHECK(dir.dir[0].mipLevels[0].blocks[0] == 0x11); - CHECK(dir.dir[1].mipLevels[0].blocks[0] == 0x22); -} - -TEST_CASE("TextureDirectory import: multiple mip levels", "[texture_archive]") -{ - // Mip 0: 2x2 blocks = 64 bytes. Mip 1: 1x1 block = 16 bytes. - std::vector<uint8_t> blob(80); - std::fill(blob.begin(), blob.begin() + 64, 0xAA); - std::fill(blob.begin() + 64, blob.end(), 0xBB); - - TexDesc tex; - tex.width = 8; - tex.height = 8; - tex.paddedWidth = 8; - tex.paddedHeight = 8; - tex.numMips = 2; - tex.mips = {{2, 2, 64}, {1, 1, 16}}; - - auto bytes = buildArchive(1, {tex}, blob); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - REQUIRE(dir.dir[0].mipLevels.size() == 2); - CHECK(dir.dir[0].mipLevels[0].bytesTotal == 64); - CHECK(dir.dir[0].mipLevels[0].blocks[0] == 0xAA); - CHECK(dir.dir[0].mipLevels[1].bytesTotal == 16); - CHECK(dir.dir[0].mipLevels[1].blocks[0] == 0xBB); -} - -TEST_CASE("TextureDirectory import: clears previous state on re-import", - "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - REQUIRE(dir.dir.size() == 1); - - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - CHECK(dir.dir.size() == 1); -} - -TEST_CASE("TextureDirectory import: bad magic", "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - bytes[0] = 'X'; - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); -} - -TEST_CASE("TextureDirectory import: empty span", "[texture_archive]") -{ - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(nullptr, 0))); -} - -TEST_CASE("TextureDirectory import: too small for header", "[texture_archive]") -{ - std::vector<uint8_t> bytes = {'R', 'T', 'E', 'X'}; // header needs 8 bytes - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); -} - -TEST_CASE("TextureDirectory import: unsupported version", "[texture_archive]") -{ - auto bytes = buildArchive(99, {}, {}); // bogus version - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); -} - -TEST_CASE("TextureDirectory import: truncated descriptor", "[texture_archive]") -{ - // Claim 1 texture but provide no descriptor bytes. - std::vector<uint8_t> buf; - buf.insert(buf.end(), {'R', 'T', 'E', 'X'}); - append(buf, uint16_t(1)); - append(buf, uint16_t(1)); - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(buf.data(), buf.size()))); -} - -TEST_CASE("TextureDirectory import: truncated mip table", "[texture_archive]") -{ - // Descriptor present but mip entries truncated. - std::vector<uint8_t> buf; - buf.insert(buf.end(), {'R', 'T', 'E', 'X'}); - append(buf, uint16_t(1)); - append(buf, uint16_t(1)); - append(buf, uint16_t(4)); // width - append(buf, uint16_t(4)); // height - append(buf, uint16_t(4)); // paddedWidth - append(buf, uint16_t(4)); // paddedHeight - append(buf, uint8_t(4)); // blockSizeX - append(buf, uint8_t(4)); // blockSizeY - append(buf, uint8_t(16)); // bytesPerBlock - append(buf, uint8_t(1)); // numMips = 1 - append(buf, uint8_t(static_cast<uint8_t>(GPUTextureFormat::bc7))); - // No mip entry follows. - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(buf.data(), buf.size()))); -} - -TEST_CASE("TextureDirectory import: blob size mismatch", "[texture_archive]") -{ - // Mip table claims 16 bytes but blob has only 8. - std::vector<uint8_t> blob(8, 0); - TexDesc tex; - tex.mips = {{1, 1, 16}}; - - auto bytes = buildArchive(1, {tex}, blob); - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); -} - -TEST_CASE("TextureDirectory import: blob too large", "[texture_archive]") -{ - // Mip table claims 16 bytes but blob has 32 — strict size check rejects. - std::vector<uint8_t> blob(32, 0); - TexDesc tex; - tex.mips = {{1, 1, 16}}; - - auto bytes = buildArchive(1, {tex}, blob); - TextureDirectory dir; - CHECK_FALSE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); -} - -TEST_CASE("TextureDirectory import: ASTC format preserved", "[texture_archive]") -{ - std::vector<uint8_t> blob(16, 0xCC); - - TexDesc tex; - tex.format = GPUTextureFormat::astc; - tex.blockSizeX = 6; - tex.blockSizeY = 6; - tex.bytesPerBlock = 16; // ASTC always 16 bytes per block - tex.mips = {{1, 1, 16}}; - - auto bytes = buildArchive(1, {tex}, blob); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - CHECK(dir.dir[0].format == GPUTextureFormat::astc); - CHECK(dir.dir[0].blockSizeX == 6); - CHECK(dir.dir[0].blockSizeY == 6); - CHECK(dir.dir[0].bytesPerBlock == 16); -} - -TEST_CASE("TextureDirectory import: ETC2 format preserved", "[texture_archive]") -{ - std::vector<uint8_t> blob(8, 0xDD); - - TexDesc tex; - tex.format = GPUTextureFormat::etc2; - tex.blockSizeX = 4; - tex.blockSizeY = 4; - tex.bytesPerBlock = 8; // ETC2 RGB8: 8 bytes per block - tex.mips = {{1, 1, 8}}; - - auto bytes = buildArchive(1, {tex}, blob); - TextureDirectory dir; - REQUIRE(dir.import(Span<const uint8_t>(bytes.data(), bytes.size()))); - - CHECK(dir.dir[0].format == GPUTextureFormat::etc2); - CHECK(dir.dir[0].bytesPerBlock == 8); -} - -TEST_CASE("TextureDirectory addTexture: packs mip data into dataBlob", - "[texture_archive]") -{ - std::vector<uint8_t> pixelData(16, 0xAB); - - TextureData td; - td.width = td.height = td.paddedWidth = td.paddedHeight = 4; - td.blockSizeX = td.blockSizeY = 4; - td.bytesPerBlock = 16; - td.numMips = 1; - td.format = GPUTextureFormat::bc7; - td.totalBytes = 16; - - TextureMipLevel mip; - mip.blocksX = mip.blocksY = 1; - mip.bytesTotal = 16; - mip.blocks = pixelData.data(); - td.mipLevels.push_back(mip); - - TextureDirectory archive; - archive.addTexture(td); - - REQUIRE(archive.dataBlob.size() == 16); - CHECK(archive.dataBlob[0] == 0xAB); - - REQUIRE(archive.dir.size() == 1); - - const uint8_t* blobBegin = archive.dataBlob.data(); - const uint8_t* blobEnd = blobBegin + archive.dataBlob.size(); - const TextureMipLevel& stored = archive.dir[0].mipLevels[0]; - CHECK(stored.blocks >= blobBegin); - CHECK(stored.blocks + stored.bytesTotal <= blobEnd); - CHECK(stored.blocks[0] == 0xAB); -} - -TEST_CASE("TextureDirectory addTexture: two textures share contiguous dataBlob", - "[texture_archive]") -{ - auto makeTd = [](uint8_t fill, GPUTextureFormat fmt) { - std::vector<uint8_t> pixels(16, fill); - TextureData td; - td.width = td.height = td.paddedWidth = td.paddedHeight = 4; - td.blockSizeX = td.blockSizeY = 4; - td.bytesPerBlock = 16; - td.numMips = 1; - td.format = fmt; - td.totalBytes = 16; - TextureMipLevel mip; - mip.blocksX = mip.blocksY = 1; - mip.bytesTotal = 16; - mip.blocks = pixels.data(); - td.mipLevels.push_back(mip); - return std::make_pair(td, pixels); - }; - - auto [td0, px0] = makeTd(0x11, GPUTextureFormat::bc7); - td0.mipLevels[0].blocks = px0.data(); - auto [td1, px1] = makeTd(0x22, GPUTextureFormat::astc); - td1.mipLevels[0].blocks = px1.data(); - - TextureDirectory archive; - archive.addTexture(td0); - archive.addTexture(td1); - - REQUIRE(archive.dataBlob.size() == 32); - REQUIRE(archive.dir.size() == 2); - - CHECK(archive.dir[0].mipLevels[0].blocks[0] == 0x11); - CHECK(archive.dir[1].mipLevels[0].blocks[0] == 0x22); - CHECK(archive.dir[1].mipLevels[0].blocks == - archive.dir[0].mipLevels[0].blocks + 16); -} - -TEST_CASE("TextureDirectory exportArchive: round-trip preserves data", - "[texture_archive]") -{ - std::vector<uint8_t> pixelData(16, 0x5A); - - TextureData td; - td.width = td.height = td.paddedWidth = td.paddedHeight = 4; - td.blockSizeX = td.blockSizeY = 4; - td.bytesPerBlock = 16; - td.numMips = 1; - td.format = GPUTextureFormat::bc7; - td.totalBytes = 16; - - TextureMipLevel mip; - mip.blocksX = mip.blocksY = 1; - mip.bytesTotal = 16; - mip.blocks = pixelData.data(); - td.mipLevels.push_back(mip); - - TextureDirectory writer; - writer.addTexture(td); - - auto path = - (std::filesystem::temp_directory_path() / "rive_ta_roundtrip.rtex") - .string(); - REQUIRE(writer.exportArchive(path)); - - TextureDirectory reader; - REQUIRE(reader.import(path)); - REQUIRE(reader.dir.size() == 1); - CHECK(reader.dir[0].format == GPUTextureFormat::bc7); - CHECK(reader.dir[0].width == 4); - CHECK(reader.dir[0].mipLevels[0].bytesTotal == 16); - CHECK(reader.dir[0].mipLevels[0].blocks[0] == 0x5A); - - std::remove(path.c_str()); -} - -TEST_CASE("TextureDirectory import (file): valid archive", "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - auto path = writeTempArchive(bytes); - TextureDirectory dir; - REQUIRE(dir.import(path)); - REQUIRE(dir.dir.size() == 1); - CHECK(dir.dir[0].width == 4); - CHECK(dir.dir[0].mipLevels[0].blocks[0] == 0xAB); - std::remove(path.c_str()); -} - -TEST_CASE("TextureDirectory import (file): file not found", "[texture_archive]") -{ - TextureDirectory dir; - CHECK_FALSE(dir.import((std::filesystem::temp_directory_path() / - "rive_does_not_exist_xyz.rtex") - .string())); -} - -TEST_CASE("TextureDirectory import (file): bad magic", "[texture_archive]") -{ - auto bytes = makeSimpleArchive(); - bytes[0] = 'X'; - auto path = writeTempArchive(bytes); - TextureDirectory dir; - CHECK_FALSE(dir.import(path)); - std::remove(path.c_str()); -} - -TEST_CASE("TextureDirectory import (file): too small for header", - "[texture_archive]") -{ - std::vector<uint8_t> bytes = {'R', 'T', 'E', 'X'}; - auto path = writeTempArchive(bytes); - TextureDirectory dir; - CHECK_FALSE(dir.import(path)); - std::remove(path.c_str()); -}