• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
DEVLiN

OpenGL
[SOLVED] D3D11 and Direct2D

14 posts in this topic

Greetings! (Before we begin, yes - I've searched on these forums for answers, they've not fully helped though) Having recently acquired a brand new computer with windows 7 and a dx11 graphics card - I wanted to finally get started implementing the dx11-only stuff I've been waiting to do for quite some time now. (Tesselation, Compute Shaders etc. Worth mentioning is that I've recently converted from OpenGL to D3D, so a lot of this stuff is new to me) However, getting Direct2D and D3D11 to work together seem to be quite a hassle. I planned on using D2D and DWrite for text and UI stuff as they seem to provide some really neat stuff. However, where all the samples show neatly how to acquire the backbuffer into a DXGI surface for use with Direct2D; for some reason, this doesn't seem to work with a D3D11 device at all (not even using feature level 10_1). I understand that there exists what I would call a "hack" to get this working (using 2 devices, shared full-screen surfaces and sync-mutexes, resulting in ugly, error-prone code - frame delays and unnecessary video memory going to waste *yuck*). However, I haven't gotten this to work either (OpenSharedResource seem to return E_INVALIDARG no matter what args I pass in.), not that I think it's the way forward at all. I don't have access to the code right now, but if someone has the energy to help me through that I'll post it tonight. Also, it doesn't seem to matter in what order I include headers and libraries - CreateDxgiSurfaceRenderTarget always return E_NOINTERFACE when trying to use the D3D11 device backbuffer instead of the double-device method. This should (?) mean that I'm using the wrong or mixed headers/libs - but I've tried getting them all from DXSDK_DIR (August 2009) or from the WinSDK (7.0A) to no avail. Is there any way to check which headers/libs are actually getting used? I'm using Visual Studio 2010 beta 2. I installed the DXSDK after the WinSDK if that matters at all. Another possible(?) solution: I have also attempted to use a hwndrendertarget until proper D3D11 support is added in as it doesn't require additional devices or mutexes and it renders - but not the way I would want it. (No E_NOINTERFACE result when using this method). The screen flickers between the two presentations irregularly. Isn't the D2D1_PRESENT_OPTIONS_NONE supposed to wait until display refresh? Do I have to turn vsync on for this to happen? Is it the double-buffering of the D3Ddevice that's causing problems? And my final question - is there any way to let the HwndRenderTarget only draw where I draw and not clear the background? (I've tried handling WM_ERASEBKGND but that doesn't seem to affect it at all). Is this method of combining D3D11 and D2D bound to fail? Sorry if some of it is not readable. English isn't my primary language but I've tried my hardest to make it passable. [Edited by - DEVLiN on November 10, 2009 5:32:25 AM]
0

Share this post


Link to post
Share on other sites
Have you used the D3D11_CREATE_DEVICE_BGRA_SUPPORT flag when creating the device? This is required for Direct2D interoperability. See D3D11_CREATE_DEVICE_FLAG in the SDK docs.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by ET3D
Have you used the D3D11_CREATE_DEVICE_BGRA_SUPPORT flag when creating the device? This is required for Direct2D interoperability. See D3D11_CREATE_DEVICE_FLAG in the SDK docs.

I'm using D3D10_CREATE_DEVICE_BGRA_SUPPORT at the moment. I can change this to D3D11_CREATE_DEVICE_BGRA_SUPPORT tonight but I have a feeling it will not matter - sadly. Thanks though!

Erik: I've read it through (thus the 2 devices comment in my original post) - but couldn't get it to work as OpenSharedResource fails with E_INVALIDARG. Definitely a coding error on my behalf due to being relatively new to D3D (coming from OpenGL). And unless I missed it there was no code samples other than the pseudo code ones. Sadly, neither the DXSDK (August 2009) nor the 7.0A WinSDK seem to provide samples for D2D at all unless I missed a setting somewhere. (they do both provide headers and libs for it though *sigh*)

I would rather get the HWND-method working if at all possible rather than the two-device method though. If they do provide proper interop soon enough the HWND-method would only require one #define and two lines change.

It would be nice to get some feedback on "we're working on this" or "not going to happen at all" because if it's soon enough I could work on other parts of the code in the meantime. If not at all, biting the ugly bullet would be the only way.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by DEVLiN
I'm using D3D10_CREATE_DEVICE_BGRA_SUPPORT at the moment. I can change this to D3D11_CREATE_DEVICE_BGRA_SUPPORT tonight but I have a feeling it will not matter - sadly. Thanks though!

I suspect you're right, since they have the same value.

There's a D2D-D3D interop sample here at Microsoft's site. It uses D3D 10.1, which may be good enough for you.

0

Share this post


Link to post
Share on other sites
Make sure the D3D11 and D3D10.1 device are created on the same DXGI1.1 adapter, and create the shared texture with render target as well as shader resource usage. Also remember the D3D10.1 device must also use the BGRA flag. For me this doesn't work with feature level 10.0 (I seem to recall there was a mention in the old thread that BGRA was removed in 10.0), and I need to use the 9.3 feature level. On my laptop I must use 9.1.

Here's an example I've tested with, it's just one function creating the resources from top to bottom that you can compare with if you still get errors (it should run pasted to an empty VC++ project). It uses CopyResource to put the D2D content in the back-buffer which you probably don't want, but the set-up is the same and it's a bit less code than setting up shaders to draw it with a quad.

#include <windows.h>
#include <D3D11.h>
#include <D3D10_1.h>
#include <D2D1.h>
#include <DXErr.h>
#include <DXGI.h>

// Libs
#pragma comment (lib, "D3D11.lib")
#pragma comment (lib, "D3D10_1.lib")
#pragma comment (lib, "D2D1.lib")
#pragma comment (lib, "DXErr.lib")
#pragma comment (lib, "DXGI.lib")


LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);



// Main
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Register windowclass
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.lpszClassName = TEXT("MyClass");
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wc);

// Create window
HWND hWnd = CreateWindow(
wc.lpszClassName,
TEXT("D3D11 with Direct2D"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);

// Create DXGI factory to enumerate adapters
IDXGIFactory1 *pDXGIFactory;

HRESULT hResult = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pDXGIFactory);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("CreateDXGIFactory1"), MB_OK);
return 0;
}

// Use the first adapter
IDXGIAdapter1 *pAdapter;

hResult = pDXGIFactory->EnumAdapters1(0, &pAdapter);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("EnumAdapters1"), MB_OK);
return 0;
}

pDXGIFactory->Release();

// Create D3D11 device and swapchain
DXGI_SWAP_CHAIN_DESC scd;
ID3D11Device *pDevice11;
IDXGISwapChain *pSwapChain;
ID3D11DeviceContext *pImmediateContext;

ZeroMemory(&scd, sizeof(scd));
scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
scd.SampleDesc.Count = 1;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.BufferCount = 1;
scd.OutputWindow = hWnd;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.Windowed = TRUE;

hResult = D3D11CreateDeviceAndSwapChain(
pAdapter,
D3D_DRIVER_TYPE_UNKNOWN,
NULL,
D3D11_CREATE_DEVICE_DEBUG |
D3D11_CREATE_DEVICE_BGRA_SUPPORT |
D3D11_CREATE_DEVICE_SINGLETHREADED,
NULL,
0,
D3D11_SDK_VERSION,
&scd,
&pSwapChain,
&pDevice11,
NULL,
&pImmediateContext
);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("D3D11CreateDeviceAndSwapChain"), MB_OK);
return 0;
}

// Create D3D10.1 device
ID3D10Device1 *pDevice101;

hResult = D3D10CreateDevice1(
pAdapter,
D3D10_DRIVER_TYPE_HARDWARE,
NULL,
D3D10_CREATE_DEVICE_DEBUG |
D3D10_CREATE_DEVICE_BGRA_SUPPORT |
D3D10_CREATE_DEVICE_SINGLETHREADED,
D3D10_FEATURE_LEVEL_9_3,
D3D10_1_SDK_VERSION,
&pDevice101
);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("D3D10CreateDevice1"), MB_OK);
return 0;
}

pAdapter->Release();

// Get the D3D11 back-buffer
ID3D11Texture2D *pBackBuffer11;
D3D11_TEXTURE2D_DESC backBufferDesc;

hResult = pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer11));
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSwapChain->GetBuffer for ID3D11Texture2D"), MB_OK);
return 0;
}

pBackBuffer11->GetDesc(&backBufferDesc);

// Create the shared texture to draw D2D content to
D3D11_TEXTURE2D_DESC sharedTextureDesc;
ID3D11Texture2D *pSharedTexture11;

ZeroMemory(&sharedTextureDesc, sizeof(sharedTextureDesc));
sharedTextureDesc.Width = backBufferDesc.Width;
sharedTextureDesc.Height = backBufferDesc.Height;
sharedTextureDesc.MipLevels = 1;
sharedTextureDesc.ArraySize = 1;
sharedTextureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
sharedTextureDesc.SampleDesc.Count = 1;
sharedTextureDesc.Usage = D3D11_USAGE_DEFAULT;
sharedTextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
sharedTextureDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;

hResult = pDevice11->CreateTexture2D(&sharedTextureDesc, NULL, &pSharedTexture11);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pDevice11->CreateTexture2D for shared texture"), MB_OK);
return 0;
}

// Get the keyed mutex for the shared texture (for D3D11)
IDXGIKeyedMutex *pKeyedMutex11;

hResult = pSharedTexture11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&pKeyedMutex11);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSharedTexture11->QueryInterface for IDXGIKeyedMutex"), MB_OK);
return 0;
}

// Get the shared handle needed to open the shared texture in D3D10.1
IDXGIResource *pSharedResource11;
HANDLE hSharedHandle11;

hResult = pSharedTexture11->QueryInterface(__uuidof(IDXGIResource), (void**)&pSharedResource11);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSharedTexture11->QueryInterface for IDXGIResource"), MB_OK);
return 0;
}

pSharedResource11->GetSharedHandle(&hSharedHandle11);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSharedResource11->GetSharedHandle"), MB_OK);
return 0;
}

pSharedResource11->Release();

// Open the surface for the shared texture in D3D10.1
IDXGISurface1 *pSharedSurface10;

hResult = pDevice101->OpenSharedResource(hSharedHandle11, __uuidof(IDXGISurface1), (void**)(&pSharedSurface10));
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pDevice101->OpenSharedResource"), MB_OK);
return 0;
}

// Get the keyed mutex for the shared texture (for D3D10.1)
IDXGIKeyedMutex *pKeyedMutex10;

hResult = pSharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&pKeyedMutex10);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSharedSurface10->QueryInterface for IDXGIKeyedMutex"), MB_OK);
return 0;
}

// Create D2D factory
ID2D1Factory *pD2DFactory;

hResult = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void**)&pD2DFactory);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("D2D1CreateFactory"), MB_OK);
return 0;
}

// Create D2D render target from the surface for the shared texture, which was opened in D3D10.1
D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties;
ID2D1RenderTarget *pD2DRenderTarget;

ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties));
renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED);

hResult = pD2DFactory->CreateDxgiSurfaceRenderTarget(pSharedSurface10, &renderTargetProperties, &pD2DRenderTarget);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pD2DFactory->CreateDxgiSurfaceRenderTarget"), MB_OK);
return 0;
}

pSharedSurface10->Release();
pD2DFactory->Release();

// Create a solid color brush to draw something with
ID2D1SolidColorBrush *pBrush;

hResult = pD2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 0.0f, 1.0f), &pBrush);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pD2DRenderTarget->CreateSolidColorBrush"), MB_OK);
return 0;
}

// Tell the debug output to be quiet..
pDevice101->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);

// Main loop
float angle = 0.0f;

ShowWindow(hWnd, nCmdShow);
while(true) {
MSG msg;
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) {
if(msg.message == WM_QUIT)
break;
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else {
// Sync the shared texture for D3D10.1
pKeyedMutex10->AcquireSync(0, INFINITE);

// Draw D2D content
angle += 360.0f / 200.0f;

pD2DRenderTarget->BeginDraw();

pD2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.7f, 0.0f, 1.0f));

D2D1_SIZE_F size = pD2DRenderTarget->GetSize();

pD2DRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(angle, D2D1::Point2F(size.width/2.0f, size.height/2.0f)));

pBrush->SetColor(D2D1::ColorF(1.0f, 1.0f, 0.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width/2.0f, size.height/2.0f), size.height/3.0f, size.height/3.0f),
pBrush,
32.0f,
NULL
);

pBrush->SetColor(D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width/4.0f, size.height/2.0f), size.height/4.0f, size.height/4.0f),
pBrush,
32.0f,
NULL
);

pBrush->SetColor(D2D1::ColorF(0.0f, 0.0f, 1.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width*3.0f/4.0f, size.height/2.0f), size.height/4.0f, size.height/4.0f),
pBrush,
32.0f,
NULL
);

pD2DRenderTarget->EndDraw();

// Release sync
pKeyedMutex10->ReleaseSync(1);


// Sync the shared texture for D3D11
pKeyedMutex11->AcquireSync(1, INFINITE);

// Copy the content from the shared texture to the back-buffer
pImmediateContext->CopyResource(pBackBuffer11, pSharedTexture11);

