18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 23:17:56 +01:00

Textures: read KTX2 files (BC1-BC7, RGBA8, zstd) in both renderers

The game now reads .ktx2 texture files, for the OpenGL 4.6 and the Vulkan
renderer alike (texture_source::load_KTX2(), parser in model/ktx2.*):

- formats: BC1 (RGB and RGBA), BC2, BC3, BC4, BC5 (unsigned and signed),
  BC6H (unsigned and signed float), BC7, and plain R8G8B8A8 / B8G8R8A8;
- the levels stored as they are or packed with zstd (the bundled zstd);
  with gfx.textures.streaming the worker threads read and unpack them;
- the KTXorientation key is honoured: "rd" files are flipped to the bottom
  row first, BC1-BC5 block by block, plain texels row by row. BC6H and BC7
  can't be flipped without decoding: an "rd" file of these is loaded as
  stored, with a warning in the log, as the BC7 dds files are. A file
  without the key is taken the way the dds files are (ddsupperorigin);
- srgb or linear colour is chosen by the material, as for the dds files;
- the alpha of BC7 is checked on a small level, as for the dds files.

Not supported, refused with the reason in the log: Basis Universal
(ETC1S / UASTC, BasisLZ), zlib supercompression, arrays, cube maps and
3d images.

BC1 without alpha, BC4, BC5 and BC6H are new formats for the renderers:
opengl_texture::mapping and the Vulkan texture_format_of() map them (no
srgb variants for BC4/BC5/BC6H; their alpha reads 1).

.ktx2 is looked for right after .dds (textures, materials, the editor's
texture browsers). Existing data holds no .ktx2 files, so nothing changes
for existing sceneries and vehicles, and no asset change in the SVN is
needed.

