Example #1
1
//========================================================================
// Initialize hardware for rendering. Member of AbstractRender
//========================================================================
HRESULT DX10Render::initDevice()
{
	UINT createDeviceFlags = 0;
	#ifdef _DEBUG
		createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
	#endif

	HRESULT hr = D3D10CreateDevice(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &this->device);
	if (FAILED(hr)) return hr;

	DXGI_SWAP_CHAIN_DESC sd;
	ZeroMemory(&sd, sizeof(sd));
	sd.BufferCount = 1;
	sd.BufferDesc.Width  = this->resolution.width;
	sd.BufferDesc.Height = this->resolution.height;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.RefreshRate.Numerator   = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.OutputWindow       = this->hWindow;
	sd.SampleDesc.Count   = 4;
	sd.SampleDesc.Quality = 4;
	sd.Windowed = !this->fullscreen;

	IDXGIFactory *factory = getDeviceFactory(device);
	if (factory == NULL) return E_FAIL;

	hr = factory->CreateSwapChain(device, &sd, &swapChain);
	if (FAILED(hr)) return hr;

	factory->Release();

	return S_OK;
}
/*
* Class:     org_lwjgl_d3d11_impl_DXGIFactoryImpl
* Method:    nCreateSwapChain
* Signature: (JJJJ)J
*/
extern "C" JNIEXPORT jlong JNICALL Java_org_lwjgl_d3d11_impl_DXGIFactoryImpl_nCreateSwapChain
(JNIEnv * env, jclass clazz, jlong thisPtr, jlong devicePtr, jlong swapChainDescPtr, jlong swapChainOutPtr) {
    IDXGIFactory* factory = (IDXGIFactory*)(intptr_t)thisPtr;
    IUnknown* device = (IUnknown*)(intptr_t)devicePtr;
    DXGI_SWAP_CHAIN_DESC* swapChainDesc = (DXGI_SWAP_CHAIN_DESC*)(intptr_t)swapChainDescPtr;
    IDXGISwapChain** swapChain = (IDXGISwapChain**)(intptr_t)swapChainOutPtr;
    return (jlong)factory->CreateSwapChain(device, swapChainDesc, swapChain);
}
	void D3D11RenderWindow::_createSwapChain()
	{
		// Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain.

		DXGI_SWAP_CHAIN_DESC sd;
		sd.BufferDesc.Width = mWidth;
		sd.BufferDesc.Height = mHeight;
		sd.BufferDesc.RefreshRate.Numerator = 60;
		sd.BufferDesc.RefreshRate.Denominator = 1;
		sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
		sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

		// Use 4X MSAA?
		if (mEnable4xMsaa)
		{
			sd.SampleDesc.Count = 4;
			sd.SampleDesc.Quality = m4xMsaaQuality - 1;
		}
		// No MSAA
		else
		{
			sd.SampleDesc.Count = 1;
			sd.SampleDesc.Quality = 0;
		}

		sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		sd.BufferCount = 2;
		sd.OutputWindow = mhMainWnd;
		sd.Windowed = true;
		sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
		sd.Flags = 0;

		// To correctly create the swap chain, we must use the IDXGIFactory that was
		// used to create the device.  If we tried to use a different IDXGIFactory instance
		// (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain:
		// This function is being called with a device from a different IDXGIFactory."

		IDXGIDevice* dxgiDevice = 0;
		HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice));

		IDXGIAdapter* dxgiAdapter = 0;
		HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));

		IDXGIFactory* dxgiFactory = 0;
		HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory));

		HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain));

		ReleaseCOM(dxgiDevice);
		ReleaseCOM(dxgiAdapter);
		ReleaseCOM(dxgiFactory);

		// The remaining steps that need to be carried out for d3d creation
		// also need to be executed every time the window is resized.  So
		// just call the OnResize method here to avoid code duplication.

		_updateSwapChain();
	}
Example #4
0
	void D3DContext::InitD3D(HWND hWnd)
	{
		m_MSAAEnabled = true;

		HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, m_DebugLayerEnabled ? D3D11_CREATE_DEVICE_DEBUG : D3D11_CREATE_DEVICE_SINGLETHREADED, NULL, NULL, D3D11_SDK_VERSION, &dev, &m_D3DFeatureLevel, &devcon);
		dev->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_MSAAQuality);
		// assert(m_MSAAQuality > 0);

		DXGI_SWAP_CHAIN_DESC scd;
		ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

		scd.BufferDesc.Width = m_Properties.width;
		scd.BufferDesc.Height = m_Properties.height;
		scd.BufferDesc.RefreshRate.Numerator = 60;
		scd.BufferDesc.RefreshRate.Denominator = 1;
		scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

		scd.SampleDesc.Count = m_MSAAEnabled ? 4 : 1;
		scd.SampleDesc.Quality = m_MSAAEnabled ? (m_MSAAQuality - 1) : 0;

		scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		scd.BufferCount = 3;
		scd.OutputWindow = hWnd;
		scd.Windowed = !m_Properties.fullscreen;
		scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
		scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

		IDXGIDevice* dxgiDevice = 0;
		IDXGIAdapter* dxgiAdapter = 0;
		IDXGIFactory* dxgiFactory = 0;

		dev->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
		dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);
		dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);
		dxgiFactory->CreateSwapChain(dev, &scd, &swapchain);

		dxgiFactory->Release();
		dxgiAdapter->Release();
		dxgiDevice->Release();

		if (m_DebugLayerEnabled)
		{
			dev->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&m_DebugLayer));
			m_DebugLayer->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY);

			ID3D11InfoQueue* infoQueue;
			dev->QueryInterface(__uuidof(ID3D11InfoQueue), reinterpret_cast<void**>(&infoQueue));
			D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET };
			D3D11_INFO_QUEUE_FILTER filter;
			memset(&filter, 0, sizeof(filter));
			filter.DenyList.NumIDs = 1;
			filter.DenyList.pIDList = hide;
			infoQueue->AddStorageFilterEntries(&filter);
		}

		Resize();
	}
bool TRenderDevice::CreateSwapChain(){
	IDXGIDevice* device;
	if (FAILED(Device->QueryInterface(__uuidof(IDXGIDevice), (void**) &device))){
		MessageBox(0,L"获取设备接口失败",0,0);
		return false;
	}
	
	IDXGIAdapter* adapter;
	if (FAILED(device->GetParent(__uuidof(IDXGIAdapter), (void**) &adapter))){
		MessageBox(0,L"获取适配器接口失败",0,0);
		return false;
	}
	
	IDXGIFactory* factory;
	if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory), (void**) &factory))){
		MessageBox(0,L"获取Factory接口失败",0,0);
		return false;
	}
	
	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width                   = RenderSize->GetRenderWidth();
	sd.BufferDesc.Height                  = RenderSize->GetRenderHeight();
	sd.BufferDesc.RefreshRate.Numerator   = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format                  = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering        = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling                 = DXGI_MODE_SCALING_UNSPECIFIED;
	
	if (MsaaQuality>0){
		sd.SampleDesc.Count = MsaaQuality;
		sd.SampleDesc.Quality = MsaaQuality - 1;
	}else{
		sd.SampleDesc.Count=1;
		sd.SampleDesc.Quality=0;
	}
	
	sd.BufferUsage  = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount  = 1;
	sd.OutputWindow = RenderWindow->GetHWnd();
	sd.Windowed     = true;
	sd.SwapEffect   = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags        = 0;
	
	if (FAILED(factory->CreateSwapChain(Device, &sd, &SwapChain))){
		MessageBox(0,L"创建SwapChain失败",0,0);
		return false;
	}
	
	device->Release();
	adapter->Release();
	factory->Release();
	
	return true;
}
Example #6
0
EGLint SwapChain11Api::createSwapChain(
    int backbufferWidth, int backbufferHeight, IDXGISwapChain **outSwapChain)
{
    // We cannot create a swap chain for an HWND that is owned by a
    // different process
    DWORD currentProcessId = GetCurrentProcessId();
    DWORD wndProcessId;
    GetWindowThreadProcessId((HWND)mWindow, &wndProcessId);

    if (currentProcessId != wndProcessId)
    {
        ERR("Could not create swap chain, window owned by different process");
        return EGL_BAD_NATIVE_WINDOW;
    }

    ID3D11Device *device = getRenderer()->getDevice();
    IDXGIFactory *factory = getRenderer()->getDxgiFactory();
    DXGI_FORMAT format = gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat);

    DXGI_SWAP_CHAIN_DESC swapChainDesc = {0};
    swapChainDesc.BufferCount = 2;
    swapChainDesc.BufferDesc.Format = format;
    swapChainDesc.BufferDesc.Width = backbufferWidth;
    swapChainDesc.BufferDesc.Height = backbufferHeight;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.Flags = 0;
    swapChainDesc.OutputWindow = mWindow;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;
    swapChainDesc.Windowed = TRUE;

    IDXGISwapChain *swapChain;
    HRESULT result = factory->CreateSwapChain(device, &swapChainDesc, &swapChain);

    if (SUCCEEDED(result))
    {
        *outSwapChain = swapChain;
        d3d11::ResourceTracker::Track(swapChain);
        return EGL_SUCCESS;
    }
    else
    {
        if (d3d11::isDeviceLostError(result))
            return EGL_CONTEXT_LOST;
        else
            return EGL_BAD_ALLOC;
    }
}
Example #7
0
//*************************************************************************************************
// Create the swap chain for the device
//*************************************************************************************************
SBOOL RenderContext::createSwapChain(HWND clientWindow, SUINT clientWidth, SUINT clientHeight)
{
	// Fill out DXGI swap chain description
	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width = clientWidth;
	sd.BufferDesc.Height = clientHeight;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Use 4x Msaa
	if(_4xMsaaEnabled)
	{
		sd.SampleDesc.Count = 4;
		sd.SampleDesc.Quality = _4xMsaaQuality - 1;
	}

	// No Msaa
	else
	{
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
	}

	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount = 1;
	sd.OutputWindow = clientWindow;
	sd.Windowed = true;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags = 0;

	// Generate an IDXGI factory to properly initialize the swap chain
	IDXGIDevice* dxgiDevice = 0;
	HR(_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice));

	IDXGIAdapter* dxgiAdapter = 0;
	HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));

	IDXGIFactory* dxgiFactory = 0;
	HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory));

	HR(dxgiFactory->CreateSwapChain(_d3dDevice, &sd, &_swapChain));

	ReleaseCOM(dxgiDevice);
	ReleaseCOM(dxgiAdapter);
	ReleaseCOM(dxgiFactory);	

	return true;
}
Example #8
0
        std::shared_ptr<SwapChain> Device::createSwapChain(const Window& window)
        {
            std::shared_ptr<SwapChain> swapChain;

            IDXGIDevice* dxgiDevice = nullptr;
            if (SUCCEEDED(m_device->QueryInterface<IDXGIDevice>(&dxgiDevice)))
            {
                IDXGIAdapter* adapter = nullptr;
                if (SUCCEEDED(dxgiDevice->GetAdapter(&adapter)))
                {
                    IDXGIFactory* dxgiFactory = nullptr;
                    if (SUCCEEDED(adapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory))))
                    {
                        DXGI_SWAP_CHAIN_DESC sd;
                        ZeroMemory(&sd, sizeof(sd));
                        sd.BufferCount = 1;
                        sd.BufferDesc.Width = window.getWidth();
                        sd.BufferDesc.Height = window.getHeight();
                        sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
                        sd.BufferDesc.RefreshRate.Numerator = 0;
                        sd.BufferDesc.RefreshRate.Denominator = 1;
                        sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
                        sd.OutputWindow = window.getPlatformData()->getHandle();
                        sd.SampleDesc.Count = 1;
                        sd.SampleDesc.Quality = 0;
                        sd.Windowed = TRUE;
                        IDXGISwapChain* nativeSwapChain = nullptr;
                        if (SUCCEEDED(dxgiFactory->CreateSwapChain(m_device, &sd, &nativeSwapChain)))
                        {
                            ID3D11Texture2D* backBufferTexture = nullptr;
                            if (SUCCEEDED(nativeSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBufferTexture))))
                            {
                                auto texture = std::make_shared<Texture2d>(backBufferTexture);
                                auto backBufferRenderCommandEncoder = createRenderCommandEncoder(1, &texture, nullptr, false);
                                swapChain = std::make_shared<SwapChain>(nativeSwapChain, backBufferRenderCommandEncoder);
                            }

                            dxgiFactory->Release();
                        }

                        adapter->Release();
                    }
                }

                dxgiDevice->Release();
            }

            return swapChain;
        }
Example #9
0
HRESULT STDMETHODCALLTYPE CDXGIFactoryDWM::CreateSwapChain(IUnknown *pDevice, DXGI_SWAP_CHAIN_DESC *pDesc, IDXGIOutput *pOutput, IDXGISwapChainDWM **ppSwapChain)
{
    IDXGISwapChain *pSwapChain = NULL;
    if (retrace::forceWindowed) {
        pDesc->Windowed = TRUE;
    }
    HRESULT hr = m_pFactory->CreateSwapChain(pDevice, pDesc, &pSwapChain);
    if (SUCCEEDED(hr)) {
        if (!retrace::forceWindowed) {
            pSwapChain->SetFullscreenState(TRUE, pOutput);
        }
        *ppSwapChain = new CDXGISwapChainDWM(pSwapChain);
    }
    return hr;
}
Example #10
0
Error::E RenderSystem::CreateSwapChain(const Window &window) {
    assert(_device);
     _swapDesc = kDefaultSwapDesc;

    _swapDesc.SampleDesc.Count = 4;
    _swapDesc.SampleDesc.Quality = _msaaQualityLevel - 1;
    _swapDesc.OutputWindow = window.GetHandle();
    _swapDesc.BufferDesc.Width = window.GetWidth();
    _swapDesc.BufferDesc.Height = window.GetHeight();

    IDXGIFactory *factory = FactoryFromDevice(_device);

    DEBUG_HR(factory->CreateSwapChain(_device, &_swapDesc, &_swapChain));
    ReleaseCom(factory);
    return Error::OK;
}
Example #11
0
void D3DApplication::InitDirect3D()
{
	// Create the device.

	UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)  
	createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif

	HR(D3D10CreateDevice(0, m_DriverType, 0, createDeviceFlags, D3D10_SDK_VERSION, &m_pDevice));

	IDXGIFactory* pFactory;
	HR(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory)));

		// Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain.
	DXGI_SWAP_CHAIN_DESC swapChainDescription;

	swapChainDescription.BufferDesc.Width					= m_ClientWidth;
	swapChainDescription.BufferDesc.Height					= m_ClientHeight;
	swapChainDescription.BufferDesc.RefreshRate.Numerator	= 60;
	swapChainDescription.BufferDesc.RefreshRate.Denominator = 1;
	swapChainDescription.BufferDesc.Format					= DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDescription.BufferDesc.ScanlineOrdering		= DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDescription.BufferDesc.Scaling					= DXGI_MODE_SCALING_UNSPECIFIED;

	// No multisampling.
	swapChainDescription.SampleDesc.Count					= 1;
	swapChainDescription.SampleDesc.Quality					= 0;

	swapChainDescription.BufferUsage						= DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDescription.BufferCount						= 1;
	swapChainDescription.OutputWindow						= m_hMainWindow;
	swapChainDescription.Windowed							= true;
	swapChainDescription.SwapEffect							= DXGI_SWAP_EFFECT_DISCARD;
	swapChainDescription.Flags								= 0;
	
	HR(pFactory->CreateSwapChain(m_pDevice, &swapChainDescription, &m_pSwapChain));
	HR(pFactory->MakeWindowAssociation(m_hMainWindow, DXGI_MWA_NO_WINDOW_CHANGES));

	// The remaining steps that need to be carried out for d3d creation
	// also need to be executed every time the window is resized. So
	// just call the OnResize method here to avoid code duplication.

	OnResize();
}
Example #12
0
bool Renderer::CreateSwapChain() {
	// Determine buffer size
	RECT rect;
	GetClientRect(hwnd,&rect);
	
	// Create swap chain
	DXGI_SWAP_CHAIN_DESC SwapChainDesc;
	SwapChainDesc.BufferCount = 1;
	SwapChainDesc.BufferDesc.Width = rect.right - rect.left;
	SwapChainDesc.BufferDesc.Height = rect.bottom - rect.top;
	SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
	SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; // 60/1 = 60 Hz
	SwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	SwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
	SwapChainDesc.OutputWindow = hwnd;
	SwapChainDesc.SampleDesc.Count = 1;
	SwapChainDesc.SampleDesc.Quality = 0; // no  AA
	SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	SwapChainDesc.Windowed = true;
	
	// Obtain DXGI factory that was used to create the device
	// ???
	IDXGIDevice* DXGIDevice;
	D3DDevice->QueryInterface(__uuidof(IDXGIDevice),(void**)&DXGIDevice);
	IDXGIAdapter* DXGIAdapter;
	DXGIDevice->GetParent(__uuidof(IDXGIAdapter),(void**)&DXGIAdapter);
	IDXGIFactory* DXGIFactory;
	DXGIAdapter->GetParent(__uuidof(IDXGIFactory),(void**)&DXGIFactory);

	// Use it
	if(DXGIFactory->CreateSwapChain(D3DDevice,&SwapChainDesc,&SwapChain) != S_OK) {
		MessageBox(hwnd,"Error creating swap chain","Error",MB_OK);
		return false;
	}
	
	// Release unused stuff
	DXGIDevice->Release();
	DXGIAdapter->Release();
	DXGIFactory->Release();
	return true;
}
Example #13
0
boolean RendererD3D11::assembleUnit()
{
    ProcessingUnitPtr windowUnit = ProcessingUnitPtr::null;
    window->getData( windowUnit );
    if( !windowUnit.isNull() )
    {
        WindowPtr wnd = staticCast<Window>( windowUnit );
        RenderDeviceD3D11* rd = static_cast<RenderDeviceD3D11*>( owner );
        IDXGIFactory* dxgiFactory = rd->getDXGIFactory();

        DXGI_SWAP_CHAIN_DESC desc;
        desc.BufferCount = 1;
        desc.BufferDesc.Width = wnd->getWidth();
        desc.BufferDesc.Height = wnd->getHeight();
        desc.BufferDesc.Format = MapperD3D11::mapPixelFormat( Render::PF_RGBA8UN );
        desc.BufferDesc.RefreshRate.Numerator = 60;
        desc.BufferDesc.RefreshRate.Denominator = 1;
        desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
        desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
        desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        desc.OutputWindow = (HWND)wnd->getHandle();
        desc.SampleDesc.Count = 1;
        desc.SampleDesc.Quality = 0;
        desc.Windowed = !wnd->isFullscreen();
        desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
        desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

        IDXGISwapChain* sc = 0;
        HRESULT hr = dxgiFactory->CreateSwapChain( rd->getD3DDevice(), &desc, &sc );
        if( SUCCEEDED( hr ) )
        {
            swapchains.add( sc );
            wnd->setSwapChain( sc );
            return true;
        }
    }

    return false;
}
	//---------------------------------------------------------------------
	void D3D10RenderWindow::createD3DResources(void)
	{
		if (mIsSwapChain && mDevice.isNull())
		{
			OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
				"Secondary window has not been given the device from the primary!",
				"D3D10RenderWindow::createD3DResources");
		}

		//SAFE_RELEASE(mpRenderSurface);

		// Set up the presentation parameters
		//		int pD3D = mDriver->getD3D();
		//	D3DDEVTYPE devType = D3DDEVTYPE_HAL;

		ZeroMemory( &md3dpp, sizeof(DXGI_SWAP_CHAIN_DESC) );
		md3dpp.Windowed				= !mIsFullScreen;
		md3dpp.SwapEffect			= DXGI_SWAP_EFFECT_DISCARD ;
		// triple buffer if VSync is on
		md3dpp.BufferCount			= mVSync ? 2 : 1;
		md3dpp.BufferUsage			= DXGI_USAGE_RENDER_TARGET_OUTPUT;
		md3dpp.OutputWindow 		= mHWnd;
		md3dpp.BufferDesc.Width		= mWidth;
		md3dpp.BufferDesc.Height	= mHeight;
		md3dpp.BufferDesc.RefreshRate.Numerator=1;
		md3dpp.BufferDesc.RefreshRate.Denominator = 1;
		if (mIsFullScreen)
		{
			md3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED;
			md3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST;
			md3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ;
		}
		md3dpp.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

		D3D10RenderSystem* rsys = static_cast<D3D10RenderSystem*>(Root::getSingleton().getRenderSystem());
		rsys->determineFSAASettings(mFSAA, mFSAAHint, md3dpp.BufferDesc.Format, &mFSAAType);


		if (mVSync)
		{
			//	md3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
		}
		else
		{
			// NB not using vsync in windowed mode in D3D10 can cause jerking at low 
			// frame rates no matter what buffering modes are used (odd - perhaps a
			// timer issue in D3D10 since GL doesn't suffer from this) 
			// low is < 200fps in this context
			if (!mIsFullScreen)
			{
				LogManager::getSingleton().logMessage("D3D10 : WARNING - "
					"disabling VSync in windowed mode can cause timing issues at lower "
					"frame rates, turn VSync on if you observe this problem.");
			}
			//	md3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
		}
		/*
		md3dpp.BufferDesc.Format= BackBufferFormat		= D3DFMT_R5G6B5;
		if( mColourDepth > 16 )
		md3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;

		if (mColourDepth > 16 )
		{
		// Try to create a 32-bit depth, 8-bit stencil
		if( FAILED( pD3D->CheckDeviceFormat(mDriver->getAdapterNumber(),
		devType,  md3dpp.BackBufferFormat,  D3DUSAGE_DEPTHSTENCIL, 
		D3DRTYPE_SURFACE, D3DFMT_D24S8 )))
		{
		// Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer 
		if( FAILED( pD3D->CheckDeviceFormat(mDriver->getAdapterNumber(),
		devType,  md3dpp.BackBufferFormat,  D3DUSAGE_DEPTHSTENCIL, 
		D3DRTYPE_SURFACE, D3DFMT_D32 )))
		{
		// Jeez, what a naff card. Fall back on 16-bit depth buffering
		md3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		}
		else
		md3dpp.AutoDepthStencilFormat = D3DFMT_D32;
		}
		else
		{
		// Woohoo!
		if( SUCCEEDED( pD3D->CheckDepthStencilMatch( mDriver->getAdapterNumber(), devType,
		md3dpp.BackBufferFormat, md3dpp.BackBufferFormat, D3DFMT_D24S8 ) ) )
		{
		md3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; 
		} 
		else 
		md3dpp.AutoDepthStencilFormat = D3DFMT_D24X8; 
		}
		}
		else
		// 16-bit depth, software stencil
		md3dpp.AutoDepthStencilFormat	= D3DFMT_D16;
		*/
		md3dpp.SampleDesc.Count = mFSAAType.Count;
		md3dpp.SampleDesc.Quality = mFSAAType.Quality;
		if (mIsSwapChain)
		{
			IDXGIFactory*	mpDXGIFactory;
			HRESULT hr;
			hr = CreateDXGIFactory( IID_IDXGIFactory, (void**)&mpDXGIFactory );
			if( FAILED(hr) )
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
					"Unable to create a DXGIFactory for the swap chain",
					"D3D10RenderWindow::createD3DResources");
			}

			// get the dxgi device
			IDXGIDevice* pDXGIDevice = NULL;
			hr = mDevice->QueryInterface( IID_IDXGIDevice, (void**)&pDXGIDevice );
			if( FAILED(hr) )
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
					"Unable to create a DXGIDevice for the swap chain",
					"D3D10RenderWindow::createD3DResources");
			}

			// Create swap chain			
			hr = mpDXGIFactory->CreateSwapChain( 
				pDXGIDevice,&md3dpp,&mpSwapChain);

			if (FAILED(hr))
			{
				// Try a second time, may fail the first time due to back buffer count,
				// which will be corrected by the runtime
				hr = mpDXGIFactory->CreateSwapChain(pDXGIDevice,&md3dpp,&mpSwapChain);
			}
			if (FAILED(hr))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
					"Unable to create an additional swap chain",
					"D3D10RenderWindow::createD3DResources");
			}
		
			// Store references to buffers for convenience
			//mpSwapChain->GetBackBuffer( 0, D3DBACKBUFFER_TYPE_MONO, &mpRenderSurface );
			// Additional swap chains need their own depth buffer
			// to support resizing them

			hr = mpSwapChain->GetBuffer( 0,  __uuidof( ID3D10Texture2D ), (LPVOID*)&mpBackBuffer  );
			if( FAILED(hr) )
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
					"Unable to Get Back Buffer for swap chain",
					"D3D10RenderWindow::createD3DResources");
			}

			// get the backbuffer desc
			D3D10_TEXTURE2D_DESC BBDesc;
			mpBackBuffer->GetDesc( &BBDesc );

			// create the render target view
			D3D10_RENDER_TARGET_VIEW_DESC RTVDesc;
			ZeroMemory( &RTVDesc, sizeof(RTVDesc) );

			RTVDesc.Format = BBDesc.Format;
			RTVDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
			RTVDesc.Texture2D.MipSlice = 0;
			hr = mDevice->CreateRenderTargetView( mpBackBuffer, &RTVDesc, &mRenderTargetView );

			if( FAILED(hr) )
			{
				String errorDescription = mDevice.getErrorDescription();
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
					"Unable to create rendertagert view\nError Description:" + errorDescription,
					"D3D10RenderWindow::createD3DResources");
			}


			if (mIsDepthBuffered) 
			{
				/*	hr = mDevice->CreateDepthStencilSurface(
				mWidth, mHeight,
				md3dpp.AutoDepthStencilFormat,
				md3dpp.MultiSampleType,
				md3dpp.MultiSampleQuality, 
				(md3dpp.Flags & D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL),
				&mpRenderZBuffer, NULL
				);

				if (FAILED(hr)) 
				{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
				"Unable to create a depth buffer for the swap chain",
				"D3D10RenderWindow::createD3DResources");

				}
				*/
				// get the backbuffer

				// Create depth stencil texture
				ID3D10Texture2D* pDepthStencil = NULL;
				D3D10_TEXTURE2D_DESC descDepth;

				descDepth.Width = mWidth;
				descDepth.Height = mHeight;
				descDepth.MipLevels = 1;
				descDepth.ArraySize = 1;
				descDepth.Format = DXGI_FORMAT_R32_TYPELESS;
				descDepth.SampleDesc.Count = 1;
				descDepth.SampleDesc.Quality = 0;
				descDepth.Usage = D3D10_USAGE_DEFAULT;
				descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
				descDepth.CPUAccessFlags = 0;
				descDepth.MiscFlags = 0;

				hr = mDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil );
				if( FAILED(hr) || mDevice.isError())
				{
					String errorDescription = mDevice.getErrorDescription(hr);
					OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
						"Unable to create depth texture\nError Description:" + errorDescription,
						"D3D10RenderWindow::createD3DResources");
				}

				// Create the depth stencil view
				D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
				descDSV.Format = DXGI_FORMAT_D32_FLOAT;
				descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
				descDSV.Texture2D.MipSlice = 0;
				hr = mDevice->CreateDepthStencilView( pDepthStencil, &descDSV, &mDepthStencilView );
				SAFE_RELEASE( pDepthStencil );
				if( FAILED(hr) )
				{
					String errorDescription = mDevice.getErrorDescription();
					OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
						"Unable to create depth stencil view\nError Description:" + errorDescription,
						"D3D10RenderWindow::createD3DResources");
				}

			} 
			else 
			{
				//				mpRenderZBuffer = 0;
			}
		}
		/*else
		{
		if (!mDevice)
		{
		// We haven't created the device yet, this must be the first time

		// Do we want to preserve the FPU mode? Might be useful for scientific apps
		DWORD extraFlags = 0;
		ConfigOptionMap& options = Root::getSingleton().getRenderSystem()->getConfigOptions();
		ConfigOptionMap::iterator opti = options.find("Floating-point mode");
		if (opti != options.end() && opti->second.currentValue == "Consistent")
		extraFlags |= D3DCREATE_FPU_PRESERVE;

		#if OGRE_THREAD_SUPPORT
		extraFlags |= D3DCREATE_MULTITHREADED;
		#endif
		// Set default settings (use the one Ogre discovered as a default)
		UINT adapterToUse = mDriver->getAdapterNumber();

		if (mUseNVPerfHUD)
		{
		// Look for 'NVIDIA NVPerfHUD' adapter (<= v4)
		// or 'NVIDIA PerfHUD' (v5)
		// If it is present, override default settings
		for (UINT adapter=0; adapter < mDriver->getD3D()->GetAdapterCount(); ++adapter)
		{
		D3DADAPTER_IDENTIFIER9 identifier;
		HRESULT res;
		res = mDriver->getD3D()->GetAdapterIdentifier(adapter,0,&identifier);
		if (strstr(identifier.Description,"PerfHUD") != 0)
		{
		adapterToUse = adapter;
		devType = D3DDEVTYPE_REF;
		break;
		}
		}
		}

		hr = pD3D->CreateDevice(adapterToUse, devType, mHWnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mDevice );
		if (FAILED(hr))
		{
		// Try a second time, may fail the first time due to back buffer count,
		// which will be corrected down to 1 by the runtime
		hr = pD3D->CreateDevice( adapterToUse, devType, mHWnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mDevice );
		}
		if( FAILED( hr ) )
		{
		hr = pD3D->CreateDevice( adapterToUse, devType, mHWnd,
		D3DCREATE_MIXED_VERTEXPROCESSING | extraFlags, &md3dpp, &mDevice );
		if( FAILED( hr ) )
		{
		hr = pD3D->CreateDevice( adapterToUse, devType, mHWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING | extraFlags, &md3dpp, &mDevice );
		}
		}
		// TODO: make this a bit better e.g. go from pure vertex processing to software
		if( FAILED( hr ) )
		{
		destroy();
		OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, 
		"Failed to create Direct3D9 Device: " + 
		Root::getSingleton().getErrorDescription(hr), 
		"D3D10RenderWindow::createD3DResources" );
		}
		}
		// update device in driver
		mDriver->setD3DDevice( mDevice );
		// Store references to buffers for convenience
		mDevice->GetRenderTarget( 0, &mpRenderSurface );
		mDevice->GetDepthStencilSurface( &mpRenderZBuffer );
		// release immediately so we don't hog them
		mpRenderZBuffer->Release();
		}
		*/
	}
