GreenForester
GreenForester

Reputation: 23

Multithreading in Direct2D

I'm trying to create a simple D2D game engine (it must be able to display and move images in a window, at least), and everything went right until the moment when I decided to switch to the multithreaded version. I read this MSDN article, and it recommends using one multithreaded factory from several threads. But this article claims it would be more effective to have several single-threaded factories (though the article describes server-side rendering scenario, the principle is the same for my case, am I wrong?). When I tried to use one-thread-one-factory approach, all the images are displayed and moved, but there's terrible flickering. In my WM_PAINT handler I'm trying to do something like this:

for (CSingleThreadEngine *pElSingleThreadEngine : m_SingleThreadEngines) //each CSingleThreadEngine instance has its own D2D factory and an image collection
    pElSingleThreadEngine->Draw();

and pElSingleThreadEngine->Draw() does drawing like this:

m_pRenderTarget->BeginDraw();
m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
for (CGameImage *pImage : m_GameImages)
{
    if (FAILED(pImage->Draw()))
        throw runtime_error("An object cannot be drawn");
}
m_pRenderTarget->EndDraw();

I think the wrong thing here is having several ID2D1HwndRenderTarget instances for just one window because if I make drawing each thread in a separate window, it works just fine. But I want to draw in one window only, and I can't avoid using multiple ID2D1HwndRenderTarget instances for this purpose. So my questions are:

  1. What are the best practices for creating multithreaded Direct2D applications at all?
  2. If the approach I'm using is right, what am I doing wrong and how can I fix it?

Any help would be highly appreciated.

Upvotes: 2

Views: 1195

Answers (1)

Anton Angelov
Anton Angelov

Reputation: 1244

I can't see a reason why you use several HWND render targets for a single window. Have you tried creating off-screen bitmaps for each thread and draw those to a single HWND render target instead?

Upvotes: 1

Related Questions