Add procedural skybox scene coverage

This commit is contained in:
2026-04-05 23:44:32 +08:00
parent be2013f3c4
commit 8151be0f45
27 changed files with 1092 additions and 5 deletions

View File

@@ -0,0 +1,35 @@
// XC_BUILTIN_SKYBOX_OPENGL_PS
#version 430
layout(std140, binding = 0) uniform EnvironmentConstants {
vec4 gSkyboxTopColor;
vec4 gSkyboxHorizonColor;
vec4 gSkyboxBottomColor;
vec4 gCameraRightAndTanHalfFov;
vec4 gCameraUpAndAspect;
vec4 gCameraForwardAndUnused;
};
in vec2 vNdc;
layout(location = 0) out vec4 fragColor;
void main() {
float tanHalfFov = gCameraRightAndTanHalfFov.w;
float aspect = gCameraUpAndAspect.w;
vec3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
vNdc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
vNdc.y * tanHalfFov * gCameraUpAndAspect.xyz);
float vertical = clamp(viewRay.y, -1.0, 1.0);
vec3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0) {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(clamp(vertical, 0.0, 1.0), 0.65));
} else {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(clamp(-vertical, 0.0, 1.0), 0.55));
}
fragColor = vec4(color, 1.0);
}

View File

@@ -0,0 +1,35 @@
// XC_BUILTIN_SKYBOX_VULKAN_PS
#version 450
layout(set = 0, binding = 0, std140) uniform EnvironmentConstants {
vec4 gSkyboxTopColor;
vec4 gSkyboxHorizonColor;
vec4 gSkyboxBottomColor;
vec4 gCameraRightAndTanHalfFov;
vec4 gCameraUpAndAspect;
vec4 gCameraForwardAndUnused;
};
layout(location = 0) in vec2 vNdc;
layout(location = 0) out vec4 fragColor;
void main() {
float tanHalfFov = gCameraRightAndTanHalfFov.w;
float aspect = gCameraUpAndAspect.w;
vec3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
vNdc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
vNdc.y * tanHalfFov * gCameraUpAndAspect.xyz);
float vertical = clamp(viewRay.y, -1.0, 1.0);
vec3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0) {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(clamp(vertical, 0.0, 1.0), 0.65));
} else {
color = mix(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(clamp(-vertical, 0.0, 1.0), 0.55));
}
fragColor = vec4(color, 1.0);
}

View File

@@ -0,0 +1,34 @@
// XC_BUILTIN_SKYBOX_D3D12_PS
cbuffer EnvironmentConstants : register(b0) {
float4 gSkyboxTopColor;
float4 gSkyboxHorizonColor;
float4 gSkyboxBottomColor;
float4 gCameraRightAndTanHalfFov;
float4 gCameraUpAndAspect;
float4 gCameraForwardAndUnused;
}
struct PSInput {
float4 position : SV_POSITION;
float2 ndc : TEXCOORD0;
};
float4 MainPS(PSInput input) : SV_Target {
const float tanHalfFov = gCameraRightAndTanHalfFov.w;
const float aspect = gCameraUpAndAspect.w;
float3 viewRay = normalize(
gCameraForwardAndUnused.xyz +
input.ndc.x * aspect * tanHalfFov * gCameraRightAndTanHalfFov.xyz +
input.ndc.y * tanHalfFov * gCameraUpAndAspect.xyz);
const float vertical = clamp(viewRay.y, -1.0f, 1.0f);
float3 color = gSkyboxHorizonColor.rgb;
if (vertical >= 0.0f) {
color = lerp(gSkyboxHorizonColor.rgb, gSkyboxTopColor.rgb, pow(saturate(vertical), 0.65f));
} else {
color = lerp(gSkyboxHorizonColor.rgb, gSkyboxBottomColor.rgb, pow(saturate(-vertical), 0.55f));
}
return float4(color, 1.0f);
}

View File

@@ -0,0 +1,22 @@
Shader "Builtin Skybox"
{
SubShader
{
Pass
{
Name "Skybox"
Tags { "LightMode" = "Skybox" }
Resources
{
EnvironmentConstants (ConstantBuffer, 0, 0) [Semantic(Environment)]
}
HLSLPROGRAM
#pragma vertex MainVS
#pragma fragment MainPS
#pragma backend D3D12 HLSL "skybox.vs.hlsl" "skybox.ps.hlsl" vs_5_0 ps_5_0
#pragma backend OpenGL GLSL "skybox.vert.glsl" "skybox.frag.glsl"
#pragma backend Vulkan GLSL "skybox.vert.vk.glsl" "skybox.frag.vk.glsl"
ENDHLSL
}
}
}

View File

@@ -0,0 +1,16 @@
// XC_BUILTIN_SKYBOX_OPENGL_VS
#version 430
out vec2 vNdc;
void main() {
const vec2 positions[3] = vec2[3](
vec2(-1.0, -1.0),
vec2(-1.0, 3.0),
vec2( 3.0, -1.0)
);
vec2 position = positions[gl_VertexID];
gl_Position = vec4(position, 1.0, 1.0);
vNdc = position;
}