Example #15
0
// ´ÙÀÌ·ºÆ® °´Ã¼ ÃʱâÈ­
// - °¢Á¾±â´ÉÀ» Áö¿øÇϴ°¡ üũÇÏ°í(´ÙÁß »ùÇøµ µî), ½º¿ÒüÀÎ, ÄÄ °´Ã¼ µîÀ» »ý¼º, Á¦°ÅÇÑ´Ù.
bool cInitD3D::InitDirect3D()
{
	// µð¹ÙÀ̽º, µð¹ÙÀ̽º ÄÁÅؽºÆ® »ý¼º
	UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)  
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL featureLevel;
	HRESULT hr = D3D11CreateDevice(
		0,                 // default adapter
		md3dDriverType,
		0,                 // no software device
		createDeviceFlags,
		0, 0,              // default feature level array
		D3D11_SDK_VERSION,
		&md3dDevice,
		&featureLevel,
		&md3dImmediateContext);

	if (FAILED(hr))
	{
		MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0);
		return false;
	}

	if (featureLevel != D3D_FEATURE_LEVEL_11_0)
	{
		MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0);
		return false;
	}

	// ¹é¹öÆÛ¿¡ 4X MSAA Ç°Áú Áö¿øÀ» È®ÀÎ
	HR(md3dDevice->CheckMultisampleQualityLevels(
		DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality));
	assert(m4xMsaaQuality > 0);

	// ½º¿ÒüÀÎ »ý¼º
	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 = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// ´ÙÁß »ùÇøµ À¯¹« (Use 4X MSAA?) 
	if (mEnable4xMsaa)
	{
		sd.SampleDesc.Count = 4;
		sd.SampleDesc.Quality = m4xMsaaQuality - 1;
	}
	// No MSAA
	else
	{
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
	}

	// ¹öÆÛ »ý¼º
	sd.BufferUsage  = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount  = 1;
	sd.OutputWindow = mhMainWnd;
	sd.Windowed     = true;
	sd.SwapEffect   = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags		= 0;

	// µð¹ÙÀ̽º »ý¼º
	IDXGIDevice* dxgiDevice = 0;
	HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice));

	IDXGIAdapter* dxgiAdapter = 0;
	HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));

	IDXGIFactory* dxgiFactory = 0;
	HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory));

	// ½º¿ÒüÀÎ »ý¼º ¹× È®ÀÎ
	HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain));

	// ÄÄ °´Ã¼ »èÁ¦
	ReleaseCOM(dxgiDevice);
	ReleaseCOM(dxgiAdapter);
	ReleaseCOM(dxgiFactory);

	// â Å©±â Á¶Àý (ÄÚµå Áߺ¹ ÇÇÇϱâ À§ÇØ »ç¿ë)
	OnResize();

	return true;
}
void DirectXController::Initialize( void )
{
	WindowController::Get()->Initialize();
	WindowController::Get()->OpenWindow();

	driverType = D3D_DRIVER_TYPE_HARDWARE;
	enable4xMsaa = false;
	msaa4xQuality = 0;
	device.dx = nullptr;
	deviceContext.dx = nullptr;
	swapChain = nullptr;
	depthStencilBuffer = nullptr;
	renderTargetView = nullptr;
	depthStencilView = nullptr;
	ZeroMemory( &viewport, sizeof(D3D11_VIEWPORT) );

	UINT createDeviceFlags = 0;
#if defined(_DEBUG) || defined(DEBUG)
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL requiredFeatureLevel = D3D_FEATURE_LEVEL_11_0;
	D3D_FEATURE_LEVEL featureLevel;
	
	HRESULT hResult = D3D11CreateDevice(
		NULL,					// Adapter
		driverType,				// Driver Type
		NULL,					// Software
		createDeviceFlags,		// Flags
		&requiredFeatureLevel,	// Feature levels
		1,						// num Feature levels
		D3D11_SDK_VERSION,		// SDK Version
		&device.dx,				// Device
		&featureLevel,			// Feature Level
		&deviceContext.dx );	// Device Context


	// Handle any device creation or DirectX version errors
	if( FAILED(hResult) )
	{
		MessageBox(NULL, L"D3D11CreateDevice Failed", NULL, NULL);
		//return false;
	}

	if( featureLevel != requiredFeatureLevel )
	{
		MessageBox(NULL, L"Direct3D Feature Level 11 unsupported", NULL, NULL);
		//return false;
	}

	// Check for 4X MSAA quality support
	HR(device.dx->CheckMultisampleQualityLevels(
		DXGI_FORMAT_R8G8B8A8_UNORM,
		4,
		&msaa4xQuality));
	//assert( msaa4xQuality > 0 ); // Potential problem if quality is 0
	
	// set up swap chain
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc) );
	swapChainDesc.BufferCount							= 1;
	swapChainDesc.BufferDesc.Width						= WindowController::Get()->GetWidth();//windowWidth;
	swapChainDesc.BufferDesc.Height						= WindowController::Get()->GetHeight();//windowHeight;
	swapChainDesc.BufferDesc.RefreshRate.Numerator		= 60;
	swapChainDesc.BufferDesc.RefreshRate.Denominator	= 1;
	swapChainDesc.BufferDesc.Format						= DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferDesc.ScanlineOrdering			= DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling					= DXGI_MODE_SCALING_UNSPECIFIED;
	swapChainDesc.BufferUsage							= DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow							= Win32Controller::Get()->GetHWnd();//hMainWnd;
	swapChainDesc.Windowed								= true;
	swapChainDesc.Flags									= 0;

	if( enable4xMsaa )
	{ // Set up 4x MSAA
		swapChainDesc.SampleDesc.Count   = 4;
		swapChainDesc.SampleDesc.Quality = msaa4xQuality - 1;
	}
	else
	{ // No MSAA
		swapChainDesc.SampleDesc.Count   = 1;
		swapChainDesc.SampleDesc.Quality = 0;
	}

	// To correctly create the swap chain, we must use the IDXGIFactory that
	// was used to create the device.
	IDXGIDevice*	dxgiDevice	= 0;
	IDXGIAdapter*	dxgiAdapter = 0;
	IDXGIFactory*	dxgiFactory = 0;
	HR(device.dx->QueryInterface(	__uuidof(IDXGIDevice),	(void**)&dxgiDevice));
	HR(dxgiDevice->GetParent(	__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));
	HR(dxgiAdapter->GetParent(	__uuidof(IDXGIFactory), (void**)&dxgiFactory));

	// Finally make the swap chain and release the DXGI stuff
	HR(dxgiFactory->CreateSwapChain(device.dx, &swapChainDesc, &swapChain));
	ReleaseCOMobjMacro(dxgiDevice);
	ReleaseCOMobjMacro(dxgiAdapter);
	ReleaseCOMobjMacro(dxgiFactory);

	// The remaining steps also need to happen each time the window
	// is resized, so just run the OnResize method
	Resize();
}
Example #17
0
bool D3DApp::InitDirect3D()
{
	/* -----------------------------------------
	Create the D3D11 Device and DeviceContext
	----------------------------------------- */

	/*  -----------------------
	//? D3D11CreateDevice Notes
	-----------------------

	//! Function Signature

	HRESULT result = D3D11CreateDevice(
	pAdapter,
	DriverType,
	Software,
	Flags,
	pFeatureLevels,
	FeatureLevels,
	SDKVersion,
	ppDevice,
	pFeatureLevel,
	ppImmediateContext
	);

	//! Parameter Descriptions

	// The display adapter we want the created device to represent
	// Notes: Specifying "null" indicates the primary display adapter.
	//! IDXGIAdapter* pAdapter;

	// Type of driver our device will represent
	// Notes: In general, this should always be D3D_DRIVER_TYPE_HARDWARE, unless you need a reference, software, or WARP device.
	//! D3D_DRIVER_TYPE DriverType;

	// Software Driver
	// Notes: This is "null" if using a hardware driver.
	//! HMODULE Software;

	// (Optional) Device creation flags
	// Ex: D3D11_CREATE_DEVICE_DEBUG - Enables the Debug Layer, Direct3D will send debug messages to the VC++ output window.
	// Ex: D3D11_CREATE_DEVICE_SINGLETHREADED - Improves performance if you guarantee that Direct3D will not be called from multiple threads.
	//! UINT Flags;

	// Array of D3D feature levels
	// Notes: The order indicates the order in which to check for feature level support.
	// Specifying "null" indicates to choose the greatest feature level supported.
	//! const D3D_FEATURE_LEVEL* pFeatureLevels;

	// Size of pFeatureLevels array.
	// Notes: Specify "0" if you specified "null" for pFeatureLevels.
	//! UINT FeatureLevels;

	// Direct3D SDK Version
	// Notes: While studying this book, always use D3D11_SDK_VERSION.
	//! UINT SDKVersion;

	// Returns: Pointer to the device which this function will create
	//! ID3D11Device** ppDevice;

	// Returns: The first (highest) supported feature level from pFeatureLevels
	//! D3D_FEATURE_LEVEL* pFeatureLevel;

	// Returns: The created device context
	//! ID3D11DeviceContext** ppImmediateContext;

	*/

	UINT CreateDeviceFlags = 0;

#if defined(DEBUG) || defined(_DEBUG)
	CreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL FeatureLevel;

	HRESULT CreateDeviceResult = D3D11CreateDevice(
		nullptr,
		mD3DDriverType,
		nullptr,
		CreateDeviceFlags,
		nullptr, 0,
		D3D11_SDK_VERSION,
		&mDevice,
		&FeatureLevel,
		&mImmediateContext
		);

	if (FAILED(CreateDeviceResult)) {
		MessageBox(0, L"D3D11CreateDevice failed.", 0, 0);
		return false;
	}

	if (FeatureLevel != D3D_FEATURE_LEVEL_11_0) {
		MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0);
		return false;
	}

	/* -----------------------------------
	Check 4X MSAA Quality Level Support
	----------------------------------- */

	HR(mDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &mMultisampleQuality));
	assert(mMultisampleQuality > 0);

	/* ----------------------------------------------
	Describe the characteristics of the swap chain
	---------------------------------------------- */

	/*  --------------------------
	//? DXGI_SWAP_CHAIN_DESC Notes
	--------------------------

	//! Structure Signature

	typedef struct DXGI_SWAP_CHAIN_DESC {
	DXGI_MODE_DESC   BufferDesc;
	DXGI_SAMPLE_DESC SampleDesc;
	DXGI_USAGE       BufferUsage;
	UINT             BufferCount;
	HWND             OutputWindow;
	BOOL             Windowed;
	DXGI_SWAP_EFFECT SwapEffect;
	UINT             Flags;
	} DXGI_SWAP_CHAIN_DESC;

	//! Member Descriptions

	// Properties of the back buffer
	// Notes: The main properties that concern us are the width, height, and pixel format.
	//! DXGI_MODE_DESC BufferDesc;

	// Number of multisamples and quality level
	//! DXGI_SAMPLE_DESC SampleDesc;

	// Usage of the back buffer
	// Notes: Specify DXGI_USAGE_RENDER_TARGET_OUTPUT to indicate that the back buffer will be used for rendering.
	//! DXGI_USAGE BufferUsage;

	// Number of back buffers in the swap chain
	// Notes: Use "1" to allocate one back buffer (double buffering)
	//! UINT BufferCount;

	// Handle to the window we are rendering to
	//! HWND OutputWindow;

	// Notes: "true" indicates windowed-mode, "false" indicates full-screen mode
	//! BOOL Windowed;

	// Notes: Specify DXGI_SWAP_EFFECT_DISCARD to let the display driver select the most efficient presentation method
	//! DXGI_SWAP_EFFECT SwapEffect;

	// (Optional) flags
	// Notes: If you use DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH, then when you switch to full-screen mode, the application
	// will select a display mode that best matches the current back buffer settings.
	//! UINT Flags;

	*/

	DXGI_SWAP_CHAIN_DESC SwapChainDesc;

	/*  --------------------------
	//? DXGI_DESC_MODE Notes
	--------------------------

	//! Structure Signature

	typedef struct DXGI_MODE_DESC {
	UINT                     Width;
	UINT                     Height;
	DXGI_RATIONAL            RefreshRate;
	DXGI_FORMAT              Format;
	DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
	DXGI_MODE_SCALING        Scaling;
	} DXGI_MODE_DESC;

	//! Member Descriptions

	// Window resolution width
	//! UINT Width;

	// Window resolution height
	//! UINT Height;

	// Refresh rate defined in Hz (Numerator and Denominator)
	//! DXGI_RATIONAL RefreshRate;

	// Display format
	//! DXGI_FORMAT Format;

	// Scanline Drawing Mode
	//! DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;

	// Scaling Mode
	// Notes: Indicates how an image is stretched to fit the screen resolution.
	//! DXGI_MODE_SCALING Scaling;

	*/

	DXGI_MODE_DESC BackBufferDesc;
	BackBufferDesc.Width = 800;
	BackBufferDesc.Height = 600;
	// Most monitors cannot output more than 24-bit color, so extra precision would be wasted
	// Even though the monitor cannot output the 8-bit alpha, those bits can be used for other things like effects
	BackBufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	BackBufferDesc.RefreshRate.Numerator = 60;
	BackBufferDesc.RefreshRate.Denominator = 1;
	BackBufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	BackBufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	SwapChainDesc.BufferDesc = BackBufferDesc;

	if (mEnableMultisample) {
		SwapChainDesc.SampleDesc.Count = 4;
		SwapChainDesc.SampleDesc.Quality = mMultisampleQuality - 1;
	}
	else {
		SwapChainDesc.SampleDesc.Count = 1;
		SwapChainDesc.SampleDesc.Quality = 0;
	}

	SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	SwapChainDesc.BufferCount = 1;
	SwapChainDesc.OutputWindow = mMainWindow;
	SwapChainDesc.Windowed = true;
	SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	SwapChainDesc.Flags = 0;

	/* ---------------------
	Create the swap chain
	--------------------- */

	IDXGIDevice* dxgiDevice = 0;
	mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);

	IDXGIAdapter* dxgiAdapter = 0;
	dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);

	IDXGIFactory* dxgiFactory = 0;
	dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

	dxgiFactory->CreateSwapChain(mDevice, &SwapChainDesc, &mSwapChain);

	ReleaseCOM(dxgiDevice);
	ReleaseCOM(dxgiAdapter);
	ReleaseCOM(dxgiFactory);

	OnResize();

	return true;
}
bool DirectX11Graphics::Initialise()
{
	if ( _is_initialised )
	{
		//LogError( "F11", "Cannot initialise F11Graphics; F11Graphics is currently initialised." );
		return false;
	}

	// Return false if no game has been set.
	if ( !GetGame() )
	{
		//LogError( "F11", "Cannot initialise F11Graphics; F11Graphics has no graphics message listener set." );
		return false;
	}

	// Get the dimensions of the screen.

	RECT rectangle;
	GetClientRect( HWND(GetGame()->GetHWND()), &rectangle );

	unsigned int width = rectangle.right - rectangle.left;
	unsigned int height = rectangle.bottom - rectangle.top;

	if ( VRIsEnabled() )
	{	
		GetGame()->GetVRTextureDimensions( width, height );
	}

	// Use the default adapter and hardware drivers.

	IDXGIFactory* factory = nullptr;
	IDXGIAdapter* adapter = nullptr;

	auto f = CreateDXGIFactory( __uuidof(IDXGIFactory), (void**)&factory );

	auto a = factory->EnumAdapters( 0, &adapter );
	
	// Create a debug device if in debug mode.

#ifdef _DEBUG
	unsigned int device_flags = D3D11_CREATE_DEVICE_DEBUG;
#else
	unsigned int device_flags = 0;
#endif

	// Create a swap chain description.

	DXGI_SWAP_CHAIN_DESC swap_chain_desc;
	
	memset( &swap_chain_desc, 0, sizeof(swap_chain_desc) );
	swap_chain_desc.BufferDesc.Width = width;
	swap_chain_desc.BufferDesc.Height = height;
	swap_chain_desc.BufferDesc.RefreshRate.Numerator = 0;
	swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1;
	swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	//swap_chain_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	//swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
	swap_chain_desc.SampleDesc.Count = 1;
	swap_chain_desc.SampleDesc.Quality = 0;
	swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swap_chain_desc.BufferCount = 2;
	swap_chain_desc.OutputWindow = HWND(GetGame()->GetHWND());
	swap_chain_desc.Windowed = true;
	swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL;
	swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	// Create the swap chain, device and immediate device context.
	
	if ( FAILED( D3D11CreateDevice(	adapter,
									adapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE,
									nullptr,
									device_flags,
									nullptr,
									0,
									D3D11_SDK_VERSION,
									&_device,
									nullptr,
									&_immediate_device_context ) ) )
	{
		//LogError( "F11", "Cannot initialise F11Graphics; cannot create device and swapchain." );
		return false;
	}

	if ( adapter )
	{
		adapter->Release();
	}

	if ( FAILED( factory->CreateSwapChain( _device, &swap_chain_desc, &_swap_chain ) ) )
	{
		return false;
	}
	ID3D11Texture2D* backbuffer = nullptr;
    HRESULT hr = _swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backbuffer);
    if (FAILED(hr))
        return false;

    hr = _device->CreateRenderTargetView(backbuffer, nullptr, &_back_buffer);
    if (FAILED(hr))
        return false;

	SetWidth( width );
	SetHeight( height );

	if ( backbuffer )
	{
		backbuffer->Release();
	}

	if ( factory )
	{
		factory->Release();
	}

	if ( VRIsEnabled() )
	{
		{
			D3D11_BUFFER_DESC cbuffer_desc;
			cbuffer_desc.ByteWidth = sizeof(OculusBlit_cbuffer);
			cbuffer_desc.Usage = D3D11_USAGE_DYNAMIC;
			cbuffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
			cbuffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
			cbuffer_desc.MiscFlags = 0;
			cbuffer_desc.StructureByteStride = sizeof(OculusBlit_cbuffer);

			if ( FAILED( Device()->CreateBuffer( &cbuffer_desc, nullptr, &_oculus_blit_cbuffer ) ) )
			{
				return false;
			}
		}
		
		_swap_chain->SetFullscreenState( 1, nullptr );
	}


	if (0)
	{
		// Get the dxgi factory and disable fullscreen toggling with alt+enter.

		IDXGIDevice* dxgi_device = nullptr;
		if ( FAILED( _device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgi_device) ) )
		{
			//LogError( "F11", "Cannot initialise F11Graphics; cannot get DXGI device." );
			return false;
		}

		if ( FAILED( dxgi_device->GetParent(__uuidof(IDXGIAdapter), (void **)&adapter) ) )
		{
			//LogError( "F11", "Cannot initialise F11Graphics; cannot get DXGI adapter." );
			return false;
		}

		IDXGIFactory * factory = nullptr;
		if ( FAILED( adapter->GetParent(__uuidof(IDXGIFactory), (void **)&factory) ) )
		{
			//LogError( "F11", "Cannot initialise F11Graphics; cannot get DXGI factory." );
			return false;
		}

		factory->MakeWindowAssociation( HWND(GetGame()->GetHWND()), DXGI_MWA_NO_WINDOW_CHANGES );

		dxgi_device->Release();
		adapter->Release();
		factory->Release();
	}
	
	// Create the back buffer by resizing
	//Resize( width, height );

	_resources.SetConfig(GetGraphicsSettings());
	if ( !_resources.Initialise() )
	{
		return false;
	}
		
	Resize( width, height );

	_is_initialised = true;
	
	return true;
}
egl::Error DXGISwapChainWindowSurfaceWGL::createSwapChain()
{
    egl::Error error = setObjectsLocked(false);
    if (error.isError())
    {
        return error;
    }

    if (mRenderbufferBufferHandle)
    {
        mFunctionsWGL->dxUnregisterObjectNV(mDeviceHandle, mRenderbufferBufferHandle);
        mRenderbufferBufferHandle = nullptr;
    }

    // If this surface is bound to a texture, unregister it.
    bool hadBoundSurface = (mTextureHandle != nullptr);
    if (hadBoundSurface)
    {
        mFunctionsWGL->dxUnregisterObjectNV(mDeviceHandle, mTextureHandle);
        mTextureHandle = nullptr;
    }

    IDXGIFactory *dxgiFactory = GetDXGIFactoryFromDevice(mDevice);
    if (dxgiFactory == nullptr)
    {
        return egl::Error(EGL_BAD_NATIVE_WINDOW, "Failed to query the DXGIFactory.");
    }

    IDXGIFactory2 *dxgiFactory2 = nullptr;
    HRESULT result = dxgiFactory->QueryInterface(__uuidof(IDXGIFactory2),
                                                 reinterpret_cast<void **>(&dxgiFactory2));
    if (SUCCEEDED(result))
    {
        ASSERT(dxgiFactory2 != nullptr);

        DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
        swapChainDesc.BufferCount           = 1;
        swapChainDesc.Format                = mSwapChainFormat;
        swapChainDesc.Width                 = static_cast<UINT>(mWidth);
        swapChainDesc.Height                = static_cast<UINT>(mHeight);
        swapChainDesc.Format                = mSwapChainFormat;
        swapChainDesc.Stereo                = FALSE;
        swapChainDesc.SampleDesc.Count      = 1;
        swapChainDesc.SampleDesc.Quality = 0;
        swapChainDesc.BufferUsage =
            DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_BACK_BUFFER;
        swapChainDesc.BufferCount = 1;
        swapChainDesc.Scaling     = DXGI_SCALING_STRETCH;
        swapChainDesc.SwapEffect  = DXGI_SWAP_EFFECT_SEQUENTIAL;
        swapChainDesc.AlphaMode   = DXGI_ALPHA_MODE_UNSPECIFIED;
        swapChainDesc.Flags       = mSwapChainFlags;

        result = dxgiFactory2->CreateSwapChainForHwnd(mDevice, mWindow, &swapChainDesc, nullptr,
                                                      nullptr, &mSwapChain1);
        SafeRelease(dxgiFactory2);
        SafeRelease(dxgiFactory);
        if (FAILED(result))
        {
            return egl::Error(EGL_BAD_ALLOC, "Failed to create swap chain for window, result: 0x%X",
                              result);
        }

        mSwapChain = mSwapChain1;
        mSwapChain->AddRef();
    }
    else
    {
        DXGI_SWAP_CHAIN_DESC swapChainDesc               = {};
        swapChainDesc.BufferCount                        = 1;
        swapChainDesc.BufferDesc.Format                  = mSwapChainFormat;
        swapChainDesc.BufferDesc.Width                   = static_cast<UINT>(mWidth);
        swapChainDesc.BufferDesc.Height                  = static_cast<UINT>(mHeight);
        swapChainDesc.BufferDesc.Scaling                 = DXGI_MODE_SCALING_UNSPECIFIED;
        swapChainDesc.BufferDesc.ScanlineOrdering        = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
        swapChainDesc.BufferDesc.RefreshRate.Numerator   = 0;
        swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
        swapChainDesc.BufferUsage =
            DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_BACK_BUFFER;
        swapChainDesc.Flags              = mSwapChainFlags;
        swapChainDesc.OutputWindow       = mWindow;
        swapChainDesc.SampleDesc.Count   = 1;
        swapChainDesc.SampleDesc.Quality = 0;
        swapChainDesc.Windowed           = TRUE;
        swapChainDesc.SwapEffect         = DXGI_SWAP_EFFECT_DISCARD;

        result = dxgiFactory->CreateSwapChain(mDevice, &swapChainDesc, &mSwapChain);
        SafeRelease(dxgiFactory);
        if (FAILED(result))
        {
            return egl::Error(EGL_BAD_ALLOC, "Failed to create swap chain for window, result: 0x%X",
                              result);
        }
    }

    ID3D11Texture2D *colorBuffer = nullptr;
    result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
                                   reinterpret_cast<void **>(&colorBuffer));
    if (FAILED(result))
    {
        return egl::Error(EGL_BAD_ALLOC, "Failed to query texture from swap chain, result: 0x%X",
                          result);
    }

    mFunctionsGL->genRenderbuffers(1, &mColorRenderbufferID);
    mStateManager->bindRenderbuffer(GL_RENDERBUFFER, mColorRenderbufferID);
    mRenderbufferBufferHandle =
        mFunctionsWGL->dxRegisterObjectNV(mDeviceHandle, colorBuffer, mColorRenderbufferID,
                                          GL_RENDERBUFFER, WGL_ACCESS_READ_WRITE_NV);
    SafeRelease(colorBuffer);
    if (mRenderbufferBufferHandle == nullptr)
    {
        return egl::Error(EGL_BAD_ALLOC, "Failed to register D3D object, error: 0x%X.",
                          HRESULT_CODE(GetLastError()));
    }

    // Rebind the surface to the texture if needed.
    if (hadBoundSurface)
    {
        mTextureHandle = mFunctionsWGL->dxRegisterObjectNV(mDeviceHandle, colorBuffer, mTextureID,
                                                           GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV);
        if (mTextureHandle == nullptr)
        {
            return egl::Error(EGL_BAD_ALLOC, "Failed to register D3D object, error: 0x%X.",
                              HRESULT_CODE(GetLastError()));
        }
    }

    error = setObjectsLocked(true);
    if (error.isError())
    {
        return error;
    }

    ASSERT(mFramebufferID != 0);
    mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mFramebufferID);
    mFunctionsGL->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
                                          mColorRenderbufferID);

    if (mDepthBufferFormat != GL_NONE)
    {
        ASSERT(mDepthRenderbufferID != 0);
        mStateManager->bindRenderbuffer(GL_RENDERBUFFER, mDepthRenderbufferID);
        mFunctionsGL->renderbufferStorage(GL_RENDERBUFFER, mDepthBufferFormat,
                                          static_cast<GLsizei>(mWidth),
                                          static_cast<GLsizei>(mHeight));

        const gl::InternalFormat &depthStencilFormatInfo =
            gl::GetInternalFormatInfo(mDepthBufferFormat);
        if (depthStencilFormatInfo.depthBits > 0)
        {
            mFunctionsGL->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                                                  GL_RENDERBUFFER, mDepthRenderbufferID);
        }
        if (depthStencilFormatInfo.stencilBits > 0)
        {
            mFunctionsGL->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
                                                  GL_RENDERBUFFER, mDepthRenderbufferID);
        }
    }

    mFirstSwap = true;

    return egl::Error(EGL_SUCCESS);
}
Example #20
0
bool Direct3D::Initialize(HWND* hWnd)
{
	mcWidth = &Settings->GetData()->mWidth;
	mcHeight = &Settings->GetData()->mHeight;

	UINT createDeviceFlags = 0;
#if defined(_DEBUG) | (DEBUG)
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL featureLevel;
	if( FAILED ( D3D11CreateDevice(
		nullptr,
		mDriverType,
		nullptr,
		0,
		nullptr,
		0,
		D3D11_SDK_VERSION,
		&mDevice,
		&featureLevel,
		&mDevCon)))
	{
		cout << "D3D11CreateDevice failed." << endl;
		return false;
	}

	if(featureLevel != D3D_FEATURE_LEVEL_11_0)
	{
		cout << "Direct3D feature level 11 unsupported." << endl;
		return false;
	}

	mDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMSAAQuality);
	assert(m4xMSAAQuality > 0);

	DXGI_SWAP_CHAIN_DESC sd = {};
	sd.BufferDesc.Width = *mcWidth;
	sd.BufferDesc.Height = *mcHeight;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	if (mEnable4xMsaa)
	{
		sd.SampleDesc.Count = 4;
		sd.SampleDesc.Quality = m4xMSAAQuality-1;
	}
	else
	{
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
	}

	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Use back buffer as render target
	sd.BufferCount = 1;								  // Number of back buffers to use in swap chain
	sd.OutputWindow = *hWnd;					  // Specify window we render into
	sd.Windowed = !Settings->GetData()->mIsFullscreen;	// Windowed mode or full-screen mode
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;	      // Let display driver select most efficient presentation method
	sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	IDXGIDevice* dxgiDevice = nullptr;
	mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);

	IDXGIAdapter* dxgiAdapter = nullptr;
	dxgiDevice->GetParent(__uuidof(IDXGIAdapter),(void**)&dxgiAdapter);

	IDXGIFactory* dxgiFactory = nullptr;
	dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

	dxgiFactory->CreateSwapChain(mDevice, &sd, &mSwapChain);

	SafeRelease(dxgiDevice);
	SafeRelease(dxgiAdapter);
	SafeRelease(dxgiFactory);

	this->OnResize();
	return true;
}
Example #21
0
bool DXApp::InitDirectX()
{
	UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
	D3D_FEATURE_LEVEL featurelvl;
	HRESULT hr = D3D11CreateDevice(
		0,				//default adapter
		D3D_DRIVER_TYPE_HARDWARE,
		0,
		createDeviceFlags,
		0, 0,
		D3D11_SDK_VERSION,
		&m_d3dDevice,
		&featurelvl,
		&m_d3dImmediateContext);

	if (FAILED(hr))
	{
		MessageBox(0, L"Creation of Context failed", 0, 0);
		return false;
	}

	if (featurelvl != D3D_FEATURE_LEVEL_11_0)
	{
		MessageBox(0, L"DirectX11 not supported", 0, 0);
		return false;
	}

	m_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality);
	assert(m_4xMsaaQuality > 0);

	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width = m_clientWidth;
	sd.BufferDesc.Height = m_clientHeight;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	if (m_enable4xMsaa)
	{
		sd.SampleDesc.Count = 4;
		sd.SampleDesc.Quality = m_4xMsaaQuality - 1;
	}
	else
	{
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = m_4xMsaaQuality - 1;
	}

	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount = 1;
	sd.OutputWindow =m_mainHandle;
	sd.Windowed = m_windowed;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags = 0;

	IDXGIDevice* dxgiDevice = 0;
	m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);

	IDXGIAdapter* dxgiAdapter = 0;
	dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);

	IDXGIFactory* dxgiFactory = 0;
	dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

	dxgiFactory->CreateSwapChain(m_d3dDevice, &sd, &m_d3dSwapChain);
	//NO ALT-ENTER
	dxgiFactory->MakeWindowAssociation(m_mainHandle, DXGI_MWA_NO_ALT_ENTER);

	UINT i = 0;
	IDXGIAdapter* pAdapter;
	std::vector<IDXGIAdapter*> vAdapters;
	while (dxgiFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND)
	{
		vAdapters.push_back(pAdapter);
		//pAdapter->CheckInterfaceSupport(__uuidof(DIRECT3D_VERSION), DIRECT3D_11.0);
		i++;
	}

	//MessageBox(0, LPCWSTR(std::to_string(vAdapters.size()).c_str()), 0, 0);

	for (auto a : vAdapters)a->Release();
	dxgiDevice->Release();
	dxgiAdapter->Release();
	dxgiFactory->Release();

	ID3D11Texture2D* backBuffer;
	m_d3dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
		reinterpret_cast<void**>(&backBuffer));
	m_d3dDevice->CreateRenderTargetView(backBuffer, 0, &m_d3dRenderTargetView);
	backBuffer->Release();

	D3D11_TEXTURE2D_DESC depthStencilDesc;
	depthStencilDesc.Width = m_clientWidth;
	depthStencilDesc.Height = m_clientHeight;
	depthStencilDesc.MipLevels = 1;
	depthStencilDesc.ArraySize = 1;
	depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	if (m_enable4xMsaa)
	{
		depthStencilDesc.SampleDesc.Count = 4;
		depthStencilDesc.SampleDesc.Quality = m_4xMsaaQuality - 1;
	}
	else
	{
		depthStencilDesc.SampleDesc.Count = 1;
		depthStencilDesc.SampleDesc.Quality = m_4xMsaaQuality - 0;
	}
	depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
	depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthStencilDesc.CPUAccessFlags = 0;
	depthStencilDesc.MiscFlags = 0;

	m_d3dDevice->CreateTexture2D(&depthStencilDesc,
		0,
		&m_d3dDepthStencilBuffer);

	m_d3dDevice->CreateDepthStencilView(m_d3dDepthStencilBuffer,
		0,
		&m_d3dDepthStencilView);

	m_d3dImmediateContext->OMSetRenderTargets(1, &m_d3dRenderTargetView, m_d3dDepthStencilView);

	D3D11_VIEWPORT vp;
	vp.TopLeftX = 0.f;
	vp.TopLeftY = 0.f;
	vp.Width	= static_cast<float>(m_clientWidth);
	vp.Height	= static_cast<float>(m_clientHeight);
	vp.MinDepth = 0.f;
	vp.MaxDepth = 0.f;

	m_d3dImmediateContext->RSSetViewports(1, &vp);

	return true;
}
    bool BasicRenderer::initD3D()
    {
	    unsigned int createDeviceFlags = 0;

    #	if defined(DEBUG) || defined(_DEBUG)
	    createDeviceFlags  |= D3D11_CREATE_DEVICE_DEBUG;
    #	endif

	    D3D_FEATURE_LEVEL featureLevel;
	    HRESULT hr = D3D11CreateDevice(
		    0,
		    m_driverType,
		    0,
		    createDeviceFlags,
		    0, 0,
		    D3D11_SDK_VERSION,
		    &m_device,
		    &featureLevel,
		    &m_context);

	    if (FAILED(hr))
	    {
		    return false;
	    }

	    if (featureLevel != D3D_FEATURE_LEVEL_11_0)
	    {
		    return false;
	    }

	    m_device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMSAAQuality);
	    assert(m_4xMSAAQuality > 0);

	    DXGI_SWAP_CHAIN_DESC swapChainDesc;
	    swapChainDesc.BufferDesc.Width = m_width;
	    swapChainDesc.BufferDesc.Height = m_height;
	    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
	    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	    if( m_enable4xMSAA )
	    {
		    swapChainDesc.SampleDesc.Count   = 4;
		    swapChainDesc.SampleDesc.Quality = m_4xMSAAQuality-1;
	    }
	    else
	    {
		    swapChainDesc.SampleDesc.Count   = 1;
		    swapChainDesc.SampleDesc.Quality = 0;
	    }

	    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	    swapChainDesc.BufferCount = 1;
	    swapChainDesc.OutputWindow = reinterpret_cast<HWND>(m_windowHandle);
	    swapChainDesc.Windowed = true;
	    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	    swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	    IDXGIDevice* dxgiDevice = 0;
	    m_device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);

	    IDXGIDevice* dxgiAdapter = 0;
	    dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);

	    IDXGIFactory* dxgiFactory = 0;
	    dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

	    dxgiFactory->CreateSwapChain(m_device, &swapChainDesc, &m_swapChain);

	    releaseCOM(dxgiDevice);
	    releaseCOM(dxgiAdapter);
	    releaseCOM(dxgiFactory);

	    onResize();

	    return true;
    }
// Direct3Dの初期化
HRESULT InitD3D( void )
{
    HRESULT hr = S_OK;
	D3D_FEATURE_LEVEL  FeatureLevelsRequested[6] = { 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 };
	UINT               numLevelsRequested = 6;
	D3D_FEATURE_LEVEL  FeatureLevelsSupported;

	// デバイス作成
	hr = D3D11CreateDevice( NULL,
					D3D_DRIVER_TYPE_HARDWARE, 
					NULL, 
					0,
					FeatureLevelsRequested, 
					numLevelsRequested,
					D3D11_SDK_VERSION, 
					&g_pd3dDevice,
					&FeatureLevelsSupported,
					&g_pImmediateContext );
	if( FAILED ( hr ) ) {
		return hr;
	}

	// ファクトリの取得
	IDXGIDevice * pDXGIDevice;
	hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), ( void ** )&pDXGIDevice );
	IDXGIAdapter * pDXGIAdapter;
	hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), ( void ** )&pDXGIAdapter );
	IDXGIFactory * pIDXGIFactory;
	pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), ( void ** )&pIDXGIFactory);

	// スワップチェインの作成
    DXGI_SWAP_CHAIN_DESC	sd;
	ZeroMemory( &sd, sizeof( sd ) );
	sd.BufferCount = 1;
	sd.BufferDesc.Width = g_nClientWidth;
	sd.BufferDesc.Height = g_nClientHeight;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.OutputWindow = g_hWnd;
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = TRUE;
	hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain );

	pDXGIDevice->Release();
	pDXGIAdapter->Release();
	pIDXGIFactory->Release();

	if( FAILED ( hr ) ) {
		return hr;
	}

    // レンダリングターゲットの生成
    ID3D11Texture2D			*pBackBuffer = NULL;
    D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc;
    hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK );
        return hr;
    }
    pBackBuffer->GetDesc( &BackBufferSurfaceDesc );
    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV );
    SAFE_RELEASE( pBackBuffer );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK );
        return hr;
    }

    g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, NULL );

    // ラスタライザの設定
    D3D11_RASTERIZER_DESC drd;
	ZeroMemory( &drd, sizeof( drd ) );
	drd.FillMode				= D3D11_FILL_SOLID;
	drd.CullMode				= D3D11_CULL_NONE;
	drd.FrontCounterClockwise	= FALSE;
	drd.DepthClipEnable			= TRUE;
    hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK );
        return hr;
    }
    g_pImmediateContext->RSSetState( g_pRS );

    // ビューポートの設定
    D3D11_VIEWPORT vp;
    vp.Width    = ( FLOAT )g_nClientWidth;
    vp.Height   = ( FLOAT )g_nClientHeight;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0.0f;
    vp.TopLeftY = 0.0f;
    g_pImmediateContext->RSSetViewports( 1, &vp );

    return S_OK;
}
bool D3DApp::InitDirect3D()
{
	// Create the device and device context.

	UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)  
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL featureLevel;
	HRESULT hr = D3D11CreateDevice(
			0,                 // default adapter
			md3dDriverType,
			0,                 // no software device
			createDeviceFlags, 
			0, 0,              // default feature level array
			D3D11_SDK_VERSION,
			&md3dDevice,
			&featureLevel,
			&md3dImmediateContext);

	if( FAILED(hr) )
	{
		MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0);
		return false;
	}

	if( featureLevel != D3D_FEATURE_LEVEL_11_0 )
	{
		MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0);
		return false;
	}

	// Check 4X MSAA quality support for our back buffer format.
	// All Direct3D 11 capable devices support 4X MSAA for all render 
	// target formats, so we only need to check quality support.

	HR(md3dDevice->CheckMultisampleQualityLevels(
		DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality));
	assert( m4xMsaaQuality > 0 );

	// Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain.

	DXGI_SWAP_CHAIN_DESC sd;
	ZeroMemory(&sd, sizeof(DXGI_SWAP_CHAIN_DESC));
	sd.BufferDesc.Width = mClientWidth;
	sd.BufferDesc.Height = mClientHeight;
	sd.Windowed = true;


	sd.BufferDesc.RefreshRate.Numerator		= m_MonitorNumerator;
	sd.BufferDesc.RefreshRate.Denominator	= m_MonitorDenumerator;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Use 4X MSAA? 
	if( mEnable4xMsaa )
	{
		sd.SampleDesc.Count   = 4;
		sd.SampleDesc.Quality = m4xMsaaQuality-1;
	}
	// No MSAA
	else
	{
		sd.SampleDesc.Count   = 1;
		sd.SampleDesc.Quality = 0;
	}

	sd.BufferUsage  = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount  = 1;
	sd.OutputWindow = mhMainWnd;
	sd.SwapEffect   = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags		= 0;

	// To correctly create the swap chain, we must use the IDXGIFactory that was
	// used to create the device.  If we tried to use a different IDXGIFactory instance
	// (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: 
	// This function is being called with a device from a different IDXGIFactory."

	IDXGIDevice* dxgiDevice = 0;
	HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice));
	      
	IDXGIAdapter* dxgiAdapter = 0;
	HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));

	IDXGIFactory* dxgiFactory = 0;

	HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory));

	HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain));
	

	//Disable Alt-Enter Sequence
	dxgiFactory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER);


	ReleaseCOM(dxgiDevice);
	ReleaseCOM(dxgiAdapter);
	ReleaseCOM(dxgiFactory);

	// The remaining steps that need to be carried out for d3d creation
	// also need to be executed every time the window is resized.  So
	// just call the OnResize method here to avoid code duplication.
	
	OnResize();

	if (mFullScreen){ mSwapChain->SetFullscreenState(true, NULL); }

	

	return true;
}
Example #25
0
bool D3DRenderer::CreateSwapChain(int screenWidth, int screenHeight, HWND hwnd)
{
	//Get refresh rate, display modes, and initialize the swap chain.
	HRESULT result;
	IDXGIDevice* dxgiDevice = 0;
	IDXGIFactory* dxgiFactory =0;
	IDXGIAdapter* dxgiAdapter =0;
	IDXGIOutput* dxgiAdapterOutput;
	unsigned int numModes, i, numerator, denominator, stringLength;
	DXGI_MODE_DESC* displayModeList;
	DXGI_ADAPTER_DESC adapterDesc;
	int error;
	DXGI_SWAP_CHAIN_DESC swapChainDesc;

	this->m_device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
	dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);
	dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);

	result = dxgiFactory->EnumAdapters(0, &dxgiAdapter);
	if (FAILED(result))
	{
		return false;
	}

	result = dxgiAdapter->EnumOutputs(0, &dxgiAdapterOutput);
	if (FAILED(result))
	{
		return false;
	}

	result = dxgiAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	if (FAILED(result))
	{
		return false;
	}

	displayModeList = new DXGI_MODE_DESC[numModes];
	if (!displayModeList)
	{
		return false;
	}

	result = dxgiAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
	if (FAILED(result))
	{
		return false;
	}

	for (i=0; i < numModes; i++)
	{
		if (displayModeList[i].Width == (unsigned int)screenWidth)
		{
			if (displayModeList[i].Height == (unsigned int)screenHeight)
			{
				numerator = displayModeList[i].RefreshRate.Numerator;
				denominator = displayModeList[i].RefreshRate.Denominator;
			}
		}
	}

	result = dxgiAdapter->GetDesc(&adapterDesc);
	if (FAILED(result))
	{
		return false;
	}

	this->m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

	error = wcstombs_s(&stringLength, this->m_videoCardDescription, 128, adapterDesc.Description, 128);
	if (error != 0)
	{
		return false;
	}

	//Initialize the swap chain
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	//Single buffer count
	swapChainDesc.BufferCount = 1;
	
	swapChainDesc.BufferDesc.Width = screenWidth;
	swapChainDesc.BufferDesc.Height = screenHeight;

	//Using regular 32bit back buffer
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	if (this->m_vsync_enabled)
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	}
	else
	{
		swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
		swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	}

	//Set the usage
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

	swapChainDesc.OutputWindow = hwnd;

	//Turn multisamping off. This setting is for MSAA, for our purposes we don't need it.
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.Windowed = true;

	//Set the scan line ordering
	swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	//Tells D3D to discard the back buffer after presenting
	swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	//Do not use advanced flags.
	swapChainDesc.Flags = 0;

	//Create the swap chain
	result = dxgiFactory->CreateSwapChain(this->m_device, &swapChainDesc, &this->m_swapChain);

	if (FAILED(result))
	{
		return false;
	}

	delete [] displayModeList;
	displayModeList = 0;

	dxgiAdapterOutput->Release();
	dxgiAdapterOutput = 0;

	dxgiAdapter->Release();
	dxgiAdapter = 0;

	dxgiFactory->Release();
	dxgiFactory = 0;

	return true;
}
// Direct3Dの初期化
HRESULT InitD3D( void )
{
    HRESULT hr = S_OK;
	D3D_FEATURE_LEVEL  FeatureLevelsRequested[6] = { 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 };
	UINT               numLevelsRequested = 6;
	D3D_FEATURE_LEVEL  FeatureLevelsSupported;

	// デバイス作成
	hr = D3D11CreateDevice( NULL,
					D3D_DRIVER_TYPE_HARDWARE, 
					NULL, 
					0,
					FeatureLevelsRequested, 
					numLevelsRequested,
					D3D11_SDK_VERSION, 
					&g_pd3dDevice,
					&FeatureLevelsSupported,
					&g_pImmediateContext );
	if( FAILED ( hr ) ) {
		return hr;
	}

	// ファクトリの取得
	IDXGIDevice * pDXGIDevice;
	hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), ( void ** )&pDXGIDevice );
	IDXGIAdapter * pDXGIAdapter;
	hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), ( void ** )&pDXGIAdapter );
	IDXGIFactory * pIDXGIFactory;
	pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), ( void ** )&pIDXGIFactory);

	// スワップチェインの作成
    DXGI_SWAP_CHAIN_DESC	sd;
	ZeroMemory( &sd, sizeof( sd ) );
	sd.BufferCount = 1;
	sd.BufferDesc.Width = g_nClientWidth;
	sd.BufferDesc.Height = g_nClientHeight;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.OutputWindow = g_hWnd;
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = TRUE;
	hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain );

	pDXGIDevice->Release();
	pDXGIAdapter->Release();
	pIDXGIFactory->Release();

	if( FAILED ( hr ) ) {
		return hr;
	}

    // レンダリングターゲットの生成
    ID3D11Texture2D			*pBackBuffer = NULL;
    D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc;
    hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK );
        return hr;
    }
    pBackBuffer->GetDesc( &BackBufferSurfaceDesc );
    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV );
    SAFE_RELEASE( pBackBuffer );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK );
        return hr;
    }

    // *** Create depth stencil texture ***
    D3D11_TEXTURE2D_DESC descDepth;
	RECT rc;
    GetClientRect( g_hWnd, &rc );
	ZeroMemory( &descDepth, sizeof(descDepth) );
    descDepth.Width = rc.right - rc.left;
    descDepth.Height = rc.bottom - rc.top;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
    if( FAILED( hr ) )
        return hr;

    // *** Create the depth stencil view ***
    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory( &descDSV, sizeof(descDSV) );
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
    hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
    if( FAILED( hr ) )
        return hr;

	// *** レンダリングターゲット設定 ***
    g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, g_pDepthStencilView );

	// ステンシルステートの作成
	D3D11_DEPTH_STENCIL_DESC dsDesc;

	// Depth test parameters
	dsDesc.DepthEnable = true;
	dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	dsDesc.DepthFunc = D3D11_COMPARISON_LESS;

	// Stencil test parameters
	dsDesc.StencilEnable = true;
	dsDesc.StencilReadMask = 0xFF;
	dsDesc.StencilWriteMask = 0xFF;

	// Stencil operations if pixel is front-facing
	dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Stencil operations if pixel is back-facing
	dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create depth stencil state
	hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState );

	dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
	hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState_NoWrite );

