Files
XCEngine/tests/RHI/integration/quad/main.cpp

589 lines
19 KiB
C++
Raw Normal View History

#include <windows.h>
#include <filesystem>
2026-03-27 13:52:56 +08:00
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gtest/gtest.h>
#include <stb/stb_image.h>
#include "../fixtures/RHIIntegrationFixture.h"
#include "XCEngine/Debug/ConsoleLogSink.h"
#include "XCEngine/Debug/Logger.h"
#include "XCEngine/RHI/RHIBuffer.h"
#include "XCEngine/RHI/RHIDescriptorPool.h"
#include "XCEngine/RHI/RHIDescriptorSet.h"
#include "XCEngine/RHI/RHIPipelineLayout.h"
#include "XCEngine/RHI/RHIPipelineState.h"
#include "XCEngine/RHI/RHIResourceView.h"
#include "XCEngine/RHI/RHISampler.h"
#include "XCEngine/RHI/RHITexture.h"
using namespace XCEngine::Debug;
using namespace XCEngine::RHI;
using namespace XCEngine::RHI::Integration;
namespace {
struct Vertex {
float pos[4];
float uv[2];
};
constexpr Vertex kQuadVertices[] = {
{ { -0.5f, -0.5f, 0.0f, 1.0f }, { 0.0f, 1.0f } },
{ { -0.5f, 0.5f, 0.0f, 1.0f }, { 0.0f, 0.0f } },
{ { 0.5f, -0.5f, 0.0f, 1.0f }, { 1.0f, 1.0f } },
{ { 0.5f, 0.5f, 0.0f, 1.0f }, { 1.0f, 0.0f } },
};
constexpr uint32_t kQuadIndices[] = { 0, 1, 2, 2, 1, 3 };
std::filesystem::path GetExecutableDirectory() {
char exePath[MAX_PATH] = {};
const DWORD length = GetModuleFileNameA(nullptr, exePath, MAX_PATH);
if (length == 0 || length >= MAX_PATH) {
return std::filesystem::current_path();
}
return std::filesystem::path(exePath).parent_path();
}
std::filesystem::path ResolveRuntimePath(const char* relativePath) {
return GetExecutableDirectory() / relativePath;
}
2026-03-27 13:52:56 +08:00
std::vector<uint8_t> LoadBinaryFileRelative(const char* filename) {
const std::filesystem::path path = ResolveRuntimePath(filename);
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
return {};
}
const std::streamsize size = file.tellg();
if (size <= 0) {
return {};
}
std::vector<uint8_t> bytes(static_cast<size_t>(size));
file.seekg(0, std::ios::beg);
if (!file.read(reinterpret_cast<char*>(bytes.data()), size)) {
return {};
}
return bytes;
}
const char kQuadHlsl[] = R"(
Texture2D gTexture : register(t0);
SamplerState gSampler : register(s0);
struct VSInput {
float4 position : POSITION;
float2 texcoord : TEXCOORD;
};
struct PSInput {
float4 position : SV_POSITION;
float2 texcoord : TEXCOORD;
};
PSInput MainVS(VSInput input) {
PSInput output;
output.position = input.position;
output.texcoord = input.texcoord;
return output;
}
float4 MainPS(PSInput input) : SV_TARGET {
return gTexture.Sample(gSampler, input.texcoord);
}
)";
const char kQuadVertexShader[] = R"(#version 430
layout(location = 0) in vec4 aPosition;
layout(location = 1) in vec2 aTexCoord;
out vec2 vTexCoord;
void main() {
gl_Position = aPosition;
vTexCoord = aTexCoord;
}
)";
const char kQuadFragmentShader[] = R"(#version 430
layout(binding = 0) uniform sampler2D uTexture;
in vec2 vTexCoord;
layout(location = 0) out vec4 fragColor;
void main() {
fragColor = texture(uTexture, vTexCoord);
}
)";
const char* GetScreenshotFilename(RHIType type) {
2026-03-27 13:52:56 +08:00
switch (type) {
case RHIType::D3D12:
return "quad_d3d12.ppm";
case RHIType::OpenGL:
return "quad_opengl.ppm";
case RHIType::Vulkan:
return "quad_vulkan.ppm";
default:
return "quad_unknown.ppm";
}
}
RHITexture* LoadQuadTexture(RHIDevice* device) {
const std::filesystem::path texturePath = ResolveRuntimePath("Res/Image/earth.png");
const std::string texturePathString = texturePath.string();
stbi_set_flip_vertically_on_load(0);
int width = 0;
int height = 0;
int channels = 0;
stbi_uc* pixels = stbi_load(texturePathString.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (pixels == nullptr) {
Log("[TEST] Failed to load quad texture: %s", texturePathString.c_str());
return nullptr;
}
TextureDesc textureDesc = {};
textureDesc.width = static_cast<uint32_t>(width);
textureDesc.height = static_cast<uint32_t>(height);
textureDesc.depth = 1;
textureDesc.mipLevels = 1;
textureDesc.arraySize = 1;
textureDesc.format = static_cast<uint32_t>(Format::R8G8B8A8_UNorm);
textureDesc.textureType = static_cast<uint32_t>(TextureType::Texture2D);
textureDesc.sampleCount = 1;
textureDesc.sampleQuality = 0;
textureDesc.flags = 0;
RHITexture* texture = device->CreateTexture(
textureDesc,
pixels,
static_cast<size_t>(width) * static_cast<size_t>(height) * 4,
static_cast<uint32_t>(width) * 4);
stbi_image_free(pixels);
return texture;
}
int GetComparisonThreshold(RHIType type) {
return type == RHIType::OpenGL ? 5 : 0;
}
GraphicsPipelineDesc CreateQuadPipelineDesc(RHIType type, RHIPipelineLayout* pipelineLayout) {
GraphicsPipelineDesc desc = {};
desc.pipelineLayout = pipelineLayout;
desc.topologyType = static_cast<uint32_t>(PrimitiveTopologyType::Triangle);
desc.renderTargetFormats[0] = static_cast<uint32_t>(Format::R8G8B8A8_UNorm);
desc.depthStencilFormat = static_cast<uint32_t>(Format::Unknown);
desc.sampleCount = 1;
desc.rasterizerState.fillMode = static_cast<uint32_t>(FillMode::Solid);
desc.rasterizerState.cullMode = static_cast<uint32_t>(CullMode::None);
desc.rasterizerState.frontFace = static_cast<uint32_t>(FrontFace::CounterClockwise);
desc.rasterizerState.depthClipEnable = true;
desc.depthStencilState.depthTestEnable = false;
desc.depthStencilState.depthWriteEnable = false;
desc.depthStencilState.stencilEnable = false;
InputElementDesc position = {};
position.semanticName = "POSITION";
position.semanticIndex = 0;
position.format = static_cast<uint32_t>(Format::R32G32B32A32_Float);
position.inputSlot = 0;
position.alignedByteOffset = 0;
desc.inputLayout.elements.push_back(position);
InputElementDesc texcoord = {};
texcoord.semanticName = "TEXCOORD";
texcoord.semanticIndex = 0;
texcoord.format = static_cast<uint32_t>(Format::R32G32_Float);
texcoord.inputSlot = 0;
texcoord.alignedByteOffset = sizeof(float) * 4;
desc.inputLayout.elements.push_back(texcoord);
if (type == RHIType::D3D12) {
desc.vertexShader.source.assign(kQuadHlsl, kQuadHlsl + strlen(kQuadHlsl));
desc.vertexShader.sourceLanguage = ShaderLanguage::HLSL;
desc.vertexShader.entryPoint = L"MainVS";
desc.vertexShader.profile = L"vs_5_0";
desc.fragmentShader.source.assign(kQuadHlsl, kQuadHlsl + strlen(kQuadHlsl));
desc.fragmentShader.sourceLanguage = ShaderLanguage::HLSL;
desc.fragmentShader.entryPoint = L"MainPS";
desc.fragmentShader.profile = L"ps_5_0";
2026-03-27 13:52:56 +08:00
} else if (type == RHIType::OpenGL) {
desc.vertexShader.source.assign(kQuadVertexShader, kQuadVertexShader + strlen(kQuadVertexShader));
desc.vertexShader.sourceLanguage = ShaderLanguage::GLSL;
desc.vertexShader.profile = L"vs_4_30";
desc.fragmentShader.source.assign(kQuadFragmentShader, kQuadFragmentShader + strlen(kQuadFragmentShader));
desc.fragmentShader.sourceLanguage = ShaderLanguage::GLSL;
desc.fragmentShader.profile = L"fs_4_30";
2026-03-27 13:52:56 +08:00
} else if (type == RHIType::Vulkan) {
desc.vertexShader.source = LoadBinaryFileRelative("quad_vulkan.vert.spv");
desc.vertexShader.sourceLanguage = ShaderLanguage::SPIRV;
desc.vertexShader.entryPoint = L"main";
desc.fragmentShader.source = LoadBinaryFileRelative("quad_vulkan.frag.spv");
desc.fragmentShader.sourceLanguage = ShaderLanguage::SPIRV;
desc.fragmentShader.entryPoint = L"main";
}
return desc;
}
class QuadTest : public RHIIntegrationFixture {
protected:
void SetUp() override;
void TearDown() override;
void RenderFrame() override;
private:
void InitializeQuadResources();
void ShutdownQuadResources();
RHIBuffer* mVertexBuffer = nullptr;
RHIResourceView* mVertexBufferView = nullptr;
RHIBuffer* mIndexBuffer = nullptr;
RHIResourceView* mIndexBufferView = nullptr;
RHITexture* mTexture = nullptr;
RHIResourceView* mTextureView = nullptr;
RHISampler* mSampler = nullptr;
RHIDescriptorPool* mTexturePool = nullptr;
RHIDescriptorSet* mTextureSet = nullptr;
RHIDescriptorPool* mSamplerPool = nullptr;
RHIDescriptorSet* mSamplerSet = nullptr;
RHIPipelineLayout* mPipelineLayout = nullptr;
RHIPipelineState* mPipelineState = nullptr;
};
void QuadTest::SetUp() {
RHIIntegrationFixture::SetUp();
InitializeQuadResources();
}
void QuadTest::TearDown() {
ShutdownQuadResources();
RHIIntegrationFixture::TearDown();
}
void QuadTest::InitializeQuadResources() {
BufferDesc vertexBufferDesc = {};
vertexBufferDesc.size = sizeof(kQuadVertices);
vertexBufferDesc.stride = sizeof(Vertex);
vertexBufferDesc.bufferType = static_cast<uint32_t>(BufferType::Vertex);
vertexBufferDesc.flags = 0;
mVertexBuffer = GetDevice()->CreateBuffer(vertexBufferDesc);
ASSERT_NE(mVertexBuffer, nullptr);
mVertexBuffer->SetData(kQuadVertices, sizeof(kQuadVertices));
mVertexBuffer->SetStride(sizeof(Vertex));
mVertexBuffer->SetBufferType(BufferType::Vertex);
ResourceViewDesc vertexViewDesc = {};
vertexViewDesc.dimension = ResourceViewDimension::Buffer;
vertexViewDesc.structureByteStride = sizeof(Vertex);
mVertexBufferView = GetDevice()->CreateVertexBufferView(mVertexBuffer, vertexViewDesc);
ASSERT_NE(mVertexBufferView, nullptr);
BufferDesc indexBufferDesc = {};
indexBufferDesc.size = sizeof(kQuadIndices);
indexBufferDesc.stride = sizeof(uint32_t);
indexBufferDesc.bufferType = static_cast<uint32_t>(BufferType::Index);
indexBufferDesc.flags = 0;
mIndexBuffer = GetDevice()->CreateBuffer(indexBufferDesc);
ASSERT_NE(mIndexBuffer, nullptr);
mIndexBuffer->SetData(kQuadIndices, sizeof(kQuadIndices));
mIndexBuffer->SetStride(sizeof(uint32_t));
mIndexBuffer->SetBufferType(BufferType::Index);
ResourceViewDesc indexViewDesc = {};
indexViewDesc.dimension = ResourceViewDimension::Buffer;
indexViewDesc.format = static_cast<uint32_t>(Format::R32_UInt);
mIndexBufferView = GetDevice()->CreateIndexBufferView(mIndexBuffer, indexViewDesc);
ASSERT_NE(mIndexBufferView, nullptr);
mTexture = LoadQuadTexture(GetDevice());
ASSERT_NE(mTexture, nullptr);
ResourceViewDesc textureViewDesc = {};
textureViewDesc.format = static_cast<uint32_t>(Format::R8G8B8A8_UNorm);
textureViewDesc.dimension = ResourceViewDimension::Texture2D;
textureViewDesc.mipLevel = 0;
mTextureView = GetDevice()->CreateShaderResourceView(mTexture, textureViewDesc);
ASSERT_NE(mTextureView, nullptr);
SamplerDesc samplerDesc = {};
samplerDesc.filter = static_cast<uint32_t>(FilterMode::Linear);
samplerDesc.addressU = static_cast<uint32_t>(TextureAddressMode::Clamp);
samplerDesc.addressV = static_cast<uint32_t>(TextureAddressMode::Clamp);
samplerDesc.addressW = static_cast<uint32_t>(TextureAddressMode::Clamp);
samplerDesc.mipLodBias = 0.0f;
samplerDesc.maxAnisotropy = 1;
samplerDesc.comparisonFunc = static_cast<uint32_t>(ComparisonFunc::Always);
samplerDesc.borderColorR = 0.0f;
samplerDesc.borderColorG = 0.0f;
samplerDesc.borderColorB = 0.0f;
samplerDesc.borderColorA = 0.0f;
samplerDesc.minLod = 0.0f;
samplerDesc.maxLod = 1000.0f;
mSampler = GetDevice()->CreateSampler(samplerDesc);
ASSERT_NE(mSampler, nullptr);
DescriptorPoolDesc texturePoolDesc = {};
texturePoolDesc.type = DescriptorHeapType::CBV_SRV_UAV;
texturePoolDesc.descriptorCount = 1;
texturePoolDesc.shaderVisible = true;
mTexturePool = GetDevice()->CreateDescriptorPool(texturePoolDesc);
ASSERT_NE(mTexturePool, nullptr);
DescriptorSetLayoutBinding textureBinding = {};
textureBinding.binding = 0;
textureBinding.type = static_cast<uint32_t>(DescriptorType::SRV);
textureBinding.count = 1;
DescriptorSetLayoutDesc textureLayoutDesc = {};
textureLayoutDesc.bindings = &textureBinding;
textureLayoutDesc.bindingCount = 1;
mTextureSet = mTexturePool->AllocateSet(textureLayoutDesc);
ASSERT_NE(mTextureSet, nullptr);
mTextureSet->Update(0, mTextureView);
DescriptorPoolDesc samplerPoolDesc = {};
samplerPoolDesc.type = DescriptorHeapType::Sampler;
samplerPoolDesc.descriptorCount = 1;
samplerPoolDesc.shaderVisible = true;
mSamplerPool = GetDevice()->CreateDescriptorPool(samplerPoolDesc);
ASSERT_NE(mSamplerPool, nullptr);
DescriptorSetLayoutBinding samplerBinding = {};
samplerBinding.binding = 0;
samplerBinding.type = static_cast<uint32_t>(DescriptorType::Sampler);
samplerBinding.count = 1;
DescriptorSetLayoutDesc samplerLayoutDesc = {};
samplerLayoutDesc.bindings = &samplerBinding;
samplerLayoutDesc.bindingCount = 1;
mSamplerSet = mSamplerPool->AllocateSet(samplerLayoutDesc);
ASSERT_NE(mSamplerSet, nullptr);
mSamplerSet->UpdateSampler(0, mSampler);
2026-03-27 13:52:56 +08:00
DescriptorSetLayoutBinding pipelineTextureBinding = {};
pipelineTextureBinding.binding = 0;
pipelineTextureBinding.type = static_cast<uint32_t>(DescriptorType::SRV);
pipelineTextureBinding.count = 1;
pipelineTextureBinding.visibility = static_cast<uint32_t>(ShaderVisibility::Pixel);
DescriptorSetLayoutDesc textureSetLayout = {};
textureSetLayout.bindings = &pipelineTextureBinding;
textureSetLayout.bindingCount = 1;
DescriptorSetLayoutBinding pipelineSamplerBinding = {};
pipelineSamplerBinding.binding = 0;
pipelineSamplerBinding.type = static_cast<uint32_t>(DescriptorType::Sampler);
pipelineSamplerBinding.count = 1;
pipelineSamplerBinding.visibility = static_cast<uint32_t>(ShaderVisibility::Pixel);
DescriptorSetLayoutDesc samplerSetLayout = {};
samplerSetLayout.bindings = &pipelineSamplerBinding;
samplerSetLayout.bindingCount = 1;
DescriptorSetLayoutDesc setLayouts[] = {
textureSetLayout,
samplerSetLayout,
};
RHIPipelineLayoutDesc pipelineLayoutDesc = {};
2026-03-27 13:52:56 +08:00
pipelineLayoutDesc.setLayouts = setLayouts;
pipelineLayoutDesc.setLayoutCount = 2;
mPipelineLayout = GetDevice()->CreatePipelineLayout(pipelineLayoutDesc);
ASSERT_NE(mPipelineLayout, nullptr);
GraphicsPipelineDesc pipelineDesc = CreateQuadPipelineDesc(GetBackendType(), mPipelineLayout);
mPipelineState = GetDevice()->CreatePipelineState(pipelineDesc);
ASSERT_NE(mPipelineState, nullptr);
ASSERT_TRUE(mPipelineState->IsValid());
Log("[TEST] Quad resources initialized for backend %d", static_cast<int>(GetBackendType()));
}
void QuadTest::ShutdownQuadResources() {
if (mPipelineState != nullptr) {
mPipelineState->Shutdown();
delete mPipelineState;
mPipelineState = nullptr;
}
if (mPipelineLayout != nullptr) {
mPipelineLayout->Shutdown();
delete mPipelineLayout;
mPipelineLayout = nullptr;
}
if (mTextureSet != nullptr) {
mTextureSet->Shutdown();
delete mTextureSet;
mTextureSet = nullptr;
}
if (mSamplerSet != nullptr) {
mSamplerSet->Shutdown();
delete mSamplerSet;
mSamplerSet = nullptr;
}
if (mTexturePool != nullptr) {
mTexturePool->Shutdown();
delete mTexturePool;
mTexturePool = nullptr;
}
if (mSamplerPool != nullptr) {
mSamplerPool->Shutdown();
delete mSamplerPool;
mSamplerPool = nullptr;
}
if (mSampler != nullptr) {
mSampler->Shutdown();
delete mSampler;
mSampler = nullptr;
}
if (mTextureView != nullptr) {
mTextureView->Shutdown();
delete mTextureView;
mTextureView = nullptr;
}
if (mTexture != nullptr) {
mTexture->Shutdown();
delete mTexture;
mTexture = nullptr;
}
if (mVertexBufferView != nullptr) {
mVertexBufferView->Shutdown();
delete mVertexBufferView;
mVertexBufferView = nullptr;
}
if (mIndexBufferView != nullptr) {
mIndexBufferView->Shutdown();
delete mIndexBufferView;
mIndexBufferView = nullptr;
}
if (mVertexBuffer != nullptr) {
mVertexBuffer->Shutdown();
delete mVertexBuffer;
mVertexBuffer = nullptr;
}
if (mIndexBuffer != nullptr) {
mIndexBuffer->Shutdown();
delete mIndexBuffer;
mIndexBuffer = nullptr;
}
}
void QuadTest::RenderFrame() {
ASSERT_NE(mPipelineState, nullptr);
ASSERT_NE(mVertexBufferView, nullptr);
ASSERT_NE(mIndexBufferView, nullptr);
ASSERT_NE(mTextureSet, nullptr);
ASSERT_NE(mSamplerSet, nullptr);
ASSERT_NE(mPipelineLayout, nullptr);
RHICommandList* cmdList = GetCommandList();
RHICommandQueue* cmdQueue = GetCommandQueue();
ASSERT_NE(cmdList, nullptr);
ASSERT_NE(cmdQueue, nullptr);
cmdList->Reset();
SetRenderTargetForClear();
Viewport viewport = { 0.0f, 0.0f, 1280.0f, 720.0f, 0.0f, 1.0f };
Rect scissorRect = { 0, 0, 1280, 720 };
cmdList->SetViewport(viewport);
cmdList->SetScissorRect(scissorRect);
cmdList->Clear(0.0f, 0.0f, 1.0f, 1.0f, 1);
cmdList->SetPipelineState(mPipelineState);
RHIDescriptorSet* descriptorSets[] = { mTextureSet, mSamplerSet };
cmdList->SetGraphicsDescriptorSets(0, 2, descriptorSets, mPipelineLayout);
cmdList->SetPrimitiveTopology(PrimitiveTopology::TriangleList);
RHIResourceView* vertexBuffers[] = { mVertexBufferView };
uint64_t offsets[] = { 0 };
uint32_t strides[] = { sizeof(Vertex) };
cmdList->SetVertexBuffers(0, 1, vertexBuffers, offsets, strides);
cmdList->SetIndexBuffer(mIndexBufferView, 0);
cmdList->DrawIndexed(static_cast<uint32_t>(sizeof(kQuadIndices) / sizeof(kQuadIndices[0])));
EndRender();
cmdList->Close();
void* cmdLists[] = { cmdList };
cmdQueue->ExecuteCommandLists(1, cmdLists);
}
TEST_P(QuadTest, RenderQuad) {
RHICommandQueue* cmdQueue = GetCommandQueue();
RHISwapChain* swapChain = GetSwapChain();
const int targetFrameCount = 30;
const char* screenshotFilename = GetScreenshotFilename(GetBackendType());
const int comparisonThreshold = GetComparisonThreshold(GetBackendType());
for (int frameCount = 0; frameCount <= targetFrameCount; ++frameCount) {
if (frameCount > 0) {
cmdQueue->WaitForPreviousFrame();
}
Log("[TEST] Quad MainLoop: frame %d", frameCount);
BeginRender();
RenderFrame();
if (frameCount >= targetFrameCount) {
cmdQueue->WaitForIdle();
Log("[TEST] Quad MainLoop: frame %d reached, capturing %s", frameCount, screenshotFilename);
ASSERT_TRUE(TakeScreenshot(screenshotFilename));
ASSERT_TRUE(CompareWithGoldenTemplate(screenshotFilename, "GT.ppm", static_cast<float>(comparisonThreshold)));
Log("[TEST] Quad MainLoop: frame %d compare passed", frameCount);
break;
}
swapChain->Present(0, 0);
}
}
} // namespace
INSTANTIATE_TEST_SUITE_P(D3D12, QuadTest, ::testing::Values(RHIType::D3D12));
INSTANTIATE_TEST_SUITE_P(OpenGL, QuadTest, ::testing::Values(RHIType::OpenGL));
2026-03-27 13:52:56 +08:00
#if defined(XCENGINE_SUPPORT_VULKAN)
INSTANTIATE_TEST_SUITE_P(Vulkan, QuadTest, ::testing::Values(RHIType::Vulkan));
#endif
GTEST_API_ int main(int argc, char** argv) {
Logger::Get().Initialize();
Logger::Get().AddSink(std::make_unique<ConsoleLogSink>());
Logger::Get().SetMinimumLevel(LogLevel::Debug);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}