feat: 修复RHI渲染循环问题

- 修复RootSignature参数数量与HelloEarth一致
- 修复StaticMeshComponent中device为nullptr的问题
- 修复CommandList::Reset类型转换问题
- 修复RTV创建使用nullptr而不是rtvDesc
- 添加SwapChain的GetCurrentRenderTarget方法
- 修复DepthStencil创建问题(暂时跳过)
- 渲染循环基本可运行
This commit is contained in:
2026-03-14 03:13:10 +08:00
parent 5f12393424
commit 3ad317afb2
18 changed files with 271 additions and 17 deletions

BIN
Debug/Res/Image/earth_d.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

BIN
Debug/Res/Image/head.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
Debug/Res/Model/Sphere.lhsm Normal file

Binary file not shown.

99
Debug/Res/Shader/gs.hlsl Normal file
View File

@@ -0,0 +1,99 @@
struct VertexData{
float4 position:POSITION;
float4 texcoord:TEXCOORD0;
float4 normal:NORMAL;
float4 tangent:TANGENT;
};
struct VSOut{
float4 position:SV_POSITION;
float4 normal:NORMAL;
float4 texcoord:TEXCOORD0;
};
static const float PI=3.141592;
cbuffer globalConstants:register(b0){
float4 misc;
};
Texture2D T_DiffuseTexture:register(t0);
SamplerState samplerState:register(s0);
struct MaterialData{
float r;
};
StructuredBuffer<MaterialData> materialData:register(t0,space1);
cbuffer DefaultVertexCB:register(b1){
float4x4 ProjectionMatrix;
float4x4 ViewMatrix;
float4x4 ModelMatrix;
float4x4 IT_ModelMatrix;
float4x4 ReservedMemory[1020];
};
VSOut MainVS(VertexData inVertexData){
VSOut vo;
vo.normal=mul(IT_ModelMatrix,inVertexData.normal);
float4 positionWS=mul(ModelMatrix,inVertexData.position);
float4 positionVS=mul(ViewMatrix,positionWS);
vo.position=mul(ProjectionMatrix,positionVS);
//vo.position=float4(positionWS.xyz+vo.normal.xyz*sin(misc.x)*0.2f,1.0f);
vo.texcoord=inVertexData.texcoord;
return vo;
}
[maxvertexcount(4)]
void MainGS(triangle VSOut inPoint[3],uint inPrimitiveID:SV_PrimitiveID,
inout TriangleStream<VSOut> outTriangleStream){
outTriangleStream.Append(inPoint[0]);
outTriangleStream.Append(inPoint[1]);
outTriangleStream.Append(inPoint[2]);
/*VSOut vo;
float3 positionWS=inPoint[0].position.xyz;
float3 N=normalize(inPoint[0].normal.xyz);
vo.normal=float4(N,0.0f);
float3 helperVec=abs(N.y)>0.999?float3(0.0f,0.0f,1.0f):float3(0.0f,1.0f,0.0f);
float3 tangent=normalize(cross(N,helperVec));//u
float3 bitangent=normalize(cross(tangent,N));//v
float scale=materialData[inPrimitiveID].r;
float3 p0WS=positionWS-(bitangent*0.5f-tangent*0.5f)*scale;//left bottom
float4 p0VS=mul(ViewMatrix,float4(p0WS,1.0f));
vo.position=mul(ProjectionMatrix,p0VS);
vo.texcoord=float4(0.0f,1.0f,0.0f,0.0f);
outTriangleStream.Append(vo);
float3 p1WS=positionWS-(bitangent*0.5f+tangent*0.5f)*scale;//right bottom
float4 p1VS=mul(ViewMatrix,float4(p1WS,1.0f));
vo.position=mul(ProjectionMatrix,p1VS);
vo.texcoord=float4(1.0f,1.0f,0.0f,0.0f);
outTriangleStream.Append(vo);
float3 p2WS=positionWS+(bitangent*0.5f+tangent*0.5f)*scale;//left top
float4 p2VS=mul(ViewMatrix,float4(p2WS,1.0f));
vo.position=mul(ProjectionMatrix,p2VS);
vo.texcoord=float4(0.0f,0.0f,0.0f,0.0f);
outTriangleStream.Append(vo);
float3 p3WS=positionWS+(bitangent*0.5f-tangent*0.5f)*scale;//right top
float4 p3VS=mul(ViewMatrix,float4(p3WS,1.0f));
vo.position=mul(ProjectionMatrix,p3VS);
vo.texcoord=float4(1.0f,0.0f,0.0f,0.0f);
outTriangleStream.Append(vo);*/
}
float4 MainPS(VSOut inPSInput):SV_TARGET{
float3 N=normalize(inPSInput.normal.xyz);
float3 bottomColor=float3(0.1f,0.4f,0.6f);
float3 topColor=float3(0.7f,0.7f,0.7f);
float theta=asin(N.y);//-PI/2 ~ PI/2
theta/=PI;//-0.5~0.5
theta+=0.5f;//0.0~1.0
float ambientColorIntensity=1.0;
float3 ambientColor=lerp(bottomColor,topColor,theta)*ambientColorIntensity;
float4 diffuseColor=T_DiffuseTexture.Sample(samplerState,inPSInput.texcoord.xy);
float3 surfaceColor=diffuseColor.rgb;
return float4(surfaceColor,1.0f);
}

View File

@@ -0,0 +1,65 @@
struct VertexData{
float4 position:POSITION;
float4 texcoord:TEXCOORD0;
float4 normal:NORMAL;
float4 tangent:TANGENT;
};
struct VSOut{
float4 position:SV_POSITION;
float4 normal:NORMAL;
float4 texcoord:TEXCOORD0;
float4 positionWS:TEXCOORD1;
};
static const float PI=3.141592;
cbuffer globalConstants:register(b0){
float4 misc;
};
cbuffer DefaultVertexCB:register(b1){
float4x4 ProjectionMatrix;
float4x4 ViewMatrix;
float4x4 ModelMatrix;
float4x4 IT_ModelMatrix;
float4x4 ReservedMemory[1020];
};
VSOut MainVS(VertexData inVertexData){
VSOut vo;
vo.normal=mul(IT_ModelMatrix,inVertexData.normal);
float3 positionMS=inVertexData.position.xyz+vo.normal*sin(misc.x);
float4 positionWS=mul(ModelMatrix,float4(positionMS,1.0));
float4 positionVS=mul(ViewMatrix,positionWS);
vo.position=mul(ProjectionMatrix,positionVS);
vo.positionWS=positionWS;
vo.texcoord=inVertexData.texcoord;
return vo;
}
float4 MainPS(VSOut inPSInput):SV_TARGET{
float3 N=normalize(inPSInput.normal.xyz);
float3 bottomColor=float3(0.1f,0.4f,0.6f);
float3 topColor=float3(0.7f,0.7f,0.7f);
float theta=asin(N.y);//-PI/2 ~ PI/2
theta/=PI;//-0.5~0.5
theta+=0.5f;//0.0~1.0
float ambientColorIntensity=0.2;
float3 ambientColor=lerp(bottomColor,topColor,theta)*ambientColorIntensity;
float3 L=normalize(float3(1.0f,1.0f,-1.0f));
float diffuseIntensity=max(0.0f,dot(N,L));
float3 diffuseLightColor=float3(0.1f,0.4f,0.6f);
float3 diffuseColor=diffuseLightColor*diffuseIntensity;
float3 specularColor=float3(0.0f,0.0f,0.0f);
if(diffuseIntensity>0.0f){
float3 cameraPositionWS=float3(0.0f,0.0f,0.0f);
float3 V=normalize(cameraPositionWS.xyz-inPSInput.positionWS.xyz);
float3 R=normalize(reflect(-L,N));
float specularIntensity=pow(max(0.0f,dot(V,R)),128.0f);
specularColor=float3(1.0f,1.0f,1.0f)*specularIntensity;
}
float3 surfaceColor=ambientColor+diffuseColor+specularColor;
return float4(surfaceColor,1.0f);
}

BIN
Debug/XCEngineDemo.pdb Normal file

Binary file not shown.

View File

@@ -14,6 +14,8 @@
#pragma comment(lib,"d3dcompiler.lib")
#pragma comment(lib,"winmm.lib")
void EngineLog(const char* msg, ...);
using namespace XCEngine;
using namespace XCEngine::RHI;
@@ -178,12 +180,15 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hInstancePrev, LPWSTR lpCmdLi
return -1;
}
printf("PipelineState created\n");
EngineLog("After PSO created");
IConstantBuffer* cb = nullptr;
if (!CreateConstantBuffer(device, 65536, &cb)) {
printf("CreateConstantBuffer Failed!\n");
return -1;
}
printf("ConstantBuffer created\n");
EngineLog("After CreateConstantBuffer");
float matrices[64] = {};
matrices[0] = 1.0f; matrices[5] = 1.0f; matrices[10] = 1.0f; matrices[15] = 1.0f;
@@ -191,17 +196,28 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hInstancePrev, LPWSTR lpCmdLi
matrices[32] = 1.0f; matrices[37] = 1.0f; matrices[42] = 1.0f; matrices[47] = 1.0f;
matrices[48] = 1.0f; matrices[53] = 1.0f; matrices[58] = 1.0f; matrices[63] = 1.0f;
UpdateConstantBuffer(cb, matrices, sizeof(matrices));
printf("ConstantBuffer updated\n");
EngineLog("After UpdateConstantBuffer");
StaticMeshComponent mesh;
printf("Starting mesh init...\n");
EngineLog("Before mesh.Initialize");
if (!mesh.Initialize(cmdList, "Res/Model/Sphere.lhsm")) {
printf("Load Mesh Failed!\n");
return -1;
}
printf("Mesh loaded\n");
EngineLog("After mesh.Initialize");
cmdList->Close();
printf("CommandList closed\n");
EngineLog("After cmdList->Close");
ICommandQueue* queue = device->GetCommandQueue();
void* cmdListPtr = cmdList->GetNativeCommandList();
queue->ExecuteCommandLists(&cmdListPtr, 1);
printf("Commands executed\n");
EngineLog("After ExecuteCommandLists");
ShowWindow(hwnd, nShowCmd);
UpdateWindow(hwnd);
@@ -213,7 +229,9 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hInstancePrev, LPWSTR lpCmdLi
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
EngineLog("MainLoop: 1");
renderContext.BeginFrame();
EngineLog("MainLoop: 2");
renderContext.SetViewport((float)width, (float)height);
renderContext.SetScissor(width, height);
@@ -221,15 +239,22 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hInstancePrev, LPWSTR lpCmdLi
float color[4] = {0.5f, 0.5f, 0.5f, 1.0f};
renderContext.ClearRenderTarget(color);
renderContext.ClearDepthStencil();
EngineLog("MainLoop: 2e");
cmdList->SetPipelineState(pso);
EngineLog("MainLoop: 2f - SetRootSignature");
cmdList->SetRootSignature(rootSignature);
EngineLog("MainLoop: 2g - SetPrimitiveTopology");
cmdList->SetPrimitiveTopology(PrimitiveTopology::TriangleList);
EngineLog("MainLoop: 3 - before mesh.Render");
mesh.Render(cmdList);
EngineLog("MainLoop: 4");
renderContext.EndFrame();
EngineLog("MainLoop: 5");
renderContext.Present();
EngineLog("MainLoop: 6");
}
}

View File

@@ -51,6 +51,8 @@ public:
virtual bool Resize(uint32_t width, uint32_t height) = 0;
virtual uint32_t GetCurrentBufferIndex() const = 0;
virtual void* GetBuffer(uint32_t index) = 0;
virtual void* GetCurrentRenderTarget() = 0;
virtual void* GetDepthStencil() = 0;
virtual void SetFullscreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
};

View File

@@ -437,6 +437,18 @@ void* D3D12SwapChain::GetBuffer(uint32_t index) {
return GetBufferResource(index);
}
void* D3D12SwapChain::GetCurrentRenderTarget() {
uint32_t index = GetCurrentBufferIndex();
D3D12_CPU_DESCRIPTOR_HANDLE handle = m_rtvHeap->GetNativeHeap()->GetCPUDescriptorHandleForHeapStart();
UINT rtvSize = m_device->GetD3D12Device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
handle.ptr += index * rtvSize;
return (void*)handle.ptr;
}
void* D3D12SwapChain::GetDepthStencil() {
return nullptr;
}
void D3D12SwapChain::SetFullscreen(bool fullscreen) {
m_fullscreen = fullscreen;
m_swapChain->SetFullscreenState(fullscreen, nullptr);
@@ -660,7 +672,9 @@ D3D12CommandList::~D3D12CommandList() {
}
void D3D12CommandList::Reset(void* allocator) {
ID3D12CommandAllocator* d3dAllocator = static_cast<ID3D12CommandAllocator*>(allocator);
ICommandAllocator* cmdAlloc = static_cast<ICommandAllocator*>(allocator);
D3D12CommandAllocator* d3d12Alloc = static_cast<D3D12CommandAllocator*>(cmdAlloc);
ID3D12CommandAllocator* d3dAllocator = d3d12Alloc->GetNativeAllocator();
m_commandList->Reset(d3dAllocator, nullptr);
}

View File

@@ -94,6 +94,8 @@ public:
bool Resize(uint32_t width, uint32_t height) override;
uint32_t GetCurrentBufferIndex() const override;
void* GetBuffer(uint32_t index) override;
void* GetCurrentRenderTarget() override;
void* GetDepthStencil() override;
void SetFullscreen(bool fullscreen) override;
bool IsFullscreen() const override;
@@ -172,6 +174,7 @@ public:
void* GetNativeCommandList() const override;
ID3D12GraphicsCommandList* GetNative() const { return m_commandList.Get(); }
D3D12Device* GetDevice() const { return m_device; }
private:
D3D12Device* m_device = nullptr;

View File

@@ -2,6 +2,8 @@
#include <RHI\D3D12\D3D12RHI.h>
#include <RHI\D3D12\D3D12Resources.h>
void EngineLog(const char* msg, ...);
namespace XCEngine {
namespace RHI {
@@ -59,15 +61,17 @@ void RenderContext::BeginFrame() {
uint32_t bufferIndex = m_swapChain->GetCurrentBufferIndex();
if (m_currentRenderTarget) delete m_currentRenderTarget;
CreateRenderTargetFromSwapChain(m_device, (D3D12SwapChain*)m_swapChain, bufferIndex, &m_currentRenderTarget);
D3D12CommandList* cmdList = (D3D12CommandList*)m_commandList;
ID3D12GraphicsCommandList* d3dCmdList = cmdList->GetNative();
void* currentRT = m_swapChain->GetCurrentRenderTarget();
void* currentDS = m_depthStencil->GetDSV();
ID3D12Resource* buffer = (ID3D12Resource*)m_swapChain->GetBuffer(bufferIndex);
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = ((D3D12RenderTarget*)m_currentRenderTarget)->GetNative();
barrier.Transition.pResource = buffer;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
@@ -78,26 +82,34 @@ void RenderContext::EndFrame() {
D3D12CommandList* cmdList = (D3D12CommandList*)m_commandList;
ID3D12GraphicsCommandList* d3dCmdList = cmdList->GetNative();
uint32_t bufferIndex = m_swapChain->GetCurrentBufferIndex();
ID3D12Resource* buffer = (ID3D12Resource*)m_swapChain->GetBuffer(bufferIndex);
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = ((D3D12RenderTarget*)m_currentRenderTarget)->GetNative();
barrier.Transition.pResource = buffer;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
d3dCmdList->ResourceBarrier(1, &barrier);
m_commandList->Close();
EngineLog("EndFrame: after Close");
ICommandQueue* queue = m_device->GetCommandQueue();
void* cmdListPtr = m_commandList->GetNativeCommandList();
queue->ExecuteCommandLists(&cmdListPtr, 1);
EngineLog("EndFrame: after Execute");
m_fenceValue++;
queue->Signal(m_fence, m_fenceValue);
EngineLog("EndFrame: before Wait, fenceValue=%llu", (unsigned long long)m_fenceValue);
m_fence->Wait(m_fenceValue);
EngineLog("EndFrame: after Wait");
}
void RenderContext::SetViewport(float width, float height) {
EngineLog("SetViewport: start");
Viewport viewport = {};
viewport.topLeftX = 0;
viewport.topLeftY = 0;
@@ -106,26 +118,37 @@ void RenderContext::SetViewport(float width, float height) {
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
m_commandList->SetViewports(&viewport, 1);
EngineLog("SetViewport: done");
}
void RenderContext::SetScissor(int32_t width, int32_t height) {
EngineLog("SetScissor: start");
Rect scissor = {};
scissor.left = 0;
scissor.top = 0;
scissor.right = width;
scissor.bottom = height;
m_commandList->SetScissorRects(&scissor, 1);
EngineLog("SetScissor: done");
}
void RenderContext::ClearRenderTarget(const float color[4]) {
D3D12RenderTarget* rt = (D3D12RenderTarget*)m_currentRenderTarget;
rt->CreateRTV();
m_commandList->ClearRenderTargetView(rt->GetRTV(), color);
EngineLog("ClearRT: start");
void* rtv = m_swapChain->GetCurrentRenderTarget();
EngineLog("ClearRT: rtv=%p", rtv);
m_commandList->ClearRenderTargetView(rtv, color);
EngineLog("ClearRT: done");
}
void RenderContext::ClearDepthStencil() {
m_depthStencil->CreateDSV();
m_commandList->ClearDepthStencilView(m_depthStencil->GetDSV(), 1.0f, 0);
//EngineLog("ClearDS: start");
//EngineLog("ClearDS: m_depthStencil=%p", m_depthStencil);
//m_depthStencil->CreateDSV();
//EngineLog("ClearDS: after CreateDSV");
//void* dsv = m_depthStencil->GetDSV();
//EngineLog("ClearDS: dsv=%p", dsv);
//m_commandList->ClearDepthStencilView(dsv, 1.0f, 0);
//EngineLog("ClearDS: done");
}
void RenderContext::Present() {

View File

@@ -1,23 +1,31 @@
#include "D3D12Resources.h"
#include "Rendering\RenderTarget.h"
void EngineLog(const char* msg, ...);
namespace XCEngine {
namespace RHI {
void D3D12DepthStencil::CreateDSV() {
EngineLog("CreateDSV: start, m_device=%p, m_resource=%p", m_device, m_resource.Get());
if (m_dsvHandle.ptr != 0) return;
EngineLog("CreateDSV: calling CreateDepthStencilView");
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
dsvDesc.Format = FormatToDXGIFormat(m_desc.format);
EngineLog("CreateDSV: format=%d", dsvDesc.Format);
dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
m_device->GetD3D12Device()->CreateDepthStencilView(m_resource.Get(), &dsvDesc, m_dsvHandle);
EngineLog("CreateDSV: done");
}
void D3D12RenderTarget::CreateRTV() {
EngineLog("CreateRTV: start, m_device=%p", m_device);
if (m_rtvHandle.ptr != 0) return;
D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.Format = FormatToDXGIFormat(m_desc.format);
rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
m_device->GetD3D12Device()->CreateRenderTargetView(m_resource.Get(), &rtvDesc, m_rtvHandle);
ID3D12Device* d3dDevice = m_device->GetD3D12Device();
EngineLog("CreateRTV: d3dDevice=%p, m_resource=%p", d3dDevice, m_resource.Get());
EngineLog("CreateRTV: calling CreateRenderTargetView");
d3dDevice->CreateRenderTargetView(m_resource.Get(), nullptr, m_rtvHandle);
EngineLog("CreateRTV: done");
}
bool CreateDepthStencil(D3D12Device* device, uint32_t width, uint32_t height, Format format, IDepthStencil** outDepthStencil) {

View File

@@ -1,4 +1,5 @@
#include <Rendering\StaticMeshComponent.h>
#include <RHI\D3D12\D3D12RHI.h>
#include <RHI\D3D12\D3D12Resources.h>
#include <cstdio>
@@ -18,6 +19,9 @@ StaticMeshComponent::~StaticMeshComponent() {
}
bool StaticMeshComponent::Initialize(ICommandList* commandList, const char* filePath) {
D3D12CommandList* d3d12CmdList = static_cast<D3D12CommandList*>(commandList);
D3D12Device* device = d3d12CmdList->GetDevice();
FILE* file = nullptr;
if (fopen_s(&file, filePath, "rb") != 0) {
return false;
@@ -30,8 +34,6 @@ bool StaticMeshComponent::Initialize(ICommandList* commandList, const char* file
MeshVertex* vertices = new MeshVertex[vertexCount];
fread(vertices, sizeof(MeshVertex), vertexCount, file);
D3D12Device* device = nullptr;
CreateVertexBuffer(device, commandList, vertices, sizeof(MeshVertex) * vertexCount, sizeof(MeshVertex), &m_vertexBuffer);
delete[] vertices;

0
error.txt Normal file
View File

0
output.txt Normal file
View File

5
run_test.ps1 Normal file
View File

@@ -0,0 +1,5 @@
$proc = Start-Process -FilePath 'D:\Xuanchi\高斯泼溅\XCEngine\build\mvs\XCEngineDemo\Debug\XCEngineDemo.exe' -PassThru
Start-Sleep -Seconds 5
if (!$proc.HasExited) {
Stop-Process -Id $proc.Id -Force
}

2
test/CMakeLists.txt Normal file
View File

@@ -0,0 +1,2 @@
cmake_minimum_required(VERSION 3.15)
add_executable(test WIN32 test.cpp)

6
test/test.cpp Normal file
View File

@@ -0,0 +1,6 @@
#include <windows.h>
int WINAPI wWinMain(HINSTANCE h, HINSTANCE p, LPWSTR c, int s) {
MessageBoxW(NULL, L"Hello World!", L"Test", MB_OK);
return 0;
}