D3D12可编程渲染流水线

一、初始化D3D库 

启用 DirectX数学库

x86需要启用SSE2指令集,所有平台均需将浮点模型设置为fast。默认为: 精度 (/fp:precise)。 

#include <DirectXMath.h>
#include <DirectXPackedVector.h>

启用调试模式下的内存泄漏检测

// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#define new  new(_CLIENT_BLOCK, __FILE__, __LINE__)
#endif


#if defined(DEBUG) | defined(_DEBUG)
    _CrtDumpMemoryLeaks();
#endif

启用D3D调试接口和调试层。 

#if defined(DEBUG) || defined(_DEBUG) 
	// Enable the D3D12 debug layer.
	{
		ComPtr<ID3D12Debug> debugController;
		ThrowIfFailed(D3D12GetDebugInterface(IID_PPV_ARGS(debugController.GetAddressOf())));
		debugController->EnableDebugLayer();
	}
#endif

1、创建DXGI对象 

ComPtr<IDXGIFactory4> mdxgiFactory;

CreateDXGIFactory1(IID_PPV_ARGS(&mdxgiFactory));

2、创建设备

ComPtr<ID3D12Device> md3dDevice; 使用高性能显卡

//枚举设备,
//requestHighPerformanceAdapter设置为true
//ComPtr<IDXGIFactory4> factory;

ComPtr<IDXGIAdapter1> adapter;

ComPtr<IDXGIFactory6> factory6;
if (SUCCEEDED(pFactory->QueryInterface(IID_PPV_ARGS(&factory6))))
{
    for (
        UINT adapterIndex = 0;
        SUCCEEDED(factory6->EnumAdapterByGpuPreference(
            adapterIndex,
            requestHighPerformanceAdapter == true ? DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE : DXGI_GPU_PREFERENCE_UNSPECIFIED,
            IID_PPV_ARGS(&adapter)));
        ++adapterIndex)
    {
        DXGI_ADAPTER_DESC1 desc;
        adapter->GetDesc1(&desc);

        if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
        {
            // Don't select the Basic Render Driver adapter.
            // If you want a software adapter, pass in "/warp" on the command line.
            continue;
        }

        // Check to see whether the adapter supports Direct3D 12, but don't create the
        // actual device yet.
        if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
        {
            break;
        }
    }
}

if(adapter.Get() == nullptr)
{
    for (UINT adapterIndex = 0; SUCCEEDED(pFactory->EnumAdapters1(adapterIndex, &adapter)); ++adapterIndex)
    {
        DXGI_ADAPTER_DESC1 desc;
        adapter->GetDesc1(&desc);

        if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
        {
            // Don't select the Basic Render Driver adapter.
            // If you want a software adapter, pass in "/warp" on the command line.
            continue;
        }

        // Check to see whether the adapter supports Direct3D 12, but don't create the
        // actual device yet.
        if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
        {
            break;
        }
    }
}

ComPtr<IDXGIAdapter1> hardwareAdapter;
D3D12CreateDevice(    hardwareAdapter.Get(),             // default adapter
    D3D_FEATURE_LEVEL_12_0,    IID_PPV_ARGS(&md3dDevice));

3、创建围栏

围栏用于CPU和GPU之间的同步,它可以强制CPU等待GPU完成所有的渲染指令。ComPtr<ID3D12Fence> mFence;

md3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,  IID_PPV_ARGS(&mFence));

4、检查多采样质量级别

D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msQualityLevels;
msQualityLevels.Format = mBackBufferFormat;
msQualityLevels.SampleCount = 4; //每像素采样次数
msQualityLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
msQualityLevels.NumQualityLevels = 0; //输入输出参数,输入时为0
ThrowIfFailed(md3dDevice->CheckFeatureSupport(
	D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS,
	&msQualityLevels,
	sizeof(msQualityLevels)));
m4xMsaaQuality = msQualityLevels.NumQualityLevels; //支持的最高质量级别, 使用时-1

5、创建命令队列、命令列表和命令分配器

多个命令列表可以关联到一个命令分配器,但不能同时记录命令,必须先关闭其他的命令列表。创建命令列表时,它处于Open状态,需要先Close。

在GPU执行完命令分配器中的所有命令前,不能重置命令分配器。 注意:命令队列是线程安全的,其他两种均不是线程安全的。

void D3DApp::CreateCommandObjects()
{
	D3D12_COMMAND_QUEUE_DESC queueDesc = {};
	queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
	queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
	ThrowIfFailed(md3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&mCommandQueue)));

	ThrowIfFailed(md3dDevice->CreateCommandAllocator(
		D3D12_COMMAND_LIST_TYPE_DIRECT,
		IID_PPV_ARGS(mDirectCmdListAlloc.GetAddressOf())));

	ThrowIfFailed(md3dDevice->CreateCommandList(
		0,
		D3D12_COMMAND_LIST_TYPE_DIRECT,
		mDirectCmdListAlloc.Get(), // Associated command allocator
		nullptr,                   // Initial PipelineStateObject
		IID_PPV_ARGS(mCommandList.GetAddressOf())));

	// Start off in a closed state.  This is because the first time we refer 
	// to the command list we will Reset it, and it needs to be closed before
	// calling Reset.
    // 关闭此命令列表在Allocator中记录命令,其他命令列表可以使用其Allocator
	mCommandList->Close();
}

二、资源管理

1、概述

GPU资源都存于堆中,本质是具有特定属性的GPU显存块。在绘制之前,需要将一次绘制调用的相关资源链接到渲染流水线,GPU通过描述符访问绑定到流水线上的资源(显存)。

创建描述符堆->创建资源->创建视图,将描述符堆的元素指向资源:

1.1 创建描述符堆

填充描述符堆描述结构D3D12_DESCRIPTOR_HEAP_DESC,然后调用md3dDevice->CreateDescriptorHeap,保存到ComPtr<ID3D12DescriptorHeap>中。

D3D12_DESCRIPTOR_HEAP_DESC
{
    D3D12_DESCRIPTOR_HEAP_TYPE Type; //类型
    UINT NumDescriptors; //描述符的数量
    D3D12_DESCRIPTOR_HEAP_FLAGS Flags;
    UINT NodeMask;
}

描述符可以看作GPU资源的句柄(handle)?描述符为GPU解释资源,以及资源将如何使用。描述符堆可看作描述符的数组,描述符堆类型主要有四种

//常量缓冲区、着色器资源、无序访问资源
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
//采样器资源
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
//渲染目标
D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
//深度\模板缓冲区
D3D12_DESCRIPTOR_HEAP_TYPE_DSV,

 1.2 创建资源

填充资源描述结构 D3D12_RESOURCE_DESC ,

struct D3D12_RESOURCE_DESC
{
    D3D12_RESOURCE_DIMENSION Dimension;
    //资源种类 D3D12_RESOURCE_DIMENSION_BUFFER,
    // D3D12_RESOURCE_DIMENSION_TEXTURE2D等
    UINT64 Alignment;
    UINT64 Width; //空间大小
    UINT Height;
    UINT16 DepthOrArraySize;
    UINT16 MipLevels;
    DXGI_FORMAT Format; //格式
    DXGI_SAMPLE_DESC SampleDesc;
    D3D12_TEXTURE_LAYOUT Layout; //D3D12_TEXTURE_LAYOUT_ROW_MAJOR
    D3D12_RESOURCE_FLAGS Flags;
}

然后调用 md3dDevice->CreateCommittedResource等函数创建资源,在指定的堆(默认堆、上传堆)中预留空间,使用ComPtr<ID3D12Resource>访问资源。创建函数包括:CreateCommittedResource、CreatePlacedResource、CreateReservedResource。

//根据提供的属性创建一个资源和一个堆,并将资源提交到这个堆中。
md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
		D3D12_HEAP_FLAG_NONE,
        &depthStencilDesc,
		D3D12_RESOURCE_STATE_COMMON,
        &optClear,
        IID_PPV_ARGS(mDepthStencilBuffer.GetAddressOf())
);

 资源的类型主要有:后台缓冲区、深度模板缓冲区,顶点缓冲区、索引缓冲区,常量缓冲区、着色器资源缓冲区等。 数据种类主要是 

D3D12_RESOURCE_DIMENSION_BUFFER	= 1,
D3D12_RESOURCE_DIMENSION_TEXTURE1D	= 2,
D3D12_RESOURCE_DIMENSION_TEXTURE2D	= 3,
D3D12_RESOURCE_DIMENSION_TEXTURE3D	= 4

  1.3 创建视图(描述符)

填充视图描述结构,不同类型的资源,视图描述结构不同。 描述符的大小是硬件依赖的,需要运行时查询,它用于在描述符堆中偏移,以找到需要的描述符。

mSamplerDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
mRtvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
mDsvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
mCbvSrvUavDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
1.3.1 常量缓冲区视图

填充描述结构D3D12_CONSTANT_BUFFER_VIEW_DESC,

struct D3D12_CONSTANT_BUFFER_VIEW_DESC
{
    D3D12_GPU_VIRTUAL_ADDRESS BufferLocation;//资源的GPU虚拟地址
    UINT SizeInBytes; //所指向资源的大小
}

然后创建视图

md3dDevice->CreateConstantBufferView(
		&cbvDesc,  //描述
		mCbvHeap->GetCPUDescriptorHandleForHeapStart() //描述符的内存地址
);
 1.3.2 深度模板缓冲区视图

填充描述结构D3D12_DEPTH_STENCIL_VIEW_DESC, 

struct D3D12_DEPTH_STENCIL_VIEW_DESC
    {
    DXGI_FORMAT Format;
    D3D12_DSV_DIMENSION ViewDimension;
    D3D12_DSV_FLAGS Flags;
    union 
        {
        D3D12_TEX1D_DSV Texture1D;
        D3D12_TEX1D_ARRAY_DSV Texture1DArray;
        D3D12_TEX2D_DSV Texture2D;
        D3D12_TEX2D_ARRAY_DSV Texture2DArray;
        D3D12_TEX2DMS_DSV Texture2DMS;
        D3D12_TEX2DMS_ARRAY_DSV Texture2DMSArray;
        } 	;
}

然后创建视图:

 md3dDevice->CreateDepthStencilView(
mDepthStencilBuffer.Get(),  //GPU资源
&dsvDesc,  //描述
mDsvHeap->GetCPUDescriptorHandleForHeapStart() //描述符内存地址
);
1.3.3 渲染目标视图

渲染目标资源在创建交换链时创建,一般有2个。

//描述符的内存地址
CD3DX12_CPU_DESCRIPTOR_HANDLE
rtvHeapHandle(mRtvHeap->GetCPUDescriptorHandleForHeapStart()); 

for (UINT i = 0; i < SwapChainBufferCount; i++)
{
    
	ThrowIfFailed(mSwapChain->GetBuffer(i, IID_PPV_ARGS(&mSwapChainBuffer[i])));

	md3dDevice->CreateRenderTargetView(
    mSwapChainBuffer[i].Get(), //GPU资源
    nullptr, 
    rtvHeapHandle
    );

	rtvHeapHandle.Offset(1, mRtvDescriptorSize); //描述符堆中的下一个描述符
}
1.3.4 采样器资源

2、交换链

ComPtr<IDXGISwapChain> mSwapChain;  创建交换链时同时也创建了2个渲染目标缓冲器资源。存储了前台和后台缓冲区两种纹理。

void D3DApp::CreateSwapChain()
{
	// Release the previous swapchain we will be recreating.
	mSwapChain.Reset();

	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width = mClientWidth;
	sd.BufferDesc.Height = mClientHeight;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format = mBackBufferFormat;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	sd.SampleDesc.Count = m4xMsaaState ? 4 : 1;
    //质量减1
	sd.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount = SwapChainBufferCount;
	sd.OutputWindow = mhMainWnd;
	sd.Windowed = true;
	sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
	sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	// Note: Swap chain uses queue to perform flush.
	ThrowIfFailed(mdxgiFactory->CreateSwapChain(
		mCommandQueue.Get(),
		&sd,
		mSwapChain.GetAddressOf()));

    //当前的后备缓冲区编号
	ComPtr<IDXGISwapChain3> m_swapChain;
	ThrowIfFailed(mSwapChain.As(&m_swapChain));
	auto m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();

}

3、渲染目标缓冲区描述符堆和视图 

//1-1 渲染目标缓冲区的描述符堆
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc;
rtvHeapDesc.NumDescriptors = SwapChainBufferCount;
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
rtvHeapDesc.NodeMask = 0;
ThrowIfFailed(md3dDevice->CreateDescriptorHeap(
	&rtvHeapDesc, IID_PPV_ARGS(mRtvHeap.GetAddressOf())));
//1-2 创建渲染缓冲区的视图,将资源与描述符堆中的描述符进行关联
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(mRtvHeap->GetCPUDescriptorHandleForHeapStart());
for (UINT i = 0; i < SwapChainBufferCount; i++)
{
	ThrowIfFailed(mSwapChain->GetBuffer(i, IID_PPV_ARGS(&mSwapChainBuffer[i])));
	md3dDevice->CreateRenderTargetView(mSwapChainBuffer[i].Get(), nullptr, rtvHeapHandle);
	rtvHeapHandle.Offset(1, mRtvDescriptorSize);
}

4、深度模板缓冲区

深度缓冲区也是纹理资源,但是存储的不是图像而是特定像素的深度信息。

//2-1 创建深度模板缓冲区资源
D3D12_RESOURCE_DESC depthStencilDesc;
depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
depthStencilDesc.Alignment = 0;
depthStencilDesc.Width = mClientWidth;
depthStencilDesc.Height = mClientHeight;
depthStencilDesc.DepthOrArraySize = 1;
depthStencilDesc.MipLevels = 1;

// Correction 11/12/2016: SSAO chapter requires an SRV to the depth buffer to read from 
// the depth buffer.  Therefore, because we need to create two views to the same resource:
//   1. SRV format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS
//   2. DSV Format: DXGI_FORMAT_D24_UNORM_S8_UINT
// we need to create the depth buffer resource with a typeless format.  
depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
depthStencilDesc.SampleDesc.Count = m4xMsaaState ? 4 : 1;
depthStencilDesc.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;

D3D12_CLEAR_VALUE optClear;
optClear.Format = mDepthStencilFormat;
optClear.DepthStencil.Depth = 1.0f;
optClear.DepthStencil.Stencil = 0;
//创建资源并提交到默认堆(显存)中
ThrowIfFailed(md3dDevice->CreateCommittedResource(
	&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
	D3D12_HEAP_FLAG_NONE,
	&depthStencilDesc,
	D3D12_RESOURCE_STATE_COMMON, //资源的初始状态
	&optClear,
	IID_PPV_ARGS(mDepthStencilBuffer.GetAddressOf())));

创建描述符堆和视图 

// 2-2 深度模板缓冲区的描述符堆
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
dsvHeapDesc.NodeMask = 0;
ThrowIfFailed(md3dDevice->CreateDescriptorHeap(
	&dsvHeapDesc, IID_PPV_ARGS(mDsvHeap.GetAddressOf())));

//2-3  创建视图
// Create descriptor to mip level 0 of entire resource using the format of the resource.
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Format = mDepthStencilFormat;
dsvDesc.Texture2D.MipSlice = 0;
md3dDevice->CreateDepthStencilView(mDepthStencilBuffer.Get(), &dsvDesc, DepthStencilView());

DepthStencilView() 返回深度模板描述符堆中的第一个描述符。

 5、常量着色器无序访问缓冲区

 创建描述符堆和视图 

D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc;
cbvHeapDesc.NumDescriptors = 1;
cbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
//着色器程序可访问数据
cbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
cbvHeapDesc.NodeMask = 0;
ThrowIfFailed(md3dDevice->CreateDescriptorHeap(&cbvHeapDesc, IID_PPV_ARGS(&mCbvHeap)));

常量缓冲区,常量的大小必须是 256字节的整数倍,常量缓冲区通常在每帧都会改变,放到上传堆中。常量缓冲区资源是D3D12_RESOURCE_DIMENSION_BUFFER类型。

struct ObjectConstants
{
    XMFLOAT4X4 WorldViewProj = MathHelper::Identity4x4();
};

template<typename T>
class UploadBuffer
{
public:
    UploadBuffer(ID3D12Device* device, UINT elementCount, bool isConstantBuffer) : 
        mIsConstantBuffer(isConstantBuffer)
    {
        mElementByteSize = sizeof(T);

        // Constant buffer elements need to be multiples of 256 bytes.
        // This is because the hardware can only view constant data 
        // at m*256 byte offsets and of n*256 byte lengths. 
        // typedef struct D3D12_CONSTANT_BUFFER_VIEW_DESC {
        // UINT64 OffsetInBytes; // multiple of 256
        // UINT   SizeInBytes;   // multiple of 256
        // } D3D12_CONSTANT_BUFFER_VIEW_DESC;
        if(isConstantBuffer)
            mElementByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(T));

        ThrowIfFailed(device->CreateCommittedResource(
            &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
            D3D12_HEAP_FLAG_NONE,
            &CD3DX12_RESOURCE_DESC::Buffer(mElementByteSize*elementCount),
			D3D12_RESOURCE_STATE_GENERIC_READ,
            nullptr,
            IID_PPV_ARGS(&mUploadBuffer)));

        ThrowIfFailed(mUploadBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mMappedData)));

        // We do not need to unmap until we are done with the resource.  However, we must not write to
        // the resource while it is in use by the GPU (so we must use synchronization techniques).
    }

    UploadBuffer(const UploadBuffer& rhs) = delete;
    UploadBuffer& operator=(const UploadBuffer& rhs) = delete;
    ~UploadBuffer()
    {
        if(mUploadBuffer != nullptr)
            mUploadBuffer->Unmap(0, nullptr);

        mMappedData = nullptr;
    }

    ID3D12Resource* Resource()const
    {
        return mUploadBuffer.Get();
    }

    void CopyData(int elementIndex, const T& data)
    {
        memcpy(&mMappedData[elementIndex*mElementByteSize], &data, sizeof(T));
    }

private:
    Microsoft::WRL::ComPtr<ID3D12Resource> mUploadBuffer;
    BYTE* mMappedData = nullptr;

    UINT mElementByteSize = 0;
    bool mIsConstantBuffer = false;
};

创建常量缓冲区资源(上传堆中),创建常量缓冲区视图。常量缓冲区视图描述显存中的地址和大小。创建视图需要CPU和GPU访问地址。

void BoxApp::BuildConstantBuffers()
{
	mObjectCB = std::make_unique<UploadBuffer<ObjectConstants>>(md3dDevice.Get(), 1, true);

	UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));

	D3D12_GPU_VIRTUAL_ADDRESS cbAddress = mObjectCB->Resource()->GetGPUVirtualAddress();
    // Offset to the ith object constant buffer in the buffer.
    int boxCBufIndex = 0;
	cbAddress += boxCBufIndex*objCBByteSize;

	D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
	cbvDesc.BufferLocation = cbAddress;
	cbvDesc.SizeInBytes = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));

	md3dDevice->CreateConstantBufferView(
		&cbvDesc,
		mCbvHeap->GetCPUDescriptorHandleForHeapStart());
}

更新常量缓冲区中的数据

void BoxApp::Update(const GameTimer& gt)
{
    // Convert Spherical to Cartesian coordinates.
    float x = mRadius*sinf(mPhi)*cosf(mTheta);
    float z = mRadius*sinf(mPhi)*sinf(mTheta);
    float y = mRadius*cosf(mPhi);

    // Build the view matrix.
    XMVECTOR pos = XMVectorSet(x, y, z, 1.0f);
    XMVECTOR target = XMVectorZero();
    XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

    XMMATRIX view = XMMatrixLookAtLH(pos, target, up);
    XMStoreFloat4x4(&mView, view);

    XMMATRIX world = XMLoadFloat4x4(&mWorld);
    XMMATRIX proj = XMLoadFloat4x4(&mProj);
    XMMATRIX worldViewProj = world*view*proj;

	// Update the constant buffer with the latest worldViewProj matrix.
	ObjectConstants objConstants;
    XMStoreFloat4x4(&objConstants.WorldViewProj, XMMatrixTranspose(worldViewProj));
    mObjectCB->CopyData(0, objConstants);
}

通常使用两种常量缓冲区,一种记录渲染场景需要的数据(如视图矩阵,投影矩阵等公共数据),一种记录场景中物体需要的数据(如世界变换矩阵)。

 6、根签名

根签名描述了着色器程序需要访问资源的描述。绘制命令执行前,绑定到渲染流水线的资源,会被映射到着色器的对应输入寄存器中。 例如顶点和像素着色器需要访问绑定到寄存器b0的常量缓冲区。根签名要与使用它的着色器相兼容。

根签名是一个绑定约定,由应用程序定义,着色器使用它来定位他们需要访问的资源。可以理解为着色器函数的输入参数定义,函数签名。
根签名实际是描述了常量(类似默认参数)、常量缓冲区(CBV)、资源(SRV,纹理)、无序访问缓冲(UAV,随机读写缓冲)、采样器(Sample)等的寄存器(Register)存储规划的一个结构体。同时它还描述了每种资源针对每个阶段Shader的可见性。

根参数

根签名是一个根参数的数组,根参数可以是根常数,根描述符或描述符表。

struct D3D12_ROOT_PARAMETER
{
    D3D12_ROOT_PARAMETER_TYPE ParameterType;
    union 
        {
        D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable;
        D3D12_ROOT_CONSTANTS Constants;
        D3D12_ROOT_DESCRIPTOR Descriptor;
        } ;
    D3D12_SHADER_VISIBILITY ShaderVisibility;
} 

6.1 描述符表

描述符表是在描述符堆中连续的范围。

 struct D3D12_ROOT_DESCRIPTOR_TABLE
{
    UINT NumDescriptorRanges;
    const D3D12_DESCRIPTOR_RANGE *pDescriptorRanges;
}

下面的根参数的第一个元素是描述符表,包括 2 CBVs, 3 SRVs and 1 UAV。

//cbuffer cbA : register(b0) { … };
//cbuffer cbB : register(b1) { … };

//cbuffer cbC : register(t0) { … };
//cbuffer cbD : register(t1) { … };
//cbuffer cbE : register(t2) { … };

//cbuffer cbF : register(u0) { … };
//cbuffer cbG : register(u1) { … };

----------------------------------------------------------------    
D3D12_DESCRIPTOR_RANGE cvbRange[3];

cvbRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
cvbRange[0].NumDescriptors = 2;
cvbRange[0].RegisterSpace = 0;
cvbRange[0].BaseShaderRegister = 0;
cvbRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;//0

cvbRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
cvbRange[1].NumDescriptors = 3;
cvbRange[1].RegisterSpace = 0;
cvbRange[1].BaseShaderRegister = 0;
cvbRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;//2

cvbRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
cvbRange[1].NumDescriptors = 1;
cvbRange[1].RegisterSpace = 0;
cvbRange[1].BaseShaderRegister = 0;
cvbRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;//5

D3D12_ROOT_PARAMETER rootParameter[3];
rootParameter[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
rootParameter[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParameter[0].DescriptorTable.NumDescriptorRanges = 3;
rootParameter[0].DescriptorTable.pDescriptorRanges = cvbRange;

--------------------------------------------------------------------
ID3D12DescriptorHeap* descriptorHeaps[] = { mCbvHeap.Get() };
mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);

mCommandList->SetGraphicsRootSignature(mRootSignature.Get());

mCommandList->SetGraphicsRootDescriptorTable(0, 
mCbvHeap->GetGPUDescriptorHandleForHeapStart()
);

应用程序设置描述符表使用: SetGraphicsRootDescriptorTable  

void BoxApp::BuildRootSignature()
{
	// Shader programs typically require resources as input (constant buffers,
	// textures, samplers).  The root signature defines the resources the shader
	// programs expect.  If we think of the shader programs as a function, and
	// the input resources as function parameters, then the root signature can be
	// thought of as defining the function signature.  

	// Root parameter can be a table, root descriptor or root constants.
	CD3DX12_ROOT_PARAMETER slotRootParameter[1];

	// Create a single descriptor table of CBVs.
	CD3DX12_DESCRIPTOR_RANGE cbvTable;
	cbvTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
	slotRootParameter[0].InitAsDescriptorTable(1, &cbvTable);

	// A root signature is an array of root parameters.
	CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(1, //根参数的数量 
        slotRootParameter, //根参数数组
        0, nullptr, 
		D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

	// create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
	ComPtr<ID3DBlob> serializedRootSig = nullptr;
	ComPtr<ID3DBlob> errorBlob = nullptr;
	HRESULT hr = D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
		serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());

	if(errorBlob != nullptr)
	{
		::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
	}
	ThrowIfFailed(hr);

	ThrowIfFailed(md3dDevice->CreateRootSignature(
		0,
		serializedRootSig->GetBufferPointer(),
		serializedRootSig->GetBufferSize(),
		IID_PPV_ARGS(&mRootSignature)));
}

6.2 根常数

struct D3D12_ROOT_CONSTANTS
{
    UINT ShaderRegister;
    UINT RegisterSpace;
    UINT Num32BitValues;
}

应用程序设置根常数使用 :  SetGraphicsRoot32BitConstants 

cbuffer cbSettings : register(b2)
{
    // We cannot have an array entry in a constant buffer that gets
    // mapped onto root constants, so list each   element.
    int gBlurRadius;
    // Support up to 11 blur weights.
    float w0;
    float w1;
    float w2;
};

rootParameter[2].Constants.RegisterSpace = 0;
rootParameter[2].Constants.ShaderRegister = 0;
rootParameter[2].Constants.Num32BitValues = 4;


// Application code: to set the constants to register b0.
// weights中有三个元素
auto weights = CalcGaussWeights(2.5f);
int blurRadius = (int)weights.size() / 2;

cmdList->SetGraphicsRoot32BitConstants(0, 1,
        &blurRadius, 0);
cmdList->SetGraphicsRoot32BitConstants(0,
        (UINT)weights.size(), weights.data(), 1);

 6.3 根描述符

struct D3D12_ROOT_DESCRIPTOR
{
    UINT ShaderRegister;
    UINT RegisterSpace;
} 

应用程序设置跟描述符使用: SetGraphicsRootConstantBufferView

//cbuffer cbPass : register(b3) { … };

rootParameter[1].Descriptor.RegisterSpace = 0;
rootParameter[1].Descriptor.ShaderRegister = 3;


cmdList->SetGraphicsRootConstantBufferView(
2, // root parameter index
objCBAddress); // 资源的显存地址 D3D12_GPU_VIRTUAL_ADDRESS

7、输入布局

用于验证顶点格式和顶点着色器输入签名是否一致。

//顶点格式,CPU端
struct Vertex
{
    XMFLOAT3 Pos;
    XMFLOAT4 Color;
};    

mInputLayout =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
    };

//作色器语言,GPU端
struct VertexIn
{
	float3 PosL  : POSITION;
    float4 Color : COLOR;
};

8、流水线状态对象

创建流水线状态对象时,需要指定输入补给描述和顶点着色器,D3D会验证两者是否匹配。

验证输入布局描述和顶点着色器输入。输入布局描述一种顶点格式。

验证根签名。根签名可以很复杂,包含很项目。

void BoxApp::BuildPSO()
{
    D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
    ZeroMemory(&psoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
    psoDesc.InputLayout = { mInputLayout.data(), (UINT)mInputLayout.size() };
    psoDesc.pRootSignature = mRootSignature.Get();
    psoDesc.VS = 
	{ 
		reinterpret_cast<BYTE*>(mvsByteCode->GetBufferPointer()), 
		mvsByteCode->GetBufferSize() 
	};
    psoDesc.PS = 
	{ 
		reinterpret_cast<BYTE*>(mpsByteCode->GetBufferPointer()), 
		mpsByteCode->GetBufferSize() 
	};
    psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
    psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
    psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
    psoDesc.SampleMask = UINT_MAX;
    psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
    psoDesc.NumRenderTargets = 1;
    psoDesc.RTVFormats[0] = mBackBufferFormat;
    psoDesc.SampleDesc.Count = m4xMsaaState ? 4 : 1;
    psoDesc.SampleDesc.Quality = m4xMsaaState ? (m4xMsaaQuality - 1) : 0;
    psoDesc.DSVFormat = mDepthStencilFormat;
    ThrowIfFailed(md3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mPSO)));
}

光栅器状态D3D12_RASTERIZER_DESC,定义三角形填充模式,剔除规则等。 

9、顶点和索引缓冲区

9.1 创建资源

GPU资源是D3D12_RESOURCE_DIMENSION_BUFFER类型,通常放到默认堆,设置值时需要使用中介的上传缓冲区。

ID3DBlob类型描述的是一段普通的内存块。

void BoxApp::BuildBoxGeometry()
{
    std::array<Vertex, 8> vertices =
    {
        Vertex({ XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(Colors::White) }),
		Vertex({ XMFLOAT3(-1.0f, +1.0f, -1.0f), XMFLOAT4(Colors::Black) }),
		Vertex({ XMFLOAT3(+1.0f, +1.0f, -1.0f), XMFLOAT4(Colors::Red) }),
		Vertex({ XMFLOAT3(+1.0f, -1.0f, -1.0f), XMFLOAT4(Colors::Green) }),
		Vertex({ XMFLOAT3(-1.0f, -1.0f, +1.0f), XMFLOAT4(Colors::Blue) }),
		Vertex({ XMFLOAT3(-1.0f, +1.0f, +1.0f), XMFLOAT4(Colors::Yellow) }),
		Vertex({ XMFLOAT3(+1.0f, +1.0f, +1.0f), XMFLOAT4(Colors::Cyan) }),
		Vertex({ XMFLOAT3(+1.0f, -1.0f, +1.0f), XMFLOAT4(Colors::Magenta) })
    };

	std::array<std::uint16_t, 36> indices =
	{
		// front face
		0, 1, 2,
		0, 2, 3,

		// back face
		4, 6, 5,
		4, 7, 6,

		// left face
		4, 5, 1,
		4, 1, 0,

		// right face
		3, 2, 6,
		3, 6, 7,

		// top face
		1, 5, 6,
		1, 6, 2,

		// bottom face
		4, 0, 3,
		4, 3, 7
	};

    const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
	const UINT ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);

	mBoxGeo = std::make_unique<MeshGeometry>();
	mBoxGeo->Name = "boxGeo";

	ThrowIfFailed(D3DCreateBlob(vbByteSize, &mBoxGeo->VertexBufferCPU));
	CopyMemory(mBoxGeo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);

	ThrowIfFailed(D3DCreateBlob(ibByteSize, &mBoxGeo->IndexBufferCPU));
	CopyMemory(mBoxGeo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);

	mBoxGeo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
		mCommandList.Get(), vertices.data(), vbByteSize, mBoxGeo->VertexBufferUploader);

	mBoxGeo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
		mCommandList.Get(), indices.data(), ibByteSize, mBoxGeo->IndexBufferUploader);

	mBoxGeo->VertexByteStride = sizeof(Vertex);
	mBoxGeo->VertexBufferByteSize = vbByteSize;
	mBoxGeo->IndexFormat = DXGI_FORMAT_R16_UINT;
	mBoxGeo->IndexBufferByteSize = ibByteSize;

	SubmeshGeometry submesh;
	submesh.IndexCount = (UINT)indices.size();
	submesh.StartIndexLocation = 0;
	submesh.BaseVertexLocation = 0;

	mBoxGeo->DrawArgs["box"] = submesh;
}

 d3dUtil::CreateDefaultBuffer使用上传堆作为中介来创建一个默认堆,并将顶点和索引数据拷贝到默认堆中。

Microsoft::WRL::ComPtr<ID3D12Resource> d3dUtil::CreateDefaultBuffer(
    ID3D12Device* device,
    ID3D12GraphicsCommandList* cmdList,
    const void* initData,
    UINT64 byteSize,
    Microsoft::WRL::ComPtr<ID3D12Resource>& uploadBuffer)
{
    ComPtr<ID3D12Resource> defaultBuffer;

    // Create the actual default buffer resource.
    ThrowIfFailed(device->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize),
		D3D12_RESOURCE_STATE_COMMON,
        nullptr,
        IID_PPV_ARGS(defaultBuffer.GetAddressOf())));

    // In order to copy CPU memory data into our default buffer, we need to create
    // an intermediate upload heap. 
    ThrowIfFailed(device->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
		D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize),
		D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(uploadBuffer.GetAddressOf())));

    // Describe the data we want to copy into the default buffer.
    D3D12_SUBRESOURCE_DATA subResourceData = {};
    subResourceData.pData = initData;
    subResourceData.RowPitch = byteSize;
    subResourceData.SlicePitch = subResourceData.RowPitch;

    // Schedule to copy the data to the default buffer resource.  At a high level, the helper function UpdateSubresources
    // will copy the CPU memory into the intermediate upload heap.  Then, using ID3D12CommandList::CopySubresourceRegion,
    // the intermediate upload heap data will be copied to mBuffer.
	cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(defaultBuffer.Get(), 
		D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
    UpdateSubresources<1>(cmdList, defaultBuffer.Get(), uploadBuffer.Get(), 0, 0, 1, &subResourceData);
	cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(defaultBuffer.Get(),
		D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_GENERIC_READ));

    // Note: uploadBuffer has to be kept alive after the above function calls because
    // the command list has not been executed yet that performs the actual copy.
    // The caller can Release the uploadBuffer after it knows the copy has been executed.

    return defaultBuffer;
}

UpdateSubresources函数来自D3DX12.h,将数据从CPU复制到上传堆,再将上传堆复制到默认堆。 

9.2 创建资源视图

无需创建描述符堆。

	D3D12_VERTEX_BUFFER_VIEW VertexBufferView()const
	{
		D3D12_VERTEX_BUFFER_VIEW vbv;
		vbv.BufferLocation = VertexBufferGPU->GetGPUVirtualAddress();
		vbv.StrideInBytes = VertexByteStride;
		vbv.SizeInBytes = VertexBufferByteSize;

		return vbv;
	}

	D3D12_INDEX_BUFFER_VIEW IndexBufferView()const
	{
		D3D12_INDEX_BUFFER_VIEW ibv;
		ibv.BufferLocation = IndexBufferGPU->GetGPUVirtualAddress();
		ibv.Format = IndexFormat;
		ibv.SizeInBytes = IndexBufferByteSize;

		return ibv;
	}

10、资源状态转换

 资源在创建时指定初始状态,D3D将其转换为另一种状态供GPU使用,转换资源屏障告诉GPU等待状态转换完成再使用资源。

//Transition the resource from its initial state to be used as a depth buffer.
mCommandList->ResourceBarrier(1, 
&CD3DX12_RESOURCE_BARRIER::Transition(mDepthStencilBuffer.Get(),
D3D12_RESOURCE_STATE_COMMON, 
D3D12_RESOURCE_STATE_DEPTH_WRITE)
);

三、渲染

绘制前,设置相关的状态,包括视口,裁剪矩形,后台缓冲区状态转换到渲染状态,清空后备缓冲区和深度模板缓冲区,绑定渲染目标资源、绑定顶点缓冲区和索引缓冲区资源,设置作色器使用资源的描述符堆、根签名,绑定资源。

void BoxApp::Draw(const GameTimer& gt)
{
    // Reuse the memory associated with command recording.
    // We can only reset when the associated command lists have finished execution on the GPU.
	ThrowIfFailed(mDirectCmdListAlloc->Reset());

	// A command list can be reset after it has been added to the command queue via ExecuteCommandList.
    // Reusing the command list reuses memory.
    // 设置流水线状态对象
    ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), mPSO.Get()));

    mCommandList->RSSetViewports(1, &mScreenViewport);
    mCommandList->RSSetScissorRects(1, &mScissorRect);

    // Indicate a state transition on the resource usage.
	mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
		D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));

    // Clear the back buffer and depth buffer.
    mCommandList->ClearRenderTargetView(CurrentBackBufferView(), Colors::LightSteelBlue, 0, nullptr);
    mCommandList->ClearDepthStencilView(DepthStencilView(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
	
    // Specify the buffers we are going to render to.
    // 将后备缓冲区资源绑定到渲染流水线的outputMerget阶段
	mCommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), 
     true, &DepthStencilView());

    //将顶点、索引缓冲区资源绑定到IA阶段
    mCommandList->IASetVertexBuffers(0, 1, &mBoxGeo->VertexBufferView());
    mCommandList->IASetIndexBuffer(&mBoxGeo->IndexBufferView());
    mCommandList->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    //设置描述符堆
	ID3D12DescriptorHeap* descriptorHeaps[] = { mCbvHeap.Get() };
	mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
	//设置根签名
    mCommandList->SetGraphicsRootSignature(mRootSignature.Get());    
    //设置使用根描述符表的第几个根描述符,与根签名对应
    //将描述符表与渲染流水线绑定
    mCommandList->SetGraphicsRootDescriptorTable(0, mCbvHeap->GetGPUDescriptorHandleForHeapStart());
    //资源绑定结束,绘制调用
    mCommandList->DrawIndexedInstanced(
		mBoxGeo->DrawArgs["box"].IndexCount, 
		1, 0, 0, 0);
	
    // Indicate a state transition on the resource usage.
	mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
		D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));

    // Done recording commands.
	ThrowIfFailed(mCommandList->Close());
 
    // Add the command list to the queue for execution.
	ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
	mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
	
	// swap the back and front buffers
	ThrowIfFailed(mSwapChain->Present(0, 0));
	mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;

	// Wait until frame commands are complete.  This waiting is inefficient and is
	// done for simplicity.  Later we will show how to organize our rendering code
	// so we do not have to wait per frame.
	FlushCommandQueue();
}

渲染流水线的各个阶段:输入装配阶段IA, 顶点着色器阶段VS\外壳着色器阶段HS\镶嵌阶段TS\域着色器阶段DS\几何着色器阶段GS(流输出阶段SO)\光栅化阶段RS\像素着色器阶段PS\输出合并器阶段OM。

参考:

DirectX12(D3D12)基础教程(一)——基础教程-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/u014038143/article/details/82730776

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/252561.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

vue实现公式编辑器组件

实现方式一 1、效果图 2、实现代码 组件弹框实现 样式自己调整 公式的数字与汉字元素、符号 建立元素表 动态获取 完整代码&#xff08;calculate.vue&#xff09; <template><div id"formulaPage"><divref"formulaView"class"f…

pyqt5实现振动波形数据标注工具

pyqt5实现振动波形数据标注工具 1、效果图 2、实现功能 1、数据库连接 2、数据筛选 3、波形图展示、频谱图展示 4、特征展示&#xff1a;时域、频域 5、数据标注与添加 6、模型训练与分类识别3、部分核心代码 3.1、连接数据库 # -*- coding: utf-8 -*-""" c…

技术探秘:在RISC Zero中验证FHE——由隐藏到证明:FHE验证的ZK路径(1)

1. 引言 开源代码实现见&#xff1a; https://github.com/hashcloak/fhe_risc0_zkvm&#xff08;Rust&#xff09;https://github.com/weikengchen/vfhe-profiled&#xff08;Rust&#xff09;https://github.com/l2iterative/vfhe0&#xff08;Rust&#xff09; L2IV Resea…

后端开发——统一处理异常Spring MVC机制

一、Spring MVC的统一处理异常机制 在Spring MVC中&#xff0c;存在统一处理异常的机制&#xff0c; 具体表现为&#xff1a;无论是哪个处理请求的过程中出现异常&#xff0c;每种类型的异常只需要编写一段处理异常的代码即可&#xff01; 统一处理异常的核心是定义处理异常的…

【INTEL(ALTERA)】Agilex7 FPGA Development Kit DK-DEV-AGI027R1BES编程/烧录/烧写/下载步骤

DK-DEV-AGI027R1BES 的编程步骤&#xff1a; 将外部 USB Blaster II 连接到 J10- 外部 JTAG 接头。将交换机 SW5.3 设置为 ON&#xff08;首次&#xff09;。打开 英特尔 Quartus Prime Pro Edition 软件编程工具。单击 硬件设置 &#xff0c;然后选择 USB Blaster II。将硬件…

LeetCode - 460 LFU缓存(Java JS Python)

题目来源 460. LFU 缓存 - 力扣&#xff08;LeetCode&#xff09; 题目描述 请你为 最不经常使用&#xff08;LFU&#xff09;缓存算法设计并实现数据结构。 实现 LFUCache 类&#xff1a; LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象int get(int key)…

