diff --git a/CMakeLists.txt b/CMakeLists.txt index 2442c6f..ec169db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -90,7 +90,6 @@ elseif(WIN32) lib/inputdev/HIDListenerWinUSB.cpp lib/inputdev/HIDDeviceWinUSB.cpp lib/graphicsdev/D3D11.cpp - lib/graphicsdev/D3D12.cpp lib/audiodev/WASAPI.cpp) list(APPEND PLAT_HDRS @@ -241,6 +240,7 @@ endif() function(glslang_set_link_args TARGET) endfunction(glslang_set_link_args) +add_definitions("-DENABLE_OPT=0") add_subdirectory(glslang/glslang) add_subdirectory(glslang/OGLCompilersDLL) add_subdirectory(glslang/SPIRV) diff --git a/README.md b/README.md index dee00ef..19b7ab7 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ refresh-rate. #### Supported Graphics Backends * OpenGL 3.3+ -* Direct3D 11/12 +* Direct3D 11 * Metal 1.1 (OS X 10.11 only for now, iOS coming soon) * Vulkan diff --git a/glslang b/glslang index 82ead04..8e4b496 160000 --- a/glslang +++ b/glslang @@ -1 +1 @@ -Subproject commit 82ead04c39c6a4b7fa153d692b26181091c43c15 +Subproject commit 8e4b496d4ad84f3524fff89395e6e6b1540c05b6 diff --git a/include/boo/DeferredWindowEvents.hpp b/include/boo/DeferredWindowEvents.hpp index 6a9c579..a520e93 100644 --- a/include/boo/DeferredWindowEvents.hpp +++ b/include/boo/DeferredWindowEvents.hpp @@ -262,7 +262,7 @@ struct DeferredWindowEvents : public IWindowCallback } if (hasResize) - m_rec.resized(latestResize, latestResize); + m_rec.resized(latestResize, false); for (const Command& cmd : cmds) cmd.dispatch(m_rec); diff --git a/include/boo/IGraphicsContext.hpp b/include/boo/IGraphicsContext.hpp index 5cb91c4..4327606 100644 --- a/include/boo/IGraphicsContext.hpp +++ b/include/boo/IGraphicsContext.hpp @@ -24,7 +24,6 @@ public: OpenGL4_2 = 2, Vulkan = 3, D3D11 = 4, - D3D12 = 5, Metal = 6, GX = 7, GX2 = 8 diff --git a/include/boo/System.hpp b/include/boo/System.hpp index a8c64cf..0a1fcce 100644 --- a/include/boo/System.hpp +++ b/include/boo/System.hpp @@ -77,15 +77,13 @@ namespace boo #define __BooTraceArgsUse , file, line #define __BooTraceInitializer , m_file(file), m_line(line) #define __BooTraceFields const char* m_file; int m_line; -#define BooCommitTransaction(...) commitTransaction(__VA_ARGS__, __FILE__, __LINE__) -#define BooNewPoolBuffer(...) newPoolBuffer(__VA_ARGS__, __FILE__, __LINE__) +#define BooTrace , __FILE__, __LINE__ #else #define __BooTraceArgs #define __BooTraceArgsUse #define __BooTraceInitializer #define __BooTraceFields -#define BooCommitTransaction(...) commitTransaction(__VA_ARGS__) -#define BooNewPoolBuffer(...) newPoolBuffer(__VA_ARGS__) +#define BooTrace #endif } diff --git a/include/boo/graphicsdev/D3D.hpp b/include/boo/graphicsdev/D3D.hpp index c3108fb..351b006 100644 --- a/include/boo/graphicsdev/D3D.hpp +++ b/include/boo/graphicsdev/D3D.hpp @@ -18,10 +18,10 @@ extern pD3DCreateBlob D3DCreateBlobPROC; namespace boo { -class ID3DDataFactory : public IGraphicsDataFactory +class D3DDataFactory : public IGraphicsDataFactory { public: - virtual ~ID3DDataFactory() {} + virtual ~D3DDataFactory() {} class Context : public IGraphicsDataFactory::Context { diff --git a/include/boo/graphicsdev/IGraphicsDataFactory.hpp b/include/boo/graphicsdev/IGraphicsDataFactory.hpp index e6b50a8..3edecb8 100644 --- a/include/boo/graphicsdev/IGraphicsDataFactory.hpp +++ b/include/boo/graphicsdev/IGraphicsDataFactory.hpp @@ -227,7 +227,6 @@ struct IGraphicsDataFactory Null, OpenGL, D3D11, - D3D12, Metal, Vulkan, GX, diff --git a/lib/audiodev/AudioMatrixSSE.cpp b/lib/audiodev/AudioMatrixSSE.cpp index 1c23020..c8b1b46 100644 --- a/lib/audiodev/AudioMatrixSSE.cpp +++ b/lib/audiodev/AudioMatrixSSE.cpp @@ -16,13 +16,8 @@ typedef union #endif } TVectorUnion; -static constexpr TVectorUnion ZeroVec = {}; -static constexpr TVectorUnion Min16Vec = {INT16_MIN, INT16_MIN, INT16_MIN, INT16_MIN}; -static constexpr TVectorUnion Max16Vec = {INT16_MAX, INT16_MAX, INT16_MAX, INT16_MAX}; -static constexpr TVectorUnion Min32Vec = {INT32_MIN, INT32_MIN, INT32_MIN, INT32_MIN}; -static constexpr TVectorUnion Max32Vec = {INT32_MAX, INT32_MAX, INT32_MAX, INT32_MAX}; -static constexpr TVectorUnion MinFltVec = {-1.f, -1.f, -1.f, -1.f}; -static constexpr TVectorUnion MaxFltVec = {1.f, 1.f, 1.f, 1.f}; +static constexpr TVectorUnion Min32Vec = {{INT32_MIN, INT32_MIN, INT32_MIN, INT32_MIN}}; +static constexpr TVectorUnion Max32Vec = {{INT32_MAX, INT32_MAX, INT32_MAX, INT32_MAX}}; void AudioMatrixMono::setDefaultMatrixCoefficients(AudioChannelSet acSet) { diff --git a/lib/audiodev/AudioSubmix.cpp b/lib/audiodev/AudioSubmix.cpp index 237223c..1cd8e8f 100644 --- a/lib/audiodev/AudioSubmix.cpp +++ b/lib/audiodev/AudioSubmix.cpp @@ -11,7 +11,7 @@ namespace boo { AudioSubmix::AudioSubmix(BaseAudioVoiceEngine& root, IAudioSubmixCallback* cb, int busId, bool mainOut) -: ListNode(&root), m_busId(busId), m_cb(cb), m_mainOut(mainOut) +: ListNode(&root), m_busId(busId), m_mainOut(mainOut), m_cb(cb) { if (mainOut) setSendLevel(m_head->m_mainSubmix.get(), 1.f, false); diff --git a/lib/audiodev/Common.hpp b/lib/audiodev/Common.hpp index 731c340..ad2519b 100644 --- a/lib/audiodev/Common.hpp +++ b/lib/audiodev/Common.hpp @@ -11,12 +11,12 @@ namespace boo /** Pertinent information from audio backend about optimal mixed-audio representation */ struct AudioVoiceEngineMixInfo { - double m_sampleRate; - soxr_datatype_t m_sampleFormat; - unsigned m_bitsPerSample; - AudioChannelSet m_channels; - ChannelMap m_channelMap; - size_t m_periodFrames; + double m_sampleRate = 32000.0; + soxr_datatype_t m_sampleFormat = SOXR_FLOAT32_I; + unsigned m_bitsPerSample = 32; + AudioChannelSet m_channels = AudioChannelSet::Stereo; + ChannelMap m_channelMap = {2, {AudioChannel::FrontLeft, AudioChannel::FrontRight}}; + size_t m_periodFrames = 160; }; } diff --git a/lib/audiodev/WASAPI.cpp b/lib/audiodev/WASAPI.cpp index a425ae7..e430b33 100644 --- a/lib/audiodev/WASAPI.cpp +++ b/lib/audiodev/WASAPI.cpp @@ -40,7 +40,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine std::vector m_5msBuffer; #if !WINDOWS_STORE - struct NotificationClient : public IMMNotificationClient + struct NotificationClient final : public IMMNotificationClient { WASAPIAudioVoiceEngine& m_parent; @@ -138,14 +138,14 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine #if !WINDOWS_STORE if (FAILED(m_enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_device))) { - Log.report(logvisor::Fatal, L"unable to obtain default audio device"); + Log.report(logvisor::Error, L"unable to obtain default audio device"); m_device.Reset(); return; } if (FAILED(m_device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, &m_audClient))) { - Log.report(logvisor::Fatal, L"unable to create audio client from device"); + Log.report(logvisor::Error, L"unable to create audio client from device"); m_device.Reset(); return; } @@ -154,7 +154,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine WAVEFORMATEXTENSIBLE* pwfx; if (FAILED(m_audClient->GetMixFormat((WAVEFORMATEX**)&pwfx))) { - Log.report(logvisor::Fatal, L"unable to obtain audio mix format from device"); + Log.report(logvisor::Error, L"unable to obtain audio mix format from device"); #if !WINDOWS_STORE m_device.Reset(); #endif @@ -239,7 +239,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine (WAVEFORMATEX*)pwfx, nullptr))) { - Log.report(logvisor::Fatal, L"unable to initialize audio client"); + Log.report(logvisor::Error, L"unable to initialize audio client"); #if !WINDOWS_STORE m_device.Reset(); #endif @@ -283,7 +283,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine } else { - Log.report(logvisor::Fatal, L"unsupported floating-point bits-per-sample %d", pwfx->Format.wBitsPerSample); + Log.report(logvisor::Error, L"unsupported floating-point bits-per-sample %d", pwfx->Format.wBitsPerSample); #if !WINDOWS_STORE m_device.Reset(); #endif @@ -296,7 +296,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine UINT32 bufferFrameCount; if (FAILED(m_audClient->GetBufferSize(&bufferFrameCount))) { - Log.report(logvisor::Fatal, L"unable to get audio buffer frame count"); + Log.report(logvisor::Error, L"unable to get audio buffer frame count"); #if !WINDOWS_STORE m_device.Reset(); #endif @@ -306,7 +306,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine if (FAILED(m_audClient->GetService(IID_IAudioRenderClient, &m_renderClient))) { - Log.report(logvisor::Fatal, L"unable to create audio render client"); + Log.report(logvisor::Error, L"unable to create audio render client"); #if !WINDOWS_STORE m_device.Reset(); #endif @@ -385,13 +385,13 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine CLSCTX_ALL, IID_IMMDeviceEnumerator, &m_enumerator))) { - Log.report(logvisor::Fatal, L"unable to create MMDeviceEnumerator instance"); + Log.report(logvisor::Error, L"unable to create MMDeviceEnumerator instance"); return; } if (FAILED(m_enumerator->RegisterEndpointNotificationCallback(&m_notificationClient))) { - Log.report(logvisor::Fatal, L"unable to register multimedia event callback"); + Log.report(logvisor::Error, L"unable to register multimedia event callback"); m_device.Reset(); return; } @@ -431,6 +431,9 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine #if WINDOWS_STORE if (!m_ready) return; +#else + if (!m_device) + return; #endif int attempt = 0; @@ -821,12 +824,7 @@ struct WASAPIAudioVoiceEngine : BaseAudioVoiceEngine std::unique_ptr NewAudioVoiceEngine() { - std::unique_ptr ret = std::make_unique(); -#if !WINDOWS_STORE - if (!static_cast(*ret).m_device) - return {}; -#endif - return ret; + return std::make_unique(); } } diff --git a/lib/graphicsdev/D3D11.cpp b/lib/graphicsdev/D3D11.cpp index 25eb4f2..8a9ca67 100644 --- a/lib/graphicsdev/D3D11.cpp +++ b/lib/graphicsdev/D3D11.cpp @@ -109,10 +109,11 @@ class D3D11GraphicsBufferS : public GraphicsDataNode BufferUse use, D3D11Context* ctx, const void* data, size_t stride, size_t count) : GraphicsDataNode(parent), - m_stride(stride), m_count(count), m_sz(stride * count) + m_sz(stride * count), m_stride(stride), m_count(count) { D3D11_SUBRESOURCE_DATA iData = {data}; - ThrowIfFailed(ctx->m_dev->CreateBuffer(&CD3D11_BUFFER_DESC(m_sz, USE_TABLE[int(use)], D3D11_USAGE_IMMUTABLE), &iData, &m_buf)); + CD3D11_BUFFER_DESC desc(m_sz, USE_TABLE[int(use)], D3D11_USAGE_IMMUTABLE); + ThrowIfFailed(ctx->m_dev->CreateBuffer(&desc, &iData, &m_buf)); } public: size_t m_stride; @@ -140,8 +141,11 @@ class D3D11GraphicsBufferD : public GraphicsDataNode m_cpuSz = stride * count; m_cpuBuf.reset(new uint8_t[m_cpuSz]); for (int i=0 ; i<3 ; ++i) - ThrowIfFailed(ctx->m_dev->CreateBuffer(&CD3D11_BUFFER_DESC(m_cpuSz, USE_TABLE[int(use)], - D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE), nullptr, &m_bufs[i])); + { + CD3D11_BUFFER_DESC desc(m_cpuSz, USE_TABLE[int(use)], + D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE); + ThrowIfFailed(ctx->m_dev->CreateBuffer(&desc, nullptr, &m_bufs[i])); + } } void update(ID3D11DeviceContext* ctx, int b); public: @@ -158,14 +162,13 @@ public: class D3D11TextureS : public GraphicsDataNode { friend class D3D11DataFactory; - size_t m_sz; D3D11TextureS(const boo::ObjToken& parent, D3D11Context* ctx, size_t width, size_t height, size_t mips, TextureFormat fmt, const void* data, size_t sz) - : GraphicsDataNode(parent), m_sz(sz) + : GraphicsDataNode(parent) { - DXGI_FORMAT pfmt; + DXGI_FORMAT pfmt = DXGI_FORMAT_UNKNOWN; int pxPitchNum = 1; int pxPitchDenom = 1; bool compressed = false; @@ -212,8 +215,8 @@ class D3D11TextureS : public GraphicsDataNode } ThrowIfFailed(ctx->m_dev->CreateTexture2D(&desc, upData, &m_tex)); - ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_tex.Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC(m_tex.Get(), D3D_SRV_DIMENSION_TEXTURE2D, pfmt, 0, mips), &m_srv)); + CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(m_tex.Get(), D3D_SRV_DIMENSION_TEXTURE2D, pfmt, 0, mips); + ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_tex.Get(), &srvDesc, &m_srv)); } public: ComPtr m_tex; @@ -225,14 +228,13 @@ class D3D11TextureSA : public GraphicsDataNode { friend class D3D11DataFactory; - size_t m_sz; D3D11TextureSA(const boo::ObjToken& parent, D3D11Context* ctx, size_t width, size_t height, size_t layers, size_t mips, TextureFormat fmt, const void* data, size_t sz) - : GraphicsDataNode(parent), m_sz(sz) + : GraphicsDataNode(parent) { - size_t pixelPitch; - DXGI_FORMAT pixelFmt; + size_t pixelPitch = 0; + DXGI_FORMAT pixelFmt = DXGI_FORMAT_UNKNOWN; switch (fmt) { case TextureFormat::RGBA8: @@ -247,6 +249,8 @@ class D3D11TextureSA : public GraphicsDataNode pixelPitch = 2; pixelFmt = DXGI_FORMAT_R16_UNORM; break; + default: + Log.report(logvisor::Fatal, "unsupported tex format"); } CD3D11_TEXTURE2D_DESC desc(pixelFmt, width, height, layers, mips, @@ -272,8 +276,8 @@ class D3D11TextureSA : public GraphicsDataNode } ThrowIfFailed(ctx->m_dev->CreateTexture2D(&desc, upData.get(), &m_tex)); - ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_tex.Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC(m_tex.Get(), D3D_SRV_DIMENSION_TEXTURE2DARRAY, pixelFmt), &m_srv)); + CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(m_tex.Get(), D3D_SRV_DIMENSION_TEXTURE2DARRAY, pixelFmt); + ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_tex.Get(), &srvDesc, &m_srv)); } public: ComPtr m_tex; @@ -287,7 +291,6 @@ class D3D11TextureD : public GraphicsDataNode friend struct D3D11CommandQueue; size_t m_width = 0; - size_t m_height = 0; D3D11CommandQueue* m_q; std::unique_ptr m_cpuBuf; size_t m_cpuSz; @@ -296,9 +299,9 @@ class D3D11TextureD : public GraphicsDataNode D3D11TextureD(const boo::ObjToken& parent, D3D11CommandQueue* q, D3D11Context* ctx, size_t width, size_t height, TextureFormat fmt) - : GraphicsDataNode(parent), m_width(width), m_height(height), m_q(q) + : GraphicsDataNode(parent), m_width(width), m_q(q) { - DXGI_FORMAT pixelFmt; + DXGI_FORMAT pixelFmt = DXGI_FORMAT_UNKNOWN; switch (fmt) { case TextureFormat::RGBA8: @@ -325,8 +328,8 @@ class D3D11TextureD : public GraphicsDataNode for (int i=0 ; i<3 ; ++i) { ThrowIfFailed(ctx->m_dev->CreateTexture2D(&desc, nullptr, &m_texs[i])); - ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_texs[i].Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC(m_texs[i].Get(), D3D_SRV_DIMENSION_TEXTURE2D, pixelFmt), &m_srvs[i])); + CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(m_texs[i].Get(), D3D_SRV_DIMENSION_TEXTURE2D, pixelFmt); + ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_texs[i].Get(), &srvDesc, &m_srvs[i])); } } void update(ID3D11DeviceContext* ctx, int b); @@ -355,10 +358,12 @@ class D3D11TextureR : public GraphicsDataNode void Setup(D3D11Context* ctx) { - ThrowIfFailed(ctx->m_dev->CreateTexture2D(&CD3D11_TEXTURE2D_DESC(ctx->m_fbFormat, m_width, m_height, - 1, 1, D3D11_BIND_RENDER_TARGET, D3D11_USAGE_DEFAULT, 0, m_samples), nullptr, &m_colorTex)); - ThrowIfFailed(ctx->m_dev->CreateTexture2D(&CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_D24_UNORM_S8_UINT, m_width, m_height, - 1, 1, D3D11_BIND_DEPTH_STENCIL, D3D11_USAGE_DEFAULT, 0, m_samples), nullptr, &m_depthTex)); + CD3D11_TEXTURE2D_DESC colorDesc(ctx->m_fbFormat, m_width, m_height, + 1, 1, D3D11_BIND_RENDER_TARGET, D3D11_USAGE_DEFAULT, 0, m_samples); + ThrowIfFailed(ctx->m_dev->CreateTexture2D(&colorDesc, nullptr, &m_colorTex)); + CD3D11_TEXTURE2D_DESC depthDesc(DXGI_FORMAT_D32_FLOAT, m_width, m_height, + 1, 1, D3D11_BIND_DEPTH_STENCIL, D3D11_USAGE_DEFAULT, 0, m_samples); + ThrowIfFailed(ctx->m_dev->CreateTexture2D(&depthDesc, nullptr, &m_depthTex)); D3D11_RTV_DIMENSION rtvDim; D3D11_DSV_DIMENSION dsvDim; @@ -374,26 +379,28 @@ class D3D11TextureR : public GraphicsDataNode dsvDim = D3D11_DSV_DIMENSION_TEXTURE2D; } - ThrowIfFailed(ctx->m_dev->CreateRenderTargetView(m_colorTex.Get(), - &CD3D11_RENDER_TARGET_VIEW_DESC(m_colorTex.Get(), rtvDim), &m_rtv)); - ThrowIfFailed(ctx->m_dev->CreateDepthStencilView(m_depthTex.Get(), - &CD3D11_DEPTH_STENCIL_VIEW_DESC(m_depthTex.Get(), dsvDim), &m_dsv)); + CD3D11_RENDER_TARGET_VIEW_DESC rtvDesc(m_colorTex.Get(), rtvDim); + ThrowIfFailed(ctx->m_dev->CreateRenderTargetView(m_colorTex.Get(), &rtvDesc, &m_rtv)); + CD3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc(m_depthTex.Get(), dsvDim); + ThrowIfFailed(ctx->m_dev->CreateDepthStencilView(m_depthTex.Get(), &dsvDesc, &m_dsv)); for (size_t i=0 ; im_dev->CreateTexture2D(&CD3D11_TEXTURE2D_DESC(ctx->m_fbFormat, m_width, m_height, - 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1), nullptr, &m_colorBindTex[i])); - ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_colorBindTex[i].Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC(m_colorBindTex[i].Get(), D3D11_SRV_DIMENSION_TEXTURE2D), &m_colorSrv[i])); + CD3D11_TEXTURE2D_DESC colorBindDesc(ctx->m_fbFormat, m_width, m_height, + 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1); + ThrowIfFailed(ctx->m_dev->CreateTexture2D(&colorBindDesc, nullptr, &m_colorBindTex[i])); + CD3D11_SHADER_RESOURCE_VIEW_DESC colorSrvDesc(m_colorBindTex[i].Get(), D3D11_SRV_DIMENSION_TEXTURE2D); + ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_colorBindTex[i].Get(), &colorSrvDesc, &m_colorSrv[i])); } for (size_t i=0 ; im_dev->CreateTexture2D(&CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_R24G8_TYPELESS, m_width, m_height, - 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1), nullptr, &m_depthBindTex[i])); - ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_depthBindTex[i].Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC(m_depthBindTex[i].Get(), D3D11_SRV_DIMENSION_TEXTURE2D, - DXGI_FORMAT_R24_UNORM_X8_TYPELESS), &m_depthSrv[i])); + CD3D11_TEXTURE2D_DESC depthBindDesc(DXGI_FORMAT_R32_FLOAT, m_width, m_height, + 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1); + ThrowIfFailed(ctx->m_dev->CreateTexture2D(&depthBindDesc, nullptr, &m_depthBindTex[i])); + CD3D11_SHADER_RESOURCE_VIEW_DESC depthSrvDesc(m_depthBindTex[i].Get(), D3D11_SRV_DIMENSION_TEXTURE2D, + DXGI_FORMAT_R32_FLOAT); + ThrowIfFailed(ctx->m_dev->CreateShaderResourceView(m_depthBindTex[i].Get(), &depthSrvDesc, &m_depthSrv[i])); } } @@ -1143,7 +1150,7 @@ struct D3D11CommandQueue : IGraphicsCommandQueue if (tex->m_samples > 1) { ctx->ResolveSubresource(tex->m_depthBindTex[bindIdx].Get(), 0, tex->m_depthTex.Get(), 0, - DXGI_FORMAT_D24_UNORM_S8_UINT); + DXGI_FORMAT_D32_FLOAT); } else { @@ -1244,7 +1251,7 @@ void D3D11TextureD::unmap() m_q->m_dynamicLock.unlock(); } -class D3D11DataFactory : public ID3DDataFactory, public GraphicsDataFactoryHead +class D3D11DataFactory : public D3DDataFactory, public GraphicsDataFactoryHead { friend struct D3D11CommandQueue; IGraphicsContext* m_parent; @@ -1286,7 +1293,7 @@ class D3D11DataFactory : public ID3DDataFactory, public GraphicsDataFactoryHead m_gammaBinding = ctx.newShaderDataBinding(m_gammaShader, m_gammaVFMT, m_gammaVBO.get(), {}, {}, 0, nullptr, nullptr, 2, texs, nullptr, nullptr); return true; - }); + } BooTrace); } public: @@ -1302,13 +1309,13 @@ public: Platform platform() const {return Platform::D3D11;} const SystemChar* platformName() const {return _S("D3D11");} - class Context : public ID3DDataFactory::Context + class Context : public D3DDataFactory::Context { friend class D3D11DataFactory; D3D11DataFactory& m_parent; boo::ObjToken m_data; - Context(D3D11DataFactory& parent) - : m_parent(parent), m_data(new BaseGraphicsData(parent)) {} + Context(D3D11DataFactory& parent __BooTraceArgs) + : m_parent(parent), m_data(new BaseGraphicsData(parent __BooTraceArgsUse)) {} public: Platform platform() const {return Platform::D3D11;} const SystemChar* platformName() const {return _S("D3D11");} @@ -1528,16 +1535,16 @@ public: } }; - boo::ObjToken newPoolBuffer(BufferUse use, size_t stride, size_t count) + boo::ObjToken newPoolBuffer(BufferUse use, size_t stride, size_t count __BooTraceArgs) { D3D11CommandQueue* q = static_cast(m_parent->getCommandQueue()); - boo::ObjToken pool(new BaseGraphicsPool(*this)); + boo::ObjToken pool(new BaseGraphicsPool(*this __BooTraceArgsUse)); return {new D3D11GraphicsBufferD(pool, q, use, m_ctx, stride, count)}; } - void commitTransaction(const FactoryCommitFunc& trans) + void commitTransaction(const FactoryCommitFunc& trans __BooTraceArgs) { - D3D11DataFactory::Context ctx(*this); + D3D11DataFactory::Context ctx(*this __BooTraceArgsUse); trans(ctx); } @@ -1727,14 +1734,16 @@ void D3D11CommandQueue::ProcessDynamicLoads(ID3D11DeviceContext* ctx) } } -IGraphicsCommandQueue* _NewD3D11CommandQueue(D3D11Context* ctx, D3D11Context::Window* windowCtx, IGraphicsContext* parent) +std::unique_ptr +_NewD3D11CommandQueue(D3D11Context* ctx, D3D11Context::Window* windowCtx, IGraphicsContext* parent) { - return new D3D11CommandQueue(ctx, windowCtx, parent); + return std::make_unique(ctx, windowCtx, parent); } -IGraphicsDataFactory* _NewD3D11DataFactory(D3D11Context* ctx, IGraphicsContext* parent) +std::unique_ptr +_NewD3D11DataFactory(D3D11Context* ctx, IGraphicsContext* parent) { - return new D3D11DataFactory(parent, ctx); + return std::make_unique(parent, ctx); } } diff --git a/lib/graphicsdev/D3D12.cpp b/lib/graphicsdev/D3D12.cpp deleted file mode 100644 index cffdfbc..0000000 --- a/lib/graphicsdev/D3D12.cpp +++ /dev/null @@ -1,2414 +0,0 @@ -#include "../win/Win32Common.hpp" -#if _WIN32_WINNT_WIN10 -#include "logvisor/logvisor.hpp" -#include "boo/graphicsdev/D3D.hpp" -#include "boo/IGraphicsContext.hpp" -#include "Common.hpp" -#include -#include "d3dx12.h" -#include -#include -#include -#include -#include "xxhash.h" - -#define MAX_UNIFORM_COUNT 8 -#define MAX_TEXTURE_COUNT 8 - -#undef min -#undef max - -extern PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignaturePROC; -extern pD3DCompile D3DCompilePROC; - -static const char* GammaVS = -"struct VertData\n" -"{\n" -" float4 posIn : POSITION;\n" -" float4 uvIn : UV;\n" -"};\n" -"\n" -"struct VertToFrag\n" -"{\n" -" float4 pos : SV_Position;\n" -" float2 uv : UV;\n" -"};\n" -"\n" -"VertToFrag main(in VertData v)\n" -"{\n" -" VertToFrag vtf;\n" -" vtf.uv = v.uvIn.xy;\n" -" vtf.pos = v.posIn;\n" -" return vtf;\n" -"}\n"; - -static const char* GammaFS = -"struct VertToFrag\n" -"{\n" -" float4 pos : SV_Position;\n" -" float2 uv : UV;\n" -"};\n" -"\n" -"Texture2D screenTex : register(t0);\n" -"Texture2D gammaLUT : register(t1);\n" -"SamplerState samp : register(s2);\n" -"float4 main(in VertToFrag vtf) : SV_Target0\n" -"{\n" -" int4 tex = int4(saturate(screenTex.Sample(samp, vtf.uv)) * float4(65535.0, 65535.0, 65535.0, 65535.0));\n" -" float4 colorOut;\n" -" for (int i=0 ; i<3 ; ++i)\n" -" colorOut[i] = gammaLUT.Load(int3(tex[i] % 256, tex[i] / 256, 0)).r;\n" -" return colorOut;\n" -"}\n"; - -namespace boo -{ -static logvisor::Module Log("boo::D3D12"); -class D3D12DataFactory; - -struct D3D12ShareableShader : IShareableShader -{ - ComPtr m_shader; - D3D12ShareableShader(D3D12DataFactory& fac, uint64_t srcKey, uint64_t binKey, ComPtr&& s) - : IShareableShader(fac, srcKey, binKey), m_shader(std::move(s)) {} -}; - -static inline void ThrowIfFailed(HRESULT hr) -{ - if (FAILED(hr)) - { - // Set a breakpoint on this line to catch Win32 API errors. -#if !WINDOWS_STORE - _com_error err(hr); -#else - _com_error err(hr, L"D3D12 fail"); -#endif - LPCTSTR errMsg = err.ErrorMessage(); - Log.report(logvisor::Fatal, errMsg); - } -} - -static inline UINT64 NextHeapOffset(UINT64 offset, const D3D12_RESOURCE_ALLOCATION_INFO& info) -{ - offset += info.SizeInBytes; - return (offset + info.Alignment - 1) & ~(info.Alignment - 1); -} - -struct D3D12Data : BaseGraphicsData -{ - ComPtr m_bufHeap; - ComPtr m_texHeap; - explicit D3D12Data(GraphicsDataFactoryHead& head) : BaseGraphicsData(head) {} -}; - -struct D3D12Pool : BaseGraphicsPool -{ - ComPtr m_bufHeap; - explicit D3D12Pool(GraphicsDataFactoryHead& head) : BaseGraphicsPool(head) {} -}; - -static const D3D12_RESOURCE_STATES USE_TABLE[] = -{ - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, - D3D12_RESOURCE_STATE_INDEX_BUFFER, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER -}; - -class D3D12GraphicsBufferS : public GraphicsDataNode -{ - friend class D3D12DataFactory; - friend struct D3D12CommandQueue; - D3D12_RESOURCE_STATES m_state; - size_t m_sz; - D3D12_RESOURCE_DESC m_gpuDesc; - D3D12GraphicsBufferS(const boo::ObjToken& parent, - BufferUse use, D3D12Context* ctx, - const void* data, size_t stride, size_t count) - : GraphicsDataNode(parent), m_state(USE_TABLE[int(use)]), - m_stride(stride), m_count(count), m_sz(stride * count) - { - size_t gpuSz = use == BufferUse::Uniform ? ((m_sz + 255) & ~255) : m_sz; - m_gpuDesc = CD3DX12_RESOURCE_DESC::Buffer(gpuSz); - size_t reqSz = GetRequiredIntermediateSize(ctx->m_dev.Get(), &m_gpuDesc, 0, 1); - m_gpuDesc = CD3DX12_RESOURCE_DESC::Buffer(reqSz); - ThrowIfFailed(ctx->m_dev->CreateCommittedResource( - &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), - D3D12_HEAP_FLAG_NONE, &m_gpuDesc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &m_buf)); - - D3D12_SUBRESOURCE_DATA upData = {data, LONG_PTR(m_sz), LONG_PTR(m_sz)}; - if (!PrepSubresources<1>(ctx->m_dev.Get(), &m_gpuDesc, m_buf.Get(), 0, 0, 1, &upData)) - Log.report(logvisor::Fatal, "error preparing resource for upload"); - } -public: - size_t m_stride; - size_t m_count; - ComPtr m_buf; - ComPtr m_gpuBuf; - ~D3D12GraphicsBufferS() = default; - - UINT64 placeForGPU(D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) - { - ThrowIfFailed(ctx->m_dev->CreatePlacedResource(gpuHeap, offset, &m_gpuDesc, m_state, - nullptr, __uuidof(ID3D12Resource), &m_gpuBuf)); - - /* Stage resource upload */ - ctx->m_loadlist->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_gpuBuf.Get(), - m_state, D3D12_RESOURCE_STATE_COPY_DEST)); - CommandSubresourcesTransfer<1>(ctx->m_dev.Get(), ctx->m_loadlist.Get(), m_gpuBuf.Get(), m_buf.Get(), 0, 0, 1); - ctx->m_loadlist->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_gpuBuf.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, m_state)); - - return NextHeapOffset(offset, ctx->m_dev->GetResourceAllocationInfo(0, 1, &m_gpuDesc)); - } -}; - -template -class D3D12GraphicsBufferD : public GraphicsDataNode -{ - friend class D3D12DataFactory; - friend struct D3D12CommandQueue; - D3D12CommandQueue* m_q; - D3D12_RESOURCE_STATES m_state; - std::unique_ptr m_cpuBuf; - size_t m_cpuSz; - int m_validSlots = 0; - D3D12GraphicsBufferD(const boo::ObjToken& parent, - D3D12CommandQueue* q, BufferUse use, - D3D12Context* ctx, size_t stride, size_t count) - : GraphicsDataNode(parent), - m_state(USE_TABLE[int(use)]), m_q(q), m_stride(stride), m_count(count) - { - m_cpuSz = stride * count; - size_t gpuSz = ((m_cpuSz + 255) & ~255); - m_cpuBuf.reset(new uint8_t[gpuSz]); - D3D12_RESOURCE_DESC desc = CD3DX12_RESOURCE_DESC::Buffer(gpuSz); - size_t reqSz = GetRequiredIntermediateSize(ctx->m_dev.Get(), &desc, 0, 1); - desc = CD3DX12_RESOURCE_DESC::Buffer(reqSz); - for (int i=0 ; i<2 ; ++i) - { - ThrowIfFailed(ctx->m_dev->CreateCommittedResource( - &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), - D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &m_bufs[i])); - } - } - void update(int b); -public: - size_t m_stride; - size_t m_count; - ComPtr m_bufs[2]; - ComPtr m_gpuBufs[2]; - ~D3D12GraphicsBufferD() = default; - - void load(const void* data, size_t sz); - void* map(size_t sz); - void unmap(); - - UINT64 placeForGPU(D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) - { - for (int i=0 ; i<2 ; ++i) - { - D3D12_RESOURCE_DESC desc = m_bufs[i]->GetDesc(); - ThrowIfFailed(ctx->m_dev->CreatePlacedResource(gpuHeap, offset, &desc, m_state, - nullptr, __uuidof(ID3D12Resource), &m_gpuBufs[i])); - offset = NextHeapOffset(offset, ctx->m_dev->GetResourceAllocationInfo(0, 1, &desc)); - } - return offset; - } -}; - -class D3D12TextureS : public GraphicsDataNode -{ - friend class D3D12DataFactory; - TextureFormat m_fmt; - size_t m_sz; - D3D12_RESOURCE_DESC m_gpuDesc; - D3D12TextureS(const boo::ObjToken& parent, - D3D12Context* ctx, size_t width, size_t height, size_t mips, - TextureFormat fmt, const void* data, size_t sz) - : GraphicsDataNode(parent), m_fmt(fmt), m_sz(sz), m_mipCount(mips) - { - DXGI_FORMAT pfmt; - int pxPitchNum = 1; - int pxPitchDenom = 1; - bool compressed = false; - switch (fmt) - { - case TextureFormat::RGBA8: - pfmt = DXGI_FORMAT_R8G8B8A8_UNORM; - pxPitchNum = 4; - break; - case TextureFormat::I8: - pfmt = DXGI_FORMAT_R8_UNORM; - break; - case TextureFormat::I16: - pfmt = DXGI_FORMAT_R16_UNORM; - pxPitchNum = 2; - break; - case TextureFormat::DXT1: - pfmt = DXGI_FORMAT_BC1_UNORM; - compressed = true; - pxPitchNum = 1; - pxPitchDenom = 2; - break; - default: - Log.report(logvisor::Fatal, "unsupported tex format"); - } - - - m_gpuDesc = CD3DX12_RESOURCE_DESC::Tex2D(pfmt, width, height, 1, mips); - size_t reqSz = GetRequiredIntermediateSize(ctx->m_dev.Get(), &m_gpuDesc, 0, mips); - ThrowIfFailed(ctx->m_dev->CreateCommittedResource( - &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), - D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(reqSz), - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &m_tex)); - - const uint8_t* dataIt = static_cast(data); - D3D12_SUBRESOURCE_DATA upData[16] = {}; - for (size_t i=0 ; i 1) - width /= 2; - if (height > 1) - height /= 2; - } - - if (!PrepSubresources<16>(ctx->m_dev.Get(), &m_gpuDesc, m_tex.Get(), 0, 0, m_gpuDesc.MipLevels, upData)) - Log.report(logvisor::Fatal, "error preparing resource for upload"); - } -public: - size_t m_mipCount; - ComPtr m_tex; - ComPtr m_gpuTex; - ~D3D12TextureS() = default; - - UINT64 placeForGPU(D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) - { - ThrowIfFailed(ctx->m_dev->CreatePlacedResource(gpuHeap, offset, &m_gpuDesc, - D3D12_RESOURCE_STATE_COPY_DEST, - nullptr, __uuidof(ID3D12Resource), &m_gpuTex)); - - CommandSubresourcesTransfer<16>(ctx->m_dev.Get(), ctx->m_loadlist.Get(), m_gpuTex.Get(), - m_tex.Get(), 0, 0, m_gpuDesc.MipLevels); - ctx->m_loadlist->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_gpuTex.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); - - return NextHeapOffset(offset, ctx->m_dev->GetResourceAllocationInfo(0, 1, &m_gpuDesc)); - } - - TextureFormat format() const {return m_fmt;} -}; - -class D3D12TextureSA : public GraphicsDataNode -{ - friend class D3D12DataFactory; - TextureFormat m_fmt; - size_t m_layers; - size_t m_sz; - D3D12_RESOURCE_DESC m_gpuDesc; - D3D12TextureSA(const boo::ObjToken& parent, D3D12Context* ctx, - size_t width, size_t height, size_t layers, - size_t mips, TextureFormat fmt, const void* data, size_t sz) - : GraphicsDataNode(parent), m_fmt(fmt), m_layers(layers), m_sz(sz) - { - size_t pxPitch; - DXGI_FORMAT pixelFmt; - switch (fmt) - { - case TextureFormat::RGBA8: - pxPitch = 4; - pixelFmt = DXGI_FORMAT_R8G8B8A8_UNORM; - break; - case TextureFormat::I8: - pxPitch = 1; - pixelFmt = DXGI_FORMAT_R8_UNORM; - break; - case TextureFormat::I16: - pxPitch = 2; - pixelFmt = DXGI_FORMAT_R16_UNORM; - break; - default: - Log.report(logvisor::Fatal, "unsupported tex format"); - } - - m_gpuDesc = CD3DX12_RESOURCE_DESC::Tex2D(pixelFmt, width, height, layers, mips); - size_t reqSz = GetRequiredIntermediateSize(ctx->m_dev.Get(), &m_gpuDesc, 0, layers * mips); - ThrowIfFailed(ctx->m_dev->CreateCommittedResource( - &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), - D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(reqSz), - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &m_tex)); - - const uint8_t* dataIt = static_cast(data); - std::unique_ptr upData(new D3D12_SUBRESOURCE_DATA[layers * mips]); - D3D12_SUBRESOURCE_DATA* outIt = upData.get(); - for (size_t i=0 ; ipData = dataIt; - outIt->RowPitch = width * pxPitch; - outIt->SlicePitch = outIt->RowPitch * height; - dataIt += outIt->SlicePitch; - ++outIt; - } - if (width > 1) - width /= 2; - if (height > 1) - height /= 2; - } - if (!PrepSubresources(ctx->m_dev.Get(), &m_gpuDesc, m_tex.Get(), 0, 0, layers * mips, upData.get())) - Log.report(logvisor::Fatal, "error preparing resource for upload"); - } -public: - ComPtr m_tex; - ComPtr m_gpuTex; - ~D3D12TextureSA() = default; - - UINT64 placeForGPU(D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) - { - ThrowIfFailed(ctx->m_dev->CreatePlacedResource(gpuHeap, offset, &m_gpuDesc, - D3D12_RESOURCE_STATE_COPY_DEST, - nullptr, __uuidof(ID3D12Resource), &m_gpuTex)); - - CommandSubresourcesTransfer(ctx->m_dev.Get(), ctx->m_loadlist.Get(), m_gpuTex.Get(), - m_tex.Get(), 0, 0, m_gpuDesc.DepthOrArraySize * m_gpuDesc.MipLevels); - ctx->m_loadlist->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_gpuTex.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); - - return NextHeapOffset(offset, ctx->m_dev->GetResourceAllocationInfo(0, 1, &m_gpuDesc)); - } - - TextureFormat format() const {return m_fmt;} - size_t layers() const {return m_layers;} -}; - -class D3D12TextureD : public GraphicsDataNode -{ - friend class D3D12DataFactory; - friend struct D3D12CommandQueue; - size_t m_width = 0; - size_t m_height = 0; - TextureFormat m_fmt; - D3D12CommandQueue* m_q; - D3D12_RESOURCE_DESC m_gpuDesc; - std::unique_ptr m_cpuBuf; - size_t m_rowPitch; - size_t m_cpuSz; - int m_validSlots = 0; - D3D12TextureD(const boo::ObjToken& parent, D3D12CommandQueue* q, D3D12Context* ctx, - size_t width, size_t height, TextureFormat fmt) - : GraphicsDataNode(parent), m_width(width), m_height(height), m_fmt(fmt), m_q(q) - { - DXGI_FORMAT pixelFmt; - size_t pxPitch; - switch (fmt) - { - case TextureFormat::RGBA8: - pixelFmt = DXGI_FORMAT_R8G8B8A8_UNORM; - pxPitch = 4; - break; - case TextureFormat::I8: - pixelFmt = DXGI_FORMAT_R8_UNORM; - pxPitch = 1; - break; - case TextureFormat::I16: - pixelFmt = DXGI_FORMAT_R16_UNORM; - pxPitch = 2; - break; - default: - Log.report(logvisor::Fatal, "unsupported tex format"); - } - - m_cpuSz = width * height * pxPitch; - m_rowPitch = width * pxPitch; - m_cpuBuf.reset(new uint8_t[m_cpuSz]); - - m_gpuDesc = CD3DX12_RESOURCE_DESC::Tex2D(pixelFmt, width, height); - size_t reqSz = GetRequiredIntermediateSize(ctx->m_dev.Get(), &m_gpuDesc, 0, 1); - for (int i=0 ; i<2 ; ++i) - { - ThrowIfFailed(ctx->m_dev->CreateCommittedResource( - &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), - D3D12_HEAP_FLAG_NONE, - &CD3DX12_RESOURCE_DESC::Buffer(reqSz), - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), &m_texs[i])); - } - } - void update(int b); -public: - ComPtr m_texs[2]; - ComPtr m_gpuTexs[2]; - ~D3D12TextureD() = default; - - void load(const void* data, size_t sz); - void* map(size_t sz); - void unmap(); - - UINT64 placeForGPU(D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) - { - for (int i=0 ; i<2 ; ++i) - { - ThrowIfFailed(ctx->m_dev->CreatePlacedResource(gpuHeap, offset, &m_gpuDesc, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - nullptr, __uuidof(ID3D12Resource), &m_gpuTexs[i])); - offset = NextHeapOffset(offset, ctx->m_dev->GetResourceAllocationInfo(0, 1, &m_gpuDesc)); - } - return offset; - } - - TextureFormat format() const {return m_fmt;} -}; - -static const float BLACK_COLOR[] = {0.0,0.0,0.0,1.0}; -#define MAX_BIND_TEXS 4 - -class D3D12TextureR : public GraphicsDataNode -{ - friend class D3D12DataFactory; - friend struct D3D12CommandQueue; - size_t m_width = 0; - size_t m_height = 0; - size_t m_samples = 0; - size_t m_colorBindCount; - size_t m_depthBindCount; - - void Setup(D3D12Context* ctx) - { - D3D12_DESCRIPTOR_HEAP_DESC rtvdesc = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - ThrowIfFailed(ctx->m_dev->CreateDescriptorHeap(&rtvdesc, __uuidof(ID3D12DescriptorHeap), &m_rtvHeap)); - - D3D12_DESCRIPTOR_HEAP_DESC dsvdesc = {D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; - ThrowIfFailed(ctx->m_dev->CreateDescriptorHeap(&dsvdesc, __uuidof(ID3D12DescriptorHeap), &m_dsvHeap)); - - D3D12_RTV_DIMENSION rtvDim; - D3D12_DSV_DIMENSION dsvDim; - CD3DX12_RESOURCE_DESC rtvresdesc; - CD3DX12_RESOURCE_DESC dsvresdesc; - CD3DX12_RESOURCE_DESC cbindresdesc; - CD3DX12_RESOURCE_DESC dbindresdesc; - - if (m_samples > 1) - { - rtvDim = D3D12_RTV_DIMENSION_TEXTURE2DMS; - dsvDim = D3D12_DSV_DIMENSION_TEXTURE2DMS; - rtvresdesc = CD3DX12_RESOURCE_DESC::Tex2D(ctx->RGBATex2DFBViewDesc.Format, m_width, m_height, 1, 1, m_samples, - 0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_TEXTURE_LAYOUT_UNKNOWN, - D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT); - dsvresdesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R24G8_TYPELESS, m_width, m_height, 1, 1, m_samples, - 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_TEXTURE_LAYOUT_UNKNOWN, - D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT); - } - else - { - rtvDim = D3D12_RTV_DIMENSION_TEXTURE2D; - dsvDim = D3D12_DSV_DIMENSION_TEXTURE2D; - rtvresdesc = CD3DX12_RESOURCE_DESC::Tex2D(ctx->RGBATex2DFBViewDesc.Format, m_width, m_height, 1, 1, 1, - 0, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); - dsvresdesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R24G8_TYPELESS, m_width, m_height, 1, 1, 1, - 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - } - - cbindresdesc = CD3DX12_RESOURCE_DESC::Tex2D(ctx->RGBATex2DFBViewDesc.Format, m_width, m_height, 1, 1, 1, - 0, D3D12_RESOURCE_FLAG_NONE); - dbindresdesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R24G8_TYPELESS, m_width, m_height, 1, 1, 1, - 0, D3D12_RESOURCE_FLAG_NONE); - - D3D12_CLEAR_VALUE colorClear = {}; - colorClear.Format = ctx->RGBATex2DFBViewDesc.Format; - ThrowIfFailed(ctx->m_dev->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, - &rtvresdesc, D3D12_RESOURCE_STATE_RENDER_TARGET, &colorClear, - __uuidof(ID3D12Resource), &m_colorTex)); - - D3D12_CLEAR_VALUE depthClear = {}; - depthClear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; - ThrowIfFailed(ctx->m_dev->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, - &dsvresdesc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthClear, - __uuidof(ID3D12Resource), &m_depthTex)); - - D3D12_RENDER_TARGET_VIEW_DESC rtvvdesc = {ctx->RGBATex2DFBViewDesc.Format, rtvDim}; - ctx->m_dev->CreateRenderTargetView(m_colorTex.Get(), &rtvvdesc, m_rtvHeap->GetCPUDescriptorHandleForHeapStart()); - - D3D12_DEPTH_STENCIL_VIEW_DESC dsvvdesc = {DXGI_FORMAT_D24_UNORM_S8_UINT, dsvDim}; - ctx->m_dev->CreateDepthStencilView(m_depthTex.Get(), &dsvvdesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); - - for (size_t i=0 ; im_dev->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, - &cbindresdesc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, - __uuidof(ID3D12Resource), &m_colorBindTex[i])); - } - - for (size_t i=0 ; im_dev->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, - &dbindresdesc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, - __uuidof(ID3D12Resource), &m_depthBindTex[i])); - } - } - - D3D12CommandQueue* m_q; - D3D12TextureR(const boo::ObjToken& parent, - D3D12Context* ctx, D3D12CommandQueue* q, - size_t width, size_t height, size_t samples, - size_t colorBindCount, size_t depthBindCount) - : GraphicsDataNode(parent), m_q(q), m_width(width), m_height(height), m_samples(samples), - m_colorBindCount(colorBindCount), m_depthBindCount(depthBindCount) - { - if (colorBindCount > MAX_BIND_TEXS) - Log.report(logvisor::Fatal, "too many color bindings for render texture"); - if (depthBindCount > MAX_BIND_TEXS) - Log.report(logvisor::Fatal, "too many depth bindings for render texture"); - - if (samples == 0) m_samples = 1; - Setup(ctx); - } -public: - size_t samples() const {return m_samples;} - ComPtr m_colorTex; - ComPtr m_rtvHeap; - - ComPtr m_depthTex; - ComPtr m_dsvHeap; - - ComPtr m_colorBindTex[MAX_BIND_TEXS]; - - ComPtr m_depthBindTex[MAX_BIND_TEXS]; - - ~D3D12TextureR(); - - void resize(D3D12Context* ctx, size_t width, size_t height) - { - if (width < 1) - width = 1; - if (height < 1) - height = 1; - m_width = width; - m_height = height; - Setup(ctx); - } -}; - -static const size_t SEMANTIC_SIZE_TABLE[] = -{ - 0, - 12, - 16, - 12, - 16, - 16, - 4, - 8, - 16, - 16, - 16 -}; - -static const char* SEMANTIC_NAME_TABLE[] = -{ - nullptr, - "POSITION", - "POSITION", - "NORMAL", - "NORMAL", - "COLOR", - "COLOR", - "UV", - "UV", - "WEIGHT", - "MODELVIEW" -}; - -static const DXGI_FORMAT SEMANTIC_TYPE_TABLE[] = -{ - DXGI_FORMAT_UNKNOWN, - DXGI_FORMAT_R32G32B32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R32G32B32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_R32G32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R32G32B32A32_FLOAT -}; - -struct D3D12VertexFormat : GraphicsDataNode -{ - size_t m_elementCount; - std::unique_ptr m_elements; - size_t m_stride = 0; - size_t m_instStride = 0; - - D3D12VertexFormat(const boo::ObjToken& parent, - size_t elementCount, const VertexElementDescriptor* elements) - : GraphicsDataNode(parent), m_elementCount(elementCount), - m_elements(new D3D12_INPUT_ELEMENT_DESC[elementCount]) - { - memset(m_elements.get(), 0, elementCount * sizeof(D3D12_INPUT_ELEMENT_DESC)); - for (size_t i=0 ; isemantic & boo::VertexSemantic::SemanticMask); - elem.SemanticName = SEMANTIC_NAME_TABLE[semantic]; - elem.SemanticIndex = elemin->semanticIdx; - elem.Format = SEMANTIC_TYPE_TABLE[semantic]; - if ((elemin->semantic & boo::VertexSemantic::Instanced) != boo::VertexSemantic::None) - { - elem.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; - elem.InstanceDataStepRate = 1; - elem.InputSlot = 1; - elem.AlignedByteOffset = m_instStride; - m_instStride += SEMANTIC_SIZE_TABLE[semantic]; - } - else - { - elem.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; - elem.AlignedByteOffset = m_stride; - m_stride += SEMANTIC_SIZE_TABLE[semantic]; - } - } - } -}; - -static const D3D12_PRIMITIVE_TOPOLOGY PRIMITIVE_TABLE[] = -{ - D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, - D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP -}; - -static const D3D12_BLEND BLEND_FACTOR_TABLE[] = -{ - D3D12_BLEND_ZERO, - D3D12_BLEND_ONE, - D3D12_BLEND_SRC_COLOR, - D3D12_BLEND_INV_SRC_COLOR, - D3D12_BLEND_DEST_COLOR, - D3D12_BLEND_INV_DEST_COLOR, - D3D12_BLEND_SRC_ALPHA, - D3D12_BLEND_INV_SRC_ALPHA, - D3D12_BLEND_DEST_ALPHA, - D3D12_BLEND_INV_DEST_ALPHA, - D3D12_BLEND_SRC1_COLOR, - D3D12_BLEND_INV_SRC1_COLOR -}; - -class D3D12ShaderPipeline : public GraphicsDataNode -{ - friend class D3D12DataFactory; - friend struct D3D12ShaderDataBinding; - boo::ObjToken m_vtxFmt; - D3D12ShareableShader::Token m_vert; - D3D12ShareableShader::Token m_pixel; - - D3D12ShaderPipeline(const boo::ObjToken& parent, - D3D12Context* ctx, D3D12ShareableShader::Token&& vert, - D3D12ShareableShader::Token&& pixel, ID3DBlob* pipeline, - const boo::ObjToken& vtxFmt, - BlendFactor srcFac, BlendFactor dstFac, Primitive prim, - ZTest depthTest, bool depthWrite, bool colorWrite, - bool alphaWrite, bool overwriteAlpha, CullMode culling) - : GraphicsDataNode(parent), m_vtxFmt(vtxFmt), - m_vert(std::move(vert)), m_pixel(std::move(pixel)), - m_topology(PRIMITIVE_TABLE[int(prim)]) - { - D3D12_CULL_MODE cullMode; - switch (culling) - { - case CullMode::None: - default: - cullMode = D3D12_CULL_MODE_NONE; - break; - case CullMode::Backface: - cullMode = D3D12_CULL_MODE_BACK; - break; - case CullMode::Frontface: - cullMode = D3D12_CULL_MODE_FRONT; - break; - } - - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = {}; - desc.pRootSignature = ctx->m_rs.Get(); - const auto& vBlob = m_vert.get().m_shader; - const auto& pBlob = m_pixel.get().m_shader; - desc.VS = {vBlob->GetBufferPointer(), vBlob->GetBufferSize()}; - desc.PS = {pBlob->GetBufferPointer(), pBlob->GetBufferSize()}; - desc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); - if (dstFac != BlendFactor::Zero) - { - desc.BlendState.RenderTarget[0].BlendEnable = true; - if (srcFac == BlendFactor::Subtract || dstFac == BlendFactor::Subtract) - { - desc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; - desc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_ONE; - desc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_REV_SUBTRACT; - if (overwriteAlpha) - { - desc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; - desc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO; - desc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; - } - else - { - desc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA; - desc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE; - desc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_REV_SUBTRACT; - } - } - else - { - desc.BlendState.RenderTarget[0].SrcBlend = BLEND_FACTOR_TABLE[int(srcFac)]; - desc.BlendState.RenderTarget[0].DestBlend = BLEND_FACTOR_TABLE[int(dstFac)]; - desc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; - if (overwriteAlpha) - { - desc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; - desc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO; - } - else - { - desc.BlendState.RenderTarget[0].SrcBlendAlpha = BLEND_FACTOR_TABLE[int(srcFac)]; - desc.BlendState.RenderTarget[0].DestBlendAlpha = BLEND_FACTOR_TABLE[int(dstFac)]; - } - desc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; - } - } - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = - (colorWrite ? (D3D12_COLOR_WRITE_ENABLE_RED | - D3D12_COLOR_WRITE_ENABLE_GREEN | - D3D12_COLOR_WRITE_ENABLE_BLUE) : 0) | - (alphaWrite ? D3D12_COLOR_WRITE_ENABLE_ALPHA : 0); - desc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); - desc.RasterizerState.FrontCounterClockwise = TRUE; - desc.RasterizerState.CullMode = cullMode; - desc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); - switch (depthTest) - { - case ZTest::None: - default: - desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; - break; - case ZTest::LEqual: - desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; - break; - case ZTest::Greater: - desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; - break; - case ZTest::GEqual: - desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; - break; - case ZTest::Equal: - desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; - break; - } - desc.DepthStencilState.DepthEnable = depthTest != ZTest::None; - if (!depthWrite) - desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; - D3D12VertexFormat* vfmt = vtxFmt.cast(); - desc.InputLayout.NumElements = vfmt->m_elementCount; - desc.InputLayout.pInputElementDescs = vfmt->m_elements.get(); - desc.SampleMask = UINT_MAX; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = ctx->RGBATex2DFBViewDesc.Format; - desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; - desc.SampleDesc.Count = ctx->m_sampleCount; - desc.SampleDesc.Quality = 0; - if (pipeline) - { - desc.CachedPSO.pCachedBlob = pipeline->GetBufferPointer(); - desc.CachedPSO.CachedBlobSizeInBytes = pipeline->GetBufferSize(); - } - ThrowIfFailed(ctx->m_dev->CreateGraphicsPipelineState(&desc, __uuidof(ID3D12PipelineState), &m_state)); - } -public: - ComPtr m_state; - D3D12_PRIMITIVE_TOPOLOGY m_topology; - ~D3D12ShaderPipeline() = default; - D3D12ShaderPipeline& operator=(const D3D12ShaderPipeline&) = delete; - D3D12ShaderPipeline(const D3D12ShaderPipeline&) = delete; -}; - -static UINT64 PlaceBufferForGPU(IGraphicsBuffer* buf, D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) -{ - if (buf->dynamic()) - return static_cast*>(buf)->placeForGPU(ctx, gpuHeap, offset); - else - return static_cast(buf)->placeForGPU(ctx, gpuHeap, offset); -} - -static UINT64 PlaceTextureForGPU(ITexture* tex, D3D12Context* ctx, ID3D12Heap* gpuHeap, UINT64 offset) -{ - switch (tex->type()) - { - case TextureType::Dynamic: - return static_cast(tex)->placeForGPU(ctx, gpuHeap, offset); - case TextureType::Static: - return static_cast(tex)->placeForGPU(ctx, gpuHeap, offset); - case TextureType::StaticArray: - return static_cast(tex)->placeForGPU(ctx, gpuHeap, offset); - } - return offset; -} - -static ID3D12Resource* GetBufferGPUResource(const IGraphicsBuffer* buf, int idx, - D3D12_VERTEX_BUFFER_VIEW& descOut, size_t offset) -{ - if (buf->dynamic()) - { - const D3D12GraphicsBufferD* cbuf = - static_cast*>(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride - offset; - descOut.StrideInBytes = cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBufs[idx]->GetGPUVirtualAddress() + offset; - return cbuf->m_gpuBufs[idx].Get(); - } - else - { - const D3D12GraphicsBufferS* cbuf = static_cast(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride - offset; - descOut.StrideInBytes = cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBuf->GetGPUVirtualAddress() + offset; - return cbuf->m_gpuBuf.Get(); - } -} - -static ID3D12Resource* GetBufferGPUResource(const IGraphicsBuffer* buf, int idx, - D3D12_INDEX_BUFFER_VIEW& descOut) -{ - if (buf->dynamic()) - { - const D3D12GraphicsBufferD* cbuf = - static_cast*>(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBufs[idx]->GetGPUVirtualAddress(); - descOut.Format = DXGI_FORMAT_R32_UINT; - return cbuf->m_gpuBufs[idx].Get(); - } - else - { - const D3D12GraphicsBufferS* cbuf = static_cast(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBuf->GetGPUVirtualAddress(); - descOut.Format = DXGI_FORMAT_R32_UINT; - return cbuf->m_gpuBuf.Get(); - } -} - -static ID3D12Resource* GetBufferGPUResource(const IGraphicsBuffer* buf, int idx, - D3D12_CONSTANT_BUFFER_VIEW_DESC& descOut) -{ - if (buf->dynamic()) - { - const D3D12GraphicsBufferD* cbuf = - static_cast*>(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBufs[idx]->GetGPUVirtualAddress(); - return cbuf->m_gpuBufs[idx].Get(); - } - else - { - const D3D12GraphicsBufferS* cbuf = static_cast(buf); - descOut.SizeInBytes = cbuf->m_count * cbuf->m_stride; - descOut.BufferLocation = cbuf->m_gpuBuf->GetGPUVirtualAddress(); - return cbuf->m_gpuBuf.Get(); - } -} - -static const struct RGBATex2DDepthViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - RGBATex2DDepthViewDesc() - { - Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2D = {UINT(0), UINT(1), UINT(0), 0.0f}; - } -} RGBATex2DDepthViewDesc; - -static const struct RGBATex2DViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - RGBATex2DViewDesc() - { - Format = DXGI_FORMAT_R8G8B8A8_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2D = {UINT(0), UINT(-1), UINT(0), 0.0f}; - } -} RGBATex2DViewDesc; - -static const struct DXTTex2DViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - DXTTex2DViewDesc() - { - Format = DXGI_FORMAT_BC1_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2D = {UINT(0), UINT(-1), UINT(0), 0.0f}; - } -} DXTTex2DViewDesc; - -static const struct GreyTex2DViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - GreyTex2DViewDesc() - { - Format = DXGI_FORMAT_R8_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2D = {UINT(0), UINT(-1), UINT(0), 0.0f}; - } -} GreyTex2DViewDesc; - -static const struct Grey16Tex2DViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - Grey16Tex2DViewDesc() - { - Format = DXGI_FORMAT_R16_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2D = {UINT(0), UINT(-1), UINT(0), 0.0f}; - } -} Grey16Tex2DViewDesc; - -static const struct RGBATex2DArrayViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - RGBATex2DArrayViewDesc() - { - Format = DXGI_FORMAT_R8G8B8A8_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2DArray = {UINT(0), UINT(1), 0, 0, UINT(0), 0.0f}; - } -} RGBATex2DArrayViewDesc; - -static const struct GreyTex2DArrayViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - GreyTex2DArrayViewDesc() - { - Format = DXGI_FORMAT_R8_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2DArray = {UINT(0), UINT(1), 0, 0, UINT(0), 0.0f}; - } -} GreyTex2DArrayViewDesc; - -static const struct Grey16Tex2DArrayViewDesc : D3D12_SHADER_RESOURCE_VIEW_DESC -{ - Grey16Tex2DArrayViewDesc() - { - Format = DXGI_FORMAT_R16_UNORM; - ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - Texture2DArray = {UINT(0), UINT(1), 0, 0, UINT(0), 0.0f}; - } -} Grey16Tex2DArrayViewDesc; - -static ID3D12Resource* GetTextureGPUResource(D3D12Context* ctx, const ITexture* tex, int idx, int bindIdx, bool depth, - D3D12_SHADER_RESOURCE_VIEW_DESC& descOut) -{ - switch (tex->type()) - { - case TextureType::Dynamic: - { - const D3D12TextureD* ctex = static_cast(tex); - switch (ctex->format()) - { - case TextureFormat::RGBA8: - descOut = RGBATex2DViewDesc; - break; - case TextureFormat::I8: - descOut = GreyTex2DViewDesc; - break; - case TextureFormat::I16: - descOut = Grey16Tex2DViewDesc; - break; - default:break; - } - descOut.Texture2D.MipLevels = 1; - return ctex->m_gpuTexs[idx].Get(); - } - case TextureType::Static: - { - const D3D12TextureS* ctex = static_cast(tex); - switch (ctex->format()) - { - case TextureFormat::RGBA8: - descOut = RGBATex2DViewDesc; - break; - case TextureFormat::I8: - descOut = GreyTex2DViewDesc; - break; - case TextureFormat::I16: - descOut = Grey16Tex2DViewDesc; - break; - case TextureFormat::DXT1: - descOut = DXTTex2DViewDesc; - break; - default:break; - } - descOut.Texture2D.MipLevels = ctex->m_mipCount; - return ctex->m_gpuTex.Get(); - } - case TextureType::StaticArray: - { - const D3D12TextureSA* ctex = static_cast(tex); - switch (ctex->format()) - { - case TextureFormat::RGBA8: - descOut = RGBATex2DArrayViewDesc; - break; - case TextureFormat::I8: - descOut = GreyTex2DArrayViewDesc; - break; - case TextureFormat::I16: - descOut = Grey16Tex2DArrayViewDesc; - break; - default:break; - } - descOut.Texture2DArray.ArraySize = ctex->layers(); - return ctex->m_gpuTex.Get(); - } - case TextureType::Render: - { - const D3D12TextureR* ctex = static_cast(tex); - if (depth) - { - descOut = RGBATex2DDepthViewDesc; - return ctex->m_depthBindTex[bindIdx].Get(); - } - else - { - descOut = ctx->RGBATex2DFBViewDesc; - return ctex->m_colorBindTex[bindIdx].Get(); - } - } - default: break; - } - return nullptr; -} - -struct D3D12ShaderDataBinding : public GraphicsDataNode -{ - boo::ObjToken m_pipeline; - ComPtr m_gpuHeap; - ComPtr m_descHeap[2]; - boo::ObjToken m_vbuf; - boo::ObjToken m_instVbuf; - boo::ObjToken m_ibuf; - std::vector> m_ubufs; - std::vector> m_ubufOffs; - ID3D12Resource* m_knownViewHandles[2][8] = {}; - struct BindTex - { - boo::ObjToken tex; - int idx; - bool depth; - }; - std::vector m_texs; - D3D12_VERTEX_BUFFER_VIEW m_vboView[2][2] = {{},{}}; - D3D12_INDEX_BUFFER_VIEW m_iboView[2]; - size_t m_vertOffset, m_instOffset; - - D3D12ShaderDataBinding(const boo::ObjToken& d, - D3D12Context* ctx, - const boo::ObjToken& pipeline, - const boo::ObjToken& vbuf, - const boo::ObjToken& instVbuf, - const boo::ObjToken& ibuf, - size_t ubufCount, const boo::ObjToken* ubufs, - const size_t* ubufOffs, const size_t* ubufSizes, - size_t texCount, const boo::ObjToken* texs, - const int* bindIdxs, const bool* bindDepth, - size_t baseVert, size_t baseInst) - : GraphicsDataNode(d), - m_pipeline(pipeline), - m_vbuf(vbuf), - m_instVbuf(instVbuf), - m_ibuf(ibuf) - { - D3D12ShaderPipeline* cpipeline = m_pipeline.cast(); - D3D12VertexFormat* vtxFmt = cpipeline->m_vtxFmt.cast(); - m_vertOffset = baseVert * vtxFmt->m_stride; - m_instOffset = baseInst * vtxFmt->m_instStride; - - if (ubufOffs && ubufSizes) - { - m_ubufOffs.reserve(ubufCount); - for (size_t i=0 ; im_dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - for (int b=0 ; b<2 ; ++b) - { - ThrowIfFailed(ctx->m_dev->CreateDescriptorHeap(&desc, _uuidof(ID3D12DescriptorHeap), &m_descHeap[b])); - CD3DX12_CPU_DESCRIPTOR_HANDLE handle(m_descHeap[b]->GetCPUDescriptorHandleForHeapStart()); - - if (m_vbuf) - GetBufferGPUResource(m_vbuf.get(), b, m_vboView[b][0], m_vertOffset); - if (m_instVbuf) - GetBufferGPUResource(m_instVbuf.get(), b, m_vboView[b][1], m_instOffset); - if (m_ibuf) - GetBufferGPUResource(m_ibuf.get(), b, m_iboView[b]); - if (m_ubufOffs.size()) - { - for (size_t i=0 ; i& offPair = m_ubufOffs[i]; - D3D12_CONSTANT_BUFFER_VIEW_DESC viewDesc; - GetBufferGPUResource(m_ubufs[i].get(), b, viewDesc); - viewDesc.BufferLocation += offPair.first; - viewDesc.SizeInBytes = (offPair.second + 255) & ~255; - ctx->m_dev->CreateConstantBufferView(&viewDesc, handle); - } - handle.Offset(1, incSz); - } - } - else - { - for (size_t i=0 ; im_dev->CreateConstantBufferView(&viewDesc, handle); - } - handle.Offset(1, incSz); - } - } - for (size_t i=0 ; im_dev->CreateShaderResourceView(res, &srvDesc, handle); - } - handle.Offset(1, incSz); - } - } - } - - void bind(D3D12Context* ctx, ID3D12GraphicsCommandList* list, int b) - { - UINT incSz = UINT(-1); - CD3DX12_CPU_DESCRIPTOR_HANDLE heapStart; - for (size_t i=0 ; itype() == TextureType::Render) - { - const D3D12TextureR* ctex = m_texs[i].tex.cast(); - if (m_texs[i].depth) - { - ID3D12Resource* res = ctex->m_depthBindTex[m_texs[i].idx].Get(); - if (res != m_knownViewHandles[b][i]) - { - if (incSz == UINT(-1)) - { - incSz = ctx->m_dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - heapStart = m_descHeap[b]->GetCPUDescriptorHandleForHeapStart(); - } - m_knownViewHandles[b][i] = res; - ctx->m_dev->CreateShaderResourceView(res, &RGBATex2DDepthViewDesc, - CD3DX12_CPU_DESCRIPTOR_HANDLE(heapStart, MAX_UNIFORM_COUNT + i, incSz)); - } - } - else - { - ID3D12Resource* res = ctex->m_colorBindTex[m_texs[i].idx].Get(); - if (res != m_knownViewHandles[b][i]) - { - if (incSz == UINT(-1)) - { - incSz = ctx->m_dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - heapStart = m_descHeap[b]->GetCPUDescriptorHandleForHeapStart(); - } - m_knownViewHandles[b][i] = res; - ctx->m_dev->CreateShaderResourceView(res, &ctx->RGBATex2DFBViewDesc, - CD3DX12_CPU_DESCRIPTOR_HANDLE(heapStart, MAX_UNIFORM_COUNT + i, incSz)); - } - } - } - } - } - - D3D12ShaderPipeline* pipeline = m_pipeline.cast(); - ID3D12DescriptorHeap* heap[] = {m_descHeap[b].Get()}; - list->SetDescriptorHeaps(1, heap); - list->SetGraphicsRootDescriptorTable(0, m_descHeap[b]->GetGPUDescriptorHandleForHeapStart()); - list->SetPipelineState(pipeline->m_state.Get()); - list->IASetVertexBuffers(0, 2, m_vboView[b]); - if (m_ibuf) - list->IASetIndexBuffer(&m_iboView[b]); - list->IASetPrimitiveTopology(pipeline->m_topology); - } -}; - -static ID3D12GraphicsCommandList* WaitForLoadList(D3D12Context* ctx) -{ - /* Wait for previous transaction to complete (if in progress) */ - if (ctx->m_loadfence->GetCompletedValue() < ctx->m_loadfenceval) - { - ThrowIfFailed(ctx->m_loadfence->SetEventOnCompletion(ctx->m_loadfenceval, ctx->m_loadfencehandle)); - WaitForSingleObject(ctx->m_loadfencehandle, INFINITE); - } - return ctx->m_loadlist.Get(); -} - -struct D3D12CommandQueue : IGraphicsCommandQueue -{ - Platform platform() const {return IGraphicsDataFactory::Platform::D3D12;} - const SystemChar* platformName() const {return _S("D3D12");} - D3D12Context* m_ctx; - D3D12Context::Window* m_windowCtx; - IGraphicsContext* m_parent; - ComPtr m_cmdList; - ComPtr m_fence; - - ComPtr m_dynamicCmdAlloc[2]; - ComPtr m_dynamicCmdQueue; - ComPtr m_dynamicCmdList; - UINT64 m_dynamicBufFenceVal = 0; - ComPtr m_dynamicBufFence; - HANDLE m_dynamicBufFenceHandle; - bool m_dynamicNeedsReset = false; - - HANDLE m_renderFenceHandle; - bool m_running = true; - - size_t m_fillBuf = 0; - size_t m_drawBuf = 0; - - void resetCommandList() - { - ThrowIfFailed(m_ctx->m_qalloc[m_fillBuf]->Reset()); - ThrowIfFailed(m_cmdList->Reset(m_ctx->m_qalloc[m_fillBuf].Get(), nullptr)); - m_cmdList->SetGraphicsRootSignature(m_ctx->m_rs.Get()); - } - - void resetDynamicCommandList() - { - ThrowIfFailed(m_dynamicCmdAlloc[m_fillBuf]->Reset()); - ThrowIfFailed(m_dynamicCmdList->Reset(m_dynamicCmdAlloc[m_fillBuf].Get(), nullptr)); - m_dynamicNeedsReset = false; - } - - void stallDynamicUpload() - { - if (m_dynamicNeedsReset) - { - if (m_dynamicBufFence->GetCompletedValue() < m_dynamicBufFenceVal) - { - ThrowIfFailed(m_dynamicBufFence->SetEventOnCompletion(m_dynamicBufFenceVal, - m_dynamicBufFenceHandle)); - WaitForSingleObject(m_dynamicBufFenceHandle, INFINITE); - } - resetDynamicCommandList(); - } - } - - D3D12CommandQueue(D3D12Context* ctx, D3D12Context::Window* windowCtx, IGraphicsContext* parent, - ID3D12CommandQueue** cmdQueueOut) - : m_ctx(ctx), m_windowCtx(windowCtx), m_parent(parent) - { - ThrowIfFailed(ctx->m_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - __uuidof(ID3D12CommandAllocator), - &ctx->m_qalloc[0])); - ThrowIfFailed(ctx->m_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - __uuidof(ID3D12CommandAllocator), - &ctx->m_qalloc[1])); - D3D12_COMMAND_QUEUE_DESC desc = - { - D3D12_COMMAND_LIST_TYPE_DIRECT, - D3D12_COMMAND_QUEUE_PRIORITY_HIGH, - D3D12_COMMAND_QUEUE_FLAG_NONE - }; - ThrowIfFailed(ctx->m_dev->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), &ctx->m_q)); - *cmdQueueOut = ctx->m_q.Get(); - ThrowIfFailed(ctx->m_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &m_fence)); - ThrowIfFailed(ctx->m_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, ctx->m_qalloc[0].Get(), - nullptr, __uuidof(ID3D12GraphicsCommandList), &m_cmdList)); - m_renderFenceHandle = CreateEvent(nullptr, FALSE, FALSE, nullptr); - m_cmdList->SetGraphicsRootSignature(m_ctx->m_rs.Get()); - - ThrowIfFailed(ctx->m_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &m_dynamicBufFence)); - m_dynamicBufFenceHandle = CreateEvent(nullptr, FALSE, FALSE, nullptr); - ThrowIfFailed(ctx->m_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - __uuidof(ID3D12CommandAllocator), &m_dynamicCmdAlloc[0])); - ThrowIfFailed(ctx->m_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - __uuidof(ID3D12CommandAllocator), &m_dynamicCmdAlloc[1])); - ThrowIfFailed(ctx->m_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_dynamicCmdAlloc[0].Get(), - nullptr, __uuidof(ID3D12GraphicsCommandList), &m_dynamicCmdList)); - } - - void startRenderer(); - void stopRenderer(); - - ~D3D12CommandQueue() - { - if (m_running) stopRenderer(); - } - - void setShaderDataBinding(const boo::ObjToken& binding) - { - D3D12ShaderDataBinding* cbind = binding.cast(); - cbind->bind(m_ctx, m_cmdList.Get(), m_fillBuf); - } - - boo::ObjToken m_boundTarget; - void setRenderTarget(const boo::ObjToken& target) - { - D3D12TextureR* ctarget = target.cast(); - - m_cmdList->OMSetRenderTargets(1, &ctarget->m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), - false, &ctarget->m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); - - m_boundTarget = target; - } - - void setViewport(const SWindowRect& rect, float znear, float zfar) - { - if (m_boundTarget) - { - D3D12TextureR* ctarget = m_boundTarget.cast(); - D3D12_VIEWPORT vp = {FLOAT(rect.location[0]), FLOAT(ctarget->m_height - rect.location[1] - rect.size[1]), - FLOAT(rect.size[0]), FLOAT(rect.size[1]), 1.f - zfar, 1.f - znear}; - m_cmdList->RSSetViewports(1, &vp); - } - } - - void setScissor(const SWindowRect& rect) - { - if (m_boundTarget) - { - D3D12TextureR* ctarget = m_boundTarget.cast(); - D3D12_RECT d3drect = {LONG(rect.location[0]), LONG(ctarget->m_height - rect.location[1] - rect.size[1]), - LONG(rect.location[0] + rect.size[0]), LONG(ctarget->m_height - rect.location[1])}; - m_cmdList->RSSetScissorRects(1, &d3drect); - } - } - - std::unordered_map> m_texResizes; - void resizeRenderTexture(const boo::ObjToken& tex, size_t width, size_t height) - { - D3D12TextureR* ctex = tex.cast(); - m_texResizes[ctex] = std::make_pair(width, height); - } - - void schedulePostFrameHandler(std::function&& func) - { - func(); - } - - float m_clearColor[4] = {0.0,0.0,0.0,0.0}; - void setClearColor(const float rgba[4]) - { - m_clearColor[0] = rgba[0]; - m_clearColor[1] = rgba[1]; - m_clearColor[2] = rgba[2]; - m_clearColor[3] = rgba[3]; - } - - void clearTarget(bool render=true, bool depth=true) - { - if (!m_boundTarget) - return; - D3D12TextureR* ctarget = m_boundTarget.cast(); - if (render) - { - CD3DX12_CPU_DESCRIPTOR_HANDLE handle(ctarget->m_rtvHeap->GetCPUDescriptorHandleForHeapStart()); - m_cmdList->ClearRenderTargetView(handle, m_clearColor, 0, nullptr); - } - if (depth) - { - CD3DX12_CPU_DESCRIPTOR_HANDLE handle(ctarget->m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); - m_cmdList->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, 0.0f, 0, 0, nullptr); - } - } - - void draw(size_t start, size_t count) - { - m_cmdList->DrawInstanced(count, 1, start, 0); - } - - void drawIndexed(size_t start, size_t count) - { - m_cmdList->DrawIndexedInstanced(count, 1, start, 0, 0); - } - - void drawInstances(size_t start, size_t count, size_t instCount) - { - m_cmdList->DrawInstanced(count, instCount, start, 0); - } - - void drawInstancesIndexed(size_t start, size_t count, size_t instCount) - { - m_cmdList->DrawIndexedInstanced(count, instCount, start, 0, 0); - } - - void resolveBindTexture(const boo::ObjToken& texture, - const SWindowRect& rect, bool tlOrigin, - int bindIdx, bool color, bool depth, bool clearDepth) - { - D3D12TextureR* tex = texture.cast(); - - if (color && tex->m_colorBindCount) - { - D3D12_RESOURCE_BARRIER copySetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_colorTex.Get(), - D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_colorBindTex[bindIdx].Get(), - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST) - }; - m_cmdList->ResourceBarrier(2, copySetup); - - if (tex->m_samples > 1) - { - m_cmdList->CopyResource(tex->m_colorBindTex[bindIdx].Get(), tex->m_colorTex.Get()); - } - else - { - SWindowRect intersectRect = rect.intersect(SWindowRect(0, 0, tex->m_width, tex->m_height)); - int y = tlOrigin ? intersectRect.location[1] : (tex->m_height - intersectRect.size[1] - intersectRect.location[1]); - D3D12_BOX box = {UINT(intersectRect.location[0]), UINT(y), 0, - UINT(intersectRect.location[0] + intersectRect.size[0]), UINT(y + intersectRect.size[1]), 1}; - - D3D12_TEXTURE_COPY_LOCATION dst = {tex->m_colorBindTex[bindIdx].Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; - dst.SubresourceIndex = 0; - D3D12_TEXTURE_COPY_LOCATION src = {tex->m_colorTex.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; - src.SubresourceIndex = 0; - m_cmdList->CopyTextureRegion(&dst, box.left, box.top, 0, &src, &box); - } - - D3D12_RESOURCE_BARRIER copyTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_colorTex.Get(), - D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET), - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_colorBindTex[bindIdx].Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE) - }; - m_cmdList->ResourceBarrier(2, copyTeardown); - } - if (depth && tex->m_depthBindCount) - { - D3D12_RESOURCE_BARRIER copySetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_depthTex.Get(), - D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE), - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_depthBindTex[bindIdx].Get(), - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST) - }; - m_cmdList->ResourceBarrier(2, copySetup); - - m_cmdList->CopyResource(tex->m_depthBindTex[bindIdx].Get(), tex->m_depthTex.Get()); - - D3D12_RESOURCE_BARRIER copyTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_depthTex.Get(), - D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_DEPTH_WRITE), - CD3DX12_RESOURCE_BARRIER::Transition(tex->m_depthBindTex[bindIdx].Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE) - }; - m_cmdList->ResourceBarrier(2, copyTeardown); - } - - if (clearDepth) - { - CD3DX12_CPU_DESCRIPTOR_HANDLE handle(tex->m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); - m_cmdList->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, 0.0f, 0, 0, nullptr); - } - } - - bool m_doPresent = false; - void resolveDisplay(const boo::ObjToken& source); - - UINT64 m_submittedFenceVal = 0; - void execute(); -}; - -D3D12TextureR::~D3D12TextureR() -{ - if (m_q->m_boundTarget.get() == this) - m_q->m_boundTarget.reset(); -} - -template -void D3D12GraphicsBufferD::update(int b) -{ - int slot = 1 << b; - if ((slot & m_validSlots) == 0) - { - m_q->stallDynamicUpload(); - ID3D12Resource* res = m_bufs[b].Get(); - ID3D12Resource* gpuRes = m_gpuBufs[b].Get(); - D3D12_SUBRESOURCE_DATA d = {m_cpuBuf.get(), LONG_PTR(m_cpuSz), LONG_PTR(m_cpuSz)}; - m_q->m_dynamicCmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(gpuRes, - m_state, D3D12_RESOURCE_STATE_COPY_DEST)); - if (!UpdateSubresources<1>(m_q->m_dynamicCmdList.Get(), gpuRes, res, 0, 0, 1, &d)) - Log.report(logvisor::Fatal, "unable to update dynamic buffer data"); - m_q->m_dynamicCmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(gpuRes, - D3D12_RESOURCE_STATE_COPY_DEST, m_state)); - m_validSlots |= slot; - } -} - -template -void D3D12GraphicsBufferD::load(const void* data, size_t sz) -{ - size_t bufSz = std::min(sz, m_cpuSz); - memcpy(m_cpuBuf.get(), data, bufSz); - m_validSlots = 0; -} -template -void* D3D12GraphicsBufferD::map(size_t sz) -{ - if (sz > m_cpuSz) - return nullptr; - return m_cpuBuf.get(); -} -template -void D3D12GraphicsBufferD::unmap() -{ - m_validSlots = 0; -} - -void D3D12TextureD::update(int b) -{ - int slot = 1 << b; - if ((slot & m_validSlots) == 0) - { - m_q->stallDynamicUpload(); - ID3D12Resource* res = m_texs[b].Get(); - ID3D12Resource* gpuRes = m_gpuTexs[b].Get(); - D3D12_SUBRESOURCE_DATA d = {m_cpuBuf.get(), LONG_PTR(m_rowPitch), LONG_PTR(m_cpuSz)}; - D3D12_RESOURCE_BARRIER setupCopy[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(gpuRes, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST), - }; - m_q->m_dynamicCmdList->ResourceBarrier(1, setupCopy); - if (!UpdateSubresources<1>(m_q->m_dynamicCmdList.Get(), gpuRes, res, 0, 0, 1, &d)) - Log.report(logvisor::Fatal, "unable to update dynamic texture data"); - D3D12_RESOURCE_BARRIER teardownCopy[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(gpuRes, - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), - }; - m_q->m_dynamicCmdList->ResourceBarrier(1, teardownCopy); - m_validSlots |= slot; - } -} -void D3D12TextureD::load(const void* data, size_t sz) -{ - size_t bufSz = std::min(sz, m_cpuSz); - memcpy(m_cpuBuf.get(), data, bufSz); - m_validSlots = 0; -} -void* D3D12TextureD::map(size_t sz) -{ - if (sz > m_cpuSz) - return nullptr; - return m_cpuBuf.get(); -} -void D3D12TextureD::unmap() -{ - m_validSlots = 0; -} - -class D3D12DataFactory : public ID3DDataFactory, public GraphicsDataFactoryHead -{ - friend struct D3D12CommandQueue; - IGraphicsContext* m_parent; - struct D3D12Context* m_ctx; - std::unordered_map> m_sharedShaders; - std::unordered_map m_sourceToBinary; - - float m_gamma = 1.f; - ObjToken m_gammaShader; - ObjToken m_gammaLUT; - ObjToken m_gammaVBO; - ObjToken m_gammaVFMT; - ObjToken m_gammaBinding; - void SetupGammaResources() - { - commitTransaction([this](IGraphicsDataFactory::Context& ctx) - { - const VertexElementDescriptor vfmt[] = { - {nullptr, nullptr, VertexSemantic::Position4}, - {nullptr, nullptr, VertexSemantic::UV4} - }; - m_gammaVFMT = ctx.newVertexFormat(2, vfmt); - m_gammaShader = static_cast(ctx).newShaderPipeline(GammaVS, GammaFS, - nullptr, nullptr, nullptr, m_gammaVFMT, BlendFactor::One, BlendFactor::Zero, - Primitive::TriStrips, ZTest::None, false, true, false, CullMode::None, true); - m_gammaLUT = ctx.newDynamicTexture(256, 256, TextureFormat::I16, TextureClampMode::ClampToEdge); - setDisplayGamma(1.f); - const struct Vert { - float pos[4]; - float uv[4]; - } verts[4] = { - {{-1.f, 1.f, 0.f, 1.f}, {0.f, 0.f, 0.f, 0.f}}, - {{ 1.f, 1.f, 0.f, 1.f}, {1.f, 0.f, 0.f, 0.f}}, - {{-1.f, -1.f, 0.f, 1.f}, {0.f, 1.f, 0.f, 0.f}}, - {{ 1.f, -1.f, 0.f, 1.f}, {1.f, 1.f, 0.f, 0.f}} - }; - m_gammaVBO = ctx.newStaticBuffer(BufferUse::Vertex, verts, 32, 4); - ObjToken texs[] = {{}, m_gammaLUT.get()}; - m_gammaBinding = ctx.newShaderDataBinding(m_gammaShader, m_gammaVFMT, m_gammaVBO.get(), {}, {}, - 0, nullptr, nullptr, 2, texs, nullptr, nullptr); - return true; - }); - } - -public: - D3D12DataFactory(IGraphicsContext* parent, D3D12Context* ctx) - : m_parent(parent), m_ctx(ctx) - { - D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS qLevels = {}; - qLevels.Format = m_ctx->RGBATex2DFBViewDesc.Format; - qLevels.SampleCount = m_ctx->m_sampleCount; - while (SUCCEEDED(ctx->m_dev->CheckFeatureSupport - (D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &qLevels, sizeof(qLevels))) && - !qLevels.NumQualityLevels) - qLevels.SampleCount = flp2(qLevels.SampleCount - 1); - m_ctx->m_sampleCount = qLevels.SampleCount; - - m_ctx->m_anisotropy = std::min(m_ctx->m_anisotropy, uint32_t(16)); - - CD3DX12_DESCRIPTOR_RANGE ranges[] = - { - {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, MAX_UNIFORM_COUNT, 0}, - {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, MAX_TEXTURE_COUNT, 0} - }; - CD3DX12_ROOT_PARAMETER rootParms[1]; - rootParms[0].InitAsDescriptorTable(2, ranges); - - ComPtr rsOutBlob; - ComPtr rsErrorBlob; - - D3D12_STATIC_SAMPLER_DESC samplers[] = - { - CD3DX12_STATIC_SAMPLER_DESC(0, D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_WRAP, 0.f, m_ctx->m_anisotropy), - CD3DX12_STATIC_SAMPLER_DESC(1, D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_BORDER, - D3D12_TEXTURE_ADDRESS_MODE_BORDER, D3D12_TEXTURE_ADDRESS_MODE_BORDER, 0.f, m_ctx->m_anisotropy), - CD3DX12_STATIC_SAMPLER_DESC(2, D3D12_FILTER_ANISOTROPIC, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, 0.f, m_ctx->m_anisotropy), - CD3DX12_STATIC_SAMPLER_DESC(3, D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, 0.f, m_ctx->m_anisotropy) - }; - - ThrowIfFailed(D3D12SerializeRootSignaturePROC( - &CD3DX12_ROOT_SIGNATURE_DESC(1, rootParms, 4, samplers, - D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), - D3D_ROOT_SIGNATURE_VERSION_1, &rsOutBlob, &rsErrorBlob)); - - ThrowIfFailed(ctx->m_dev->CreateRootSignature(0, rsOutBlob->GetBufferPointer(), - rsOutBlob->GetBufferSize(), __uuidof(ID3D12RootSignature), &ctx->m_rs)); - } - - Platform platform() const {return Platform::D3D12;} - const SystemChar* platformName() const {return _S("D3D12");} - - class Context : public ID3DDataFactory::Context - { - friend class D3D12DataFactory; - D3D12DataFactory& m_parent; - boo::ObjToken m_data; - Context(D3D12DataFactory& parent) - : m_parent(parent), m_data(new D3D12Data(parent)) {} - public: - Platform platform() const {return Platform::D3D12;} - const SystemChar* platformName() const {return _S("D3D12");} - - boo::ObjToken - newStaticBuffer(BufferUse use, const void* data, size_t stride, size_t count) - { - return {new D3D12GraphicsBufferS(m_data, use, m_parent.m_ctx, data, stride, count)}; - } - - boo::ObjToken - newDynamicBuffer(BufferUse use, size_t stride, size_t count) - { - D3D12CommandQueue* q = static_cast(m_parent.m_parent->getCommandQueue()); - return {new D3D12GraphicsBufferD(m_data, q, use, m_parent.m_ctx, stride, count)}; - } - - boo::ObjToken - newStaticTexture(size_t width, size_t height, size_t mips, TextureFormat fmt, - TextureClampMode clampMode, const void* data, size_t sz) - { - return {new D3D12TextureS(m_data, m_parent.m_ctx, width, height, mips, fmt, data, sz)}; - } - - boo::ObjToken - newStaticArrayTexture(size_t width, size_t height, size_t layers, size_t mips, - TextureFormat fmt, TextureClampMode clampMode, const void* data, size_t sz) - { - return {new D3D12TextureSA(m_data, m_parent.m_ctx, width, height, layers, mips, fmt, data, sz)}; - } - - boo::ObjToken - newDynamicTexture(size_t width, size_t height, TextureFormat fmt, TextureClampMode clampMode) - { - D3D12CommandQueue* q = static_cast(m_parent.m_parent->getCommandQueue()); - return {new D3D12TextureD(m_data, q, m_parent.m_ctx, width, height, fmt)}; - } - - boo::ObjToken - newRenderTexture(size_t width, size_t height, TextureClampMode clampMode, - size_t colorBindCount, size_t depthBindCount) - { - D3D12CommandQueue* q = static_cast(m_parent.m_parent->getCommandQueue()); - return {new D3D12TextureR(m_data, m_parent.m_ctx, q, width, height, m_parent.m_ctx->m_sampleCount, - colorBindCount, depthBindCount)}; - } - - boo::ObjToken - newVertexFormat(size_t elementCount, const VertexElementDescriptor* elements, - size_t baseVert, size_t baseInst) - { - return {new struct D3D12VertexFormat(m_data, elementCount, elements)}; - } - -#if _DEBUG && 0 -#define BOO_D3DCOMPILE_FLAG D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL0 -#else -#define BOO_D3DCOMPILE_FLAG D3DCOMPILE_OPTIMIZATION_LEVEL3 -#endif - - static uint64_t CompileVert(ComPtr& vertBlobOut, const char* vertSource, uint64_t srcKey, - D3D12DataFactory& factory) - { - ComPtr errBlob; - if (FAILED(D3DCompilePROC(vertSource, strlen(vertSource), "HECL Vert Source", nullptr, nullptr, "main", - "vs_5_0", BOO_D3DCOMPILE_FLAG, 0, &vertBlobOut, &errBlob))) - { - printf("%s\n", vertSource); - Log.report(logvisor::Fatal, "error compiling vert shader: %s", errBlob->GetBufferPointer()); - } - - XXH64_state_t hashState; - XXH64_reset(&hashState, 0); - XXH64_update(&hashState, vertBlobOut->GetBufferPointer(), vertBlobOut->GetBufferSize()); - uint64_t binKey = XXH64_digest(&hashState); - factory.m_sourceToBinary[srcKey] = binKey; - return binKey; - } - - static uint64_t CompileFrag(ComPtr& fragBlobOut, const char* fragSource, uint64_t srcKey, - D3D12DataFactory& factory) - { - ComPtr errBlob; - if (FAILED(D3DCompilePROC(fragSource, strlen(fragSource), "HECL Pixel Source", nullptr, nullptr, "main", - "ps_5_0", BOO_D3DCOMPILE_FLAG, 0, &fragBlobOut, &errBlob))) - { - printf("%s\n", fragSource); - Log.report(logvisor::Fatal, "error compiling pixel shader: %s", errBlob->GetBufferPointer()); - } - - XXH64_state_t hashState; - XXH64_reset(&hashState, 0); - XXH64_update(&hashState, fragBlobOut->GetBufferPointer(), fragBlobOut->GetBufferSize()); - uint64_t binKey = XXH64_digest(&hashState); - factory.m_sourceToBinary[srcKey] = binKey; - return binKey; - } - - boo::ObjToken newShaderPipeline - (const char* vertSource, const char* fragSource, - ComPtr* vertBlobOut, ComPtr* fragBlobOut, - ComPtr* pipelineBlob, const boo::ObjToken& vtxFmt, - BlendFactor srcFac, BlendFactor dstFac, Primitive prim, - ZTest depthTest, bool depthWrite, bool colorWrite, - bool alphaWrite, CullMode culling, bool overwriteAlpha) - { - XXH64_state_t hashState; - uint64_t srcHashes[2] = {}; - uint64_t binHashes[2] = {}; - XXH64_reset(&hashState, 0); - if (vertSource) - { - XXH64_update(&hashState, vertSource, strlen(vertSource)); - srcHashes[0] = XXH64_digest(&hashState); - auto binSearch = m_parent.m_sourceToBinary.find(srcHashes[0]); - if (binSearch != m_parent.m_sourceToBinary.cend()) - binHashes[0] = binSearch->second; - } - else if (vertBlobOut && *vertBlobOut) - { - XXH64_update(&hashState, (*vertBlobOut)->GetBufferPointer(), (*vertBlobOut)->GetBufferSize()); - binHashes[0] = XXH64_digest(&hashState); - } - XXH64_reset(&hashState, 0); - if (fragSource) - { - XXH64_update(&hashState, fragSource, strlen(fragSource)); - srcHashes[1] = XXH64_digest(&hashState); - auto binSearch = m_parent.m_sourceToBinary.find(srcHashes[1]); - if (binSearch != m_parent.m_sourceToBinary.cend()) - binHashes[1] = binSearch->second; - } - else if (fragBlobOut && *fragBlobOut) - { - XXH64_update(&hashState, (*fragBlobOut)->GetBufferPointer(), (*fragBlobOut)->GetBufferSize()); - binHashes[1] = XXH64_digest(&hashState); - } - - if (vertBlobOut && !*vertBlobOut) - binHashes[0] = CompileVert(*vertBlobOut, vertSource, srcHashes[0], m_parent); - - if (fragBlobOut && !*fragBlobOut) - binHashes[1] = CompileFrag(*fragBlobOut, fragSource, srcHashes[1], m_parent); - - D3D12ShareableShader::Token vertShader; - D3D12ShareableShader::Token fragShader; - auto vertFind = binHashes[0] ? m_parent.m_sharedShaders.find(binHashes[0]) : - m_parent.m_sharedShaders.end(); - if (vertFind != m_parent.m_sharedShaders.end()) - { - vertShader = vertFind->second->lock(); - } - else - { - ComPtr vertBlob; - if (vertBlobOut) - vertBlob = *vertBlobOut; - else - binHashes[0] = CompileVert(vertBlob, vertSource, srcHashes[0], m_parent); - - auto it = - m_parent.m_sharedShaders.emplace(std::make_pair(binHashes[0], - std::make_unique(m_parent, srcHashes[0], binHashes[0], - std::move(vertBlob)))).first; - vertShader = it->second->lock(); - } - auto fragFind = binHashes[1] ? m_parent.m_sharedShaders.find(binHashes[1]) : - m_parent.m_sharedShaders.end(); - if (fragFind != m_parent.m_sharedShaders.end()) - { - fragShader = fragFind->second->lock(); - } - else - { - ComPtr fragBlob; - if (fragBlobOut) - fragBlob = *fragBlobOut; - else - binHashes[1] = CompileFrag(fragBlob, fragSource, srcHashes[1], m_parent); - - auto it = - m_parent.m_sharedShaders.emplace(std::make_pair(binHashes[1], - std::make_unique(m_parent, srcHashes[1], binHashes[1], - std::move(fragBlob)))).first; - fragShader = it->second->lock(); - } - - ID3DBlob* pipeline = pipelineBlob ? pipelineBlob->Get() : nullptr; - D3D12ShaderPipeline* retval = new D3D12ShaderPipeline( - m_data, m_parent.m_ctx, std::move(vertShader), std::move(fragShader), - pipeline, vtxFmt, srcFac, dstFac, prim, depthTest, depthWrite, colorWrite, - alphaWrite, overwriteAlpha, culling); - if (pipelineBlob && !*pipelineBlob) - retval->m_state->GetCachedBlob(&*pipelineBlob); - return retval; - } - - boo::ObjToken newShaderDataBinding( - const boo::ObjToken& pipeline, - const boo::ObjToken& vtxFormat, - const boo::ObjToken& vbuf, - const boo::ObjToken& instVbuf, - const boo::ObjToken& ibuf, - size_t ubufCount, const boo::ObjToken* ubufs, const PipelineStage* ubufStages, - const size_t* ubufOffs, const size_t* ubufSizes, - size_t texCount, const boo::ObjToken* texs, - const int* bindIdxs, const bool* bindDepth, - size_t baseVert, size_t baseInst) - { - return {new D3D12ShaderDataBinding(m_data, m_parent.m_ctx, pipeline, vbuf, instVbuf, ibuf, - ubufCount, ubufs, ubufOffs, ubufSizes, texCount, texs, - bindIdxs, bindDepth, baseVert, baseInst)}; - } - }; - - boo::ObjToken newPoolBuffer(BufferUse use, size_t stride, size_t count) - { - D3D12CommandQueue* q = static_cast(m_parent->getCommandQueue()); - boo::ObjToken pool(new D3D12Pool(*this)); - D3D12Pool* cpool = pool.cast(); - D3D12GraphicsBufferD* retval = - new D3D12GraphicsBufferD(pool, q, use, m_ctx, stride, count); - - /* Gather resource descriptions */ - D3D12_RESOURCE_DESC bufDescs[2]; - bufDescs[0] = retval->m_bufs[0]->GetDesc(); - bufDescs[1] = retval->m_bufs[1]->GetDesc(); - - /* Create heap */ - D3D12_RESOURCE_ALLOCATION_INFO bufAllocInfo = - m_ctx->m_dev->GetResourceAllocationInfo(0, 2, bufDescs); - ThrowIfFailed(m_ctx->m_dev->CreateHeap(&CD3DX12_HEAP_DESC(bufAllocInfo, - D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS), - __uuidof(ID3D12Heap), &cpool->m_bufHeap)); - - /* Place resources */ - PlaceBufferForGPU(retval, m_ctx, cpool->m_bufHeap.Get(), 0); - - return {retval}; - } - - void commitTransaction(const FactoryCommitFunc& trans) - { - D3D12DataFactory::Context ctx(*this); - if (!trans(ctx)) - return; - - D3D12Data* data = ctx.m_data.cast(); - - /* Gather resource descriptions */ - std::vector bufDescs; - bufDescs.reserve(data->countForward() + - data->countForward() * 2); - - std::vector texDescs; - texDescs.reserve(data->countForward() + - data->countForward() + - data->countForward() * 2); - - if (data->m_SBufs) - for (IGraphicsBufferS& buf : *data->m_SBufs) - bufDescs.push_back(static_cast(buf).m_gpuDesc); - - if (data->m_DBufs) - for (IGraphicsBufferD& buf : *data->m_DBufs) - { - bufDescs.push_back(static_cast&>(buf).m_bufs[0]->GetDesc()); - bufDescs.push_back(static_cast&>(buf).m_bufs[1]->GetDesc()); - } - - if (data->m_STexs) - for (ITextureS& tex : *data->m_STexs) - texDescs.push_back(static_cast(tex).m_gpuDesc); - - if (data->m_SATexs) - for (ITextureSA& tex : *data->m_SATexs) - texDescs.push_back(static_cast(tex).m_gpuDesc); - - if (data->m_DTexs) - for (ITextureD& tex : *data->m_DTexs) - { - texDescs.push_back(static_cast(tex).m_gpuDesc); - texDescs.push_back(static_cast(tex).m_gpuDesc); - } - - /* Create heap */ - if (bufDescs.size()) - { - D3D12_RESOURCE_ALLOCATION_INFO bufAllocInfo = - m_ctx->m_dev->GetResourceAllocationInfo(0, bufDescs.size(), bufDescs.data()); - ThrowIfFailed(m_ctx->m_dev->CreateHeap(&CD3DX12_HEAP_DESC(bufAllocInfo, - D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS), - __uuidof(ID3D12Heap), &data->m_bufHeap)); - } - if (texDescs.size()) - { - D3D12_RESOURCE_ALLOCATION_INFO texAllocInfo = - m_ctx->m_dev->GetResourceAllocationInfo(0, texDescs.size(), texDescs.data()); - ThrowIfFailed(m_ctx->m_dev->CreateHeap(&CD3DX12_HEAP_DESC(texAllocInfo, - D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES), - __uuidof(ID3D12Heap), &data->m_texHeap)); - } - ID3D12Heap* bufHeap = data->m_bufHeap.Get(); - ID3D12Heap* texHeap = data->m_texHeap.Get(); - - /* Place resources */ - UINT64 offsetBuf = 0; - if (data->m_SBufs) - for (IGraphicsBufferS& buf : *data->m_SBufs) - offsetBuf = PlaceBufferForGPU(&buf, m_ctx, bufHeap, offsetBuf); - - if (data->m_DBufs) - for (IGraphicsBufferD& buf : *data->m_DBufs) - offsetBuf = PlaceBufferForGPU(&buf, m_ctx, bufHeap, offsetBuf); - - UINT64 offsetTex = 0; - if (data->m_STexs) - for (ITextureS& tex : *data->m_STexs) - offsetTex = PlaceTextureForGPU(&tex, m_ctx, texHeap, offsetTex); - - if (data->m_SATexs) - for (ITextureSA& tex : *data->m_SATexs) - offsetTex = PlaceTextureForGPU(&tex, m_ctx, texHeap, offsetTex); - - if (data->m_DTexs) - for (ITextureD& tex : *data->m_DTexs) - offsetTex = PlaceTextureForGPU(&tex, m_ctx, texHeap, offsetTex); - - /* Execute static uploads */ - ThrowIfFailed(m_ctx->m_loadlist->Close()); - ID3D12CommandList* list[] = {m_ctx->m_loadlist.Get()}; - m_ctx->m_loadq->ExecuteCommandLists(1, list); - ++m_ctx->m_loadfenceval; - ThrowIfFailed(m_ctx->m_loadq->Signal(m_ctx->m_loadfence.Get(), m_ctx->m_loadfenceval)); - - /* Commit data bindings (create descriptor heaps) */ - if (data->m_SBinds) - for (IShaderDataBinding& bind : *data->m_SBinds) - static_cast(bind).commit(m_ctx); - - /* Block handle return until data is ready on GPU */ - WaitForLoadList(m_ctx); - - /* Reset allocator and list */ - ThrowIfFailed(m_ctx->m_loadqalloc->Reset()); - ThrowIfFailed(m_ctx->m_loadlist->Reset(m_ctx->m_loadqalloc.Get(), nullptr)); - - /* Delete static upload heaps */ - if (data->m_SBufs) - for (IGraphicsBufferS& buf : *data->m_SBufs) - static_cast(buf).m_buf.Reset(); - - if (data->m_STexs) - for (ITextureS& tex : *data->m_STexs) - static_cast(tex).m_tex.Reset(); - - if (data->m_SATexs) - for (ITextureSA& tex : *data->m_SATexs) - static_cast(tex).m_tex.Reset(); - } - - void _unregisterShareableShader(uint64_t srcKey, uint64_t binKey) - { - if (srcKey) - m_sourceToBinary.erase(srcKey); - m_sharedShaders.erase(binKey); - } - - void setDisplayGamma(float gamma) - { - if (m_ctx->RGBATex2DFBViewDesc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) - m_gamma = gamma * 2.2f; - else - m_gamma = gamma; - if (m_gamma != 1.f) - UpdateGammaLUT(m_gammaLUT.get(), m_gamma); - } -}; - -void D3D12CommandQueue::startRenderer() -{ - static_cast(m_parent->getDataFactory())->SetupGammaResources(); -} - -void D3D12CommandQueue::stopRenderer() -{ - m_running = false; - if (m_fence->GetCompletedValue() < m_submittedFenceVal) - { - ThrowIfFailed(m_fence->SetEventOnCompletion(m_submittedFenceVal, m_renderFenceHandle)); - WaitForSingleObject(m_renderFenceHandle, INFINITE); - } - /* - D3D12DataFactory* dataFactory = static_cast(m_parent->getDataFactory()); - dataFactory->m_gammaShader.reset(); - dataFactory->m_gammaLUT.reset(); - dataFactory->m_gammaVBO.reset(); - dataFactory->m_gammaVFMT.reset(); - dataFactory->m_gammaBinding.reset(); - */ -} - -void D3D12CommandQueue::resolveDisplay(const boo::ObjToken& source) -{ - D3D12TextureR* csource = source.cast(); -#ifndef NDEBUG - if (!csource->m_colorBindCount) - Log.report(logvisor::Fatal, - "texture provided to resolveDisplay() must have at least 1 color binding"); -#endif - - if (m_windowCtx->m_needsResize) - { - UINT nodeMasks[] = {0,0}; - IUnknown* const queues[] = {m_ctx->m_q.Get(), m_ctx->m_q.Get()}; - m_windowCtx->m_swapChain->ResizeBuffers1(2, m_windowCtx->width, m_windowCtx->height, - m_ctx->RGBATex2DFBViewDesc.Format, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH, nodeMasks, queues); - m_windowCtx->m_backBuf = m_windowCtx->m_swapChain->GetCurrentBackBufferIndex(); - m_windowCtx->m_rtvHeaps.clear(); - m_windowCtx->m_needsResize = false; - return; - } - - ComPtr dest; - ThrowIfFailed(m_windowCtx->m_swapChain->GetBuffer(m_windowCtx->m_backBuf, __uuidof(ID3D12Resource), &dest)); - - ID3D12Resource* src = csource->m_colorTex.Get(); - D3D12_RESOURCE_STATES srcState = D3D12_RESOURCE_STATE_COPY_SOURCE; - if (m_boundTarget.get() == csource) - srcState = D3D12_RESOURCE_STATE_RENDER_TARGET; - - D3D12DataFactory* dataFactory = static_cast(m_parent->getDataFactory()); - if (dataFactory->m_gamma != 1.f) - { - SWindowRect rect(0, 0, csource->m_width, csource->m_height); - resolveBindTexture(source, rect, true, 0, true, false, false); - - auto search = m_windowCtx->m_rtvHeaps.find(dest.Get()); - if (search == m_windowCtx->m_rtvHeaps.end()) - { - ComPtr rtvHeap; - D3D12_DESCRIPTOR_HEAP_DESC rtvdesc = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - ThrowIfFailed(m_ctx->m_dev->CreateDescriptorHeap(&rtvdesc, __uuidof(ID3D12DescriptorHeap), &rtvHeap)); - - D3D12_RENDER_TARGET_VIEW_DESC rtvvdesc = {m_ctx->RGBATex2DFBViewDesc.Format, D3D12_RTV_DIMENSION_TEXTURE2D}; - m_ctx->m_dev->CreateRenderTargetView(dest.Get(), &rtvvdesc, rtvHeap->GetCPUDescriptorHandleForHeapStart()); - - search = m_windowCtx->m_rtvHeaps.insert(std::make_pair(dest.Get(), rtvHeap)).first; - } - - D3D12_RESOURCE_BARRIER gammaSetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET) - }; - m_cmdList->ResourceBarrier(1, gammaSetup); - - m_cmdList->OMSetRenderTargets(1, &search->second->GetCPUDescriptorHandleForHeapStart(), false, nullptr); - - D3D12ShaderDataBinding* gammaBinding = dataFactory->m_gammaBinding.cast(); - gammaBinding->m_texs[0].tex = source.get(); - gammaBinding->bind(m_ctx, m_cmdList.Get(), m_fillBuf); - m_cmdList->DrawInstanced(4, 1, 0, 0); - gammaBinding->m_texs[0].tex.reset(); - - D3D12_RESOURCE_BARRIER gammaTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT) - }; - m_cmdList->ResourceBarrier(1, gammaTeardown); - } - else - { - if (csource->m_samples > 1) - { - D3D12_RESOURCE_BARRIER msaaSetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(src, - srcState, D3D12_RESOURCE_STATE_RESOLVE_SOURCE), - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RESOLVE_DEST) - }; - m_cmdList->ResourceBarrier(2, msaaSetup); - - m_cmdList->ResolveSubresource(dest.Get(), 0, src, 0, m_ctx->RGBATex2DFBViewDesc.Format); - - D3D12_RESOURCE_BARRIER msaaTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(src, - D3D12_RESOURCE_STATE_RESOLVE_SOURCE, srcState), - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_PRESENT) - }; - m_cmdList->ResourceBarrier(2, msaaTeardown); - } - else - { - if (srcState != D3D12_RESOURCE_STATE_COPY_SOURCE) - { - D3D12_RESOURCE_BARRIER copySetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(src, - srcState, D3D12_RESOURCE_STATE_COPY_SOURCE), - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST) - }; - m_cmdList->ResourceBarrier(2, copySetup); - } - else - { - D3D12_RESOURCE_BARRIER copySetup[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST) - }; - m_cmdList->ResourceBarrier(1, copySetup); - } - - m_cmdList->CopyResource(dest.Get(), src); - - if (srcState != D3D12_RESOURCE_STATE_COPY_SOURCE) - { - D3D12_RESOURCE_BARRIER copyTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(src, - D3D12_RESOURCE_STATE_COPY_SOURCE, srcState), - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT) - }; - m_cmdList->ResourceBarrier(2, copyTeardown); - } - else - { - D3D12_RESOURCE_BARRIER copyTeardown[] = - { - CD3DX12_RESOURCE_BARRIER::Transition(dest.Get(), - D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT) - }; - m_cmdList->ResourceBarrier(1, copyTeardown); - } - } - } - - m_doPresent = true; -} - -void D3D12CommandQueue::execute() -{ - if (!m_running) - return; - - /* Stage dynamic uploads */ - D3D12DataFactory* gfxF = static_cast(m_parent->getDataFactory()); - std::unique_lock datalk(gfxF->m_dataMutex); - if (gfxF->m_dataHead) - { - for (BaseGraphicsData& d : *gfxF->m_dataHead) - { - if (d.m_DBufs) - for (IGraphicsBufferD& b : *d.m_DBufs) - static_cast&>(b).update(m_fillBuf); - if (d.m_DTexs) - for (ITextureD& t : *d.m_DTexs) - static_cast(t).update(m_fillBuf); - } - } - if (gfxF->m_poolHead) - { - for (BaseGraphicsPool& p : *gfxF->m_poolHead) - { - if (p.m_DBufs) - for (IGraphicsBufferD& b : *p.m_DBufs) - static_cast&>(b).update(m_fillBuf); - } - } - datalk.unlock(); - - /* Perform dynamic uploads */ - if (!m_dynamicNeedsReset) - { - m_dynamicCmdList->Close(); - ID3D12CommandList* dcl[] = {m_dynamicCmdList.Get()}; - m_ctx->m_q->ExecuteCommandLists(1, dcl); - ++m_dynamicBufFenceVal; - ThrowIfFailed(m_ctx->m_q->Signal(m_dynamicBufFence.Get(), m_dynamicBufFenceVal)); - } - - /* Check on fence */ - if (m_fence->GetCompletedValue() < m_submittedFenceVal) - { - /* Abandon this list (renderer too slow) */ - m_cmdList->Close(); - resetCommandList(); - m_dynamicNeedsReset = true; - m_doPresent = false; - return; - } - - /* Perform texture resizes */ - if (m_texResizes.size()) - { - for (const auto& resize : m_texResizes) - resize.first->resize(m_ctx, resize.second.first, resize.second.second); - m_texResizes.clear(); - m_cmdList->Close(); - resetCommandList(); - m_dynamicNeedsReset = true; - m_doPresent = false; - return; - } - - m_drawBuf = m_fillBuf; - m_fillBuf ^= 1; - - m_cmdList->Close(); - ID3D12CommandList* cl[] = {m_cmdList.Get()}; - m_ctx->m_q->ExecuteCommandLists(1, cl); - - if (m_doPresent) - { - ThrowIfFailed(m_windowCtx->m_swapChain->Present(1, 0)); - m_windowCtx->m_backBuf = m_windowCtx->m_swapChain->GetCurrentBackBufferIndex(); - m_doPresent = false; - } - - ++m_submittedFenceVal; - ThrowIfFailed(m_ctx->m_q->Signal(m_fence.Get(), m_submittedFenceVal)); - - resetCommandList(); - resetDynamicCommandList(); -} - -IGraphicsCommandQueue* _NewD3D12CommandQueue(D3D12Context* ctx, D3D12Context::Window* windowCtx, IGraphicsContext* parent, - ID3D12CommandQueue** cmdQueueOut) -{ - return new struct D3D12CommandQueue(ctx, windowCtx, parent, cmdQueueOut); -} - -IGraphicsDataFactory* _NewD3D12DataFactory(D3D12Context* ctx, IGraphicsContext* parent) -{ - return new D3D12DataFactory(parent, ctx); -} - -} - -#endif // _WIN32_WINNT_WIN10 diff --git a/lib/graphicsdev/GL.cpp b/lib/graphicsdev/GL.cpp index 3129bdc..b10e563 100644 --- a/lib/graphicsdev/GL.cpp +++ b/lib/graphicsdev/GL.cpp @@ -83,7 +83,7 @@ class GLDataFactoryImpl : public GLDataFactory, public GraphicsDataFactoryHead ObjToken m_gammaVFMT; void SetupGammaResources() { - BooCommitTransaction([this](IGraphicsDataFactory::Context& ctx) + commitTransaction([this](IGraphicsDataFactory::Context& ctx) { const char* texNames[] = {"screenTex", "gammaLUT"}; m_gammaShader = static_cast(ctx).newShaderPipeline(GammaVS, GammaFS, @@ -106,7 +106,7 @@ class GLDataFactoryImpl : public GLDataFactory, public GraphicsDataFactoryHead }; m_gammaVFMT = ctx.newVertexFormat(2, vfmt); return true; - }); + } BooTrace); } public: @@ -390,8 +390,8 @@ class GLTextureSA : public GraphicsDataNode SetClampMode(GL_TEXTURE_2D_ARRAY, clampMode); - GLenum intFormat, format; - int pxPitch; + GLenum intFormat = 0, format = 0; + int pxPitch = 0; switch (fmt) { case TextureFormat::RGBA8: diff --git a/lib/graphicsdev/Vulkan.cpp b/lib/graphicsdev/Vulkan.cpp index ed92793..6910512 100644 --- a/lib/graphicsdev/Vulkan.cpp +++ b/lib/graphicsdev/Vulkan.cpp @@ -96,7 +96,7 @@ class VulkanDataFactoryImpl : public VulkanDataFactory, public GraphicsDataFacto ObjToken m_gammaBinding; void SetupGammaResources() { - BooCommitTransaction([this](IGraphicsDataFactory::Context& ctx) + commitTransaction([this](IGraphicsDataFactory::Context& ctx) { const VertexElementDescriptor vfmt[] = { {nullptr, nullptr, VertexSemantic::Position4}, @@ -122,7 +122,7 @@ class VulkanDataFactoryImpl : public VulkanDataFactory, public GraphicsDataFacto m_gammaBinding = ctx.newShaderDataBinding(m_gammaShader, m_gammaVFMT, m_gammaVBO.get(), {}, {}, 0, nullptr, nullptr, 2, texs, nullptr, nullptr); return true; - }); + } BooTrace); } void DestroyGammaResources() diff --git a/lib/graphicsdev/d3dx12.h b/lib/graphicsdev/d3dx12.h deleted file mode 100644 index e133b8c..0000000 --- a/lib/graphicsdev/d3dx12.h +++ /dev/null @@ -1,1705 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the MIT License (MIT). -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -// (UpdateSubresources-related additions and alterations for boo) -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef __D3DX12_H__ -#define __D3DX12_H__ - -#include "d3d12.h" - -#if defined( __cplusplus ) - -struct CD3DX12_DEFAULT {}; -extern const DECLSPEC_SELECTANY CD3DX12_DEFAULT D3D12_DEFAULT; - -//------------------------------------------------------------------------------------------------ -inline bool operator==( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) -{ - return l.TopLeftX == r.TopLeftX && l.TopLeftY == r.TopLeftY && l.Width == r.Width && - l.Height == r.Height && l.MinDepth == r.MinDepth && l.MaxDepth == r.MaxDepth; -} - -//------------------------------------------------------------------------------------------------ -inline bool operator!=( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) -{ return !( l == r ); } - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RECT : public D3D12_RECT -{ - CD3DX12_RECT() - {} - explicit CD3DX12_RECT( const D3D12_RECT& o ) : - D3D12_RECT( o ) - {} - explicit CD3DX12_RECT( - LONG Left, - LONG Top, - LONG Right, - LONG Bottom ) - { - left = Left; - top = Top; - right = Right; - bottom = Bottom; - } - ~CD3DX12_RECT() {} - operator const D3D12_RECT&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_BOX : public D3D12_BOX -{ - CD3DX12_BOX() - {} - explicit CD3DX12_BOX( const D3D12_BOX& o ) : - D3D12_BOX( o ) - {} - explicit CD3DX12_BOX( - LONG Left, - LONG Right ) - { - left = Left; - top = 0; - front = 0; - right = Right; - bottom = 1; - back = 1; - } - explicit CD3DX12_BOX( - LONG Left, - LONG Top, - LONG Right, - LONG Bottom ) - { - left = Left; - top = Top; - front = 0; - right = Right; - bottom = Bottom; - back = 1; - } - explicit CD3DX12_BOX( - LONG Left, - LONG Top, - LONG Front, - LONG Right, - LONG Bottom, - LONG Back ) - { - left = Left; - top = Top; - front = Front; - right = Right; - bottom = Bottom; - back = Back; - } - ~CD3DX12_BOX() {} - operator const D3D12_BOX&() const { return *this; } -}; -inline bool operator==( const D3D12_BOX& l, const D3D12_BOX& r ) -{ - return l.left == r.left && l.top == r.top && l.front == r.front && - l.right == r.right && l.bottom == r.bottom && l.back == r.back; -} -inline bool operator!=( const D3D12_BOX& l, const D3D12_BOX& r ) -{ return !( l == r ); } - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC -{ - CD3DX12_DEPTH_STENCIL_DESC() - {} - explicit CD3DX12_DEPTH_STENCIL_DESC( const D3D12_DEPTH_STENCIL_DESC& o ) : - D3D12_DEPTH_STENCIL_DESC( o ) - {} - explicit CD3DX12_DEPTH_STENCIL_DESC( CD3DX12_DEFAULT ) - { - DepthEnable = TRUE; - DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; - DepthFunc = D3D12_COMPARISON_FUNC_LESS; - StencilEnable = FALSE; - StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; - StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; - const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = - { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS }; - FrontFace = defaultStencilOp; - BackFace = defaultStencilOp; - } - explicit CD3DX12_DEPTH_STENCIL_DESC( - BOOL depthEnable, - D3D12_DEPTH_WRITE_MASK depthWriteMask, - D3D12_COMPARISON_FUNC depthFunc, - BOOL stencilEnable, - UINT8 stencilReadMask, - UINT8 stencilWriteMask, - D3D12_STENCIL_OP frontStencilFailOp, - D3D12_STENCIL_OP frontStencilDepthFailOp, - D3D12_STENCIL_OP frontStencilPassOp, - D3D12_COMPARISON_FUNC frontStencilFunc, - D3D12_STENCIL_OP backStencilFailOp, - D3D12_STENCIL_OP backStencilDepthFailOp, - D3D12_STENCIL_OP backStencilPassOp, - D3D12_COMPARISON_FUNC backStencilFunc ) - { - DepthEnable = depthEnable; - DepthWriteMask = depthWriteMask; - DepthFunc = depthFunc; - StencilEnable = stencilEnable; - StencilReadMask = stencilReadMask; - StencilWriteMask = stencilWriteMask; - FrontFace.StencilFailOp = frontStencilFailOp; - FrontFace.StencilDepthFailOp = frontStencilDepthFailOp; - FrontFace.StencilPassOp = frontStencilPassOp; - FrontFace.StencilFunc = frontStencilFunc; - BackFace.StencilFailOp = backStencilFailOp; - BackFace.StencilDepthFailOp = backStencilDepthFailOp; - BackFace.StencilPassOp = backStencilPassOp; - BackFace.StencilFunc = backStencilFunc; - } - ~CD3DX12_DEPTH_STENCIL_DESC() {} - operator const D3D12_DEPTH_STENCIL_DESC&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC -{ - CD3DX12_BLEND_DESC() - {} - explicit CD3DX12_BLEND_DESC( const D3D12_BLEND_DESC& o ) : - D3D12_BLEND_DESC( o ) - {} - explicit CD3DX12_BLEND_DESC( CD3DX12_DEFAULT ) - { - AlphaToCoverageEnable = FALSE; - IndependentBlendEnable = FALSE; - const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = - { - FALSE,FALSE, - D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, - D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, - D3D12_LOGIC_OP_NOOP, - D3D12_COLOR_WRITE_ENABLE_ALL, - }; - for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) - RenderTarget[ i ] = defaultRenderTargetBlendDesc; - } - ~CD3DX12_BLEND_DESC() {} - operator const D3D12_BLEND_DESC&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC -{ - CD3DX12_RASTERIZER_DESC() - {} - explicit CD3DX12_RASTERIZER_DESC( const D3D12_RASTERIZER_DESC& o ) : - D3D12_RASTERIZER_DESC( o ) - {} - explicit CD3DX12_RASTERIZER_DESC( CD3DX12_DEFAULT ) - { - FillMode = D3D12_FILL_MODE_SOLID; - CullMode = D3D12_CULL_MODE_BACK; - FrontCounterClockwise = FALSE; - DepthBias = D3D12_DEFAULT_DEPTH_BIAS; - DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; - SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; - DepthClipEnable = TRUE; - MultisampleEnable = FALSE; - AntialiasedLineEnable = FALSE; - ForcedSampleCount = 0; - ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - } - explicit CD3DX12_RASTERIZER_DESC( - D3D12_FILL_MODE fillMode, - D3D12_CULL_MODE cullMode, - BOOL frontCounterClockwise, - INT depthBias, - FLOAT depthBiasClamp, - FLOAT slopeScaledDepthBias, - BOOL depthClipEnable, - BOOL multisampleEnable, - BOOL antialiasedLineEnable, - UINT forcedSampleCount, - D3D12_CONSERVATIVE_RASTERIZATION_MODE conservativeRaster) - { - FillMode = fillMode; - CullMode = cullMode; - FrontCounterClockwise = frontCounterClockwise; - DepthBias = depthBias; - DepthBiasClamp = depthBiasClamp; - SlopeScaledDepthBias = slopeScaledDepthBias; - DepthClipEnable = depthClipEnable; - MultisampleEnable = multisampleEnable; - AntialiasedLineEnable = antialiasedLineEnable; - ForcedSampleCount = forcedSampleCount; - ConservativeRaster = conservativeRaster; - } - ~CD3DX12_RASTERIZER_DESC() {} - operator const D3D12_RASTERIZER_DESC&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RESOURCE_ALLOCATION_INFO : public D3D12_RESOURCE_ALLOCATION_INFO -{ - CD3DX12_RESOURCE_ALLOCATION_INFO() - {} - explicit CD3DX12_RESOURCE_ALLOCATION_INFO( const D3D12_RESOURCE_ALLOCATION_INFO& o ) : - D3D12_RESOURCE_ALLOCATION_INFO( o ) - {} - CD3DX12_RESOURCE_ALLOCATION_INFO( - UINT64 size, - UINT64 alignment ) - { - SizeInBytes = size; - Alignment = alignment; - } - operator const D3D12_RESOURCE_ALLOCATION_INFO&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_HEAP_PROPERTIES : public D3D12_HEAP_PROPERTIES -{ - CD3DX12_HEAP_PROPERTIES() - {} - explicit CD3DX12_HEAP_PROPERTIES(const D3D12_HEAP_PROPERTIES &o) : - D3D12_HEAP_PROPERTIES(o) - {} - CD3DX12_HEAP_PROPERTIES( - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - UINT creationNodeMask = 1, - UINT nodeMask = 1 ) - { - Type = D3D12_HEAP_TYPE_CUSTOM; - CPUPageProperty = cpuPageProperty; - MemoryPoolPreference = memoryPoolPreference; - CreationNodeMask = creationNodeMask; - VisibleNodeMask = nodeMask; - } - explicit CD3DX12_HEAP_PROPERTIES( - D3D12_HEAP_TYPE type, - UINT creationNodeMask = 1, - UINT nodeMask = 1 ) - { - Type = type; - CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - CreationNodeMask = creationNodeMask; - VisibleNodeMask = nodeMask; - } - operator const D3D12_HEAP_PROPERTIES&() const { return *this; } - bool IsCPUAccessible() const - { - return Type == D3D12_HEAP_TYPE_UPLOAD || Type == D3D12_HEAP_TYPE_READBACK || (Type == D3D12_HEAP_TYPE_CUSTOM && - (CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE || CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); - } -}; -inline bool operator==( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) -{ - return l.Type == r.Type && l.CPUPageProperty == r.CPUPageProperty && - l.MemoryPoolPreference == r.MemoryPoolPreference && - l.CreationNodeMask == r.CreationNodeMask && - l.VisibleNodeMask == r.VisibleNodeMask; -} -inline bool operator!=( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) -{ return !( l == r ); } - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_HEAP_DESC : public D3D12_HEAP_DESC -{ - CD3DX12_HEAP_DESC() - {} - explicit CD3DX12_HEAP_DESC(const D3D12_HEAP_DESC &o) : - D3D12_HEAP_DESC(o) - {} - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_HEAP_PROPERTIES properties, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = size; - Properties = properties; - Alignment = alignment; - Flags = flags; - } - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_HEAP_TYPE type, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = size; - Properties = CD3DX12_HEAP_PROPERTIES( type ); - Alignment = alignment; - Flags = flags; - } - CD3DX12_HEAP_DESC( - UINT64 size, - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - UINT64 alignment = 0, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = size; - Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); - Alignment = alignment; - Flags = flags; - } - CD3DX12_HEAP_DESC( - const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_HEAP_PROPERTIES properties, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = resAllocInfo.SizeInBytes; - Properties = properties; - Alignment = resAllocInfo.Alignment; - Flags = flags; - } - CD3DX12_HEAP_DESC( - const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_HEAP_TYPE type, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = resAllocInfo.SizeInBytes; - Properties = CD3DX12_HEAP_PROPERTIES( type ); - Alignment = resAllocInfo.Alignment; - Flags = flags; - } - CD3DX12_HEAP_DESC( - const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_CPU_PAGE_PROPERTY cpuPageProperty, - D3D12_MEMORY_POOL memoryPoolPreference, - D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) - { - SizeInBytes = resAllocInfo.SizeInBytes; - Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); - Alignment = resAllocInfo.Alignment; - Flags = flags; - } - operator const D3D12_HEAP_DESC&() const { return *this; } - bool IsCPUAccessible() const - { return static_cast< const CD3DX12_HEAP_PROPERTIES* >( &Properties )->IsCPUAccessible(); } -}; -inline bool operator==( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) -{ - return l.SizeInBytes == r.SizeInBytes && - l.Properties == r.Properties && - l.Alignment == r.Alignment && - l.Flags == r.Flags; -} -inline bool operator!=( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) -{ return !( l == r ); } - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_CLEAR_VALUE : public D3D12_CLEAR_VALUE -{ - CD3DX12_CLEAR_VALUE() - {} - explicit CD3DX12_CLEAR_VALUE(const D3D12_CLEAR_VALUE &o) : - D3D12_CLEAR_VALUE(o) - {} - CD3DX12_CLEAR_VALUE( - DXGI_FORMAT format, - const FLOAT color[4] ) - { - Format = format; - memcpy( Color, color, sizeof( Color ) ); - } - CD3DX12_CLEAR_VALUE( - DXGI_FORMAT format, - FLOAT depth, - UINT8 stencil ) - { - Format = format; - /* Use memcpy to preserve NAN values */ - memcpy( &DepthStencil.Depth, &depth, sizeof( depth ) ); - DepthStencil.Stencil = stencil; - } - operator const D3D12_CLEAR_VALUE&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RANGE : public D3D12_RANGE -{ - CD3DX12_RANGE() - {} - explicit CD3DX12_RANGE(const D3D12_RANGE &o) : - D3D12_RANGE(o) - {} - CD3DX12_RANGE( - SIZE_T begin, - SIZE_T end ) - { - Begin = begin; - End = end; - } - operator const D3D12_RANGE&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_TILED_RESOURCE_COORDINATE : public D3D12_TILED_RESOURCE_COORDINATE -{ - CD3DX12_TILED_RESOURCE_COORDINATE() - {} - explicit CD3DX12_TILED_RESOURCE_COORDINATE(const D3D12_TILED_RESOURCE_COORDINATE &o) : - D3D12_TILED_RESOURCE_COORDINATE(o) - {} - CD3DX12_TILED_RESOURCE_COORDINATE( - UINT x, - UINT y, - UINT z, - UINT subresource ) - { - X = x; - Y = y; - Z = z; - Subresource = subresource; - } - operator const D3D12_TILED_RESOURCE_COORDINATE&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_TILE_REGION_SIZE : public D3D12_TILE_REGION_SIZE -{ - CD3DX12_TILE_REGION_SIZE() - {} - explicit CD3DX12_TILE_REGION_SIZE(const D3D12_TILE_REGION_SIZE &o) : - D3D12_TILE_REGION_SIZE(o) - {} - CD3DX12_TILE_REGION_SIZE( - UINT numTiles, - BOOL useBox, - UINT width, - UINT16 height, - UINT16 depth ) - { - NumTiles = numTiles; - UseBox = useBox; - Width = width; - Height = height; - Depth = depth; - } - operator const D3D12_TILE_REGION_SIZE&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_SUBRESOURCE_TILING : public D3D12_SUBRESOURCE_TILING -{ - CD3DX12_SUBRESOURCE_TILING() - {} - explicit CD3DX12_SUBRESOURCE_TILING(const D3D12_SUBRESOURCE_TILING &o) : - D3D12_SUBRESOURCE_TILING(o) - {} - CD3DX12_SUBRESOURCE_TILING( - UINT widthInTiles, - UINT16 heightInTiles, - UINT16 depthInTiles, - UINT startTileIndexInOverallResource ) - { - WidthInTiles = widthInTiles; - HeightInTiles = heightInTiles; - DepthInTiles = depthInTiles; - StartTileIndexInOverallResource = startTileIndexInOverallResource; - } - operator const D3D12_SUBRESOURCE_TILING&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_TILE_SHAPE : public D3D12_TILE_SHAPE -{ - CD3DX12_TILE_SHAPE() - {} - explicit CD3DX12_TILE_SHAPE(const D3D12_TILE_SHAPE &o) : - D3D12_TILE_SHAPE(o) - {} - CD3DX12_TILE_SHAPE( - UINT widthInTexels, - UINT heightInTexels, - UINT depthInTexels ) - { - WidthInTexels = widthInTexels; - HeightInTexels = heightInTexels; - DepthInTexels = depthInTexels; - } - operator const D3D12_TILE_SHAPE&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER -{ - CD3DX12_RESOURCE_BARRIER() - {} - explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER &o) : - D3D12_RESOURCE_BARRIER(o) - {} - static inline CD3DX12_RESOURCE_BARRIER Transition( - _In_ ID3D12Resource* pResource, - D3D12_RESOURCE_STATES stateBefore, - D3D12_RESOURCE_STATES stateAfter, - UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) - { - CD3DX12_RESOURCE_BARRIER result; - ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - result.Flags = flags; - barrier.Transition.pResource = pResource; - barrier.Transition.StateBefore = stateBefore; - barrier.Transition.StateAfter = stateAfter; - barrier.Transition.Subresource = subresource; - return result; - } - static inline CD3DX12_RESOURCE_BARRIER Aliasing( - _In_ ID3D12Resource* pResourceBefore, - _In_ ID3D12Resource* pResourceAfter) - { - CD3DX12_RESOURCE_BARRIER result; - ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; - barrier.Aliasing.pResourceBefore = pResourceBefore; - barrier.Aliasing.pResourceAfter = pResourceAfter; - return result; - } - static inline CD3DX12_RESOURCE_BARRIER UAV( - _In_ ID3D12Resource* pResource) - { - CD3DX12_RESOURCE_BARRIER result; - ZeroMemory(&result, sizeof(result)); - D3D12_RESOURCE_BARRIER &barrier = result; - result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - barrier.UAV.pResource = pResource; - return result; - } - operator const D3D12_RESOURCE_BARRIER&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_PACKED_MIP_INFO : public D3D12_PACKED_MIP_INFO -{ - CD3DX12_PACKED_MIP_INFO() - {} - explicit CD3DX12_PACKED_MIP_INFO(const D3D12_PACKED_MIP_INFO &o) : - D3D12_PACKED_MIP_INFO(o) - {} - CD3DX12_PACKED_MIP_INFO( - UINT8 numStandardMips, - UINT8 numPackedMips, - UINT numTilesForPackedMips, - UINT startTileIndexInOverallResource ) - { - NumStandardMips = numStandardMips; - NumPackedMips = numPackedMips; - NumTilesForPackedMips = numTilesForPackedMips; - StartTileIndexInOverallResource = startTileIndexInOverallResource; - } - operator const D3D12_PACKED_MIP_INFO&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_SUBRESOURCE_FOOTPRINT : public D3D12_SUBRESOURCE_FOOTPRINT -{ - CD3DX12_SUBRESOURCE_FOOTPRINT() - {} - explicit CD3DX12_SUBRESOURCE_FOOTPRINT(const D3D12_SUBRESOURCE_FOOTPRINT &o) : - D3D12_SUBRESOURCE_FOOTPRINT(o) - {} - CD3DX12_SUBRESOURCE_FOOTPRINT( - DXGI_FORMAT format, - UINT width, - UINT height, - UINT depth, - UINT rowPitch ) - { - Format = format; - Width = width; - Height = height; - Depth = depth; - RowPitch = rowPitch; - } - explicit CD3DX12_SUBRESOURCE_FOOTPRINT( - const D3D12_RESOURCE_DESC& resDesc, - UINT rowPitch ) - { - Format = resDesc.Format; - Width = UINT( resDesc.Width ); - Height = resDesc.Height; - Depth = (resDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? resDesc.DepthOrArraySize : 1); - RowPitch = rowPitch; - } - operator const D3D12_SUBRESOURCE_FOOTPRINT&() const { return *this; } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_TEXTURE_COPY_LOCATION : public D3D12_TEXTURE_COPY_LOCATION -{ - CD3DX12_TEXTURE_COPY_LOCATION() - {} - explicit CD3DX12_TEXTURE_COPY_LOCATION(const D3D12_TEXTURE_COPY_LOCATION &o) : - D3D12_TEXTURE_COPY_LOCATION(o) - {} - CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes) { pResource = pRes; } - CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, D3D12_PLACED_SUBRESOURCE_FOOTPRINT const& Footprint) - { - pResource = pRes; - Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - PlacedFootprint = Footprint; - } - CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, UINT Sub) - { - pResource = pRes; - Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - SubresourceIndex = Sub; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_DESCRIPTOR_RANGE : public D3D12_DESCRIPTOR_RANGE -{ - CD3DX12_DESCRIPTOR_RANGE() { } - explicit CD3DX12_DESCRIPTOR_RANGE(const D3D12_DESCRIPTOR_RANGE &o) : - D3D12_DESCRIPTOR_RANGE(o) - {} - CD3DX12_DESCRIPTOR_RANGE( - D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) - { - Init(rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); - } - - inline void Init( - D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) - { - Init(*this, rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); - } - - static inline void Init( - _Out_ D3D12_DESCRIPTOR_RANGE &range, - D3D12_DESCRIPTOR_RANGE_TYPE rangeType, - UINT numDescriptors, - UINT baseShaderRegister, - UINT registerSpace = 0, - UINT offsetInDescriptorsFromTableStart = - D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) - { - range.RangeType = rangeType; - range.NumDescriptors = numDescriptors; - range.BaseShaderRegister = baseShaderRegister; - range.RegisterSpace = registerSpace; - range.OffsetInDescriptorsFromTableStart = offsetInDescriptorsFromTableStart; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_ROOT_DESCRIPTOR_TABLE : public D3D12_ROOT_DESCRIPTOR_TABLE -{ - CD3DX12_ROOT_DESCRIPTOR_TABLE() {} - explicit CD3DX12_ROOT_DESCRIPTOR_TABLE(const D3D12_ROOT_DESCRIPTOR_TABLE &o) : - D3D12_ROOT_DESCRIPTOR_TABLE(o) - {} - CD3DX12_ROOT_DESCRIPTOR_TABLE( - UINT numDescriptorRanges, - _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) - { - Init(numDescriptorRanges, _pDescriptorRanges); - } - - inline void Init( - UINT numDescriptorRanges, - _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) - { - Init(*this, numDescriptorRanges, _pDescriptorRanges); - } - - static inline void Init( - _Out_ D3D12_ROOT_DESCRIPTOR_TABLE &rootDescriptorTable, - UINT numDescriptorRanges, - _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) - { - rootDescriptorTable.NumDescriptorRanges = numDescriptorRanges; - rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS -{ - CD3DX12_ROOT_CONSTANTS() {} - explicit CD3DX12_ROOT_CONSTANTS(const D3D12_ROOT_CONSTANTS &o) : - D3D12_ROOT_CONSTANTS(o) - {} - CD3DX12_ROOT_CONSTANTS( - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0) - { - Init(num32BitValues, shaderRegister, registerSpace); - } - - inline void Init( - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0) - { - Init(*this, num32BitValues, shaderRegister, registerSpace); - } - - static inline void Init( - _Out_ D3D12_ROOT_CONSTANTS &rootConstants, - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0) - { - rootConstants.Num32BitValues = num32BitValues; - rootConstants.ShaderRegister = shaderRegister; - rootConstants.RegisterSpace = registerSpace; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR -{ - CD3DX12_ROOT_DESCRIPTOR() {} - explicit CD3DX12_ROOT_DESCRIPTOR(const D3D12_ROOT_DESCRIPTOR &o) : - D3D12_ROOT_DESCRIPTOR(o) - {} - CD3DX12_ROOT_DESCRIPTOR( - UINT shaderRegister, - UINT registerSpace = 0) - { - Init(shaderRegister, registerSpace); - } - - inline void Init( - UINT shaderRegister, - UINT registerSpace = 0) - { - Init(*this, shaderRegister, registerSpace); - } - - static inline void Init(_Out_ D3D12_ROOT_DESCRIPTOR &table, UINT shaderRegister, UINT registerSpace = 0) - { - table.ShaderRegister = shaderRegister; - table.RegisterSpace = registerSpace; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_ROOT_PARAMETER : public D3D12_ROOT_PARAMETER -{ - CD3DX12_ROOT_PARAMETER() {} - explicit CD3DX12_ROOT_PARAMETER(const D3D12_ROOT_PARAMETER &o) : - D3D12_ROOT_PARAMETER(o) - {} - - static inline void InitAsDescriptorTable( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT numDescriptorRanges, - _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParam.ShaderVisibility = visibility; - CD3DX12_ROOT_DESCRIPTOR_TABLE::Init(rootParam.DescriptorTable, numDescriptorRanges, pDescriptorRanges); - } - - static inline void InitAsConstants( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - rootParam.ShaderVisibility = visibility; - CD3DX12_ROOT_CONSTANTS::Init(rootParam.Constants, num32BitValues, shaderRegister, registerSpace); - } - - static inline void InitAsConstantBufferView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParam.ShaderVisibility = visibility; - CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); - } - - static inline void InitAsShaderResourceView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; - rootParam.ShaderVisibility = visibility; - CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); - } - - static inline void InitAsUnorderedAccessView( - _Out_ D3D12_ROOT_PARAMETER &rootParam, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - rootParam.ShaderVisibility = visibility; - CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); - } - - inline void InitAsDescriptorTable( - UINT numDescriptorRanges, - _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - InitAsDescriptorTable(*this, numDescriptorRanges, pDescriptorRanges, visibility); - } - - inline void InitAsConstants( - UINT num32BitValues, - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - InitAsConstants(*this, num32BitValues, shaderRegister, registerSpace, visibility); - } - - inline void InitAsConstantBufferView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - InitAsConstantBufferView(*this, shaderRegister, registerSpace, visibility); - } - - inline void InitAsShaderResourceView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - InitAsShaderResourceView(*this, shaderRegister, registerSpace, visibility); - } - - inline void InitAsUnorderedAccessView( - UINT shaderRegister, - UINT registerSpace = 0, - D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) - { - InitAsUnorderedAccessView(*this, shaderRegister, registerSpace, visibility); - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_STATIC_SAMPLER_DESC : public D3D12_STATIC_SAMPLER_DESC -{ - CD3DX12_STATIC_SAMPLER_DESC() {} - explicit CD3DX12_STATIC_SAMPLER_DESC(const D3D12_STATIC_SAMPLER_DESC &o) : - D3D12_STATIC_SAMPLER_DESC(o) - {} - CD3DX12_STATIC_SAMPLER_DESC( - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) - { - Init( - shaderRegister, - filter, - addressU, - addressV, - addressW, - mipLODBias, - maxAnisotropy, - comparisonFunc, - borderColor, - minLOD, - maxLOD, - shaderVisibility, - registerSpace); - } - - static inline void Init( - _Out_ D3D12_STATIC_SAMPLER_DESC &samplerDesc, - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) - { - samplerDesc.ShaderRegister = shaderRegister; - samplerDesc.Filter = filter; - samplerDesc.AddressU = addressU; - samplerDesc.AddressV = addressV; - samplerDesc.AddressW = addressW; - samplerDesc.MipLODBias = mipLODBias; - samplerDesc.MaxAnisotropy = maxAnisotropy; - samplerDesc.ComparisonFunc = comparisonFunc; - samplerDesc.BorderColor = borderColor; - samplerDesc.MinLOD = minLOD; - samplerDesc.MaxLOD = maxLOD; - samplerDesc.ShaderVisibility = shaderVisibility; - samplerDesc.RegisterSpace = registerSpace; - } - inline void Init( - UINT shaderRegister, - D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, - D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, - FLOAT mipLODBias = 0, - UINT maxAnisotropy = 16, - D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, - D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, - FLOAT minLOD = 0.f, - FLOAT maxLOD = D3D12_FLOAT32_MAX, - D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, - UINT registerSpace = 0) - { - Init( - *this, - shaderRegister, - filter, - addressU, - addressV, - addressW, - mipLODBias, - maxAnisotropy, - comparisonFunc, - borderColor, - minLOD, - maxLOD, - shaderVisibility, - registerSpace); - } - -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC -{ - CD3DX12_ROOT_SIGNATURE_DESC() {} - explicit CD3DX12_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC &o) : - D3D12_ROOT_SIGNATURE_DESC(o) - {} - CD3DX12_ROOT_SIGNATURE_DESC( - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) - { - Init(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); - } - CD3DX12_ROOT_SIGNATURE_DESC(CD3DX12_DEFAULT) - { - Init(0, NULL, 0, NULL, D3D12_ROOT_SIGNATURE_FLAG_NONE); - } - - inline void Init( - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) - { - Init(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); - } - - static inline void Init( - _Out_ D3D12_ROOT_SIGNATURE_DESC &desc, - UINT numParameters, - _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, - UINT numStaticSamplers = 0, - _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL, - D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) - { - desc.NumParameters = numParameters; - desc.pParameters = _pParameters; - desc.NumStaticSamplers = numStaticSamplers; - desc.pStaticSamplers = _pStaticSamplers; - desc.Flags = flags; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE -{ - CD3DX12_CPU_DESCRIPTOR_HANDLE() {} - explicit CD3DX12_CPU_DESCRIPTOR_HANDLE(const D3D12_CPU_DESCRIPTOR_HANDLE &o) : - D3D12_CPU_DESCRIPTOR_HANDLE(o) - {} - CD3DX12_CPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) { ptr = 0; } - CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) - { - InitOffsetted(other, offsetScaledByIncrementSize); - } - CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); - } - CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) - { - ptr += offsetInDescriptors * descriptorIncrementSize; - return *this; - } - CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) - { - ptr += offsetScaledByIncrementSize; - return *this; - } - bool operator==(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other) - { - return (ptr == other.ptr); - } - bool operator!=(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other) - { - return (ptr != other.ptr); - } - CD3DX12_CPU_DESCRIPTOR_HANDLE &operator=(const D3D12_CPU_DESCRIPTOR_HANDLE &other) - { - ptr = other.ptr; - return *this; - } - - inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) - { - InitOffsetted(*this, base, offsetScaledByIncrementSize); - } - - inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); - } - - static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) - { - handle.ptr = base.ptr + offsetScaledByIncrementSize; - } - - static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - handle.ptr = base.ptr + offsetInDescriptors * descriptorIncrementSize; - } -}; - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_GPU_DESCRIPTOR_HANDLE : public D3D12_GPU_DESCRIPTOR_HANDLE -{ - CD3DX12_GPU_DESCRIPTOR_HANDLE() {} - explicit CD3DX12_GPU_DESCRIPTOR_HANDLE(const D3D12_GPU_DESCRIPTOR_HANDLE &o) : - D3D12_GPU_DESCRIPTOR_HANDLE(o) - {} - CD3DX12_GPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) { ptr = 0; } - CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) - { - InitOffsetted(other, offsetScaledByIncrementSize); - } - CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); - } - CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) - { - ptr += offsetInDescriptors * descriptorIncrementSize; - return *this; - } - CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) - { - ptr += offsetScaledByIncrementSize; - return *this; - } - inline bool operator==(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other) - { - return (ptr == other.ptr); - } - inline bool operator!=(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other) - { - return (ptr != other.ptr); - } - CD3DX12_GPU_DESCRIPTOR_HANDLE &operator=(const D3D12_GPU_DESCRIPTOR_HANDLE &other) - { - ptr = other.ptr; - return *this; - } - - inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) - { - InitOffsetted(*this, base, offsetScaledByIncrementSize); - } - - inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); - } - - static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) - { - handle.ptr = base.ptr + offsetScaledByIncrementSize; - } - - static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) - { - handle.ptr = base.ptr + offsetInDescriptors * descriptorIncrementSize; - } -}; - -//------------------------------------------------------------------------------------------------ -inline UINT D3D12CalcSubresource( UINT MipSlice, UINT ArraySlice, UINT PlaneSlice, UINT MipLevels, UINT ArraySize ) -{ - return MipSlice + ArraySlice * MipLevels + PlaneSlice * MipLevels * ArraySize; -} - -//------------------------------------------------------------------------------------------------ -template -inline void D3D12DecomposeSubresource( UINT Subresource, UINT MipLevels, UINT ArraySize, _Out_ T& MipSlice, _Out_ U& ArraySlice, _Out_ V& PlaneSlice ) -{ - MipSlice = static_cast(Subresource % MipLevels); - ArraySlice = static_cast((Subresource / MipLevels) % ArraySize); - PlaneSlice = static_cast(Subresource / (MipLevels * ArraySize)); -} - -//------------------------------------------------------------------------------------------------ -inline UINT8 D3D12GetFormatPlaneCount( - _In_ ID3D12Device* pDevice, - DXGI_FORMAT Format - ) -{ - D3D12_FEATURE_DATA_FORMAT_INFO formatInfo = {Format}; - if (FAILED(pDevice->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &formatInfo, sizeof(formatInfo)))) - { - return 0; - } - return formatInfo.PlaneCount; -} - -//------------------------------------------------------------------------------------------------ -struct CD3DX12_RESOURCE_DESC : public D3D12_RESOURCE_DESC -{ - CD3DX12_RESOURCE_DESC() - {} - explicit CD3DX12_RESOURCE_DESC( const D3D12_RESOURCE_DESC& o ) : - D3D12_RESOURCE_DESC( o ) - {} - CD3DX12_RESOURCE_DESC( - D3D12_RESOURCE_DIMENSION dimension, - UINT64 alignment, - UINT64 width, - UINT height, - UINT16 depthOrArraySize, - UINT16 mipLevels, - DXGI_FORMAT format, - UINT sampleCount, - UINT sampleQuality, - D3D12_TEXTURE_LAYOUT layout, - D3D12_RESOURCE_FLAGS flags ) - { - Dimension = dimension; - Alignment = alignment; - Width = width; - Height = height; - DepthOrArraySize = depthOrArraySize; - MipLevels = mipLevels; - Format = format; - SampleDesc.Count = sampleCount; - SampleDesc.Quality = sampleQuality; - Layout = layout; - Flags = flags; - } - static inline CD3DX12_RESOURCE_DESC Buffer( - const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes, - 1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); - } - static inline CD3DX12_RESOURCE_DESC Buffer( - UINT64 width, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - UINT64 alignment = 0 ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1, - DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); - } - static inline CD3DX12_RESOURCE_DESC Tex1D( - DXGI_FORMAT format, - UINT64 width, - UINT16 arraySize = 1, - UINT16 mipLevels = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize, - mipLevels, format, 1, 0, layout, flags ); - } - static inline CD3DX12_RESOURCE_DESC Tex2D( - DXGI_FORMAT format, - UINT64 width, - UINT height, - UINT16 arraySize = 1, - UINT16 mipLevels = 0, - UINT sampleCount = 1, - UINT sampleQuality = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize, - mipLevels, format, sampleCount, sampleQuality, layout, flags ); - } - static inline CD3DX12_RESOURCE_DESC Tex3D( - DXGI_FORMAT format, - UINT64 width, - UINT height, - UINT16 depth, - UINT16 mipLevels = 0, - D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, - D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, - UINT64 alignment = 0 ) - { - return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth, - mipLevels, format, 1, 0, layout, flags ); - } - inline UINT16 Depth() const - { return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - inline UINT16 ArraySize() const - { return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1); } - inline UINT8 PlaneCount(_In_ ID3D12Device* pDevice) const - { return D3D12GetFormatPlaneCount(pDevice, Format); } - inline UINT Subresources(_In_ ID3D12Device* pDevice) const - { return MipLevels * ArraySize() * PlaneCount(pDevice); } - inline UINT CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT PlaneSlice) - { return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize()); } - operator const D3D12_RESOURCE_DESC&() const { return *this; } -}; -inline bool operator==( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) -{ - return l.Dimension == r.Dimension && - l.Alignment == r.Alignment && - l.Width == r.Width && - l.Height == r.Height && - l.DepthOrArraySize == r.DepthOrArraySize && - l.MipLevels == r.MipLevels && - l.Format == r.Format && - l.SampleDesc.Count == r.SampleDesc.Count && - l.SampleDesc.Quality == r.SampleDesc.Quality && - l.Layout == r.Layout && - l.Flags == r.Flags; -} -inline bool operator!=( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) -{ return !( l == r ); } - -//------------------------------------------------------------------------------------------------ -// Row-by-row memcpy -inline void MemcpySubresource( - _In_ const D3D12_MEMCPY_DEST* pDest, - _In_ const D3D12_SUBRESOURCE_DATA* pSrc, - SIZE_T RowSizeInBytes, - UINT NumRows, - UINT NumSlices) -{ - for (UINT z = 0; z < NumSlices; ++z) - { - BYTE* pDestSlice = reinterpret_cast(pDest->pData) + pDest->SlicePitch * z; - const BYTE* pSrcSlice = reinterpret_cast(pSrc->pData) + pSrc->SlicePitch * z; - for (UINT y = 0; y < NumRows; ++y) - { - memcpy(pDestSlice + pDest->RowPitch * y, - pSrcSlice + pSrc->RowPitch * y, - RowSizeInBytes); - } - } -} - -//------------------------------------------------------------------------------------------------ -// Returns required size of a buffer to be used for data upload -inline UINT64 GetRequiredIntermediateSize( - _In_ ID3D12Resource* pDestinationResource, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) -{ - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - UINT64 RequiredSize = 0; - - ID3D12Device* pDevice; - pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); - pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, 0, nullptr, nullptr, nullptr, &RequiredSize); - pDevice->Release(); - - return RequiredSize; -} - -inline UINT64 GetRequiredIntermediateSize( - _In_ ID3D12Device* pDevice, - _In_ D3D12_RESOURCE_DESC* Desc, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) -{ - UINT64 RequiredSize = 0; - pDevice->GetCopyableFootprints(Desc, FirstSubresource, NumSubresources, 0, nullptr, nullptr, nullptr, &RequiredSize); - return RequiredSize; -} - -//------------------------------------------------------------------------------------------------ -// All arrays must be populated (e.g. by calling GetCopyableFootprints) -inline UINT64 UpdateSubresources( - _In_ ID3D12GraphicsCommandList* pCmdList, - _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - UINT64 RequiredSize, - _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, - _In_reads_(NumSubresources) const UINT* pNumRows, - _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, - _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) -{ - // Minor validation - D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc(); - D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc(); - if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || - IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || - RequiredSize > (SIZE_T)-1 || - (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && - (FirstSubresource != 0 || NumSubresources != 1))) - { - return 0; - } - - BYTE* pData; - HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast(&pData)); - if (FAILED(hr)) - { - return 0; - } - - for (UINT i = 0; i < NumSubresources; ++i) - { - if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0; - D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] }; - MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth); - } - pIntermediate->Unmap(0, NULL); - - if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) - { - CD3DX12_BOX SrcBox( UINT( pLayouts[0].Offset ), UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ) ); - pCmdList->CopyBufferRegion( - pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width); - } - else - { - for (UINT i = 0; i < NumSubresources; ++i) - { - CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource); - CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]); - pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr); - } - } - return RequiredSize; -} - -//------------------------------------------------------------------------------------------------ -// Heap-allocating UpdateSubresources implementation -inline UINT64 UpdateSubresources( - _In_ ID3D12GraphicsCommandList* pCmdList, - _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) -{ - UINT64 RequiredSize = 0; - UINT64 MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; - if (MemToAlloc > SIZE_MAX) - { - return 0; - } - void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); - if (pMem == NULL) - { - return 0; - } - D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast(pMem); - UINT64* pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); - UINT* pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); - - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - ID3D12Device* pDevice; - pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); - pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); - pDevice->Release(); - - UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData); - HeapFree(GetProcessHeap(), 0, pMem); - return Result; -} - -//------------------------------------------------------------------------------------------------ -// Stack-allocating UpdateSubresources implementation -template -inline UINT64 UpdateSubresources( - _In_ ID3D12GraphicsCommandList* pCmdList, - _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0, MaxSubresources) UINT FirstSubresource, - _In_range_(1, MaxSubresources - FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) -{ - UINT64 RequiredSize = 0; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; - UINT NumRows[MaxSubresources]; - UINT64 RowSizesInBytes[MaxSubresources]; - - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - ID3D12Device* pDevice; - pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast(&pDevice)); - pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); - pDevice->Release(); - - return UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, Layouts, NumRows, RowSizesInBytes, pSrcData); -} - -//------------------------------------------------------------------------------------------------ -// All arrays must be populated (e.g. by calling GetCopyableFootprints) -inline UINT64 PrepSubresources( - _In_ ID3D12Device* pDevice, - _In_ D3D12_RESOURCE_DESC* DestinationDesc, - _In_ ID3D12Resource* pIntermediate, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - UINT64 RequiredSize, - _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, - _In_reads_(NumSubresources) const UINT* pNumRows, - _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, - _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) -{ - // Minor validation - D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc(); - if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || - IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || - RequiredSize > (SIZE_T)-1 || - (DestinationDesc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && - (FirstSubresource != 0 || NumSubresources != 1))) - { - return 0; - } - - BYTE* pData; - HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast(&pData)); - if (FAILED(hr)) - { - return 0; - } - - for (UINT i = 0; i < NumSubresources; ++i) - { - if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0; - D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] }; - MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth); - } - pIntermediate->Unmap(0, NULL); - - return RequiredSize; -} - -//------------------------------------------------------------------------------------------------ -// Heap-allocating PrepSubresources implementation -inline UINT64 PrepSubresources( - _In_ ID3D12Device* pDevice, - _In_ D3D12_RESOURCE_DESC* DestinationDesc, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) -{ - UINT64 RequiredSize = 0; - UINT64 MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; - if (MemToAlloc > SIZE_MAX) - { - return 0; - } - void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); - if (pMem == NULL) - { - return 0; - } - D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast(pMem); - UINT64* pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); - UINT* pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); - - pDevice->GetCopyableFootprints(DestinationDesc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); - - UINT64 result = PrepSubresources(pDevice, DestinationDesc, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData); - HeapFree(GetProcessHeap(), 0, pMem); - return result; -} - -//------------------------------------------------------------------------------------------------ -// Stack-allocating PrepSubresources implementation -template -inline UINT64 PrepSubresources( - _In_ ID3D12Device* pDevice, - _In_ D3D12_RESOURCE_DESC* DestinationDesc, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, - _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, - _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData) -{ - UINT64 RequiredSize = 0; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; - UINT NumRows[MaxSubresources]; - UINT64 RowSizesInBytes[MaxSubresources]; - - pDevice->GetCopyableFootprints(DestinationDesc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); - - return PrepSubresources(pDevice, DestinationDesc, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, Layouts, NumRows, RowSizesInBytes, pSrcData); -} - -//------------------------------------------------------------------------------------------------ -// Heap-allocating CommandSubresourcesTransfer implementation -inline void CommandSubresourcesTransfer( - _In_ ID3D12Device* pDevice, - _In_ ID3D12GraphicsCommandList* pCmdList, - _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0, MaxSubresources) UINT FirstSubresource, - _In_range_(1, MaxSubresources - FirstSubresource) UINT NumSubresources) -{ - UINT64 RequiredSize = 0; - UINT64 MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; - if (MemToAlloc > SIZE_MAX) - { - return; - } - void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); - if (pMem == NULL) - { - return; - } - D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast(pMem); - UINT64* pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); - UINT* pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); - - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); - - if (Desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) - { - CD3DX12_BOX SrcBox( UINT( pLayouts[0].Offset ), UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ) ); - pCmdList->CopyBufferRegion( - pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width); - } - else - { - for (UINT i = 0; i < NumSubresources; ++i) - { - CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource); - CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]); - pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr); - } - } - - HeapFree(GetProcessHeap(), 0, pMem); -} - -//------------------------------------------------------------------------------------------------ -// Stack-allocating CommandSubresourcesTransfer implementation -template -inline void CommandSubresourcesTransfer( - _In_ ID3D12Device* pDevice, - _In_ ID3D12GraphicsCommandList* pCmdList, - _In_ ID3D12Resource* pDestinationResource, - _In_ ID3D12Resource* pIntermediate, - UINT64 IntermediateOffset, - _In_range_(0, MaxSubresources) UINT FirstSubresource, - _In_range_(1, MaxSubresources - FirstSubresource) UINT NumSubresources) -{ - UINT64 RequiredSize = 0; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; - UINT NumRows[MaxSubresources]; - UINT64 RowSizesInBytes[MaxSubresources]; - - D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc(); - pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); - - if (Desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) - { - CD3DX12_BOX SrcBox( UINT( Layouts[0].Offset ), UINT( Layouts[0].Offset + Layouts[0].Footprint.Width ) ); - pCmdList->CopyBufferRegion( - pDestinationResource, 0, pIntermediate, Layouts[0].Offset, Layouts[0].Footprint.Width); - } - else - { - for (UINT i = 0; i < NumSubresources; ++i) - { - CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource); - CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, Layouts[i]); - pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr); - } - } -} - -//------------------------------------------------------------------------------------------------ -inline bool D3D12IsLayoutOpaque( D3D12_TEXTURE_LAYOUT Layout ) -{ return Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN || Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; } - -//------------------------------------------------------------------------------------------------ -inline ID3D12CommandList * const * CommandListCast(ID3D12GraphicsCommandList * const * pp) -{ - // This cast is useful for passing strongly typed command list pointers into - // ExecuteCommandLists. - // This cast is valid as long as the const-ness is respected. D3D12 APIs do - // respect the const-ness of their arguments. - return reinterpret_cast(pp); -} - - -#endif // defined( __cplusplus ) - -#endif //__D3DX12_H__ - - diff --git a/lib/inputdev/HIDDeviceWinUSB.cpp b/lib/inputdev/HIDDeviceWinUSB.cpp index 13e4744..793030f 100644 --- a/lib/inputdev/HIDDeviceWinUSB.cpp +++ b/lib/inputdev/HIDDeviceWinUSB.cpp @@ -280,7 +280,7 @@ class HIDDeviceWinUSB final : public IHIDDevice if (Error != ERROR_IO_PENDING) { - fprintf(stderr, "Write Failed %08X\n", Error); + fprintf(stderr, "Write Failed %08X\n", int(Error)); return false; } } @@ -288,7 +288,7 @@ class HIDDeviceWinUSB final : public IHIDDevice if (!GetOverlappedResult(m_hidHandle, &Overlapped, &BytesWritten, TRUE)) { DWORD Error = GetLastError(); - fprintf(stderr, "Write Failed %08X\n", Error); + fprintf(stderr, "Write Failed %08X\n", int(Error)); return false; } } @@ -297,7 +297,7 @@ class HIDDeviceWinUSB final : public IHIDDevice DWORD useLength = DWORD(std::max(length, m_minFeatureSz)); if (!HidD_SetFeature(m_hidHandle, (PVOID)m_sendBuf.data(), useLength)) { - int error = GetLastError(); + //int error = GetLastError(); return false; } } @@ -377,7 +377,7 @@ public: } else if (Error != ERROR_IO_PENDING) { - fprintf(stderr, "Read Failed: %08X\n", Error); + fprintf(stderr, "Read Failed: %08X\n", int(Error)); return; } else if (!GetOverlappedResultEx(m_hidHandle, &m_overlapped, &BytesRead, 10, TRUE)) diff --git a/lib/inputdev/HIDParser.cpp b/lib/inputdev/HIDParser.cpp index e5ce7d3..1320ee3 100644 --- a/lib/inputdev/HIDParser.cpp +++ b/lib/inputdev/HIDParser.cpp @@ -323,59 +323,6 @@ const char* HIDMainItem::GetUsageName() const } } -static HIDParser::ParserStatus -AdvanceIt(const uint8_t*& it, const uint8_t* end, size_t adv) -{ - it += adv; - if (it > end) - { - it = end; - return HIDParser::ParserStatus::Error; - } - else if (it == end) - { - return HIDParser::ParserStatus::Done; - } - return HIDParser::ParserStatus::OK; -} - -static uint8_t -GetByteValue(const uint8_t*& it, const uint8_t* end, HIDParser::ParserStatus& status) -{ - const uint8_t* oldIt = it; - status = AdvanceIt(it, end, 1); - if (status == HIDParser::ParserStatus::Error) - return 0; - return *oldIt; -} - -static uint32_t -GetShortValue(const uint8_t*& it, const uint8_t* end, int adv, HIDParser::ParserStatus& status) -{ - const uint8_t* oldIt = it; - switch (adv) - { - case 1: - status = AdvanceIt(it, end, 1); - if (status == HIDParser::ParserStatus::Error) - return 0; - return *oldIt; - case 2: - status = AdvanceIt(it, end, 2); - if (status == HIDParser::ParserStatus::Error) - return 0; - return *reinterpret_cast(&*oldIt); - case 3: - status = AdvanceIt(it, end, 4); - if (status == HIDParser::ParserStatus::Error) - return 0; - return *reinterpret_cast(&*oldIt); - default: - break; - } - return 0; -} - struct HIDReports { std::map> m_inputReports; @@ -479,6 +426,59 @@ HIDParser::ParserStatus HIDParser::Parse(const PHIDP_PREPARSED_DATA descriptorDa #endif #else +static HIDParser::ParserStatus +AdvanceIt(const uint8_t*& it, const uint8_t* end, size_t adv) +{ + it += adv; + if (it > end) + { + it = end; + return HIDParser::ParserStatus::Error; + } + else if (it == end) + { + return HIDParser::ParserStatus::Done; + } + return HIDParser::ParserStatus::OK; +} + +static uint8_t +GetByteValue(const uint8_t*& it, const uint8_t* end, HIDParser::ParserStatus& status) +{ + const uint8_t* oldIt = it; + status = AdvanceIt(it, end, 1); + if (status == HIDParser::ParserStatus::Error) + return 0; + return *oldIt; +} + +static uint32_t +GetShortValue(const uint8_t*& it, const uint8_t* end, int adv, HIDParser::ParserStatus& status) +{ + const uint8_t* oldIt = it; + switch (adv) + { + case 1: + status = AdvanceIt(it, end, 1); + if (status == HIDParser::ParserStatus::Error) + return 0; + return *oldIt; + case 2: + status = AdvanceIt(it, end, 2); + if (status == HIDParser::ParserStatus::Error) + return 0; + return *reinterpret_cast(&*oldIt); + case 3: + status = AdvanceIt(it, end, 4); + if (status == HIDParser::ParserStatus::Error) + return 0; + return *reinterpret_cast(&*oldIt); + default: + break; + } + return 0; +} + HIDParser::ParserStatus HIDParser::ParseItem(HIDReports& reportsOut, std::stack& stateStack, diff --git a/lib/win/ApplicationWin32.cpp b/lib/win/ApplicationWin32.cpp index f0f3894..1af6c6e 100644 --- a/lib/win/ApplicationWin32.cpp +++ b/lib/win/ApplicationWin32.cpp @@ -28,9 +28,6 @@ PFN_GetScaleFactorForMonitor MyGetScaleFactorForMonitor = nullptr; DWORD g_mainThreadId = 0; static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); -#if _WIN32_WINNT_WIN10 -PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignaturePROC = nullptr; -#endif pD3DCompile D3DCompilePROC = nullptr; pD3DCreateBlob D3DCreateBlobPROC = nullptr; @@ -77,7 +74,6 @@ class ApplicationWin32 final : public IApplication const SystemString m_pname; const std::vector m_args; std::unordered_map> m_allWindows; - bool m_singleInstance; Boo3DAppContextWin32 m_3dCtx; #if BOO_HAS_VULKAN @@ -105,15 +101,11 @@ public: m_uniqueName(uniqueName), m_friendlyName(friendlyName), m_pname(pname), - m_args(args), - m_singleInstance(singleInstance) + m_args(args) { m_3dCtx.m_ctx11.m_sampleCount = samples; m_3dCtx.m_ctx11.m_anisotropy = anisotropy; m_3dCtx.m_ctx11.m_fbFormat = deepColor ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM; - m_3dCtx.m_ctx12.m_sampleCount = samples; - m_3dCtx.m_ctx12.m_anisotropy = anisotropy; - m_3dCtx.m_ctx12.RGBATex2DFBViewDesc.Format = deepColor ? DXGI_FORMAT_R16G16B16A16_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM; m_3dCtx.m_ctxOgl.m_glCtx.m_sampleCount = samples; m_3dCtx.m_ctxOgl.m_glCtx.m_anisotropy = anisotropy; m_3dCtx.m_ctxOgl.m_glCtx.m_deepColor = deepColor; @@ -133,7 +125,6 @@ public: if (!MyCreateDXGIFactory1) Log.report(logvisor::Fatal, "unable to find CreateDXGIFactory1 in DXGI.dll\n"); - bool yes12 = false; bool noD3d = false; #if BOO_HAS_VULKAN bool useVulkan = false; @@ -141,11 +132,6 @@ public: if (!gfxApi.empty()) { #if BOO_HAS_VULKAN - if (!gfxApi.compare("D3D12")) - { - useVulkan = false; - yes12 = true; - } if (!gfxApi.compare("Vulkan")) { noD3d = true; @@ -157,8 +143,6 @@ public: useVulkan = false; } #else - if (!gfxApi.compare("D3D12")) - yes12 = true; if (!gfxApi.compare("OpenGL")) noD3d = true; #endif @@ -166,16 +150,9 @@ public: for (const SystemString& arg : args) { #if BOO_HAS_VULKAN - if (!arg.compare(L"--d3d12")) - { - useVulkan = false; - yes12 = true; - noD3d = false; - } if (!arg.compare(L"--d3d11")) { useVulkan = false; - yes12 = false; noD3d = false; } if (!arg.compare(L"--vulkan")) @@ -189,109 +166,13 @@ public: useVulkan = false; } #else - if (!arg.compare(L"--d3d12")) - { - yes12 = true; - noD3d = false; - } if (!arg.compare(L"--d3d11")) - { - yes12 = false; noD3d = false; - } if (!arg.compare(L"--gl")) noD3d = true; #endif } -#if _WIN32_WINNT_WIN10 - HMODULE d3d12lib = nullptr; - if (yes12 && !noD3d) - d3d12lib = LoadLibraryW(L"D3D12.dll"); - if (d3d12lib) - { -#if _DEBUG - { - PFN_D3D12_GET_DEBUG_INTERFACE MyD3D12GetDebugInterface = - (PFN_D3D12_GET_DEBUG_INTERFACE)GetProcAddress(d3d12lib, "D3D12GetDebugInterface"); - ComPtr debugController; - if (SUCCEEDED(MyD3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) - { - debugController->EnableDebugLayer(); - } - } -#endif - if (!FindBestD3DCompile()) - Log.report(logvisor::Fatal, "unable to find D3DCompile_[43-47].dll"); - - D3D12SerializeRootSignaturePROC = - (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)GetProcAddress(d3d12lib, "D3D12SerializeRootSignature"); - - /* Create device */ - PFN_D3D12_CREATE_DEVICE MyD3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(d3d12lib, "D3D12CreateDevice"); - if (!MyD3D12CreateDevice) - Log.report(logvisor::Fatal, "unable to find D3D12CreateDevice in D3D12.dll"); - - /* Obtain DXGI Factory */ - HRESULT hr = MyCreateDXGIFactory1(__uuidof(IDXGIFactory2), &m_3dCtx.m_ctx12.m_dxFactory); - if (FAILED(hr)) - Log.report(logvisor::Fatal, "unable to create DXGI factory"); - - /* Adapter */ - ComPtr ppAdapter; - for (UINT adapterIndex = 0; ; ++adapterIndex) - { - ComPtr pAdapter; - if (DXGI_ERROR_NOT_FOUND == m_3dCtx.m_ctx12.m_dxFactory->EnumAdapters1(adapterIndex, &pAdapter)) - break; - - // Check to see if the adapter supports Direct3D 12, but don't create the - // actual device yet. - if (SUCCEEDED(MyD3D12CreateDevice(pAdapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) - { - ppAdapter = std::move(pAdapter); - break; - } - } - - /* Create device */ - hr = ppAdapter ? MyD3D12CreateDevice(ppAdapter.Get(), D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), &m_3dCtx.m_ctx12.m_dev) : E_FAIL; - if (!FAILED(hr)) - { - /* Establish loader objects */ - if (FAILED(m_3dCtx.m_ctx12.m_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - __uuidof(ID3D12CommandAllocator), &m_3dCtx.m_ctx12.m_loadqalloc))) - Log.report(logvisor::Fatal, "unable to create loader allocator"); - - D3D12_COMMAND_QUEUE_DESC desc = - { - D3D12_COMMAND_LIST_TYPE_DIRECT, - D3D12_COMMAND_QUEUE_PRIORITY_NORMAL, - D3D12_COMMAND_QUEUE_FLAG_NONE - }; - if (FAILED(m_3dCtx.m_ctx12.m_dev->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), &m_3dCtx.m_ctx12.m_loadq))) - Log.report(logvisor::Fatal, "unable to create loader queue"); - - if (FAILED(m_3dCtx.m_ctx12.m_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &m_3dCtx.m_ctx12.m_loadfence))) - Log.report(logvisor::Fatal, "unable to create loader fence"); - - m_3dCtx.m_ctx12.m_loadfencehandle = CreateEvent(nullptr, FALSE, FALSE, nullptr); - - if (FAILED(m_3dCtx.m_ctx12.m_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_3dCtx.m_ctx12.m_loadqalloc.Get(), - nullptr, __uuidof(ID3D12GraphicsCommandList), &m_3dCtx.m_ctx12.m_loadlist))) - Log.report(logvisor::Fatal, "unable to create loader list"); - - Log.report(logvisor::Info, "initialized D3D12 renderer"); - return; - } - else - { - /* Some Win10 client HW doesn't support D3D12 (despite being supposedly HW-agnostic) */ - m_3dCtx.m_ctx12.m_dev.Reset(); - m_3dCtx.m_ctx12.m_dxFactory.Reset(); - } - } -#endif HMODULE d3d11lib = nullptr; if (!noD3d) d3d11lib = LoadLibraryW(L"D3D11.dll"); @@ -621,7 +502,7 @@ int ApplicationRun(IApplication::EPlatformType platform, }; wndClass.hIcon = LoadIconW(wndClass.hInstance, MAKEINTRESOURCEW(101)); wndClass.hCursor = WIN32_CURSORS.m_arrow; - ATOM a = RegisterClassW(&wndClass); + RegisterClassW(&wndClass); APP = new ApplicationWin32(cb, uniqueName, friendlyName, pname, args, gfxApi, samples, anisotropy, deepColor, singleInstance); @@ -633,9 +514,7 @@ int ApplicationRun(IApplication::EPlatformType platform, static const DEV_BROADCAST_DEVICEINTERFACE HOTPLUG_CONF = { sizeof(DEV_BROADCAST_DEVICEINTERFACE), - DBT_DEVTYP_DEVICEINTERFACE, - 0, - 0 + DBT_DEVTYP_DEVICEINTERFACE }; static bool HOTPLUG_REGISTERED = false; static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) diff --git a/lib/win/Win32Common.hpp b/lib/win/Win32Common.hpp index 3aad788..1874d6f 100644 --- a/lib/win/Win32Common.hpp +++ b/lib/win/Win32Common.hpp @@ -101,15 +101,6 @@ struct Boo3DAppContextWin32 : Boo3DAppContext } #endif -#if _WIN32_WINNT_WIN10 - if (m_ctx12.m_dev) - { - D3D12Context::Window& win = m_ctx12.m_windows[window]; - BOOL isFScr; - win.m_swapChain->GetFullscreenState(&isFScr, nullptr); - return isFScr != 0; - } -#endif if (m_ctx11.m_dev) { D3D11Context::Window& win = m_ctx11.m_windows[window]; @@ -136,34 +127,6 @@ struct Boo3DAppContextWin32 : Boo3DAppContext } #endif -#if _WIN32_WINNT_WIN10 - if (m_ctx12.m_dev) - { - D3D12Context::Window& win = m_ctx12.m_windows[window]; - BOOL isFScr; - win.m_swapChain->GetFullscreenState(&isFScr, nullptr); - if (fs && isFScr) - return false; - else if (!fs && !isFScr) - return false; - - if (fs) - { - ComPtr out; - win.m_swapChain->GetContainingOutput(&out); - DXGI_OUTPUT_DESC outDesc; - out->GetDesc(&outDesc); - - win.m_swapChain->SetFullscreenState(true, nullptr); - DXGI_MODE_DESC mdesc = {UINT(outDesc.DesktopCoordinates.right - outDesc.DesktopCoordinates.left), - UINT(outDesc.DesktopCoordinates.bottom - outDesc.DesktopCoordinates.top)}; - win.m_swapChain->ResizeTarget(&mdesc); - } - else - win.m_swapChain->SetFullscreenState(false, nullptr); - return true; - } -#endif if (m_ctx11.m_dev) { D3D11Context::Window& win = m_ctx11.m_windows[window]; diff --git a/lib/win/WinCommon.hpp b/lib/win/WinCommon.hpp index 9807eb4..12ed901 100644 --- a/lib/win/WinCommon.hpp +++ b/lib/win/WinCommon.hpp @@ -1,4 +1,4 @@ -#ifndef BOO_WI2COMMON_HPP +#ifndef BOO_WINCOMMON_HPP #define BOO_WINCOMMON_HPP #include @@ -107,28 +107,13 @@ struct D3D11Context struct Boo3DAppContext { D3D11Context m_ctx11; -#if _WIN32_WINNT_WIN10 - D3D12Context m_ctx12; -#endif void resize(boo::IWindow* window, size_t width, size_t height) { -#if _WIN32_WINNT_WIN10 - if (m_ctx12.m_dev) - { - D3D12Context::Window& win = m_ctx12.m_windows[window]; - win.width = width; - win.height = height; - win.m_needsResize = true; - } - else -#endif - { - D3D11Context::Window& win = m_ctx11.m_windows[window]; - win.width = width; - win.height = height; - win.m_needsResize = true; - } + D3D11Context::Window& win = m_ctx11.m_windows[window]; + win.width = width; + win.height = height; + win.m_needsResize = true; } }; diff --git a/lib/win/WindowWin32.cpp b/lib/win/WindowWin32.cpp index 1457057..e36b945 100644 --- a/lib/win/WindowWin32.cpp +++ b/lib/win/WindowWin32.cpp @@ -32,20 +32,20 @@ static const int ContextAttribs[] = namespace boo { static logvisor::Module Log("boo::WindowWin32"); -#if _WIN32_WINNT_WIN10 -IGraphicsCommandQueue* _NewD3D12CommandQueue(D3D12Context* ctx, D3D12Context::Window* windowCtx, IGraphicsContext* parent, - ID3D12CommandQueue** cmdQueueOut); -IGraphicsDataFactory* _NewD3D12DataFactory(D3D12Context* ctx, IGraphicsContext* parent); -#endif -IGraphicsCommandQueue* _NewD3D11CommandQueue(D3D11Context* ctx, D3D11Context::Window* windowCtx, IGraphicsContext* parent); -IGraphicsDataFactory* _NewD3D11DataFactory(D3D11Context* ctx, IGraphicsContext* parent); -IGraphicsCommandQueue* _NewGLCommandQueue(IGraphicsContext* parent, GLContext* glCtx); -IGraphicsDataFactory* _NewGLDataFactory(IGraphicsContext* parent, GLContext* glCtx); + +std::unique_ptr +_NewD3D11CommandQueue(D3D11Context* ctx, D3D11Context::Window* windowCtx, IGraphicsContext* parent); +std::unique_ptr +_NewD3D11DataFactory(D3D11Context* ctx, IGraphicsContext* parent); +std::unique_ptr +_NewGLCommandQueue(IGraphicsContext* parent, GLContext* glCtx); +std::unique_ptr +_NewGLDataFactory(IGraphicsContext* parent, GLContext* glCtx); #if BOO_HAS_VULKAN -IGraphicsCommandQueue* _NewVulkanCommandQueue(VulkanContext* ctx, - VulkanContext::Window* windowCtx, - IGraphicsContext* parent); -IGraphicsDataFactory* _NewVulkanDataFactory(IGraphicsContext* parent, VulkanContext* ctx); +std::unique_ptr +_NewVulkanCommandQueue(VulkanContext* ctx, VulkanContext::Window* windowCtx, IGraphicsContext* parent); +std::unique_ptr +_NewVulkanDataFactory(IGraphicsContext* parent, VulkanContext* ctx); #endif struct GraphicsContextWin32 : IGraphicsContext @@ -71,8 +71,8 @@ struct GraphicsContextWin32D3D : GraphicsContextWin32 { ComPtr m_swapChain; - IGraphicsCommandQueue* m_commandQueue = nullptr; - IGraphicsDataFactory* m_dataFactory = nullptr; + std::unique_ptr m_dataFactory; + std::unique_ptr m_commandQueue; public: IWindowCallback* m_callback; @@ -89,66 +89,27 @@ public: scDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; scDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; -#if _WIN32_WINNT_WIN10 - if (b3dCtx.m_ctx12.m_dev) - { - auto insIt = b3dCtx.m_ctx12.m_windows.emplace(std::make_pair(parentWindow, D3D12Context::Window())); - D3D12Context::Window& w = insIt.first->second; + scDesc.Format = b3dCtx.m_ctx11.m_fbFormat; + if (FAILED(b3dCtx.m_ctx11.m_dxFactory->CreateSwapChainForHwnd(b3dCtx.m_ctx11.m_dev.Get(), + hwnd, &scDesc, nullptr, nullptr, &m_swapChain))) + Log.report(logvisor::Fatal, "unable to create swap chain"); + b3dCtx.m_ctx11.m_dxFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER); - ID3D12CommandQueue* cmdQueue; - m_dataFactory = _NewD3D12DataFactory(&b3dCtx.m_ctx12, this); - m_commandQueue = _NewD3D12CommandQueue(&b3dCtx.m_ctx12, &w, this, &cmdQueue); - m_commandQueue->startRenderer(); + auto insIt = b3dCtx.m_ctx11.m_windows.emplace(std::make_pair(parentWindow, D3D11Context::Window())); + D3D11Context::Window& w = insIt.first->second; + w.setupRTV(m_swapChain, b3dCtx.m_ctx11.m_dev.Get()); - scDesc.Format = b3dCtx.m_ctx12.RGBATex2DFBViewDesc.Format; - scDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; - HRESULT hr = b3dCtx.m_ctx12.m_dxFactory->CreateSwapChainForHwnd(cmdQueue, - hwnd, &scDesc, nullptr, nullptr, &m_swapChain); - if (FAILED(hr)) - Log.report(logvisor::Fatal, "unable to create swap chain"); - b3dCtx.m_ctx12.m_dxFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER); + m_dataFactory = _NewD3D11DataFactory(&b3dCtx.m_ctx11, this); + m_commandQueue = _NewD3D11CommandQueue(&b3dCtx.m_ctx11, &insIt.first->second, this); + m_commandQueue->startRenderer(); - m_swapChain.As(&w.m_swapChain); - ComPtr fb; - m_swapChain->GetBuffer(0, __uuidof(ID3D12Resource), &fb); - w.m_backBuf = w.m_swapChain->GetCurrentBackBufferIndex(); - D3D12_RESOURCE_DESC resDesc = fb->GetDesc(); - w.width = resDesc.Width; - w.height = resDesc.Height; - - if (FAILED(m_swapChain->GetContainingOutput(&m_output))) - Log.report(logvisor::Fatal, "unable to get DXGI output"); - } - else -#endif - { - scDesc.Format = b3dCtx.m_ctx11.m_fbFormat; - if (FAILED(b3dCtx.m_ctx11.m_dxFactory->CreateSwapChainForHwnd(b3dCtx.m_ctx11.m_dev.Get(), - hwnd, &scDesc, nullptr, nullptr, &m_swapChain))) - Log.report(logvisor::Fatal, "unable to create swap chain"); - b3dCtx.m_ctx11.m_dxFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER); - - auto insIt = b3dCtx.m_ctx11.m_windows.emplace(std::make_pair(parentWindow, D3D11Context::Window())); - D3D11Context::Window& w = insIt.first->second; - w.setupRTV(m_swapChain, b3dCtx.m_ctx11.m_dev.Get()); - - m_dataFactory = _NewD3D11DataFactory(&b3dCtx.m_ctx11, this); - m_commandQueue = _NewD3D11CommandQueue(&b3dCtx.m_ctx11, &insIt.first->second, this); - m_commandQueue->startRenderer(); - - if (FAILED(m_swapChain->GetContainingOutput(&m_output))) - Log.report(logvisor::Fatal, "unable to get DXGI output"); - } + if (FAILED(m_swapChain->GetContainingOutput(&m_output))) + Log.report(logvisor::Fatal, "unable to get DXGI output"); } ~GraphicsContextWin32D3D() { -#if _WIN32_WINNT_WIN10 - if (m_3dCtx.m_ctx12.m_dev) - m_3dCtx.m_ctx12.m_windows.erase(m_parentWindow); - else -#endif - m_3dCtx.m_ctx11.m_windows.erase(m_parentWindow); + m_3dCtx.m_ctx11.m_windows.erase(m_parentWindow); } void _setCallback(IWindowCallback* cb) @@ -183,29 +144,29 @@ public: IGraphicsCommandQueue* getCommandQueue() { - return m_commandQueue; + return m_commandQueue.get(); } IGraphicsDataFactory* getDataFactory() { - return m_dataFactory; + return m_dataFactory.get(); } IGraphicsDataFactory* getMainContextDataFactory() { - return m_dataFactory; + return m_dataFactory.get(); } IGraphicsDataFactory* getLoadContextDataFactory() { - return m_dataFactory; + return m_dataFactory.get(); } }; struct GraphicsContextWin32GL : GraphicsContextWin32 { - IGraphicsCommandQueue* m_commandQueue = nullptr; - IGraphicsDataFactory* m_dataFactory = nullptr; + std::unique_ptr m_dataFactory; + std::unique_ptr m_commandQueue; public: IWindowCallback* m_callback; @@ -370,7 +331,7 @@ public: void postInit() { - OGLContext::Window& w = m_3dCtx.m_ctxOgl.m_windows[m_parentWindow]; + //OGLContext::Window& w = m_3dCtx.m_ctxOgl.m_windows[m_parentWindow]; //wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) // wglGetProcAddress("wglCreateContextAttribsARB"); @@ -393,12 +354,12 @@ public: IGraphicsCommandQueue* getCommandQueue() { - return m_commandQueue; + return m_commandQueue.get(); } IGraphicsDataFactory* getDataFactory() { - return m_dataFactory; + return m_dataFactory.get(); } /* Creates a new context on current thread!! Call from client loading thread */ @@ -414,7 +375,7 @@ public: } if (!wglMakeCurrent(w.m_deviceContext, m_mainCtx)) Log.report(logvisor::Fatal, "unable to make main WGL context current"); - return m_dataFactory; + return m_dataFactory.get(); } /* Creates a new context on current thread!! Call from client loading thread */ @@ -430,7 +391,7 @@ public: } if (!wglMakeCurrent(w.m_deviceContext, m_loadCtx)) Log.report(logvisor::Fatal, "unable to make load WGL context current"); - return m_dataFactory; + return m_dataFactory.get(); } }; @@ -444,8 +405,8 @@ struct GraphicsContextWin32Vulkan : GraphicsContextWin32 VkFormat m_format = VK_FORMAT_UNDEFINED; VkColorSpaceKHR m_colorspace; - IGraphicsCommandQueue* m_commandQueue = nullptr; - IGraphicsDataFactory* m_dataFactory = nullptr; + std::unique_ptr m_dataFactory; + std::unique_ptr m_commandQueue; std::thread m_vsyncThread; bool m_vsyncRunning; @@ -655,12 +616,12 @@ public: IGraphicsCommandQueue* getCommandQueue() { - return m_commandQueue; + return m_commandQueue.get(); } IGraphicsDataFactory* getDataFactory() { - return m_dataFactory; + return m_dataFactory.get(); } IGraphicsDataFactory* getMainContextDataFactory() @@ -1043,12 +1004,10 @@ public: if (m_gfxCtx->initializeContext(nullptr)) return; } +#else + (void)wndInstance; #endif IGraphicsContext::EGraphicsAPI api = IGraphicsContext::EGraphicsAPI::D3D11; -#if _WIN32_WINNT_WIN10 - if (b3dCtx.m_ctx12.m_dev) - api = IGraphicsContext::EGraphicsAPI::D3D12; -#endif if (b3dCtx.m_ctxOgl.m_dxFactory) { m_gfxCtx.reset(new GraphicsContextWin32GL(IGraphicsContext::EGraphicsAPI::OpenGL3_3, diff --git a/test/main.cpp b/test/main.cpp index 95643e3..8428131 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -19,7 +19,7 @@ class DolphinSmashAdapterCallback : public IDolphinSmashAdapterCallback { // printf("CONTROLLER %u CONNECTED\n", idx); } - void controllerDisconnected(unsigned idx, EDolphinControllerType) + void controllerDisconnected(unsigned idx) { // printf("CONTROLLER %u DISCONNECTED\n", idx); } @@ -281,7 +281,7 @@ struct TestApplicationCallback : IApplicationCallback { IGraphicsDataFactory* factory = self->mainWindow->getLoadContextDataFactory(); - factory->BooCommitTransaction([&](IGraphicsDataFactory::Context& ctx) + factory->commitTransaction([&](IGraphicsDataFactory::Context& ctx) { /* Create render target */ int x, y, w, h; @@ -409,10 +409,9 @@ struct TestApplicationCallback : IApplicationCallback } else #endif #if _WIN32 - if (plat == IGraphicsDataFactory::Platform::D3D12 || - plat == IGraphicsDataFactory::Platform::D3D11) + if (plat == IGraphicsDataFactory::Platform::D3D11) { - ID3DDataFactory::Context& d3dF = dynamic_cast(ctx); + D3DDataFactory::Context& d3dF = dynamic_cast(ctx); static const char* VS = "struct VertData {float3 in_pos : POSITION; float2 in_uv : UV;};\n" @@ -482,7 +481,7 @@ struct TestApplicationCallback : IApplicationCallback 1, &texture, nullptr, nullptr); return true; - }); + } BooTrace); } int appMain(IApplication* app)