#include #include #include #include #include #include #include #include #include #include "../fixtures/RHIIntegrationFixture.h" #include "XCEngine/Core/Math/Matrix4.h" #include "XCEngine/Core/Math/Vector3.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::Math; using namespace XCEngine::RHI; using namespace XCEngine::RHI::Integration; namespace { struct Vertex { float pos[4]; float uv[2]; }; struct MatrixBufferData { Matrix4x4 projection; Matrix4x4 view; Matrix4x4 model; }; constexpr float kSphereRadius = 1.0f; constexpr int kSphereSegments = 32; constexpr float kPi = 3.14159265358979323846f; constexpr uint32_t kSphereDescriptorFirstSet = 1; constexpr uint32_t kSphereDescriptorSetCount = 4; 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; } void GenerateSphere(std::vector& vertices, std::vector& indices, float radius, int segments) { vertices.clear(); indices.clear(); segments = segments < 3 ? 3 : segments; for (int lat = 0; lat <= segments; ++lat) { const float phi = kPi * static_cast(lat) / static_cast(segments); const float sinPhi = sinf(phi); const float cosPhi = cosf(phi); for (int lon = 0; lon <= segments; ++lon) { const float theta = (kPi * 2.0f) * static_cast(lon) / static_cast(segments); const float sinTheta = sinf(theta); const float cosTheta = cosf(theta); Vertex vertex = {}; vertex.pos[0] = radius * sinPhi * cosTheta; vertex.pos[1] = radius * cosPhi; vertex.pos[2] = radius * sinPhi * sinTheta; vertex.pos[3] = 1.0f; vertex.uv[0] = static_cast(lon) / static_cast(segments); vertex.uv[1] = static_cast(lat) / static_cast(segments); vertices.push_back(vertex); } } for (int lat = 0; lat < segments; ++lat) { for (int lon = 0; lon < segments; ++lon) { const uint32_t topLeft = static_cast(lat * (segments + 1) + lon); const uint32_t topRight = topLeft + 1; const uint32_t bottomLeft = static_cast((lat + 1) * (segments + 1) + lon); const uint32_t bottomRight = bottomLeft + 1; indices.push_back(topLeft); indices.push_back(bottomLeft); indices.push_back(topRight); indices.push_back(topRight); indices.push_back(bottomLeft); indices.push_back(bottomRight); } } } MatrixBufferData CreateMatrixBufferData() { const float aspect = 1280.0f / 720.0f; const Matrix4x4 projection = Matrix4x4::Perspective(45.0f * 3.141592f / 180.0f, aspect, 0.1f, 1000.0f); const Matrix4x4 view = Matrix4x4::Identity(); const Matrix4x4 model = Matrix4x4::Translation(Vector3(0.0f, 0.0f, 5.0f)); MatrixBufferData data = {}; data.projection = projection.Transpose(); data.view = view.Transpose(); data.model = model.Transpose(); return data; } const char kSphereHlsl[] = R"( Texture2D gDiffuseTexture : register(t0); SamplerState gSampler : register(s0); cbuffer MatrixBuffer : register(b0) { float4x4 gProjectionMatrix; float4x4 gViewMatrix; float4x4 gModelMatrix; }; struct VSInput { float4 position : POSITION; float2 texcoord : TEXCOORD0; }; struct PSInput { float4 position : SV_POSITION; float2 texcoord : TEXCOORD0; }; PSInput MainVS(VSInput input) { PSInput output; float4 positionWS = mul(gModelMatrix, input.position); float4 positionVS = mul(gViewMatrix, positionWS); output.position = mul(gProjectionMatrix, positionVS); output.texcoord = input.texcoord; return output; } float4 MainPS(PSInput input) : SV_TARGET { return gDiffuseTexture.Sample(gSampler, input.texcoord); } )"; const char kSphereVertexShader[] = R"(#version 430 layout(location = 0) in vec4 aPosition; layout(location = 1) in vec2 aTexCoord; layout(std140, binding = 0) uniform MatrixBuffer { mat4 gProjectionMatrix; mat4 gViewMatrix; mat4 gModelMatrix; }; out vec2 vTexCoord; void main() { vec4 positionWS = gModelMatrix * aPosition; vec4 positionVS = gViewMatrix * positionWS; gl_Position = gProjectionMatrix * positionVS; vTexCoord = aTexCoord; } )"; const char kSphereFragmentShader[] = 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) { return type == RHIType::D3D12 ? "sphere_d3d12.ppm" : "sphere_opengl.ppm"; } int GetComparisonThreshold(RHIType type) { return type == RHIType::OpenGL ? 5 : 0; } RHITexture* LoadSphereTexture(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 sphere texture: %s", texturePathString.c_str()); return nullptr; } TextureDesc textureDesc = {}; textureDesc.width = static_cast(width); textureDesc.height = static_cast(height); textureDesc.depth = 1; textureDesc.mipLevels = 1; textureDesc.arraySize = 1; textureDesc.format = static_cast(Format::R8G8B8A8_UNorm); textureDesc.textureType = static_cast(TextureType::Texture2D); textureDesc.sampleCount = 1; textureDesc.sampleQuality = 0; textureDesc.flags = 0; RHITexture* texture = device->CreateTexture( textureDesc, pixels, static_cast(width) * static_cast(height) * 4, static_cast(width) * 4); stbi_image_free(pixels); return texture; } GraphicsPipelineDesc CreateSpherePipelineDesc(RHIType type, RHIPipelineLayout* pipelineLayout) { GraphicsPipelineDesc desc = {}; desc.pipelineLayout = pipelineLayout; desc.topologyType = static_cast(PrimitiveTopologyType::Triangle); desc.renderTargetFormats[0] = static_cast(Format::R8G8B8A8_UNorm); desc.depthStencilFormat = static_cast(Format::D24_UNorm_S8_UInt); desc.sampleCount = 1; desc.rasterizerState.fillMode = static_cast(FillMode::Solid); desc.rasterizerState.cullMode = static_cast(CullMode::None); desc.rasterizerState.frontFace = static_cast(FrontFace::CounterClockwise); desc.rasterizerState.depthClipEnable = true; desc.depthStencilState.depthTestEnable = true; desc.depthStencilState.depthWriteEnable = true; desc.depthStencilState.depthFunc = static_cast(ComparisonFunc::Less); desc.depthStencilState.stencilEnable = false; InputElementDesc position = {}; position.semanticName = "POSITION"; position.semanticIndex = 0; position.format = static_cast(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(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(kSphereHlsl, kSphereHlsl + strlen(kSphereHlsl)); desc.vertexShader.sourceLanguage = ShaderLanguage::HLSL; desc.vertexShader.entryPoint = L"MainVS"; desc.vertexShader.profile = L"vs_5_0"; desc.fragmentShader.source.assign(kSphereHlsl, kSphereHlsl + strlen(kSphereHlsl)); desc.fragmentShader.sourceLanguage = ShaderLanguage::HLSL; desc.fragmentShader.entryPoint = L"MainPS"; desc.fragmentShader.profile = L"ps_5_0"; } else { desc.vertexShader.source.assign(kSphereVertexShader, kSphereVertexShader + strlen(kSphereVertexShader)); desc.vertexShader.sourceLanguage = ShaderLanguage::GLSL; desc.vertexShader.profile = L"vs_4_30"; desc.fragmentShader.source.assign(kSphereFragmentShader, kSphereFragmentShader + strlen(kSphereFragmentShader)); desc.fragmentShader.sourceLanguage = ShaderLanguage::GLSL; desc.fragmentShader.profile = L"fs_4_30"; } return desc; } class SphereTest : public RHIIntegrationFixture { protected: void SetUp() override; void TearDown() override; void RenderFrame() override; private: void InitializeSphereResources(); void ShutdownSphereResources(); std::vector mVertices; std::vector mIndices; RHIBuffer* mVertexBuffer = nullptr; RHIResourceView* mVertexBufferView = nullptr; RHIBuffer* mIndexBuffer = nullptr; RHIResourceView* mIndexBufferView = nullptr; RHITexture* mTexture = nullptr; RHIResourceView* mTextureView = nullptr; RHISampler* mSampler = nullptr; RHIDescriptorPool* mConstantPool = nullptr; RHIDescriptorSet* mConstantSet = nullptr; RHIDescriptorPool* mTexturePool = nullptr; RHIDescriptorSet* mTextureSet = nullptr; RHIDescriptorPool* mSamplerPool = nullptr; RHIDescriptorSet* mSamplerSet = nullptr; RHIPipelineLayout* mPipelineLayout = nullptr; RHIPipelineState* mPipelineState = nullptr; }; void SphereTest::SetUp() { RHIIntegrationFixture::SetUp(); InitializeSphereResources(); } void SphereTest::TearDown() { ShutdownSphereResources(); RHIIntegrationFixture::TearDown(); } void SphereTest::InitializeSphereResources() { GenerateSphere(mVertices, mIndices, kSphereRadius, kSphereSegments); ASSERT_FALSE(mVertices.empty()); ASSERT_FALSE(mIndices.empty()); BufferDesc vertexBufferDesc = {}; vertexBufferDesc.size = static_cast(mVertices.size() * sizeof(Vertex)); vertexBufferDesc.stride = sizeof(Vertex); vertexBufferDesc.bufferType = static_cast(BufferType::Vertex); mVertexBuffer = GetDevice()->CreateBuffer(vertexBufferDesc); ASSERT_NE(mVertexBuffer, nullptr); mVertexBuffer->SetData(mVertices.data(), mVertices.size() * sizeof(Vertex)); 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 = static_cast(mIndices.size() * sizeof(uint32_t)); indexBufferDesc.stride = sizeof(uint32_t); indexBufferDesc.bufferType = static_cast(BufferType::Index); mIndexBuffer = GetDevice()->CreateBuffer(indexBufferDesc); ASSERT_NE(mIndexBuffer, nullptr); mIndexBuffer->SetData(mIndices.data(), mIndices.size() * sizeof(uint32_t)); mIndexBuffer->SetStride(sizeof(uint32_t)); mIndexBuffer->SetBufferType(BufferType::Index); ResourceViewDesc indexViewDesc = {}; indexViewDesc.dimension = ResourceViewDimension::Buffer; indexViewDesc.format = static_cast(Format::R32_UInt); mIndexBufferView = GetDevice()->CreateIndexBufferView(mIndexBuffer, indexViewDesc); ASSERT_NE(mIndexBufferView, nullptr); mTexture = LoadSphereTexture(GetDevice()); ASSERT_NE(mTexture, nullptr); ResourceViewDesc textureViewDesc = {}; textureViewDesc.format = static_cast(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(FilterMode::Linear); samplerDesc.addressU = static_cast(TextureAddressMode::Clamp); samplerDesc.addressV = static_cast(TextureAddressMode::Clamp); samplerDesc.addressW = static_cast(TextureAddressMode::Clamp); samplerDesc.mipLodBias = 0.0f; samplerDesc.maxAnisotropy = 1; samplerDesc.comparisonFunc = static_cast(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 constantPoolDesc = {}; constantPoolDesc.type = DescriptorHeapType::CBV_SRV_UAV; constantPoolDesc.descriptorCount = 1; constantPoolDesc.shaderVisible = false; mConstantPool = GetDevice()->CreateDescriptorPool(constantPoolDesc); ASSERT_NE(mConstantPool, nullptr); DescriptorSetLayoutBinding constantBinding = {}; constantBinding.binding = 0; constantBinding.type = static_cast(DescriptorType::CBV); constantBinding.count = 1; DescriptorSetLayoutDesc constantLayoutDesc = {}; constantLayoutDesc.bindings = &constantBinding; constantLayoutDesc.bindingCount = 1; mConstantSet = mConstantPool->AllocateSet(constantLayoutDesc); ASSERT_NE(mConstantSet, nullptr); const MatrixBufferData matrixData = CreateMatrixBufferData(); mConstantSet->WriteConstant(0, &matrixData, sizeof(matrixData)); 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(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(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); DescriptorSetLayoutDesc setLayouts[kSphereDescriptorSetCount] = {}; // Reserve set0 so the integration test exercises non-zero firstSet binding. setLayouts[1] = constantLayoutDesc; setLayouts[2] = textureLayoutDesc; setLayouts[3] = samplerLayoutDesc; RHIPipelineLayoutDesc pipelineLayoutDesc = {}; pipelineLayoutDesc.setLayouts = setLayouts; pipelineLayoutDesc.setLayoutCount = kSphereDescriptorSetCount; mPipelineLayout = GetDevice()->CreatePipelineLayout(pipelineLayoutDesc); ASSERT_NE(mPipelineLayout, nullptr); GraphicsPipelineDesc pipelineDesc = CreateSpherePipelineDesc(GetBackendType(), mPipelineLayout); mPipelineState = GetDevice()->CreatePipelineState(pipelineDesc); ASSERT_NE(mPipelineState, nullptr); ASSERT_TRUE(mPipelineState->IsValid()); Log("[TEST] Sphere resources initialized for backend %d", static_cast(GetBackendType())); } void SphereTest::ShutdownSphereResources() { if (mPipelineState != nullptr) { mPipelineState->Shutdown(); delete mPipelineState; mPipelineState = nullptr; } if (mPipelineLayout != nullptr) { mPipelineLayout->Shutdown(); delete mPipelineLayout; mPipelineLayout = nullptr; } if (mConstantSet != nullptr) { mConstantSet->Shutdown(); delete mConstantSet; mConstantSet = nullptr; } if (mTextureSet != nullptr) { mTextureSet->Shutdown(); delete mTextureSet; mTextureSet = nullptr; } if (mSamplerSet != nullptr) { mSamplerSet->Shutdown(); delete mSamplerSet; mSamplerSet = nullptr; } if (mConstantPool != nullptr) { mConstantPool->Shutdown(); delete mConstantPool; mConstantPool = 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 SphereTest::RenderFrame() { ASSERT_NE(mPipelineState, nullptr); ASSERT_NE(mPipelineLayout, nullptr); ASSERT_NE(mConstantSet, nullptr); ASSERT_NE(mTextureSet, nullptr); ASSERT_NE(mSamplerSet, nullptr); ASSERT_NE(mVertexBufferView, nullptr); ASSERT_NE(mIndexBufferView, nullptr); RHICommandList* cmdList = GetCommandList(); RHICommandQueue* cmdQueue = GetCommandQueue(); ASSERT_NE(cmdList, nullptr); ASSERT_NE(cmdQueue, nullptr); cmdList->Reset(); SetRenderTargetForClear(true); 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 | 2); cmdList->SetPipelineState(mPipelineState); RHIDescriptorSet* descriptorSets[] = { mConstantSet, mTextureSet, mSamplerSet }; cmdList->SetGraphicsDescriptorSets(kSphereDescriptorFirstSet, 3, 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(mIndices.size())); EndRender(); cmdList->Close(); void* cmdLists[] = { cmdList }; cmdQueue->ExecuteCommandLists(1, cmdLists); } TEST_P(SphereTest, RenderSphere) { 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] Sphere MainLoop: frame %d", frameCount); BeginRender(); RenderFrame(); if (frameCount >= targetFrameCount) { cmdQueue->WaitForIdle(); Log("[TEST] Sphere MainLoop: frame %d reached, capturing %s", frameCount, screenshotFilename); ASSERT_TRUE(TakeScreenshot(screenshotFilename)); ASSERT_TRUE(CompareWithGoldenTemplate(screenshotFilename, "GT.ppm", static_cast(comparisonThreshold))); Log("[TEST] Sphere MainLoop: frame %d compare passed", frameCount); break; } swapChain->Present(0, 0); } } } // namespace INSTANTIATE_TEST_SUITE_P(D3D12, SphereTest, ::testing::Values(RHIType::D3D12)); INSTANTIATE_TEST_SUITE_P(OpenGL, SphereTest, ::testing::Values(RHIType::OpenGL)); GTEST_API_ int main(int argc, char** argv) { Logger::Get().Initialize(); Logger::Get().AddSink(std::make_unique()); Logger::Get().SetMinimumLevel(LogLevel::Debug); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }