当前位置: 首页>>代码示例>>C++>>正文


C++ ComPtr类代码示例

本文整理汇总了C++中ComPtr的典型用法代码示例。如果您正苦于以下问题:C++ ComPtr类的具体用法?C++ ComPtr怎么用?C++ ComPtr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ComPtr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: defined

// Load the rendering pipeline dependencies.
void D3D12ExecuteIndirect::LoadPipeline()
{
#if defined(_DEBUG)
	// Enable the D3D12 debug layer.
	{
		ComPtr<ID3D12Debug> debugController;
		if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
		{
			debugController->EnableDebugLayer();
		}
	}
#endif

	ComPtr<IDXGIFactory4> factory;
	ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));

	if (m_useWarpDevice)
	{
		ComPtr<IDXGIAdapter> warpAdapter;
		ThrowIfFailed(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));

		ThrowIfFailed(D3D12CreateDevice(
			warpAdapter.Get(),
			D3D_FEATURE_LEVEL_11_0,
			IID_PPV_ARGS(&m_device)
			));
	}
	else
	{
		ComPtr<IDXGIAdapter1> hardwareAdapter;
		GetHardwareAdapter(factory.Get(), &hardwareAdapter);

		ThrowIfFailed(D3D12CreateDevice(
			hardwareAdapter.Get(),
			D3D_FEATURE_LEVEL_11_0,
			IID_PPV_ARGS(&m_device)
			));
	}

	// Describe and create the command queues.
	D3D12_COMMAND_QUEUE_DESC queueDesc = {};
	queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
	queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;

	ThrowIfFailed(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue)));
	NAME_D3D12_OBJECT(m_commandQueue);

	D3D12_COMMAND_QUEUE_DESC computeQueueDesc = {};
	computeQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
	computeQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;

	ThrowIfFailed(m_device->CreateCommandQueue(&computeQueueDesc, IID_PPV_ARGS(&m_computeCommandQueue)));
	NAME_D3D12_OBJECT(m_computeCommandQueue);

	// Describe and create the swap chain.
	DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
	swapChainDesc.BufferCount = FrameCount;
	swapChainDesc.Width = m_width;
	swapChainDesc.Height = m_height;
	swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
	swapChainDesc.SampleDesc.Count = 1;

	ComPtr<IDXGISwapChain1> swapChain;
	ThrowIfFailed(factory->CreateSwapChainForCoreWindow(
		m_commandQueue.Get(),		// Swap chain needs the queue so that it can force a flush on it.
		reinterpret_cast<IUnknown*>(Windows::UI::Core::CoreWindow::GetForCurrentThread()),
		&swapChainDesc,
		nullptr,
		&swapChain
		));

	ThrowIfFailed(swapChain.As(&m_swapChain));
	m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();

	// Create descriptor heaps.
	{
		// Describe and create a render target view (RTV) descriptor heap.
		D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
		rtvHeapDesc.NumDescriptors = FrameCount;
		rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
		rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
		ThrowIfFailed(m_device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_rtvHeap)));

		// Describe and create a depth stencil view (DSV) descriptor heap.
		D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
		dsvHeapDesc.NumDescriptors = 1;
		dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
		dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
		ThrowIfFailed(m_device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&m_dsvHeap)));

		// Describe and create a constant buffer view (CBV), Shader resource
		// view (SRV), and unordered access view (UAV) descriptor heap.
		D3D12_DESCRIPTOR_HEAP_DESC cbvSrvUavHeapDesc = {};
		cbvSrvUavHeapDesc.NumDescriptors = CbvSrvUavDescriptorCountPerFrame * FrameCount;
		cbvSrvUavHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
		cbvSrvUavHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
		ThrowIfFailed(m_device->CreateDescriptorHeap(&cbvSrvUavHeapDesc, IID_PPV_ARGS(&m_cbvSrvUavHeap)));
//.........这里部分代码省略.........
开发者ID:LH8888,项目名称:DirectX-Graphics-Samples,代码行数:101,代码来源:D3D12ExecuteIndirect.cpp

示例2: listNetworkInterfaces

/**
 * List network interfaces information (bridged/host only).
 *
 * @returns See produceList.
 * @param   pVirtualBox         Reference to the IVirtualBox smart pointer.
 * @param   fIsBridged          Selects between listing host interfaces (for
 *                              use with bridging) or host only interfaces.
 */
static HRESULT listNetworkInterfaces(const ComPtr<IVirtualBox> pVirtualBox,
                                     bool fIsBridged)
{
    HRESULT rc;
    ComPtr<IHost> host;
    CHECK_ERROR(pVirtualBox, COMGETTER(Host)(host.asOutParam()));
    com::SafeIfaceArray<IHostNetworkInterface> hostNetworkInterfaces;
#if defined(VBOX_WITH_NETFLT)
    if (fIsBridged)
        CHECK_ERROR(host, FindHostNetworkInterfacesOfType(HostNetworkInterfaceType_Bridged,
                                                          ComSafeArrayAsOutParam(hostNetworkInterfaces)));
    else
        CHECK_ERROR(host, FindHostNetworkInterfacesOfType(HostNetworkInterfaceType_HostOnly,
                                                          ComSafeArrayAsOutParam(hostNetworkInterfaces)));
#else
    CHECK_ERROR(host, COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(hostNetworkInterfaces)));
#endif
    for (size_t i = 0; i < hostNetworkInterfaces.size(); ++i)
    {
        ComPtr<IHostNetworkInterface> networkInterface = hostNetworkInterfaces[i];
#ifndef VBOX_WITH_HOSTNETIF_API
        Bstr interfaceName;
        networkInterface->COMGETTER(Name)(interfaceName.asOutParam());
        RTPrintf("Name:        %ls\n", interfaceName.raw());
        Guid interfaceGuid;
        networkInterface->COMGETTER(Id)(interfaceGuid.asOutParam());
        RTPrintf("GUID:        %ls\n\n", Bstr(interfaceGuid.toString()).raw());
#else /* VBOX_WITH_HOSTNETIF_API */
        Bstr interfaceName;
        networkInterface->COMGETTER(Name)(interfaceName.asOutParam());
        RTPrintf("Name:            %ls\n", interfaceName.raw());
        Bstr interfaceGuid;
        networkInterface->COMGETTER(Id)(interfaceGuid.asOutParam());
        RTPrintf("GUID:            %ls\n", interfaceGuid.raw());
        BOOL bDHCPEnabled;
        networkInterface->COMGETTER(DHCPEnabled)(&bDHCPEnabled);
        RTPrintf("DHCP:            %s\n", bDHCPEnabled ? "Enabled" : "Disabled");

        Bstr IPAddress;
        networkInterface->COMGETTER(IPAddress)(IPAddress.asOutParam());
        RTPrintf("IPAddress:       %ls\n", IPAddress.raw());
        Bstr NetworkMask;
        networkInterface->COMGETTER(NetworkMask)(NetworkMask.asOutParam());
        RTPrintf("NetworkMask:     %ls\n", NetworkMask.raw());
        Bstr IPV6Address;
        networkInterface->COMGETTER(IPV6Address)(IPV6Address.asOutParam());
        RTPrintf("IPV6Address:     %ls\n", IPV6Address.raw());
        ULONG IPV6NetworkMaskPrefixLength;
        networkInterface->COMGETTER(IPV6NetworkMaskPrefixLength)(&IPV6NetworkMaskPrefixLength);
        RTPrintf("IPV6NetworkMaskPrefixLength: %d\n", IPV6NetworkMaskPrefixLength);
        Bstr HardwareAddress;
        networkInterface->COMGETTER(HardwareAddress)(HardwareAddress.asOutParam());
        RTPrintf("HardwareAddress: %ls\n", HardwareAddress.raw());
        HostNetworkInterfaceMediumType_T Type;
        networkInterface->COMGETTER(MediumType)(&Type);
        RTPrintf("MediumType:      %s\n", getHostIfMediumTypeText(Type));
        HostNetworkInterfaceStatus_T Status;
        networkInterface->COMGETTER(Status)(&Status);
        RTPrintf("Status:          %s\n", getHostIfStatusText(Status));
        Bstr netName;
        networkInterface->COMGETTER(NetworkName)(netName.asOutParam());
        RTPrintf("VBoxNetworkName: %ls\n\n", netName.raw());
#endif
    }
    return rc;
}
开发者ID:eaas-framework,项目名称:virtualbox,代码行数:74,代码来源:VBoxManageList.cpp

示例3: listUsbHost

/**
 * List USB devices attached to the host.
 *
 * @returns See produceList.
 * @param   pVirtualBox         Reference to the IVirtualBox smart pointer.
 */
static HRESULT listUsbHost(const ComPtr<IVirtualBox> &pVirtualBox)
{
    HRESULT rc;
    ComPtr<IHost> Host;
    CHECK_ERROR_RET(pVirtualBox, COMGETTER(Host)(Host.asOutParam()), 1);

    SafeIfaceArray<IHostUSBDevice> CollPtr;
    CHECK_ERROR_RET(Host, COMGETTER(USBDevices)(ComSafeArrayAsOutParam(CollPtr)), 1);

    RTPrintf("Host USB Devices:\n\n");

    if (CollPtr.size() == 0)
    {
        RTPrintf("<none>\n\n");
    }
    else
    {
        for (size_t i = 0; i < CollPtr.size(); ++i)
        {
            ComPtr<IHostUSBDevice> dev = CollPtr[i];

            /* Query info. */
            Bstr id;
            CHECK_ERROR_RET(dev, COMGETTER(Id)(id.asOutParam()), 1);
            USHORT usVendorId;
            CHECK_ERROR_RET(dev, COMGETTER(VendorId)(&usVendorId), 1);
            USHORT usProductId;
            CHECK_ERROR_RET(dev, COMGETTER(ProductId)(&usProductId), 1);
            USHORT bcdRevision;
            CHECK_ERROR_RET(dev, COMGETTER(Revision)(&bcdRevision), 1);
            USHORT usPort;
            CHECK_ERROR_RET(dev, COMGETTER(Port)(&usPort), 1);
            USHORT usVersion;
            CHECK_ERROR_RET(dev, COMGETTER(Version)(&usVersion), 1);
            USHORT usPortVersion;
            CHECK_ERROR_RET(dev, COMGETTER(PortVersion)(&usPortVersion), 1);

            RTPrintf("UUID:               %s\n"
                     "VendorId:           %#06x (%04X)\n"
                     "ProductId:          %#06x (%04X)\n"
                     "Revision:           %u.%u (%02u%02u)\n"
                     "Port:               %u\n"
                     "USB version/speed:  %u/%u\n",
                     Utf8Str(id).c_str(),
                     usVendorId, usVendorId, usProductId, usProductId,
                     bcdRevision >> 8, bcdRevision & 0xff,
                     bcdRevision >> 8, bcdRevision & 0xff,
                     usPort, usVersion, usPortVersion);

            /* optional stuff. */
            Bstr bstr;
            CHECK_ERROR_RET(dev, COMGETTER(Manufacturer)(bstr.asOutParam()), 1);
            if (!bstr.isEmpty())
                RTPrintf("Manufacturer:       %ls\n", bstr.raw());
            CHECK_ERROR_RET(dev, COMGETTER(Product)(bstr.asOutParam()), 1);
            if (!bstr.isEmpty())
                RTPrintf("Product:            %ls\n", bstr.raw());
            CHECK_ERROR_RET(dev, COMGETTER(SerialNumber)(bstr.asOutParam()), 1);
            if (!bstr.isEmpty())
                RTPrintf("SerialNumber:       %ls\n", bstr.raw());
            CHECK_ERROR_RET(dev, COMGETTER(Address)(bstr.asOutParam()), 1);
            if (!bstr.isEmpty())
                RTPrintf("Address:            %ls\n", bstr.raw());

            /* current state  */
            USBDeviceState_T state;
            CHECK_ERROR_RET(dev, COMGETTER(State)(&state), 1);
            const char *pszState = "?";
            switch (state)
            {
                case USBDeviceState_NotSupported:
                    pszState = "Not supported";
                    break;
                case USBDeviceState_Unavailable:
                    pszState = "Unavailable";
                    break;
                case USBDeviceState_Busy:
                    pszState = "Busy";
                    break;
                case USBDeviceState_Available:
                    pszState = "Available";
                    break;
                case USBDeviceState_Held:
                    pszState = "Held";
                    break;
                case USBDeviceState_Captured:
                    pszState = "Captured";
                    break;
                default:
                    ASSERT(false);
                    break;
            }
            RTPrintf("Current State:      %s\n\n", pszState);
        }
//.........这里部分代码省略.........
开发者ID:eaas-framework,项目名称:virtualbox,代码行数:101,代码来源:VBoxManageList.cpp

示例4: ProcessFrame

void FrameMixer::ProcessFrame(ID3D11Device *pDevice, ID3D11Texture2D *pInput, UINT uiInIndex, ID3D11Texture2D *pOutput, UINT uiOutIndex)
{
    ComPtr<ID3D11DeviceContext> spd3dImmediateContext;

    // Render targets
    ComPtr<ID3D11RenderTargetView> rgpOrigRTV;
    ComPtr<ID3D11DepthStencilView> pOrigDSV;
    ComPtr<ID3D11RenderTargetView> spRTV;

    // Shader resources
    ComPtr<ID3D11ShaderResourceView> rgpOrigSRV;
    ComPtr<ID3D11ShaderResourceView> spSRV;

    // Vertex buffers
    ID3D11Buffer *pBuffers[1] = { m_spScreenQuadVB.Get() };
    UINT vbStrides = sizeof( ScreenVertex );
    UINT vbOffsets = 0;

    // Samplers
    ID3D11SamplerState *pSamplers[1] = { m_spSampleStateLinear.Get() };

    // View port
    D3D11_VIEWPORT vpOld[D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX];
    UINT nViewPorts = 1;
    D3D11_VIEWPORT vp;

    // Transition parameter;
    TransitionParameter parameter = m_transition_parameter;

    // Get the context
    pDevice->GetImmediateContext(&spd3dImmediateContext);
   
    // Get the resource views
    ThrowIfError(CreateShaderInputView(pInput, uiInIndex, pDevice, &spSRV));

    ThrowIfError(CreateShaderOutputView(pOutput, uiOutIndex, pDevice, &spRTV));

    // Setup the Draw call
    spd3dImmediateContext->IASetInputLayout(m_spQuadLayout.Get());

    spd3dImmediateContext->IASetVertexBuffers(0, 1, pBuffers, &vbStrides, &vbOffsets);

    spd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

    spd3dImmediateContext->PSSetSamplers(0, 1, pSamplers);

    spd3dImmediateContext->OMGetRenderTargets(1, &rgpOrigRTV, &pOrigDSV);

    const FLOAT background_color[4] = { parameter.m_backgound_color[0],
                                        parameter.m_backgound_color[1],
                                        parameter.m_backgound_color[2],
                                        parameter.m_backgound_color[3] };

    if (parameter.m_draw_background)
    {
        spd3dImmediateContext->ClearRenderTargetView(spRTV.Get(), background_color);
    }

    spd3dImmediateContext->OMSetRenderTargets(1, spRTV.GetAddressOf(), nullptr);

    // apply transform and fading
    XMStoreFloat4x4(
        &m_vsTransformBufferData.transform,
        XMMatrixTranspose(XMMatrixTranslation(parameter.m_offset_x, parameter.m_offset_y, parameter.m_offset_z) *
        XMMatrixScaling(parameter.m_scaling_x, parameter.m_scaling_y, 1.0))
        );

    m_psFadingBufferData.fading = parameter.m_fading_ratio;

    spd3dImmediateContext->UpdateSubresource(m_vsTransformBuffer.Get(), 0, nullptr, &m_vsTransformBufferData, 0, 0);
    spd3dImmediateContext->UpdateSubresource(m_psFadingBuffer.Get(), 0, nullptr, &m_psFadingBufferData, 0, 0);
    //

    spd3dImmediateContext->PSGetShaderResources(0, 1, &rgpOrigSRV);

    spd3dImmediateContext->PSSetShaderResources(0, 1, spSRV.GetAddressOf());

    spd3dImmediateContext->RSGetViewports(&nViewPorts, vpOld);

    // Setup the viewport to match the backbuffer
    vp.Width = (float)m_uiWidth;
    vp.Height = (float)m_uiHeight;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0.0f;
    vp.TopLeftY = 0.0f;

    spd3dImmediateContext->RSSetViewports(1, &vp);

    spd3dImmediateContext->VSSetShader(m_spVertexShader.Get(), nullptr, 0);

    // Set the vertex shader constant buffer data.
    spd3dImmediateContext->VSSetConstantBuffers(0, 1, m_vsTransformBuffer.GetAddressOf());

    spd3dImmediateContext->PSSetShader(m_spPixelShader.Get(), nullptr, 0);

    // Set the pixel shader constant buffer data.
    spd3dImmediateContext->PSSetConstantBuffers(0, 1, m_psFadingBuffer.GetAddressOf());

    UINT sampleMask = 0xffffffff;
//.........这里部分代码省略.........
开发者ID:ashfaq-uddin,项目名称:TransitionEffect,代码行数:101,代码来源:FrameMixer.cpp

示例5: Startup

TESTENV_API BOOL WINAPI Startup(HINSTANCE hInstance, HWND hWnd) {
	HRESULT lastHR = CreateDXGIFactory2(NULL, IID_PPV_ARGS(m_dxgiFactory.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("CreateDXGIFactory2"), lastHR);

	ComPtr<IDXGIAdapter> adapter;

	lastHR = m_dxgiFactory->EnumAdapters(0, adapter.GetAddressOf());
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("DXGIAdapter - EnumAdapters"), lastHR);

	lastHR = D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(m_dxDevice.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("D3D12CreateDevice"), lastHR);

	lastHR = m_dxDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(m_cmdAllocator.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("ID3D12Device - CreateCommandAllocator"), lastHR);

	D3D12_COMMAND_QUEUE_DESC descCommandQueue;
	ZeroMemory(&descCommandQueue, sizeof(descCommandQueue));
	descCommandQueue.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
	descCommandQueue.Priority = 0;
	descCommandQueue.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;

	lastHR = m_dxDevice->CreateCommandQueue(&descCommandQueue, IID_PPV_ARGS(m_cmdQueue.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("ID3D12Device - CreateCommandQueue"), lastHR);

	m_hFenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	lastHR = m_dxDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(m_queueFence.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("ID3D12Device - CreateFence"), lastHR);

	DXGI_SWAP_CHAIN_DESC descSwapChain;
	ZeroMemory(&descSwapChain, sizeof(descSwapChain));
	descSwapChain.BufferCount = 2;
	descSwapChain.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	descSwapChain.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	descSwapChain.OutputWindow = hWnd;
	descSwapChain.SampleDesc.Count = 1;
	descSwapChain.Windowed = TRUE;
	descSwapChain.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
	descSwapChain.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	lastHR = m_dxgiFactory->CreateSwapChain(m_cmdQueue.Get(), &descSwapChain, (IDXGISwapChain**)m_swapChain.GetAddressOf());
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("IDXGIFactory3 - CreateSwapChain"), lastHR);

	lastHR = m_dxDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_cmdAllocator.Get(), nullptr, IID_PPV_ARGS(m_cmdList.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("ID3D12Device - CreateCommandList"), lastHR);

	D3D12_DESCRIPTOR_HEAP_DESC descHeap;
	ZeroMemory(&descHeap, sizeof(descHeap));
	descHeap.NumDescriptors = 2;
	descHeap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
	descHeap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

	lastHR = m_dxDevice->CreateDescriptorHeap(&descHeap, IID_PPV_ARGS(m_descriptorHeapRTV.GetAddressOf()));
	if (FAILED(lastHR))
		return ShowErrorMessage(MB_ICONERROR, TEXT("ID3D12Device - CreateDescriptorHeap"), lastHR);

	UINT strideHandleBytes = m_dxDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
	for (UINT i = 0; i < descSwapChain.BufferCount; ++i) {
		lastHR = m_swapChain->GetBuffer(i, IID_PPV_ARGS(m_renderTarget[i].GetAddressOf()));
		if (FAILED(lastHR))
			return ShowErrorMessage(MB_ICONERROR, TEXT("IDXGISwapChain3 - GetBuffer"), lastHR);

		m_handleRTV[i] = m_descriptorHeapRTV->GetCPUDescriptorHandleForHeapStart();
		m_handleRTV[i].ptr += i * strideHandleBytes;
		m_dxDevice->CreateRenderTargetView(m_renderTarget[i].Get(), nullptr, m_handleRTV[i]);
	}

	RECT wndRect;
	GetWindowRect(hWnd, &wndRect);
	Resize(wndRect.right - wndRect.left, wndRect.bottom - wndRect.top);

	m_viewport.TopLeftX = 0;
	m_viewport.TopLeftY = 0;

	m_viewport.MinDepth = 0;
	m_viewport.MaxDepth = 1;

	return TRUE;
}
开发者ID:ChunHungLiu,项目名称:Test-Environment,代码行数:87,代码来源:main.cpp

示例6: renderTargetDesc

// Allocate all memory resources that depend on the window size.
void Direct3DBase::CreateWindowSizeDependentResources()
{
	// Create a descriptor for the render target buffer.
	CD3D11_TEXTURE2D_DESC renderTargetDesc(
		DXGI_FORMAT_B8G8R8A8_UNORM,
		static_cast<UINT>(m_renderTargetSize.Width),
		static_cast<UINT>(m_renderTargetSize.Height),
		1,
		1,
		D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE
		);
	renderTargetDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;

	// Allocate a 2-D surface as the render target buffer.
	DX::ThrowIfFailed(
		m_d3dDevice->CreateTexture2D(
			&renderTargetDesc,
			nullptr,
			&m_renderTarget
			)
		);

	DX::ThrowIfFailed(
		m_d3dDevice->CreateRenderTargetView(
			m_renderTarget.Get(),
			nullptr,
			&m_renderTargetView
			)
		);

	// Create a depth stencil view.
	CD3D11_TEXTURE2D_DESC depthStencilDesc(
		DXGI_FORMAT_D24_UNORM_S8_UINT,
		static_cast<UINT>(m_renderTargetSize.Width),
		static_cast<UINT>(m_renderTargetSize.Height),
		1,
		1,
		D3D11_BIND_DEPTH_STENCIL
		);

	ComPtr<ID3D11Texture2D> depthStencil;
	DX::ThrowIfFailed(
		m_d3dDevice->CreateTexture2D(
			&depthStencilDesc,
			nullptr,
			&depthStencil
			)
		);

	CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
	DX::ThrowIfFailed(
		m_d3dDevice->CreateDepthStencilView(
			depthStencil.Get(),
			&depthStencilViewDesc,
			&m_depthStencilView
			)
		);

	// Set the rendering viewport to target the entire window.
	CD3D11_VIEWPORT viewport(
		0.0f,
		0.0f,
		m_renderTargetSize.Width,
		m_renderTargetSize.Height
		);

	m_viewport = viewport;
	m_d3dContext->RSSetViewports(1, &viewport);
}
开发者ID:Mengke-Yuan,项目名称:stereo,代码行数:70,代码来源:Direct3DBase.cpp

示例7: ThrowIfFailed

// Load the sample assets.
void D3D1211on12::LoadAssets()
{
	// Create an empty root signature.
	{
		CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
		rootSignatureDesc.Init(0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

		ComPtr<ID3DBlob> signature;
		ComPtr<ID3DBlob> error;
		ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
		ThrowIfFailed(m_d3d12Device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature)));
		NAME_D3D12_OBJECT(m_rootSignature);
	}

	// Create the pipeline state, which includes compiling and loading shaders.
	{
		ComPtr<ID3DBlob> vertexShader;
		ComPtr<ID3DBlob> pixelShader;

#if defined(_DEBUG)
		// Enable better shader debugging with the graphics debugging tools.
		UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
		UINT compileFlags = 0;
#endif

		ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "VSMain", "vs_5_0", compileFlags, 0, &vertexShader, nullptr));
		ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "PSMain", "ps_5_0", compileFlags, 0, &pixelShader, nullptr));

		// Define the vertex input layout.
		D3D12_INPUT_ELEMENT_DESC inputElementDescs[] =
		{
			{ "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 }
		};

		// Describe and create the graphics pipeline state object (PSO).
		D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
		psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
		psoDesc.pRootSignature = m_rootSignature.Get();
		psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader.Get());
		psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader.Get());
		psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
		psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
		psoDesc.DepthStencilState.DepthEnable = FALSE;
		psoDesc.DepthStencilState.StencilEnable = FALSE;
		psoDesc.SampleMask = UINT_MAX;
		psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
		psoDesc.NumRenderTargets = 1;
		psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
		psoDesc.SampleDesc.Count = 1;

		ThrowIfFailed(m_d3d12Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState)));
		NAME_D3D12_OBJECT(m_pipelineState);
	}

	ThrowIfFailed(m_d3d12Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocators[m_frameIndex].Get(), m_pipelineState.Get(), IID_PPV_ARGS(&m_commandList)));
	NAME_D3D12_OBJECT(m_commandList);

	// Create D2D/DWrite objects for rendering text.
	{
		ThrowIfFailed(m_d2dDeviceContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_textBrush));
		ThrowIfFailed(m_dWriteFactory->CreateTextFormat(
			L"Verdana",
			NULL,
			DWRITE_FONT_WEIGHT_NORMAL,
			DWRITE_FONT_STYLE_NORMAL,
			DWRITE_FONT_STRETCH_NORMAL,
			50,
			L"en-us",
			&m_textFormat
			));
		ThrowIfFailed(m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER));
		ThrowIfFailed(m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER));
	}

	// Note: ComPtr's are CPU objects but this resource needs to stay in scope until
	// the command list that references it has finished executing on the GPU.
	// We will flush the GPU at the end of this method to ensure the resource is not
	// prematurely destroyed.
	ComPtr<ID3D12Resource> vertexBufferUpload;

	// Create the vertex buffer.
	{
		// Define the geometry for a triangle.
		Vertex triangleVertices[] =
		{
			{ { 0.0f, 0.25f * m_aspectRatio, 0.0f }, { 1.0f, 0.0f, 0.0f, 1.0f } },
			{ { 0.25f, -0.25f * m_aspectRatio, 0.0f }, { 0.0f, 1.0f, 0.0f, 1.0f } },
			{ { -0.25f, -0.25f * m_aspectRatio, 0.0f }, { 0.0f, 0.0f, 1.0f, 1.0f } }
		};

		const UINT vertexBufferSize = sizeof(triangleVertices);

		ThrowIfFailed(m_d3d12Device->CreateCommittedResource(
			&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
			D3D12_HEAP_FLAG_NONE,
			&CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
			D3D12_RESOURCE_STATE_COPY_DEST,
//.........这里部分代码省略.........
开发者ID:prabindh,项目名称:DirectX-Graphics-Samples,代码行数:101,代码来源:D3D1211On12.cpp

示例8: defined

// Load the rendering pipeline dependencies.
void D3D12HelloTexture::LoadPipeline()
{
#if defined(_DEBUG)
	// Enable the D3D12 debug layer.
	{
		ComPtr<ID3D12Debug> debugController;
		if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
		{
			debugController->EnableDebugLayer();
		}
	}
#endif

	ComPtr<IDXGIFactory4> factory;
	ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));

	if (m_useWarpDevice)
	{
		ComPtr<IDXGIAdapter> warpAdapter;
		ThrowIfFailed(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));

		ThrowIfFailed(D3D12CreateDevice(
			warpAdapter.Get(),
			D3D_FEATURE_LEVEL_11_0,
			IID_PPV_ARGS(&m_device)
			));
	}
	else
	{
		ComPtr<IDXGIAdapter1> hardwareAdapter;
		GetHardwareAdapter(factory.Get(), &hardwareAdapter);

		ThrowIfFailed(D3D12CreateDevice(
			hardwareAdapter.Get(),
			D3D_FEATURE_LEVEL_11_0,
			IID_PPV_ARGS(&m_device)
			));
	}

	// Describe and create the command queue.
	D3D12_COMMAND_QUEUE_DESC queueDesc = {};
	queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
	queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;

	ThrowIfFailed(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue)));

	// Describe and create the swap chain.
	DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
	swapChainDesc.BufferCount = FrameCount;
	swapChainDesc.Width = m_width;
	swapChainDesc.Height = m_height;
	swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
	swapChainDesc.SampleDesc.Count = 1;

	ComPtr<IDXGISwapChain1> swapChain;
	ThrowIfFailed(factory->CreateSwapChainForHwnd(
		m_commandQueue.Get(),		// Swap chain needs the queue so that it can force a flush on it.
		Win32Application::GetHwnd(),
		&swapChainDesc,
		nullptr,
		nullptr,
		&swapChain
		));

	// This sample does not support fullscreen transitions.
	ThrowIfFailed(factory->MakeWindowAssociation(Win32Application::GetHwnd(), DXGI_MWA_NO_ALT_ENTER));

	ThrowIfFailed(swapChain.As(&m_swapChain));
	m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();

	// Create descriptor heaps.
	{
		// Describe and create a render target view (RTV) descriptor heap.
		D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
		rtvHeapDesc.NumDescriptors = FrameCount;
		rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
		rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
		ThrowIfFailed(m_device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_rtvHeap)));

		// Describe and create a shader resource view (SRV) heap for the texture.
		D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
		srvHeapDesc.NumDescriptors = 1;
		srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
		srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
		ThrowIfFailed(m_device->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&m_srvHeap)));

		m_rtvDescriptorSize = m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
	}

	// Create frame resources.
	{
		CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());

		// Create a RTV for each frame.
		for (UINT n = 0; n < FrameCount; n++)
		{
			ThrowIfFailed(m_swapChain->GetBuffer(n, IID_PPV_ARGS(&m_renderTargets[n])));
//.........这里部分代码省略.........
开发者ID:AhmedSaid,项目名称:DirectX-Graphics-Samples,代码行数:101,代码来源:D3D12HelloTexture.cpp

示例9: get_xinput_devices

	//-----------------------------------------------------------------------------
	// Enum each PNP device using WMI and check each device ID to see if it contains
	// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it's an XInput device
	// Unfortunately this information can not be found by just using DirectInput.
	// Checking against a VID/PID of 0x028E/0x045E won't find 3rd party or future
	// XInput devices.
	//-----------------------------------------------------------------------------
	HRESULT get_xinput_devices(std::list<DWORD> &xinput_id_list) const
	{
		ComPtr<IWbemServices> pIWbemServices;
		ComPtr<IEnumWbemClassObject> pEnumDevices;
		ComPtr<IWbemLocator> pIWbemLocator;
		ComArray<IWbemClassObject> pDevices(20);
		bstr_ptr bstrDeviceID;
		bstr_ptr bstrClassName;
		bstr_ptr bstrNamespace;
		DWORD uReturned = 0;
		UINT iDevice;
		variant_wrapper var;
		HRESULT hr;

		// CoInit if needed
		CoInitialize(nullptr);

		// Create WMI
		hr = CoCreateInstance(
			__uuidof(WbemLocator),
			nullptr,
			CLSCTX_INPROC_SERVER,
			__uuidof(IWbemLocator),
			reinterpret_cast<void**>(pIWbemLocator.GetAddressOf()));

		if (FAILED(hr) || pIWbemLocator == nullptr)
		{
			osd_printf_error("Creating WbemLocator failed. Error: 0x%X\n", static_cast<unsigned int>(hr));
			return hr;
		}

		// Create BSTRs for WMI
		bstrNamespace = bstr_ptr(SysAllocString(L"\\\\.\\root\\cimv2"));
		bstrDeviceID = bstr_ptr(SysAllocString(L"DeviceID"));
		bstrClassName = bstr_ptr(SysAllocString(L"Win32_PNPEntity"));

		// Connect to WMI
		hr = pIWbemLocator->ConnectServer(
			bstrNamespace.get(),
			nullptr,
			nullptr,
			nullptr,
			0L,
			nullptr,
			nullptr,
			pIWbemServices.GetAddressOf());

		if (FAILED(hr) || pIWbemServices == nullptr)
		{
			osd_printf_error("Connecting to WMI Server failed. Error: 0x%X\n", static_cast<unsigned int>(hr));
			return hr;
		}

		// Switch security level to IMPERSONATE
		(void)CoSetProxyBlanket(
			pIWbemServices.Get(),
			RPC_C_AUTHN_WINNT,
			RPC_C_AUTHZ_NONE,
			nullptr,
			RPC_C_AUTHN_LEVEL_CALL,
			RPC_C_IMP_LEVEL_IMPERSONATE,
			nullptr,
			0);

		// Get list of Win32_PNPEntity devices
		hr = pIWbemServices->CreateInstanceEnum(bstrClassName.get(), 0, nullptr, pEnumDevices.GetAddressOf());
		if (FAILED(hr) || pEnumDevices == nullptr)
		{
			osd_printf_error("Getting list of Win32_PNPEntity devices failed. Error: 0x%X\n", static_cast<unsigned int>(hr));
			return hr;
		}

		// Loop over all devices
		for (; ; )
		{
			// Get a few at a time
			hr = pEnumDevices->Next(10000, pDevices.Size(), pDevices.ReleaseAndGetAddressOf(), &uReturned);
			if (FAILED(hr))
			{
				osd_printf_error("Enumerating WMI classes failed. Error: 0x%X\n", static_cast<unsigned int>(hr));
				return hr;
			}

			if (uReturned == 0)
				break;

			for (iDevice = 0; iDevice < uReturned; iDevice++)
			{
				if (!pDevices[iDevice])
					continue;

				// For each device, get its device ID
				hr = pDevices[iDevice]->Get(bstrDeviceID.get(), 0L, var.ClearAndGetAddressOf(), nullptr, nullptr);
//.........这里部分代码省略.........
开发者ID:MASHinfo,项目名称:mame,代码行数:101,代码来源:input_winhybrid.cpp

示例10: Q_UNUSED

bool QWinRTMessageDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent)
{
    Q_UNUSED(windowFlags)
    Q_UNUSED(windowModality)
    Q_UNUSED(parent)
    Q_D(QWinRTMessageDialogHelper);

    QSharedPointer<QMessageDialogOptions> options = this->options();
    const QString informativeText = options->informativeText();
    const QString title = options->windowTitle();
    const QString text = informativeText.isEmpty() ? options->text() : (options->text() + QLatin1Char('\n') + informativeText);

    HRESULT hr;
    ComPtr<IMessageDialogFactory> dialogFactory;
    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Popups_MessageDialog).Get(),
                                IID_PPV_ARGS(&dialogFactory));
    RETURN_FALSE_IF_FAILED("Failed to create dialog factory");

    ComPtr<IUICommandFactory> commandFactory;
    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_UI_Popups_UICommand).Get(),
                                IID_PPV_ARGS(&commandFactory));
    RETURN_FALSE_IF_FAILED("Failed to create command factory");

    ComPtr<IMessageDialog> dialog;
    HStringReference nativeText(reinterpret_cast<LPCWSTR>(text.utf16()), text.size());
    if (!title.isEmpty()) {
        HStringReference nativeTitle(reinterpret_cast<LPCWSTR>(title.utf16()), title.size());
        hr = dialogFactory->CreateWithTitle(nativeText.Get(), nativeTitle.Get(), &dialog);
        RETURN_FALSE_IF_FAILED("Failed to create dialog with title");
    } else {
        hr = dialogFactory->Create(nativeText.Get(), &dialog);
        RETURN_FALSE_IF_FAILED("Failed to create dialog");
    }

    // Add Buttons
    ComPtr<IVector<IUICommand *>> dialogCommands;
    hr = dialog->get_Commands(&dialogCommands);
    RETURN_FALSE_IF_FAILED("Failed to get dialog commands");

    // If no button is specified we need to create one to get close notification
    int buttons = options->standardButtons();
    if (buttons == 0)
        buttons = Ok;

    for (int i = FirstButton; i < LastButton; i<<=1) {
        if (!(buttons & i))
            continue;
        // Add native command
        const QString label = d->theme->standardButtonText(i);
        HStringReference nativeLabel(reinterpret_cast<LPCWSTR>(label.utf16()), label.size());
        ComPtr<IUICommand> command;
        hr = commandFactory->Create(nativeLabel.Get(), &command);
        RETURN_FALSE_IF_FAILED("Failed to create message box command");
        ComPtr<IInspectable> id = Make<CommandId>(static_cast<StandardButton>(i));
        hr = command->put_Id(id.Get());
        RETURN_FALSE_IF_FAILED("Failed to set command ID");
        hr = dialogCommands->Append(command.Get());
        if (hr == E_BOUNDS) {
            qErrnoWarning(hr, "The WinRT message dialog supports a maximum of three buttons");
            continue;
        }
        RETURN_FALSE_IF_FAILED("Failed to append message box command");
        if (i == Abort || i == Cancel || i == Close) {
            quint32 size;
            hr = dialogCommands->get_Size(&size);
            RETURN_FALSE_IF_FAILED("Failed to get command list size");
            hr = dialog->put_CancelCommandIndex(size - 1);
            RETURN_FALSE_IF_FAILED("Failed to set cancel index");
        }
    }

    ComPtr<IAsyncOperation<IUICommand *>> op;
    hr = dialog->ShowAsync(&op);
    RETURN_FALSE_IF_FAILED("Failed to show dialog");
    hr = op->put_Completed(Callback<DialogCompletedHandler>(this, &QWinRTMessageDialogHelper::onCompleted).Get());
    RETURN_FALSE_IF_FAILED("Failed to set dialog callback");

    d->shown = true;
    hr = op.As(&d->info);
    RETURN_FALSE_IF_FAILED("Failed to acquire AsyncInfo for MessageDialog");

    return true;
}
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:83,代码来源:qwinrtmessagedialoghelper.cpp