View File

@@ -0,0 +1,16 @@
// XC_BUILTIN_SKYBOX_VULKAN_VS
#version 450
layout(location = 0) out vec2 vNdc;
void main() {
const vec2 positions[3] = vec2[3](
vec2(-1.0, -1.0),
vec2(-1.0, 3.0),
vec2( 3.0, -1.0)
);
vec2 position = positions[gl_VertexIndex];
gl_Position = vec4(position, 1.0, 1.0);
vNdc = position;
}

View File

@@ -0,0 +1,18 @@
// XC_BUILTIN_SKYBOX_D3D12_VS
struct VSOutput {
float4 position : SV_POSITION;
float2 ndc : TEXCOORD0;
};
VSOutput MainVS(uint vertexId : SV_VertexID) {
const float2 positions[3] = {
float2(-1.0f, -1.0f),
float2(-1.0f, 3.0f),
float2( 3.0f, -1.0f)
};
VSOutput output;
output.position = float4(positions[vertexId], 1.0f, 1.0f);
output.ndc = positions[vertexId];
return output;
}

View File

@@ -64,6 +64,18 @@ public:
const Math::Color& GetClearColor() const { return m_clearColor; }
void SetClearColor(const Math::Color& value) { m_clearColor = value; }
bool IsSkyboxEnabled() const { return m_skyboxEnabled; }
void SetSkyboxEnabled(bool value) { m_skyboxEnabled = value; }
const Math::Color& GetSkyboxTopColor() const { return m_skyboxTopColor; }
void SetSkyboxTopColor(const Math::Color& value) { m_skyboxTopColor = value; }
const Math::Color& GetSkyboxHorizonColor() const { return m_skyboxHorizonColor; }
void SetSkyboxHorizonColor(const Math::Color& value) { m_skyboxHorizonColor = value; }
const Math::Color& GetSkyboxBottomColor() const { return m_skyboxBottomColor; }
void SetSkyboxBottomColor(const Math::Color& value) { m_skyboxBottomColor = value; }
void Serialize(std::ostream& os) const override;
void Deserialize(std::istream& is) override;
@@ -80,6 +92,10 @@ private:
uint32_t m_cullingMask = 0xFFFFFFFFu;
Math::Rect m_viewportRect = Math::Rect(0.0f, 0.0f, 1.0f, 1.0f);
Math::Color m_clearColor = Math::Color(0.192f, 0.302f, 0.475f, 1.0f);
bool m_skyboxEnabled = false;
Math::Color m_skyboxTopColor = Math::Color(0.18f, 0.36f, 0.74f, 1.0f);
Math::Color m_skyboxHorizonColor = Math::Color(0.78f, 0.84f, 0.92f, 1.0f);
Math::Color m_skyboxBottomColor = Math::Color(0.92f, 0.93f, 0.95f, 1.0f);
};
} // namespace Components

View File

@@ -35,8 +35,17 @@ struct RenderCameraData {
Math::Matrix4x4 projection = Math::Matrix4x4::Identity();
Math::Matrix4x4 viewProjection = Math::Matrix4x4::Identity();
Math::Vector3 worldPosition = Math::Vector3::Zero();
Math::Vector3 worldRight = Math::Vector3::Right();
Math::Vector3 worldUp = Math::Vector3::Up();
Math::Vector3 worldForward = Math::Vector3::Forward();
Math::Color clearColor = Math::Color::Black();
RenderClearFlags clearFlags = RenderClearFlags::All;
bool perspectiveProjection = true;
float verticalFovRadians = 60.0f * Math::DEG_TO_RAD;
float orthographicSize = 5.0f;
float aspectRatio = 1.0f;
float nearClipPlane = 0.1f;
float farClipPlane = 1000.0f;
uint32_t viewportWidth = 0;
uint32_t viewportHeight = 0;
};

View File

@@ -0,0 +1,31 @@
#pragma once
#include <XCEngine/Core/Math/Color.h>
#include <cstdint>
namespace XCEngine {
namespace Rendering {
enum class RenderEnvironmentMode : uint32_t {
None = 0,
ProceduralSkybox
};
struct ProceduralSkyboxData {
Math::Color topColor = Math::Color(0.18f, 0.36f, 0.74f, 1.0f);
Math::Color horizonColor = Math::Color(0.78f, 0.84f, 0.92f, 1.0f);
Math::Color bottomColor = Math::Color(0.92f, 0.93f, 0.95f, 1.0f);
};
struct RenderEnvironmentData {
RenderEnvironmentMode mode = RenderEnvironmentMode::None;
ProceduralSkyboxData skybox = {};
bool HasProceduralSkybox() const {
return mode == RenderEnvironmentMode::ProceduralSkybox;
}
};
} // namespace Rendering
} // namespace XCEngine

View File