// Release sync
pKeyedMutex11->ReleaseSync(0);


// Present to screen
pSwapChain->Present(1, 0);
}
}

// Release
pSwapChain->SetFullscreenState(FALSE, NULL);

pImmediateContext->ClearState();

pBrush->Release();
pD2DRenderTarget->Release();

pKeyedMutex10->Release();
pKeyedMutex11->Release();
pSharedTexture11->Release();
pBackBuffer11->Release();

pImmediateContext->Flush();

pDevice101->Release();

pImmediateContext->Release();
pSwapChain->Release();
pDevice11->Release();

UnregisterClass(wc.lpszClassName, hInstance);

return 0;
}

// Window procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
// Window destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}

return DefWindowProc(hWnd, msg, wParam, lParam);
}


0

Share this post


Link to post
Share on other sites
Thanks a lot guys - I'll give it a try. :)

Just curious though - is there any way to overlay a hwndsurfacerendertarget or is that bound to fail?
0

Share this post


Link to post
Share on other sites
I'm not sure, haven't tried that path, but you can create the swap-chain with the GDI compatible flag, and use GetDC on the back-buffer and draw to that with a DC D2D render target. It's not very fast (I think it draws in software, or at least copies to system-memory in between), but if you only draw to part of the screen and specify an update rectangle it isn't very slow.
0

Share this post


Link to post
Share on other sites
Actually.. it might be better to create a texture with GDI compatibility, and draw to that DC.. I'm gonna try that one, I'll post back. =)
0

Share this post


Link to post
Share on other sites
Seems to be working quite well.

Here's the code:

#include <windows.h>
#include <D3D11.h>
#include <D2D1.h>
#include <DXErr.h>
#include <DXGI.h>

// Libs
#pragma comment (lib, "D3D11.lib")
#pragma comment (lib, "D2D1.lib")
#pragma comment (lib, "DXErr.lib")
#pragma comment (lib, "DXGI.lib")


LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);



// Main
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Register windowclass
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.lpszClassName = TEXT("MyClass");
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wc);

// Create window
HWND hWnd = CreateWindow(
wc.lpszClassName,
TEXT("D3D11 with Direct2D"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);

// Create DXGI factory to enumerate adapters
IDXGIFactory1 *pDXGIFactory;

HRESULT hResult = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pDXGIFactory);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("CreateDXGIFactory1"), MB_OK);
return 0;
}

// Use the first adapter
IDXGIAdapter1 *pAdapter;

hResult = pDXGIFactory->EnumAdapters1(0, &pAdapter);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("EnumAdapters1"), MB_OK);
return 0;
}

pDXGIFactory->Release();

// Create D3D11 device and swapchain
DXGI_SWAP_CHAIN_DESC scd;
ID3D11Device *pDevice11;
IDXGISwapChain *pSwapChain;
ID3D11DeviceContext *pImmediateContext;

ZeroMemory(&scd, sizeof(scd));
scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
scd.SampleDesc.Count = 1;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.BufferCount = 1;
scd.OutputWindow = hWnd;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.Windowed = TRUE;

hResult = D3D11CreateDeviceAndSwapChain(
pAdapter,
D3D_DRIVER_TYPE_UNKNOWN,
NULL,
D3D11_CREATE_DEVICE_DEBUG |
D3D11_CREATE_DEVICE_BGRA_SUPPORT |
D3D11_CREATE_DEVICE_SINGLETHREADED,
NULL,
0,
D3D11_SDK_VERSION,
&scd,
&pSwapChain,
&pDevice11,
NULL,
&pImmediateContext
);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("D3D11CreateDeviceAndSwapChain"), MB_OK);
return 0;
}

// Get the D3D11 back-buffer
ID3D11Texture2D *pBackBuffer11;
D3D11_TEXTURE2D_DESC backBufferDesc;

hResult = pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer11));
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pSwapChain->GetBuffer for ID3D11Texture2D"), MB_OK);
return 0;
}

pBackBuffer11->GetDesc(&backBufferDesc);

// Create the texture to draw D2D content to
D3D11_TEXTURE2D_DESC textureDesc;
ID3D11Texture2D *pTexture;

ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = backBufferDesc.Width;
textureDesc.Height = backBufferDesc.Height;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;

hResult = pDevice11->CreateTexture2D(&textureDesc, NULL, &pTexture);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pDevice11->CreateTexture2D"), MB_OK);
return 0;
}

// Get DXGI surface from texture
IDXGISurface1 *pSurface;

hResult = pTexture->QueryInterface(__uuidof(IDXGISurface1), (void**)&pSurface);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pTexture->QueryInterface for IDXGISurface1"), MB_OK);
return 0;
}

// Create D2D factory
ID2D1Factory *pD2DFactory;

hResult = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void**)&pD2DFactory);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("D2D1CreateFactory"), MB_OK);
return 0;
}

// Create D2D DC render target
D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties;
ID2D1DCRenderTarget *pD2DRenderTarget;

ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties));
renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED);

hResult = pD2DFactory->CreateDCRenderTarget(&renderTargetProperties, &pD2DRenderTarget);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pD2DFactory->CreateDCRenderTarget"), MB_OK);
return 0;
}

pD2DFactory->Release();

// Create a solid color brush to draw something with
ID2D1SolidColorBrush *pBrush;

hResult = pD2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 0.0f, 1.0f), &pBrush);
if(FAILED(hResult)) {
MessageBox(NULL, DXGetErrorDescription(hResult), TEXT("pD2DRenderTarget->CreateSolidColorBrush"), MB_OK);
return 0;
}

// Main loop
float angle = 0.0f;

ShowWindow(hWnd, nCmdShow);
while(true) {
MSG msg;
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) {
if(msg.message == WM_QUIT)
break;
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else {
// Get surface DC for the texture
HDC hDC;
hResult = pSurface->GetDC(TRUE, &hDC);
if(FAILED(hResult)) {
}
else {
// The rect of the texture to draw to with D2D
RECT rect;
SetRect(&rect, 0, 0, backBufferDesc.Width, backBufferDesc.Height);

// Bind the DC render target to the HDC
hResult = pD2DRenderTarget->BindDC(hDC, &rect);
if(FAILED(hResult)) {
}
else {
// Draw D2D content
angle += 360.0f / 200.0f;

pD2DRenderTarget->BeginDraw();

pD2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.7f, 0.0f, 1.0f));

D2D1_SIZE_F size = pD2DRenderTarget->GetSize();

pD2DRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(angle, D2D1::Point2F(size.width/2.0f, size.height/2.0f)));

pBrush->SetColor(D2D1::ColorF(1.0f, 1.0f, 0.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width/2.0f, size.height/2.0f), size.height/3.0f, size.height/3.0f),
pBrush,
32.0f,
NULL
);

pBrush->SetColor(D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width/4.0f, size.height/2.0f), size.height/4.0f, size.height/4.0f),
pBrush,
32.0f,
NULL
);

pBrush->SetColor(D2D1::ColorF(0.0f, 0.0f, 1.0f, 1.0f));
pD2DRenderTarget->DrawEllipse(
D2D1::Ellipse(D2D1::Point2F(size.width*3.0f/4.0f, size.height/2.0f), size.height/4.0f, size.height/4.0f),
pBrush,
32.0f,
NULL
);

pD2DRenderTarget->EndDraw();
}

// Release the DC specifying the dirty rect
pSurface->ReleaseDC(&rect);
}

// Copy the content from the texture to the back-buffer
pImmediateContext->CopyResource(pBackBuffer11, pTexture);


// Present to screen
pSwapChain->Present(1, 0);
}
}

// Release
pSwapChain->SetFullscreenState(FALSE, NULL);

pImmediateContext->ClearState();

pBrush->Release();
pD2DRenderTarget->Release();

pSurface->Release();
pTexture->Release();
pBackBuffer11->Release();

pImmediateContext->Flush();

pImmediateContext->Release();
pSwapChain->Release();
pDevice11->Release();

UnregisterClass(wc.lpszClassName, hInstance);

return 0;
}

// Window procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
// Window destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}

return DefWindowProc(hWnd, msg, wParam, lParam);
}




EDIT: I noticed that at least for simple test-cases it's faster to use software-mode for the D2D render-target with this method. I assume it's because it copies back-and-forth between GPU and system memory otherwise..
It's significantly slower than using the shared texture method, when drawing large areas.

[Edited by - Erik Rufelt on November 9, 2009 12:58:40 PM]
1

Share this post


Link to post
Share on other sites
Tack så mycket för hjälpen! ;) (Thanks!)

Odd thing though, that last sample you posted - while working well, it doesn't actually clear properly. I might have a case of bad drivers?



Edit: Same result on the shared resource example.

[Edited by - DEVLiN on November 9, 2009 12:26:43 PM]
0

Share this post


Link to post
Share on other sites
Np =) That's strange.. I would update everything before trouble-shooting at least. There's a Clear in there so I don't know what it could be.
0

Share this post


Link to post
Share on other sites
Must be a driver issue. It seems it was a problem with "dirty" areas, only clearing the areas where something happened. It went away if I drew a fullscreen filled rectangle (even with alpha 0).

Might not prove to be a problem in the long run though - have to give it a try in a real application.

Thanks for your help yet again. :)
0

Share this post


Link to post
Share on other sites
Using two devices IS the story for D3D11 and D2D interop. Any flickering is very likely due to a sync problem between two devices. Using the GetDC will mean you take a hit since the resource is unbound from the pipeline and transferred to the CPU for CPU side rendering. The hit might be less than using D2D though.

As a possible way around this issue, it would be possible to make a texture cache of your fonts, and then use DWrite for all layout/spacing information. The only new code to write would be whatever is necessary to dynamically emit quads for each character to the screen. DWrite will provide all screen alignment, spacing, and other layout details needed to place your text onscreen efficiently. In this way, the texture font cache is the only thing shared between devices, leaving you to render solely in D3D11.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Toastmastern
      So it's been a while since I took a break from my whole creating a planet in DX11. Last time around I got stuck on fixing a nice LOD.
      A week back or so I got help to find this:
      https://github.com/sp4cerat/Planet-LOD
      In general this is what I'm trying to recreate in DX11, he that made that planet LOD uses OpenGL but that is a minor issue and something I can solve. But I have a question regarding the code
      He gets the position using this row
      vec4d pos = b.var.vec4d["position"]; Which is then used further down when he sends the variable "center" into the drawing function:
      if (pos.len() < 1) pos.norm(); world::draw(vec3d(pos.x, pos.y, pos.z));  
      Inside the draw function this happens:
      draw_recursive(p3[0], p3[1], p3[2], center); Basically the 3 vertices of the triangle and the center of details that he sent as a parameter earlier: vec3d(pos.x, pos.y, pos.z)
      Now onto my real question, he does vec3d edge_center[3] = { (p1 + p2) / 2, (p2 + p3) / 2, (p3 + p1) / 2 }; to get the edge center of each edge, nothing weird there.
      But this is used later on with:
      vec3d d = center + edge_center[i]; edge_test[i] = d.len() > ratio_size; edge_test is then used to evaluate if there should be a triangle drawn or if it should be split up into 3 new triangles instead. Why is it working for him? shouldn't it be like center - edge_center or something like that? Why adding them togheter? I asume here that the center is the center of details for the LOD. the position of the camera if stood on the ground of the planet and not up int he air like it is now.

      Full code can be seen here:
      https://github.com/sp4cerat/Planet-LOD/blob/master/src.simple/Main.cpp
      If anyone would like to take a look and try to help me understand this code I would love this person. I'm running out of ideas on how to solve this in my own head, most likely twisted it one time to many up in my head
      Thanks in advance
      Toastmastern
       
       
    • By fllwr0491
      I googled around but are unable to find source code or details of implementation.
      What keywords should I search for this topic?
      Things I would like to know:
      A. How to ensure that partially covered pixels are rasterized?
         Apparently by expanding each triangle by 1 pixel or so, rasterization problem is almost solved.
         But it will result in an unindexable triangle list without tons of overlaps. Will it incur a large performance penalty?
      B. A-buffer like bitmask needs a read-modiry-write operation.
         How to ensure proper synchronizations in GLSL?
         GLSL seems to only allow int32 atomics on image.
      C. Is there some simple ways to estimate coverage on-the-fly?
         In case I am to draw 2D shapes onto an exisitng target:
         1. A multi-pass whatever-buffer seems overkill.
         2. Multisampling could cost a lot memory though all I need is better coverage.
            Besides, I have to blit twice, if draw target is not multisampled.
       
    • By mapra99
      Hello

      I am working on a recent project and I have been learning how to code in C# using OpenGL libraries for some graphics. I have achieved some quite interesting things using TAO Framework writing in Console Applications, creating a GLUT Window. But my problem now is that I need to incorporate the Graphics in a Windows Form so I can relate the objects that I render with some .NET Controls.

      To deal with this problem, I have seen in some forums that it's better to use OpenTK instead of TAO Framework, so I can use the glControl that OpenTK libraries offer. However, I haven't found complete articles, tutorials or source codes that help using the glControl or that may insert me into de OpenTK functions. Would somebody please share in this forum some links or files where I can find good documentation about this topic? Or may I use another library different of OpenTK?

      Thanks!
    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
  • Popular Now