示例11: ThrowIfFailed

// Load the sample assets.
void D3D12HelloTexture::LoadAssets()
{
	// Create the root signature.
	{
		CD3DX12_DESCRIPTOR_RANGE ranges[1];
		ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);

		CD3DX12_ROOT_PARAMETER rootParameters[1];
		rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_PIXEL);

		D3D12_STATIC_SAMPLER_DESC sampler = {};
		sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
		sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
		sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
		sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
		sampler.MipLODBias = 0;
		sampler.MaxAnisotropy = 0;
		sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
		sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
		sampler.MinLOD = 0.0f;
		sampler.MaxLOD = D3D12_FLOAT32_MAX;
		sampler.ShaderRegister = 0;
		sampler.RegisterSpace = 0;
		sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

		CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
		rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

		ComPtr<ID3DBlob> signature;
		ComPtr<ID3DBlob> error;
		ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
		ThrowIfFailed(m_device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature)));
	}

	// Create the pipeline state, which includes compiling and loading shaders.
	{
		ComPtr<ID3DBlob> vertexShader;
		ComPtr<ID3DBlob> pixelShader;

#if defined(_DEBUG)
		// Enable better shader debugging with the graphics debugging tools.
		UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
		UINT compileFlags = 0;
#endif

		ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "VSMain", "vs_5_0", compileFlags, 0, &vertexShader, nullptr));
		ThrowIfFailed(D3DCompileFromFile(GetAssetFullPath(L"shaders.hlsl").c_str(), nullptr, nullptr, "PSMain", "ps_5_0", compileFlags, 0, &pixelShader, nullptr));

		// Define the vertex input layout.
		D3D12_INPUT_ELEMENT_DESC inputElementDescs[] =
		{
			{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
			{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
		};

		// Describe and create the graphics pipeline state object (PSO).
		D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
		psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
		psoDesc.pRootSignature = m_rootSignature.Get();
		psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader.Get());
		psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader.Get());
		psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
		psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
		psoDesc.DepthStencilState.DepthEnable = FALSE;
		psoDesc.DepthStencilState.StencilEnable = FALSE;
		psoDesc.SampleMask = UINT_MAX;
		psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
		psoDesc.NumRenderTargets = 1;
		psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
		psoDesc.SampleDesc.Count = 1;
		ThrowIfFailed(m_device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState)));
	}

	// Create the command list.
	ThrowIfFailed(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocator.Get(), m_pipelineState.Get(), IID_PPV_ARGS(&m_commandList)));

	// Create the vertex buffer.
	{
		// Define the geometry for a triangle.
		Vertex triangleVertices[] =
		{
			{ { 0.0f, 0.25f * m_aspectRatio, 0.0f }, { 0.5f, 0.0f } },
			{ { 0.25f, -0.25f * m_aspectRatio, 0.0f }, { 1.0f, 1.0f } },
			{ { -0.25f, -0.25f * m_aspectRatio, 0.0f }, { 0.0f, 1.0f } }
		};

		const UINT vertexBufferSize = sizeof(triangleVertices);

		// Note: using upload heaps to transfer static data like vert buffers is not 
		// recommended. Every time the GPU needs it, the upload heap will be marshalled 
		// over. Please read up on Default Heap usage. An upload heap is used here for 
		// code simplicity and because there are very few verts to actually transfer.
		ThrowIfFailed(m_device->CreateCommittedResource(
			&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
			D3D12_HEAP_FLAG_NONE,
			&CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
			D3D12_RESOURCE_STATE_GENERIC_READ,
			nullptr,
//.........这里部分代码省略.........
开发者ID:AhmedSaid,项目名称:DirectX-Graphics-Samples,代码行数:101,代码来源:D3D12HelloTexture.cpp

示例12: float

Impl::World::World(const float(&terrainXform)[4][3])// : bvh(Hierarchy::SplitTechnique::MEAN, .5f)
{
	extern ComPtr<ID3D12Device2> device;

	// create terrain root signature
	{
		CD3DX12_ROOT_PARAMETER1 CBV_params[2];
		CBV_params[0].InitAsConstantBufferView(0, 0, D3D12_ROOT_DESCRIPTOR_FLAG_NONE, D3D12_SHADER_VISIBILITY_VERTEX);
		CBV_params[1].InitAsConstants(3, 0, 1, D3D12_SHADER_VISIBILITY_PIXEL);
		const CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC sigDesc(2, CBV_params, 0, NULL, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
		ComPtr<ID3DBlob> sig, error;
		const HRESULT hr = D3D12SerializeVersionedRootSignature(&sigDesc, &sig, &error);
		if (error)
		{
			cerr.write((const char *)error->GetBufferPointer(), error->GetBufferSize()) << endl;
		}
		CheckHR(hr);
		CheckHR(device->CreateRootSignature(0, sig->GetBufferPointer(), sig->GetBufferSize(), IID_PPV_ARGS(&terrainVectorLayerRootSig)));
	}

	// create terrain PSO
	{
		const CD3DX12_RASTERIZER_DESC rasterDesc
		(
			D3D12_FILL_MODE_SOLID,
			D3D12_CULL_MODE_NONE,
			FALSE,										// front CCW
			D3D12_DEFAULT_DEPTH_BIAS,
			D3D12_DEFAULT_DEPTH_BIAS_CLAMP,
			D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS,
			TRUE,										// depth clip
			FALSE,										// MSAA
			FALSE,										// AA line
			0,											// force sample count
			D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF
		);

		const CD3DX12_DEPTH_STENCIL_DESC dsDesc
		(
			FALSE,																								// depth
			D3D12_DEPTH_WRITE_MASK_ZERO,
			D3D12_COMPARISON_FUNC_ALWAYS,
			FALSE,																								// stencil
			D3D12_DEFAULT_STENCIL_READ_MASK,
			D3D12_DEFAULT_STENCIL_WRITE_MASK,
			D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS,	// front
			D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS	// back
		);

		const D3D12_INPUT_ELEMENT_DESC VB_decl[] =
		{
			{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
		};

		D3D12_GRAPHICS_PIPELINE_STATE_DESC PSO_desc =
		{
			terrainVectorLayerRootSig.Get(),								// root signature
			CD3DX12_SHADER_BYTECODE(vectorLayerVS, sizeof vectorLayerVS),	// VS
			CD3DX12_SHADER_BYTECODE(vectorLayerPS, sizeof vectorLayerPS),	// PS
			{},																// DS
			{},																// HS
			{},																// GS
			{},																// SO
			CD3DX12_BLEND_DESC(D3D12_DEFAULT),								// blend
			UINT_MAX,														// sample mask
			rasterDesc,														// rasterizer
			dsDesc,															// depth stencil
			{ VB_decl, size(VB_decl) },										// IA
			D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED,					// restart primtive
			D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,							// primitive topology
			1,																// render targets
			{ DXGI_FORMAT_R8G8B8A8_UNORM },									// RT formats
			DXGI_FORMAT_UNKNOWN,											// depth stencil format
			{1}																// MSAA
		};

		CheckHR(device->CreateGraphicsPipelineState(&PSO_desc, IID_PPV_ARGS(&terrainVectorLayerPSO)));
	}

	// create terrain CB
	{
		// create buffer
		CheckHR(device->CreateCommittedResource(
			&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
			D3D12_HEAP_FLAG_NONE,
			&CD3DX12_RESOURCE_DESC::Buffer(terrainCB_storeSize * CB_overlap/*, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE*/),
			D3D12_RESOURCE_STATE_GENERIC_READ,
			NULL,	// clear value
			IID_PPV_ARGS(&terrainCB)));

#if PERSISTENT_MAPS
		// map buffer
		const CD3DX12_RANGE readRange(0, 0);
		CheckHR(terrainCB->Map(0, &readRange, const_cast<void **>(&terrainCB_CPU_ptr)));
#endif
	}

	memcpy(this->terrainXform, terrainXform, sizeof terrainXform);
}
开发者ID:DGLE-HQ,项目名称:DWinDirect,代码行数:99,代码来源:world.cpp

示例13: ThrowIfFailed

// Load the rendering pipeline dependencies.
void DX12ClothSimulation::LoadPipeline()
{
#ifdef _DEBUG
	// Enable the D3D12 debug layer.
{
	ComPtr<ID3D12Debug> debugController;
	if ( SUCCEEDED( D3D12GetDebugInterface( IID_PPV_ARGS( &debugController ) ) ) )
	{
		debugController->EnableDebugLayer();
	}
}
#endif

ComPtr<IDXGIFactory4> factory;
ThrowIfFailed( CreateDXGIFactory1( IID_PPV_ARGS( &factory ) ) );

if ( m_useWarpDevice )
{
	ComPtr<IDXGIAdapter> warpAdapter;
	ThrowIfFailed( factory->EnumWarpAdapter( IID_PPV_ARGS( &warpAdapter ) ) );

	ThrowIfFailed( D3D12CreateDevice(
		warpAdapter.Get(),
		D3D_FEATURE_LEVEL_11_0,
		IID_PPV_ARGS( &m_device )
		) );
}
else
{
	ComPtr<IDXGIAdapter1> hardwareAdapter;
	GetHardwareAdapter( factory.Get(), &hardwareAdapter );

	ThrowIfFailed( D3D12CreateDevice(
		hardwareAdapter.Get(),
		D3D_FEATURE_LEVEL_11_0,
		IID_PPV_ARGS( &m_device )
		) );
}

// Describe and create the command queue.
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;

ThrowIfFailed( m_device->CreateCommandQueue( &queueDesc, IID_PPV_ARGS( &m_commandQueue ) ) );

// Describe and create the swap chain.
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferCount = FrameCount;
swapChainDesc.BufferDesc.Width = m_width;
swapChainDesc.BufferDesc.Height = m_height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.OutputWindow = m_hwnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.Windowed = TRUE;

ComPtr<IDXGISwapChain> swapChain;
ThrowIfFailed( factory->CreateSwapChain(
	m_commandQueue.Get(),		// Swap chain needs the queue so that it can force a flush on it.
	&swapChainDesc,
	&swapChain
	) );

ThrowIfFailed( swapChain.As( &m_swapChain ) );

m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();

// Create descriptor heaps.
{
	// Describe and create a render target view (RTV) descriptor heap.
	D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
	rtvHeapDesc.NumDescriptors = FrameCount;
	rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
	rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
	ThrowIfFailed( m_device->CreateDescriptorHeap( &rtvHeapDesc, IID_PPV_ARGS( &m_rtvHeap ) ) );

	m_rtvDescriptorSize = m_device->GetDescriptorHandleIncrementSize( D3D12_DESCRIPTOR_HEAP_TYPE_RTV );
}

// Create a command allocator for each frame.
for ( UINT n = 0; n < FrameCount; n++ )
{
	ThrowIfFailed( m_device->CreateCommandAllocator( D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS( &m_commandAllocators[n] ) ) );
}
}
开发者ID:pengliu916,项目名称:DX12ClothSimulation,代码行数:88,代码来源:DX12ClothSimulation.cpp

示例14: ZeroMemory

void DXBitmap::Initialize()
{
	// CreateDeviceIndependentResources
    D2D1_FACTORY_OPTIONS options;
    ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));

#if defined(_DEBUG)
     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
    options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif

    DX::ThrowIfFailed(
        D2D1CreateFactory(
            D2D1_FACTORY_TYPE_SINGLE_THREADED, 
            __uuidof(ID2D1Factory1),
            &options, 
            &m_d2dFactory
            )
        );

    DX::ThrowIfFailed(
        DWriteCreateFactory(
            DWRITE_FACTORY_TYPE_SHARED,
            __uuidof(IDWriteFactory),
            &m_dwriteFactory
            )
        );

	DX::ThrowIfFailed(
        CoCreateInstance(
            CLSID_WICImagingFactory,
            nullptr,
            CLSCTX_INPROC_SERVER,
            IID_PPV_ARGS(&m_wicFactory)
            )
        );


    // This flag adds support for surfaces with a different color channel ordering than the API default.
    // It is recommended usage, and is required for compatibility with Direct2D.
    UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

#if defined(_DEBUG)
    // If the project is in a debug build, enable debugging via SDK Layers with this flag.
    creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    // This array defines the set of DirectX hardware feature levels this app will support.
    // Note the ordering should be preserved.
    // Don't forget to declare your application's minimum required feature level in its
    // description.  All applications are assumed to support 9.1 unless otherwise stated.
    D3D_FEATURE_LEVEL featureLevels[] = 
    {
        D3D_FEATURE_LEVEL_11_1,
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_2,
        D3D_FEATURE_LEVEL_9_1
    };

    // Create the DX11 API device object, and get a corresponding context.
    ComPtr<ID3D11Device> d3dDevice;
    ComPtr<ID3D11DeviceContext> d3dContext;
    DX::ThrowIfFailed(
        D3D11CreateDevice(
            nullptr,                  // specify null to use the default adapter
            D3D_DRIVER_TYPE_HARDWARE,
            nullptr,                  // leave as nullptr unless software device
            creationFlags,            // optionally set debug and Direct2D compatibility flags
            featureLevels,            // list of feature levels this app can support
            ARRAYSIZE(featureLevels), // number of entries in above list
            D3D11_SDK_VERSION,        // always set this to D3D11_SDK_VERSION for modern
            &d3dDevice,               // returns the Direct3D device created
            &m_featureLevel,          // returns feature level of device created
            &d3dContext               // returns the device immediate context
            )
        );

    // Get the DirectX11.1 device by QI off the DirectX11 one.
    DX::ThrowIfFailed(
        d3dDevice.As(&m_d3dDevice)
        );

    // And get the corresponding device context in the same way.
    DX::ThrowIfFailed(
        d3dContext.As(&m_d3dContext)
        );

    // Obtain the underlying DXGI device of the Direct3D11.1 device.
    ComPtr<IDXGIDevice> dxgiDevice;
    DX::ThrowIfFailed(
        m_d3dDevice.As(&dxgiDevice)
        );

    // Obtain the Direct2D device for 2D rendering.
    DX::ThrowIfFailed(
        m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
        );
//.........这里部分代码省略.........
开发者ID:moonmile,项目名称:win8,代码行数:101,代码来源:WinRTComponent.cpp

示例15: SetAppropriateEvent

//
// Copies dirty rectangles
//
bool ScreenProcessor::ProcessDirty(ComPtr<ID3D11Texture2D> sourceSurface, ComPtr<ID3D11Texture2D> sharedSurface, RECT* dirtyRects, unsigned int dirtyCount, int offsetX, int offsetY, const DXGI_OUTPUT_DESC& desktopDescription)
{
	HRESULT hr;

	D3D11_TEXTURE2D_DESC sharedDescription;
	sharedSurface->GetDesc(&sharedDescription);

	D3D11_TEXTURE2D_DESC sourceDescription;
	sourceSurface->GetDesc(&sourceDescription);

	// Make sure we have a render target view
	if (!m_RTV)
	{
		hr = m_Device->CreateRenderTargetView(sharedSurface.Get(), nullptr, &m_RTV);
		if (FAILED(hr))
		{
			SetAppropriateEvent(hr, SystemTransitionsExpectedErrors, m_ExpectedErrorEvent, m_UnexpectedErrorEvent);
			return false;
		}
	}
	
	// Create a shader resource view for the source
	D3D11_SHADER_RESOURCE_VIEW_DESC shaderDesc;
	shaderDesc.Format = sourceDescription.Format;
	shaderDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	shaderDesc.Texture2D.MostDetailedMip = sourceDescription.MipLevels - 1;
	shaderDesc.Texture2D.MipLevels = sourceDescription.MipLevels;

	ComPtr<ID3D11ShaderResourceView> shaderResource = nullptr;
	hr = m_Device->CreateShaderResourceView(sourceSurface.Get(), &shaderDesc, &shaderResource);
	if (FAILED(hr))
	{
		SetAppropriateEvent(hr, SystemTransitionsExpectedErrors, m_ExpectedErrorEvent, m_UnexpectedErrorEvent);
		return false;
	}

	// Set up shader / blending states
	FLOAT blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
	m_DeviceContext->OMSetBlendState(nullptr, blendFactor, 0xFFFFFFFF);
	m_DeviceContext->OMSetRenderTargets(1, m_RTV.GetAddressOf(), nullptr);
	m_DeviceContext->VSSetShader(m_VertexShader.Get(), nullptr, 0);
	m_DeviceContext->PSSetShader(m_PixelShader.Get(), nullptr, 0);
	m_DeviceContext->PSSetShaderResources(0, 1, shaderResource.GetAddressOf());
	m_DeviceContext->PSSetSamplers(0, 1, m_SamplerLinear.GetAddressOf());
	m_DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Create space for vertices for the dirty rects if the current space isn't large enough
	// 2 triangles per rect = 6 verts
	unsigned int numVerticesPerRect = 6;
	unsigned int numVertices = numVerticesPerRect * dirtyCount;
	if (numVertices == 0)
	{
		return true;
	}
	if (m_DirtyRectVertices.size() < numVertices)
	{
		m_DirtyRectVertices.resize(numVertices);
	}

	// Fill them in
	Vertex* vertex = &m_DirtyRectVertices[0];
	for (unsigned int rectIndex = 0; rectIndex < dirtyCount; ++rectIndex, vertex += numVerticesPerRect)
	{
		BuildDirtyVerts(vertex, dirtyRects[rectIndex], offsetX, offsetY, desktopDescription, sharedDescription, sourceDescription);
	}

	// Create vertex buffer
	D3D11_BUFFER_DESC bufferDesc;
	RtlZeroMemory(&bufferDesc, sizeof(bufferDesc));
	bufferDesc.Usage = D3D11_USAGE_DEFAULT;
	bufferDesc.ByteWidth = numVertices * sizeof(Vertex);
	bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bufferDesc.CPUAccessFlags = 0;

	D3D11_SUBRESOURCE_DATA initData;
	RtlZeroMemory(&initData, sizeof(initData));
	initData.pSysMem = &m_DirtyRectVertices[0];

	ComPtr<ID3D11Buffer> vertexBuffer = nullptr;
	hr = m_Device->CreateBuffer(&bufferDesc, &initData, &vertexBuffer);
	if (FAILED(hr))
	{
		SetAppropriateEvent(hr, SystemTransitionsExpectedErrors, m_ExpectedErrorEvent, m_UnexpectedErrorEvent);
		return false;
	}
	unsigned int stride = sizeof(Vertex);
	unsigned int offset = 0;
	m_DeviceContext->IASetVertexBuffers(0, 1, vertexBuffer.GetAddressOf(), &stride, &offset);

	// Setup the viewport
	D3D11_VIEWPORT viewport;
	viewport.Width = static_cast<FLOAT>(sharedDescription.Width);
	viewport.Height = static_cast<FLOAT>(sharedDescription.Height);
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;
//.........这里部分代码省略.........
开发者ID:f8k8,项目名称:Lights,代码行数:101,代码来源:ScreenProcessor.cpp


注:本文中的ComPtr类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。