diff --git a/include/Interface/IUtilAssetsIntegrity.h b/include/Interface/IUtilAssetsIntegrity.h index e01e980..af028ff 100644 --- a/include/Interface/IUtilAssetsIntegrity.h +++ b/include/Interface/IUtilAssetsIntegrity.h @@ -98,6 +98,12 @@ class IUtilAssetsIntegrity : public IBaseInterface size_t bufSize, UtilAssetsIntegrityBSPLayout layout, UtilAssetsIntegrityCheckResult_BSP* result) = 0; + + //Version 2 IDSP, a complete WAD2/WAD3 file (directory ranges only), and one unpacked + //GoldSrc miptex with pixel and palette data, respectively. Diagnostics are optional. + virtual UtilAssetsIntegrityCheckReason CheckSprite(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) = 0; + virtual UtilAssetsIntegrityCheckReason CheckWADDirectory(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) = 0; + virtual UtilAssetsIntegrityCheckReason CheckMiptex(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) = 0; }; //The interface is published only through EXPOSE_SINGLE_INTERFACE; callers resolve diff --git a/src/BSPValidation.h b/src/BSPValidation.h index 952b704..9e58426 100644 --- a/src/BSPValidation.h +++ b/src/BSPValidation.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "TextureAssetValidation.h" #include #include #include @@ -121,25 +121,17 @@ class CBSPValidation static constexpr size_t ModelVisLeafsOffset = 52; static constexpr size_t ModelFirstFaceOffset = 56; static constexpr size_t ModelFaceCountOffset = 60; - static constexpr size_t MiptexWidthOffset = 16; - static constexpr size_t MiptexHeightOffset = 20; - static constexpr size_t MiptexPixelsOffset = 24; - static constexpr size_t MiptexNameBytes = 16; - - static constexpr int Axes = 3; - static constexpr int TextureAxes = 2; - static constexpr int TextureVecs = 4; - static constexpr int Hulls = 4; - static constexpr int LightStyles = 4; - static constexpr int NoLightStyle = 255; - static constexpr int LightSample = 3; - static constexpr int LuxelSize = 16; - static constexpr int TexSpecial = 1; - static constexpr int AbsentOffset = -1; - static constexpr int MaxTextureSide = 16384; - static constexpr int TextureAlign = 16; - static constexpr size_t PaletteColors = 256; - static constexpr size_t PaletteCountLen = sizeof(std::uint16_t); + + static constexpr int Axes = 3; + static constexpr int TextureAxes = 2; + static constexpr int TextureVecs = 4; + static constexpr int Hulls = 4; + static constexpr int LightStyles = 4; + static constexpr int NoLightStyle = 255; + static constexpr int LightSample = 3; + static constexpr int LuxelSize = 16; + static constexpr int TexSpecial = 1; + static constexpr int AbsentOffset = -1; //A face whose extents exceed this either errors in CalcSurfaceExtents or is TEX_SPECIAL, which has no lightmap. static constexpr int MaxSurfaceExtent = 512; //CalcSurfaceExtents' starting extremes, kept as its floats. @@ -326,32 +318,9 @@ class CBSPValidation return Bad("miptex outside lump"); const auto miptex = base + static_cast(offset); - if (!std::memchr(m_pData + miptex, 0, MiptexNameBytes)) - return Bad("unterminated miptex name"); - - const auto width = Read(miptex + MiptexWidthOffset); - const auto height = Read(miptex + MiptexHeightOffset); - if (!width || !height || width > MaxTextureSide || height > MaxTextureSide) - return Bad("invalid miptex dimensions", Reason::InvalidFormat); - - //Textures without embedded pixels come from the WADs by name. - if (!Read(miptex + MiptexPixelsOffset)) - continue; - - if ((width % TextureAlign) || (height % TextureAlign)) - return Bad("miptex is not 16 aligned", Reason::InvalidFormat); - - //Four mip levels: 1 + 1/4 + 1/16 + 1/64 of the pixels, as the engine's width * height / 64 * 85. - const auto pixelBytes = std::uint64_t(width) * height / 64 * 85; - const auto paletteCount = miptex + MiptexBytes + pixelBytes; - const auto end = base + length; - if (paletteCount > end || PaletteCountLen > end - paletteCount) - return Bad("miptex pixels outside lump"); - - const auto colors = Read(static_cast(paletteCount)); - const auto bytes = std::uint64_t(colors < PaletteColors ? PaletteColors : colors) * LightSample; - if (bytes > end - paletteCount - PaletteCountLen) - return Bad("miptex palette outside lump"); + m_Reason = TextureAssetValidation::Miptex(m_pData + miptex, length - offset, true, m_pResult); + if (m_Reason != Reason::OK) + return false; } return true; diff --git a/src/TextureAssetValidation.h b/src/TextureAssetValidation.h new file mode 100644 index 0000000..33bd39f --- /dev/null +++ b/src/TextureAssetValidation.h @@ -0,0 +1,190 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace TextureAssetValidation +{ +using Reason = UtilAssetsIntegrityCheckReason; +using Byte = std::uint8_t; + +constexpr int MaxTextureSide = 16384; +constexpr unsigned PaletteColors = 256; +constexpr size_t MipLevels = 4; + +//GoldSrc little-endian disk records. Copy into aligned locals before inspecting fields. +struct MiptexHeader +{ + char name[16]; + std::uint32_t width, height, offsets[MipLevels]; +}; +struct WADHeader +{ + char signature[4]; + std::int32_t count, directory; +}; +struct WADEntry +{ + std::int32_t position, diskSize, size; + Byte type, compression, padding[2]; + char name[16]; +}; +struct SpriteHeader +{ + char signature[4]; + std::int32_t version, orientation, textureFormat; + float radius; + std::int32_t width, height, frames; + float beamLength; + std::int32_t syncType; +}; +struct SpriteFrame +{ + std::int32_t x, y, width, height; +}; +static_assert(sizeof(MiptexHeader) == 40 && sizeof(WADHeader) == 12 && sizeof(WADEntry) == 32); +static_assert(sizeof(SpriteHeader) == 40 && sizeof(SpriteFrame) == 16); + +template +T Read(const Byte* bytes) +{ + T value; + std::memcpy(&value, bytes, sizeof(value)); + return value; +} + +inline Reason Fail(UtilAssetsIntegrityCheckResult* result, const char* text, Reason reason = Reason::OutOfBound) +{ + if (result) + std::snprintf(result->ReasonStr, sizeof(result->ReasonStr), "%s", text); + return reason; +} + +inline Reason Miptex(const void* buffer, size_t size, bool allowExternal, UtilAssetsIntegrityCheckResult* result) +{ + if (result) + result->ReasonStr[0] = 0; + constexpr size_t alignment = 16; + const auto* p = static_cast(buffer); + if (!p || size < sizeof(MiptexHeader)) + return Fail(result, "Truncated miptex header"); + const auto header = Read(p); + if (!std::memchr(header.name, 0, sizeof(header.name))) + return Fail(result, "Unterminated miptex name"); + const auto width = header.width, height = header.height; + if (!width || !height || width > MaxTextureSide || height > MaxTextureSide) + return Fail(result, "Invalid miptex dimensions", Reason::InvalidFormat); + if (allowExternal && !header.offsets[0]) + return Reason::OK; + if (width % alignment || height % alignment) + return Fail(result, "Miptex dimensions are not 16 aligned", Reason::InvalidFormat); + + //Mod_LoadTextures locates the base pixels and palette using the packed layout. + size_t cursor = sizeof(header), pixels = width * height; + for (size_t level = 0; level < MipLevels; ++level) + { + if (header.offsets[level] != cursor || pixels > size - cursor) + return Fail(result, "Miptex level outside packed pixel data"); + cursor += pixels; + pixels /= 4; + } + if (size - cursor < sizeof(std::uint16_t)) + return Fail(result, "Missing miptex color count"); + const auto colors = Read(p + cursor); + const size_t paletteBytes = (colors < PaletteColors ? PaletteColors : colors) * 3; + if (paletteBytes > size - cursor - sizeof(colors)) + return Fail(result, "Miptex palette outside lump"); + return Reason::OK; +} + +inline Reason WADDirectory(const void* buffer, size_t size, UtilAssetsIntegrityCheckResult* result) +{ + if (result) + result->ReasonStr[0] = 0; + const auto* p = static_cast(buffer); + if (!p || size < sizeof(WADHeader)) + return Fail(result, "Truncated WAD header"); + const auto header = Read(p); + if (std::memcmp(header.signature, "WAD2", 4) && std::memcmp(header.signature, "WAD3", 4)) + return Fail(result, "Unknown WAD signature", Reason::InvalidFormat); + const int count = header.count, offset = header.directory; + if (count < 0 || offset < 0 || size_t(offset) > size || size_t(count) > (size - offset) / sizeof(WADEntry)) + return Fail(result, "WAD directory outside file"); + for (int i = 0; i < count; ++i) + { + const auto lump = Read(p + offset + size_t(i) * sizeof(WADEntry)); + const int pos = lump.position, bytes = lump.diskSize; + if (pos < 0 || bytes < 0 || size_t(pos) > size || size_t(bytes) > size - pos) + return Fail(result, "WAD lump outside file"); + } + return Reason::OK; +} + +inline Reason Sprite(const void* buffer, size_t size, UtilAssetsIntegrityCheckResult* result) +{ + if (result) + result->ReasonStr[0] = 0; + constexpr size_t frameHeader = sizeof(SpriteFrame); + const auto* p = static_cast(buffer); + if (!p || size < sizeof(SpriteHeader) + sizeof(std::uint16_t)) + return Fail(result, "Truncated sprite header"); + const auto header = Read(p); + if (std::memcmp(header.signature, "IDSP", 4) || header.version != 2) + return Fail(result, "Expected version 2 sprite", Reason::InvalidFormat); + if (header.orientation < 0 || header.orientation > 4 || header.textureFormat < 0 || header.textureFormat > 3 || header.syncType < 0 || header.syncType > 1) + return Fail(result, "Invalid sprite render or sync type", Reason::InvalidFormat); + if (header.width <= 0 || header.height <= 0 || !std::isfinite(header.beamLength) || !std::isfinite(header.radius)) + return Fail(result, "Invalid sprite bounds", Reason::InvalidFormat); + const auto frames = header.frames; + const auto colors = Read(p + sizeof(header)); + if (colors != PaletteColors) + return Fail(result, "Expected 256 sprite palette colors", Reason::InvalidFormat); + size_t cursor = sizeof(header) + sizeof(colors) + colors * 3; + if (cursor > size || size > INT_MAX || frames <= 0 || size_t(frames) > (size - cursor) / (4 + frameHeader + 1)) + return Fail(result, "Sprite palette or frames outside file"); + for (int i = 0; i < frames; ++i) + { + if (size - cursor < 4) + return Fail(result, "Missing sprite frame type"); + const auto type = Read(p + cursor); + cursor += 4; + int count = 1; + if (type == 1) + { + if (size - cursor < 4) + return Fail(result, "Missing sprite group count"); + count = Read(p + cursor); + cursor += 4; + if (count <= 0 || size_t(count) > (size - cursor) / (sizeof(float) + frameHeader + 1) || + std::int64_t(i) * 100 + count - 1 > INT_MAX) + return Fail(result, "Invalid sprite group count"); + for (int j = 0; j < count; ++j) + { + const float interval = Read(p + cursor); + if (!std::isfinite(interval) || interval <= 0) + return Fail(result, "Invalid sprite group interval", Reason::InvalidFormat); + cursor += sizeof(float); + } + } + else if (type != 0) + return Fail(result, "Invalid sprite frame type", Reason::InvalidFormat); + for (int j = 0; j < count; ++j) + { + if (size - cursor < frameHeader) + return Fail(result, "Truncated sprite frame header"); + const auto frame = Read(p + cursor); + const int width = frame.width, height = frame.height; + cursor += frameHeader; + if (width <= 0 || height <= 0 || width > MaxTextureSide || height > MaxTextureSide || frame.x > INT_MAX - width || frame.y < INT_MIN + height || + size_t(width) > (size - cursor) / size_t(height)) + return Fail(result, "Invalid sprite frame dimensions or origin"); + cursor += size_t(width) * height; + } + } + return Reason::OK; +} +} // namespace TextureAssetValidation diff --git a/src/UtilAssetsIntegrity.cpp b/src/UtilAssetsIntegrity.cpp index 90cd58a..a572762 100644 --- a/src/UtilAssetsIntegrity.cpp +++ b/src/UtilAssetsIntegrity.cpp @@ -104,6 +104,21 @@ class CUtilAssetsIntegrity : public IUtilAssetsIntegrity { return CBSPValidation(buf, bufSize, layout, result).Check(); } + + UtilAssetsIntegrityCheckReason CheckSprite(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) noexcept override + { + return TextureAssetValidation::Sprite(buf, bufSize, result); + } + + UtilAssetsIntegrityCheckReason CheckWADDirectory(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) noexcept override + { + return TextureAssetValidation::WADDirectory(buf, bufSize, result); + } + + UtilAssetsIntegrityCheckReason CheckMiptex(const void* buf, size_t bufSize, UtilAssetsIntegrityCheckResult* result) noexcept override + { + return TextureAssetValidation::Miptex(buf, bufSize, false, result); + } }; EXPOSE_SINGLE_INTERFACE(CUtilAssetsIntegrity, IUtilAssetsIntegrity, UTIL_ASSETS_INTEGRITY_INTERFACE_VERSION); diff --git a/tests/BSPTests.h b/tests/BSPTests.h index 7bd9383..19a19fb 100644 --- a/tests/BSPTests.h +++ b/tests/BSPTests.h @@ -135,7 +135,7 @@ struct BSPFixture Append(Textures, std::int32_t{1}); Append(Textures, static_cast(MiptexOffset)); - Miptex miptex{"fixture", Side, Side, {sizeof(Miptex), 0, 0, 0}}; + Miptex miptex{"fixture", Side, Side, {sizeof(Miptex), sizeof(Miptex) + Side * Side, sizeof(Miptex) + Side * Side * 5 / 4, sizeof(Miptex) + Side * Side * 21 / 16}}; Append(Textures, miptex); lumps[Textures].resize(lumps[Textures].size() + MipBytes); Append(Textures, static_cast(PaletteColors)); diff --git a/tests/SmokeTests.cpp b/tests/SmokeTests.cpp index 690e83b..1695737 100644 --- a/tests/SmokeTests.cpp +++ b/tests/SmokeTests.cpp @@ -174,6 +174,7 @@ void CheckBmps(IUtilAssetsIntegrity& api) } #include "StudioModelTests.h" #include "BSPTests.h" +#include "TextureAssetTests.h" } // namespace int wmain(int argc, wchar_t** argv) @@ -210,14 +211,25 @@ int wmain(int argc, wchar_t** argv) CheckSequenceGroups(library.handle, *api); CheckBmps(*api); CheckBSPs(*api); + CheckTextureAssets(*api); if (failures != 0) return 1; if (argc == 4) { - size_t checked = 0, checkedGroups = 0, checkedMaps = 0, rejected = 0; + TextureScanCounts textureCounts; + size_t checked = 0, checkedGroups = 0, checkedMaps = 0, rejected = 0; for (const auto& entry : std::filesystem::recursive_directory_iterator(argv[3])) { - if (entry.is_regular_file() && entry.path().extension() == L".bsp") + if (!entry.is_regular_file()) + continue; + const auto ext = entry.path().extension(); + const bool isSprite = !_wcsicmp(ext.c_str(), L".spr"); + if (isSprite || !_wcsicmp(ext.c_str(), L".wad")) + { + ScanTextureAsset(*api, entry.path(), isSprite, textureCounts); + continue; + } + if (ext == L".bsp") { //Brush files below a bshift directory use Blue Shift's lump table, as the engine picks it by game. auto layout = UtilAssetsIntegrityBSPLayout::GoldSrc; @@ -277,9 +289,13 @@ int wmain(int argc, wchar_t** argv) } } } + std::cout << std::filesystem::path(argv[3]).string() << ": " << textureCounts.sprites << " sprites, " << textureCounts.wads + << " WADs, " << textureCounts.textures << " miptex lumps; rejected " << textureCounts.rejected << ".\n"; + if (textureCounts.rejected) + return 1; std::cout << "Scanned " << checked << " MDL files, " << checkedGroups << " sequence groups against their main models and " << checkedMaps << " BSP files; rejected " << rejected << ".\n"; } - std::cout << "Public interface, StudioModel, BMP and BSP smoke tests passed.\n"; + std::cout << "Public interface, StudioModel, BMP, BSP, sprite and WAD smoke tests passed.\n"; return 0; } catch (const std::exception& error) diff --git a/tests/TextureAssetTests.h b/tests/TextureAssetTests.h new file mode 100644 index 0000000..33c9d91 --- /dev/null +++ b/tests/TextureAssetTests.h @@ -0,0 +1,150 @@ +#pragma once + +//Independent disk fixtures. Each mutation starts with a valid asset. +using AssetBytes = std::vector; +template +void SetAssetField(AssetBytes& bytes, size_t offset, T value) +{ + std::memcpy(bytes.data() + offset, &value, sizeof(value)); +} + +void CheckTextureAssets(IUtilAssetsIntegrity& api) +{ + using Reason = UtilAssetsIntegrityCheckReason; + auto check = [&](auto method, const AssetBytes& bytes, bool valid, const char* label) { + UtilAssetsIntegrityCheckResult result; + const auto reason = (api.*method)(bytes.data(), bytes.size(), &result); + Check((reason == Reason::OK) == valid && (valid || result.ReasonStr[0]), label); + }; + constexpr size_t palette = 42, frameType = palette + 768; + AssetBytes sprite(frameType + 4 + 16 + 1); + std::memcpy(sprite.data(), "IDSP", 4); + SetAssetField(sprite, 4, 2); + for (const size_t offset : {20, 24, 28}) + SetAssetField(sprite, offset, 1); + SetAssetField(sprite, 40, std::uint16_t{256}); + SetAssetField(sprite, frameType + 12, 1); + SetAssetField(sprite, frameType + 16, 1); + const auto spr = &IUtilAssetsIntegrity::CheckSprite; + const auto wad = &IUtilAssetsIntegrity::CheckWADDirectory; + const auto mip = &IUtilAssetsIntegrity::CheckMiptex; + auto mutate = [&](auto method, AssetBytes bytes, size_t offset, auto value, const char* label) { + SetAssetField(bytes, offset, value); + check(method, bytes, false, label); + }; + check(spr, sprite, true, "single sprite"); + mutate(spr, sprite, 0, 0, "sprite signature"); + mutate(spr, sprite, 4, 3, "sprite version"); + mutate(spr, sprite, 8, 5, "sprite orientation"); + mutate(spr, sprite, 12, 4, "sprite texture format"); + mutate(spr, sprite, 16, std::numeric_limits::quiet_NaN(), "sprite radius"); + mutate(spr, sprite, 20, 0, "sprite width"); + mutate(spr, sprite, 24, -1, "sprite height"); + mutate(spr, sprite, 28, INT_MAX, "sprite frame count"); + mutate(spr, sprite, 32, std::numeric_limits::infinity(), "sprite beam length"); + mutate(spr, sprite, 36, 2, "sprite sync type"); + mutate(spr, sprite, 40, std::uint16_t{255}, "sprite palette count"); + mutate(spr, sprite, frameType, 2, "sprite frame type"); + mutate(spr, sprite, frameType + 4, INT_MAX, "sprite right edge overflow"); + mutate(spr, sprite, frameType + 8, INT_MIN, "sprite bottom edge overflow"); + mutate(spr, sprite, frameType + 12, 0, "sprite frame width"); + mutate(spr, sprite, frameType + 16, INT_MAX, "sprite frame height"); + sprite.insert(sprite.begin() + frameType + 4, 8, 0); + SetAssetField(sprite, frameType, 1); + SetAssetField(sprite, frameType + 4, 1); + SetAssetField(sprite, frameType + 8, 0.5f); + check(spr, sprite, true, "group sprite"); + mutate(spr, sprite, frameType + 4, 0, "empty sprite group"); + mutate(spr, sprite, frameType + 4, INT_MAX, "oversize sprite group"); + mutate(spr, sprite, frameType + 8, 0.0f, "zero group interval"); + mutate(spr, sprite, frameType + 8, std::numeric_limits::quiet_NaN(), "nonfinite group interval"); + for (size_t length = 0; length < sprite.size(); ++length) + Check((api.*spr)(sprite.data(), length, nullptr) != Reason::OK, "truncated group sprite"); + + AssetBytes directory(12 + 32); + std::memcpy(directory.data(), "WAD2", 4); + SetAssetField(directory, 4, 1); + SetAssetField(directory, 8, 12); + check(wad, directory, true, "WAD2 directory"); + directory[3] = '3'; + check(wad, directory, true, "WAD3 directory with non-texture entry"); + mutate(wad, directory, 0, 0, "WAD signature"); + mutate(wad, directory, 4, -1, "negative WAD count"); + mutate(wad, directory, 4, INT_MAX, "WAD directory size"); + mutate(wad, directory, 8, -1, "negative WAD directory offset"); + mutate(wad, directory, 8, 13, "truncated WAD directory"); + mutate(wad, directory, 12, -1, "negative WAD filepos"); + mutate(wad, directory, 12, INT_MAX, "WAD filepos outside file"); + mutate(wad, directory, 16, -1, "negative WAD disksize"); + mutate(wad, directory, 16, 45, "WAD disksize outside file"); + directory.resize(11); + check(wad, directory, false, "truncated WAD header"); + + BSPFixture bsp; + const auto& lump = bsp.lumps[BSPFixture::Textures]; + AssetBytes texture(lump.begin() + BSPFixture::MiptexOffset, lump.end()); + check(mip, texture, true, "WAD packed miptex"); + for (size_t level = 0; level < 4; ++level) + { + mutate(mip, texture, 24 + level * 4, 0, "WAD mip offset"); + if (level) + { + BSPFixture broken; + broken.Set(BSPFixture::Textures, 0, 0, BSPFixture::MiptexOffset + 24 + level * 4); + auto bytes = broken.Build(); + Check(api.CheckBSP(bytes.data(), bytes.size(), UtilAssetsIntegrityBSPLayout::GoldSrc, nullptr) != Reason::OK, "BSP mip offset"); + } + } + mutate(mip, texture, 16, 17, "WAD miptex alignment"); + mutate(mip, texture, 20, 0, "WAD miptex height"); + texture.pop_back(); + check(mip, texture, false, "truncated WAD palette"); +} + +struct TextureScanCounts +{ + size_t sprites{}, wads{}, textures{}, rejected{}; +}; + +void ScanTextureAsset(IUtilAssetsIntegrity& api, const std::filesystem::path& path, bool isSprite, TextureScanCounts& counts) +{ + std::ifstream input(path, std::ios::binary); + const AssetBytes bytes((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + UtilAssetsIntegrityCheckResult result; + auto reject = [&](const std::string& entry) { + ++counts.rejected; + std::cerr << path.string() << entry << ": " << result.ReasonStr << '\n'; + }; + if (isSprite) + { + ++counts.sprites; + if (api.CheckSprite(bytes.data(), bytes.size(), &result) != UtilAssetsIntegrityCheckReason::OK) + reject(""); + return; + } + ++counts.wads; + if (api.CheckWADDirectory(bytes.data(), bytes.size(), &result) != UtilAssetsIntegrityCheckReason::OK) + { + reject(""); + return; + } + auto readInt = [&](size_t offset) { + std::int32_t value; + std::memcpy(&value, bytes.data() + offset, sizeof(value)); + return value; + }; + const int count = readInt(4), directory = readInt(8); + const auto miptexType = bytes[3] == '3' ? 67 : 68; + for (int i = 0; i < count; ++i) + { + const size_t entry = directory + size_t(i) * 32; + if (bytes[entry + 12] != miptexType) + continue; + ++counts.textures; + if (bytes[entry + 13]) + std::snprintf(result.ReasonStr, sizeof(result.ReasonStr), "Compressed miptex"); + else if (api.CheckMiptex(bytes.data() + readInt(entry), readInt(entry + 4), &result) == UtilAssetsIntegrityCheckReason::OK) + continue; + reject(" lump #" + std::to_string(i)); + } +}