Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions include/Interface/IUtilAssetsIntegrity.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 15 additions & 46 deletions src/BSPValidation.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#pragma once

#include <IUtilAssetsIntegrity.h>
#include "TextureAssetValidation.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -326,32 +318,9 @@ class CBSPValidation
return Bad("miptex outside lump");

const auto miptex = base + static_cast<size_t>(offset);
if (!std::memchr(m_pData + miptex, 0, MiptexNameBytes))
return Bad("unterminated miptex name");

const auto width = Read<std::uint32_t>(miptex + MiptexWidthOffset);
const auto height = Read<std::uint32_t>(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<std::uint32_t>(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<std::uint16_t>(static_cast<size_t>(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;
Expand Down
190 changes: 190 additions & 0 deletions src/TextureAssetValidation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
#pragma once

#include <IUtilAssetsIntegrity.h>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>

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 <class T>
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<const Byte*>(buffer);
if (!p || size < sizeof(MiptexHeader))
return Fail(result, "Truncated miptex header");
const auto header = Read<MiptexHeader>(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<std::uint16_t>(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<const Byte*>(buffer);
if (!p || size < sizeof(WADHeader))
return Fail(result, "Truncated WAD header");
const auto header = Read<WADHeader>(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<WADEntry>(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<const Byte*>(buffer);
if (!p || size < sizeof(SpriteHeader) + sizeof(std::uint16_t))
return Fail(result, "Truncated sprite header");
const auto header = Read<SpriteHeader>(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<uint16_t>(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<int32_t>(p + cursor);
cursor += 4;
int count = 1;
if (type == 1)
{
if (size - cursor < 4)
return Fail(result, "Missing sprite group count");
count = Read<int32_t>(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<float>(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<SpriteFrame>(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
15 changes: 15 additions & 0 deletions src/UtilAssetsIntegrity.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
2 changes: 1 addition & 1 deletion tests/BSPTests.h
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ struct BSPFixture

Append(Textures, std::int32_t{1});
Append(Textures, static_cast<std::int32_t>(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<std::uint16_t>(PaletteColors));
Expand Down
22 changes: 19 additions & 3 deletions tests/SmokeTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading