-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcu_dx11_interop.h
More file actions
109 lines (87 loc) · 2.67 KB
/
cu_dx11_interop.h
File metadata and controls
109 lines (87 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#ifndef __CU_DX11_INTEROP_H__
#define __CU_DX11_INTEROP_H__
#include <cuda_runtime.h>
#include <cuda_d3d11_interop.h>
#include "cu_errors.h"
#include "core_types.h"
#include "dx11_tex.h"
// TODO: is this more efficient than a copy ?
template<bool DBG_WITH_SURFACE>
struct interop_mapped_resource
{
cudaGraphicsResource* dx11Mapping;
cudaStream_t stream;
cudaArray* mem;
cudaSurfaceObject_t surf = 0;
inline interop_mapped_resource( cudaGraphicsResource* dx11Rsc, cudaStream_t s )
{
dx11Mapping = dx11Rsc;
stream = s;
CUDA_CHECK( cudaGraphicsMapResources( 1, &dx11Mapping, stream ) );
CUDA_CHECK( cudaGraphicsSubResourceGetMappedArray( &mem, dx11Mapping, 0, 0 ) );
if( DBG_WITH_SURFACE )
{
cudaResourceDesc resDesc = { .resType = cudaResourceTypeArray };
resDesc.res.array.array = mem;
CUDA_CHECK( cudaCreateSurfaceObject( &surf, &resDesc ) );
}
}
inline ~interop_mapped_resource()
{
if( surf ) CUDA_CHECK( cudaDestroySurfaceObject( surf ) );
CUDA_CHECK( cudaGraphicsUnmapResources( 1, &dx11Mapping, stream ) );
}
};
enum interop_mutex_key_t : u64
{
CUDA_ACQUIRE = 0,
DX11_ACQUIRE = 1,
};
template<interop_mutex_key_t INTEROP_DIR>
struct scoped_interop_mutex
{
IDXGIKeyedMutex* mtx;
scoped_interop_mutex( IDXGIKeyedMutex* mtx ) : mtx{ mtx }
{
HR_CHECK( mtx->AcquireSync( INTEROP_DIR, INFINITE ) );
}
~scoped_interop_mutex()
{
u64 flippedOwnership = INTEROP_DIR ^ 1;
HR_CHECK( mtx->ReleaseSync( flippedOwnership ) );
}
NON_COPYABLE( scoped_interop_mutex );
};
struct interop_tex2d
{
dx11_texture dx11;
cudaGraphicsResource* cudaView;
interop_tex2d( const dx11_texture& dx11Tex )
{
assert( nullptr != dx11Tex.rsc );
dx11 = dx11Tex;
CUDA_CHECK( cudaGraphicsD3D11RegisterResource( &cudaView, dx11.rsc, cudaGraphicsRegisterFlagsNone ) );
}
template<bool DBG_WITH_SURFACE>
inline interop_mapped_resource<DBG_WITH_SURFACE> GetMapped( cudaStream_t stream ) const
{
return { cudaView, stream };
}
template<interop_mutex_key_t INTEROP_DIR>
inline auto GetScopedMutex()
{
assert( dx11.keyedMutex );
return scoped_interop_mutex<INTEROP_DIR>{ dx11.keyedMutex };
}
};
inline void DestroyInteropTex2D( interop_tex2d* interopTex )
{
if( !interopTex ) return;
if( interopTex->cudaView )
{
CUDA_CHECK( cudaGraphicsUnregisterResource( interopTex->cudaView ) );
interopTex->cudaView = nullptr;
}
interopTex->dx11.Release();
}
#endif // !__CU_DX11_INTEROP_H__