RocketMQ系统性学习-SpringCloud Alibaba集成RocketMQ以及消息追踪、延时消息实战

文章目录 消息追踪延时消息实战 消息追踪 设置消息追踪需要修改 broker 启动的配置文件&#xff0c;添加一行配置&#xff1a;traceTopicEnabletrue 即可&#xff0c;操作如下&#xff1a; # 进入到 rocketmq 的安装目录中 # 先复制一份配置文件 cp broker.conf custom.conf …

高并发音频转口型服务器开发

课程名称&#xff1a;高并发口型服务器开发 高并发口型服务器 哈喽&#xff0c;大家好&#xff0c;我叫人宅&#xff0c;很高兴和大家一起分享本套课程&#xff0c;高并发口型服务器开发。 虚拟人的口型一直是我们避免不了问题&#xff0c;即使我们不做虚拟人实时口型&#x…

WorkPlus搭建高效即时通讯,打造高效协作新标杆

在现代企业中&#xff0c;即时通讯已成为团队沟通和协作的重要组成部分。作为一款创新的即时通讯工具&#xff0c;WorkPlus致力于提供高效、便捷的沟通和协作体验&#xff0c;打造全新的企业沟通标杆。 WorkPlus的出色之处在于其高效的即时通讯能力。无论是团队内部交流还是跨团…

H266/VVC标准的编码结构介绍

概述 CVS&#xff1a; H266的编码码流包含一个或多个编码视频序列&#xff08;Coded Video Swquence&#xff0c;CVS&#xff09;&#xff0c;每个CVS以帧内随机接入点&#xff08;Intra Random Access Point&#xff0c; IRAP&#xff09;或逐渐解码刷新&#xff08;Gradual …

MySQL 教程 2.2

MySQL WHERE 子句 我们知道从 MySQL 表中使用 SELECT 语句来读取数据。 如需有条件地从表中选取数据&#xff0c;可将 WHERE 子句添加到 SELECT 语句中。 WHERE 子句用于在 MySQL 中过滤查询结果&#xff0c;只返回满足特定条件的行。 语法 以下是 SQL SELECT 语句使用 WH…

项目实战:自动驾驶之方向盘操纵

项目介绍 根据汽车前方摄像头捕捉的画面,控制汽车方向盘转动的方向和角度,这是自动驾驶要解决的核心问题。这个项目主要是通过使用深度神经网络解决一个回归问题。不同于分类、识别场景,回归问题中神经网络输出的是一个连续的值。 通过这个项目的学习,可以将神经网络用于通…

Python开源项目周排行 2023年第40周

Python 趋势周报&#xff0c;按周浏览往期 GitHub,Gitee 等最热门的Python开源项目&#xff0c;入选的项目主要参考GitHub Trending,部分参考了Gitee和其他。排名不分先后&#xff0c;都是当周相对热门的项目。 入选公式&#xff1d;70%GitHub Trending20%Gitee10%其他 关注微…

CSS 的背景属性(开发中常用)

目录 1 内容预览 背景颜色 背景图片 背景平铺 背景图片位置(常用) 背景图像固定 背景复合写法 背景色半透明 实现案例 1 内容预览 背景属性可以设置背景颜色、背景图片、背景平铺、背景图片位置、背景图像固定等。 注意&#xff1a; 把表格中的五个属背下来&#xff0c…

搞懂这6 个持续集成工具,领先80%测试人!

开发人员喜欢把写的代码当成自己的孩子&#xff0c;他们会被当成艺术品一样呵护。作为家长&#xff0c;总是会认为自己的孩子是最好的&#xff0c;也会尽全力给自己的孩子最好的&#xff0c;就算有时候会超出自己的能力范围。 最终&#xff0c;孩子会走出去&#xff0c;和其他…

京东看数据-京东运营数据分析-10月宠物市场销售数据分析(宠物店铺数据查询)

近年来&#xff0c;宠物成为越来越多家庭的成员&#xff0c;宠物数量不断增长&#xff0c;“宠物经济”异军突起&#xff0c;成为消费市场中特殊的存在。“撸猫”“吸狗”正迅速成为人们交际的热门谈资&#xff0c;宠物经济也迈入快速发展阶段。 根据鲸参谋电商数据分析平台的相…

fckeditor编辑器改造示例:增加PRE,CODE控件

查看专栏目录 Network 灰鸽宝典专栏主要关注服务器的配置&#xff0c;前后端开发环境的配置&#xff0c;编辑器的配置&#xff0c;网络服务的配置&#xff0c;网络命令的应用与配置&#xff0c;windows常见问题的解决等。 文章目录 修改方法&#xff1a;1&#xff09;修改fckco…

JS基本语法

JS基本语法 变量数据类型原始数据类型 函数定义第一种方式第二种方式 JS 对象ArrayStringJavaScript 自定义对象JSONDOMBOM JS 事件事件监听事件绑定常见事件 变量 数据类型 原始数据类型 函数定义 第一种方式 第二种方式 JS 对象 Array String JavaScript 自定义对象 JSON …

VR汽车技术服务虚拟仿真实训平台更好地辅助职业上岗培训

VR汽车虚拟仿真教学软件是一种基于虚拟现实技术的教学辅助工具。它能够模拟真实的汽车环境和操作场景&#xff0c;让学生能够通过虚拟仿真来学习和实践汽车相关知识和技能。 与传统的教学方式相比&#xff0c;VR汽车虚拟仿真教学软件具有更高的视觉沉浸感和互动性&#xff0c;能…

19.Tomcat搭建

Tomcat 简介 Tomcat的安装和启动 前置条件 • JDK 已安装(JAVA_HOME环境变量已被成功配置) Windows 下安装 访问 http://tomcat.apache.org ⇒ 左侧边栏 “Download” 2. 解压缩下载的文件到 “D:\tomcat”, tomcat的内容最终被解压到 “D:\tomcat\apache-tomcat-9.0.84” 3.…