From 03391c66cb79448c3db364628a7f8f350236d273 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 21:42:39 +0200 Subject: [PATCH] Texture replacement: Support palette-indexed replacement images - Fixes #15145 A replacement listed in a new [indexed] section of textures.ini holds palette indices instead of colors: a palette PNG (the file's palette index) or an 8-bit grayscale PNG (the gray value), at any resolution. When the texture is built, the indices go through the game's current CLUT, including the CLUT index shift, mask and start position, and the result is uploaded as an ordinary RGBA texture. A game that swaps or customizes a palette keeps working with a high-resolution replacement. [indexed] keys use the [hashes] format and are matched with the same wildcards, so a key with a zero CLUT hash covers every palette of the texture. The contents hash only covers the indices, so one image is shared by all palettes (the loaded data is shared, each palette still has its own texture cache entry). Saving does not dump indexed textures yet. Co-Authored-By: Claude Sonnet 5.5 --- Common/Data/Format/PNGLoad.cpp | 82 ++++++++++++++ Common/Data/Format/PNGLoad.h | 7 ++ GPU/Common/ReplacedTexture.cpp | 54 +++++++++ GPU/Common/ReplacedTexture.h | 15 +++ GPU/Common/TextureCacheCommon.cpp | 49 ++++++++- GPU/Common/TextureCacheCommon.h | 2 + GPU/Common/TextureReplacer.cpp | 33 +++++- GPU/Common/TextureReplacer.h | 4 + unittest/TestTextureReplacer.cpp | 176 ++++++++++++++++++++++++++++++ 9 files changed, 420 insertions(+), 2 deletions(-) diff --git a/Common/Data/Format/PNGLoad.cpp b/Common/Data/Format/PNGLoad.cpp index 7294d049dd..c65c199703 100644 --- a/Common/Data/Format/PNGLoad.cpp +++ b/Common/Data/Format/PNGLoad.cpp @@ -144,6 +144,88 @@ int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, in return 1; } +int pngLoadIndexed(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr, int maxWidth, int maxHeight) { + *image_data_ptr = nullptr; + if (input_len == 0) { + return 0; + } + + png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, pngErrorHandler, pngWarningHandler); + if (!png) { + return 0; + } + + png_set_option(png, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); + png_set_benign_errors(png, PNG_OPTION_ON); + + png_infop info = png_create_info_struct(png); + if (!info) { + png_destroy_read_struct(&png, NULL, NULL); + return 0; + } + + unsigned char *data = nullptr; + if (setjmp(png_jmpbuf(png))) { + png_destroy_read_struct(&png, &info, NULL); + free(data); + return 0; + } + + PngReadContext readContext = {input_ptr, input_len}; + + png_set_read_fn(png, &readContext, [](png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead) { + PngReadContext *ctx = (PngReadContext *)png_get_io_ptr(png_ptr); + if (byteCountToRead > ctx->remaining) { + png_error(png_ptr, "Read past end of buffer"); + return; + } + + memcpy(outBytes, ctx->ptr, byteCountToRead); + ctx->ptr += byteCountToRead; + ctx->remaining -= byteCountToRead; + }); + + png_read_info(png, info); + + // Only formats where a pixel is a single index: palette images (the index into the file's + // palette) and grayscale images (the gray value itself). Nothing is expanded or scaled, + // so with 1, 2 and 4 bit images the index keeps its raw value. + const int color_type = png_get_color_type(png, info); + const int bit_depth = png_get_bit_depth(png, info); + if ((color_type != PNG_COLOR_TYPE_PALETTE && color_type != PNG_COLOR_TYPE_GRAY) || bit_depth > 8) { + png_destroy_read_struct(&png, &info, NULL); + return 0; + } + + png_set_packing(png); + png_set_interlace_handling(png); + png_read_update_info(png, info); + + *pwidth = png_get_image_width(png, info); + *pheight = png_get_image_height(png, info); + if (*pwidth <= 0 || *pheight <= 0 || *pwidth > maxWidth || *pheight > maxHeight) { + png_destroy_read_struct(&png, &info, NULL); + return 0; + } + + const size_t row_bytes = png_get_rowbytes(png, info); + data = (unsigned char *)malloc(row_bytes * (*pheight)); + if (!data) { + png_destroy_read_struct(&png, &info, NULL); + return 0; + } + + std::vector row_pointers(*pheight); + for (int y = 0; y < *pheight; y++) { + row_pointers[y] = data + y * row_bytes; + } + + png_read_image(png, row_pointers.data()); + png_destroy_read_struct(&png, &info, NULL); + *image_data_ptr = data; + return 1; +} + bool PNGHeaderPeek::IsValidPNGHeader() const { if (magic != 0x474e5089 || ihdrTag != 0x52444849) { return false; diff --git a/Common/Data/Format/PNGLoad.h b/Common/Data/Format/PNGLoad.h index 4bd7f3c2b5..fb042f6582 100644 --- a/Common/Data/Format/PNGLoad.h +++ b/Common/Data/Format/PNGLoad.h @@ -14,6 +14,13 @@ int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr, int maxWidth = 8192, int maxHeight = 8192); +// Loads a palette or grayscale PNG (up to 8 bits) as one byte per pixel, tightly packed: +// the palette index for palette images, the gray value for grayscale ones. Returns 0 for any +// other kind of PNG. *image_data_ptr should be deleted with free(). +int pngLoadIndexed(const unsigned char *input_ptr, size_t input_len, int *pwidth, + int *pheight, unsigned char **image_data_ptr, + int maxWidth = 8192, int maxHeight = 8192); + // PNG peeker - just read the start of a PNG straight into this struct, in order to // look at basic parameters like width and height. Note that while PNG is a chunk-based // format, the IHDR chunk is REQUIRED to be the first one, so this will work. diff --git a/GPU/Common/ReplacedTexture.cpp b/GPU/Common/ReplacedTexture.cpp index 15d980198c..93a92fe8ad 100644 --- a/GPU/Common/ReplacedTexture.cpp +++ b/GPU/Common/ReplacedTexture.cpp @@ -358,6 +358,12 @@ ReplacedTexture::LoadLevelResult ReplacedTexture::LoadLevelData(VFSFileReference std::string magic; ReplacedImageType imageType = Identify(vfs_, openFile, &magic); + if (desc_.indexed && imageType != ReplacedImageType::PNG) { + ERROR_LOG(Log::TexReplacement, "Indexed replacement %s must be a palette or grayscale PNG", filename.c_str()); + vfs_->CloseFile(openFile); + return LoadLevelResult::LOAD_ERROR; + } + // Disallow mixing image formats across mip levels: a KTX2/DDS container // manages its own mip chain, so mixing one in at a higher mip level // would corrupt the shared level data layout. @@ -489,6 +495,11 @@ ReplacedTexture::LoadLevelResult ReplacedTexture::LoadLevelData(VFSFileReference level.w = headerPeek.Width(); level.h = headerPeek.Height(); good = true; + // colorType 0 is grayscale, 3 is palette. + if (desc_.indexed && ((headerPeek.colorType != 0 && headerPeek.colorType != 3) || headerPeek.bitDepth > 8)) { + ERROR_LOG(Log::TexReplacement, "Indexed replacement %s must be a palette or grayscale PNG of at most 8 bits", filename.c_str()); + good = false; + } } else { ERROR_LOG(Log::TexReplacement, "Could not get PNG dimensions: %s (zip)", filename.c_str()); good = false; @@ -724,6 +735,30 @@ ReplacedTexture::LoadLevelResult ReplacedTexture::LoadLevelData(VFSFileReference return LoadLevelResult::CONTINUE; + } else if (imageType == ReplacedImageType::PNG && desc_.indexed) { + std::string pngdata; + pngdata.resize(fileSize); + pngdata.resize(vfs_->Read(openFile, &pngdata[0], fileSize)); + vfs_->CloseFile(openFile); + + int w = 0, h = 0; + unsigned char *indices = nullptr; + if (!pngLoadIndexed((const unsigned char *)pngdata.data(), pngdata.size(), &w, &h, &indices, level.w, level.h)) { + ERROR_LOG(Log::TexReplacement, "Could not load indexed texture replacement: %s", filename.c_str()); + return LoadLevelResult::LOAD_ERROR; + } + + std::vector &out = data_[mipLevel]; + out.resize(level.w * level.h); + for (int y = 0; y < h; ++y) { + memcpy(&out[level.w * y], indices + w * y, w); + } + free(indices); + + // The palette decides the alpha. + alphaStatus_ = TextureAlpha::Any; + levels_.push_back(level); + return LoadLevelResult::CONTINUE; } else if (imageType == ReplacedImageType::PNG) { png_image png = {}; png.version = PNG_IMAGE_VERSION; @@ -778,6 +813,25 @@ ReplacedTexture::LoadLevelResult ReplacedTexture::LoadLevelData(VFSFileReference return LoadLevelResult::LOAD_ERROR; } +bool ReplacedTexture::CopyIndexLevelTo(int level, uint8_t *out, size_t outDataSize) { + _assert_msg_(IsIndexed(), "Not an indexed texture"); + _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); + + if (State() != ReplacementState::ACTIVE) { + WARN_LOG(Log::TexReplacement, "Init not done yet"); + return false; + } + + std::lock_guard guard(lock_); + const std::vector &data = data_[level]; + if (data.empty() || data.size() > outDataSize) { + WARN_LOG(Log::TexReplacement, "Level %d is empty or doesn't fit", level); + return false; + } + memcpy(out, data.data(), data.size()); + return true; +} + bool ReplacedTexture::CopyLevelTo(int level, uint8_t *out, size_t outDataSize, int rowPitch) { _assert_msg_((size_t)level < levels_.size(), "Invalid miplevel"); _assert_msg_(out != nullptr && rowPitch > 0, "Invalid out/pitch"); diff --git a/GPU/Common/ReplacedTexture.h b/GPU/Common/ReplacedTexture.h index 7be90e24ff..efb846697a 100644 --- a/GPU/Common/ReplacedTexture.h +++ b/GPU/Common/ReplacedTexture.h @@ -111,6 +111,8 @@ struct ReplacementDesc { std::vector filenames; std::string logId; GPUFormatSupport formatSupport; + // The files hold palette indices (palette or grayscale PNG) that the game's own palette colors. + bool indexed = false; }; class ReplacedTexture; @@ -204,6 +206,19 @@ public: return alphaStatus_; } + bool IsIndexed() const { + return desc_.indexed; + } + + // Indexed textures only. Size of the stored indices, before padding to the full size. + void GetIndexDataSize(int level, int *w, int *h) const { + _dbg_assert_(IsIndexed() && (size_t)level < levels_.size()); + *w = levels_[level].w; + *h = levels_[level].h; + } + // Indexed textures only. Copies the indices, one byte each, tightly packed. + bool CopyIndexLevelTo(int level, uint8_t *out, size_t outDataSize); + bool Poll(double budget); bool CopyLevelTo(int level, uint8_t *out, size_t outDataSize, int rowPitch); diff --git a/GPU/Common/TextureCacheCommon.cpp b/GPU/Common/TextureCacheCommon.cpp index ec77feee43..7442c554fc 100644 --- a/GPU/Common/TextureCacheCommon.cpp +++ b/GPU/Common/TextureCacheCommon.cpp @@ -3055,6 +3055,49 @@ bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEnt return true; } +bool TextureCacheCommon::CopyIndexedReplacementLevel(ReplacedTexture *replaced, int level, uint8_t *data, size_t dataSize, int stride) { + int idxW, idxH, fullW, fullH; + replaced->GetIndexDataSize(level, &idxW, &idxH); + replaced->GetSize(level, &fullW, &fullH); + + if (stride < fullW * 4 || (dataSize != 0 && dataSize < (size_t)stride * (fullH - 1) + fullW * 4)) { + ERROR_LOG(Log::TexReplacement, "Indexed replacement doesn't fit the upload buffer (%dx%d, stride %d)", fullW, fullH, stride); + return false; + } + + std::vector indices(idxW * idxH); + if (!replaced->CopyIndexLevelTo(level, indices.data(), indices.size())) { + for (int y = 0; y < fullH; ++y) { + memset(data + stride * y, 0, fullW * 4); + } + return false; + } + + // The same as for a regular CLUT8 texture. The indices go through the CLUT index transform + // (shift, mask and start position), so the game controls which entries the image uses. + const GEPaletteFormat palFormat = gstate.getClutPaletteFormat(); + const u32 *clut32; + if (palFormat == GE_CMODE_32BIT_ABGR8888) { + clut32 = (const u32 *)clutBufRaw_; + } else { + // 512 entries, since the start position can put the index past the first 256. + ConvertFormatToRGBA8888(palFormat, expandClut_, (const u16 *)clutBufRaw_, 512); + clut32 = expandClut_; + } + + u32 alphaSum = 0xFFFFFFFF; + for (int y = 0; y < idxH; ++y) { + u32 *row = (u32 *)(data + stride * y); + DeIndexTexture(row, indices.data() + idxW * y, idxW, clut32, &alphaSum); + // Pad the right side to the full size. + memset(row + idxW, 0, (fullW - idxW) * 4); + } + for (int y = idxH; y < fullH; ++y) { + memset(data + stride * y, 0, fullW * 4); + } + return true; +} + // Passing 0 into dataSize will disable checking. void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, size_t dataSize, int stride, BuildTexturePlan &plan, int srcLevel, Draw::DataFormat dstFmt, TexDecodeFlags texDecFlags) { int w = gstate.getTextureWidth(srcLevel); @@ -3065,7 +3108,11 @@ void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, s if (plan.doReplace) { plan.replaced->GetSize(srcLevel, &w, &h); double replaceStart = time_now_d(); - plan.replaced->CopyLevelTo(srcLevel, data, dataSize, stride); + if (plan.replaced->IsIndexed()) { + CopyIndexedReplacementLevel(plan.replaced, srcLevel, data, dataSize, stride); + } else { + plan.replaced->CopyLevelTo(srcLevel, data, dataSize, stride); + } replacementTimeThisFrame_ += time_now_d() - replaceStart; } else { GETextureFormat tfmt = (GETextureFormat)entry.format; diff --git a/GPU/Common/TextureCacheCommon.h b/GPU/Common/TextureCacheCommon.h index 30549035c1..6dbc430491 100644 --- a/GPU/Common/TextureCacheCommon.h +++ b/GPU/Common/TextureCacheCommon.h @@ -428,6 +428,8 @@ protected: // Return value is mapData normally, but could be another buffer allocated with AllocateAlignedMemory. void LoadTextureLevel(TexCacheEntry &entry, uint8_t *mapData, size_t dataSize, int mapRowPitch, BuildTexturePlan &plan, int srcLevel, Draw::DataFormat dstFmt, TexDecodeFlags texDecFlags); + // Colors an indexed replacement with the current CLUT, into 32-bit RGBA padded to the full size. + bool CopyIndexedReplacementLevel(ReplacedTexture *replaced, int level, uint8_t *data, size_t dataSize, int stride); // This needs to be a member functions just for IsVideo and Replacer. SamplerCacheKey GetSamplingParams(int maxLevel, const TexCacheEntry *entry, bool flatZ, bool pixelMapped); diff --git a/GPU/Common/TextureReplacer.cpp b/GPU/Common/TextureReplacer.cpp index aa36770b69..60f06f73d5 100644 --- a/GPU/Common/TextureReplacer.cpp +++ b/GPU/Common/TextureReplacer.cpp @@ -152,6 +152,7 @@ bool TextureReplacer::LoadIni(std::string *error, bool notify) { cache_.clear(); savedCache_.clear(); + indexed_.clear(); ignoreAddress_ = false; reduceHash_ = false; reduceHashGlobalValue = 0.5; @@ -448,6 +449,15 @@ bool TextureReplacer::LoadIniValues(IniFile &ini, VFSBackend *dir, bool isOverri } } + if (ini.HasSection("indexed")) { + auto indexed = ini.GetOrCreateSection("indexed")->ToMap(); + // Format: hashname = true. The image files then hold palette indices, which the + // game's palette colors, so one image serves every palette of the texture. + for (const auto &[k, v] : indexed) { + ParseIndexed(k, v); + } + } + if (ini.HasSection("reducehashranges")) { auto reducehashranges = ini.GetOrCreateSection("reducehashranges")->ToMap(); // Format: w,h = reducehashvalues @@ -522,6 +532,21 @@ void TextureReplacer::ParseFiltering(const std::string &key, const std::string & } } +void TextureReplacer::ParseIndexed(const std::string &key, const std::string &value) { + ReplacementCacheKey itemKey(0, 0); + if (sscanf(key.c_str(), "%16llx%8x", &itemKey.cachekey, &itemKey.hash) >= 1) { + if (!strcasecmp(value.c_str(), "true") || value == "1") { + indexed_[itemKey] = true; + } else if (!strcasecmp(value.c_str(), "false") || value == "0") { + indexed_[itemKey] = false; + } else { + ERROR_LOG(Log::TexReplacement, "Unsupported syntax under [indexed]: %s", value.c_str()); + } + } else { + ERROR_LOG(Log::TexReplacement, "Unsupported syntax under [indexed]: %s", key.c_str()); + } +} + void TextureReplacer::ParseReduceHashRange(const std::string& key, const std::string& value) { std::vector keyParts; SplitString(key, ',', keyParts); @@ -697,6 +722,7 @@ ReplacedTexture *TextureReplacer::FindReplacement(ReplacementCacheKey replacemen } FindFiltering(lookupKey, &desc.forceFiltering); + desc.indexed = IsIndexed(lookupKey); if (foundAlias) { desc.logId = hashfiles; @@ -716,7 +742,7 @@ ReplacedTexture *TextureReplacer::FindReplacement(ReplacementCacheKey replacemen _dbg_assert_(!hashfiles.empty()); // OK, we might already have a matching texture. Textures sharing files can still differ in how // they're scaled and filtered, so those go in the level cache key too. - std::string levelKey = StringFromFormat("%s#%dx%d>%dx%d#%d", hashfiles.c_str(), desc.w, desc.h, desc.newW, desc.newH, (int)desc.forceFiltering); + std::string levelKey = StringFromFormat("%s#%dx%d>%dx%d#%d#%d", hashfiles.c_str(), desc.w, desc.h, desc.newW, desc.newH, (int)desc.forceFiltering, (int)desc.indexed); auto iter = levelCache_.find(levelKey); if (iter != levelCache_.end()) { // Insert an entry into the cache for faster lookup next time. @@ -1021,6 +1047,11 @@ bool TextureReplacer::FindFiltering(ReplacementCacheKey replacementKey, TextureF return false; } +bool TextureReplacer::IsIndexed(ReplacementCacheKey key) const { + auto found = LookupWildcard(indexed_, key, ignoreAddress_); + return found != indexed_.end() && found->second; +} + std::string TextureReplacer::LookupHashFile(ReplacementCacheKey key, bool *foundAlias, bool *ignored) { auto alias = LookupWildcard(aliases_, key, ignoreAddress_); if (alias != aliases_.end()) { diff --git a/GPU/Common/TextureReplacer.h b/GPU/Common/TextureReplacer.h index 210221562e..a064ab5638 100644 --- a/GPU/Common/TextureReplacer.h +++ b/GPU/Common/TextureReplacer.h @@ -116,12 +116,14 @@ public: protected: bool FindFiltering(ReplacementCacheKey key, TextureFiltering *forceFiltering); + bool IsIndexed(ReplacementCacheKey key) const; bool LoadIni(std::string *error, bool notify = true); void DeleteVFS(); bool LoadIniValues(IniFile &ini, VFSBackend *dir, bool isOverride, std::string *error); void ParseHashRange(const std::string &key, const std::string &value); void ParseFiltering(const std::string &key, const std::string &value); + void ParseIndexed(const std::string &key, const std::string &value); void ParseReduceHashRange(const std::string& key, const std::string& value); bool LookupHashRange(u32 addr, int w, int h, int *newW, int *newH); float LookupReduceHashRange(int w, int h); @@ -154,6 +156,8 @@ protected: std::unordered_map aliases_; std::unordered_map filtering_; + // Replacements that hold palette indices instead of colors, from the [indexed] section. + std::unordered_map indexed_; std::unordered_map cache_; std::unordered_map savedCache_; diff --git a/unittest/TestTextureReplacer.cpp b/unittest/TestTextureReplacer.cpp index 9b780ccf32..d10af9b68b 100644 --- a/unittest/TestTextureReplacer.cpp +++ b/unittest/TestTextureReplacer.cpp @@ -2,6 +2,8 @@ #include #include +#include + #include "Common/Data/Format/PNGLoad.h" #include "Common/File/FileUtil.h" #include "Common/File/Path.h" @@ -207,6 +209,175 @@ static bool TestIgnoreAddress(const Path &packDir) { return true; } +// Writes an 8-bit palette PNG (a palette in reverse gray order, so the index is not the color) +// or an 8-bit grayscale PNG, one byte per pixel. +static bool CreateIndexedPNG(const Path &filename, int w, int h, bool palette, const std::vector &indices) { + FILE *fp = File::OpenCFile(filename, "wb"); + if (!fp) { + return false; + } + png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + png_infop info = png_create_info_struct(png); + if (setjmp(png_jmpbuf(png))) { + png_destroy_write_struct(&png, &info); + fclose(fp); + return false; + } + png_init_io(png, fp); + png_set_IHDR(png, info, w, h, 8, palette ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + if (palette) { + png_color entries[256]; + for (int i = 0; i < 256; i++) { + entries[i].red = entries[i].green = entries[i].blue = 255 - i; + } + png_set_PLTE(png, info, entries, 256); + } + std::vector rows(h); + for (int y = 0; y < h; y++) { + rows[y] = (png_bytep)indices.data() + y * w; + } + png_set_rows(png, info, rows.data()); + png_write_png(png, info, PNG_TRANSFORM_IDENTITY, nullptr); + png_destroy_write_struct(&png, &info); + fclose(fp); + return true; +} + +static bool ReadFileBytes(const Path &filename, std::vector *data) { + std::string str; + if (!File::ReadBinaryFileToString(filename, &str)) { + return false; + } + data->assign(str.begin(), str.end()); + return true; +} + +static bool TestIndexedPNG(const Path &packDir) { + std::vector indices(16 * 8); + for (size_t i = 0; i < indices.size(); i++) { + indices[i] = (u8)(i * 7 + 3); + } + + for (int palette = 0; palette < 2; palette++) { + Path file = packDir / "indexed_test.png"; + if (!CreateIndexedPNG(file, 16, 8, palette != 0, indices)) { + return false; + } + std::vector png; + if (!ReadFileBytes(file, &png)) { + return false; + } + int w = 0, h = 0; + unsigned char *out = nullptr; + EXPECT_TRUE(pngLoadIndexed(png.data(), png.size(), &w, &h, &out) == 1); + EXPECT_EQ_INT(w, 16); + EXPECT_EQ_INT(h, 8); + if (!out) { + return false; + } + EXPECT_TRUE(memcmp(out, indices.data(), indices.size()) == 0); + free(out); + + // Too small a limit is refused. + EXPECT_TRUE(pngLoadIndexed(png.data(), png.size(), &w, &h, &out, 8, 8) == 0); + } + + // Truecolor is not an index. + Path rgba = packDir / "indexed_rgba.png"; + if (!CreateTestPNG(rgba, 4, 4, 0x11223344)) { + return false; + } + std::vector png; + if (!ReadFileBytes(rgba, &png)) { + return false; + } + int w = 0, h = 0; + unsigned char *out = nullptr; + EXPECT_TRUE(pngLoadIndexed(png.data(), png.size(), &w, &h, &out) == 0); + EXPECT_TRUE(out == nullptr); + return true; +} + +// The [indexed] section marks an image as palette indices. It is looked up without the CLUT hash +// so that every palette of the texture shares the one image. +static bool TestIndexedReplacement(const Path &packDir) { + static const char *iniContent = + "[options]\n" + "hash = quick\n" + "version = 1\n" + "\n" + "[hashes]\n" + "A00000080000000010000008 = indexed.png\n" + "A00000090000000010000009 = indexed_rgba.png\n" + "A000000A000000001000000A = indexed.png\n" + "\n" + "[indexed]\n" + "A00000080000000010000008 = true\n" + "A00000090000000010000009 = true\n"; + if (!WriteIni(packDir, iniContent)) { + return false; + } + + std::vector indices(16 * 8); + for (size_t i = 0; i < indices.size(); i++) { + indices[i] = (u8)(255 - i * 2); + } + if (!CreateIndexedPNG(packDir / "indexed.png", 16, 8, true, indices)) { + return false; + } + if (!CreateTestPNG(packDir / "indexed_rgba.png", 16, 8, 0x11223344)) { + return false; + } + + TextureReplacer replacer(nullptr); + std::string error; + if (!replacer.LoadPackForTesting(packDir, &error)) { + return false; + } + + // Two palettes of the same texture. + ReplacedTexture *pal1 = replacer.FindReplacement(ReplacementCacheKey(0xA0000008C0000001ULL, 0x10000008), 16, 8); + ReplacedTexture *pal2 = replacer.FindReplacement(ReplacementCacheKey(0xA0000008C0000002ULL, 0x10000008), 16, 8); + EXPECT_TRUE(pal1 != nullptr); + EXPECT_TRUE(pal1 == pal2); + + // The same image without the [indexed] entry is a regular replacement, which can't share the texture. + ReplacedTexture *plain = replacer.FindReplacement(ReplacementCacheKey(0xA000000AC0000001ULL, 0x1000000A), 16, 8); + EXPECT_TRUE(plain != nullptr); + EXPECT_TRUE(plain != pal1); + + ReplacedTexture *bad = replacer.FindReplacement(ReplacementCacheKey(0xA0000009C0000001ULL, 0x10000009), 16, 8); + EXPECT_TRUE(bad != nullptr); + if (!pal1 || !plain || !bad) { + return false; + } + EXPECT_TRUE(pal1->IsIndexed()); + EXPECT_FALSE(plain->IsIndexed()); + + g_threadManager.Init(1, 1); + EXPECT_TRUE(pal1->Poll(1.0)); + EXPECT_TRUE(pal1->State() == ReplacementState::ACTIVE); + EXPECT_EQ_INT(pal1->NumLevels(), 1); + int w = 0, h = 0; + pal1->GetIndexDataSize(0, &w, &h); + EXPECT_EQ_INT(w, 16); + EXPECT_EQ_INT(h, 8); + pal1->GetSize(0, &w, &h); + EXPECT_EQ_INT(w, 16); + EXPECT_EQ_INT(h, 8); + EXPECT_TRUE(pal1->Format() == Draw::DataFormat::R8G8B8A8_UNORM); + + std::vector copy(indices.size()); + EXPECT_TRUE(pal1->CopyIndexLevelTo(0, copy.data(), copy.size())); + EXPECT_TRUE(copy == indices); + + // A truecolor image can't serve as indices. + EXPECT_TRUE(bad->Poll(1.0)); + EXPECT_TRUE(bad->State() == ReplacementState::NOT_FOUND); + g_threadManager.Teardown(); + return true; +} + bool TestTextureReplacer() { Path packDir = Path("unittest_texture_pack"); if (!CreateTestPack(packDir)) { @@ -236,6 +407,11 @@ bool TestTextureReplacer() { return false; } + if (!TestIndexedPNG(packDir) || !TestIndexedReplacement(packDir)) { + File::DeleteDirRecursively(packDir); + return false; + } + File::DeleteDirRecursively(packDir); return true; }