Search code examples
multithreadingdirectxtextures

How to copy texture from context to another context inside GPU?


for example,texA is created on deviceA in threadA, texB is created on deviceB in threadB,deviceA and deviceB use the same GPU, so how can I use ID3D11DeviceContext::CopyResource()(or CopySubresourceRegion()) to copy texA to texB inside GPU?


Solution

  • Create one of the textures so it can be shared across devices.

    If you only support Win8 and newer, and both devices are D3D 11.1, the recommended way is specify D3D11_RESOURCE_MISC_SHARED_NTHANDLE and D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX flags, in MiscFlags field of D3D11_TEXTURE2D_DESC.

    Once created, QueryInterface for IDXGIResource1 interface. Call IDXGIResource1::CreateSharedHandle on that interface. You don’t need name, pass nullptr. Specify DXGI_SHARED_RESOURCE_READ if you’ll copy from this texture into another device, or DXGI_SHARED_RESOURCE_WRITE if you’ll copy stuff from another device into this texture.

    You’ll get a HANDLE value. Then, on second device, call ID3D11Device1::OpenSharedResource1, passing that handle. If succeeded, you’ll get ID3D11Texture2D pointer of that texture, shared into the second D3D device. Then you can call CopyResource or any oother D3D API on the second device, to copy data between textures. Don’t forget to CloseHandle once you’ve opened that texture on second device.

    If you have D3D 11.0 or still supporting Windows 7, the workflow is slightly different. Use D3D11_RESOURCE_MISC_SHARED resource flag when creating a resource, call IDXGIResource::GetSharedHandle to obtain the handle, call ID3D11Device::OpenSharedResource to open that texture on another device, and do not call CloseHandle on that handle.