/*
 * Class:     org_lwjgl_d3d11_impl_DXGIFactoryImpl
 * Method:    nMakeWindowAssociation
 * Signature: (JJI)J
 */
extern "C" JNIEXPORT jlong JNICALL Java_org_lwjgl_d3d11_impl_DXGIFactoryImpl_nMakeWindowAssociation
(JNIEnv * env, jclass clazz, jlong thisPtr, jlong hwnd, jint flags) {
    IDXGIFactory* factory = (IDXGIFactory*)(intptr_t)thisPtr;
    HWND hWnd = (HWND)hwnd;
    UINT Flags = (UINT)flags;
    return (jlong)factory->MakeWindowAssociation(hWnd, Flags);
}
HRESULT CContextManager::CreateContext(HWND hWnd, int Width, int Height)
{

	D3D_FEATURE_LEVEL featureLevels[] =
	{
		D3D_FEATURE_LEVEL_11_0,		
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};
	UINT numFeatureLevels = ARRAYSIZE(featureLevels);

	DXGI_SWAP_CHAIN_DESC sd;
	ZeroMemory(&sd, sizeof(sd));
	sd.BufferCount = 1;
	sd.BufferDesc.Width = Width;
	sd.BufferDesc.Height = 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 = hWnd;
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = TRUE;
	sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

/*#if _DEBUG
	int flags = D3D11_CREATE_DEVICE_DEBUG;
#else
	int flags = 0;
#endif*/
	int flags = 0;
	
	if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, flags, featureLevels, numFeatureLevels,
		D3D11_SDK_VERSION, &sd, &m_SwapChain, &m_D3DDevice, NULL, &m_DeviceContext)))
	{
		return S_FALSE;
	}

#if _DEBUG
	HRESULT hr = m_D3DDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&m_D3DDebug));
	if (FAILED(hr))
		return hr;
#endif


	// treure el ALT+INTRO automàtic
	IDXGIFactory* dxgiFactory;
	hr = m_SwapChain->GetParent(__uuidof(IDXGIFactory), (void **)&dxgiFactory);
	assert(hr == S_OK);

	hr = dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);
	assert(hr == S_OK);

	dxgiFactory->Release();

	return S_OK;
}
Example #3
0
void SysMtgsThread::OpenPlugin()
{

	if( m_PluginOpened ) return;

	memcpy( RingBuffer.Regs, PS2MEM_GS, sizeof(PS2MEM_GS) );
	GSsetBaseMem( RingBuffer.Regs );
	GSirqCallback( dummyIrqCallback );

	int result;

	if( GSopen2 != NULL )
		result = GSopen2( (void*)pDsp, 1 | (renderswitch ? 4 : 0) );
	else
		result = GSopen( (void*)pDsp, "PCSX2", renderswitch ? 2 : 1 );


	GSsetVsync(EmuConfig.GS.FrameLimitEnable && EmuConfig.GS.VsyncEnable);

	if( result != 0 )
	{
		DevCon.WriteLn( "GSopen Failed: return code: 0x%x", result );
		throw Exception::PluginOpenError( PluginId_GS );
	}

// This is the preferred place to implement DXGI fullscreen overrides, using LoadLibrary.
// But I hate COM, I don't know to make this work, and I don't have DX10, so I give up
// and enjoy my working DX9 alt-enter instead. Someone else can fix this mess. --air

// Also: Prolly needs some DX10 header includes?  Which ones?  Too many, I gave up.

#if 0    // defined(__WXMSW__) && defined(_MSC_VER)
	wxDynamicLibrary dynlib( L"dxgi.dll" );
	SomeFuncTypeIDunno isThisEvenTheRightFunctionNameIDunno = dynlib.GetSymbol("CreateDXGIFactory");
	if( isThisEvenTheRightFunctionNameIDunno )
	{
		// Is this how LoadLibrary for COM works?  I dunno.  I dont care.

		IDXGIFactory* pFactory;
		hr = isThisEvenTheRightFunctionNameIDunno(__uuidof(IDXGIFactory), (void**)(&pFactory) );
		pFactory->MakeWindowAssociation((HWND)&pDsp, DXGI_MWA_NO_WINDOW_CHANGES);
		pFactory->Release();
	}
#endif

	m_PluginOpened = true;
	m_sem_OpenDone.Post();

	GSsetGameCRC( ElfCRC, 0 );
}
inline void DisableDXGIWindowChanges(IUnknown* device, HWND window)
{
    IDXGIDevice * pDXGIDevice;
    ThrowIfFailed(device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)));
    IDXGIAdapter * pDXGIAdapter;
    ThrowIfFailed(pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)));
    IDXGIFactory * pIDXGIFactory;
    ThrowIfFailed(pDXGIAdapter->GetParent(IID_PPV_ARGS(&pIDXGIFactory)));

    ThrowIfFailed(pIDXGIFactory->MakeWindowAssociation(window, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER));

    pIDXGIFactory->Release();
    pDXGIAdapter->Release();
    pDXGIDevice->Release();
}
Example #5
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 #6
0
HRESULT Create(HWND wnd)
{
	hWnd = wnd;
	HRESULT hr;

	RECT client;
	GetClientRect(hWnd, &client);
	xres = client.right - client.left;
	yres = client.bottom - client.top;

	hr = LoadDXGI();
	if (SUCCEEDED(hr)) hr = LoadD3D();
	if (SUCCEEDED(hr)) hr = LoadD3DCompiler();
	if (FAILED(hr))
	{
		UnloadDXGI();
		UnloadD3D();
		UnloadD3DCompiler();
		return hr;
	}

	IDXGIFactory* factory;
	IDXGIAdapter* adapter;
	IDXGIOutput* output;
	hr = PCreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
	if (FAILED(hr)) MessageBox(wnd, _T("Failed to create IDXGIFactory object"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);

	hr = factory->EnumAdapters(g_ActiveConfig.iAdapter, &adapter);
	if (FAILED(hr))
	{
		// try using the first one
		hr = factory->EnumAdapters(0, &adapter);
		if (FAILED(hr)) MessageBox(wnd, _T("Failed to enumerate adapters"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);
	}

	// TODO: Make this configurable
	hr = adapter->EnumOutputs(0, &output);
	if (FAILED(hr))
	{
		// try using the first one
		hr = adapter->EnumOutputs(0, &output);
		if (FAILED(hr)) MessageBox(wnd, _T("Failed to enumerate outputs!\n")
		                                _T("This usually happens when you've set your video adapter to the Nvidia GPU in an Optimus-equipped system.\n")
		                                _T("Set Dolphin to use the high-performance graphics in Nvidia's drivers instead and leave Dolphin's video adapter set to the Intel GPU."),
		                                _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);
	}

	// get supported AA modes
	aa_modes = EnumAAModes(adapter);
	if (g_Config.iMultisampleMode >= (int)aa_modes.size())
	{
		g_Config.iMultisampleMode = 0;
		UpdateActiveConfig();
	}

	DXGI_SWAP_CHAIN_DESC swap_chain_desc;
	memset(&swap_chain_desc, 0, sizeof(swap_chain_desc));
	swap_chain_desc.BufferCount = 1;
	swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swap_chain_desc.OutputWindow = wnd;
	swap_chain_desc.SampleDesc.Count = 1;
	swap_chain_desc.SampleDesc.Quality = 0;
	swap_chain_desc.Windowed = !g_ActiveConfig.bFullscreen;

	DXGI_OUTPUT_DESC out_desc;
	memset(&out_desc, 0, sizeof(out_desc));
	output->GetDesc(&out_desc);

	DXGI_MODE_DESC mode_desc;
	memset(&mode_desc, 0, sizeof(mode_desc));
	mode_desc.Width = out_desc.DesktopCoordinates.right - out_desc.DesktopCoordinates.left;
	mode_desc.Height = out_desc.DesktopCoordinates.bottom - out_desc.DesktopCoordinates.top;
	mode_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	mode_desc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	hr = output->FindClosestMatchingMode(&mode_desc, &swap_chain_desc.BufferDesc, nullptr);
	if (FAILED(hr)) MessageBox(wnd, _T("Failed to find a supported video mode"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);

	if (swap_chain_desc.Windowed)
	{
		// forcing buffer resolution to xres and yres..
		// this is not a problem as long as we're in windowed mode
		swap_chain_desc.BufferDesc.Width = xres;
		swap_chain_desc.BufferDesc.Height = yres;
	}

#if defined(_DEBUG) || defined(DEBUGFAST)
	// Creating debug devices can sometimes fail if the user doesn't have the correct
	// version of the DirectX SDK. If it does, simply fallback to a non-debug device.
	{
		hr = PD3D11CreateDeviceAndSwapChain(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr,
											D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_DEBUG,
											supported_feature_levels, NUM_SUPPORTED_FEATURE_LEVELS,
											D3D11_SDK_VERSION, &swap_chain_desc, &swapchain, &device,
											&featlevel, &context);
	}

	if (FAILED(hr))
#endif
	{
		hr = PD3D11CreateDeviceAndSwapChain(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr,
											D3D11_CREATE_DEVICE_SINGLETHREADED,
											supported_feature_levels, NUM_SUPPORTED_FEATURE_LEVELS,
											D3D11_SDK_VERSION, &swap_chain_desc, &swapchain, &device,
											&featlevel, &context);
	}

	if (FAILED(hr))
	{
		MessageBox(wnd, _T("Failed to initialize Direct3D.\nMake sure your video card supports at least D3D 10.0"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);
		SAFE_RELEASE(device);
		SAFE_RELEASE(context);
		SAFE_RELEASE(swapchain);
		return E_FAIL;
	}

	// prevent DXGI from responding to Alt+Enter, unfortunately DXGI_MWA_NO_ALT_ENTER
	// does not work so we disable all monitoring of window messages. However this
	// may make it more difficult for DXGI to handle display mode changes.
	hr = factory->MakeWindowAssociation(wnd, DXGI_MWA_NO_WINDOW_CHANGES);
	if (FAILED(hr)) MessageBox(wnd, _T("Failed to associate the window"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);

	SetDebugObjectName((ID3D11DeviceChild*)context, "device context");
	SAFE_RELEASE(factory);
	SAFE_RELEASE(output);
	SAFE_RELEASE(adapter);

	ID3D11Texture2D* buf;
	hr = swapchain->GetBuffer(0, IID_ID3D11Texture2D, (void**)&buf);
	if (FAILED(hr))
	{
		MessageBox(wnd, _T("Failed to get swapchain buffer"), _T("Dolphin Direct3D 11 backend"), MB_OK | MB_ICONERROR);
		SAFE_RELEASE(device);
		SAFE_RELEASE(context);
		SAFE_RELEASE(swapchain);
		return E_FAIL;
	}
	backbuf = new D3DTexture2D(buf, D3D11_BIND_RENDER_TARGET);
	SAFE_RELEASE(buf);
	CHECK(backbuf!=nullptr, "Create back buffer texture");
	SetDebugObjectName((ID3D11DeviceChild*)backbuf->GetTex(), "backbuffer texture");
	SetDebugObjectName((ID3D11DeviceChild*)backbuf->GetRTV(), "backbuffer render target view");

	context->OMSetRenderTargets(1, &backbuf->GetRTV(), nullptr);

	// BGRA textures are easier to deal with in TextureCache, but might not be supported by the hardware
	UINT format_support;
	device->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &format_support);
	bgra_textures_supported = (format_support & D3D11_FORMAT_SUPPORT_TEXTURE2D) != 0;

	stateman = new StateManager;
	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;
}
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;
}
Example #9
0
	bool Graphics::Initialize()
	{
		IDXGIFactory					*factory;
		IDXGIAdapter					*adapter;
		IDXGIOutput						*adapterOutput;
		DXGI_MODE_DESC					*displayModeList;
		DXGI_ADAPTER_DESC				adapterDesc;
		DXGI_SWAP_CHAIN_DESC			swapChainDesc;
		D3D_FEATURE_LEVEL				featureLevel;
		D3D11_BLEND_DESC				blendDesc;
		D3D11_DEPTH_STENCIL_DESC		depthStencilDesc;
		D3D11_SAMPLER_DESC				samplerDesc;
		unsigned int numModes, i, numerator, denominator, stringLength;
		int error;

		m_screenSize.cx = m_window->GetSize().cx;
		m_screenSize.cy = m_window->GetSize().cy;

		RETURN_FAIL( CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory) );
		RETURN_FAIL( factory->EnumAdapters(0, &adapter) );
		RETURN_FAIL( adapter->EnumOutputs(0, &adapterOutput) );
		RETURN_FAIL( adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL) );

		displayModeList = new DXGI_MODE_DESC[numModes];

		RETURN_FAIL( adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList) );

		for(i = 0; i < numModes; ++i)
		{
			if(displayModeList[i].Width == m_screenSize.cx)
			{
				if(displayModeList[i].Height == m_screenSize.cy)
				{
					numerator = displayModeList[i].RefreshRate.Numerator;
					denominator = displayModeList[i].RefreshRate.Denominator;
				}
			}
		}

		RETURN_FAIL( adapter->GetDesc(&adapterDesc) );

		m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);

		RETURN_ERROR( wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128) );

		SAFE_DELETE_ARRAY( displayModeList );
		SAFE_RELEASE(adapterOutput);
		SAFE_RELEASE(adapter);
		SAFE_RELEASE(factory);

		ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
		swapChainDesc.BufferCount = 2;
		swapChainDesc.Windowed = true;
		swapChainDesc.BufferDesc.Width = m_screenSize.cx;
		swapChainDesc.BufferDesc.Height = m_screenSize.cy;
		swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		if(m_vsync_enabled)
		{
			swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
			swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
		}
		else
		{
			swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
			swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
		}
		swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		swapChainDesc.OutputWindow = m_window->GetHWnd();
		swapChainDesc.SampleDesc.Count = 1;
		swapChainDesc.SampleDesc.Quality = 0;
		swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
		swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
		swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

		featureLevel = D3D_FEATURE_LEVEL_11_0;
		RETURN_FAIL( D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext) );
		RETURN_FAIL( m_swapChain->GetParent(__uuidof(IDXGIFactory), (LPVOID*)&factory) );
		RETURN_FAIL( factory->MakeWindowAssociation(m_window->GetHWnd(), DXGI_MWA_NO_WINDOW_CHANGES) );

		ZeroMemory( &blendDesc, sizeof( blendDesc ) );
		blendDesc.AlphaToCoverageEnable = true;
		blendDesc.RenderTarget[0].BlendEnable = TRUE;
		blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
		blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
		blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
		blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
		blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
		blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
		blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
		RETURN_FAIL( m_device->CreateBlendState( &blendDesc, &m_blendAlpha ) );

		m_deviceContext->OMSetBlendState( m_blendAlpha, NULL, 0xFFFFFF );

		ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
		depthStencilDesc.DepthEnable = true;
		depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
		depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
		depthStencilDesc.StencilEnable = true;
		depthStencilDesc.StencilReadMask = 0xFF;
		depthStencilDesc.StencilWriteMask = 0xFF;
		depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
		depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
		depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
		depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
		depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
		RETURN_FAIL( m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState) );

		m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

		ZeroMemory( &samplerDesc, sizeof( samplerDesc ) );
		samplerDesc.AddressU        = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.AddressV        = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.AddressW        = D3D11_TEXTURE_ADDRESS_CLAMP;
		samplerDesc.ComparisonFunc  = D3D11_COMPARISON_NEVER;
		samplerDesc.Filter          = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
		samplerDesc.MaxLOD          = D3D11_FLOAT32_MAX;
		RETURN_FAIL( m_device->CreateSamplerState( &samplerDesc, &m_samplerLinear ) );

		return CreateTargets();
	}
Example #10
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;
}
//
// FUNCTION: GraphicsDeviceInterface::Initialize()
//
// PURPOSE: Initializes Direct3D
// 
bool GraphicsDeviceInterface::Initialize(HWND hWnd, WindowSize* wind) {
	HRESULT hResult;

	// Clear the struct
	ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

	// Set the swap chain values
	scd.BufferCount = 1;								// one back buffer
	scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;	// use 32 bit color
	scd.BufferDesc.Width = wind->getWidth();			// set width using windowSize object
	scd.BufferDesc.Height = wind->getHeight();			// set height using windowSize object
	scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;	// swap chain is output
	scd.OutputWindow = hWnd;							// window to render into
	scd.SampleDesc.Count = 4;							// use 4 multisamples for antialiasing
	scd.Windowed = wind->getWindowed();					// Sets windowed mode
	scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;	// Allow full-screen switching


	// Create the device, context, and swap chain
	hResult = D3D11CreateDeviceAndSwapChain(NULL,
		D3D_DRIVER_TYPE_HARDWARE,
		NULL,
		NULL, //D3D_FEATURE_LEVEL_10_0,
		NULL,
		NULL,
		D3D11_SDK_VERSION,
		&scd,
		&m_Swapchain,
		&m_Device,
		NULL,
		&m_Context);

	if (hResult != S_OK)
	{
		return FALSE;
	}

	// Retrieves the IDXGIFactory that created "m_Device"
	IDXGIDevice *pDXGIDevice;
	m_Device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
	IDXGIAdapter *pDXGIAdapter;
	pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter);
	IDXGIFactory *pDXGIFactory;
	pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pDXGIFactory);

	// Disables the use of Alt-Enter to switch between fullscreen/windowed
	pDXGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);
	
	// Resized the target (window or screen resolution) and back buffers
	m_Swapchain->ResizeTarget(&scd.BufferDesc);
	m_Swapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, scd.Flags);

	// Get the back buffer address
	ID3D11Texture1D *pBackBuffer;
	m_Swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

	// Use the back buffer address to create a render target
	m_Device->CreateRenderTargetView(pBackBuffer, NULL, &m_BackBuffer);
	pBackBuffer->Release();

	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;

	ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

	depthBufferDesc.Width = wind->getWidth();
	depthBufferDesc.Height = wind->getHeight();
	depthBufferDesc.MipLevels = 1;
	depthBufferDesc.ArraySize = 1;
	depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthBufferDesc.SampleDesc.Count = 4;
	depthBufferDesc.SampleDesc.Quality = 0;
	depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthBufferDesc.CPUAccessFlags = 0;
	depthBufferDesc.MiscFlags = 0;

	m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer);

	// Initialize the description of the stencil state.
	ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

	// Set up the description of the stencil state.
	depthStencilDesc.DepthEnable = true;
	depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

	depthStencilDesc.StencilEnable = true;
	depthStencilDesc.StencilReadMask = 0xFF;
	depthStencilDesc.StencilWriteMask = 0xFF;

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

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

	m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState);

	m_Context->OMSetDepthStencilState(m_DepthStencilState, 1);
	
	// Initailze the depth stencil view.
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

	// Set up the depth stencil view description.
	depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	depthStencilViewDesc.Texture2D.MipSlice = 0;

	m_Device->CreateDepthStencilView(m_DepthStencilBuffer, NULL, &m_DepthStencilView);

	// set the render target as the back buffer
	m_Context->OMSetRenderTargets(1, &m_BackBuffer, m_DepthStencilView);

	// Set the viewport using windowSize object
	D3D11_VIEWPORT viewport;
	ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.Width = (float)wind->getWidth();
	viewport.Height = (float)wind->getHeight();

	m_Context->RSSetViewports(1, &viewport);

	// Setup the projection matrix.
	float fieldOfView = (float)D3DX_PI / 4.0f;
	float screenAspect = (float)wind->getWidth() / (float)wind->getHeight();

	// TODO: Make constants for screen depth and screen near.
	// Create the projection matrix for 3D rendering.
	D3DXMatrixPerspectiveFovLH(&m_projMatrix, fieldOfView, screenAspect, 0.1f, 1000.0f);

	InitPipeline();
	InitGraphics();


	return TRUE;
}
Example #12
0
File: MTGS.cpp Project: tsiru/pcsx2
void SysMtgsThread::OpenPlugin()
{
	if( m_PluginOpened ) return;

	memcpy_aligned( RingBuffer.Regs, PS2MEM_GS, sizeof(PS2MEM_GS) );
	GSsetBaseMem( RingBuffer.Regs );
	GSirqCallback( dummyIrqCallback );

	int result;

	if( GSopen2 != NULL )
		result = GSopen2( (void*)pDsp, 1 | (renderswitch ? 4 : 0) );
	else
		result = GSopen( (void*)pDsp, "PCSX2", renderswitch ? 2 : 1 );

	// Vsync on / off ?
	if( renderswitch )
	{
		Console.Indent(2).WriteLn( "Forced software switch enabled." );
		if (EmuConfig.GS.VsyncEnable && !EmuConfig.GS.ManagedVsync)
		{
			// Better turn Vsync off now, as in most cases sw rendering is not fast enough to support a steady 60fps.
			// Having Vsync still enabled then means a big cut in speed and sloppy rendering.
			// It's possible though that some users have very fast machines, and rather kept Vsync enabled,
			// but let's assume this is the minority. At least for now ;)
			GSsetVsync( false );
			Console.Indent(2).WriteLn( "Vsync temporarily disabled" );
		}
	}
	else
	{
		GSsetVsync( EmuConfig.GS.FrameLimitEnable && EmuConfig.GS.VsyncEnable );
	}

	if( result != 0 )
	{
		DevCon.WriteLn( "GSopen Failed: return code: 0x%x", result );
		throw Exception::PluginOpenError( PluginId_GS );
	}

// This is the preferred place to implement DXGI fullscreen overrides, using LoadLibrary.
// But I hate COM, I don't know to make this work, and I don't have DX10, so I give up
// and enjoy my working DX9 alt-enter instead. Someone else can fix this mess. --air

// Also: Prolly needs some DX10 header includes?  Which ones?  Too many, I gave up.

#if 0    // defined(__WXMSW__) && defined(_MSC_VER)
	wxDynamicLibrary dynlib( L"dxgi.dll" );
	SomeFuncTypeIDunno isThisEvenTheRightFunctionNameIDunno = dynlib.GetSymbol("CreateDXGIFactory");
	if( isThisEvenTheRightFunctionNameIDunno )
	{
		// Is this how LoadLibrary for COM works?  I dunno.  I dont care.

		IDXGIFactory* pFactory;
		hr = isThisEvenTheRightFunctionNameIDunno(__uuidof(IDXGIFactory), (void**)(&pFactory) );
		pFactory->MakeWindowAssociation((HWND)&pDsp, DXGI_MWA_NO_WINDOW_CHANGES);
		pFactory->Release();
	}
#endif

	m_PluginOpened = true;
	m_sem_OpenDone.Post();

	GSsetGameCRC( ElfCRC, 0 );
}
bool D3D10App::initAPI(const DXGI_FORMAT backBufferFmt, const DXGI_FORMAT depthBufferFmt, const int samples, const uint flags){
	backBufferFormat = backBufferFmt;
	depthBufferFormat = depthBufferFmt;
	msaaSamples = samples;

//	if (screen >= GetSystemMetrics(SM_CMONITORS)) screen = 0;

	IDXGIFactory *dxgiFactory;
	if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void **) &dxgiFactory))){
		ErrorMsg("Couldn't create DXGIFactory");
		return false;
	}

	IDXGIAdapter *dxgiAdapter;
	if (dxgiFactory->EnumAdapters(0, &dxgiAdapter) == DXGI_ERROR_NOT_FOUND){
		ErrorMsg("No adapters found");
		return false;
	}

//	DXGI_ADAPTER_DESC adapterDesc;
//	dxgiAdapter->GetDesc(&adapterDesc);

	IDXGIOutput *dxgiOutput;
	if (dxgiAdapter->EnumOutputs(0, &dxgiOutput) == DXGI_ERROR_NOT_FOUND){
		ErrorMsg("No outputs found");
		return false;
	}

	DXGI_OUTPUT_DESC oDesc;
	dxgiOutput->GetDesc(&oDesc);


	// Find a suitable fullscreen format
	int targetHz = 85;
	DXGI_RATIONAL fullScreenRefresh;
	int fsRefresh = 60;
	fullScreenRefresh.Numerator = fsRefresh;
	fullScreenRefresh.Denominator = 1;
	char str[128];

	uint nModes = 0;
	dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, NULL);
	DXGI_MODE_DESC *modes = new DXGI_MODE_DESC[nModes];
	dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, modes);

	resolution->clear();
	for (uint i = 0; i < nModes; i++){
		if (modes[i].Width >= 640 && modes[i].Height >= 480){
			sprintf(str, "%dx%d", modes[i].Width, modes[i].Height);
			int index = resolution->addItemUnique(str);

			if (int(modes[i].Width) == fullscreenWidth && int(modes[i].Height) == fullscreenHeight){
				int refresh = modes[i].RefreshRate.Numerator / modes[i].RefreshRate.Denominator;
				if (abs(refresh - targetHz) < abs(fsRefresh - targetHz)){
					fsRefresh = refresh;
					fullScreenRefresh = modes[i].RefreshRate;
				}
				resolution->selectItem(index);
			}
		}
	}
	delete modes;

	sprintf(str, "%s (%dx%d)", getTitle(), width, height);

	DWORD wndFlags = 0;
	int x, y, w, h;
	if (fullscreen){
		wndFlags |= WS_POPUP;
		x = y = 0;
		w = width;
		h = height;
	} else {
		wndFlags |= WS_OVERLAPPEDWINDOW;

		RECT wRect;
		wRect.left = 0;
		wRect.right = width;
		wRect.top = 0;
		wRect.bottom = height;
		AdjustWindowRect(&wRect, wndFlags, FALSE);

		MONITORINFO monInfo;
		monInfo.cbSize = sizeof(monInfo);
		GetMonitorInfo(oDesc.Monitor, &monInfo);

		w = min(wRect.right  - wRect.left, monInfo.rcWork.right  - monInfo.rcWork.left);
		h = min(wRect.bottom - wRect.top,  monInfo.rcWork.bottom - monInfo.rcWork.top);
		x = (monInfo.rcWork.left + monInfo.rcWork.right  - w) / 2;
		y = (monInfo.rcWork.top  + monInfo.rcWork.bottom - h) / 2;
	}


	hwnd = CreateWindow("Humus", str, wndFlags, x, y, w, h, HWND_DESKTOP, NULL, hInstance, NULL);

	RECT rect;
	GetClientRect(hwnd, &rect);

	// Create device and swap chain
	DXGI_SWAP_CHAIN_DESC sd;
	memset(&sd, 0, sizeof(sd));
	sd.BufferDesc.Width  = rect.right;
	sd.BufferDesc.Height = rect.bottom;
	sd.BufferDesc.Format = backBufferFormat;
	sd.BufferDesc.RefreshRate = fullScreenRefresh;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount = 1;
	sd.OutputWindow = hwnd;
	sd.Windowed = (BOOL) (!fullscreen);
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

	DWORD deviceFlags = D3D10_CREATE_DEVICE_SINGLETHREADED;
#ifdef _DEBUG
    deviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif

	if (FAILED(D3D10CreateDevice(dxgiAdapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, D3D10_SDK_VERSION, &device))){
		ErrorMsg("Couldn't create D3D10 device");
		return false;
	}

	while (msaaSamples > 0){
		UINT nQuality;
		if (SUCCEEDED(device->CheckMultisampleQualityLevels(backBufferFormat, msaaSamples, &nQuality)) && nQuality > 0){
			if ((flags & NO_SETTING_CHANGE) == 0) antiAliasSamples = msaaSamples;
			break;
		} else {
			msaaSamples -= 2;
		}
	}
	sd.SampleDesc.Count = msaaSamples;
	sd.SampleDesc.Quality = 0;

	if (FAILED(dxgiFactory->CreateSwapChain(device, &sd, &swapChain))){
		ErrorMsg("Couldn't create swapchain");
		return false;
	}

	// We'll handle Alt-Enter ourselves thank you very much ...
	dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);

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


	if (!createBuffers()) return false;


	if (fullscreen){
		captureMouse(!configDialog->isVisible());
	}

	renderer = new Direct3D10Renderer(device);
	((Direct3D10Renderer *) renderer)->setFrameBuffer(backBufferRTV, depthBufferDSV);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Example #14
0
/* Initialize DirectX11 Graphics */
void nlInitD3D11( HWND hWnd, bool isFullScreen, nlEngineContext& cxt )
{
    cxt.hwnd = hWnd;

    IDXGIAdapter* pAdapter		= NULL;
    IDXGIDevice1* pDXGI			= NULL;
    IDXGIFactory* pDXGIFactory	= NULL;
    D3D_FEATURE_LEVEL fl;
    /* FeatureLevelは10.1(SM4.0)で固定する */
    const D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_10_0;
    NL_HR_VALID( D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE,(HMODULE)0,0,&featureLevel,1, D3D11_SDK_VERSION, &cxt.d3dDevice, &fl, &cxt.d3dContext ) );
    NL_HR_ASSSERT( fl == D3D_FEATURE_LEVEL_10_0 );
    /* create DXGI */
    NL_HR_VALID( cxt.d3dDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&pDXGI) );
    /* get adapter info */
    NL_HR_VALID( pDXGI->GetAdapter(&pAdapter) );
    NL_HR_ASSSERT( pAdapter != NULL );
    /* get factory */
    NL_HR_VALID( pAdapter->GetParent( __uuidof(IDXGIFactory), (void**)&pDXGIFactory)  );
    NL_HR_ASSSERT( pDXGIFactory != NULL );
    {/* create swap chain */
        DXGI_SWAP_CHAIN_DESC swapChainDesc =
        {
            /* DXGI_MODE_DESC */
            {cxt.rendertargets[0].width_, cxt.rendertargets[0].height_, {60,1}, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, DXGI_MODE_SCALING_UNSPECIFIED },
            /* DXGI_SAMPLE_DESC */
            {1, 0},
            /* BufferUsage */
            DXGI_USAGE_RENDER_TARGET_OUTPUT,
            /* BufferCount */
            3,
            /* OutputWindow */
            hWnd,
            /* Windowed */
            !isFullScreen,
            /* DXGI_SWAP_EFFECT */
            DXGI_SWAP_EFFECT_DISCARD,
            /* Flags */
            DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH,
        };
        NL_HR_VALID( pDXGIFactory->CreateSwapChain(cxt.d3dDevice, &swapChainDesc, &cxt.dxgiSwpChain) );
    }
    /* Disalbe "Alt+Enter" and so on. must call this after CreateSwapChain() call MakeWindowAssociation(). */
    NL_HR_VALID( pDXGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_PRINT_SCREEN ));
    {/* get backbuffer view */
        D3D11_TEXTURE2D_DESC desc;
        cxt.rendertargets[0].renderTargetShaderResource_ = NULL;
        NL_HR_VALID( cxt.dxgiSwpChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), (void**)(&cxt.rendertargets[0].renderTarget_) ) );
        NL_HR_VALID( cxt.d3dDevice->CreateRenderTargetView( cxt.rendertargets[0].renderTarget_, NULL, &cxt.rendertargets[0].renderTargetView_ ) );
        cxt.rendertargets[0].renderTarget_->GetDesc( &desc );
        cxt.rendertargets[0].width_  = desc.Width;
        cxt.rendertargets[0].height_ = desc.Height;
    }
    {/* create and set depthStencil */
        D3D11_TEXTURE2D_DESC depthDesc =
        {
            /*UINT Width;*/
            cxt.rendertargets[0].width_,
            /*UINT Height;*/
            cxt.rendertargets[0].height_,
            /*UINT MipLevels;*/
            1,
            /*UINT ArraySize;*/
            1,
            /*DXGI_FORMAT Format;*/
            DXGI_FORMAT_D24_UNORM_S8_UINT,
            /*DXGI_SAMPLE_DESC SampleDesc;*/
            {1,0},
            /*D3D11_USAGE Usage;*/
            D3D11_USAGE_DEFAULT,
            /*UINT BindFlags;*/
            D3D11_BIND_DEPTH_STENCIL,
            /*UINT CPUAccessFlags;*/
            0,
            /*UINT MiscFlags;*/
            0,
        };
        D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc =
        {
            /* DXGI_FORMAT Format; */
            DXGI_FORMAT_D24_UNORM_S8_UINT,
            /* D3D11_DSV_DIMENSION ViewDimension; */
            D3D11_DSV_DIMENSION_TEXTURE2DMS,
            /* UINT Flags; */
            0,
            /* D3D11_TEX2D_DSV */
            {0}
        };
        cxt.depthStencils[0].width  = depthDesc.Width;
        cxt.depthStencils[0].height = depthDesc.Height;
        NL_HR_VALID( cxt.d3dDevice->CreateTexture2D(&depthDesc, NULL, &cxt.depthStencils[0].tex ) );
        NL_HR_VALID( cxt.d3dDevice->CreateDepthStencilView(cxt.depthStencils[0].tex, &dsvDesc, &cxt.depthStencils[0].view) );
    }
    cxt.d3dContext->OMSetRenderTargets(1, &cxt.rendertargets[0].renderTargetView_, cxt.depthStencils[0].view );

    /* デフォルトの設定 */
    D3D11_VIEWPORT	viewportDesc =
    {
        /* FLOAT TopLeftX; */
        0.0f,
        /* FLOAT TopLeftY; */
        0.0f,
        /* FLOAT Width; */
        (FLOAT)cxt.rendertargets[0].width_,
        /* FLOAT Height; */
        (FLOAT)cxt.rendertargets[0].height_,
        /* FLOAT MinDepth; */
        0.0f,
        /* FLOAT MaxDepth; */
        1.0f,
    };
    cxt.viewportDesc = viewportDesc;
    nlUpdateViewPortSetting(cxt);    
    /**/
    D3D11_RASTERIZER_DESC rasterDesc =
    {
        /* D3D11_FILL_MODE FillMode; */
        D3D11_FILL_SOLID,
        /* D3D11_CULL_MODE CullMode; */
        D3D11_CULL_NONE,
        /* BOOL FrontCounterClockwise; */
        0,
        /* INT DepthBias; */
        0,
        /* FLOAT DepthBiasClamp; */
        0,
        /* FLOAT SlopeScaledDepthBias; */
        0,
        /* BOOL DepthClipEnable; */
        TRUE,
        /* BOOL ScissorEnable; */
        0,
        /* BOOL MultisampleEnable; */
        0,
        /* BOOL AntialiasedLineEnable; */
        0
    };
    cxt.rasterDesc = rasterDesc;
    nlUpdateRasterizeSetting(cxt);
    /**/
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc =
    {
        /* BOOL DepthEnable; */
        TRUE,
        /* D3D11_DEPTH_WRITE_MASK DepthWriteMask; */
        D3D11_DEPTH_WRITE_MASK_ALL,
        /* D3D11_COMPARISON_FUNC DepthFunc; */
        D3D11_COMPARISON_LESS,
        /* BOOL StencilEnable; */
        FALSE,
        /* UINT8 StencilReadMask; */
        0,
        /* UINT8 StencilWriteMask; */
        0,
        /* D3D11_DEPTH_STENCILOP_DESC FrontFace; ダミーデータであることに注意*/
        { D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_NEVER },
        /* D3D11_DEPTH_STENCILOP_DESC BackFace; */
        { D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_NEVER },
    };
    ID3D11DepthStencilState* depthStencilState;
    cxt.d3dDevice->CreateDepthStencilState(&depthStencilDesc, &depthStencilState );
    cxt.d3dContext->OMSetDepthStencilState(depthStencilState, 0);
    depthStencilState->Release();
    /**/
    D3D11_SAMPLER_DESC samplerDesc = 
    {
        /*D3D11_FILTER Filter;*/
        D3D11_FILTER_MIN_MAG_MIP_LINEAR,
        /* D3D11_TEXTURE_ADDRESS_MODE AddressU;*/
        D3D11_TEXTURE_ADDRESS_WRAP,
        /* D3D11_TEXTURE_ADDRESS_MODE AddressV;*/
        D3D11_TEXTURE_ADDRESS_WRAP,
        /* D3D11_TEXTURE_ADDRESS_MODE AddressW;*/
        D3D11_TEXTURE_ADDRESS_WRAP,
        /* FLOAT MipLODBias;*/
        0.0f,
        /* UINT MaxAnisotropy;*/
        1,
        /* D3D11_COMPARISON_FUNC ComparisonFunc;*/
        D3D11_COMPARISON_ALWAYS,
        /* FLOAT BorderColor[ 4 ];*/
        {0.0f,0.0f,0.0f,0.0f},
        /* FLOAT MinLOD;*/
        0,
        /* FLOAT MaxLOD;*/
        D3D11_FLOAT32_MAX,
    };
    cxt.samplerDesc = samplerDesc;
    /**/
    nlUpdateSamplerState(cxt);
}