@@ -3,6 +3,7 @@
#include <XCEngine/Core/Math/Vector3.h>
#include <XCEngine/Core/Math/Vector4.h>
#include <XCEngine/Rendering/FrameData/RenderCameraData.h>
#include <XCEngine/Rendering/FrameData/RenderEnvironmentData.h>
#include <XCEngine/Rendering/FrameData/VisibleRenderItem.h>
#include <array>
@@ -81,6 +82,7 @@ struct RenderLightingData {
struct RenderSceneData {
Components::CameraComponent* camera = nullptr;
RenderCameraData cameraData;
RenderEnvironmentData environment;
RenderLightingData lighting;
std::vector<VisibleRenderItem> visibleItems;

View File

@@ -38,6 +38,7 @@ class RenderSurface;
namespace Pipelines {
namespace Detail {
class BuiltinForwardOpaquePass;
class BuiltinForwardSkyboxPass;
class BuiltinForwardTransparentPass;
} // namespace Detail
@@ -57,6 +58,7 @@ public:
private:
friend class Detail::BuiltinForwardOpaquePass;
friend class Detail::BuiltinForwardSkyboxPass;
friend class Detail::BuiltinForwardTransparentPass;
struct OwnedDescriptorSet {
@@ -98,6 +100,15 @@ private:
Math::Vector4 baseColorFactor = Math::Vector4::One();
};
struct SkyboxConstants {
Math::Vector4 topColor = Math::Vector4::Zero();
Math::Vector4 horizonColor = Math::Vector4::Zero();
Math::Vector4 bottomColor = Math::Vector4::Zero();
Math::Vector4 cameraRightAndTanHalfFov = Math::Vector4::Zero();
Math::Vector4 cameraUpAndAspect = Math::Vector4::Zero();
Math::Vector4 cameraForwardAndUnused = Math::Vector4::Zero();
};
struct PassLayoutKey {
const Resources::Shader* shader = nullptr;
Containers::String passName;
@@ -235,9 +246,11 @@ private:
RHI::RHIResourceView* ResolveTextureView(const VisibleRenderItem& visibleItem);
static LightingConstants BuildLightingConstants(const RenderLightingData& lightingData);
static AdditionalLightConstants BuildAdditionalLightConstants(const RenderAdditionalLightData& lightData);
bool HasProceduralSkybox(const RenderSceneData& sceneData) const;
bool BeginForwardScenePass(const RenderPassContext& context);
void EndForwardScenePass(const RenderPassContext& context);
bool ExecuteForwardOpaquePass(const RenderPassContext& context);
bool ExecuteForwardSkyboxPass(const RenderPassContext& context);
bool ExecuteForwardTransparentPass(const RenderPassContext& context);
bool DrawVisibleItems(
const RenderContext& context,
@@ -247,12 +260,16 @@ private:
const RenderContext& context,
const RenderSceneData& sceneData,
const VisibleRenderItem& visibleItem);
bool EnsureSkyboxResources(const RenderContext& context);
bool CreateSkyboxResources(const RenderContext& context);
void DestroySkyboxResources();
RHI::RHIDevice* m_device = nullptr;
RHI::RHIType m_backendType = RHI::RHIType::D3D12;
bool m_initialized = false;
Resources::ResourceHandle<Resources::Shader> m_builtinForwardShader;
Resources::ResourceHandle<Resources::Shader> m_builtinUnlitShader;
Resources::ResourceHandle<Resources::Shader> m_builtinSkyboxShader;
RenderResourceCache m_resourceCache;
@@ -263,6 +280,10 @@ private:
RHI::RHISampler* m_shadowSampler = nullptr;
RHI::RHITexture* m_fallbackTexture = nullptr;
RHI::RHIResourceView* m_fallbackTextureView = nullptr;
RHI::RHIPipelineLayout* m_skyboxPipelineLayout = nullptr;
RHI::RHIPipelineState* m_skyboxPipelineState = nullptr;
RHI::RHIDescriptorPool* m_skyboxConstantPool = nullptr;
RHI::RHIDescriptorSet* m_skyboxConstantSet = nullptr;
RenderPassSequence m_passSequence;
};

View File

@@ -28,6 +28,7 @@ Containers::String GetBuiltinUnlitShaderPath();
Containers::String GetBuiltinDepthOnlyShaderPath();
Containers::String GetBuiltinShadowCasterShaderPath();
Containers::String GetBuiltinObjectIdShaderPath();
Containers::String GetBuiltinSkyboxShaderPath();
Containers::String GetBuiltinDefaultPrimitiveTexturePath();
bool TryParseBuiltinPrimitiveType(const Containers::String& path, BuiltinPrimitiveType& outPrimitiveType);

View File

@@ -48,6 +48,10 @@ void CameraComponent::Serialize(std::ostream& os) const {
os << "cullingMask=" << m_cullingMask << ";";
os << "viewportRect=" << m_viewportRect.x << "," << m_viewportRect.y << "," << m_viewportRect.width << "," << m_viewportRect.height << ";";
os << "clearColor=" << m_clearColor.r << "," << m_clearColor.g << "," << m_clearColor.b << "," << m_clearColor.a << ";";
os << "skyboxEnabled=" << (m_skyboxEnabled ? 1 : 0) << ";";
os << "skyboxTopColor=" << m_skyboxTopColor.r << "," << m_skyboxTopColor.g << "," << m_skyboxTopColor.b << "," << m_skyboxTopColor.a << ";";
os << "skyboxHorizonColor=" << m_skyboxHorizonColor.r << "," << m_skyboxHorizonColor.g << "," << m_skyboxHorizonColor.b << "," << m_skyboxHorizonColor.a << ";";
os << "skyboxBottomColor=" << m_skyboxBottomColor.r << "," << m_skyboxBottomColor.g << "," << m_skyboxBottomColor.b << "," << m_skyboxBottomColor.a << ";";
}
void CameraComponent::Deserialize(std::istream& is) {
@@ -95,6 +99,20 @@ void CameraComponent::Deserialize(std::istream& is) {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_clearColor.r >> m_clearColor.g >> m_clearColor.b >> m_clearColor.a;
} else if (key == "skyboxEnabled") {
m_skyboxEnabled = (std::stoi(value) != 0);
} else if (key == "skyboxTopColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxTopColor.r >> m_skyboxTopColor.g >> m_skyboxTopColor.b >> m_skyboxTopColor.a;
} else if (key == "skyboxHorizonColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxHorizonColor.r >> m_skyboxHorizonColor.g >> m_skyboxHorizonColor.b >> m_skyboxHorizonColor.a;
} else if (key == "skyboxBottomColor") {
std::replace(value.begin(), value.end(), ',', ' ');
std::istringstream ss(value);
ss >> m_skyboxBottomColor.r >> m_skyboxBottomColor.g >> m_skyboxBottomColor.b >> m_skyboxBottomColor.a;
}
}
}

View File

@@ -4,9 +4,11 @@
#include "XCEngine/RHI/Vulkan/VulkanPipelineLayout.h"
#include "XCEngine/RHI/Vulkan/VulkanShader.h"
#include "XCEngine/RHI/Vulkan/VulkanShaderCompiler.h"
#include "XCEngine/Debug/Logger.h"
#include <algorithm>
#include <map>
#include <sstream>
#include <vector>
namespace XCEngine {
@@ -110,10 +112,21 @@ bool VulkanPipelineState::EnsurePipelineLayout(const GraphicsPipelineDesc& desc)
bool VulkanPipelineState::CreateGraphicsPipeline(const GraphicsPipelineDesc& desc) {
VulkanCompiledShader vertexShader = {};
VulkanCompiledShader fragmentShader = {};
if (!CompileVulkanShader(desc.vertexShader, vertexShader, nullptr) ||
!CompileVulkanShader(desc.fragmentShader, fragmentShader, nullptr) ||
std::string vertexError;
std::string fragmentError;
if (!CompileVulkanShader(desc.vertexShader, vertexShader, &vertexError) ||
!CompileVulkanShader(desc.fragmentShader, fragmentShader, &fragmentError) ||
vertexShader.type != ShaderType::Vertex ||
fragmentShader.type != ShaderType::Fragment) {
std::ostringstream message;
message << "VulkanPipelineState failed to compile graphics shaders.";
if (!vertexError.empty()) {
message << " Vertex: " << vertexError;
}
if (!fragmentError.empty()) {
message << " Fragment: " << fragmentError;
}
Debug::Logger::Get().Error(Debug::LogCategory::Rendering, message.str().c_str());
return false;
}
@@ -316,18 +329,23 @@ bool VulkanPipelineState::CreateGraphicsPipeline(const GraphicsPipelineDesc& des
pipelineInfo.renderPass = m_renderPass;
pipelineInfo.subpass = 0;
const bool success = vkCreateGraphicsPipelines(
const VkResult pipelineCreateResult = vkCreateGraphicsPipelines(
m_device,
VK_NULL_HANDLE,
1,
&pipelineInfo,
nullptr,
&m_pipeline) == VK_SUCCESS;
&m_pipeline);
const bool success = pipelineCreateResult == VK_SUCCESS;
vkDestroyShaderModule(m_device, fragmentModule, nullptr);
vkDestroyShaderModule(m_device, vertexModule, nullptr);
if (!success) {
std::ostringstream message;
message << "VulkanPipelineState vkCreateGraphicsPipelines failed with VkResult="
<< static_cast<int>(pipelineCreateResult);
Debug::Logger::Get().Error(Debug::LogCategory::Rendering, message.str().c_str());
return false;
}

View File

@@ -1,5 +1,6 @@
#include "Rendering/Execution/CameraRenderer.h"
#include "Components/CameraComponent.h"
#include "Rendering/Caches/DirectionalShadowSurfaceCache.h"
#include "Rendering/Passes/BuiltinDepthOnlyPass.h"
#include "Rendering/Passes/BuiltinObjectIdPass.h"
@@ -241,6 +242,23 @@ RenderDirectionalShadowData BuildDirectionalShadowData(
return shadowData;
}
RenderEnvironmentData BuildEnvironmentData(const CameraRenderRequest& request) {
RenderEnvironmentData environment = {};
if (request.camera == nullptr ||
request.surface.GetDepthAttachment() == nullptr ||
!HasRenderClearFlag(request.clearFlags, RenderClearFlags::Color) ||
!request.camera->IsSkyboxEnabled() ||
request.camera->GetProjectionType() != Components::CameraProjectionType::Perspective) {
return environment;
}
environment.mode = RenderEnvironmentMode::ProceduralSkybox;
environment.skybox.topColor = request.camera->GetSkyboxTopColor();
environment.skybox.horizonColor = request.camera->GetSkyboxHorizonColor();
environment.skybox.bottomColor = request.camera->GetSkyboxBottomColor();
return environment;
}
} // namespace
CameraRenderer::CameraRenderer()
@@ -407,6 +425,7 @@ bool CameraRenderer::BuildSceneDataForRequest(
}
outSceneData.cameraData.clearFlags = request.clearFlags;
outSceneData.environment = BuildEnvironmentData(request);
if (request.hasClearColorOverride) {
outSceneData.cameraData.clearColor = request.clearColorOverride;
}

View File

@@ -22,12 +22,22 @@ RenderCameraData BuildRenderCameraData(
cameraData.viewportWidth = viewportWidth;
cameraData.viewportHeight = viewportHeight;
cameraData.worldPosition = camera.transform().GetPosition();
cameraData.worldRight = camera.transform().GetRight();
cameraData.worldUp = camera.transform().GetUp();
cameraData.worldForward = camera.transform().GetForward();
cameraData.clearColor = camera.GetClearColor();
cameraData.perspectiveProjection =
camera.GetProjectionType() == Components::CameraProjectionType::Perspective;
cameraData.verticalFovRadians = camera.GetFieldOfView() * Math::DEG_TO_RAD;
cameraData.orthographicSize = camera.GetOrthographicSize();
cameraData.nearClipPlane = camera.GetNearClipPlane();
cameraData.farClipPlane = camera.GetFarClipPlane();
const Math::Matrix4x4 view = camera.transform().GetWorldToLocalMatrix();
const float aspect = viewportHeight > 0
? static_cast<float>(viewportWidth) / static_cast<float>(viewportHeight)
: 1.0f;
cameraData.aspectRatio = aspect;
Math::Matrix4x4 projection = Math::Matrix4x4::Identity();
if (camera.GetProjectionType() == Components::CameraProjectionType::Perspective) {

View File

@@ -3,11 +3,13 @@
#include "Debug/Logger.h"
#include "Core/Asset/ResourceManager.h"
#include "RHI/RHICommandList.h"
#include "Rendering/Detail/ShaderVariantUtils.h"
#include "Rendering/Materials/RenderMaterialResolve.h"
#include "Rendering/RenderSurface.h"
#include "Resources/BuiltinResources.h"
#include <cstddef>
#include <cmath>
namespace XCEngine {
namespace Rendering {
@@ -40,6 +42,32 @@ private:
BuiltinForwardPipeline& m_pipeline;
};
class BuiltinForwardSkyboxPass final : public RenderPass {
public:
explicit BuiltinForwardSkyboxPass(BuiltinForwardPipeline& pipeline)
: m_pipeline(pipeline) {
}
const char* GetName() const override {
return "BuiltinForwardSkyboxPass";
}
bool Initialize(const RenderContext& context) override {
return m_pipeline.EnsureInitialized(context);
}
void Shutdown() override {
m_pipeline.DestroyPipelineResources();
}
bool Execute(const RenderPassContext& context) override {
return m_pipeline.ExecuteForwardSkyboxPass(context);
}
private:
BuiltinForwardPipeline& m_pipeline;
};
class BuiltinForwardTransparentPass final : public RenderPass {
public:
explicit BuiltinForwardTransparentPass(BuiltinForwardPipeline& pipeline)
@@ -75,10 +103,66 @@ bool IsDepthFormat(RHI::Format format) {
format == RHI::Format::D32_Float;
}
const Resources::ShaderPass* FindCompatibleSkyboxPass(
const Resources::Shader& shader,
Resources::ShaderBackend backend) {
const Resources::ShaderPass* skyboxPass = shader.FindPass("Skybox");
if (skyboxPass != nullptr &&
::XCEngine::Rendering::Detail::ShaderPassHasGraphicsVariants(shader, skyboxPass->name, backend)) {
return skyboxPass;
}
if (shader.GetPassCount() > 0 &&
::XCEngine::Rendering::Detail::ShaderPassHasGraphicsVariants(shader, shader.GetPasses()[0].name, backend)) {
return &shader.GetPasses()[0];
}
return nullptr;
}
RHI::GraphicsPipelineDesc CreateSkyboxPipelineDesc(
RHI::RHIType backendType,
RHI::RHIPipelineLayout* pipelineLayout,
const Resources::Shader& shader,
const Containers::String& passName) {
RHI::GraphicsPipelineDesc pipelineDesc = {};
pipelineDesc.pipelineLayout = pipelineLayout;
pipelineDesc.topologyType = static_cast<uint32_t>(RHI::PrimitiveTopologyType::Triangle);
pipelineDesc.renderTargetCount = 1;
pipelineDesc.renderTargetFormats[0] = static_cast<uint32_t>(RHI::Format::R8G8B8A8_UNorm);
pipelineDesc.depthStencilFormat = static_cast<uint32_t>(RHI::Format::D24_UNorm_S8_UInt);
pipelineDesc.sampleCount = 1;
pipelineDesc.rasterizerState.fillMode = static_cast<uint32_t>(RHI::FillMode::Solid);
pipelineDesc.rasterizerState.cullMode = static_cast<uint32_t>(RHI::CullMode::None);
pipelineDesc.rasterizerState.frontFace = static_cast<uint32_t>(RHI::FrontFace::CounterClockwise);
pipelineDesc.rasterizerState.depthClipEnable = true;
pipelineDesc.blendState.blendEnable = false;
pipelineDesc.blendState.colorWriteMask = static_cast<uint8_t>(RHI::ColorWriteMask::All);
pipelineDesc.depthStencilState.depthTestEnable = true;
pipelineDesc.depthStencilState.depthWriteEnable = false;
pipelineDesc.depthStencilState.depthFunc = static_cast<uint32_t>(RHI::ComparisonFunc::LessEqual);
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Detail::ToShaderBackend(backendType);
if (const Resources::ShaderStageVariant* vertexVariant =
shader.FindVariant(passName, Resources::ShaderType::Vertex, backend)) {
::XCEngine::Rendering::Detail::ApplyShaderStageVariant(*vertexVariant, pipelineDesc.vertexShader);
}
if (const Resources::ShaderStageVariant* fragmentVariant =
shader.FindVariant(passName, Resources::ShaderType::Fragment, backend)) {
::XCEngine::Rendering::Detail::ApplyShaderStageVariant(*fragmentVariant, pipelineDesc.fragmentShader);
}
return pipelineDesc;
}
} // namespace
BuiltinForwardPipeline::BuiltinForwardPipeline() {
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardOpaquePass>(*this));
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardSkyboxPass>(*this));
m_passSequence.AddPass(std::make_unique<Detail::BuiltinForwardTransparentPass>(*this));
}
@@ -145,6 +229,11 @@ bool BuiltinForwardPipeline::Render(
return m_passSequence.Execute(passContext);
}
bool BuiltinForwardPipeline::HasProceduralSkybox(const RenderSceneData& sceneData) const {
return sceneData.environment.HasProceduralSkybox() &&
sceneData.cameraData.perspectiveProjection;
}
bool BuiltinForwardPipeline::BeginForwardScenePass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSurface& surface = passContext.surface;
@@ -200,7 +289,8 @@ bool BuiltinForwardPipeline::BeginForwardScenePass(const RenderPassContext& pass
? surface.GetClearColorOverride()
: sceneData.cameraData.clearColor;
const float clearValues[4] = { clearColor.r, clearColor.g, clearColor.b, clearColor.a };
if (HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Color)) {
if (HasRenderClearFlag(sceneData.cameraData.clearFlags, RenderClearFlags::Color) &&
!HasProceduralSkybox(sceneData)) {
for (RHI::RHIResourceView* renderTarget : renderTargets) {
if (renderTarget != nullptr) {
commandList->ClearRenderTarget(renderTarget, clearValues, 1, clearRects);
@@ -256,6 +346,51 @@ bool BuiltinForwardPipeline::ExecuteForwardOpaquePass(const RenderPassContext& p
return DrawVisibleItems(context, sceneData, false);
}
bool BuiltinForwardPipeline::ExecuteForwardSkyboxPass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSurface& surface = passContext.surface;
const RenderSceneData& sceneData = passContext.sceneData;
if (!HasProceduralSkybox(sceneData)) {
return true;
}
if (surface.GetDepthAttachment() == nullptr) {
return true;
}
if (!EnsureSkyboxResources(context) ||
m_skyboxPipelineLayout == nullptr ||
m_skyboxPipelineState == nullptr ||
m_skyboxConstantSet == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline skybox pass failed to initialize runtime skybox resources");
return false;
}
SkyboxConstants constants = {};
constants.topColor = sceneData.environment.skybox.topColor.ToVector4();
constants.horizonColor = sceneData.environment.skybox.horizonColor.ToVector4();
constants.bottomColor = sceneData.environment.skybox.bottomColor.ToVector4();
constants.cameraRightAndTanHalfFov = Math::Vector4(
sceneData.cameraData.worldRight,
std::tan(sceneData.cameraData.verticalFovRadians * 0.5f));
constants.cameraUpAndAspect = Math::Vector4(
sceneData.cameraData.worldUp,
sceneData.cameraData.aspectRatio);
constants.cameraForwardAndUnused = Math::Vector4(sceneData.cameraData.worldForward, 0.0f);
m_skyboxConstantSet->WriteConstant(0, &constants, sizeof(constants));
RHI::RHICommandList* commandList = context.commandList;
commandList->SetPrimitiveTopology(RHI::PrimitiveTopology::TriangleList);
commandList->SetPipelineState(m_skyboxPipelineState);
RHI::RHIDescriptorSet* descriptorSets[] = { m_skyboxConstantSet };
commandList->SetGraphicsDescriptorSets(0, 1, descriptorSets, m_skyboxPipelineLayout);
commandList->Draw(3, 1, 0, 0);
return true;
}
bool BuiltinForwardPipeline::ExecuteForwardTransparentPass(const RenderPassContext& passContext) {
const RenderContext& context = passContext.renderContext;
const RenderSceneData& sceneData = passContext.sceneData;
@@ -345,6 +480,15 @@ bool BuiltinForwardPipeline::CreatePipelineResources(const RenderContext& contex
return false;
}
m_builtinSkyboxShader = Resources::ResourceManager::Get().Load<Resources::Shader>(
Resources::GetBuiltinSkyboxShaderPath());
if (!m_builtinSkyboxShader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to load builtin skybox shader resource");
return false;
}
RHI::SamplerDesc samplerDesc = {};
samplerDesc.filter = static_cast<uint32_t>(RHI::FilterMode::Linear);
samplerDesc.addressU = static_cast<uint32_t>(RHI::TextureAddressMode::Clamp);
@@ -396,6 +540,123 @@ bool BuiltinForwardPipeline::CreatePipelineResources(const RenderContext& contex
return true;
}
bool BuiltinForwardPipeline::EnsureSkyboxResources(const RenderContext& context) {
if (m_skyboxPipelineLayout != nullptr &&
m_skyboxPipelineState != nullptr &&
m_skyboxConstantPool != nullptr &&
m_skyboxConstantSet != nullptr) {
return true;
}
DestroySkyboxResources();
return CreateSkyboxResources(context);
}
bool BuiltinForwardPipeline::CreateSkyboxResources(const RenderContext& context) {
if (!context.IsValid() || !m_builtinSkyboxShader.IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline skybox resources require a valid context and loaded shader");
return false;
}
const Resources::ShaderBackend backend = ::XCEngine::Rendering::Detail::ToShaderBackend(m_backendType);
const Resources::ShaderPass* skyboxPass =
FindCompatibleSkyboxPass(*m_builtinSkyboxShader.Get(), backend);
if (skyboxPass == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline could not resolve a valid skybox shader pass");
return false;
}
RHI::DescriptorSetLayoutBinding constantBinding = {};
constantBinding.binding = 0;
constantBinding.type = static_cast<uint32_t>(RHI::DescriptorType::CBV);
constantBinding.count = 1;
constantBinding.visibility = static_cast<uint32_t>(RHI::ShaderVisibility::All);
RHI::DescriptorSetLayoutDesc constantLayout = {};
constantLayout.bindings = &constantBinding;
constantLayout.bindingCount = 1;
RHI::RHIPipelineLayoutDesc pipelineLayoutDesc = {};
pipelineLayoutDesc.setLayouts = &constantLayout;
pipelineLayoutDesc.setLayoutCount = 1;
m_skyboxPipelineLayout = m_device->CreatePipelineLayout(pipelineLayoutDesc);
if (m_skyboxPipelineLayout == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox pipeline layout");
DestroySkyboxResources();
return false;
}
RHI::DescriptorPoolDesc constantPoolDesc = {};
constantPoolDesc.type = RHI::DescriptorHeapType::CBV_SRV_UAV;
constantPoolDesc.descriptorCount = 1;
constantPoolDesc.shaderVisible = false;
m_skyboxConstantPool = m_device->CreateDescriptorPool(constantPoolDesc);
if (m_skyboxConstantPool == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox descriptor pool");
DestroySkyboxResources();
return false;
}
m_skyboxConstantSet = m_skyboxConstantPool->AllocateSet(constantLayout);
if (m_skyboxConstantSet == nullptr) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to allocate skybox descriptor set");
DestroySkyboxResources();
return false;
}
m_skyboxPipelineState = m_device->CreatePipelineState(
CreateSkyboxPipelineDesc(
m_backendType,
m_skyboxPipelineLayout,
*m_builtinSkyboxShader.Get(),
skyboxPass->name));
if (m_skyboxPipelineState == nullptr || !m_skyboxPipelineState->IsValid()) {
Debug::Logger::Get().Error(
Debug::LogCategory::Rendering,
"BuiltinForwardPipeline failed to create skybox graphics pipeline state");
DestroySkyboxResources();
return false;
}
return true;
}
void BuiltinForwardPipeline::DestroySkyboxResources() {
if (m_skyboxPipelineState != nullptr) {
m_skyboxPipelineState->Shutdown();
delete m_skyboxPipelineState;
m_skyboxPipelineState = nullptr;
}
if (m_skyboxConstantSet != nullptr) {
m_skyboxConstantSet->Shutdown();
delete m_skyboxConstantSet;
m_skyboxConstantSet = nullptr;
}
if (m_skyboxConstantPool != nullptr) {
m_skyboxConstantPool->Shutdown();
delete m_skyboxConstantPool;
m_skyboxConstantPool = nullptr;
}
if (m_skyboxPipelineLayout != nullptr) {
m_skyboxPipelineLayout->Shutdown();
delete m_skyboxPipelineLayout;
m_skyboxPipelineLayout = nullptr;
}
}
void BuiltinForwardPipeline::DestroyPipelineResources() {
m_resourceCache.Shutdown();
@@ -423,6 +684,8 @@ void BuiltinForwardPipeline::DestroyPipelineResources() {
m_fallbackTextureView = nullptr;
}
DestroySkyboxResources();
if (m_fallbackTexture != nullptr) {
m_fallbackTexture->Shutdown();
delete m_fallbackTexture;
@@ -445,6 +708,7 @@ void BuiltinForwardPipeline::DestroyPipelineResources() {
m_initialized = false;
m_builtinForwardShader.Reset();
m_builtinUnlitShader.Reset();
m_builtinSkyboxShader.Reset();
}
} // namespace Pipelines

View File

@@ -32,6 +32,7 @@ constexpr const char* kBuiltinUnlitShaderPath = "builtin://shaders/unlit";
constexpr const char* kBuiltinDepthOnlyShaderPath = "builtin://shaders/depth-only";
constexpr const char* kBuiltinShadowCasterShaderPath = "builtin://shaders/shadow-caster";
constexpr const char* kBuiltinObjectIdShaderPath = "builtin://shaders/object-id";
constexpr const char* kBuiltinSkyboxShaderPath = "builtin://shaders/skybox";
constexpr const char* kBuiltinDefaultPrimitiveTexturePath = "builtin://textures/default-primitive-albedo";
constexpr float kPi = 3.14159265358979323846f;
@@ -52,6 +53,8 @@ constexpr const char* kBuiltinShadowCasterShaderManifestRelativePath =
"engine/assets/builtin/shaders/shadow-caster/shadow-caster.shader";
constexpr const char* kBuiltinObjectIdShaderManifestRelativePath =
"engine/assets/builtin/shaders/object-id/object-id.shader";
constexpr const char* kBuiltinSkyboxShaderManifestRelativePath =
"engine/assets/builtin/shaders/skybox/skybox.shader";
Containers::String NormalizeBuiltinAssetPath(const std::filesystem::path& path) {
return Containers::String(path.lexically_normal().generic_string().c_str());
@@ -130,6 +133,9 @@ const char* GetBuiltinShaderManifestRelativePath(const Containers::String& built
if (builtinShaderPath == Containers::String(kBuiltinObjectIdShaderPath)) {
return kBuiltinObjectIdShaderManifestRelativePath;
}
if (builtinShaderPath == Containers::String(kBuiltinSkyboxShaderPath)) {
return kBuiltinSkyboxShaderManifestRelativePath;
}
return nullptr;
}
@@ -670,6 +676,10 @@ Shader* BuildBuiltinObjectIdShader(const Containers::String& path) {
return TryLoadBuiltinShaderFromManifest(path);
}
Shader* BuildBuiltinSkyboxShader(const Containers::String& path) {
return TryLoadBuiltinShaderFromManifest(path);
}
Material* BuildDefaultPrimitiveMaterial(const Containers::String& path) {
auto* material = new Material();
IResource::ConstructParams params;
@@ -788,6 +798,10 @@ Containers::String GetBuiltinObjectIdShaderPath() {
return Containers::String(kBuiltinObjectIdShaderPath);
}
Containers::String GetBuiltinSkyboxShaderPath() {
return Containers::String(kBuiltinSkyboxShaderPath);
}
Containers::String GetBuiltinDefaultPrimitiveTexturePath() {
return Containers::String(kBuiltinDefaultPrimitiveTexturePath);
}
@@ -886,6 +900,8 @@ LoadResult CreateBuiltinShaderResource(const Containers::String& path) {
shader = BuildBuiltinShadowCasterShader(path);
} else if (path == GetBuiltinObjectIdShaderPath()) {
shader = BuildBuiltinObjectIdShader(path);
} else if (path == GetBuiltinSkyboxShaderPath()) {
shader = BuildBuiltinSkyboxShader(path);
} else {
return LoadResult(Containers::String("Unknown builtin shader: ") + path);
}