//	g_pImmediateContext->OMSetDepthStencilState( g_pDSDepthState, 1 );

    // ラスタライザの設定
    D3D11_RASTERIZER_DESC drd;
	ZeroMemory( &drd, sizeof( drd ) );
	drd.FillMode				= D3D11_FILL_SOLID;
	drd.CullMode				= D3D11_CULL_NONE;
	drd.FrontCounterClockwise	= FALSE;
	drd.DepthClipEnable			= TRUE;
    hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK );
        return hr;
    }
	g_pImmediateContext->RSSetState( g_pRS );

    // ラスタライザの設定(時計回りカリング)
	ZeroMemory( &drd, sizeof( drd ) );
	drd.FillMode				= D3D11_FILL_SOLID;
	drd.CullMode				= D3D11_CULL_BACK;
	drd.FrontCounterClockwise	= TRUE;
	drd.DepthClipEnable			= TRUE;
    hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CW );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK );
        return hr;
    }
//    g_pImmediateContext->RSSetState( g_pRS_Cull_CW );

    // ラスタライザの設定(反時計回りカリング)
	ZeroMemory( &drd, sizeof( drd ) );
	drd.FillMode				= D3D11_FILL_SOLID;
	drd.CullMode				= D3D11_CULL_BACK;
	drd.FrontCounterClockwise	= FALSE;
	drd.DepthClipEnable			= TRUE;
    hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CCW );
    if ( FAILED( hr ) ) {
		MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK );
        return hr;
    }
//    g_pImmediateContext->RSSetState( g_pRS_Cull_CCW );

    // ビューポートの設定
    D3D11_VIEWPORT vp;
    vp.Width    = ( FLOAT )g_nClientWidth;
    vp.Height   = ( FLOAT )g_nClientHeight;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0.0f;
    vp.TopLeftY = 0.0f;
    g_pImmediateContext->RSSetViewports( 1, &vp );

    return S_OK;
}
Example #27
0
bool D3DRenderWidget::createDevice()
{
	HRESULT re;  // 函数返回值, HRESULT 是一种简单的数据类型,通常被属性和 ATL 用作返回值。
	UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
	D3D_FEATURE_LEVEL featureLevel;  // Direct3D 设备的功能级别目标
	HRESULT hr = D3D11CreateDevice(
		0,
		m_d3dDriverType,
		0,
		createDeviceFlags,
		0,
		0,
		D3D11_SDK_VERSION,
		&m_d3dDevice,
		&featureLevel,
		&m_d3dImmediateContext);

	if (FAILED(hr))
	{
		MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0);
		return false;
	}

	if (featureLevel != D3D_FEATURE_LEVEL_11_0)
	{
		MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0);
		return false;
	}

	re = m_d3dDevice->CheckMultisampleQualityLevels(
		DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality);
	if (FAILED(re))	return false;

	assert(m_4xMsaaQuality > 0);

	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width = width();
	sd.BufferDesc.Height = height();
	sd.BufferDesc.RefreshRate.Numerator = 60;  // 分子
	sd.BufferDesc.RefreshRate.Denominator = 1;  // 分母
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	if (m_enable4xMsaa)
	{
		sd.SampleDesc.Count = 4;
		sd.SampleDesc.Quality = m_4xMsaaQuality - 1;
	}
	else
	{
		sd.SampleDesc.Count = 1;
		sd.SampleDesc.Quality = 0;
	}

	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount = 1;
	sd.OutputWindow = (HWND)winId();
	sd.Windowed = true;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags = 0;

	IDXGIDevice* dxgiDevice = 0;
	re = m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
	if (FAILED(re))	return false;

	IDXGIAdapter* dxgiAdapter = 0;
	re = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter);
	if (FAILED(re))	return false;

	IDXGIFactory* dxgiFactory = 0;
	re = dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory);
	if (FAILED(re))	return false;

	re = dxgiFactory->CreateSwapChain(m_d3dDevice, &sd, &m_swapChain);
	if (FAILED(re))	return false;

	safe_release(dxgiDevice);
	safe_release(dxgiAdapter);
	safe_release(dxgiFactory);

	return true;
}
HRESULT KGraphicsDevice::Init(int32 window_width, int32 window_height)
{
	HRESULT hr;

	m_WindowWidth = window_width;
	m_WindowHeight = window_height;

	//Setup SDL window
	HWND handle;

	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)
	{
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "SDL_Init failed: %s", SDL_GetError());
	}

	IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF);

	m_MainWindow = SDL_CreateWindow("Conservative Clustered Shading DirectX12", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, m_WindowWidth, m_WindowHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

	SDL_SysWMinfo info;
	//Must init info struct with SDL version info, see documentation for explanation
	SDL_VERSION(&info.version);

	if (SDL_GetWindowWMInfo(m_MainWindow, &info))
		handle = info.info.win.window;
	else
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to get WMInfo: %s", SDL_GetError());

	uint32 flags = 0;

#ifdef _DEBUG
	{
		ID3D12Debug* debugController;
		D3D12GetDebugInterface(IID_PPV_ARGS(&debugController));
		debugController->EnableDebugLayer();

		if (debugController)
			debugController->Release();
	}
#endif

	DXGI_SWAP_CHAIN_DESC descSwapChain;
	ZeroMemory(&descSwapChain, sizeof(descSwapChain));
	descSwapChain.BufferCount = 2;
	descSwapChain.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	descSwapChain.BufferUsage = DXGI_USAGE_BACK_BUFFER | DXGI_USAGE_RENDER_TARGET_OUTPUT;
	descSwapChain.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
	descSwapChain.OutputWindow = handle;
	descSwapChain.SampleDesc.Count = 1;
	descSwapChain.Windowed = true;

	hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_Device));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to create D3D12 Device");

	D3D12_FEATURE_DATA_D3D12_OPTIONS opts;
	hr = m_Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opts, sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to CheckFeatureSupport");
	
	//Print hardware opts
	PrintHWopts(opts);

	uint32 node_count = m_Device->GetNodeCount();
	shared_context.log->LogText(LogLevel::DEBUG_PRINT, "Device node count: %d", node_count);

	IDXGIFactory* dxgifactory;
	hr = CreateDXGIFactory1(IID_PPV_ARGS(&dxgifactory));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to create IDXGIFactory");

	D3D12_COMMAND_QUEUE_DESC queueDesc;
	ZeroMemory(&queueDesc, sizeof(queueDesc));
	queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
	queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
	hr = m_Device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_CommandQueue));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to create Command Queue");

	hr = dxgifactory->CreateSwapChain(m_CommandQueue, &descSwapChain, &m_SwapChain);
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to create SwapChain");

	
	dxgifactory->Release();

	//Set up descriptor heaps
	m_DescHeapCBV_SRV.CreateDescriptorHeap(50, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
	m_DescHeapDSV.CreateDescriptorHeap(2, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
	m_DescHeapRTV.CreateDescriptorHeap(20, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
	m_DescHeapSampler.CreateDescriptorHeap(1, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);

	m_Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&m_CommandAllocator));

	m_Device->SetStablePowerState(TRUE);

	hr = m_CommandQueue->GetTimestampFrequency(&m_Freq);
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed GetTimestampFrequency");

	m_ViewPort = { 0.0f, 0.0f, (float)m_WindowWidth, (float)m_WindowHeight, 0.0f, 1.0f };
	m_ScissorRect = { 0, 0, m_WindowWidth, m_WindowHeight };

	m_RTDescriptor[0] = m_DescHeapRTV.GetNewCPUHandle();
	m_RTDescriptor[1] = m_DescHeapRTV.GetNewCPUHandle();

	//Get back buffer and create RTVs
	m_SwapChain->GetBuffer(0, IID_PPV_ARGS(&m_RenderTarget[0]));
	m_Device->CreateRenderTargetView(m_RenderTarget[0], nullptr, m_RTDescriptor[0]);
	m_RenderTarget[0]->SetName(L"RENDER TARGET");

	m_SwapChain->GetBuffer(1, IID_PPV_ARGS(&m_RenderTarget[1]));
	m_Device->CreateRenderTargetView(m_RenderTarget[1], nullptr, m_RTDescriptor[1]);

	//Create time stamp query heap
	const uint32 num_time_queries = 24;
	D3D12_QUERY_HEAP_DESC desc;
	desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
	desc.Count = num_time_queries;
	desc.NodeMask = 0;

	hr = m_Device->CreateQueryHeap(&desc, IID_PPV_ARGS(&m_TimeStampQueryHeap));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to CreateQueryHeap");

	m_Device->CreateCommittedResource(
		&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_READBACK, 0, 0),
		D3D12_HEAP_FLAG_NONE,
		&CD3DX12_RESOURCE_DESC::Buffer(num_time_queries * sizeof(uint64)),
		D3D12_RESOURCE_STATE_COPY_DEST,
		nullptr,
		IID_PPV_ARGS(&m_TimeStampQueryReadBackRes));
	if (FAILED(hr))
		shared_context.log->LogText(LogLevel::FATAL_ERROR, "Failed to CreateCommittedResource for query readback buffer");

	//Create fence
	m_Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_Fence));
	m_CurrentFence = 1;

	m_HandleEvent = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS);

	return hr;
}
Example #29
0
HRESULT ACD3D::AddViewport(HWND hWnd, BOOL enableVSync)
{
	HRESULT hr;
	VSyncEnable = enableVSync;

	Log("Add viewport");

	//cria o retangulo para renderizacao
	RECT rc;
	GetClientRect( hWnd, &rc );
	UINT width = rc.right - rc.left;
	UINT height = rc.bottom - rc.top;

	//adiciona os objetos necessarios para cada vp
	ACD3DVpComponents* vpComponent = new ACD3DVpComponents();

	//pega o factory
	IDXGIFactory* pDXGIFactory = ACD3DTools::GetDXGIFactory();

	#pragma region CREATE SWAP CHAIN
	IDXGISwapChain* pSwapChain;

	//define o rendertargetview, define o buffer e coloca como backbuffer em cada swapchain
	//cria os swpachains para cada janela
	DXGI_SWAP_CHAIN_DESC scd;
	SecureZeroMemory(&scd, sizeof(scd));
	if (VSyncEnable)
		scd = ACD3DConfigurations::DefineSwapShain(hWnd, width, height, ACD3DGlobals::G_Numerator, ACD3DGlobals::G_Denomerator); //ser form o vsync enable ele sincroniza a renderizacao com o refreshrate da tela
	else
		scd = ACD3DConfigurations::DefineSwapShain(hWnd, width, height, 60, 1); //senao ele usa direto os valores padroes isso pode gerar alguns artefatos MF
	hr = pDXGIFactory->CreateSwapChain(ACD3DGlobals::G_pD3dDevice, &scd, &pSwapChain);
	if( FAILED( hr ) )
	{
		MessageBoxA(nullptr, "[ERROR] Creating SwapChain. AddViewport()", "Error", MB_OK | MB_ICONERROR);
		return hr;
	}

	// Release the factory.
	pDXGIFactory->Release();
	pDXGIFactory = nullptr;

	vpComponent->pSwapChain = pSwapChain;
	#pragma endregion

	#pragma region CREATE RENDERTARGETVIEW
	//array de backbuffers, um pra cada janela
	ID3D11Texture2D* pBackBuffer;
	ID3D11RenderTargetView* pRenderTargetView;

	hr = pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
	if( FAILED( hr ) )
	{
		MessageBoxA(nullptr, "[ERROR] Create buffer. AddViewport()", "Error", MB_OK | MB_ICONERROR);
		return hr;
	}

	hr = ACD3DGlobals::G_pD3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &pRenderTargetView );
	if( FAILED( hr ) )
	{
		MessageBoxA(nullptr, "[ERROR] Create render target. AddViewport()", "Error", MB_OK | MB_ICONERROR);
		return hr;
	}

	vpComponent->pRenderTargetView = pRenderTargetView;

	pBackBuffer->Release();
	#pragma endregion

	#pragma region CREATE DEPTHSTENCILVIEW
	ID3D11Texture2D* pDepthStencil;
    ID3D11DepthStencilView* pDepthStencilView;

	//define o stencil view
	hr = ACD3DConfigurations::DefineDepthStencilView(ACD3DGlobals::G_pD3dDevice,
													&pDepthStencil, &pDepthStencilView, 
													width, height);
	if( FAILED( hr ) )
	{
		MessageBoxA(nullptr, "[ERROR] Create depth stencil view. AddViewport()", "Error", MB_OK | MB_ICONERROR);
		return hr;
	}

	vpComponent->pDepthStencilView = pDepthStencilView;

	pDepthStencil->Release();
	#pragma endregion

	#pragma region CREATE VIEWPORT
	D3D11_VIEWPORT vp;
	ACD3DConfigurations::DefineViewPort(width, height, 0, 1, rc.left, rc.top, &vp);

	vpComponent->Viewport = vp;
	#pragma endregion

	//inser o objeto no map
	mpVpComponents.insert(std::pair<HWND, ACD3DVpComponents*>(hWnd, vpComponent));


	//seta a viewport
	ACD3DGlobals::G_pContext->RSSetViewports( 1, &vp );

	//seta o render target e o depthstencil
	ACD3DGlobals::G_pContext->OMSetRenderTargets( 1, &pRenderTargetView, pDepthStencilView );

	SetActiveViewport(hWnd);
	SetActiveRenderingViewport(hWnd);

	return AC_OK;
};
Example #30
0
bool Renderer::Init()
{
    UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
    //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
    //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUGGABLE;
#endif

    D3D_FEATURE_LEVEL featureLevel;
    HRESULT hresult = D3D11CreateDevice(0, _d3dDriverType, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &_d3dDevice, &featureLevel, &_d3dImmediateContext);

    if (FAILED(hresult))
    {
        // TODO: Throw exceptions
        _logger.LogLine(L"Failed to initialize Renderer: Failed to create D3D11CreateDevice.");
        _logger.LogHResult(hresult);
        MessageBox(0, L"Failed to initialize Renderer, see log for details.", 0, 0);
        return false;
    }

    if (featureLevel != D3D_FEATURE_LEVEL_11_0)
        //if (featureLevel != 0xc000)
    {
        // TODO: Throw exceptions
        _logger.LogLine(L"Failed to initialize Renderer: Required D3D feature level 11 not supported.");
        MessageBox(0, L"Failed to initialize Renderer, see log for details.", 0, 0);
        return false;
    }

    hresult = (_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &_4xMsaaQuality));
    if (FAILED(hresult))
    {
        _logger.LogHResult(hresult);
    }
    assert(_4xMsaaQuality > 0);

    DXGI_SWAP_CHAIN_DESC swapChainDescription;
    swapChainDescription.BufferDesc.Width = _clientWidth;
    swapChainDescription.BufferDesc.Height = _clientHeight;
    swapChainDescription.BufferDesc.RefreshRate.Numerator = 60;
    swapChainDescription.BufferDesc.RefreshRate.Denominator = 1;
    swapChainDescription.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDescription.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDescription.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    if (_enable4xMsaa)
    {
        swapChainDescription.SampleDesc.Count = 4;
        swapChainDescription.SampleDesc.Quality = _4xMsaaQuality - 1;
    }
    else
    {
        swapChainDescription.SampleDesc.Count = 1;
        swapChainDescription.SampleDesc.Quality = 0;
    }
    swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDescription.BufferCount = 1;
    swapChainDescription.OutputWindow = _windowHandle;
    swapChainDescription.Windowed = true;
    swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    swapChainDescription.Flags = 0;

    IDXGIDevice* dxgiDevice = 0;
    hresult = (_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice));
    if (FAILED(hresult))
    {
        _logger.LogHResult(hresult);
    }

    IDXGIAdapter* dxgiAdapter = 0;
    hresult = (dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter));
    if (FAILED(hresult))
    {
        _logger.LogHResult(hresult);
    }

    IDXGIFactory* dxgiFactory = 0;
    hresult = (dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory));
    if (FAILED(hresult))
    {
        _logger.LogHResult(hresult);
    }

    hresult = (dxgiFactory->CreateSwapChain(_d3dDevice, &swapChainDescription, &_swapChain));
    if (FAILED(hresult))
    {
        _logger.LogHResult(hresult);
    }

    if (dxgiDevice)
    {
        dxgiDevice->Release();
        dxgiDevice = 0;
    }
    if (dxgiAdapter)
    {
        dxgiAdapter->Release();
        dxgiAdapter = 0;
    }
    if (dxgiFactory)
    {
        dxgiFactory->Release();
        dxgiFactory = 0;
    }

    OnResize();

    return true;
}