Unit tests: tests/unit/test_ktx2.cpp (header, levels, zstd, orientation,
refused files, flipping of BC1-BC5 and plain texels).
This commit is contained in:
2026-11-30 15:08:45 +01:00
parent 6a716b6720
commit 7d3ccd6dc4
11 changed files with 1351 additions and 11 deletions
+248 -5
View File
@@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/Logs.h"
#include "utilities/utilities.h"
#include "scene/sn_utils.h"
#include "model/ktx2.h"
#include "rendering/flip-s3tc.h"
#include "rendering/common/texturealpha.h"
#include "stb/stb_image.h"
@@ -30,6 +31,8 @@ http://mozilla.org/MPL/2.0/.
#include "winheaders.h"
#include <bit>
#include <format>
#include <span>
#include <utility>
#define EU07_DEFERRED_TEXTURE_UPLOAD
@@ -51,6 +54,10 @@ struct texture_request {
int height { 0 };
int mapcount { 0 };
int blocksize { 0 };
// of a ktx2 file: its image, of which the worker reads mapcount levels from firstlevel on (and unpacks them), flipped if flip
// is set; width and height are those of the first level read
std::optional<ktx2::Description> ktx2image;
std::size_t firstlevel { 0 };
// handed to the workers (texture_source::prefetch()), and when: the main thread only
bool submitted { false };
std::chrono::steady_clock::time_point submittime;
@@ -61,11 +68,74 @@ struct texture_request {
// every texel passes the alpha test of the shadow maps: checked by the worker threads, not by a thread waiting for the data
std::optional<bool> alphakept;
bool failed { false };
std::string error; // why the data couldn't be read, when the reader knows
bool done { false }; // guarded by the mutex of the loader
};
namespace {
// what the texture takes of a format of the ktx2 files: the format of its data, and the components it has
struct ktx2_layout {
GLint format;
GLint components;
};
ktx2_layout ktx2_layout_of( ktx2::Format const Format ) {
using enum ktx2::Format;
switch( Format ) {
case bc1Rgb: { return { GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB }; }
// the 1 bit alpha is cut out by the alpha test, the texture isn't a translucent one: as with the dxt1 dds files
case bc1Rgba: { return { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGB }; }
case bc2: { return { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA }; }
case bc3: { return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA }; }
case bc4: { return { GL_COMPRESSED_RED_RGTC1, GL_RED }; }
case bc4Signed: { return { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED }; }
case bc5: { return { GL_COMPRESSED_RG_RGTC2, GL_RG }; }
case bc5Signed: { return { GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG }; }
case bc6h: { return { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RGB }; }
case bc6hSigned: { return { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB }; }
// whether the texels use the alpha is checked on the data (bc7_components())
case bc7: { return { GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA }; }
case bgra8: { return { GL_BGRA, GL_RGBA }; }
default: { return { GL_RGBA, GL_RGBA }; }
} }
// the alpha test of the shadow maps checked on the data of a ktx2 file. the formats without alpha are known to pass it by their
// format alone
std::optional<bool> ktx2_alpha_kept( ktx2::Format const Format, std::span<std::uint8_t const> const Data ) {
using enum ktx2::Format;
switch( Format ) {
case bc1Rgba: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc1, Data ); }
case bc2: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc2, Data ); }
case bc3: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc3, Data ); }
case bc7: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::bc7, Data ); }
case rgba8:
case bgra8: { return gfx::texels_pass_alpha_test( gfx::alpha_layout::rgba8, Data ); }
default: { return std::nullopt; }
} }
// reads the levels of a ktx2 file a request asks for, unpacks and flips them. Check: the alpha of the texels checked too
void read_ktx2( texture_request &Request, bool const Check ) {
auto const &image { *Request.ktx2image };
Request.data.clear();
std::ifstream file( Request.file, std::ios::binary );
if( false == file.is_open() ) {
Request.failed = true;
return;
}
if( false == ktx2::ReadLevels( file, image, Request.firstlevel, static_cast<std::size_t>( Request.mapcount ), Request.data, Request.error ) ) {
Request.data = std::vector<unsigned char>();
Request.failed = true;
return;
}
if( Request.flip ) {
ktx2::FlipLevels( image.format, Request.data, static_cast<std::uint32_t>( Request.width ), static_cast<std::uint32_t>( Request.height ), static_cast<std::size_t>( Request.mapcount ) );
}
Request.alphakept.reset();
if( Check ) {
Request.alphakept = ktx2_alpha_kept( image.format, Request.data );
} }
// the alpha test of the shadow maps checked on the data of a dds file, block by block of its format
std::optional<bool> dds_alpha_kept( texture_request const &Request ) {
switch( Request.fourcc ) {
@@ -163,6 +233,10 @@ private:
// same as the reading part of texture_source::load_DDS(). Check: the alpha of the texels checked too (on a worker thread)
static void read( texture_request &Request, bool const Check ) {
if( Request.ktx2image.has_value() ) {
read_ktx2( Request, Check );
return;
}
std::ifstream file( Request.file, std::ios::binary );
if( false == file.is_open() ) {
Request.failed = true;
@@ -316,6 +390,46 @@ GLint bc7_components( std::istream &File, std::streamoff const Start, std::size_
}
return GL_RGB; }
// the components of BC7 data held in memory (a level of a ktx2 file), checked as bc7_components() checks a dds file
GLint bc7_components( std::span<std::uint8_t const> const Data ) {
for( std::size_t block = 0; block + 16 <= Data.size(); block += 16 ) {
if( bc7_block_has_alpha( &Data[ block ] ) ) {
return GL_RGBA;
}
}
return GL_RGB; }
// the components of a bc7 ktx2 image: a level of up to 256x256 texels (or the smallest one) checked for translucent texels, as for
// the dds files. the level is read from the file whether the data is streamed or not, so the result doesn't depend on it
GLint ktx2_bc7_components( std::istream &File, ktx2::Description const &Image, std::size_t Level ) {
while( ( Level + 1 < Image.levels.size() )
&& ( std::max( ktx2::LevelExtent( Image.width, Level ), ktx2::LevelExtent( Image.height, Level ) ) > 256 ) ) {
++Level;
}
std::vector<std::uint8_t> probe;
std::string error;
if( false == ktx2::ReadLevels( File, Image, Level, 1, probe, error ) ) {
// a broken file, erring on the side of translucency like DXT5 does
return GL_RGBA;
}
return bc7_components( probe ); }
// the first level of a ktx2 image within maxtexturesize, or the count of the levels when none is
std::size_t ktx2_first_level( ktx2::Description const &Image ) {
auto const limit { static_cast<std::uint32_t>( std::max( Global.CurrentMaxTextureSize, 1 ) ) };
std::size_t level { 0 };
while( ( level < Image.levels.size() )
&& ( std::max( ktx2::LevelExtent( Image.width, level ), ktx2::LevelExtent( Image.height, level ) ) > limit ) ) {
++level;
}
return level; }
// the formats of the bptc extension, BC6H and BC7
bool is_bptc( GLint const Format ) {
return ( Format == GL_COMPRESSED_RGBA_BPTC_UNORM )
|| ( Format == GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT )
|| ( Format == GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT ); }
// BC7 is core since GL 4.2, older contexts need the extension. requires current gl context
bool bptc_supported() {
static bool const supported = []() {
@@ -346,6 +460,7 @@ GLint readback_format( GLint const Internalformat ) {
switch( Internalformat ) {
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: { return GL_COMPRESSED_RGBA8_ETC2_EAC; }
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; }
case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; }
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; }
case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; }
case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: { return GL_COMPRESSED_RGBA_BPTC_UNORM; }
@@ -371,6 +486,15 @@ std::unordered_map<GLint, int> texture_source::precompressed_formats =
{ GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 16 },
{ GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, 16 },
{ GL_COMPRESSED_RGBA_BPTC_UNORM, 16 },
// of the ktx2 files only
{ GL_COMPRESSED_RGB_S3TC_DXT1_EXT, 8 },
{ GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, 8 },
{ GL_COMPRESSED_RED_RGTC1, 8 },
{ GL_COMPRESSED_SIGNED_RED_RGTC1, 8 },
{ GL_COMPRESSED_RG_RGTC2, 16 },
{ GL_COMPRESSED_SIGNED_RG_RGTC2, 16 },
{ GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, 16 },
{ GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, 16 },
};
std::unordered_map<GLint, GLint> opengl_texture::drivercompressed_formats =
@@ -416,7 +540,50 @@ std::unordered_map<GLint, std::unordered_map<GLint, GLint>> opengl_texture::mapp
{ GL_RGB, GL_COMPRESSED_RGBA_BPTC_UNORM },
{ GL_RG, GL_COMPRESSED_RGBA_BPTC_UNORM },
{ GL_RED, GL_COMPRESSED_RGBA_BPTC_UNORM } } },
{ GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 },
// of the ktx2 files only. bc4, bc5 and bc6h have no srgb variants: their values are taken as they are, whatever the material wants
{ GL_COMPRESSED_RGB_S3TC_DXT1_EXT, { { GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT },
{ GL_SRGB, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT },
{ GL_RGBA, GL_COMPRESSED_RGB_S3TC_DXT1_EXT },
{ GL_RGB, GL_COMPRESSED_RGB_S3TC_DXT1_EXT },
{ GL_RG, GL_COMPRESSED_RGB_S3TC_DXT1_EXT },
{ GL_RED, GL_COMPRESSED_RGB_S3TC_DXT1_EXT } } },
{ GL_COMPRESSED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_RED_RGTC1 },
{ GL_SRGB, GL_COMPRESSED_RED_RGTC1 },
{ GL_RGBA, GL_COMPRESSED_RED_RGTC1 },
{ GL_RGB, GL_COMPRESSED_RED_RGTC1 },
{ GL_RG, GL_COMPRESSED_RED_RGTC1 },
{ GL_RED, GL_COMPRESSED_RED_RGTC1 } } },
{ GL_COMPRESSED_SIGNED_RED_RGTC1, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RED_RGTC1 },
{ GL_SRGB, GL_COMPRESSED_SIGNED_RED_RGTC1 },
{ GL_RGBA, GL_COMPRESSED_SIGNED_RED_RGTC1 },
{ GL_RGB, GL_COMPRESSED_SIGNED_RED_RGTC1 },
{ GL_RG, GL_COMPRESSED_SIGNED_RED_RGTC1 },
{ GL_RED, GL_COMPRESSED_SIGNED_RED_RGTC1 } } },
{ GL_COMPRESSED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_RG_RGTC2 },
{ GL_SRGB, GL_COMPRESSED_RG_RGTC2 },
{ GL_RGBA, GL_COMPRESSED_RG_RGTC2 },
{ GL_RGB, GL_COMPRESSED_RG_RGTC2 },
{ GL_RG, GL_COMPRESSED_RG_RGTC2 },
{ GL_RED, GL_COMPRESSED_RG_RGTC2 } } },
{ GL_COMPRESSED_SIGNED_RG_RGTC2, { { GL_SRGB_ALPHA, GL_COMPRESSED_SIGNED_RG_RGTC2 },
{ GL_SRGB, GL_COMPRESSED_SIGNED_RG_RGTC2 },
{ GL_RGBA, GL_COMPRESSED_SIGNED_RG_RGTC2 },
{ GL_RGB, GL_COMPRESSED_SIGNED_RG_RGTC2 },
{ GL_RG, GL_COMPRESSED_SIGNED_RG_RGTC2 },
{ GL_RED, GL_COMPRESSED_SIGNED_RG_RGTC2 } } },
{ GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT },
{ GL_SRGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT },
{ GL_RGBA, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT },
{ GL_RGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT },
{ GL_RG, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT },
{ GL_RED, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT } } },
{ GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, { { GL_SRGB_ALPHA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT },
{ GL_SRGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT },
{ GL_RGBA, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT },
{ GL_RGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT },
{ GL_RG, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT },
{ GL_RED, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT } } },
{ GL_RGBA, { { GL_SRGB_ALPHA, GL_SRGB8_ALPHA8 },
{ GL_SRGB, GL_SRGB8 },
{ GL_RGBA, GL_RGBA8 },
{ GL_RGB, GL_RGB8 },
@@ -483,6 +650,7 @@ texture_source::load() {
else if( type == ".tga" ) { load_TGA(); }
else if( type == ".png" ) { load_STBI(); }
else if( type == ".ktx" ) { load_KTX(); }
else if( type == ".ktx2" ) { load_KTX2(); }
else if( type == ".bmp" ) { load_STBI(); }
else if( type == ".jpg" ) { load_STBI(); }
else if( type == ".tex" ) { load_TEX(); }
@@ -1080,6 +1248,78 @@ texture_source::load_KTX() {
data_state = resource_state::good;
}
// a khronos texture 2.0 file: the levels within maxtexturesize, unpacked (zstd) and with the bottom row first. the material
// decides between srgb and linear colour, as it does for the dds files
void
texture_source::load_KTX2() {
auto const path { FileOnDisk( name + type ) };
std::ifstream file( path, std::ios::binary );
std::string error;
auto image { ktx2::Parse( file, error ) };
if( false == image.has_value() ) {
ErrorLog( std::format( "Bad texture: \"{}{}\" can't be read: {}", name, type, error ), logtype::texture );
data_state = resource_state::failed;
return;
}
auto const first { ktx2_first_level( *image ) };
if( first == image->levels.size() ) {
WriteLog( std::format( "Texture \"{}\" has no mipmaps which can fit currently set texture pixelcount limits.", name ) );
data_state = resource_state::failed;
return;
}
if( first > 0 ) {
WriteLog( std::format( "Texture pixelcount exceeds specified limits, skipping {} mipmap level(s) of \"{}\"", first, name ), logtype::texture );
}
auto const layout { ktx2_layout_of( image->format ) };
data_format = layout.format;
data_width = ktx2::LevelExtent( image->width, first );
data_height = ktx2::LevelExtent( image->height, first );
// of plain texels only the largest level is taken, the gpu makes the rest as it does for the other image files
auto const count { ktx2::IsCompressed( image->format ) ? image->levels.size() - first : std::size_t { 1 } };
data_mapcount = static_cast<unsigned int>( count );
data_components = (
image->format == ktx2::Format::bc7 ?
ktx2_bc7_components( file, *image, first ) :
layout.components );
// the data is kept with the bottom row first. the file states where its first row is, and one which doesn't is taken the way
// the dds files are (ddsupperorigin)
auto const topfirst { ( image->origin == ktx2::Origin::top ) || ( ( image->origin == ktx2::Origin::unstated ) && Global.dds_upper_origin ) };
auto const flip { topfirst && ktx2::CanFlip( image->format ) };
if( topfirst && ( false == flip ) ) {
WriteLog( std::format( "Warning: BC6H/BC7 texture \"{}\" has its first row at the top and can't be flipped, it's loaded as stored", name ), logtype::texture );
}
if( true == Global.gfx_texture_streaming ) {
// the levels are read and unpacked by a worker thread, everything else about the texture is known already
request = std::make_shared<texture_request>();
request->file = path;
request->flip = flip;
request->width = static_cast<int>( data_width );
request->height = static_cast<int>( data_height );
request->mapcount = static_cast<int>( count );
request->firstlevel = first;
request->ktx2image = std::move( image );
data_state = resource_state::loading;
return;
}
data.clear();
if( false == ktx2::ReadLevels( file, *image, first, count, data, error ) ) {
data = std::vector<unsigned char>();
ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, error ), logtype::texture );
data_state = resource_state::failed;
return;
}
if( flip ) {
ktx2::FlipLevels( image->format, data, data_width, data_height, count );
}
data_state = resource_state::good;
}
void
texture_source::load_TEX() {
@@ -1322,9 +1562,9 @@ opengl_texture::create( bool const Static ) {
return false;
}
if( ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM )
if( is_bptc( data_format )
&& ( false == bptc_supported() ) ) {
ErrorLog( "Bad texture: \"" + name + "\" uses BC7 compression, which the graphics driver doesn't support", logtype::texture );
ErrorLog( std::format( "Bad texture: \"{}\" uses {} compression, which the graphics driver doesn't support", name, ( data_format == GL_COMPRESSED_RGBA_BPTC_UNORM ? "BC7" : "BC6H" ) ), logtype::texture );
data = std::vector<unsigned char>();
data_state = resource_state::failed;
// NOTE: temporary workaround for texture assignment errors, same as in load()
@@ -1476,6 +1716,9 @@ texture_source::complete_data() {
if( true == completed->failed ) {
data_state = resource_state::failed;
if( false == completed->error.empty() ) {
ErrorLog( std::format( "Bad texture: \"{}{}\": {}", name, type, completed->error ), logtype::texture );
}
ErrorLog( "Bad texture: failed to load texture \"" + name + "\"" );
// NOTE: temporary workaround for texture assignment errors, same as in load()
on_failed();
@@ -1517,7 +1760,7 @@ bool
texture_source::streamed() const {
return ( ( true == Global.gfx_texture_streaming )
&& ( type == ".dds" )
&& ( ( type == ".dds" ) || ( type == ".ktx2" ) )
&& ( false == is_rendertarget ) );
}
@@ -2184,7 +2427,7 @@ texture_bank::find_on_disk( std::string const &Texturename ) {
// if the first attempt fails, try entire extension list
// NOTE: slightly wasteful as it means preferred extension is tested twice, but, eh
return FileExists(filenames, {".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"});
return FileExists(filenames, {".dds", ".ktx2", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex"});
}
//---------------------------------------------------------------------------