Consume bounded additional lights in forward-lit

This commit is contained in:
2026-04-05 16:15:12 +08:00
parent 9db0d82082
commit f03a8f63ec
10 changed files with 941 additions and 40 deletions

View File

@@ -10,9 +10,20 @@ layout(std140, binding = 0) uniform PerObjectConstants {
mat4 gNormalMatrix;
};
const int XC_MAX_ADDITIONAL_LIGHTS = 8;
struct AdditionalLightData {
vec4 colorAndIntensity;
vec4 positionAndRange;
vec4 directionAndType;
vec4 spotAnglesAndFlags;
};
layout(std140, binding = 1) uniform LightingConstants {
vec4 gMainLightDirectionAndIntensity;
vec4 gMainLightColorAndFlags;
vec4 gLightingParams;
AdditionalLightData gAdditionalLights[XC_MAX_ADDITIONAL_LIGHTS];
};
layout(std140, binding = 2) uniform MaterialConstants {
@@ -57,20 +68,97 @@ float ComputeShadowAttenuation(vec3 positionWS) {
return receiverDepth <= shadowDepth ? 1.0 : (1.0 - shadowStrength);
}
float ComputeRangeAttenuation(float distanceSq, float range) {
if (range <= 0.0) {
return 0.0;
}
float clampedRange = max(range, 0.0001);
float rangeSq = clampedRange * clampedRange;
if (distanceSq >= rangeSq) {
return 0.0;
}
float distance = sqrt(max(distanceSq, 0.0));
float normalized = clamp(1.0 - distance / clampedRange, 0.0, 1.0);
return normalized * normalized;
}
float ComputeSpotAttenuation(AdditionalLightData light, vec3 directionToLightWS) {
float cosOuter = light.spotAnglesAndFlags.x;
float cosInner = light.spotAnglesAndFlags.y;
vec3 spotAxisToLightWS = normalize(light.directionAndType.xyz);
float cosTheta = dot(spotAxisToLightWS, directionToLightWS);
return clamp((cosTheta - cosOuter) / max(cosInner - cosOuter, 1e-4), 0.0, 1.0);
}
vec3 EvaluateAdditionalLight(AdditionalLightData light, vec3 normalWS, vec3 positionWS) {
float lightType = light.directionAndType.w;
vec3 lightColor = light.colorAndIntensity.rgb;
float lightIntensity = light.colorAndIntensity.w;
vec3 directionToLightWS = vec3(0.0);
float attenuation = 1.0;
if (lightType < 0.5) {
directionToLightWS = normalize(light.directionAndType.xyz);
} else {
vec3 lightVectorWS = light.positionAndRange.xyz - positionWS;
float distanceSq = dot(lightVectorWS, lightVectorWS);
if (distanceSq <= 1e-6) {
return vec3(0.0);
}
directionToLightWS = normalize(lightVectorWS);
attenuation = ComputeRangeAttenuation(distanceSq, light.positionAndRange.w);
if (attenuation <= 0.0) {
return vec3(0.0);
}
if (lightType > 1.5) {
attenuation *= ComputeSpotAttenuation(light, directionToLightWS);
if (attenuation <= 0.0) {
return vec3(0.0);
}
}
}
float diffuse = max(dot(normalWS, directionToLightWS), 0.0);
if (diffuse <= 0.0) {
return vec3(0.0);
}
return lightColor * (diffuse * lightIntensity * attenuation);
}
void main() {
vec4 baseColor = texture(uBaseColorTexture, vTexCoord) * gBaseColorFactor;
if (gMainLightColorAndFlags.w < 0.5) {
int additionalLightCount = min(int(gLightingParams.x + 0.5), XC_MAX_ADDITIONAL_LIGHTS);
if (gMainLightColorAndFlags.w < 0.5 && additionalLightCount == 0) {
fragColor = baseColor;
return;
}
vec3 normalWS = normalize(vNormalWS);
vec3 lighting = gLightingParams.yyy;
if (gMainLightColorAndFlags.w >= 0.5) {
vec3 directionToLightWS = normalize(gMainLightDirectionAndIntensity.xyz);
float diffuse = max(dot(normalWS, directionToLightWS), 0.0);
float shadowAttenuation = diffuse > 0.0
? ComputeShadowAttenuation(vPositionWS)
: 1.0;
vec3 lighting = vec3(0.28) +
lighting +=
gMainLightColorAndFlags.rgb * (diffuse * gMainLightDirectionAndIntensity.w * shadowAttenuation);
}
for (int lightIndex = 0; lightIndex < XC_MAX_ADDITIONAL_LIGHTS; ++lightIndex) {
if (lightIndex >= additionalLightCount) {
break;
}
lighting += EvaluateAdditionalLight(gAdditionalLights[lightIndex], normalWS, vPositionWS);
}
fragColor = vec4(baseColor.rgb * lighting, baseColor.a);
}

View File

@@ -12,9 +12,20 @@ layout(set = 0, binding = 0, std140) uniform PerObjectConstants {
mat4 gNormalMatrix;
};
const int XC_MAX_ADDITIONAL_LIGHTS = 8;
struct AdditionalLightData {
vec4 colorAndIntensity;
vec4 positionAndRange;
vec4 directionAndType;
vec4 spotAnglesAndFlags;
};
layout(set = 1, binding = 0, std140) uniform LightingConstants {
vec4 gMainLightDirectionAndIntensity;
vec4 gMainLightColorAndFlags;
vec4 gLightingParams;
AdditionalLightData gAdditionalLights[XC_MAX_ADDITIONAL_LIGHTS];
};
layout(set = 2, binding = 0, std140) uniform MaterialConstants {
@@ -59,20 +70,97 @@ float ComputeShadowAttenuation(vec3 positionWS) {
return receiverDepth <= shadowDepth ? 1.0 : (1.0 - shadowStrength);
}
float ComputeRangeAttenuation(float distanceSq, float range) {
if (range <= 0.0) {
return 0.0;
}
float clampedRange = max(range, 0.0001);
float rangeSq = clampedRange * clampedRange;
if (distanceSq >= rangeSq) {
return 0.0;
}
float distance = sqrt(max(distanceSq, 0.0));
float normalized = clamp(1.0 - distance / clampedRange, 0.0, 1.0);
return normalized * normalized;
}
float ComputeSpotAttenuation(AdditionalLightData light, vec3 directionToLightWS) {
float cosOuter = light.spotAnglesAndFlags.x;
float cosInner = light.spotAnglesAndFlags.y;
vec3 spotAxisToLightWS = normalize(light.directionAndType.xyz);
float cosTheta = dot(spotAxisToLightWS, directionToLightWS);
return clamp((cosTheta - cosOuter) / max(cosInner - cosOuter, 1e-4), 0.0, 1.0);
}
vec3 EvaluateAdditionalLight(AdditionalLightData light, vec3 normalWS, vec3 positionWS) {
float lightType = light.directionAndType.w;
vec3 lightColor = light.colorAndIntensity.rgb;
float lightIntensity = light.colorAndIntensity.w;
vec3 directionToLightWS = vec3(0.0);
float attenuation = 1.0;
if (lightType < 0.5) {
directionToLightWS = normalize(light.directionAndType.xyz);
} else {
vec3 lightVectorWS = light.positionAndRange.xyz - positionWS;
float distanceSq = dot(lightVectorWS, lightVectorWS);
if (distanceSq <= 1e-6) {
return vec3(0.0);
}
directionToLightWS = normalize(lightVectorWS);
attenuation = ComputeRangeAttenuation(distanceSq, light.positionAndRange.w);
if (attenuation <= 0.0) {
return vec3(0.0);
}
if (lightType > 1.5) {
attenuation *= ComputeSpotAttenuation(light, directionToLightWS);
if (attenuation <= 0.0) {
return vec3(0.0);
}
}
}
float diffuse = max(dot(normalWS, directionToLightWS), 0.0);
if (diffuse <= 0.0) {
return vec3(0.0);
}
return lightColor * (diffuse * lightIntensity * attenuation);
}
void main() {
vec4 baseColor = texture(sampler2D(uBaseColorTexture, uLinearSampler), vTexCoord) * gBaseColorFactor;
if (gMainLightColorAndFlags.w < 0.5) {
int additionalLightCount = min(int(gLightingParams.x + 0.5), XC_MAX_ADDITIONAL_LIGHTS);
if (gMainLightColorAndFlags.w < 0.5 && additionalLightCount == 0) {
fragColor = baseColor;
return;
}
vec3 normalWS = normalize(vNormalWS);
vec3 lighting = gLightingParams.yyy;
if (gMainLightColorAndFlags.w >= 0.5) {
vec3 directionToLightWS = normalize(gMainLightDirectionAndIntensity.xyz);
float diffuse = max(dot(normalWS, directionToLightWS), 0.0);
float shadowAttenuation = diffuse > 0.0
? ComputeShadowAttenuation(vPositionWS)
: 1.0;
vec3 lighting = vec3(0.28) +
lighting +=
gMainLightColorAndFlags.rgb * (diffuse * gMainLightDirectionAndIntensity.w * shadowAttenuation);
}
for (int lightIndex = 0; lightIndex < XC_MAX_ADDITIONAL_LIGHTS; ++lightIndex) {
if (lightIndex >= additionalLightCount) {
break;
}
lighting += EvaluateAdditionalLight(gAdditionalLights[lightIndex], normalWS, vPositionWS);
}
fragColor = vec4(baseColor.rgb * lighting, baseColor.a);
}

View File

@@ -11,9 +11,20 @@ cbuffer PerObjectConstants : register(b0) {
float4x4 gNormalMatrix;
};
static const int XC_MAX_ADDITIONAL_LIGHTS = 8;
struct AdditionalLightData {
float4 colorAndIntensity;
float4 positionAndRange;
float4 directionAndType;
float4 spotAnglesAndFlags;
};
cbuffer LightingConstants : register(b1) {
float4 gMainLightDirectionAndIntensity;
float4 gMainLightColorAndFlags;
float4 gLightingParams;
AdditionalLightData gAdditionalLights[XC_MAX_ADDITIONAL_LIGHTS];
};
cbuffer MaterialConstants : register(b2) {
@@ -59,19 +70,97 @@ float ComputeShadowAttenuation(float3 positionWS) {
return receiverDepth <= shadowDepth ? 1.0f : (1.0f - shadowStrength);
}
float ComputeRangeAttenuation(float distanceSq, float range) {
if (range <= 0.0f) {
return 0.0f;
}
const float clampedRange = max(range, 0.0001f);
const float rangeSq = clampedRange * clampedRange;
if (distanceSq >= rangeSq) {
return 0.0f;
}
const float distance = sqrt(max(distanceSq, 0.0f));
const float normalized = saturate(1.0f - distance / clampedRange);
return normalized * normalized;
}
float ComputeSpotAttenuation(AdditionalLightData light, float3 directionToLightWS) {
const float cosOuter = light.spotAnglesAndFlags.x;
const float cosInner = light.spotAnglesAndFlags.y;
const float3 spotAxisToLightWS = normalize(light.directionAndType.xyz);
const float cosTheta = dot(spotAxisToLightWS, directionToLightWS);
return saturate((cosTheta - cosOuter) / max(cosInner - cosOuter, 1e-4f));
}
float3 EvaluateAdditionalLight(AdditionalLightData light, float3 normalWS, float3 positionWS) {
const float lightType = light.directionAndType.w;
const float3 lightColor = light.colorAndIntensity.rgb;
const float lightIntensity = light.colorAndIntensity.w;
float3 directionToLightWS = float3(0.0f, 0.0f, 0.0f);
float attenuation = 1.0f;
if (lightType < 0.5f) {
directionToLightWS = normalize(light.directionAndType.xyz);
} else {
const float3 lightVectorWS = light.positionAndRange.xyz - positionWS;
const float distanceSq = dot(lightVectorWS, lightVectorWS);
if (distanceSq <= 1e-6f) {
return 0.0f.xxx;
}
directionToLightWS = lightVectorWS * rsqrt(distanceSq);
attenuation = ComputeRangeAttenuation(distanceSq, light.positionAndRange.w);
if (attenuation <= 0.0f) {
return 0.0f.xxx;
}
if (lightType > 1.5f) {
attenuation *= ComputeSpotAttenuation(light, directionToLightWS);
if (attenuation <= 0.0f) {
return 0.0f.xxx;
}
}
}
const float diffuse = saturate(dot(normalWS, directionToLightWS));
if (diffuse <= 0.0f) {
return 0.0f.xxx;
}
return lightColor * (diffuse * lightIntensity * attenuation);
}
float4 MainPS(PSInput input) : SV_TARGET {
float4 baseColor = gBaseColorTexture.Sample(gLinearSampler, input.texcoord) * gBaseColorFactor;
if (gMainLightColorAndFlags.a < 0.5f) {
const int additionalLightCount = min((int)gLightingParams.x, XC_MAX_ADDITIONAL_LIGHTS);
if (gMainLightColorAndFlags.a < 0.5f && additionalLightCount == 0) {
return baseColor;
}
float3 normalWS = normalize(input.normalWS);
float3 lighting = gLightingParams.yyy;
if (gMainLightColorAndFlags.a >= 0.5f) {
float3 directionToLightWS = normalize(gMainLightDirectionAndIntensity.xyz);
float diffuse = saturate(dot(normalWS, directionToLightWS));
float shadowAttenuation = diffuse > 0.0f
? ComputeShadowAttenuation(input.positionWS)
: 1.0f;
float3 lighting = float3(0.28f, 0.28f, 0.28f) +
lighting +=
gMainLightColorAndFlags.rgb * (diffuse * gMainLightDirectionAndIntensity.w * shadowAttenuation);
}
[unroll]
for (int lightIndex = 0; lightIndex < XC_MAX_ADDITIONAL_LIGHTS; ++lightIndex) {
if (lightIndex >= additionalLightCount) {
break;
}
lighting += EvaluateAdditionalLight(gAdditionalLights[lightIndex], normalWS, input.positionWS);
}
return float4(baseColor.rgb * lighting, baseColor.a);
}

View File

@@ -14,6 +14,7 @@
#include <XCEngine/RHI/RHISampler.h>
#include <XCEngine/RHI/RHITexture.h>
#include <array>
#include <functional>
#include <unordered_map>
#include <vector>
@@ -66,9 +67,21 @@ private:
Math::Matrix4x4 normalMatrix = Math::Matrix4x4::Identity();
};
static constexpr Core::uint32 kMaxLightingAdditionalLightCount =
RenderLightingData::kMaxAdditionalLightCount;
struct AdditionalLightConstants {
Math::Vector4 colorAndIntensity = Math::Vector4::Zero();
Math::Vector4 positionAndRange = Math::Vector4::Zero();
Math::Vector4 directionAndType = Math::Vector4::Zero();
Math::Vector4 spotAnglesAndFlags = Math::Vector4::Zero();
};
struct LightingConstants {
Math::Vector4 mainLightDirectionAndIntensity = Math::Vector4::Zero();
Math::Vector4 mainLightColorAndFlags = Math::Vector4::Zero();
Math::Vector4 lightingParams = Math::Vector4::Zero();
std::array<AdditionalLightConstants, kMaxLightingAdditionalLightCount> additionalLights = {};
};
struct ShadowReceiverConstants {
@@ -213,6 +226,8 @@ private:
const Resources::Texture* ResolveTexture(const Resources::Material* material) const;
RHI::RHIResourceView* ResolveTextureView(const VisibleRenderItem& visibleItem);
static LightingConstants BuildLightingConstants(const RenderLightingData& lightingData);
static AdditionalLightConstants BuildAdditionalLightConstants(const RenderAdditionalLightData& lightData);
bool ExecuteForwardOpaquePass(const RenderPassContext& context);
bool DrawVisibleItem(
const RenderContext& context,

View File

@@ -15,6 +15,7 @@
#include "Resources/Texture/Texture.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
namespace XCEngine {
@@ -52,6 +53,9 @@ private:
namespace {
constexpr float kForwardAmbientIntensity = 0.28f;
constexpr float kSpotInnerAngleRatio = 0.8f;
bool IsDepthFormat(RHI::Format format) {
return format == RHI::Format::D24_UNorm_S8_UInt ||
format == RHI::Format::D32_Float;
@@ -866,6 +870,78 @@ RHI::RHIResourceView* BuiltinForwardPipeline::ResolveTextureView(
return m_fallbackTextureView;
}
BuiltinForwardPipeline::LightingConstants BuiltinForwardPipeline::BuildLightingConstants(
const RenderLightingData& lightingData) {
LightingConstants lightingConstants = {};
if (lightingData.HasMainDirectionalLight()) {
lightingConstants.mainLightDirectionAndIntensity = Math::Vector4(
lightingData.mainDirectionalLight.direction.x,
lightingData.mainDirectionalLight.direction.y,
lightingData.mainDirectionalLight.direction.z,
lightingData.mainDirectionalLight.intensity);
lightingConstants.mainLightColorAndFlags = Math::Vector4(
lightingData.mainDirectionalLight.color.r,
lightingData.mainDirectionalLight.color.g,
lightingData.mainDirectionalLight.color.b,
1.0f);
}
const Core::uint32 additionalLightCount = std::min<Core::uint32>(
lightingData.additionalLightCount,
kMaxLightingAdditionalLightCount);
lightingConstants.lightingParams = Math::Vector4(
static_cast<float>(additionalLightCount),
kForwardAmbientIntensity,
0.0f,
0.0f);
for (Core::uint32 index = 0; index < additionalLightCount; ++index) {
lightingConstants.additionalLights[index] =
BuildAdditionalLightConstants(lightingData.additionalLights[index]);
}
return lightingConstants;
}
BuiltinForwardPipeline::AdditionalLightConstants BuiltinForwardPipeline::BuildAdditionalLightConstants(
const RenderAdditionalLightData& lightData) {
AdditionalLightConstants constants = {};
constants.colorAndIntensity = Math::Vector4(
lightData.color.r,
lightData.color.g,
lightData.color.b,
lightData.intensity);
constants.positionAndRange = Math::Vector4(
lightData.position.x,
lightData.position.y,
lightData.position.z,
lightData.range);
constants.directionAndType = Math::Vector4(
lightData.direction.x,
lightData.direction.y,
lightData.direction.z,
static_cast<float>(lightData.type));
if (lightData.type == RenderLightType::Spot) {
const float outerHalfAngleRadians = Math::Radians(lightData.spotAngle * 0.5f);
const float innerHalfAngleRadians = outerHalfAngleRadians * kSpotInnerAngleRatio;
constants.spotAnglesAndFlags = Math::Vector4(
std::cos(outerHalfAngleRadians),
std::cos(innerHalfAngleRadians),
lightData.castsShadows ? 1.0f : 0.0f,
0.0f);
} else {
constants.spotAnglesAndFlags = Math::Vector4(
0.0f,
0.0f,
lightData.castsShadows ? 1.0f : 0.0f,
0.0f);
}
return constants;
}
bool BuiltinForwardPipeline::DrawVisibleItem(
const RenderContext& context,
const RenderSceneData& sceneData,
@@ -891,22 +967,7 @@ bool BuiltinForwardPipeline::DrawVisibleItem(
visibleItem.localToWorld.Transpose(),
visibleItem.localToWorld.Inverse()
};
const LightingConstants lightingConstants = {
sceneData.lighting.HasMainDirectionalLight()
? Math::Vector4(
sceneData.lighting.mainDirectionalLight.direction.x,
sceneData.lighting.mainDirectionalLight.direction.y,
sceneData.lighting.mainDirectionalLight.direction.z,
sceneData.lighting.mainDirectionalLight.intensity)
: Math::Vector4::Zero(),
sceneData.lighting.HasMainDirectionalLight()
? Math::Vector4(
sceneData.lighting.mainDirectionalLight.color.r,
sceneData.lighting.mainDirectionalLight.color.g,
sceneData.lighting.mainDirectionalLight.color.b,
1.0f)
: Math::Vector4::Zero()
};
const LightingConstants lightingConstants = BuildLightingConstants(sceneData.lighting);
const ShadowReceiverConstants shadowReceiverConstants = {
sceneData.lighting.HasMainDirectionalShadow()
? sceneData.lighting.mainDirectionalShadow.viewProjection

View File

@@ -6,6 +6,7 @@ add_subdirectory(textured_quad_scene)
add_subdirectory(unlit_scene)
add_subdirectory(object_id_scene)
add_subdirectory(directional_shadow_scene)
add_subdirectory(multi_light_scene)
add_subdirectory(backpack_scene)
add_subdirectory(backpack_lit_scene)
add_subdirectory(camera_stack_scene)

View File

@@ -0,0 +1,63 @@
cmake_minimum_required(VERSION 3.15)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
project(rendering_integration_multi_light_scene)
set(ENGINE_ROOT_DIR ${CMAKE_SOURCE_DIR}/engine)
set(PACKAGE_DIR ${CMAKE_SOURCE_DIR}/mvs/OpenGL/package)
get_filename_component(PROJECT_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../.. ABSOLUTE)
find_package(Vulkan QUIET)
add_executable(rendering_integration_multi_light_scene
main.cpp
${CMAKE_SOURCE_DIR}/tests/RHI/integration/fixtures/RHIIntegrationFixture.cpp
${PACKAGE_DIR}/src/glad.c
)
target_include_directories(rendering_integration_multi_light_scene PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tests/RHI/integration/fixtures
${ENGINE_ROOT_DIR}/include
${PACKAGE_DIR}/include
${PROJECT_ROOT_DIR}/engine/src
)
target_link_libraries(rendering_integration_multi_light_scene PRIVATE
d3d12
dxgi
d3dcompiler
winmm
opengl32
XCEngine
GTest::gtest
)
if(TARGET Vulkan::Vulkan)
target_link_libraries(rendering_integration_multi_light_scene PRIVATE Vulkan::Vulkan)
target_compile_definitions(rendering_integration_multi_light_scene PRIVATE XCENGINE_SUPPORT_VULKAN)
endif()
target_compile_definitions(rendering_integration_multi_light_scene PRIVATE
UNICODE
_UNICODE
XCENGINE_SUPPORT_OPENGL
XCENGINE_SUPPORT_D3D12
)
add_custom_command(TARGET rendering_integration_multi_light_scene POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_SOURCE_DIR}/tests/RHI/integration/compare_ppm.py
$<TARGET_FILE_DIR:rendering_integration_multi_light_scene>/
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/GT.ppm
$<TARGET_FILE_DIR:rendering_integration_multi_light_scene>/GT.ppm
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${ENGINE_ROOT_DIR}/third_party/renderdoc/renderdoc.dll
$<TARGET_FILE_DIR:rendering_integration_multi_light_scene>/
)
include(GoogleTest)
gtest_discover_tests(rendering_integration_multi_light_scene)

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,480 @@
#define NOMINMAX
#include <windows.h>
#include <gtest/gtest.h>
#include "../RenderingIntegrationMain.h"
#include <XCEngine/Components/CameraComponent.h>
#include <XCEngine/Components/GameObject.h>
#include <XCEngine/Components/LightComponent.h>
#include <XCEngine/Components/MeshFilterComponent.h>
#include <XCEngine/Components/MeshRendererComponent.h>
#include <XCEngine/Core/Asset/IResource.h>
#include <XCEngine/Core/Math/Color.h>
#include <XCEngine/Core/Math/Quaternion.h>
#include <XCEngine/Core/Math/Vector2.h>
#include <XCEngine/Core/Math/Vector3.h>
#include <XCEngine/Rendering/RenderContext.h>
#include <XCEngine/Rendering/RenderSurface.h>
#include <XCEngine/Rendering/SceneRenderer.h>
#include <XCEngine/Resources/BuiltinResources.h>
#include <XCEngine/Resources/Material/Material.h>
#include <XCEngine/Resources/Mesh/Mesh.h>
#include <XCEngine/Resources/Shader/Shader.h>
#include <XCEngine/RHI/RHITexture.h>
#include <XCEngine/Scene/Scene.h>
#include "../../../RHI/integration/fixtures/RHIIntegrationFixture.h"
#include <memory>
#include <vector>
using namespace XCEngine::Components;
using namespace XCEngine::Math;
using namespace XCEngine::Rendering;
using namespace XCEngine::Resources;
using namespace XCEngine::RHI;
using namespace XCEngine::RHI::Integration;
namespace {
constexpr const char* kD3D12Screenshot = "multi_light_scene_d3d12.ppm";
constexpr const char* kOpenGLScreenshot = "multi_light_scene_opengl.ppm";
constexpr const char* kVulkanScreenshot = "multi_light_scene_vulkan.ppm";
constexpr uint32_t kFrameWidth = 1280;
constexpr uint32_t kFrameHeight = 720;
void AppendQuadFace(
std::vector<StaticMeshVertex>& vertices,
std::vector<uint32_t>& indices,
const Vector3& v0,
const Vector3& v1,
const Vector3& v2,
const Vector3& v3,
const Vector3& normal) {
const uint32_t baseIndex = static_cast<uint32_t>(vertices.size());
StaticMeshVertex vertex = {};
vertex.normal = normal;
vertex.position = v0;
vertex.uv0 = Vector2(0.0f, 1.0f);
vertices.push_back(vertex);
vertex.position = v1;
vertex.uv0 = Vector2(1.0f, 1.0f);
vertices.push_back(vertex);
vertex.position = v2;
vertex.uv0 = Vector2(0.0f, 0.0f);
vertices.push_back(vertex);
vertex.position = v3;
vertex.uv0 = Vector2(1.0f, 0.0f);
vertices.push_back(vertex);
indices.push_back(baseIndex + 0);
indices.push_back(baseIndex + 2);
indices.push_back(baseIndex + 1);
indices.push_back(baseIndex + 1);
indices.push_back(baseIndex + 2);
indices.push_back(baseIndex + 3);
}
Mesh* CreateCubeMesh() {
auto* mesh = new Mesh();
IResource::ConstructParams params = {};
params.name = "MultiLightCubeMesh";
params.path = "Tests/Rendering/MultiLightCube.mesh";
params.guid = ResourceGUID::Generate(params.path);
mesh->Initialize(params);
std::vector<StaticMeshVertex> vertices;
std::vector<uint32_t> indices;
vertices.reserve(24);
indices.reserve(36);
constexpr float half = 0.5f;
AppendQuadFace(
vertices, indices,
Vector3(-half, -half, half),
Vector3(half, -half, half),
Vector3(-half, half, half),
Vector3(half, half, half),
Vector3::Forward());
AppendQuadFace(
vertices, indices,
Vector3(half, -half, -half),
Vector3(-half, -half, -half),
Vector3(half, half, -half),
Vector3(-half, half, -half),
Vector3::Back());
AppendQuadFace(
vertices, indices,
Vector3(-half, -half, -half),
Vector3(-half, -half, half),
Vector3(-half, half, -half),
Vector3(-half, half, half),
Vector3::Left());
AppendQuadFace(
vertices, indices,
Vector3(half, -half, half),
Vector3(half, -half, -half),
Vector3(half, half, half),
Vector3(half, half, -half),
Vector3::Right());
AppendQuadFace(
vertices, indices,
Vector3(-half, half, half),
Vector3(half, half, half),
Vector3(-half, half, -half),
Vector3(half, half, -half),
Vector3::Up());
AppendQuadFace(
vertices, indices,
Vector3(-half, -half, -half),
Vector3(half, -half, -half),
Vector3(-half, -half, half),
Vector3(half, -half, half),
Vector3::Down());
mesh->SetVertexData(
vertices.data(),
vertices.size() * sizeof(StaticMeshVertex),
static_cast<uint32_t>(vertices.size()),
sizeof(StaticMeshVertex),
VertexAttribute::Position | VertexAttribute::Normal | VertexAttribute::UV0);
mesh->SetIndexData(
indices.data(),
indices.size() * sizeof(uint32_t),
static_cast<uint32_t>(indices.size()),
true);
const Bounds bounds(Vector3::Zero(), Vector3::One());
mesh->SetBounds(bounds);
MeshSection section = {};
section.baseVertex = 0;
section.vertexCount = static_cast<uint32_t>(vertices.size());
section.startIndex = 0;
section.indexCount = static_cast<uint32_t>(indices.size());
section.materialID = 0;
section.bounds = bounds;
mesh->AddSection(section);
return mesh;
}
Material* CreateForwardLitMaterial(
const char* name,
const char* path,
const Vector4& baseColor) {
auto* material = new Material();
IResource::ConstructParams params = {};
params.name = name;
params.path = path;
params.guid = ResourceGUID::Generate(params.path);
material->Initialize(params);
material->SetShader(ResourceManager::Get().Load<Shader>(GetBuiltinForwardLitShaderPath()));
material->SetShaderPass("ForwardLit");
material->SetFloat4("_BaseColor", baseColor);
return material;
}
const char* GetScreenshotFilename(RHIType backendType) {
switch (backendType) {
case RHIType::D3D12:
return kD3D12Screenshot;
case RHIType::Vulkan:
return kVulkanScreenshot;
case RHIType::OpenGL:
default:
return kOpenGLScreenshot;
}
}
int GetComparisonThreshold(RHIType backendType) {
return backendType == RHIType::D3D12 ? 10 : 10;
}
class MultiLightSceneTest : public RHIIntegrationFixture {
protected:
void SetUp() override;
void TearDown() override;
void RenderFrame() override;
private:
void BuildScene();
RHIResourceView* GetCurrentBackBufferView();
std::unique_ptr<Scene> mScene;
std::unique_ptr<SceneRenderer> mSceneRenderer;
std::vector<RHIResourceView*> mBackBufferViews;
RHITexture* mDepthTexture = nullptr;
RHIResourceView* mDepthView = nullptr;
Mesh* mCubeMesh = nullptr;
Material* mGroundMaterial = nullptr;
Material* mLeftMaterial = nullptr;
Material* mCenterMaterial = nullptr;
Material* mRightMaterial = nullptr;
};
void MultiLightSceneTest::SetUp() {
RHIIntegrationFixture::SetUp();
mSceneRenderer = std::make_unique<SceneRenderer>();
mScene = std::make_unique<Scene>("MultiLightScene");
mCubeMesh = CreateCubeMesh();
ASSERT_NE(mCubeMesh, nullptr);
mGroundMaterial = CreateForwardLitMaterial(
"MultiLightGround",
"Tests/Rendering/MultiLightGround.material",
Vector4(0.84f, 0.84f, 0.86f, 1.0f));
mLeftMaterial = CreateForwardLitMaterial(
"MultiLightLeftCube",
"Tests/Rendering/MultiLightLeftCube.material",
Vector4(0.95f, 0.92f, 0.90f, 1.0f));
mCenterMaterial = CreateForwardLitMaterial(
"MultiLightCenterCube",
"Tests/Rendering/MultiLightCenterCube.material",
Vector4(0.92f, 0.92f, 0.95f, 1.0f));
mRightMaterial = CreateForwardLitMaterial(
"MultiLightRightCube",
"Tests/Rendering/MultiLightRightCube.material",
Vector4(0.93f, 0.95f, 0.96f, 1.0f));
BuildScene();
TextureDesc depthDesc = {};
depthDesc.width = kFrameWidth;
depthDesc.height = kFrameHeight;
depthDesc.depth = 1;
depthDesc.mipLevels = 1;
depthDesc.arraySize = 1;
depthDesc.format = static_cast<uint32_t>(Format::D24_UNorm_S8_UInt);
depthDesc.textureType = static_cast<uint32_t>(XCEngine::RHI::TextureType::Texture2D);
depthDesc.sampleCount = 1;
depthDesc.sampleQuality = 0;
depthDesc.flags = 0;
mDepthTexture = GetDevice()->CreateTexture(depthDesc);
ASSERT_NE(mDepthTexture, nullptr);
ResourceViewDesc depthViewDesc = {};
depthViewDesc.format = static_cast<uint32_t>(Format::D24_UNorm_S8_UInt);
depthViewDesc.dimension = ResourceViewDimension::Texture2D;
depthViewDesc.mipLevel = 0;
mDepthView = GetDevice()->CreateDepthStencilView(mDepthTexture, depthViewDesc);
ASSERT_NE(mDepthView, nullptr);
mBackBufferViews.resize(2, nullptr);
}
void MultiLightSceneTest::TearDown() {
mSceneRenderer.reset();
if (mDepthView != nullptr) {
mDepthView->Shutdown();
delete mDepthView;
mDepthView = nullptr;
}
if (mDepthTexture != nullptr) {
mDepthTexture->Shutdown();
delete mDepthTexture;
mDepthTexture = nullptr;
}
for (RHIResourceView*& backBufferView : mBackBufferViews) {
if (backBufferView != nullptr) {
backBufferView->Shutdown();
delete backBufferView;
backBufferView = nullptr;
}
}
mBackBufferViews.clear();
mScene.reset();
delete mGroundMaterial;
mGroundMaterial = nullptr;
delete mLeftMaterial;
mLeftMaterial = nullptr;
delete mCenterMaterial;
mCenterMaterial = nullptr;
delete mRightMaterial;
mRightMaterial = nullptr;
delete mCubeMesh;
mCubeMesh = nullptr;
RHIIntegrationFixture::TearDown();
}
void MultiLightSceneTest::BuildScene() {
ASSERT_NE(mScene, nullptr);
ASSERT_NE(mCubeMesh, nullptr);
GameObject* cameraObject = mScene->CreateGameObject("MainCamera");
auto* camera = cameraObject->AddComponent<CameraComponent>();
camera->SetPrimary(true);
camera->SetFieldOfView(40.0f);
camera->SetNearClipPlane(0.1f);
camera->SetFarClipPlane(50.0f);
camera->SetClearColor(XCEngine::Math::Color(0.025f, 0.025f, 0.035f, 1.0f));
cameraObject->GetTransform()->SetLocalPosition(Vector3(0.0f, 3.4f, -7.6f));
cameraObject->GetTransform()->SetLocalRotation(
Quaternion::LookRotation(Vector3(0.0f, -0.16f, 1.0f).Normalized()));
GameObject* mainDirectionalObject = mScene->CreateGameObject("MainDirectionalLight");
auto* mainDirectional = mainDirectionalObject->AddComponent<LightComponent>();
mainDirectional->SetLightType(LightType::Directional);
mainDirectional->SetColor(XCEngine::Math::Color(1.0f, 0.97f, 0.93f, 1.0f));
mainDirectional->SetIntensity(1.25f);
mainDirectionalObject->GetTransform()->SetLocalRotation(
Quaternion::LookRotation(Vector3(0.35f, -0.88f, -0.31f).Normalized()));
GameObject* fillDirectionalObject = mScene->CreateGameObject("FillDirectionalLight");
auto* fillDirectional = fillDirectionalObject->AddComponent<LightComponent>();
fillDirectional->SetLightType(LightType::Directional);
fillDirectional->SetColor(XCEngine::Math::Color(0.22f, 0.55f, 1.0f, 1.0f));
fillDirectional->SetIntensity(0.42f);
fillDirectionalObject->GetTransform()->SetLocalRotation(
Quaternion::LookRotation(Vector3(-0.72f, -0.34f, 0.61f).Normalized()));
GameObject* pointLightObject = mScene->CreateGameObject("PointLight");
auto* pointLight = pointLightObject->AddComponent<LightComponent>();
pointLight->SetLightType(LightType::Point);
pointLight->SetColor(XCEngine::Math::Color(1.0f, 0.30f, 0.18f, 1.0f));
pointLight->SetIntensity(6.0f);
pointLight->SetRange(6.8f);
pointLightObject->GetTransform()->SetLocalPosition(Vector3(-3.0f, 2.8f, 8.0f));
GameObject* spotLightObject = mScene->CreateGameObject("SpotLight");
auto* spotLight = spotLightObject->AddComponent<LightComponent>();
spotLight->SetLightType(LightType::Spot);
spotLight->SetColor(XCEngine::Math::Color(0.18f, 1.0f, 0.62f, 1.0f));
spotLight->SetIntensity(7.0f);
spotLight->SetRange(11.0f);
spotLight->SetSpotAngle(38.0f);
spotLightObject->GetTransform()->SetLocalPosition(Vector3(3.3f, 4.2f, 11.8f));
spotLightObject->GetTransform()->SetLocalRotation(
Quaternion::LookRotation(Vector3(-0.18f, -0.84f, -0.52f).Normalized()));
GameObject* groundObject = mScene->CreateGameObject("Ground");
auto* groundMeshFilter = groundObject->AddComponent<MeshFilterComponent>();
auto* groundMeshRenderer = groundObject->AddComponent<MeshRendererComponent>();
groundObject->GetTransform()->SetLocalPosition(Vector3(0.0f, -0.16f, 10.4f));
groundObject->GetTransform()->SetLocalScale(Vector3(12.0f, 0.18f, 10.0f));
groundMeshFilter->SetMesh(ResourceHandle<Mesh>(mCubeMesh));
groundMeshRenderer->SetMaterial(0, mGroundMaterial);
GameObject* leftCubeObject = mScene->CreateGameObject("LeftCube");
auto* leftMeshFilter = leftCubeObject->AddComponent<MeshFilterComponent>();
auto* leftMeshRenderer = leftCubeObject->AddComponent<MeshRendererComponent>();
leftCubeObject->GetTransform()->SetLocalPosition(Vector3(-2.8f, 0.80f, 8.3f));
leftCubeObject->GetTransform()->SetLocalScale(Vector3(1.45f, 1.60f, 1.45f));
leftMeshFilter->SetMesh(ResourceHandle<Mesh>(mCubeMesh));
leftMeshRenderer->SetMaterial(0, mLeftMaterial);
GameObject* centerCubeObject = mScene->CreateGameObject("CenterCube");
auto* centerMeshFilter = centerCubeObject->AddComponent<MeshFilterComponent>();
auto* centerMeshRenderer = centerCubeObject->AddComponent<MeshRendererComponent>();
centerCubeObject->GetTransform()->SetLocalPosition(Vector3(0.0f, 1.0f, 10.4f));
centerCubeObject->GetTransform()->SetLocalScale(Vector3(1.90f, 2.0f, 1.90f));
centerMeshFilter->SetMesh(ResourceHandle<Mesh>(mCubeMesh));
centerMeshRenderer->SetMaterial(0, mCenterMaterial);
GameObject* rightCubeObject = mScene->CreateGameObject("RightCube");
auto* rightMeshFilter = rightCubeObject->AddComponent<MeshFilterComponent>();
auto* rightMeshRenderer = rightCubeObject->AddComponent<MeshRendererComponent>();
rightCubeObject->GetTransform()->SetLocalPosition(Vector3(2.9f, 0.66f, 12.0f));
rightCubeObject->GetTransform()->SetLocalScale(Vector3(1.25f, 1.32f, 1.25f));
rightMeshFilter->SetMesh(ResourceHandle<Mesh>(mCubeMesh));
rightMeshRenderer->SetMaterial(0, mRightMaterial);
}
RHIResourceView* MultiLightSceneTest::GetCurrentBackBufferView() {
const int backBufferIndex = GetCurrentBackBufferIndex();
if (backBufferIndex < 0) {
return nullptr;
}
if (static_cast<size_t>(backBufferIndex) >= mBackBufferViews.size()) {
mBackBufferViews.resize(static_cast<size_t>(backBufferIndex) + 1, nullptr);
}
if (mBackBufferViews[backBufferIndex] == nullptr) {
ResourceViewDesc viewDesc = {};
viewDesc.format = static_cast<uint32_t>(Format::R8G8B8A8_UNorm);
viewDesc.dimension = ResourceViewDimension::Texture2D;
viewDesc.mipLevel = 0;
mBackBufferViews[backBufferIndex] = GetDevice()->CreateRenderTargetView(GetCurrentBackBuffer(), viewDesc);
}
return mBackBufferViews[backBufferIndex];
}
void MultiLightSceneTest::RenderFrame() {
ASSERT_NE(mScene, nullptr);
ASSERT_NE(mSceneRenderer, nullptr);
RHICommandList* commandList = GetCommandList();
ASSERT_NE(commandList, nullptr);
commandList->Reset();
RenderSurface surface(kFrameWidth, kFrameHeight);
surface.SetColorAttachment(GetCurrentBackBufferView());
surface.SetDepthAttachment(mDepthView);
RenderContext renderContext = {};
renderContext.device = GetDevice();
renderContext.commandList = commandList;
renderContext.commandQueue = GetCommandQueue();
renderContext.backendType = GetBackendType();
ASSERT_TRUE(mSceneRenderer->Render(*mScene, nullptr, renderContext, surface));
commandList->Close();
void* commandLists[] = { commandList };
GetCommandQueue()->ExecuteCommandLists(1, commandLists);
}
TEST_P(MultiLightSceneTest, RenderMultiLightScene) {
RHICommandQueue* commandQueue = 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) {
commandQueue->WaitForPreviousFrame();
}
BeginRender();
RenderFrame();
if (frameCount >= targetFrameCount) {
commandQueue->WaitForIdle();
ASSERT_TRUE(TakeScreenshot(screenshotFilename));
ASSERT_TRUE(CompareWithGoldenTemplate(screenshotFilename, "GT.ppm", static_cast<float>(comparisonThreshold)));
break;
}
swapChain->Present(0, 0);
}
}
} // namespace
INSTANTIATE_TEST_SUITE_P(D3D12, MultiLightSceneTest, ::testing::Values(RHIType::D3D12));
INSTANTIATE_TEST_SUITE_P(OpenGL, MultiLightSceneTest, ::testing::Values(RHIType::OpenGL));
#if defined(XCENGINE_SUPPORT_VULKAN)
INSTANTIATE_TEST_SUITE_P(Vulkan, MultiLightSceneTest, ::testing::Values(RHIType::Vulkan));
#endif
GTEST_API_ int main(int argc, char** argv) {
return RunRenderingIntegrationTestMain(argc, argv);
}

View File

@@ -747,12 +747,22 @@ TEST(ShaderLoader, LoadBuiltinForwardLitShaderBuildsBackendVariants) {
ASSERT_NE(d3d12Vertex, nullptr);
EXPECT_NE(std::string(d3d12Vertex->sourceCode.CStr()).find("XC_BUILTIN_FORWARD_LIT_D3D12_VS"), std::string::npos);
const ShaderStageVariant* d3d12Fragment = shader->FindVariant(
"ForwardLit",
ShaderType::Fragment,
ShaderBackend::D3D12);
ASSERT_NE(d3d12Fragment, nullptr);
EXPECT_NE(std::string(d3d12Fragment->sourceCode.CStr()).find("gAdditionalLights"), std::string::npos);
EXPECT_NE(std::string(d3d12Fragment->sourceCode.CStr()).find("gLightingParams"), std::string::npos);
const ShaderStageVariant* openglFragment = shader->FindVariant(
"ForwardLit",
ShaderType::Fragment,
ShaderBackend::OpenGL);
ASSERT_NE(openglFragment, nullptr);
EXPECT_NE(std::string(openglFragment->sourceCode.CStr()).find("XC_BUILTIN_FORWARD_LIT_OPENGL_PS"), std::string::npos);
EXPECT_NE(std::string(openglFragment->sourceCode.CStr()).find("gAdditionalLights"), std::string::npos);
EXPECT_NE(std::string(openglFragment->sourceCode.CStr()).find("gLightingParams"), std::string::npos);
const ShaderStageVariant* vulkanFragment = shader->FindVariant(
"ForwardLit",
@@ -760,6 +770,8 @@ TEST(ShaderLoader, LoadBuiltinForwardLitShaderBuildsBackendVariants) {
ShaderBackend::Vulkan);
ASSERT_NE(vulkanFragment, nullptr);
EXPECT_NE(std::string(vulkanFragment->sourceCode.CStr()).find("XC_BUILTIN_FORWARD_LIT_VULKAN_PS"), std::string::npos);
EXPECT_NE(std::string(vulkanFragment->sourceCode.CStr()).find("gAdditionalLights"), std::string::npos);
EXPECT_NE(std::string(vulkanFragment->sourceCode.CStr()).find("gLightingParams"), std::string::npos);
delete shader;
}